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