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