summaryrefslogtreecommitdiff
path: root/includes/HttpFunctions.php
blob: d59836356e0ea3971ce9f473fe114c6d0cbeafec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
<?php
/**
 * @defgroup HTTP HTTP
 */

/**
 * Various HTTP related functions
 * @ingroup HTTP
 */
class Http {
	static $httpEngine = false;

	/**
	 * Perform an HTTP request
	 * @param $method string HTTP method. Usually GET/POST
	 * @param $url string Full URL to act on
	 * @param $options options to pass to HttpRequest object
	 *				 Possible keys for the array:
	 *					timeout			  Timeout length in seconds
	 *					postData		  An array of key-value pairs or a url-encoded form data
	 *					proxy			  The proxy to use.	 Will use $wgHTTPProxy (if set) otherwise.
	 *					noProxy			  Override $wgHTTPProxy (if set) and don't use any proxy at all.
	 *					sslVerifyHost	  (curl only) Verify the SSL certificate
	 *					caInfo			  (curl only) Provide CA information
	 *					maxRedirects	  Maximum number of redirects to follow (defaults to 5)
	 *					followRedirects	  Whether to follow redirects (defaults to true)
	 * @returns mixed (bool)false on failure or a string on success
	 */
	public static function request( $method, $url, $options = array() ) {
		wfDebug( "HTTP: $method: $url" );
		$options['method'] = strtoupper( $method );
		if ( !isset( $options['timeout'] ) ) {
			$options['timeout'] = 'default';
		}
		$req = HttpRequest::factory( $url, $options );
		$status = $req->execute();
		if ( $status->isOK() ) {
			return $req->getContent();
		} else {
			return false;
		}
	}

	/**
	 * Simple wrapper for Http::request( 'GET' )
	 * @see Http::request()
	 */
	public static function get( $url, $timeout = 'default', $options = array() ) {
		$options['timeout'] = $timeout;
		return Http::request( 'GET', $url, $options );
	}

	/**
	 * Simple wrapper for Http::request( 'POST' )
	 * @see Http::request()
	 */
	public static function post( $url, $options = array() ) {
		return Http::request( 'POST', $url, $options );
	}

	/**
	 * Check if the URL can be served by localhost
	 * @param $url string Full url to check
	 * @return bool
	 */
	public static function isLocalURL( $url ) {
		global $wgCommandLineMode, $wgConf;
		if ( $wgCommandLineMode ) {
			return false;
		}

		// Extract host part
		$matches = array();
		if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
			$host = $matches[1];
			// Split up dotwise
			$domainParts = explode( '.', $host );
			// Check if this domain or any superdomain is listed in $wgConf as a local virtual host
			$domainParts = array_reverse( $domainParts );
			for ( $i = 0; $i < count( $domainParts ); $i++ ) {
				$domainPart = $domainParts[$i];
				if ( $i == 0 ) {
					$domain = $domainPart;
				} else {
					$domain = $domainPart . '.' . $domain;
				}
				if ( $wgConf->isLocalVHost( $domain ) ) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * A standard user-agent we can use for external requests.
	 * @returns string
	 */
	public static function userAgent() {
		global $wgVersion;
		return "MediaWiki/$wgVersion";
	}

	/**
	 * Checks that the given URI is a valid one
	 * @param $uri Mixed: URI to check for validity
	 * @returns bool
	 */
	public static function isValidURI( $uri ) {
		return preg_match(
			'/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
			$uri,
			$matches
		);
	}
}

/**
 * This wrapper class will call out to curl (if available) or fallback
 * to regular PHP if necessary for handling internal HTTP requests.
 */
class HttpRequest {
	protected $content;
	protected $timeout = 'default';
	protected $headersOnly = null;
	protected $postData = null;
	protected $proxy = null;
	protected $noProxy = false;
	protected $sslVerifyHost = true;
	protected $caInfo = null;
	protected $method = "GET";
	protected $reqHeaders = array();
	protected $url;
	protected $parsedUrl;
	protected $callback;
	protected $maxRedirects = 5;
	protected $followRedirects = true;

	protected $cookieJar;

	protected $headerList = array();
	protected $respVersion = "0.9";
	protected $respStatus = "200 Ok";
	protected $respHeaders = array();

	public $status;

	/**
	 * @param $url	 string url to use
	 * @param $options array (optional) extra params to pass (see Http::request())
	 */
	function __construct( $url, $options = array() ) {
		global $wgHTTPTimeout;

		$this->url = $url;
		$this->parsedUrl = parse_url( $url );

		if ( !Http::isValidURI( $this->url ) ) {
			$this->status = Status::newFatal('http-invalid-url');
		} else {
			$this->status = Status::newGood( 100 ); // continue
		}

		if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
			$this->timeout = $options['timeout'];
		} else {
			$this->timeout = $wgHTTPTimeout;
		}

		$members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
						  "method", "followRedirects", "maxRedirects" );
		foreach ( $members as $o ) {
			if ( isset($options[$o]) ) {
				$this->$o = $options[$o];
			}
		}
	}

