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