Subversion Repositories munaweb

Rev

Rev 149 | Rev 180 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
<?php
178 - 2
error_reporting(-1);
3
 
2 - 4
/**
5
 * AJAX Cross Domain (PHP) Proxy 0.8
6
 * Copyright (C) 2016 Iacovos Constantinou (https://github.com/softius)
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU General Public License for more details.
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18
 */
19
/**
20
 * Enables or disables filtering for cross domain requests.
21
 * Recommended value: true
22
 */
23
define('CSAJAX_FILTERS', true);
24
/**
25
 * If set to true, $valid_requests should hold only domains i.e. a.example.com, b.example.com, usethisdomain.com
26
 * If set to false, $valid_requests should hold the whole URL ( without the parameters ) i.e. http://example.com/this/is/long/url/
27
 * Recommended value: false (for security reasons - do not forget that anyone can access your proxy)
28
 */
29
define('CSAJAX_FILTER_DOMAIN', true);
30
/**
31
 * Enables or disables Expect: 100-continue header. Some webservers don't
32
 * handle this header correctly.
33
 * Recommended value: false
34
 */
35
define('CSAJAX_SUPPRESS_EXPECT', false);
36
/**
37
 * Set debugging to true to receive additional messages - really helpful on development
38
 */
39
define('CSAJAX_DEBUG', false);
40
/**
41
 * A set of valid cross domain requests
42
 */
43
$valid_requests = array(
44
		'api.ebay.com',
45
		'open.api.ebay.com',
46
		'secure.shippingapis.com',
47
		'muna-trading.myshopify.com',
48
		'svcs.ebay.com',
49
		'api.discogs.com',
50
		'onlinetools.ups.com'
51
);
52
/**
53
 * Set extra multiple options for cURL
54
 * Could be used to define CURLOPT_SSL_VERIFYPEER & CURLOPT_SSL_VERIFYHOST for HTTPS
55
 * Also to overwrite any other options without changing the code
56
 * See http://php.net/manual/en/function.curl-setopt-array.php
57
 */
58
$curl_options = array(
59
    // CURLOPT_SSL_VERIFYPEER => false,
60
    // CURLOPT_SSL_VERIFYHOST => 2,
178 - 61
	CURLOPT_CONNECTTIMEOUT => 5
2 - 62
);
4 - 63
/**
64
 * Decode POST parameters after building the http array. Send Header X-DECODE-PARAMS
65
 */
19 - 66
$decodeFlag = false;
32 - 67
/**
68
 * Do not decode X-Proxy-Url. Send Header X-LEAVE-ENCODED
69
 */
70
$leaveEncodedFlag = false;
71
 
2 - 72
/* * * STOP EDITING HERE UNLESS YOU KNOW WHAT YOU ARE DOING * * */
73
// identify request headers
74
$request_headers = array( );
75
foreach ($_SERVER as $key => $value) {
76
    if (strpos($key, 'HTTP_') === 0  ||  strpos($key, 'CONTENT_') === 0) {
77
        $headername = str_replace('_', ' ', str_replace('HTTP_', '', $key));
78
        $headername = str_replace(' ', '-', ucwords(strtolower($headername)));
79
        if (!in_array($headername, array( 'Host', 'X-Proxy-Url' ))) {
80
        	if ($headername == "X-Authorization") {
81
        		$headername = "Authorization";
4 - 82
        	} else if ($headername == "X-Decode-Params") {
83
                $decodeFlag = true;
84
                continue;
32 - 85
        	} else if ($headername == "X-Leave-Encoded") {
86
                $leaveEncodedFlag = true;
87
                continue;
2 - 88
        	}
83 - 89
 
90
            $value = authReplace($value);
91
 
2 - 92
            $request_headers[] = "$headername: $value";
93
        }
94
    }
95
}
96
// identify request method, url and params
97
$request_method = $_SERVER['REQUEST_METHOD'];
98
if ('GET' == $request_method) {
99
    $request_params = $_GET;
100
} elseif ('POST' == $request_method) {
101
    $request_params = $_POST;
102
    if (empty($request_params)) {
103
        $data = file_get_contents('php://input');
104
        if (!empty($data)) {
105
            $request_params = $data;
106
        }
107
    }
108
} elseif ('PUT' == $request_method || 'DELETE' == $request_method) {
109
    $request_params = file_get_contents('php://input');
110
} else {
111
    $request_params = null;
112
}
113
// Get URL from `csurl` in GET or POST data, before falling back to X-Proxy-URL header.
114
if (isset($_REQUEST['csurl'])) {
115
    $request_url = urldecode($_REQUEST['csurl']);
116
} elseif (isset($_SERVER['HTTP_X_PROXY_URL'])) {
32 - 117
    if ($leaveEncodedFlag) {
118
        $request_url = $_SERVER['HTTP_X_PROXY_URL'];
119
    } else {
120
        $request_url = urldecode($_SERVER['HTTP_X_PROXY_URL']);
121
    }
2 - 122
} else {
123
    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
124
    header('Status: 404 Not Found');
125
    $_SERVER['REDIRECT_STATUS'] = 404;
126
    exit;
127
}
75 - 128
 
