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