Merge "Fix fatal in LocalRepo::findFiles()"
[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 Mixed: (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 $url
89 * @param $timeout string
90 * @param $options array
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 $url
103 * @param $options array
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 Boolean
115 */
116 public static function isLocalURL( $url ) {
117 global $wgCommandLineMode, $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 in $wgConf 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 ( $wgConf->isLocalVHost( $domain ) ) {
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 $uri Mixed: URI to check for validity
170 * @return Boolean
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 $args Array
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 referrer header
355 */
356 public function setReferer( $url ) {
357 $this->setHeader( 'Referer', $url );
358 }
359
360 /**
361 * Set the user agent
362 * @param $UA string
363 */
364 public function setUserAgent( $UA ) {
365 $this->setHeader( 'User-Agent', $UA );
366 }
367
368 /**
369 * Set an arbitrary header
370 * @param $name
371 * @param $value
372 */
373 public function setHeader( $name, $value ) {
374 // I feel like I should normalize the case here...
375 $this->reqHeaders[$name] = $value;
376 }
377
378 /**
379 * Get an array of the headers
380 * @return array
381 */
382 public function getHeaderList() {
383 $list = array();
384
385 if ( $this->cookieJar ) {
386 $this->reqHeaders['Cookie'] =
387 $this->cookieJar->serializeToHttpRequest(
388 $this->parsedUrl['path'],
389 $this->parsedUrl['host']
390 );
391 }
392
393 foreach ( $this->reqHeaders as $name => $value ) {
394 $list[] = "$name: $value";
395 }
396
397 return $list;
398 }
399
400 /**
401 * Set a read callback to accept data read from the HTTP request.
402 * By default, data is appended to an internal buffer which can be
403 * retrieved through $req->getContent().
404 *
405 * To handle data as it comes in -- especially for large files that
406 * would not fit in memory -- you can instead set your own callback,
407 * in the form function($resource, $buffer) where the first parameter
408 * is the low-level resource being read (implementation specific),
409 * and the second parameter is the data buffer.
410 *
411 * You MUST return the number of bytes handled in the buffer; if fewer
412 * bytes are reported handled than were passed to you, the HTTP fetch
413 * will be aborted.
414 *
415 * @param $callback Callback
416 * @throws MWException
417 */
418 public function setCallback( $callback ) {
419 if ( !is_callable( $callback ) ) {
420 throw new MWException( 'Invalid MwHttpRequest callback' );
421 }
422 $this->callback = $callback;
423 }
424
425 /**
426 * A generic callback to read the body of the response from a remote
427 * server.
428 *
429 * @param $fh handle
430 * @param $content String
431 * @return int
432 */
433 public function read( $fh, $content ) {
434 $this->content .= $content;
435 return strlen( $content );
436 }
437
438 /**
439 * Take care of whatever is necessary to perform the URI request.
440 *
441 * @return Status
442 */
443 public function execute() {
444 global $wgTitle;
445
446 wfProfileIn( __METHOD__ );
447
448 $this->content = "";
449
450 if ( strtoupper( $this->method ) == "HEAD" ) {
451 $this->headersOnly = true;
452 }
453
454 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
455 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT ) );
456 }
457
458 $this->proxySetup(); // set up any proxy as needed
459
460 if ( !$this->callback ) {
461 $this->setCallback( array( $this, 'read' ) );
462 }
463
464 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
465 $this->setUserAgent( Http::userAgent() );
466 }
467
468 wfProfileOut( __METHOD__ );
469 }
470
471 /**
472 * Parses the headers, including the HTTP status code and any
473 * Set-Cookie headers. This function expects the headers to be
474 * found in an array in the member variable headerList.
475 */
476 protected function parseHeader() {
477 wfProfileIn( __METHOD__ );
478
479 $lastname = "";
480
481 foreach ( $this->headerList as $header ) {
482 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
483 $this->respVersion = $match[1];
484 $this->respStatus = $match[2];
485 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
486 $last = count( $this->respHeaders[$lastname] ) - 1;
487 $this->respHeaders[$lastname][$last] .= "\r\n$header";
488 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
489 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
490 $lastname = strtolower( $match[1] );
491 }
492 }
493
494 $this->parseCookies();
495
496 wfProfileOut( __METHOD__ );
497 }
498
499 /**
500 * Sets HTTPRequest status member to a fatal value with the error
501 * message if the returned integer value of the status code was
502 * not successful (< 300) or a redirect (>=300 and < 400). (see
503 * RFC2616, section 10,
504 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
505 * list of status codes.)
506 */
507 protected function setStatus() {
508 if ( !$this->respHeaders ) {
509 $this->parseHeader();
510 }
511
512 if ( (int)$this->respStatus > 399 ) {
513 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
514 $this->status->fatal( "http-bad-status", $code, $message );
515 }
516 }
517
518 /**
519 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
520 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
521 * for a list of status codes.)
522 *
523 * @return Integer
524 */
525 public function getStatus() {
526 if ( !$this->respHeaders ) {
527 $this->parseHeader();
528 }
529
530 return (int)$this->respStatus;
531 }
532
533 /**
534 * Returns true if the last status code was a redirect.
535 *
536 * @return Boolean
537 */
538 public function isRedirect() {
539 if ( !$this->respHeaders ) {
540 $this->parseHeader();
541 }
542
543 $status = (int)$this->respStatus;
544
545 if ( $status >= 300 && $status <= 303 ) {
546 return true;
547 }
548
549 return false;
550 }
551
552 /**
553 * Returns an associative array of response headers after the
554 * request has been executed. Because some headers
555 * (e.g. Set-Cookie) can appear more than once the, each value of
556 * the associative array is an array of the values given.
557 *
558 * @return Array
559 */
560 public function getResponseHeaders() {
561 if ( !$this->respHeaders ) {
562 $this->parseHeader();
563 }
564
565 return $this->respHeaders;
566 }
567
568 /**
569 * Returns the value of the given response header.
570 *
571 * @param $header String
572 * @return String
573 */
574 public function getResponseHeader( $header ) {
575 if ( !$this->respHeaders ) {
576 $this->parseHeader();
577 }
578
579 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
580 $v = $this->respHeaders[strtolower( $header )];
581 return $v[count( $v ) - 1];
582 }
583
584 return null;
585 }
586
587 /**
588 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
589 *
590 * @param $jar CookieJar
591 */
592 public function setCookieJar( $jar ) {
593 $this->cookieJar = $jar;
594 }
595
596 /**
597 * Returns the cookie jar in use.
598 *
599 * @return CookieJar
600 */
601 public function getCookieJar() {
602 if ( !$this->respHeaders ) {
603 $this->parseHeader();
604 }
605
606 return $this->cookieJar;
607 }
608
609 /**
610 * Sets a cookie. Used before a request to set up any individual
611 * cookies. Used internally after a request to parse the
612 * Set-Cookie headers.
613 * @see Cookie::set
614 * @param $name
615 * @param $value null
616 * @param $attr null
617 */
618 public function setCookie( $name, $value = null, $attr = null ) {
619 if ( !$this->cookieJar ) {
620 $this->cookieJar = new CookieJar;
621 }
622
623 $this->cookieJar->setCookie( $name, $value, $attr );
624 }
625
626 /**
627 * Parse the cookies in the response headers and store them in the cookie jar.
628 */
629 protected function parseCookies() {
630 wfProfileIn( __METHOD__ );
631
632 if ( !$this->cookieJar ) {
633 $this->cookieJar = new CookieJar;
634 }
635
636 if ( isset( $this->respHeaders['set-cookie'] ) ) {
637 $url = parse_url( $this->getFinalUrl() );
638 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
639 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
640 }
641 }
642
643 wfProfileOut( __METHOD__ );
644 }
645
646 /**
647 * Returns the final URL after all redirections.
648 *
649 * Relative values of the "Location" header are incorrect as
650 * stated in RFC, however they do happen and modern browsers
651 * support them. This function loops backwards through all
652 * locations in order to build the proper absolute URI - Marooned
653 * at wikia-inc.com
654 *
655 * Note that the multiple Location: headers are an artifact of
656 * CURL -- they shouldn't actually get returned this way. Rewrite
657 * this when bug 29232 is taken care of (high-level redirect
658 * handling rewrite).
659 *
660 * @return string
661 */
662 public function getFinalUrl() {
663 $headers = $this->getResponseHeaders();
664
665 //return full url (fix for incorrect but handled relative location)
666 if ( isset( $headers['location'] ) ) {
667 $locations = $headers['location'];
668 $domain = '';
669 $foundRelativeURI = false;
670 $countLocations = count( $locations );
671
672 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
673 $url = parse_url( $locations[$i] );
674
675 if ( isset( $url['host'] ) ) {
676 $domain = $url['scheme'] . '://' . $url['host'];
677 break; //found correct URI (with host)
678 } else {
679 $foundRelativeURI = true;
680 }
681 }
682
683 if ( $foundRelativeURI ) {
684 if ( $domain ) {
685 return $domain . $locations[$countLocations - 1];
686 } else {
687 $url = parse_url( $this->url );
688 if ( isset( $url['host'] ) ) {
689 return $url['scheme'] . '://' . $url['host'] .
690 $locations[$countLocations - 1];
691 }
692 }
693 } else {
694 return $locations[$countLocations - 1];
695 }
696 }
697
698 return $this->url;
699 }
700
701 /**
702 * Returns true if the backend can follow redirects. Overridden by the
703 * child classes.
704 * @return bool
705 */
706 public function canFollowRedirects() {
707 return true;
708 }
709 }
710
711 /**
712 * MWHttpRequest implemented using internal curl compiled into PHP
713 */
714 class CurlHttpRequest extends MWHttpRequest {
715 const SUPPORTS_FILE_POSTS = true;
716
717 protected $curlOptions = array();
718 protected $headerText = "";
719
720 /**
721 * @param $fh
722 * @param $content
723 * @return int
724 */
725 protected function readHeader( $fh, $content ) {
726 $this->headerText .= $content;
727 return strlen( $content );
728 }
729
730 public function execute() {
731 wfProfileIn( __METHOD__ );
732
733 parent::execute();
734
735 if ( !$this->status->isOK() ) {
736 wfProfileOut( __METHOD__ );
737 return $this->status;
738 }
739
740 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
741 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
742
743 // Only supported in curl >= 7.16.2
744 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
745 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
746 }
747
748 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
749 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
750 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
751 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
752 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
753
754 /* not sure these two are actually necessary */
755 if ( isset( $this->reqHeaders['Referer'] ) ) {
756 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
757 }
758 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
759
760 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
761 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
762
763 if ( $this->caInfo ) {
764 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
765 }
766
767 if ( $this->headersOnly ) {
768 $this->curlOptions[CURLOPT_NOBODY] = true;
769 $this->curlOptions[CURLOPT_HEADER] = true;
770 } elseif ( $this->method == 'POST' ) {
771 $this->curlOptions[CURLOPT_POST] = true;
772 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
773 // Suppress 'Expect: 100-continue' header, as some servers
774 // will reject it with a 417 and Curl won't auto retry
775 // with HTTP 1.0 fallback
776 $this->reqHeaders['Expect'] = '';
777 } else {
778 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
779 }
780
781 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
782
783 $curlHandle = curl_init( $this->url );
784
785 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
786 wfProfileOut( __METHOD__ );
787 throw new MWException( "Error setting curl options." );
788 }
789
790 if ( $this->followRedirects && $this->canFollowRedirects() ) {
791 wfSuppressWarnings();
792 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
793 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
794 "Probably safe_mode or open_basedir is set.\n" );
795 // Continue the processing. If it were in curl_setopt_array,
796 // processing would have halted on its entry
797 }
798 wfRestoreWarnings();
799 }
800
801 $curlRes = curl_exec( $curlHandle );
802 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
803 $this->status->fatal( 'http-timed-out', $this->url );
804 } elseif ( $curlRes === false ) {
805 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
806 } else {
807 $this->headerList = explode( "\r\n", $this->headerText );
808 }
809
810 curl_close( $curlHandle );
811
812 $this->parseHeader();
813 $this->setStatus();
814
815 wfProfileOut( __METHOD__ );
816
817 return $this->status;
818 }
819
820 /**
821 * @return bool
822 */
823 public function canFollowRedirects() {
824 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
825 wfDebug( "Cannot follow redirects in safe mode\n" );
826 return false;
827 }
828
829 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
830 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
831 return false;
832 }
833
834 return true;
835 }
836 }
837
838 class PhpHttpRequest extends MWHttpRequest {
839
840 /**
841 * @param $url string
842 * @return string
843 */
844 protected function urlToTcp( $url ) {
845 $parsedUrl = parse_url( $url );
846
847 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
848 }
849
850 public function execute() {
851 wfProfileIn( __METHOD__ );
852
853 parent::execute();
854
855 if ( is_array( $this->postData ) ) {
856 $this->postData = wfArrayToCgi( $this->postData );
857 }
858
859 if ( $this->parsedUrl['scheme'] != 'http'
860 && $this->parsedUrl['scheme'] != 'https' ) {
861 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
862 }
863
864 $this->reqHeaders['Accept'] = "*/*";
865 if ( $this->method == 'POST' ) {
866 // Required for HTTP 1.0 POSTs
867 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
868 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
869 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
870 }
871 }
872
873 $options = array();
874 if ( $this->proxy ) {
875 $options['proxy'] = $this->urlToTCP( $this->proxy );
876 $options['request_fulluri'] = true;
877 }
878
879 if ( !$this->followRedirects ) {
880 $options['max_redirects'] = 0;
881 } else {
882 $options['max_redirects'] = $this->maxRedirects;
883 }
884
885 $options['method'] = $this->method;
886 $options['header'] = implode( "\r\n", $this->getHeaderList() );
887 // Note that at some future point we may want to support
888 // HTTP/1.1, but we'd have to write support for chunking
889 // in version of PHP < 5.3.1
890 $options['protocol_version'] = "1.0";
891
892 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
893 // Only works on 5.2.10+
894 $options['ignore_errors'] = true;
895
896 if ( $this->postData ) {
897 $options['content'] = $this->postData;
898 }
899
900 $options['timeout'] = $this->timeout;
901
902 if ( $this->sslVerifyHost ) {
903 $options['CN_match'] = $this->parsedUrl['host'];
904 }
905 if ( $this->sslVerifyCert ) {
906 $options['verify_peer'] = true;
907 }
908
909 if ( is_dir( $this->caInfo ) ) {
910 $options['capath'] = $this->caInfo;
911 } elseif ( is_file( $this->caInfo ) ) {
912 $options['cafile'] = $this->caInfo;
913 } elseif ( $this->caInfo ) {
914 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
915 }
916
917 $scheme = $this->parsedUrl['scheme'];
918 $context = stream_context_create( array( "$scheme" => $options ) );
919
920 $this->headerList = array();
921 $reqCount = 0;
922 $url = $this->url;
923
924 $result = array();
925
926 do {
927 $reqCount++;
928 wfSuppressWarnings();
929 $fh = fopen( $url, "r", false, $context );
930 wfRestoreWarnings();
931
932 if ( !$fh ) {
933 break;
934 }
935
936 $result = stream_get_meta_data( $fh );
937 $this->headerList = $result['wrapper_data'];
938 $this->parseHeader();
939
940 if ( !$this->followRedirects ) {
941 break;
942 }
943
944 # Handle manual redirection
945 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
946 break;
947 }
948 # Check security of URL
949 $url = $this->getResponseHeader( "Location" );
950
951 if ( !Http::isValidURI( $url ) ) {
952 wfDebug( __METHOD__ . ": insecure redirection\n" );
953 break;
954 }
955 } while ( true );
956
957 $this->setStatus();
958
959 if ( $fh === false ) {
960 $this->status->fatal( 'http-request-error' );
961 wfProfileOut( __METHOD__ );
962 return $this->status;
963 }
964
965 if ( $result['timed_out'] ) {
966 $this->status->fatal( 'http-timed-out', $this->url );
967 wfProfileOut( __METHOD__ );
968 return $this->status;
969 }
970
971 // If everything went OK, or we received some error code
972 // get the response body content.
973 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
974 while ( !feof( $fh ) ) {
975 $buf = fread( $fh, 8192 );
976
977 if ( $buf === false ) {
978 $this->status->fatal( 'http-read-error' );
979 break;
980 }
981
982 if ( strlen( $buf ) ) {
983 call_user_func( $this->callback, $fh, $buf );
984 }
985 }
986 }
987 fclose( $fh );
988
989 wfProfileOut( __METHOD__ );
990
991 return $this->status;
992 }
993 }