83 - 129
$request_url = authReplace($request_url);
75 - 130
 
2 - 131
$p_request_url = parse_url($request_url);
132
// csurl may exist in GET request methods
133
if (is_array($request_params) && array_key_exists('csurl', $request_params)) {
134
    unset($request_params['csurl']);
135
}
136
// ignore requests for proxy :)
137
if (preg_match('!' . $_SERVER['SCRIPT_NAME'] . '!', $request_url) || empty($request_url) || count($p_request_url) == 1) {
138
    csajax_debug_message('Invalid request - make sure that csurl variable is not empty');
139
    exit;
140
}
141
// check against valid requests
142
if (CSAJAX_FILTERS) {
143
    $parsed = $p_request_url;
144
    if (CSAJAX_FILTER_DOMAIN) {
145
        if (!in_array($parsed['host'], $valid_requests)) {
146
            csajax_debug_message('Invalid domain - ' . $parsed['host'] . ' is not included in valid requests');
147
            exit;
148
        }
149
    } else {
150
        $check_url = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '';
151
        $check_url .= isset($parsed['user']) ? $parsed['user'] . ($parsed['pass'] ? ':' . $parsed['pass'] : '') . '@' : '';
152
        $check_url .= isset($parsed['host']) ? $parsed['host'] : '';
153
        $check_url .= isset($parsed['port']) ? ':' . $parsed['port'] : '';
154
        $check_url .= isset($parsed['path']) ? $parsed['path'] : '';
155
        if (!in_array($check_url, $valid_requests)) {
156
            csajax_debug_message('Invalid url - ' . $request_url . ' does not included in valid requests');
157
            exit;
158
        }
159
    }
160
}
161
// append query string for GET requests
162
if ($request_method == 'GET' && count($request_params) > 0 && (!array_key_exists('query', $p_request_url) || empty($p_request_url['query']))) {
163
    $request_url .= '?' . http_build_query($request_params);
164
}
178 - 165
 
2 - 166
// let the request begin
167
$ch = curl_init($request_url);
168
// Suppress Expect header
169
if (CSAJAX_SUPPRESS_EXPECT) {
170
    array_push($request_headers, 'Expect:');
171
}
172
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);   // (re-)send headers
173
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // return response
174
curl_setopt($ch, CURLOPT_HEADER, true);       // enabled response headers
175
// add data for POST, PUT or DELETE requests
176
if ('POST' == $request_method) {
4 - 177
    $post_data = is_array($request_params) ? http_build_query($request_params) : $request_params;
87 - 178
    $post_data = authReplace($post_data);
2 - 179
    curl_setopt($ch, CURLOPT_POST, true);
4 - 180
    if ($decodeFlag) {
181
      curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode($post_data));
182
    } else {
183
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
184
    }
2 - 185
} elseif ('PUT' == $request_method || 'DELETE' == $request_method) {
186
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_method);
187
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request_params);
188
}
189
// Set multiple options for curl according to configuration
190
if (is_array($curl_options) && 0 <= count($curl_options)) {
191
    curl_setopt_array($ch, $curl_options);
192
}
178 - 193
 
2 - 194
// retrieve response (headers and content)
195
$response = curl_exec($ch);
196
curl_close($ch);
197
 
19 - 198
// delete 100 Continue headers
199
$delimiter = "\r\n\r\n"; // HTTP header delimiter
200
// check if the 100 Continue header exists
201
while ( preg_match('#^HTTP/[0-9\\.]+\s+100\s+Continue#i',$response) ) {
202
    $tmp = explode($delimiter,$response,2); // grab the 100 Continue header
203
    $response = $tmp[1]; // update the response, purging the most recent 100 Continue header
2 - 204
}
205
 
