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