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