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 // read http response, until one of is true
256 // b) bodyLength is at least maxLength
257 // c) bodyLength is at least Content-Length
259 $remoteFile->eof() ||
260 (isset($this->options
['maxLength']) && $bodyLength >= $this->options
['maxLength']) ||
261 (isset($this->replyHeaders
['content-length']) && $bodyLength >= end($this->replyHeaders
['content-length']))
265 if (isset($this->options
['maxLength'])) $chunkLength = min($chunkLength, $this->options
['maxLength'] - $bodyLength);
266 $line = $remoteFile->read($chunkLength);
268 else if (!$inHeader) {
269 $length = min(1024, $this->options
['maxLength'] - $bodyLength);
270 if (isset($this->replyHeaders
['content-length'])) $length = min($length, end($this->replyHeaders
['content-length']) - $bodyLength);
272 $line = $remoteFile->read($length);
275 $line = $remoteFile->gets();
279 if (rtrim($line) === '') {
281 $this->parseReplyHeaders();
285 $this->replyHeaders
[] = $line;
288 $chunkedTransferRegex = new Regex('(^|,)[ \t]*chunked[ \t]*$', Regex
::CASE_INSENSITIVE
);
289 if (isset($this->replyHeaders
['transfer-encoding']) && $chunkedTransferRegex->match(end($this->replyHeaders
['transfer-encoding']))) {
290 // last chunk finished
291 if ($chunkLength === 0) {
292 // read hex data and trash chunk-extension
293 list($hex) = explode(';', $line, 2);
294 $chunkLength = hexdec($hex);
296 // $chunkLength === 0 -> no more data
297 if ($chunkLength === 0) {
298 // clear remaining response
299 while (!$remoteFile->gets(1024));
301 // remove chunked from transfer-encoding
302 $this->replyHeaders
['transfer-encoding'] = array_filter(array_map(function ($element) use ($chunkedTransferRegex) {
303 return $chunkedTransferRegex->replace($element, '');
304 }, $this->replyHeaders
['transfer-encoding']), 'trim');
305 if (empty($this->replyHeaders
['transfer-encoding'])) unset($this->replyHeaders
['transfer-encoding']);
307 // break out of main reading loop
312 $this->replyBody
.= $line;
313 $chunkLength -= strlen($line);
314 $bodyLength +
= strlen($line);
315 if ($chunkLength === 0) $remoteFile->read(2); // CRLF
319 $this->replyBody
.= $line;
320 $bodyLength +
= strlen($line);
325 if (isset($this->options
['maxLength'])) $this->replyBody
= substr($this->replyBody
, 0, $this->options
['maxLength']);
327 $remoteFile->close();
333 * Parses the reply headers.
335 private function parseReplyHeaders() {
338 foreach ($this->replyHeaders
as $header) {
339 if (strpos($header, ':') === false) {
340 $headers[trim($header)] = array(trim($header));
344 // 4.2 Header fields can be
345 // extended over multiple lines by preceding each extra line with at
346 // least one SP or HT.
347 if (ltrim($header, "\t ") !== $header) {
348 $headers[$lastKey][] = array_pop($headers[$lastKey]).' '.trim($header);
351 list($key, $value) = explode(':', $header, 2);
354 if (!isset($headers[$key])) $headers[$key] = array();
355 $headers[$key][] = trim($value);
358 // 4.2 Field names are case-insensitive.
359 $this->replyHeaders
= array_change_key_case($headers);
360 if (isset($this->replyHeaders
['transfer-encoding'])) $this->replyHeaders
['transfer-encoding'] = array(implode(',', $this->replyHeaders
['transfer-encoding']));
361 $this->legacyHeaders
= array_map('end', $headers);
364 $statusLine = reset($this->replyHeaders
);
365 $regex = new Regex('^HTTP/1.\d+ +(\d{3})');
366 if (!$regex->match($statusLine[0])) throw new SystemException("Unexpected status '".$statusLine."'");
367 $matches = $regex->getMatches();
368 $this->statusCode
= $matches[1];
374 private function parseReply() {
375 // 4.4 Messages MUST NOT include both a Content-Length header field and a
376 // non-identity transfer-coding. If the message does include a non-
377 // identity transfer-coding, the Content-Length MUST be ignored.
378 if (isset($this->replyHeaders
['content-length']) && (!isset($this->replyHeaders
['transfer-encoding']) ||
strtolower(end($this->replyHeaders
['transfer-encoding'])) !== 'identity') && !isset($this->options
['maxLength'])) {
379 if (strlen($this->replyBody
) != end($this->replyHeaders
['content-length'])) {
380 throw new SystemException('Body length does not match length given in header');
384 // validate status code
385 switch ($this->statusCode
) {
391 if ($this->options
['maxDepth'] <= 0) throw new SystemException("Received status code '".$this->statusCode
."' from server, but recursion level is exhausted");
393 $newRequest = clone $this;
394 $newRequest->options
['maxDepth']--;
396 // 10.3.4 The response to the request can be found under a different URI and SHOULD
397 // be retrieved using a GET method on that resource.
398 if ($this->statusCode
== '303') {
399 $newRequest->options
['method'] = 'GET';
400 $newRequest->postParameters
= array();
401 $newRequest->addHeader('content-length', '');
402 $newRequest->addHeader('content-type', '');
406 $newRequest->setURL(end($this->replyHeaders
['location']));
408 catch (SystemException
$e) {
409 throw new SystemException("Received 'Location: ".end($this->replyHeaders
['location'])."' from server, which is invalid.", 0, $e);
413 $newRequest->execute();
415 // update data with data from the inner request
416 $this->url
= $newRequest->url
;
417 $this->statusCode
= $newRequest->statusCode
;
418 $this->replyHeaders
= $newRequest->replyHeaders
;
419 $this->replyBody
= $newRequest->replyBody
;
421 catch (SystemException
$e) {
422 // update data with data from the inner request
423 $this->url
= $newRequest->url
;
424 $this->statusCode
= $newRequest->statusCode
;
425 $this->replyHeaders
= $newRequest->replyHeaders
;
426 $this->replyBody
= $newRequest->replyBody
;
435 // check, if partial content was expected
436 if (!isset($this->headers
['range'])) {
437 throw new HTTPServerErrorException("Received unexpected status code '206' from server");
439 else if (!isset($this->replyHeaders
['content-range'])) {
440 throw new HTTPServerErrorException("Content-Range is missing in reply header");
447 throw new HTTPUnauthorizedException("Received status code '".$this->statusCode
."' from server");
451 throw new HTTPNotFoundException("Received status code '404' from server");
455 // 6.1.1 However, applications MUST
456 // understand the class of any status code, as indicated by the first
457 // digit, and treat any unrecognized response as being equivalent to the
458 // x00 status code of that class, with the exception that an
459 // unrecognized response MUST NOT be cached.
460 switch (substr($this->statusCode
, 0, 1)) {
461 case '2': // 200 and unknown 2XX
462 case '3': // 300 and unknown 3XX
465 case '5': // 500 and unknown 5XX
466 throw new HTTPServerErrorException("Received status code '".$this->statusCode
."' from server");
469 throw new SystemException("Received unhandled status code '".$this->statusCode
."' from server");
477 * Returns an array with the replied data.
478 * Note that the 'headers' element is deprecated and may be removed in the future.
482 public function getReply() {
484 'statusCode' => $this->statusCode
,
485 'headers' => $this->legacyHeaders
,
486 'httpHeaders' => $this->replyHeaders
,
487 'body' => $this->replyBody
,
493 * Sets options and applies default values when an option is omitted.
495 * @param array $options
497 private function setOptions(array $options) {
498 if (!isset($options['timeout'])) {
499 $options['timeout'] = 10;
502 if (!isset($options['method'])) {
503 $options['method'] = (!empty($this->postParameters
) ||
!empty($this->files
) ?
'POST' : 'GET');
506 if (!isset($options['maxDepth'])) {
507 $options['maxDepth'] = 2;
510 if (isset($options['auth'])) {
511 if (!isset($options['auth']['username'])) {
512 throw new SystemException('Username is missing in authentification data.');
514 if (!isset($options['auth']['password'])) {
515 throw new SystemException('Password is missing in authentification data.');
519 $this->options
= $options;
523 * Adds a header to this request.
524 * When an empty value is given existing headers of this name will be removed. When append
525 * is set to false existing values will be overwritten.
527 * @param string $name
528 * @param string $value
529 * @param boolean $append
531 public function addHeader($name, $value, $append = false) {
532 // 4.2 Field names are case-insensitive.
533 $name = strtolower($name);
536 unset($this->headers
[$name]);
540 if ($append && isset($this->headers
[$name])) {
541 $this->headers
[$name][] = $value;
544 $this->headers
[$name] = array($value);
549 * Resets reply data when cloning.
551 private function __clone() {
552 $this->replyHeaders
= array();
553 $this->replyBody
= '';
554 $this->statusCode
= 0;