	/**
	 * Generate a new request object
	 * @see HttpRequest::__construct
	 */
	public static function factory( $url, $options = null ) {
		if ( !Http::$httpEngine ) {
			Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
		} elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
			throw new MWException( __METHOD__.': curl (http://php.net/curl) is not installed, but'.
								   ' Http::$httpEngine is set to "curl"' );
		}

		switch( Http::$httpEngine ) {
		case 'curl':
			return new CurlHttpRequest( $url, $options );
		case 'php':
			if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
				throw new MWException( __METHOD__.': allow_url_fopen needs to be enabled for pure PHP'.
					' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
			}
			return new PhpHttpRequest( $url, $options );
		default:
			throw new MWException( __METHOD__.': The setting of Http::$httpEngine is not valid.' );
		}
	}

	/**
	 * Get the body, or content, of the response to the request
	 * @return string
	 */
	public function getContent() {
		return $this->content;
	}

	/**
	 * Take care of setting up the proxy
	 * (override in subclass)
	 * @return string
	 */
	public function proxySetup() {
		global $wgHTTPProxy;

		if ( $this->proxy ) {
			return;
		}
		if ( Http::isLocalURL( $this->url ) ) {
			$this->proxy = 'http://localhost:80/';
		} elseif ( $wgHTTPProxy ) {
			$this->proxy = $wgHTTPProxy ;
		} elseif ( getenv( "http_proxy" ) ) {
			$this->proxy = getenv( "http_proxy" );
		}
	}

	/**
	 * Set the refererer header
	 */
	public function setReferer( $url ) {
		$this->setHeader('Referer', $url);
	}

	/**
	 * Set the user agent
	 */
	public function setUserAgent( $UA ) {
		$this->setHeader('User-Agent', $UA);
	}

	/**
	 * Set an arbitrary header
	 */
	public function setHeader($name, $value) {
		// I feel like I should normalize the case here...
		$this->reqHeaders[$name] = $value;
	}

	/**
	 * Get an array of the headers
	 */
	public function getHeaderList() {
		$list = array();

		if( $this->cookieJar ) {
			$this->reqHeaders['Cookie'] =
				$this->cookieJar->serializeToHttpRequest($this->parsedUrl['path'],
														 $this->parsedUrl['host']);
		}
		foreach($this->reqHeaders as $name => $value) {
			$list[] = "$name: $value";
		}
		return $list;
	}

	/**
	 * Set the callback
	 * @param $callback callback
	 */
	public function setCallback( $callback ) {
		$this->callback = $callback;
	}

	/**
	 * A generic callback to read the body of the response from a remote
	 * server.
	 * @param $fh handle
	 * @param $content string
	 */
	public function read( $fh, $content ) {
		$this->content .= $content;
		return strlen( $content );
	}

	/**
	 * Take care of whatever is necessary to perform the URI request.
	 * @return Status
	 */
	public function execute() {
		global $wgTitle;

		if( strtoupper($this->method) == "HEAD" ) {
			$this->headersOnly = true;
		}

		if ( is_array( $this->postData ) ) {
			$this->postData = wfArrayToCGI( $this->postData );
		}

		if ( is_object( $wgTitle ) && !isset($this->reqHeaders['Referer']) ) {
			$this->setReferer( $wgTitle->getFullURL() );
		}

		if ( !$this->noProxy ) {
			$this->proxySetup();
		}

		if ( !$this->callback ) {
			$this->setCallback( array( $this, 'read' ) );
		}

		if ( !isset($this->reqHeaders['User-Agent']) ) {
			$this->setUserAgent(Http::userAgent());
		}
	}

	/**
	 * Parses the headers, including the HTTP status code and any
	 * Set-Cookie headers.  This function expectes the headers to be
	 * found in an array in the member variable headerList.
	 * @returns nothing
	 */
	protected function parseHeader() {
		$lastname = "";
		foreach( $this->headerList as $header ) {
			if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
				$this->respVersion = $match[1];
				$this->respStatus = $match[2];
			} elseif( preg_match( "#^[ \t]#", $header ) ) {
				$last = count($this->respHeaders[$lastname]) - 1;
				$this->respHeaders[$lastname][$last] .= "\r\n$header";
			} elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
				$this->respHeaders[strtolower( $match[1] )][] = $match[2];
				$lastname = strtolower( $match[1] );
			}
		}

		$this->parseCookies();
	}

	/**
	 * Sets the member variable status to a fatal status if the HTTP
	 * status code was not 200.
	 * @returns nothing
	 */
	protected function setStatus() {
		if( !$this->respHeaders ) {
			$this->parseHeader();
		}

		if((int)$this->respStatus !== 200) {
			list( $code, $message ) = explode(" ", $this->respStatus, 2);
			$this->status->fatal("http-bad-status", $code, $message );
		}
	}


	/**
	 * Returns true if the last status code was a redirect.
	 * @return bool
	 */
	public function isRedirect() {
		if( !$this->respHeaders ) {
			$this->parseHeader();
		}

		$status = (int)$this->respStatus;
		if ( $status >= 300 && $status < 400 ) {
			return true;
		}
		return false;
	}

	/**
	 * Returns an associative array of response headers after the
	 * request has been executed.  Because some headers
	 * (e.g. Set-Cookie) can appear more than once the, each value of
	 * the associative array is an array of the values given.
	 * @return array
	 */
	public function getResponseHeaders() {
		if( !$this->respHeaders ) {
			$this->parseHeader();
		}
		return $this->respHeaders;
	}

	/**
	 * Returns the value of the given response header.
	 * @param $header string
	 * @return string
	 */
	public function getResponseHeader($header) {
		if( !$this->respHeaders ) {
			$this->parseHeader();
		}
		if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
			$v = $this->respHeaders[strtolower ( $header ) ];
			return $v[count( $v ) - 1];
		}
		return null;
	}

	/**
	 * Tells the HttpRequest object to use this pre-loaded CookieJar.
	 * @param $jar CookieJar
	 */
	public function setCookieJar( $jar ) {
		$this->cookieJar = $jar;
	}

	/**
	 * Returns the cookie jar in use.
	 * @returns CookieJar
	 */
	public function getCookieJar() {
		if( !$this->respHeaders ) {
			$this->parseHeader();
		}
		return $this->cookieJar;
	}

	/**
	 * Sets a cookie.  Used before a request to set up any individual
	 * cookies.	 Used internally after a request to parse the
	 * Set-Cookie headers.
	 * @see Cookie::set
	 */
	public function setCookie( $name, $value = null, $attr = null) {
		if( !$this->cookieJar ) {
			$this->cookieJar = new CookieJar;
		}
		$this->cookieJar->setCookie($name, $value, $attr);
	}

	/**
	 * Parse the cookies in the response headers and store them in the cookie jar.
	 */
	protected function parseCookies() {
		if( !$this->cookieJar ) {
			$this->cookieJar = new CookieJar;
		}
		if( isset( $this->respHeaders['set-cookie'] ) ) {
			$url = parse_url( $this->getFinalUrl() );
			foreach( $this->respHeaders['set-cookie'] as $cookie ) {
				$this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
			}
		}
	}

	/**
	 * Returns the final URL after all redirections.
	 * @returns string
	 */
	public function getFinalUrl() {
		$location = $this->getResponseHeader("Location");
		if ( $location ) {
			return $location;
		}

		return $this->url;
	}
}