206
// split response to header and content
149 - 207
list($response_headers, $response_content) = array_pad(preg_split('/(\r\n){2}/', $response, 2), 2, "");
2 - 208
// (re-)send the headers
209
$response_headers = preg_split('/(\r\n){1}/', $response_headers);
210
foreach ($response_headers as $key => $response_header) {
211
    // Rewrite the `Location` header, so clients will also use the proxy for redirects.
212
    if (preg_match('/^Location:/', $response_header)) {
213
        list($header, $value) = preg_split('/: /', $response_header, 2);
214
        $response_header = 'Location: ' . $_SERVER['REQUEST_URI'] . '?csurl=' . $value;
215
    }
178 - 216
    if (!preg_match('/^(Transfer-Encoding):/', $response_header) &&
217
        !preg_match('/^(Connection):/', $response_header)) {
2 - 218
        header($response_header, false);
219
    }
220
}
221
 
178 - 222
ob_flush(); // Strange behaviour, will not work
223
flush();    // Unless both are called !
224
 
19 - 225
// Debug File proxy.log
226
if (true == CSAJAX_DEBUG) {
227
  $h = fopen("proxy.log", "a");
228
  fwrite($h, "Request URL: " . $request_url . "\n");
178 - 229
  fwrite($h, "Request Headers: " . print_r($request_headers, true));
19 - 230
  fwrite($h, "Request Method: " . $request_method . "\n");
231
  if ('POST' == $request_method) {
232
    fwrite($h, "Post Params: " . $post_data . "\n");
233
  } elseif ('PUT' == $request_method || 'DELETE' == $request_method) {
234
    fwrite($h, "Request Params: " . print_r($request_params, true) . "\n");
235
  }
236
  fwrite($h, "Return: " . $response . "\n");
178 - 237
  fwrite($h, "Response Headers: " . print_r($response_headers, true));
19 - 238
  fwrite($h, "Response Content: " . $response_content . "\n");
239
  fwrite($h, "\n");
240
  fclose($h);
241
}
2 - 242
 
19 - 243
// finally, output the content
178 - 244
echo $response_content;
245
ob_end_flush(); // Strange behaviour, will not work
246
flush();        // Unless both are called !
2 - 247
 
83 - 248
// insert authorization
249
function authReplace($str) {
87 - 250
    $str = str_replace('XxXRuNamexxxxxxxxxxxxxxxxxxxxxxx', 'Uwe_Jacobs-UweJacob-MUNATr-jwkrg', $str);
83 - 251
    $str = str_replace('XxXAppid', 'UweJacob-MUNATrad-PRD-d132041a0-85284729', $str);
252
    $str = str_replace('XxXDevid', '00fd6fda-3751-4095-b733-3899b20431ad', $str);
253
    $str = str_replace('XxXCertid', 'PRD-132041a078aa-1ee6-4300-9454-6c5b', $str);
85 - 254
    $str = str_replace('XxXDiscogsToken', 'zFvVdCdHTtQnDHCxEFTJiBhalyHFUsjdyFPCjbqP', $str);
83 - 255
    $str = str_replace('XxXUSPSUserId', '275MUNAT7574', $str);
256
    $str = str_replace('XxXShopifyApiKey', '41f0d3bf0e8e114496b198938996d9d8', $str);
257
    $str = str_replace('XxXShopifyPassword', 'f169694c488f45ccf187c92676765889', $str);
258
    $str = str_replace('XxXUPSAccessKey', 'DD53C5F37DF74D28', $str);
259
    $str = str_replace('XxXUPSUsername', 'muna_trading', $str);
260
    $str = str_replace('XxXUPSPassword', 'ZX83tbf!w7', $str);
261
    $str = str_replace('XxXAuthorization', base64_encode('UweJacob-MUNATrad-PRD-d132041a0-85284729' . ':' . 'PRD-132041a078aa-1ee6-4300-9454-6c5b'), $str);
262
 
263
    return($str);
264
}
2 - 265
function csajax_debug_message($message)
266
{
267
    if (true == CSAJAX_DEBUG) {
268
        print $message . PHP_EOL;
269
    }
3 - 270
}