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.
255 while (!$remoteFile->eof()) {
257 if (isset($this->options
['maxLength'])) $chunkLength = min($chunkLength, $this->options
['maxLength'] - $bodyLength);
258 $line = $remoteFile->read($chunkLength);
261 $line = $remoteFile->gets();
265 if (rtrim($line) === '') {
267 $this->parseReplyHeaders();
271 $this->replyHeaders
[] = $line;
274 $chunkedTransferRegex = new Regex('(^|,)[ \t]*chunked[ \t]*$', Regex
::CASE_INSENSITIVE
);
275 if (isset($this->replyHeaders
['transfer-encoding']) && $chunkedTransferRegex->match(end($this->replyHeaders
['transfer-encoding']))) {
276 // last chunk finished
277 if ($chunkLength === 0) {
278 // read hex data and trash chunk-extension
279 list($hex) = explode(';', $line, 2);
280 $chunkLength = hexdec($hex);
282 // $chunkLength === 0 -> no more data
283 if ($chunkLength === 0) {
284 // clear remaining response
285 while (!$remoteFile->gets());
287 // remove chunked from transfer-encoding
288 $this->replyHeaders
['transfer-encoding'] = array_filter(array_map(function ($element) use ($chunkedTransferRegex) {
289 return $chunkedTransferRegex->replace($element, '');
290 }, $this->replyHeaders
['transfer-encoding']), 'trim');
291 if (empty($this->replyHeaders
['transfer-encoding'])) unset($this->replyHeaders
['transfer-encoding']);
293 // break out of main reading loop
298 $this->replyBody
.= $line;
299 $chunkLength -= strlen($line);
300 $bodyLength +
= strlen($line);
301 if ($chunkLength === 0) $remoteFile->read(2); // CRLF
305 $this->replyBody
.= $line;
306 $bodyLength +
= strlen($line);
309 if (isset($this->options
['maxLength']) && $bodyLength >= $this->options
['maxLength']) {
315 if (isset($this->options
['maxLength'])) $this->replyBody
= substr($this->replyBody
, 0, $this->options
['maxLength']);
317 $remoteFile->close();
323 * Parses the reply headers.
325 private function parseReplyHeaders() {
328 foreach ($this->replyHeaders
as $header) {
329 if (strpos($header, ':') === false) {
330 $headers[trim($header)] = array(trim($header));
334 // 4.2 Header fields can be
335 // extended over multiple lines by preceding each extra line with at
336 // least one SP or HT.
337 if (ltrim($header, "\t ") !== $header) {
338 $headers[$lastKey][] = array_pop($headers[$lastKey]).' '.trim($header);
341 list($key, $value) = explode(':', $header, 2);
344 if (!isset($headers[$key])) $headers[$key] = array();
345 $headers[$key][] = trim($value);
348 // 4.2 Field names are case-insensitive.
349 $this->replyHeaders
= array_change_key_case($headers);
350 if (isset($this->replyHeaders
['transfer-encoding'])) $this->replyHeaders
['transfer-encoding'] = array(implode(',', $this->replyHeaders
['transfer-encoding']));
351 $this->legacyHeaders
= array_map('end', $headers);
354 $statusLine = reset($this->replyHeaders
);
355 $regex = new Regex('^HTTP/1.\d+ +(\d{3})');
356 if (!$regex->match($statusLine[0])) throw new SystemException("Unexpected status '".$statusLine."'");
357 $matches = $regex->getMatches();
358 $this->statusCode
= $matches[1];
364 private function parseReply() {
365 // 4.4 Messages MUST NOT include both a Content-Length header field and a
366 // non-identity transfer-coding. If the message does include a non-
367 // identity transfer-coding, the Content-Length MUST be ignored.
368 if (isset($this->replyHeaders
['content-length']) && (!isset($this->replyHeaders
['transfer-encoding']) ||
strtolower(end($this->replyHeaders
['transfer-encoding'])) !== 'identity') && !isset($this->options
['maxLength'])) {
369 if (strlen($this->replyBody
) != end($this->replyHeaders
['content-length'])) {
370 throw new SystemException('Body length does not match length given in header');
374 // validate status code
375 switch ($this->statusCode
) {
381 if ($this->options
['maxDepth'] <= 0) throw new SystemException("Received status code '".$this->statusCode
."' from server, but recursion level is exhausted");
383 $newRequest = clone $this;
384 $newRequest->options
['maxDepth']--;
386 // 10.3.4 The response to the request can be found under a different URI and SHOULD
387 // be retrieved using a GET method on that resource.
388 if ($this->statusCode
== '303') {
389 $newRequest->options
['method'] = 'GET';
390 $newRequest->postParameters
= array();
391 $newRequest->addHeader('content-length', '');
392 $newRequest->addHeader('content-type', '');
396 $newRequest->setURL(end($this->replyHeaders
['location']));
398 catch (SystemException
$e) {
399 throw new SystemException("Received 'Location: ".end($this->replyHeaders
['location'])."' from server, which is invalid.", 0, $e);
403 $newRequest->execute();
405 // update data with data from the inner request
406 $this->url
= $newRequest->url
;
407 $this->statusCode
= $newRequest->statusCode
;
408 $this->replyHeaders
= $newRequest->replyHeaders
;
409 $this->replyBody
= $newRequest->replyBody
;
411 catch (SystemException
$e) {
412 // update data with data from the inner request
413 $this->url
= $newRequest->url
;
414 $this->statusCode
= $newRequest->statusCode
;
415 $this->replyHeaders
= $newRequest->replyHeaders
;
416 $this->replyBody
= $newRequest->replyBody
;
425 // check, if partial content was expected
426 if (!isset($this->headers
['range'])) {
427 throw new HTTPServerErrorException("Received unexpected status code '206' from server");
429 else if (!isset($this->replyHeaders
['content-range'])) {
430 throw new HTTPServerErrorException("Content-Range is missing in reply header");
437 throw new HTTPUnauthorizedException("Received status code '".$this->statusCode
."' from server");
441 throw new HTTPNotFoundException("Received status code '404' from server");
445 // 6.1.1 However, applications MUST
446 // understand the class of any status code, as indicated by the first
447 // digit, and treat any unrecognized response as being equivalent to the
448 // x00 status code of that class, with the exception that an
449 // unrecognized response MUST NOT be cached.
450 switch (substr($this->statusCode
, 0, 1)) {
451 case '2': // 200 and unknown 2XX
452 case '3': // 300 and unknown 3XX
455 case '5': // 500 and unknown 5XX
456 throw new HTTPServerErrorException("Received status code '".$this->statusCode
."' from server");
459 throw new SystemException("Received unhandled status code '".$this->statusCode
."' from server");
467 * Returns an array with the replied data.
468 * Note that the 'headers' element is deprecated and may be removed in the future.
472 public function getReply() {
474 'statusCode' => $this->statusCode
,
475 'headers' => $this->legacyHeaders
,
476 'httpHeaders' => $this->replyHeaders
,
477 'body' => $this->replyBody
,
483 * Sets options and applies default values when an option is omitted.
485 * @param array $options
487 private function setOptions(array $options) {
488 if (!isset($options['timeout'])) {
489 $options['timeout'] = 10;
492 if (!isset($options['method'])) {
493 $options['method'] = (!empty($this->postParameters
) ||
!empty($this->files
) ?
'POST' : 'GET');
496 if (!isset($options['maxDepth'])) {
497 $options['maxDepth'] = 2;
500 if (isset($options['auth'])) {
501 if (!isset($options['auth']['username'])) {
502 throw new SystemException('Username is missing in authentification data.');
504 if (!isset($options['auth']['password'])) {
505 throw new SystemException('Password is missing in authentification data.');
509 $this->options
= $options;
513 * Adds a header to this request.
514 * When an empty value is given existing headers of this name will be removed. When append
515 * is set to false existing values will be overwritten.
517 * @param string $name
518 * @param string $value
519 * @param boolean $append
521 public function addHeader($name, $value, $append = false) {
522 // 4.2 Field names are case-insensitive.
523 $name = strtolower($name);
526 unset($this->headers
[$name]);
530 if ($append && isset($this->headers
[$name])) {
531 $this->headers
[$name][] = $value;
534 $this->headers
[$name] = array($value);
539 * Resets reply data when cloning.
541 private function __clone() {
542 $this->replyHeaders
= array();
543 $this->replyBody
= '';
544 $this->statusCode
= 0;