3 use wcf\system\exception\HTTPNotFoundException
;
4 use wcf\system\exception\HTTPServerErrorException
;
5 use wcf\system\exception\HTTPUnauthorizedException
;
6 use wcf\system\exception\SystemException
;
7 use wcf\system\io\RemoteFile
;
12 * Sends HTTP/1.1 requests.
13 * It supports POST, SSL, Basic Auth etc.
15 * @author Tim Duesterhus
16 * @copyright 2001-2014 WoltLab GmbH
17 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
18 * @package com.woltlab.wcf
20 * @category Community Framework
22 final class HTTPRequest
{
27 private $options = array();
30 * given post parameters
33 private $postParameters = array();
39 private $files = array();
42 * indicates if request will be made via SSL
45 private $useSSL = false;
81 private $headers = array();
87 private $legacyHeaders = array();
99 private $replyHeaders = array();
105 private $replyBody = '';
111 private $statusCode = 0;
114 * Constructs a new instance of HTTPRequest.
116 * @param string $url URL to connect to
117 * @param array<string> $options
118 * @param mixed $postParameters Parameters to send via POST
119 * @param array $files Files to attach to the request
121 public function __construct($url, array $options = array(), $postParameters = array(), array $files = array()) {
124 $this->postParameters
= $postParameters;
125 $this->files
= $files;
127 $this->setOptions($options);
129 // set default headers
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());
134 if (isset($this->options
['maxLength'])) {
135 $this->addHeader('Range', 'bytes=0-'.($this->options
['maxLength'] - 1));
138 if ($this->options
['method'] !== 'GET') {
139 if (empty($this->files
)) {
140 if (is_array($postParameters)) {
141 $this->body
= http_build_query($this->postParameters
, '', '&');
143 else if (is_string($postParameters) && !empty($postParameters)) {
144 $this->body
= $postParameters;
147 $this->addHeader('content-type', 'application/x-www-form-urlencoded');
150 $boundary = StringUtil
::getRandomID();
151 $this->addHeader('content-type', 'multipart/form-data; boundary='.$boundary);
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()) {
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().']';
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";
171 $iterator = new \
RecursiveIteratorIterator(new \
RecursiveArrayIterator($this->files
), \RecursiveIteratorIterator
::SELF_FIRST
);
172 foreach ($iterator as $k => $v) {
173 if (!$iterator->hasChildren()) {
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().']';
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";
187 $this->body
.= "--".$boundary."--";
189 $this->addHeader('content-length', strlen($this->body
));
191 if (isset($this->options
['auth'])) {
192 $this->addHeader('authorization', "Basic ".base64_encode($options['auth']['username'].":".$options['auth']['password']));
194 $this->addHeader('host', $this->host
.($this->port
!= ($this->useSSL ?
443 : 80) ?
':'.$this->port
: ''));
195 $this->addHeader('connection', 'Close');
199 * Parses the given URL and applies PROXY_SERVER_HTTP.
203 private function setURL($url) {
204 if (PROXY_SERVER_HTTP
) {
205 $parsedUrl = parse_url(PROXY_SERVER_HTTP
);
209 $parsedUrl = parse_url($url);
210 $this->path
= isset($parsedUrl['path']) ?
$parsedUrl['path'] : '/';
213 $this->useSSL
= $parsedUrl['scheme'] === 'https';
214 $this->host
= $parsedUrl['host'];
215 $this->port
= isset($parsedUrl['port']) ?
$parsedUrl['port'] : ($this->useSSL ?
443 : 80);
216 $this->query
= isset($parsedUrl['query']) ?
$parsedUrl['query'] : '';
218 // update the 'Host:' header if URL has changed
219 if (!empty($this->url
) && $this->url
!= $url) {
220 $this->addHeader('host', $this->host
.($this->port
!= ($this->useSSL ?
443 : 80) ?
':'.$this->port
: ''));
227 * Executes the HTTP request.
229 public function execute() {
231 $remoteFile = new RemoteFile(($this->useSSL ?
'ssl://' : '').$this->host
, $this->port
, $this->options
['timeout']);
233 $request = $this->options
['method']." ".$this->path
.($this->query ?
'?'.$this->query
: '')." HTTP/1.1\r\n";
236 foreach ($this->headers
as $name => $values) {
237 foreach ($values as $value) {
238 $request .= $name.": ".$value."\r\n";
243 // add post parameters
244 if ($this->options
['method'] !== 'GET') $request .= $this->body
."\r\n\r\n";
246 $remoteFile->puts($request);
249 $this->replyHeaders
= array();
250 $this->replyBody
= '';
254 $chunkedTransferRegex = new Regex('(^|,)[ \t]*chunked[ \t]*$', Regex
::CASE_INSENSITIVE
);
255 // read http response, until one of is true
257 // b) bodyLength is at least maxLength
258 // c) bodyLength is at least Content-Length
260 $remoteFile->eof() ||
261 (isset($this->options
['maxLength']) && $bodyLength >= $this->options
['maxLength']) ||
262 (isset($this->replyHeaders
['content-length']) && $bodyLength >= end($this->replyHeaders
['content-length']))
266 if (isset($this->options
['maxLength'])) $chunkLength = min($chunkLength, $this->options
['maxLength'] - $bodyLength);
267 $line = $remoteFile->read($chunkLength);
269 else if (!$inHeader && (!isset($this->replyHeaders
['transfer-encoding']) ||
!$chunkedTransferRegex->match(end($this->replyHeaders
['transfer-encoding'])))) {
271 if (isset($this->options
['maxLength'])) $length = min($length, $this->options
['maxLength'] - $bodyLength);
272 if (isset($this->replyHeaders
['content-length'])) $length = min($length, end($this->replyHeaders
['content-length']) - $bodyLength);
274 $line = $remoteFile->read($length);
277 $line = $remoteFile->gets();
281 if (rtrim($line) === '') {
283 $this->parseReplyHeaders();
287 $this->replyHeaders
[] = $line;
290 if (isset($this->replyHeaders
['transfer-encoding']) && $chunkedTransferRegex->match(end($this->replyHeaders
['transfer-encoding']))) {
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);
297 // $chunkLength === 0 -> no more data
298 if ($chunkLength === 0) {
299 // clear remaining response
300 while (!$remoteFile->gets(1024));
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']);
308 // break out of main reading loop
313 $this->replyBody
.= $line;
314 $chunkLength -= strlen($line);
315 $bodyLength +
= strlen($line);
316 if ($chunkLength === 0) $remoteFile->read(2); // CRLF
320 $this->replyBody
.= $line;
321 $bodyLength +
= strlen($line);
326 if (isset($this->options
['maxLength'])) $this->replyBody
= substr($this->replyBody
, 0, $this->options
['maxLength']);
328 $remoteFile->close();
334 * Parses the reply headers.
336 private function parseReplyHeaders() {
339 foreach ($this->replyHeaders
as $header) {
340 if (strpos($header, ':') === false) {
341 $headers[trim($header)] = array(trim($header));
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);
352 list($key, $value) = explode(':', $header, 2);
355 if (!isset($headers[$key])) $headers[$key] = array();
356 $headers[$key][] = trim($value);
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);
365 $statusLine = reset($this->replyHeaders
);
366 $regex = new Regex('^HTTP/1.\d+ +(\d{3})');
367 if (!$regex->match($statusLine[0])) throw new SystemException("Unexpected status '".$statusLine."'");
368 $matches = $regex->getMatches();
369 $this->statusCode
= $matches[1];
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.
379 if (isset($this->replyHeaders
['content-length']) && (!isset($this->replyHeaders
['transfer-encoding']) ||
strtolower(end($this->replyHeaders
['transfer-encoding'])) !== 'identity') && !isset($this->options
['maxLength'])) {
380 if (strlen($this->replyBody
) != end($this->replyHeaders
['content-length'])) {
381 throw new SystemException('Body length does not match length given in header');
385 // validate status code
386 switch ($this->statusCode
) {
392 if ($this->options
['maxDepth'] <= 0) throw new SystemException("Received status code '".$this->statusCode
."' from server, but recursion level is exhausted");
394 $newRequest = clone $this;
395 $newRequest->options
['maxDepth']--;
397 // 10.3.4 The response to the request can be found under a different URI and SHOULD
398 // be retrieved using a GET method on that resource.
399 if ($this->statusCode
== '303') {
400 $newRequest->options
['method'] = 'GET';
401 $newRequest->postParameters
= array();
402 $newRequest->addHeader('content-length', '');
403 $newRequest->addHeader('content-type', '');
407 $newRequest->setURL(end($this->replyHeaders
['location']));
409 catch (SystemException
$e) {
410 throw new SystemException("Received 'Location: ".end($this->replyHeaders
['location'])."' from server, which is invalid.", 0, $e);
414 $newRequest->execute();
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
;
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
;
436 // check, if partial content was expected
437 if (!isset($this->headers
['range'])) {
438 throw new HTTPServerErrorException("Received unexpected status code '206' from server");
440 else if (!isset($this->replyHeaders
['content-range'])) {
441 throw new HTTPServerErrorException("Content-Range is missing in reply header");
448 throw new HTTPUnauthorizedException("Received status code '".$this->statusCode
."' from server");
452 throw new HTTPNotFoundException("Received status code '404' from server");
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
466 case '5': // 500 and unknown 5XX
467 throw new HTTPServerErrorException("Received status code '".$this->statusCode
."' from server");
470 throw new SystemException("Received unhandled status code '".$this->statusCode
."' from server");
478 * Returns an array with the replied data.
479 * Note that the 'headers' element is deprecated and may be removed in the future.
483 public function getReply() {
485 'statusCode' => $this->statusCode
,
486 'headers' => $this->legacyHeaders
,
487 'httpHeaders' => $this->replyHeaders
,
488 'body' => $this->replyBody
,
494 * Sets options and applies default values when an option is omitted.
496 * @param array $options
498 private function setOptions(array $options) {
499 if (!isset($options['timeout'])) {
500 $options['timeout'] = 10;
503 if (!isset($options['method'])) {
504 $options['method'] = (!empty($this->postParameters
) ||
!empty($this->files
) ?
'POST' : 'GET');
507 if (!isset($options['maxDepth'])) {
508 $options['maxDepth'] = 2;
511 if (isset($options['auth'])) {
512 if (!isset($options['auth']['username'])) {
513 throw new SystemException('Username is missing in authentification data.');
515 if (!isset($options['auth']['password'])) {
516 throw new SystemException('Password is missing in authentification data.');
520 $this->options
= $options;
524 * Adds a header to this request.
525 * When an empty value is given existing headers of this name will be removed. When append
526 * is set to false existing values will be overwritten.
528 * @param string $name
529 * @param string $value
530 * @param boolean $append
532 public function addHeader($name, $value, $append = false) {
533 // 4.2 Field names are case-insensitive.
534 $name = strtolower($name);
537 unset($this->headers
[$name]);
541 if ($append && isset($this->headers
[$name])) {
542 $this->headers
[$name][] = $value;
545 $this->headers
[$name] = array($value);
550 * Resets reply data when cloning.
552 private function __clone() {
553 $this->replyHeaders
= array();
554 $this->replyBody
= '';
555 $this->statusCode
= 0;