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