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