Bug #29755: Apply patch from Vitaliy Filippov so that MW's HTTP client
[lhc/web/wiklou.git] / includes / HttpFunctions.php
1 <?php
2 /**
3 * @defgroup HTTP HTTP
4 */
5
6 /**
7 * Various HTTP related functions
8 * @ingroup HTTP
9 */
10 class Http {
11 static $httpEngine = false;
12
13 /**
14 * Perform an HTTP request
15 *
16 * @param $method String: HTTP method. Usually GET/POST
17 * @param $url String: full URL to act on
18 * @param $options Array: options to pass to MWHttpRequest object.
19 * Possible keys for the array:
20 * - timeout Timeout length in seconds
21 * - postData An array of key-value pairs or a url-encoded form data
22 * - proxy The proxy to use.
23 * Will use $wgHTTPProxy (if set) otherwise.
24 * - noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
25 * - sslVerifyHost (curl only) Verify hostname against certificate
26 * - sslVerifyCert (curl only) Verify SSL certificate
27 * - caInfo (curl only) Provide CA information
28 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
29 * - followRedirects Whether to follow redirects (defaults to false).
30 * Note: this should only be used when the target URL is trusted,
31 * to avoid attacks on intranet services accessible by HTTP.
32 * @return Mixed: (bool)false on failure or a string on success
33 */
34 public static function request( $method, $url, $options = array() ) {
35 $url = wfExpandUrl( $url );
36 wfDebug( "HTTP: $method: $url\n" );
37 $options['method'] = strtoupper( $method );
38
39 if ( !isset( $options['timeout'] ) ) {
40 $options['timeout'] = 'default';
41 }
42
43 $req = MWHttpRequest::factory( $url, $options );
44 $status = $req->execute();
45
46 if ( $status->isOK() ) {
47 return $req->getContent();
48 } else {
49 return false;
50 }
51 }
52
53 /**
54 * Simple wrapper for Http::request( 'GET' )
55 * @see Http::request()
56 *
57 * @return string
58 */
59 public static function get( $url, $timeout = 'default', $options = array() ) {
60 $options['timeout'] = $timeout;
61 return Http::request( 'GET', $url, $options );
62 }
63
64 /**
65 * Simple wrapper for Http::request( 'POST' )
66 * @see Http::request()
67 *
68 * @return string
69 */
70 public static function post( $url, $options = array() ) {
71 return Http::request( 'POST', $url, $options );
72 }
73
74 /**
75 * Check if the URL can be served by localhost
76 *
77 * @param $url String: full url to check
78 * @return Boolean
79 */
80 public static function isLocalURL( $url ) {
81 global $wgCommandLineMode, $wgConf;
82
83 if ( $wgCommandLineMode ) {
84 return false;
85 }
86
87 // Extract host part
88 $matches = array();
89 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
90 $host = $matches[1];
91 // Split up dotwise
92 $domainParts = explode( '.', $host );
93 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
94 $domainParts = array_reverse( $domainParts );
95
96 $domain = '';
97 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
98 $domainPart = $domainParts[$i];
99 if ( $i == 0 ) {
100 $domain = $domainPart;
101 } else {
102 $domain = $domainPart . '.' . $domain;
103 }
104
105 if ( $wgConf->isLocalVHost( $domain ) ) {
106 return true;
107 }
108 }
109 }
110
111 return false;
112 }
113
114 /**
115 * A standard user-agent we can use for external requests.
116 * @return String
117 */
118 public static function userAgent() {
119 global $wgVersion;
120 return "MediaWiki/$wgVersion";
121 }
122
123 /**
124 * Checks that the given URI is a valid one. Hardcoding the
125 * protocols, because we only want protocols that both cURL
126 * and php support.
127 *
128 * @fixme this is wildly inaccurate and fails to actually check most stuff
129 *
130 * @param $uri Mixed: URI to check for validity
131 * @returns Boolean
132 */
133 public static function isValidURI( $uri ) {
134 return preg_match(
135 '/^https?:\/\/[^\/\s]\S*$/D',
136 $uri
137 );
138 }
139 }
140
141 /**
142 * This wrapper class will call out to curl (if available) or fallback
143 * to regular PHP if necessary for handling internal HTTP requests.
144 *
145 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
146 * PHP's HTTP extension.
147 */
148 class MWHttpRequest {
149 const SUPPORTS_FILE_POSTS = false;
150
151 protected $content;
152 protected $timeout = 'default';
153 protected $headersOnly = null;
154 protected $postData = null;
155 protected $proxy = null;
156 protected $noProxy = false;
157 protected $sslVerifyHost = true;
158 protected $sslVerifyCert = true;
159 protected $caInfo = null;
160 protected $method = "GET";
161 protected $reqHeaders = array();
162 protected $url;
163 protected $parsedUrl;
164 protected $callback;
165 protected $maxRedirects = 5;
166 protected $followRedirects = false;
167
168 /**
169 * @var CookieJar
170 */
171 protected $cookieJar;
172
173 protected $headerList = array();
174 protected $respVersion = "0.9";
175 protected $respStatus = "200 Ok";
176 protected $respHeaders = array();
177
178 public $status;
179
180 /**
181 * @param $url String: url to use
182 * @param $options Array: (optional) extra params to pass (see Http::request())
183 */
184 function __construct( $url, $options = array() ) {
185 global $wgHTTPTimeout;
186
187 $this->url = $url;
188 $this->parsedUrl = parse_url( $url );
189
190 if ( !Http::isValidURI( $this->url ) ) {
191 $this->status = Status::newFatal( 'http-invalid-url' );
192 } else {
193 $this->status = Status::newGood( 100 ); // continue
194 }
195
196 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
197 $this->timeout = $options['timeout'];
198 } else {
199 $this->timeout = $wgHTTPTimeout;
200 }
201
202 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
203 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
204
205 foreach ( $members as $o ) {
206 if ( isset( $options[$o] ) ) {
207 $this->$o = $options[$o];
208 }
209 }
210 }
211
212 /**
213 * Generate a new request object
214 * @param $url String: url to use
215 * @param $options Array: (optional) extra params to pass (see Http::request())
216 * @see MWHttpRequest::__construct
217 */
218 public static function factory( $url, $options = null ) {
219 if ( !Http::$httpEngine ) {
220 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
221 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
222 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
223 ' Http::$httpEngine is set to "curl"' );
224 }
225
226 switch( Http::$httpEngine ) {
227 case 'curl':
228 return new CurlHttpRequest( $url, $options );
229 case 'php':
230 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
231 throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
232 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
233 }
234 return new PhpHttpRequest( $url, $options );
235 default:
236 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
237 }
238 }
239
240 /**
241 * Get the body, or content, of the response to the request
242 *
243 * @return String
244 */
245 public function getContent() {
246 return $this->content;
247 }
248
249 /**
250 * Set the parameters of the request
251
252 * @param $args Array
253 * @todo overload the args param
254 */
255 public function setData( $args ) {
256 $this->postData = $args;
257 }
258
259 /**
260 * Take care of setting up the proxy
261 * (override in subclass)
262 *
263 * @return String
264 */
265 public function proxySetup() {
266 global $wgHTTPProxy;
267
268 if ( $this->proxy ) {
269 return;
270 }
271
272 if ( Http::isLocalURL( $this->url ) ) {
273 $this->proxy = 'http://localhost:80/';
274 } elseif ( $wgHTTPProxy ) {
275 $this->proxy = $wgHTTPProxy ;
276 } elseif ( $this->useProxy( $this->url ) ) {
277 $this->proxy = $this->useProxy( $this->url );
278 }
279 }
280
281 /**
282 * Determine HTTP proxy from environment settings respecting
283 * 'http_proxy' and 'no_proxy' environment variables
284 */
285 public static function useProxy( $url ) {
286 if ( $proxy = getenv( "http_proxy" ) ) {
287 $useproxy = true;
288 if ( $url && ( $noproxy = preg_split( "#\s*,\s*#is", getenv( "no_proxy" ) ) ) ) {
289 foreach ( $noproxy as $n ) {
290 if ( preg_match('#(\d+)\.(\d+)\.(\d+)\.(\d+)/(\d+)#s', $n, $m) &&
291 preg_match('#^[a-z0-9_]+://(?:[^/]*:[^/]*@)?([^/@]+)(?:/|$|\?)#is', $url, $ip) ) {
292 $mask = array(
293 max( 0x100 - ( 1 << max( 8-$m[5], 0 ) ), 0 ),
294 max( 0x100 - ( 1 << max( 16-$m[5], 0 ) ), 0 ),
295 max( 0x100 - ( 1 << max( 24-$m[5], 0 ) ), 0 ),
296 max( 0x100 - ( 1 << max( 32-$m[5], 0 ) ), 0 ),
297 );
298 $ip = @gethostbyname( $ip[1] );
299 if ( preg_match( '#(\d+)\.(\d+)\.(\d+)\.(\d+)#s', $ip, $ipm ) &&
300 ( intval( $ipm[1] ) & $mask[0] ) == intval( $m[1] ) &&
301 ( intval( $ipm[2] ) & $mask[1] ) == intval( $m[2] ) &&
302 ( intval( $ipm[3] ) & $mask[2] ) == intval( $m[3] ) &&
303 ( intval( $ipm[4] ) & $mask[3] ) == intval( $m[4] ) ) {
304 $useproxy = false;
305 break;
306 }
307 } else {
308 $n = preg_replace( '/#.*$/is', '', $n );
309 $n = preg_quote( $n );
310 $n = str_replace( '\\*', '.*', $n );
311 if ( preg_match( '#'.$n.'#is', $url ) ) {
312 $useproxy = false;
313 break;
314 }
315 }
316 }
317 }
318 if ( $useproxy ) {
319 $proxy = preg_replace( '#^http://#is', '', $proxy );
320 $proxy = preg_replace( '#/*$#is', '', $proxy );
321 }
322 else {
323 $proxy = null;
324 }
325 return $proxy;
326 }
327 return null;
328 }
329
330 /**
331 * Set the refererer header
332 */
333 public function setReferer( $url ) {
334 $this->setHeader( 'Referer', $url );
335 }
336
337 /**
338 * Set the user agent
339 */
340 public function setUserAgent( $UA ) {
341 $this->setHeader( 'User-Agent', $UA );
342 }
343
344 /**
345 * Set an arbitrary header
346 */
347 public function setHeader( $name, $value ) {
348 // I feel like I should normalize the case here...
349 $this->reqHeaders[$name] = $value;
350 }
351
352 /**
353 * Get an array of the headers
354 */
355 public function getHeaderList() {
356 $list = array();
357
358 if ( $this->cookieJar ) {
359 $this->reqHeaders['Cookie'] =
360 $this->cookieJar->serializeToHttpRequest(
361 $this->parsedUrl['path'],
362 $this->parsedUrl['host']
363 );
364 }
365
366 foreach ( $this->reqHeaders as $name => $value ) {
367 $list[] = "$name: $value";
368 }
369
370 return $list;
371 }
372
373 /**
374 * Set a read callback to accept data read from the HTTP request.
375 * By default, data is appended to an internal buffer which can be
376 * retrieved through $req->getContent().
377 *
378 * To handle data as it comes in -- especially for large files that
379 * would not fit in memory -- you can instead set your own callback,
380 * in the form function($resource, $buffer) where the first parameter
381 * is the low-level resource being read (implementation specific),
382 * and the second parameter is the data buffer.
383 *
384 * You MUST return the number of bytes handled in the buffer; if fewer
385 * bytes are reported handled than were passed to you, the HTTP fetch
386 * will be aborted.
387 *
388 * @param $callback Callback
389 */
390 public function setCallback( $callback ) {
391 if ( !is_callable( $callback ) ) {
392 throw new MWException( 'Invalid MwHttpRequest callback' );
393 }
394 $this->callback = $callback;
395 }
396
397 /**
398 * A generic callback to read the body of the response from a remote
399 * server.
400 *
401 * @param $fh handle
402 * @param $content String
403 */
404 public function read( $fh, $content ) {
405 $this->content .= $content;
406 return strlen( $content );
407 }
408
409 /**
410 * Take care of whatever is necessary to perform the URI request.
411 *
412 * @return Status
413 */
414 public function execute() {
415 global $wgTitle;
416
417 $this->content = "";
418
419 if ( strtoupper( $this->method ) == "HEAD" ) {
420 $this->headersOnly = true;
421 }
422
423 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
424 $this->setReferer( $wgTitle->getFullURL() );
425 }
426
427 if ( !$this->noProxy ) {
428 $this->proxySetup();
429 }
430
431 if ( !$this->callback ) {
432 $this->setCallback( array( $this, 'read' ) );
433 }
434
435 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
436 $this->setUserAgent( Http::userAgent() );
437 }
438 }
439
440 /**
441 * Parses the headers, including the HTTP status code and any
442 * Set-Cookie headers. This function expectes the headers to be
443 * found in an array in the member variable headerList.
444 *
445 * @return nothing
446 */
447 protected function parseHeader() {
448 $lastname = "";
449
450 foreach ( $this->headerList as $header ) {
451 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
452 $this->respVersion = $match[1];
453 $this->respStatus = $match[2];
454 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
455 $last = count( $this->respHeaders[$lastname] ) - 1;
456 $this->respHeaders[$lastname][$last] .= "\r\n$header";
457 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
458 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
459 $lastname = strtolower( $match[1] );
460 }
461 }
462
463 $this->parseCookies();
464 }
465
466 /**
467 * Sets HTTPRequest status member to a fatal value with the error
468 * message if the returned integer value of the status code was
469 * not successful (< 300) or a redirect (>=300 and < 400). (see
470 * RFC2616, section 10,
471 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
472 * list of status codes.)
473 *
474 * @return nothing
475 */
476 protected function setStatus() {
477 if ( !$this->respHeaders ) {
478 $this->parseHeader();
479 }
480
481 if ( (int)$this->respStatus > 399 ) {
482 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
483 $this->status->fatal( "http-bad-status", $code, $message );
484 }
485 }
486
487 /**
488 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
489 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
490 * for a list of status codes.)
491 *
492 * @return Integer
493 */
494 public function getStatus() {
495 if ( !$this->respHeaders ) {
496 $this->parseHeader();
497 }
498
499 return (int)$this->respStatus;
500 }
501
502
503 /**
504 * Returns true if the last status code was a redirect.
505 *
506 * @return Boolean
507 */
508 public function isRedirect() {
509 if ( !$this->respHeaders ) {
510 $this->parseHeader();
511 }
512
513 $status = (int)$this->respStatus;
514
515 if ( $status >= 300 && $status <= 303 ) {
516 return true;
517 }
518
519 return false;
520 }
521
522 /**
523 * Returns an associative array of response headers after the
524 * request has been executed. Because some headers
525 * (e.g. Set-Cookie) can appear more than once the, each value of
526 * the associative array is an array of the values given.
527 *
528 * @return Array
529 */
530 public function getResponseHeaders() {
531 if ( !$this->respHeaders ) {
532 $this->parseHeader();
533 }
534
535 return $this->respHeaders;
536 }
537
538 /**
539 * Returns the value of the given response header.
540 *
541 * @param $header String
542 * @return String
543 */
544 public function getResponseHeader( $header ) {
545 if ( !$this->respHeaders ) {
546 $this->parseHeader();
547 }
548
549 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
550 $v = $this->respHeaders[strtolower ( $header ) ];
551 return $v[count( $v ) - 1];
552 }
553
554 return null;
555 }
556
557 /**
558 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
559 *
560 * @param $jar CookieJar
561 */
562 public function setCookieJar( $jar ) {
563 $this->cookieJar = $jar;
564 }
565
566 /**
567 * Returns the cookie jar in use.
568 *
569 * @returns CookieJar
570 */
571 public function getCookieJar() {
572 if ( !$this->respHeaders ) {
573 $this->parseHeader();
574 }
575
576 return $this->cookieJar;
577 }
578
579 /**
580 * Sets a cookie. Used before a request to set up any individual
581 * cookies. Used internally after a request to parse the
582 * Set-Cookie headers.
583 * @see Cookie::set
584 */
585 public function setCookie( $name, $value = null, $attr = null ) {
586 if ( !$this->cookieJar ) {
587 $this->cookieJar = new CookieJar;
588 }
589
590 $this->cookieJar->setCookie( $name, $value, $attr );
591 }
592
593 /**
594 * Parse the cookies in the response headers and store them in the cookie jar.
595 */
596 protected function parseCookies() {
597 if ( !$this->cookieJar ) {
598 $this->cookieJar = new CookieJar;
599 }
600
601 if ( isset( $this->respHeaders['set-cookie'] ) ) {
602 $url = parse_url( $this->getFinalUrl() );
603 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
604 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
605 }
606 }
607 }
608
609 /**
610 * Returns the final URL after all redirections.
611 *
612 * @return String
613 */
614 public function getFinalUrl() {
615 $location = $this->getResponseHeader( "Location" );
616
617 if ( $location ) {
618 return $location;
619 }
620
621 return $this->url;
622 }
623
624 /**
625 * Returns true if the backend can follow redirects. Overridden by the
626 * child classes.
627 */
628 public function canFollowRedirects() {
629 return true;
630 }
631 }
632
633 /**
634 * MWHttpRequest implemented using internal curl compiled into PHP
635 */
636 class CurlHttpRequest extends MWHttpRequest {
637 const SUPPORTS_FILE_POSTS = true;
638
639 static $curlMessageMap = array(
640 6 => 'http-host-unreachable',
641 28 => 'http-timed-out'
642 );
643
644 protected $curlOptions = array();
645 protected $headerText = "";
646
647 protected function readHeader( $fh, $content ) {
648 $this->headerText .= $content;
649 return strlen( $content );
650 }
651
652 public function execute() {
653 parent::execute();
654
655 if ( !$this->status->isOK() ) {
656 return $this->status;
657 }
658
659 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
660 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
661 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
662 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
663 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
664 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
665 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
666
667 /* not sure these two are actually necessary */
668 if ( isset( $this->reqHeaders['Referer'] ) ) {
669 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
670 }
671 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
672
673 if ( isset( $this->sslVerifyHost ) ) {
674 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
675 }
676
677 if ( isset( $this->sslVerifyCert ) ) {
678 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
679 }
680
681 if ( $this->caInfo ) {
682 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
683 }
684
685 if ( $this->headersOnly ) {
686 $this->curlOptions[CURLOPT_NOBODY] = true;
687 $this->curlOptions[CURLOPT_HEADER] = true;
688 } elseif ( $this->method == 'POST' ) {
689 $this->curlOptions[CURLOPT_POST] = true;
690 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
691 // Suppress 'Expect: 100-continue' header, as some servers
692 // will reject it with a 417 and Curl won't auto retry
693 // with HTTP 1.0 fallback
694 $this->reqHeaders['Expect'] = '';
695 } else {
696 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
697 }
698
699 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
700
701 $curlHandle = curl_init( $this->url );
702
703 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
704 throw new MWException( "Error setting curl options." );
705 }
706
707 if ( $this->followRedirects && $this->canFollowRedirects() ) {
708 wfSuppressWarnings();
709 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
710 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
711 "Probably safe_mode or open_basedir is set.\n" );
712 // Continue the processing. If it were in curl_setopt_array,
713 // processing would have halted on its entry
714 }
715 wfRestoreWarnings();
716 }
717
718 if ( false === curl_exec( $curlHandle ) ) {
719 $code = curl_error( $curlHandle );
720
721 if ( isset( self::$curlMessageMap[$code] ) ) {
722 $this->status->fatal( self::$curlMessageMap[$code] );
723 } else {
724 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
725 }
726 } else {
727 $this->headerList = explode( "\r\n", $this->headerText );
728 }
729
730 curl_close( $curlHandle );
731
732 $this->parseHeader();
733 $this->setStatus();
734
735 return $this->status;
736 }
737
738 public function canFollowRedirects() {
739 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
740 wfDebug( "Cannot follow redirects in safe mode\n" );
741 return false;
742 }
743
744 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
745 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
746 return false;
747 }
748
749 return true;
750 }
751 }
752
753 class PhpHttpRequest extends MWHttpRequest {
754 protected function urlToTcp( $url ) {
755 $parsedUrl = parse_url( $url );
756
757 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
758 }
759
760 public function execute() {
761 parent::execute();
762
763 if ( is_array( $this->postData ) ) {
764 $this->postData = wfArrayToCGI( $this->postData );
765 }
766
767 if ( $this->parsedUrl['scheme'] != 'http' &&
768 $this->parsedUrl['scheme'] != 'https' ) {
769 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
770 }
771
772 $this->reqHeaders['Accept'] = "*/*";
773 if ( $this->method == 'POST' ) {
774 // Required for HTTP 1.0 POSTs
775 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
776 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
777 }
778
779 $options = array();
780 if ( $this->proxy && !$this->noProxy ) {
781 $options['proxy'] = $this->urlToTCP( $this->proxy );
782 $options['request_fulluri'] = true;
783 }
784
785 if ( !$this->followRedirects ) {
786 $options['max_redirects'] = 0;
787 } else {
788 $options['max_redirects'] = $this->maxRedirects;
789 }
790
791 $options['method'] = $this->method;
792 $options['header'] = implode( "\r\n", $this->getHeaderList() );
793 // Note that at some future point we may want to support
794 // HTTP/1.1, but we'd have to write support for chunking
795 // in version of PHP < 5.3.1
796 $options['protocol_version'] = "1.0";
797
798 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
799 // Only works on 5.2.10+
800 $options['ignore_errors'] = true;
801
802 if ( $this->postData ) {
803 $options['content'] = $this->postData;
804 }
805
806 $options['timeout'] = $this->timeout;
807
808 $context = stream_context_create( array( 'http' => $options ) );
809
810 $this->headerList = array();
811 $reqCount = 0;
812 $url = $this->url;
813
814 $result = array();
815
816 do {
817 $reqCount++;
818 wfSuppressWarnings();
819 $fh = fopen( $url, "r", false, $context );
820 wfRestoreWarnings();
821
822 if ( !$fh ) {
823 break;
824 }
825
826 $result = stream_get_meta_data( $fh );
827 $this->headerList = $result['wrapper_data'];
828 $this->parseHeader();
829
830 if ( !$this->followRedirects ) {
831 break;
832 }
833
834 # Handle manual redirection
835 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
836 break;
837 }
838 # Check security of URL
839 $url = $this->getResponseHeader( "Location" );
840
841 if ( substr( $url, 0, 7 ) !== 'http://' ) {
842 wfDebug( __METHOD__ . ": insecure redirection\n" );
843 break;
844 }
845 } while ( true );
846
847 $this->setStatus();
848
849 if ( $fh === false ) {
850 $this->status->fatal( 'http-request-error' );
851 return $this->status;
852 }
853
854 if ( $result['timed_out'] ) {
855 $this->status->fatal( 'http-timed-out', $this->url );
856 return $this->status;
857 }
858
859 // If everything went OK, or we recieved some error code
860 // get the response body content.
861 if ( $this->status->isOK()
862 || (int)$this->respStatus >= 300) {
863 while ( !feof( $fh ) ) {
864 $buf = fread( $fh, 8192 );
865
866 if ( $buf === false ) {
867 $this->status->fatal( 'http-read-error' );
868 break;
869 }
870
871 if ( strlen( $buf ) ) {
872 call_user_func( $this->callback, $fh, $buf );
873 }
874 }
875 }
876 fclose( $fh );
877
878 return $this->status;
879 }
880 }