class Cookie {
	protected $name;
	protected $value;
	protected $expires;
	protected $path;
	protected $domain;
	protected $isSessionKey = true;
	// TO IMPLEMENT	 protected $secure
	// TO IMPLEMENT? protected $maxAge (add onto expires)
	// TO IMPLEMENT? protected $version
	// TO IMPLEMENT? protected $comment

	function __construct( $name, $value, $attr ) {
		$this->name = $name;
		$this->set( $value, $attr );
	}

	/**
	 * Sets a cookie.  Used before a request to set up any individual
	 * cookies.	 Used internally after a request to parse the
	 * Set-Cookie headers.
	 * @param $name string the name of the cookie
	 * @param $value string the value of the cookie
	 * @param $attr array possible key/values:
	 *		expires	 A date string
	 *		path	 The path this cookie is used on
	 *		domain	 Domain this cookie is used on
	 */
	public function set( $value, $attr ) {
		$this->value = $value;
		if( isset( $attr['expires'] ) ) {
			$this->isSessionKey = false;
			$this->expires = strtotime( $attr['expires'] );
		}
		if( isset( $attr['path'] ) ) {
			$this->path = $attr['path'];
		} else {
			$this->path = "/";
		}
		if( isset( $attr['domain'] ) ) {
			if( self::validateCookieDomain( $attr['domain'] ) ) {
				$this->domain = $attr['domain'];
			}
		} else {
			throw new MWException("You must specify a domain.");
		}
	}

