forked from iRail/The-DataTank
-
Notifications
You must be signed in to change notification settings - Fork 2
/
TDT.class.php
368 lines (326 loc) · 13.9 KB
/
TDT.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
/**
* Helper classes that are specifically designed for TDT. When developing modules you can use these for better performance
*
* @package The-DataTank
* @copyright (C) 2011 by iRail vzw/asbl
* @license AGPLv3
* @author Jan Vansteenlandt <[email protected]>
* @author Pieter Colpaert <[email protected]>
*/
/**
* Helper class specifically designed for TDT. When developing modules you can use these for better performance.
*/
class TDT {
private static $HTTP_REQUEST_TIMEOUT = 10; // set the standard timeout to 10
private static $CACHE_TIME = 60; // set the default caching time to 60 seconds
/**
* The HttpRequest stolen from Drupal 7. Drupal is licensed GPLv2 or later. This is compatible with our AGPL license.
* Use this function to get some content
* @param string $url The url for the request
* @param array $options Additional arguments to pass along the httprequest.
* @return mixed Returns errorcode or result of the httprequest.
*/
public static function HttpRequest($url, array $options = array()) {
// Parse the URL and make sure we can handle the schema.
$uri = @parse_url($url);
if ($uri == FALSE) {
throw new CouldNotParseUrlTDTException($url);
}
//maybe our result is the cache. If so, return the cache value
$cache = Cache::getInstance();
//Generate a cachekey for the url and the post data
$cachekey = "";
if(isset($options["data"])){
$cachekey = md5(urlencode($url) . md5($options["data"]));
}else{
$cachekey = md5(urlencode($url));
}
//DEBUG echo $url . " " . $cachekey . "<br/>\n";
$result = $cache->get($cachekey);
if (!is_null($result)) {
return $result;
}
//in any other case, just continue and add it to the cache afterwards
$result = new StdClass();
if (!isset($uri['scheme'])) {
throw new CouldNotParseUrlTDTException("Forgot to add http(s)? " . $url);
}
self::timer_start(__FUNCTION__);
// Merge the default options.
$options += array(
'headers' => array(),
'method' => 'GET',
'data' => NULL,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);
// stream_socket_client() requires timeout to be a float.
$options['timeout'] = (float) $options['timeout'];
switch ($uri['scheme']) {
case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$socket = 'tcp://' . $uri['host'] . ':' . $port;
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the standard port to prevent from breaking rewrite rules
// checking the host that do not take into account the port number.
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
break;
case 'https':
// Note: Only works when PHP is compiled with OpenSSL support.
$port = isset($uri['port']) ? $uri['port'] : 443;
$socket = 'ssl://' . $uri['host'] . ':' . $port;
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
break;
default:
$result->error = 'invalid schema ' . $uri['scheme'];
$result->code = -1003;
return $result;
}
if (empty($options['context'])) {
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
} else {
// Create a stream with context. Allows verification of a SSL certificate.
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
}
// Make sure the socket opened properly.
if (!$fp) {
throw new HttpOutException($url);
}
// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?' . $uri['query'];
}
// Merge the default headers.
$options['headers'] += array(
'User-Agent' => 'The DataTank 1.0', //TODO VERSION
);
// Only add Content-Length if we actually have any content or if it is a POST
// or PUT request. Some non-standard servers get confused by Content-Length in
// at least HEAD/GET requests, and Squid always requires Content-Length in
// POST/PUT requests.
$content_length = strlen($options['data']);
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
$options['headers']['Content-Length'] = $content_length;
}
// If the server URL has a user then attempt to use basic authentication.
if (isset($uri['user'])) {
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
}
// If the database prefix is being used by SimpleTest to run the tests in a copied
// database then set the user-agent header to the database prefix so that any
// calls to other Drupal pages will run the SimpleTest prefixed database. The
// user-agent is used to ensure that multiple testing sessions running at the
// same time won't interfere with each other as they would if the database
// prefix were stored statically in a file or database variable.
$test_info = &$GLOBALS['drupal_test_info'];
if (!empty($test_info['test_run_id'])) {
$options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
}
$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
foreach ($options['headers'] as $name => $value) {
$request .= $name . ': ' . trim($value) . "\r\n";
}
$request .= "\r\n" . $options['data'];
$result->request = $request;
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - self::timer_read(__FUNCTION__) / 1000;
if ($timeout > 0) {
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
fwrite($fp, $request);
}
// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
// instead must invoke stream_get_meta_data() each iteration.
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'];
$response = '';
while ($alive) {
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - self::timer_read(__FUNCTION__) / 1000;
if ($timeout <= 0) {
$info['timed_out'] = TRUE;
break;
}
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
$chunk = fread($fp, 1024);
$response .= $chunk;
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
}
fclose($fp);
if ($info['timed_out']) {
$result->code = self::$HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
return $result;
}
// Parse response headers from the response body.
// Be tolerant of malformed HTTP responses that separate header and body with
// \n\n or \r\r instead of \r\n\r\n.
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response = preg_split("/\r\n|\n|\r/", $response);
// Parse the response status line.
list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
$result->protocol = $protocol;
$result->status_message = $status_message;
$result->headers = array();
// Parse the response headers.
while ($line = trim(array_shift($response))) {
list($name, $value) = explode(':', $line, 2);
$name = strtolower($name);
if (isset($result->headers[$name]) && $name == 'set-cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$name] .= ',' . trim($value);
} else {
$result->headers[$name] = trim($value);
}
}
$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
$result->code = $code;
switch ($code) {
case 200: // OK
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['location'];
$options['timeout'] -= self::timer_read(__FUNCTION__) / 1000;
if ($options['timeout'] <= 0) {
$result->code = self::$HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
} elseif ($options['max_redirects']) {
// Redirect to the new location.
$options['max_redirects']--;
$result = self::HttpRequest($location, $options);
$result->redirect_code = $code;
}
if (!isset($result->redirect_url)) {
$result->redirect_url = $location;
}
break;
default:
$result->error = $url;
}
//store the result in cache
$cachingtime = self::$CACHE_TIME;
if (isset($options["cache-time"])) { //are we sure we're going to call the option cache-time?
$cachingtime = $options["cache-time"];
}
$cache->set($cachekey, $result, $cachingtime);
return $result;
}
private static function timer_start($name) {
global $timers;
$timers[$name]['start'] = microtime(TRUE);
$timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
}
/**
* Function needed by drupal for http request.
*/
private static function timer_stop($name) {
global $timers;
if (isset($timers[$name]['start'])) {
$stop = microtime(TRUE);
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);
if (isset($timers[$name]['time'])) {
$timers[$name]['time'] += $diff;
} else {
$timers[$name]['time'] = $diff;
}
unset($timers[$name]['start']);
}
return $timers[$name];
}
/**
* Function needed by drupal for http request ({@link HttpRequest()}).
*/
private static function timer_read($name) {
global $timers;
if (isset($timers[$name]['start'])) {
$stop = microtime(TRUE);
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);
if (isset($timers[$name]['time'])) {
$diff += $timers[$name]['time'];
}
return $diff;
}
return $timers[$name]['time'];
}
/**
* This functions sorts the parameters.
*/
public static function sort_parameters($params) {
asort($params);
return $params;
//$query = preg_split('?', $url, 1, PREG_SPLIT_NO_EMPTY)[1];
//$pairs = preg_split('&', $query, PREG_SPLIT_NO_EMPTY);
//sort($pairs);
//$sorted_query = '';
//foreach ($pairs as $key => $val) {
//$sorted_query .= $val;
//}
//return $sorted_query;
}
/**
* This function checks if an array is associative
*/
public static function is_assoc($arr) {
if (!is_array($arr))
return false;
if (count($arr)==0)
return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
}
?>