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