	/**
	 * Return the true if the cookie is valid is valid.  Otherwise,
	 * false.  The uses a method similar to IE cookie security
	 * described here:
	 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
	 * A better method might be to use a blacklist like
	 * http://publicsuffix.org/
	 *
	 * @param $domain string the domain to validate
	 * @param $originDomain string (optional) the domain the cookie originates from
	 * @return bool
	 */
	public static function validateCookieDomain( $domain, $originDomain = null) {
		// Don't allow a trailing dot
		if( substr( $domain, -1 ) == "." ) return false;

		$dc = explode(".", $domain);

		// Don't allow cookies for "localhost", "ls" or other dot-less hosts
		if( count($dc) < 2 ) return false;

		// Only allow full, valid IP addresses
		if( preg_match( '/^[0-9.]+$/', $domain ) ) {
			if( count( $dc ) != 4 ) return false;

			if( ip2long( $domain ) === false ) return false;

			if( $originDomain == null || $originDomain == $domain ) return true;

		}

		// Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
		if( strrpos( $domain, "." ) - strlen( $domain )  == -3 ) {
			if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
				|| (count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
				return false;
			}
			if( (count($dc) == 2 || (count($dc) == 3 && $dc[0] == "") )
				&& preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
				return false;
			}
		}

		if( $originDomain != null ) {
			if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
				return false;
			}
			if( substr( $domain, 0, 1 ) == "."
				&& substr_compare( $originDomain, $domain, -strlen( $domain ),
								   strlen( $domain ), TRUE ) != 0 ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Serialize the cookie jar into a format useful for HTTP Request headers.
	 * @param $path string the path that will be used. Required.
	 * @param $domain string the domain that will be used. Required.
	 * @return string
	 */
	public function serializeToHttpRequest( $path, $domain ) {
		$ret = "";

		if( $this->canServeDomain( $domain )
				&& $this->canServePath( $path )
				&& $this->isUnExpired() ) {
			$ret = $this->name ."=". $this->value;
		}

		return $ret;
	}

	protected function canServeDomain( $domain ) {
		if( $domain == $this->domain
			|| ( strlen( $domain) > strlen( $this->domain )
				 && substr( $this->domain, 0, 1) == "."
				 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
									strlen( $this->domain ), TRUE ) == 0 ) ) {
			return true;
		}
		return false;
	}

	protected function canServePath( $path ) {
		if( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
			return true;
		}
		return false;
	}

	protected function isUnExpired() {
		if( $this->isSessionKey || $this->expires > time() ) {
			return true;
		}
		return false;
	}

}

class CookieJar {
	private $cookie = array();

