MediaWiki  1.27.0
HttpFunctions.php
Go to the documentation of this file.
1 <?php
29 
34 class Http {
35  static public $httpEngine = false;
36 
63  public static function request( $method, $url, $options = [], $caller = __METHOD__ ) {
64  wfDebug( "HTTP: $method: $url\n" );
65 
66  $options['method'] = strtoupper( $method );
67 
68  if ( !isset( $options['timeout'] ) ) {
69  $options['timeout'] = 'default';
70  }
71  if ( !isset( $options['connectTimeout'] ) ) {
72  $options['connectTimeout'] = 'default';
73  }
74 
75  $req = MWHttpRequest::factory( $url, $options, $caller );
76  $status = $req->execute();
77 
78  if ( $status->isOK() ) {
79  return $req->getContent();
80  } else {
81  $errors = $status->getErrorsByType( 'error' );
82  $logger = LoggerFactory::getInstance( 'http' );
83  $logger->warning( $status->getWikiText( false, false, 'en' ),
84  [ 'error' => $errors, 'caller' => $caller, 'content' => $req->getContent() ] );
85  return false;
86  }
87  }
88 
100  public static function get( $url, $options = [], $caller = __METHOD__ ) {
101  $args = func_get_args();
102  if ( isset( $args[1] ) && ( is_string( $args[1] ) || is_numeric( $args[1] ) ) ) {
103  // Second was used to be the timeout
104  // And third parameter used to be $options
105  wfWarn( "Second parameter should not be a timeout.", 2 );
106  $options = isset( $args[2] ) && is_array( $args[2] ) ?
107  $args[2] : [];
108  $options['timeout'] = $args[1];
109  $caller = __METHOD__;
110  }
111  return Http::request( 'GET', $url, $options, $caller );
112  }
113 
123  public static function post( $url, $options = [], $caller = __METHOD__ ) {
124  return Http::request( 'POST', $url, $options, $caller );
125  }
126 
133  public static function isLocalURL( $url ) {
134  global $wgCommandLineMode, $wgLocalVirtualHosts;
135 
136  if ( $wgCommandLineMode ) {
137  return false;
138  }
139 
140  // Extract host part
141  $matches = [];
142  if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
143  $host = $matches[1];
144  // Split up dotwise
145  $domainParts = explode( '.', $host );
146  // Check if this domain or any superdomain is listed as a local virtual host
147  $domainParts = array_reverse( $domainParts );
148 
149  $domain = '';
150  $countParts = count( $domainParts );
151  for ( $i = 0; $i < $countParts; $i++ ) {
152  $domainPart = $domainParts[$i];
153  if ( $i == 0 ) {
154  $domain = $domainPart;
155  } else {
156  $domain = $domainPart . '.' . $domain;
157  }
158 
159  if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
160  return true;
161  }
162  }
163  }
164 
165  return false;
166  }
167 
172  public static function userAgent() {
174  return "MediaWiki/$wgVersion";
175  }
176 
189  public static function isValidURI( $uri ) {
190  return preg_match(
191  '/^https?:\/\/[^\/\s]\S*$/D',
192  $uri
193  );
194  }
195 
201  public static function getProxy() {
202  global $wgHTTPProxy;
203 
204  if ( $wgHTTPProxy ) {
205  return $wgHTTPProxy;
206  }
207 
208  $envHttpProxy = getenv( "http_proxy" );
209  if ( $envHttpProxy ) {
210  return $envHttpProxy;
211  }
212 
213  return "";
214  }
215 }
216 
225  const SUPPORTS_FILE_POSTS = false;
226 
227  protected $content;
228  protected $timeout = 'default';
229  protected $headersOnly = null;
230  protected $postData = null;
231  protected $proxy = null;
232  protected $noProxy = false;
233  protected $sslVerifyHost = true;
234  protected $sslVerifyCert = true;
235  protected $caInfo = null;
236  protected $method = "GET";
237  protected $reqHeaders = [];
238  protected $url;
239  protected $parsedUrl;
240  protected $callback;
241  protected $maxRedirects = 5;
242  protected $followRedirects = false;
243 
247  protected $cookieJar;
248 
249  protected $headerList = [];
250  protected $respVersion = "0.9";
251  protected $respStatus = "200 Ok";
252  protected $respHeaders = [];
253 
254  public $status;
255 
259  protected $profiler;
260 
264  protected $profileName;
265 
272  protected function __construct(
273  $url, $options = [], $caller = __METHOD__, $profiler = null
274  ) {
275  global $wgHTTPTimeout, $wgHTTPConnectTimeout;
276 
277  $this->url = wfExpandUrl( $url, PROTO_HTTP );
278  $this->parsedUrl = wfParseUrl( $this->url );
279 
280  if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
281  $this->status = Status::newFatal( 'http-invalid-url', $url );
282  } else {
283  $this->status = Status::newGood( 100 ); // continue
284  }
285 
286  if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
287  $this->timeout = $options['timeout'];
288  } else {
289  $this->timeout = $wgHTTPTimeout;
290  }
291  if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
292  $this->connectTimeout = $options['connectTimeout'];
293  } else {
294  $this->connectTimeout = $wgHTTPConnectTimeout;
295  }
296  if ( isset( $options['userAgent'] ) ) {
297  $this->setUserAgent( $options['userAgent'] );
298  }
299 
300  $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
301  "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
302 
303  foreach ( $members as $o ) {
304  if ( isset( $options[$o] ) ) {
305  // ensure that MWHttpRequest::method is always
306  // uppercased. Bug 36137
307  if ( $o == 'method' ) {
308  $options[$o] = strtoupper( $options[$o] );
309  }
310  $this->$o = $options[$o];
311  }
312  }
313 
314  if ( $this->noProxy ) {
315  $this->proxy = ''; // noProxy takes precedence
316  }
317 
318  // Profile based on what's calling us
319  $this->profiler = $profiler;
320  $this->profileName = $caller;
321  }
322 
328  public static function canMakeRequests() {
329  return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
330  }
331 
341  public static function factory( $url, $options = null, $caller = __METHOD__ ) {
342  if ( !Http::$httpEngine ) {
343  Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
344  } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
345  throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
346  ' Http::$httpEngine is set to "curl"' );
347  }
348 
349  switch ( Http::$httpEngine ) {
350  case 'curl':
351  return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
352  case 'php':
353  if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
354  throw new MWException( __METHOD__ . ': allow_url_fopen ' .
355  'needs to be enabled for pure PHP http requests to ' .
356  'work. If possible, curl should be used instead. See ' .
357  'http://php.net/curl.'
358  );
359  }
360  return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
361  default:
362  throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
363  }
364  }
365 
371  public function getContent() {
372  return $this->content;
373  }
374 
381  public function setData( $args ) {
382  $this->postData = $args;
383  }
384 
390  public function proxySetup() {
391  // If there is an explicit proxy set and proxies are not disabled, then use it
392  if ( $this->proxy && !$this->noProxy ) {
393  return;
394  }
395 
396  // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
397  // local URL and proxies are not disabled
398  if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
399  $this->proxy = '';
400  } else {
401  $this->proxy = Http::getProxy();
402  }
403  }
404 
409  public function setUserAgent( $UA ) {
410  $this->setHeader( 'User-Agent', $UA );
411  }
412 
418  public function setHeader( $name, $value ) {
419  // I feel like I should normalize the case here...
420  $this->reqHeaders[$name] = $value;
421  }
422 
427  public function getHeaderList() {
428  $list = [];
429 
430  if ( $this->cookieJar ) {
431  $this->reqHeaders['Cookie'] =
432  $this->cookieJar->serializeToHttpRequest(
433  $this->parsedUrl['path'],
434  $this->parsedUrl['host']
435  );
436  }
437 
438  foreach ( $this->reqHeaders as $name => $value ) {
439  $list[] = "$name: $value";
440  }
441 
442  return $list;
443  }
444 
463  public function setCallback( $callback ) {
464  if ( !is_callable( $callback ) ) {
465  throw new MWException( 'Invalid MwHttpRequest callback' );
466  }
467  $this->callback = $callback;
468  }
469 
478  public function read( $fh, $content ) {
479  $this->content .= $content;
480  return strlen( $content );
481  }
482 
488  public function execute() {
489 
490  $this->content = "";
491 
492  if ( strtoupper( $this->method ) == "HEAD" ) {
493  $this->headersOnly = true;
494  }
495 
496  $this->proxySetup(); // set up any proxy as needed
497 
498  if ( !$this->callback ) {
499  $this->setCallback( [ $this, 'read' ] );
500  }
501 
502  if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
503  $this->setUserAgent( Http::userAgent() );
504  }
505 
506  }
507 
513  protected function parseHeader() {
514 
515  $lastname = "";
516 
517  foreach ( $this->headerList as $header ) {
518  if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
519  $this->respVersion = $match[1];
520  $this->respStatus = $match[2];
521  } elseif ( preg_match( "#^[ \t]#", $header ) ) {
522  $last = count( $this->respHeaders[$lastname] ) - 1;
523  $this->respHeaders[$lastname][$last] .= "\r\n$header";
524  } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
525  $this->respHeaders[strtolower( $match[1] )][] = $match[2];
526  $lastname = strtolower( $match[1] );
527  }
528  }
529 
530  $this->parseCookies();
531 
532  }
533 
542  protected function setStatus() {
543  if ( !$this->respHeaders ) {
544  $this->parseHeader();
545  }
546 
547  if ( (int)$this->respStatus > 399 ) {
548  list( $code, $message ) = explode( " ", $this->respStatus, 2 );
549  $this->status->fatal( "http-bad-status", $code, $message );
550  }
551  }
552 
560  public function getStatus() {
561  if ( !$this->respHeaders ) {
562  $this->parseHeader();
563  }
564 
565  return (int)$this->respStatus;
566  }
567 
573  public function isRedirect() {
574  if ( !$this->respHeaders ) {
575  $this->parseHeader();
576  }
577 
578  $status = (int)$this->respStatus;
579 
580  if ( $status >= 300 && $status <= 303 ) {
581  return true;
582  }
583 
584  return false;
585  }
586 
595  public function getResponseHeaders() {
596  if ( !$this->respHeaders ) {
597  $this->parseHeader();
598  }
599 
600  return $this->respHeaders;
601  }
602 
609  public function getResponseHeader( $header ) {
610  if ( !$this->respHeaders ) {
611  $this->parseHeader();
612  }
613 
614  if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
615  $v = $this->respHeaders[strtolower( $header )];
616  return $v[count( $v ) - 1];
617  }
618 
619  return null;
620  }
621 
627  public function setCookieJar( $jar ) {
628  $this->cookieJar = $jar;
629  }
630 
636  public function getCookieJar() {
637  if ( !$this->respHeaders ) {
638  $this->parseHeader();
639  }
640 
641  return $this->cookieJar;
642  }
643 
653  public function setCookie( $name, $value = null, $attr = null ) {
654  if ( !$this->cookieJar ) {
655  $this->cookieJar = new CookieJar;
656  }
657 
658  $this->cookieJar->setCookie( $name, $value, $attr );
659  }
660 
664  protected function parseCookies() {
665 
666  if ( !$this->cookieJar ) {
667  $this->cookieJar = new CookieJar;
668  }
669 
670  if ( isset( $this->respHeaders['set-cookie'] ) ) {
671  $url = parse_url( $this->getFinalUrl() );
672  foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
673  $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
674  }
675  }
676 
677  }
678 
695  public function getFinalUrl() {
696  $headers = $this->getResponseHeaders();
697 
698  // return full url (fix for incorrect but handled relative location)
699  if ( isset( $headers['location'] ) ) {
700  $locations = $headers['location'];
701  $domain = '';
702  $foundRelativeURI = false;
703  $countLocations = count( $locations );
704 
705  for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
706  $url = parse_url( $locations[$i] );
707 
708  if ( isset( $url['host'] ) ) {
709  $domain = $url['scheme'] . '://' . $url['host'];
710  break; // found correct URI (with host)
711  } else {
712  $foundRelativeURI = true;
713  }
714  }
715 
716  if ( $foundRelativeURI ) {
717  if ( $domain ) {
718  return $domain . $locations[$countLocations - 1];
719  } else {
720  $url = parse_url( $this->url );
721  if ( isset( $url['host'] ) ) {
722  return $url['scheme'] . '://' . $url['host'] .
723  $locations[$countLocations - 1];
724  }
725  }
726  } else {
727  return $locations[$countLocations - 1];
728  }
729  }
730 
731  return $this->url;
732  }
733 
739  public function canFollowRedirects() {
740  return true;
741  }
742 }
743 
748  const SUPPORTS_FILE_POSTS = true;
749 
750  protected $curlOptions = [];
751  protected $headerText = "";
752 
758  protected function readHeader( $fh, $content ) {
759  $this->headerText .= $content;
760  return strlen( $content );
761  }
762 
763  public function execute() {
764 
765  parent::execute();
766 
767  if ( !$this->status->isOK() ) {
768  return $this->status;
769  }
770 
771  $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
772  $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
773 
774  // Only supported in curl >= 7.16.2
775  if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
776  $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
777  }
778 
779  $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
780  $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
781  $this->curlOptions[CURLOPT_HEADERFUNCTION] = [ $this, "readHeader" ];
782  $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
783  $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
784 
785  $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
786 
787  $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
788  $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
789 
790  if ( $this->caInfo ) {
791  $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
792  }
793 
794  if ( $this->headersOnly ) {
795  $this->curlOptions[CURLOPT_NOBODY] = true;
796  $this->curlOptions[CURLOPT_HEADER] = true;
797  } elseif ( $this->method == 'POST' ) {
798  $this->curlOptions[CURLOPT_POST] = true;
800  // Don't interpret POST parameters starting with '@' as file uploads, because this
801  // makes it impossible to POST plain values starting with '@' (and causes security
802  // issues potentially exposing the contents of local files).
803  // The PHP manual says this option was introduced in PHP 5.5 defaults to true in PHP 5.6,
804  // but we support lower versions, and the option doesn't exist in HHVM 5.6.99.
805  if ( defined( 'CURLOPT_SAFE_UPLOAD' ) ) {
806  $this->curlOptions[CURLOPT_SAFE_UPLOAD] = true;
807  } elseif ( is_array( $postData ) ) {
808  // In PHP 5.2 and later, '@' is interpreted as a file upload if POSTFIELDS
809  // is an array, but not if it's a string. So convert $req['body'] to a string
810  // for safety.
812  }
813  $this->curlOptions[CURLOPT_POSTFIELDS] = $postData;
814 
815  // Suppress 'Expect: 100-continue' header, as some servers
816  // will reject it with a 417 and Curl won't auto retry
817  // with HTTP 1.0 fallback
818  $this->reqHeaders['Expect'] = '';
819  } else {
820  $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
821  }
822 
823  $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
824 
825  $curlHandle = curl_init( $this->url );
826 
827  if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
828  throw new MWException( "Error setting curl options." );
829  }
830 
831  if ( $this->followRedirects && $this->canFollowRedirects() ) {
832  MediaWiki\suppressWarnings();
833  if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
834  wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
835  "Probably open_basedir is set.\n" );
836  // Continue the processing. If it were in curl_setopt_array,
837  // processing would have halted on its entry
838  }
839  MediaWiki\restoreWarnings();
840  }
841 
842  if ( $this->profiler ) {
843  $profileSection = $this->profiler->scopedProfileIn(
844  __METHOD__ . '-' . $this->profileName
845  );
846  }
847 
848  $curlRes = curl_exec( $curlHandle );
849  if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
850  $this->status->fatal( 'http-timed-out', $this->url );
851  } elseif ( $curlRes === false ) {
852  $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
853  } else {
854  $this->headerList = explode( "\r\n", $this->headerText );
855  }
856 
857  curl_close( $curlHandle );
858 
859  if ( $this->profiler ) {
860  $this->profiler->scopedProfileOut( $profileSection );
861  }
862 
863  $this->parseHeader();
864  $this->setStatus();
865 
866  return $this->status;
867  }
868 
872  public function canFollowRedirects() {
873  $curlVersionInfo = curl_version();
874  if ( $curlVersionInfo['version_number'] < 0x071304 ) {
875  wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
876  return false;
877  }
878 
879  if ( version_compare( PHP_VERSION, '5.6.0', '<' ) ) {
880  if ( strval( ini_get( 'open_basedir' ) ) !== '' ) {
881  wfDebug( "Cannot follow redirects when open_basedir is set\n" );
882  return false;
883  }
884  }
885 
886  return true;
887  }
888 }
889 
891 
892  private $fopenErrors = [];
893 
898  protected function urlToTcp( $url ) {
899  $parsedUrl = parse_url( $url );
900 
901  return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
902  }
903 
913  protected function getCertOptions() {
914  $certOptions = [];
915  $certLocations = [];
916  if ( $this->caInfo ) {
917  $certLocations = [ 'manual' => $this->caInfo ];
918  } elseif ( version_compare( PHP_VERSION, '5.6.0', '<' ) ) {
919  // @codingStandardsIgnoreStart Generic.Files.LineLength
920  // Default locations, based on
921  // https://www.happyassassin.net/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
922  // PHP 5.5 and older doesn't have any defaults, so we try to guess ourselves.
923  // PHP 5.6+ gets the CA location from OpenSSL as long as it is not set manually,
924  // so we should leave capath/cafile empty there.
925  // @codingStandardsIgnoreEnd
926  $certLocations = array_filter( [
927  getenv( 'SSL_CERT_DIR' ),
928  getenv( 'SSL_CERT_PATH' ),
929  '/etc/pki/tls/certs/ca-bundle.crt', # Fedora et al
930  '/etc/ssl/certs', # Debian et al
931  '/etc/pki/tls/certs/ca-bundle.trust.crt',
932  '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem',
933  '/System/Library/OpenSSL', # OSX
934  ] );
935  }
936 
937  foreach ( $certLocations as $key => $cert ) {
938  if ( is_dir( $cert ) ) {
939  $certOptions['capath'] = $cert;
940  break;
941  } elseif ( is_file( $cert ) ) {
942  $certOptions['cafile'] = $cert;
943  break;
944  } elseif ( $key === 'manual' ) {
945  // fail more loudly if a cert path was manually configured and it is not valid
946  throw new DomainException( "Invalid CA info passed: $cert" );
947  }
948  }
949 
950  return $certOptions;
951  }
952 
960  public function errorHandler( $errno, $errstr ) {
961  $n = count( $this->fopenErrors ) + 1;
962  $this->fopenErrors += [ "errno$n" => $errno, "errstr$n" => $errstr ];
963  }
964 
965  public function execute() {
966 
967  parent::execute();
968 
969  if ( is_array( $this->postData ) ) {
970  $this->postData = wfArrayToCgi( $this->postData );
971  }
972 
973  if ( $this->parsedUrl['scheme'] != 'http'
974  && $this->parsedUrl['scheme'] != 'https' ) {
975  $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
976  }
977 
978  $this->reqHeaders['Accept'] = "*/*";
979  $this->reqHeaders['Connection'] = 'Close';
980  if ( $this->method == 'POST' ) {
981  // Required for HTTP 1.0 POSTs
982  $this->reqHeaders['Content-Length'] = strlen( $this->postData );
983  if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
984  $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
985  }
986  }
987 
988  // Set up PHP stream context
989  $options = [
990  'http' => [
991  'method' => $this->method,
992  'header' => implode( "\r\n", $this->getHeaderList() ),
993  'protocol_version' => '1.1',
994  'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
995  'ignore_errors' => true,
996  'timeout' => $this->timeout,
997  // Curl options in case curlwrappers are installed
998  'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
999  'curl_verify_ssl_peer' => $this->sslVerifyCert,
1000  ],
1001  'ssl' => [
1002  'verify_peer' => $this->sslVerifyCert,
1003  'SNI_enabled' => true,
1004  'ciphers' => 'HIGH:!SSLv2:!SSLv3:-ADH:-kDH:-kECDH:-DSS',
1005  'disable_compression' => true,
1006  ],
1007  ];
1008 
1009  if ( $this->proxy ) {
1010  $options['http']['proxy'] = $this->urlToTcp( $this->proxy );
1011  $options['http']['request_fulluri'] = true;
1012  }
1013 
1014  if ( $this->postData ) {
1015  $options['http']['content'] = $this->postData;
1016  }
1017 
1018  if ( $this->sslVerifyHost ) {
1019  // PHP 5.6.0 deprecates CN_match, in favour of peer_name which
1020  // actually checks SubjectAltName properly.
1021  if ( version_compare( PHP_VERSION, '5.6.0', '>=' ) ) {
1022  $options['ssl']['peer_name'] = $this->parsedUrl['host'];
1023  } else {
1024  $options['ssl']['CN_match'] = $this->parsedUrl['host'];
1025  }
1026  }
1027 
1028  $options['ssl'] += $this->getCertOptions();
1029 
1030  $context = stream_context_create( $options );
1031 
1032  $this->headerList = [];
1033  $reqCount = 0;
1034  $url = $this->url;
1035 
1036  $result = [];
1037 
1038  if ( $this->profiler ) {
1039  $profileSection = $this->profiler->scopedProfileIn(
1040  __METHOD__ . '-' . $this->profileName
1041  );
1042  }
1043  do {
1044  $reqCount++;
1045  $this->fopenErrors = [];
1046  set_error_handler( [ $this, 'errorHandler' ] );
1047  $fh = fopen( $url, "r", false, $context );
1048  restore_error_handler();
1049 
1050  if ( !$fh ) {
1051  // HACK for instant commons.
1052  // If we are contacting (commons|upload).wikimedia.org
1053  // try again with CN_match for en.wikipedia.org
1054  // as php does not handle SubjectAltName properly
1055  // prior to "peer_name" option in php 5.6
1056  if ( isset( $options['ssl']['CN_match'] )
1057  && ( $options['ssl']['CN_match'] === 'commons.wikimedia.org'
1058  || $options['ssl']['CN_match'] === 'upload.wikimedia.org' )
1059  ) {
1060  $options['ssl']['CN_match'] = 'en.wikipedia.org';
1061  $context = stream_context_create( $options );
1062  continue;
1063  }
1064  break;
1065  }
1066 
1067  $result = stream_get_meta_data( $fh );
1068  $this->headerList = $result['wrapper_data'];
1069  $this->parseHeader();
1070 
1071  if ( !$this->followRedirects ) {
1072  break;
1073  }
1074 
1075  # Handle manual redirection
1076  if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
1077  break;
1078  }
1079  # Check security of URL
1080  $url = $this->getResponseHeader( "Location" );
1081 
1082  if ( !Http::isValidURI( $url ) ) {
1083  wfDebug( __METHOD__ . ": insecure redirection\n" );
1084  break;
1085  }
1086  } while ( true );
1087  if ( $this->profiler ) {
1088  $this->profiler->scopedProfileOut( $profileSection );
1089  }
1090 
1091  $this->setStatus();
1092 
1093  if ( $fh === false ) {
1094  if ( $this->fopenErrors ) {
1095  LoggerFactory::getInstance( 'http' )->warning( __CLASS__
1096  . ': error opening connection: {errstr1}', $this->fopenErrors );
1097  }
1098  $this->status->fatal( 'http-request-error' );
1099  return $this->status;
1100  }
1101 
1102  if ( $result['timed_out'] ) {
1103  $this->status->fatal( 'http-timed-out', $this->url );
1104  return $this->status;
1105  }
1106 
1107  // If everything went OK, or we received some error code
1108  // get the response body content.
1109  if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
1110  while ( !feof( $fh ) ) {
1111  $buf = fread( $fh, 8192 );
1112 
1113  if ( $buf === false ) {
1114  $this->status->fatal( 'http-read-error' );
1115  break;
1116  }
1117 
1118  if ( strlen( $buf ) ) {
1119  call_user_func( $this->callback, $fh, $buf );
1120  }
1121  }
1122  }
1123  fclose( $fh );
1124 
1125  return $this->status;
1126  }
1127 }
CookieJar $cookieJar
readHeader($fh, $content)
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
proxySetup()
Take care of setting up the proxy (do nothing if "noProxy" is set)
$wgVersion
MediaWiki version number.
$context
Definition: load.php:44
$batch execute()
setCookie($name, $value=null, $attr=null)
Sets a cookie.
static getProxy()
Gets the relevant proxy from $wgHTTPProxy/http_proxy (when set).
execute()
Take care of whatever is necessary to perform the URI request.
per default it will return the text for text based content
canFollowRedirects()
Returns true if the backend can follow redirects.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
setHeader($name, $value)
Set an arbitrary header.
static instance()
Singleton.
Definition: Profiler.php:60
setCookieJar($jar)
Tells the MWHttpRequest object to use this pre-loaded CookieJar.
isRedirect()
Returns true if the last status code was a redirect.
$value
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfExpandUrl($url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
static canMakeRequests()
Simple function to test if we can make any sort of requests at all, using cURL or fopen() ...
MWHttpRequest implemented using internal curl compiled into PHP.
static request($method, $url, $options=[], $caller=__METHOD__)
Perform an HTTP request.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static userAgent()
A standard user-agent we can use for external requests.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1796
parseCookies()
Parse the cookies in the response headers and store them in the cookie jar.
if($line===false) $args
Definition: cdb.php:64
$last
global $wgCommandLineMode
Definition: Setup.php:513
getCookieJar()
Returns the cookie jar in use.
getHeaderList()
Get an array of the headers.
static $httpEngine
getFinalUrl()
Returns the final URL after all redirections.
Profiler $profiler
wfWarn($msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfIniGetBool($setting)
Safety wrapper around ini_get() for boolean settings.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1004
__construct($url, $options=[], $caller=__METHOD__, $profiler=null)
errorHandler($errno, $errstr)
Custom error handler for dealing with fopen() errors.
const SUPPORTS_FILE_POSTS
read($fh, $content)
A generic callback to read the body of the response from a remote server.
getCertOptions()
Returns an array with a 'capath' or 'cafile' key that is suitable to be merged into the 'ssl' sub-arr...
setStatus()
Sets HTTPRequest status member to a fatal value with the error message if the returned integer value ...
MediaWiki has optional support for a high distributed memory object caching system For general information on but for a larger site with heavy like it should help lighten the load on the database servers by caching data and objects in Debian
Definition: memcached.txt:10
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
setCallback($callback)
Set a read callback to accept data read from the HTTP request.
getResponseHeaders()
Returns an associative array of response headers after the request has been executed.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:762
const PROTO_HTTP
Definition: Defines.php:261
getStatus()
Get the integer value of the HTTP status code (e.g.
parseHeader()
Parses the headers, including the HTTP status code and any Set-Cookie headers.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only $req
Definition: hooks.txt:965
setUserAgent($UA)
Set the user agent.
wfArrayToCgi($array1, $array2=null, $prefix= '')
This function takes one or two arrays as input, and returns a CGI-style string, e.g.
static post($url, $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'POST' )
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1004
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
static isLocalURL($url)
Check if the URL can be served by localhost.
static factory($url, $options=null, $caller=__METHOD__)
Generate a new request object.
getContent()
Get the body, or content, of the response to the request.
wfParseUrl($url)
parse_url() work-alike, but non-broken.
setData($args)
Set the parameters of the request.
setCookie($name, $value, $attr)
Set a cookie in the cookie jar.
Definition: CookieJar.php:32
static isValidURI($uri)
Checks that the given URI is a valid one.
getResponseHeader($header)
Returns the value of the given response header.
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
$matches
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310