Fixed some rendering issues on mobile devices
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / util / HTTPRequest.class.php
CommitLineData
86fc0430
TD
1<?php
2namespace wcf\util;
3536d2fe
AE
3use wcf\system\exception\HTTPNotFoundException;
4use wcf\system\exception\HTTPServerErrorException;
5use wcf\system\exception\HTTPUnauthorizedException;
86fc0430
TD
6use wcf\system\exception\SystemException;
7use wcf\system\io\RemoteFile;
8use wcf\system\Regex;
9use wcf\system\WCF;
10
11/**
8fe14bd6 12 * Sends HTTP/1.1 requests.
86fc0430
TD
13 * It supports POST, SSL, Basic Auth etc.
14 *
3536d2fe 15 * @author Tim Duesterhus
ca4ba303 16 * @copyright 2001-2014 WoltLab GmbH
86fc0430
TD
17 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
18 * @package com.woltlab.wcf
19 * @subpackage util
20 * @category Community Framework
21 */
a195ffa6 22final class HTTPRequest {
86fc0430
TD
23 /**
24 * given options
a17de04e 25 * @var array
86fc0430
TD
26 */
27 private $options = array();
28
29 /**
30 * given post parameters
a17de04e 31 * @var array
86fc0430
TD
32 */
33 private $postParameters = array();
34
5f70a0de
TD
35 /**
36 * given files
06355ec3 37 * @var array
5f70a0de
TD
38 */
39 private $files = array();
40
86fc0430 41 /**
60f613e2 42 * indicates if request will be made via SSL
a17de04e 43 * @var boolean
86fc0430
TD
44 */
45 private $useSSL = false;
46
47 /**
48 * target host
a17de04e 49 * @var string
86fc0430
TD
50 */
51 private $host;
52
53 /**
54 * target port
a17de04e 55 * @var integer
86fc0430
TD
56 */
57 private $port;
a17de04e 58
86fc0430
TD
59 /**
60 * target path
a17de04e 61 * @var string
86fc0430
TD
62 */
63 private $path;
64
65 /**
66 * target query string
a17de04e 67 * @var string
86fc0430
TD
68 */
69 private $query;
70
25cdc083
AE
71 /**
72 * request URL
73 * @var string
74 */
75 private $url = '';
76
86fc0430
TD
77 /**
78 * request headers
a17de04e 79 * @var array<string>
86fc0430
TD
80 */
81 private $headers = array();
82
8fe14bd6
TD
83 /**
84 * legacy headers
85 * @var array<string>
86 */
87 private $legacyHeaders = array();
88
5f70a0de
TD
89 /**
90 * request body
91 * @var string
92 */
93 private $body = '';
94
86fc0430
TD
95 /**
96 * reply headers
a17de04e 97 * @var array<string>
86fc0430
TD
98 */
99 private $replyHeaders = array();
100
101 /**
102 * reply body
a17de04e 103 * @var string
86fc0430
TD
104 */
105 private $replyBody = '';
106
107 /**
108 * reply status code
a17de04e 109 * @var integer
86fc0430
TD
110 */
111 private $statusCode = 0;
112
113 /**
a17de04e 114 * Constructs a new instance of HTTPRequest.
86fc0430
TD
115 *
116 * @param string $url URL to connect to
117 * @param array<string> $options
1b20f990 118 * @param mixed $postParameters Parameters to send via POST
5f70a0de 119 * @param array $files Files to attach to the request
86fc0430 120 */
1b20f990 121 public function __construct($url, array $options = array(), $postParameters = array(), array $files = array()) {
86fc0430
TD
122 $this->setURL($url);
123
124 $this->postParameters = $postParameters;
5f70a0de 125 $this->files = $files;
86fc0430
TD
126
127 $this->setOptions($options);
128
a195ffa6 129 // set default headers
8fe14bd6
TD
130 $this->addHeader('user-agent', "HTTP.PHP (HTTPRequest.class.php; WoltLab Community Framework/".WCF_VERSION."; ".WCF::getLanguage()->languageCode.")");
131 $this->addHeader('accept', '*/*');
132 $this->addHeader('accept-language', WCF::getLanguage()->getFixedLanguageCode());
133
4d28d5a2 134 if (isset($this->options['maxLength'])) {
5262964b 135 $this->addHeader('Range', 'bytes=0-'.($this->options['maxLength'] - 1));
4d28d5a2
SG
136 }
137
86fc0430 138 if ($this->options['method'] !== 'GET') {
5f70a0de 139 if (empty($this->files)) {
1b20f990
AE
140 if (is_array($postParameters)) {
141 $this->body = http_build_query($this->postParameters, '', '&');
142 }
143 else if (is_string($postParameters) && !empty($postParameters)) {
144 $this->body = $postParameters;
145 }
146
8fe14bd6 147 $this->addHeader('content-type', 'application/x-www-form-urlencoded');
5f70a0de
TD
148 }
149 else {
150 $boundary = StringUtil::getRandomID();
8fe14bd6 151 $this->addHeader('content-type', 'multipart/form-data; boundary='.$boundary);
5f70a0de
TD
152
153 // source of the iterators: http://stackoverflow.com/a/7623716/782822
154 if (!empty($this->postParameters)) {
155 $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($this->postParameters), \RecursiveIteratorIterator::SELF_FIRST);
156 foreach ($iterator as $k => $v) {
157 if (!$iterator->hasChildren()) {
158 $key = '';
159 for ($i = 0, $max = $iterator->getDepth(); $i <= $max; $i++) {
160 if ($i === 0) $key .= $iterator->getSubIterator($i)->key();
161 else $key .= '['.$iterator->getSubIterator($i)->key().']';
162 }
163
164 $this->body .= "--".$boundary."\r\n";
165 $this->body .= 'Content-Disposition: form-data; name="'.$key.'"'."\r\n\r\n";
166 $this->body .= $v."\r\n";
167 }
168 }
169 }
170
171 $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($this->files), \RecursiveIteratorIterator::SELF_FIRST);
172 foreach ($iterator as $k => $v) {
173 if (!$iterator->hasChildren()) {
174 $key = '';
175 for ($i = 0, $max = $iterator->getDepth(); $i <= $max; $i++) {
176 if ($i === 0) $key .= $iterator->getSubIterator($i)->key();
177 else $key .= '['.$iterator->getSubIterator($i)->key().']';
178 }
179
180 $this->body .= "--".$boundary."\r\n";
181 $this->body .= 'Content-Disposition: form-data; name="'.$k.'"; filename="'.basename($v).'"'."\r\n";
182 $this->body .= 'Content-Type: '.(FileUtil::getMimeType($v) ?: 'application/octet-stream.')."\r\n\r\n";
183 $this->body .= file_get_contents($v)."\r\n";
184 }
185 }
186
187 $this->body .= "--".$boundary."--";
188 }
8fe14bd6 189 $this->addHeader('content-length', strlen($this->body));
86fc0430
TD
190 }
191 if (isset($this->options['auth'])) {
8fe14bd6 192 $this->addHeader('authorization', "Basic ".base64_encode($options['auth']['username'].":".$options['auth']['password']));
86fc0430 193 }
8fe14bd6
TD
194 $this->addHeader('host', $this->host.($this->port != ($this->useSSL ? 443 : 80) ? ':'.$this->port : ''));
195 $this->addHeader('connection', 'Close');
86fc0430
TD
196 }
197
198 /**
199 * Parses the given URL and applies PROXY_SERVER_HTTP.
200 *
a17de04e 201 * @param string $url
86fc0430
TD
202 */
203 private function setURL($url) {
204 if (PROXY_SERVER_HTTP) {
205 $parsedUrl = parse_url(PROXY_SERVER_HTTP);
206 $this->path = $url;
207 }
208 else {
209 $parsedUrl = parse_url($url);
210 $this->path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '/';
211 }
d5bd7602 212
86fc0430
TD
213 $this->useSSL = $parsedUrl['scheme'] === 'https';
214 $this->host = $parsedUrl['host'];
215 $this->port = isset($parsedUrl['port']) ? $parsedUrl['port'] : ($this->useSSL ? 443 : 80);
86fc0430 216 $this->query = isset($parsedUrl['query']) ? $parsedUrl['query'] : '';
d5bd7602
AE
217
218 // update the 'Host:' header if URL has changed
219 if (!empty($this->url) && $this->url != $url) {
8fe14bd6 220 $this->addHeader('host', $this->host.($this->port != ($this->useSSL ? 443 : 80) ? ':'.$this->port : ''));
d5bd7602
AE
221 }
222
223 $this->url = $url;
86fc0430
TD
224 }
225
226 /**
227 * Executes the HTTP request.
228 */
229 public function execute() {
230 // connect
231 $remoteFile = new RemoteFile(($this->useSSL ? 'ssl://' : '').$this->host, $this->port, $this->options['timeout']);
232
8fe14bd6 233 $request = $this->options['method']." ".$this->path.($this->query ? '?'.$this->query : '')." HTTP/1.1\r\n";
86fc0430 234
a195ffa6 235 // add headers
86fc0430
TD
236 foreach ($this->headers as $name => $values) {
237 foreach ($values as $value) {
238 $request .= $name.": ".$value."\r\n";
239 }
240 }
241 $request .= "\r\n";
8fe14bd6 242
a195ffa6 243 // add post parameters
5f70a0de 244 if ($this->options['method'] !== 'GET') $request .= $this->body."\r\n\r\n";
d5bd7602 245
86fc0430
TD
246 $remoteFile->puts($request);
247
248 $inHeader = true;
249 $this->replyHeaders = array();
250 $this->replyBody = '';
8fe14bd6 251 $chunkLength = 0;
5262964b 252 $bodyLength = 0;
c7fe2510 253
7ced4c6a
TD
254 // read http response, until one of is true
255 // a) EOF is reached
256 // b) bodyLength is at least maxLength
257 // c) bodyLength is at least Content-Length
258 while (!(
259 $remoteFile->eof() ||
260 (isset($this->options['maxLength']) && $bodyLength >= $this->options['maxLength']) ||
261 (isset($this->replyHeaders['content-length']) && $bodyLength >= end($this->replyHeaders['content-length']))
262 )) {
263
8fe14bd6 264 if ($chunkLength) {
5262964b 265 if (isset($this->options['maxLength'])) $chunkLength = min($chunkLength, $this->options['maxLength'] - $bodyLength);
8fe14bd6
TD
266 $line = $remoteFile->read($chunkLength);
267 }
7ced4c6a 268 else if (!$inHeader) {
4b3a6b71
TD
269 $length = 1024;
270 if (isset($this->options['maxLength'])) $length = min($length, $this->options['maxLength'] - $bodyLength);
7ced4c6a
TD
271 if (isset($this->replyHeaders['content-length'])) $length = min($length, end($this->replyHeaders['content-length']) - $bodyLength);
272
273 $line = $remoteFile->read($length);
274 }
8fe14bd6
TD
275 else {
276 $line = $remoteFile->gets();
277 }
278
86fc0430
TD
279 if ($inHeader) {
280 if (rtrim($line) === '') {
281 $inHeader = false;
8fe14bd6
TD
282 $this->parseReplyHeaders();
283
86fc0430
TD
284 continue;
285 }
286 $this->replyHeaders[] = $line;
287 }
288 else {
8fe14bd6
TD
289 $chunkedTransferRegex = new Regex('(^|,)[ \t]*chunked[ \t]*$', Regex::CASE_INSENSITIVE);
290 if (isset($this->replyHeaders['transfer-encoding']) && $chunkedTransferRegex->match(end($this->replyHeaders['transfer-encoding']))) {
8fe14bd6
TD
291 // last chunk finished
292 if ($chunkLength === 0) {
293 // read hex data and trash chunk-extension
294 list($hex) = explode(';', $line, 2);
295 $chunkLength = hexdec($hex);
296
297 // $chunkLength === 0 -> no more data
298 if ($chunkLength === 0) {
299 // clear remaining response
7ced4c6a 300 while (!$remoteFile->gets(1024));
8fe14bd6 301
8f3e6138
TD
302 // remove chunked from transfer-encoding
303 $this->replyHeaders['transfer-encoding'] = array_filter(array_map(function ($element) use ($chunkedTransferRegex) {
304 return $chunkedTransferRegex->replace($element, '');
305 }, $this->replyHeaders['transfer-encoding']), 'trim');
306 if (empty($this->replyHeaders['transfer-encoding'])) unset($this->replyHeaders['transfer-encoding']);
307
8fe14bd6
TD
308 // break out of main reading loop
309 break;
310 }
311 }
312 else {
313 $this->replyBody .= $line;
314 $chunkLength -= strlen($line);
8f3e6138
TD
315 $bodyLength += strlen($line);
316 if ($chunkLength === 0) $remoteFile->read(2); // CRLF
8fe14bd6
TD
317 }
318 }
319 else {
320 $this->replyBody .= $line;
8f3e6138 321 $bodyLength += strlen($line);
5262964b 322 }
86fc0430
TD
323 }
324 }
325
5262964b
TD
326 if (isset($this->options['maxLength'])) $this->replyBody = substr($this->replyBody, 0, $this->options['maxLength']);
327
8fe14bd6
TD
328 $remoteFile->close();
329
86fc0430
TD
330 $this->parseReply();
331 }
332
333 /**
8fe14bd6 334 * Parses the reply headers.
86fc0430 335 */
8fe14bd6 336 private function parseReplyHeaders() {
86fc0430 337 $headers = array();
8fe14bd6 338 $lastKey = '';
86fc0430
TD
339 foreach ($this->replyHeaders as $header) {
340 if (strpos($header, ':') === false) {
8fe14bd6 341 $headers[trim($header)] = array(trim($header));
86fc0430
TD
342 continue;
343 }
8fe14bd6
TD
344
345 // 4.2 Header fields can be
346 // extended over multiple lines by preceding each extra line with at
347 // least one SP or HT.
348 if (ltrim($header, "\t ") !== $header) {
349 $headers[$lastKey][] = array_pop($headers[$lastKey]).' '.trim($header);
350 }
351 else {
352 list($key, $value) = explode(':', $header, 2);
353
354 $lastKey = $key;
355 if (!isset($headers[$key])) $headers[$key] = array();
356 $headers[$key][] = trim($value);
357 }
86fc0430 358 }
8fe14bd6
TD
359 // 4.2 Field names are case-insensitive.
360 $this->replyHeaders = array_change_key_case($headers);
361 if (isset($this->replyHeaders['transfer-encoding'])) $this->replyHeaders['transfer-encoding'] = array(implode(',', $this->replyHeaders['transfer-encoding']));
362 $this->legacyHeaders = array_map('end', $headers);
86fc0430 363
a0eb8370 364 // get status code
86fc0430 365 $statusLine = reset($this->replyHeaders);
8fe14bd6
TD
366 $regex = new Regex('^HTTP/1.\d+ +(\d{3})');
367 if (!$regex->match($statusLine[0])) throw new SystemException("Unexpected status '".$statusLine."'");
86fc0430 368 $matches = $regex->getMatches();
aeaa135c 369 $this->statusCode = $matches[1];
8fe14bd6
TD
370 }
371
372 /**
373 * Parses the reply.
374 */
375 private function parseReply() {
376 // 4.4 Messages MUST NOT include both a Content-Length header field and a
377 // non-identity transfer-coding. If the message does include a non-
378 // identity transfer-coding, the Content-Length MUST be ignored.
5262964b 379 if (isset($this->replyHeaders['content-length']) && (!isset($this->replyHeaders['transfer-encoding']) || strtolower(end($this->replyHeaders['transfer-encoding'])) !== 'identity') && !isset($this->options['maxLength'])) {
8009cc11 380 if (strlen($this->replyBody) != end($this->replyHeaders['content-length'])) {
a0eb8370
DR
381 throw new SystemException('Body length does not match length given in header');
382 }
383 }
384
385 // validate status code
aeaa135c 386 switch ($this->statusCode) {
86fc0430
TD
387 case '301':
388 case '302':
389 case '303':
390 case '307':
391 // redirect
c7fe2510 392 if ($this->options['maxDepth'] <= 0) throw new SystemException("Received status code '".$this->statusCode."' from server, but recursion level is exhausted");
86fc0430
TD
393
394 $newRequest = clone $this;
395 $newRequest->options['maxDepth']--;
c7fe2510 396
8fe14bd6 397 // 10.3.4 The response to the request can be found under a different URI and SHOULD
c7fe2510 398 // be retrieved using a GET method on that resource.
c7fe2510 399 if ($this->statusCode == '303') {
86fc0430
TD
400 $newRequest->options['method'] = 'GET';
401 $newRequest->postParameters = array();
8fe14bd6
TD
402 $newRequest->addHeader('content-length', '');
403 $newRequest->addHeader('content-type', '');
86fc0430 404 }
c7fe2510 405
86fc0430 406 try {
8fe14bd6 407 $newRequest->setURL(end($this->replyHeaders['location']));
86fc0430
TD
408 }
409 catch (SystemException $e) {
8fe14bd6 410 throw new SystemException("Received 'Location: ".end($this->replyHeaders['location'])."' from server, which is invalid.", 0, $e);
86fc0430 411 }
86fc0430 412
283df336
TD
413 try {
414 $newRequest->execute();
415
416 // update data with data from the inner request
417 $this->url = $newRequest->url;
418 $this->statusCode = $newRequest->statusCode;
419 $this->replyHeaders = $newRequest->replyHeaders;
420 $this->replyBody = $newRequest->replyBody;
421 }
422 catch (SystemException $e) {
423 // update data with data from the inner request
424 $this->url = $newRequest->url;
425 $this->statusCode = $newRequest->statusCode;
426 $this->replyHeaders = $newRequest->replyHeaders;
427 $this->replyBody = $newRequest->replyBody;
428
429 throw $e;
430 }
431
86fc0430
TD
432 return;
433 break;
a17de04e 434
4d28d5a2
SG
435 case '206':
436 // check, if partial content was expected
5262964b 437 if (!isset($this->headers['range'])) {
4d28d5a2
SG
438 throw new HTTPServerErrorException("Received unexpected status code '206' from server");
439 }
5262964b 440 else if (!isset($this->replyHeaders['content-range'])) {
4d28d5a2
SG
441 throw new HTTPServerErrorException("Content-Range is missing in reply header");
442 }
443 break;
444
3536d2fe 445 case '401':
5cd59413 446 case '402':
3536d2fe
AE
447 case '403':
448 throw new HTTPUnauthorizedException("Received status code '".$this->statusCode."' from server");
449 break;
450
451 case '404':
452 throw new HTTPNotFoundException("Received status code '404' from server");
453 break;
8fe14bd6 454
86fc0430 455 default:
8fe14bd6
TD
456 // 6.1.1 However, applications MUST
457 // understand the class of any status code, as indicated by the first
458 // digit, and treat any unrecognized response as being equivalent to the
459 // x00 status code of that class, with the exception that an
460 // unrecognized response MUST NOT be cached.
461 switch (substr($this->statusCode, 0, 1)) {
462 case '2': // 200 and unknown 2XX
463 case '3': // 300 and unknown 3XX
464 // we are fine
465 break;
466 case '5': // 500 and unknown 5XX
467 throw new HTTPServerErrorException("Received status code '".$this->statusCode."' from server");
468 break;
469 default:
470 throw new SystemException("Received unhandled status code '".$this->statusCode."' from server");
471 break;
472 }
86fc0430
TD
473 break;
474 }
86fc0430
TD
475 }
476
477 /**
478 * Returns an array with the replied data.
8fe14bd6 479 * Note that the 'headers' element is deprecated and may be removed in the future.
86fc0430 480 *
a17de04e 481 * @return array
86fc0430
TD
482 */
483 public function getReply() {
a195ffa6
TD
484 return array(
485 'statusCode' => $this->statusCode,
8fe14bd6
TD
486 'headers' => $this->legacyHeaders,
487 'httpHeaders' => $this->replyHeaders,
25cdc083
AE
488 'body' => $this->replyBody,
489 'url' => $this->url
a195ffa6 490 );
86fc0430
TD
491 }
492
493 /**
494 * Sets options and applies default values when an option is omitted.
495 *
a17de04e 496 * @param array $options
86fc0430
TD
497 */
498 private function setOptions(array $options) {
499 if (!isset($options['timeout'])) {
c7fe2510 500 $options['timeout'] = 10;
86fc0430
TD
501 }
502
503 if (!isset($options['method'])) {
5f70a0de 504 $options['method'] = (!empty($this->postParameters) || !empty($this->files) ? 'POST' : 'GET');
86fc0430
TD
505 }
506
507 if (!isset($options['maxDepth'])) {
508 $options['maxDepth'] = 2;
509 }
510
511 if (isset($options['auth'])) {
512 if (!isset($options['auth']['username'])) {
c7fe2510 513 throw new SystemException('Username is missing in authentification data.');
86fc0430
TD
514 }
515 if (!isset($options['auth']['password'])) {
c7fe2510 516 throw new SystemException('Password is missing in authentification data.');
86fc0430
TD
517 }
518 }
519
520 $this->options = $options;
521 }
522
523 /**
524 * Adds a header to this request.
c7fe2510 525 * When an empty value is given existing headers of this name will be removed. When append
86fc0430
TD
526 * is set to false existing values will be overwritten.
527 *
a17de04e
MS
528 * @param string $name
529 * @param string $value
530 * @param boolean $append
86fc0430
TD
531 */
532 public function addHeader($name, $value, $append = false) {
8fe14bd6
TD
533 // 4.2 Field names are case-insensitive.
534 $name = strtolower($name);
535
86fc0430
TD
536 if ($value === '') {
537 unset($this->headers[$name]);
538 return;
539 }
540
541 if ($append && isset($this->headers[$name])) {
542 $this->headers[$name][] = $value;
543 }
a377993e
TD
544 else {
545 $this->headers[$name] = array($value);
546 }
86fc0430
TD
547 }
548
549 /**
550 * Resets reply data when cloning.
551 */
552 private function __clone() {
553 $this->replyHeaders = array();
554 $this->replyBody = '';
555 $this->statusCode = 0;
556 }
58e1d71f 557}