	/**
	 * Set a cookie in the cookie jar.	Make sure only one cookie per-name exists.
	 * @see Cookie::set()
	 */
	public function setCookie ($name, $value, $attr) {
		/* cookies: case insensitive, so this should work.
		 * We'll still send the cookies back in the same case we got them, though.
		 */
		$index = strtoupper($name);
		if( isset( $this->cookie[$index] ) ) {
			$this->cookie[$index]->set( $value, $attr );
		} else {
			$this->cookie[$index] = new Cookie( $name, $value, $attr );
		}
	}

	/**
	 * @see Cookie::serializeToHttpRequest
	 */
	public function serializeToHttpRequest( $path, $domain ) {
		$cookies = array();

		foreach( $this->cookie as $c ) {
			$serialized = $c->serializeToHttpRequest( $path, $domain );
			if ( $serialized ) $cookies[] = $serialized;
		}

		return implode("; ", $cookies);
	}

	/**
	 * Parse the content of an Set-Cookie HTTP Response header.
	 * @param $cookie string
	 */
	public function parseCookieResponseHeader ( $cookie, $domain ) {
		$len = strlen( "Set-Cookie:" );
		if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
			$cookie = substr( $cookie, $len );
		}

		$bit = array_map( 'trim', explode( ";", $cookie ) );
		if ( count($bit) >= 1 ) {
			list($name, $value) = explode( "=", array_shift( $bit ), 2 );
			$attr = array();
			foreach( $bit as $piece ) {
				$parts = explode( "=", $piece );
				if( count( $parts ) > 1 ) {
					$attr[strtolower( $parts[0] )] = $parts[1];
				} else {
					$attr[strtolower( $parts[0] )] = true;
				}
			}

			if( !isset( $attr['domain'] ) ) {
				$attr['domain'] = $domain;
			} elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
				return null;
			}

			$this->setCookie( $name, $value, $attr );
		}
	}
}


/**
 * HttpRequest implemented using internal curl compiled into PHP
 */
class CurlHttpRequest extends HttpRequest {
	static $curlMessageMap = array(
		6 => 'http-host-unreachable',
		28 => 'http-timed-out'
	);

	protected $curlOptions = array();
	protected $headerText = "";

	protected function readHeader( $fh, $content ) {
		$this->headerText .= $content;
		return strlen( $content );
	}

	public function execute() {
		parent::execute();
		if ( !$this->status->isOK() ) {
			return $this->status;
		}
		$this->curlOptions[CURLOPT_PROXY] = $this->proxy;
		$this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
		$this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
		$this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
		$this->curlOptions[CURLOPT_HEADERFUNCTION] = array($this, "readHeader");
		$this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;

		/* not sure these two are actually necessary */
		if(isset($this->reqHeaders['Referer'])) {
			$this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
		}
		$this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];

		if ( $this->sslVerifyHost ) {
			$this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
		}

		if ( $this->caInfo ) {
			$this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
		}

		if ( $this->headersOnly ) {
			$this->curlOptions[CURLOPT_NOBODY] = true;
			$this->curlOptions[CURLOPT_HEADER] = true;
		} elseif ( $this->method == 'POST' ) {
			$this->curlOptions[CURLOPT_POST] = true;
			$this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
			// Suppress 'Expect: 100-continue' header, as some servers
			// will reject it with a 417 and Curl won't auto retry
			// with HTTP 1.0 fallback
			$this->reqHeaders['Expect'] = '';
		} else {
			$this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
		}

		$this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();

