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