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