		$curlHandle = curl_init( $this->url );
		if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
			throw new MWException("Error setting curl options.");
		}
		if ( ! @curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, $this->followRedirects ) ) {
			wfDebug("Couldn't set CURLOPT_FOLLOWLOCATION. Probably safe_mode or open_basedir is set.");
			/* Continue the processing. If it were in curl_setopt_array, processing would have halted on its entry */
		}

		if ( false === curl_exec( $curlHandle ) ) {
			$code = curl_error( $curlHandle );

			if ( isset( self::$curlMessageMap[$code] ) ) {
				$this->status->fatal( self::$curlMessageMap[$code] );
			} else {
				$this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
			}
		} else {
			$this->headerList = explode("\r\n", $this->headerText);
		}

		curl_close( $curlHandle );

		$this->parseHeader();
		$this->setStatus();
		return $this->status;
	}
}

class PhpHttpRequest extends HttpRequest {
	protected $manuallyRedirect = false;

	protected function urlToTcp( $url ) {
		$parsedUrl = parse_url( $url );

		return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
	}

	public function execute() {
		parent::execute();

		// At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
		// causes a segfault
		if ( version_compare( '5.1.7', phpversion(), '>' ) ) {
			$this->manuallyRedirect = true;
		}

		if ( $this->parsedUrl['scheme'] != 'http' ) {
			$this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
		}

		$this->reqHeaders['Accept'] = "*/*";
		if ( $this->method == 'POST' ) {
			// Required for HTTP 1.0 POSTs
			$this->reqHeaders['Content-Length'] = strlen( $this->postData );
			$this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
		}

		$options = array();
		if ( $this->proxy && !$this->noProxy ) {
			$options['proxy'] = $this->urlToTCP( $this->proxy );
			$options['request_fulluri'] = true;
		}

		if ( !$this->followRedirects || $this->manuallyRedirect ) {
			$options['max_redirects'] = 0;
		} else {
			$options['max_redirects'] = $this->maxRedirects;
		}

		$options['method'] = $this->method;
		$options['header'] = implode("\r\n", $this->getHeaderList());
		// Note that at some future point we may want to support
		// HTTP/1.1, but we'd have to write support for chunking
		// in version of PHP < 5.3.1
		$options['protocol_version'] = "1.0";

		// This is how we tell PHP we want to deal with 404s (for example) ourselves.
		// Only works on 5.2.10+
		$options['ignore_errors'] = true;

		if ( $this->postData ) {
			$options['content'] = $this->postData;
		}

		$oldTimeout = false;
		if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
			$oldTimeout = ini_set('default_socket_timeout', $this->timeout);
		} else {
			$options['timeout'] = $this->timeout;
		}

		$context = stream_context_create( array( 'http' => $options ) );

		$this->headerList = array();
		$reqCount = 0;
		$url = $this->url;
		do {
			$again = false;
			$reqCount++;
			wfSuppressWarnings();
			$fh = fopen( $url, "r", false, $context );
			wfRestoreWarnings();
			if ( $fh ) {
				$result = stream_get_meta_data( $fh );
				$this->headerList = $result['wrapper_data'];
				$this->parseHeader();
				$url = $this->getResponseHeader("Location");
				$again = $this->manuallyRedirect && $this->followRedirects && $url
					&& $this->isRedirect() && $this->maxRedirects > $reqCount;
			}
		} while ( $again );

		if ( $oldTimeout !== false ) {
			ini_set('default_socket_timeout', $oldTimeout);
		}
		$this->setStatus();

		if ( $fh === false ) {
			$this->status->fatal( 'http-request-error' );
			return $this->status;
		}

		if ( $result['timed_out'] ) {
			$this->status->fatal( 'http-timed-out', $this->url );
			return $this->status;
		}

		if($this->status->isOK()) {
			while ( !feof( $fh ) ) {
				$buf = fread( $fh, 8192 );
				if ( $buf === false ) {
					$this->status->fatal( 'http-read-error' );
					break;
				}
				if ( strlen( $buf ) ) {
					call_user_func( $this->callback, $fh, $buf );
				}
			}
		}
		fclose( $fh );

		return $this->status;
	}
}