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