MediaWiki  1.34.0
WebRequest.php
Go to the documentation of this file.
1 <?php
30 use Wikimedia\AtEase\AtEase;
31 
32 // The point of this class is to be a wrapper around super globals
33 // phpcs:disable MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
34 
42 class WebRequest {
47  protected $data;
48 
55 
59  protected $queryParams;
60 
65  protected $headers = [];
66 
71  const GETHEADER_LIST = 1;
72 
77  private static $reqId;
78 
83  private $response;
84 
89  private $ip;
90 
95  protected $requestTime;
96 
101  protected $protocol;
102 
108  protected $sessionId = null;
109 
111  protected $markedAsSafe = false;
112 
116  public function __construct() {
117  $this->requestTime = $_SERVER['REQUEST_TIME_FLOAT'];
118 
119  // POST overrides GET data
120  // We don't use $_REQUEST here to avoid interference from cookies...
121  $this->data = $_POST + $_GET;
122 
123  $this->queryAndPathParams = $this->queryParams = $_GET;
124  }
125 
141  public static function getPathInfo( $want = 'all' ) {
142  // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
143  // And also by Apache 2.x, double slashes are converted to single slashes.
144  // So we will use REQUEST_URI if possible.
145  if ( isset( $_SERVER['REQUEST_URI'] ) ) {
146  // Slurp out the path portion to examine...
147  $url = $_SERVER['REQUEST_URI'];
148  if ( !preg_match( '!^https?://!', $url ) ) {
149  $url = 'http://unused' . $url;
150  }
151  AtEase::suppressWarnings();
152  $a = parse_url( $url );
153  AtEase::restoreWarnings();
154  if ( !$a ) {
155  return [];
156  }
157  $path = $a['path'] ?? '';
158 
159  global $wgScript;
160  if ( $path == $wgScript && $want !== 'all' ) {
161  // Script inside a rewrite path?
162  // Abort to keep from breaking...
163  return [];
164  }
165 
166  $router = new PathRouter;
167 
168  // Raw PATH_INFO style
169  $router->add( "$wgScript/$1" );
170 
171  if ( isset( $_SERVER['SCRIPT_NAME'] )
172  && strpos( $_SERVER['SCRIPT_NAME'], '.php' ) !== false
173  ) {
174  // Check for SCRIPT_NAME, we handle index.php explicitly
175  // But we do have some other .php files such as img_auth.php
176  // Don't let root article paths clober the parsing for them
177  $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
178  }
179 
180  global $wgArticlePath;
181  if ( $wgArticlePath ) {
182  $router->add( $wgArticlePath );
183  }
184 
185  global $wgActionPaths;
187  if ( $articlePaths ) {
188  $router->add( $articlePaths, [ 'action' => '$key' ] );
189  }
190 
191  global $wgVariantArticlePath;
192  if ( $wgVariantArticlePath ) {
193  $router->add( $wgVariantArticlePath,
194  [ 'variant' => '$2' ],
195  [ '$2' => MediaWikiServices::getInstance()->getContentLanguage()->
196  getVariants() ]
197  );
198  }
199 
200  Hooks::run( 'WebRequestPathInfoRouter', [ $router ] );
201 
202  $matches = $router->parse( $path );
203  } else {
204  global $wgUsePathInfo;
205  $matches = [];
206  if ( $wgUsePathInfo ) {
207  if ( !empty( $_SERVER['ORIG_PATH_INFO'] ) ) {
208  // Mangled PATH_INFO
209  // https://bugs.php.net/bug.php?id=31892
210  // Also reported when ini_get('cgi.fix_pathinfo')==false
211  $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
212  } elseif ( !empty( $_SERVER['PATH_INFO'] ) ) {
213  // Regular old PATH_INFO yay
214  $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
215  }
216  }
217  }
218 
219  return $matches;
220  }
221 
228  public static function detectServer() {
230 
231  $proto = self::detectProtocol();
232  $stdPort = $proto === 'https' ? 443 : 80;
233 
234  $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
235  $host = 'localhost';
236  $port = $stdPort;
237  foreach ( $varNames as $varName ) {
238  if ( !isset( $_SERVER[$varName] ) ) {
239  continue;
240  }
241 
242  $parts = IP::splitHostAndPort( $_SERVER[$varName] );
243  if ( !$parts ) {
244  // Invalid, do not use
245  continue;
246  }
247 
248  $host = $parts[0];
249  if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
250  // T72021: Assume that upstream proxy is running on the default
251  // port based on the protocol. We have no reliable way to determine
252  // the actual port in use upstream.
253  $port = $stdPort;
254  } elseif ( $parts[1] === false ) {
255  if ( isset( $_SERVER['SERVER_PORT'] ) ) {
256  $port = $_SERVER['SERVER_PORT'];
257  } // else leave it as $stdPort
258  } else {
259  $port = $parts[1];
260  }
261  break;
262  }
263 
264  return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
265  }
266 
274  public static function detectProtocol() {
275  if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
276  ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
277  $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
278  return 'https';
279  } else {
280  return 'http';
281  }
282  }
283 
291  public function getElapsedTime() {
292  return microtime( true ) - $this->requestTime;
293  }
294 
303  public static function getRequestId() {
304  // This method is called from various error handlers and should be kept simple.
305 
306  if ( self::$reqId ) {
307  return self::$reqId;
308  }
309 
310  global $wgAllowExternalReqID;
311 
312  self::$reqId = $_SERVER['UNIQUE_ID'] ?? wfRandomString( 24 );
313  if ( $wgAllowExternalReqID ) {
314  $id = RequestContext::getMain()->getRequest()->getHeader( 'X-Request-Id' );
315  if ( $id ) {
316  self::$reqId = $id;
317  }
318  }
319 
320  return self::$reqId;
321  }
322 
330  public static function overrideRequestId( $id ) {
331  self::$reqId = $id;
332  }
333 
338  public function getProtocol() {
339  if ( $this->protocol === null ) {
340  $this->protocol = self::detectProtocol();
341  }
342  return $this->protocol;
343  }
344 
352  public function interpolateTitle() {
353  // T18019: title interpolation on API queries is useless and sometimes harmful
354  if ( defined( 'MW_API' ) ) {
355  return;
356  }
357 
358  $matches = self::getPathInfo( 'title' );
359  foreach ( $matches as $key => $val ) {
360  $this->data[$key] = $this->queryAndPathParams[$key] = $val;
361  }
362  }
363 
374  static function extractTitle( $path, $bases, $key = false ) {
375  foreach ( (array)$bases as $keyValue => $base ) {
376  // Find the part after $wgArticlePath
377  $base = str_replace( '$1', '', $base );
378  $baseLen = strlen( $base );
379  if ( substr( $path, 0, $baseLen ) == $base ) {
380  $raw = substr( $path, $baseLen );
381  if ( $raw !== '' ) {
382  $matches = [ 'title' => rawurldecode( $raw ) ];
383  if ( $key ) {
384  $matches[$key] = $keyValue;
385  }
386  return $matches;
387  }
388  }
389  }
390  return [];
391  }
392 
400  public function normalizeUnicode( $data ) {
401  if ( is_array( $data ) ) {
402  foreach ( $data as $key => $val ) {
403  $data[$key] = $this->normalizeUnicode( $val );
404  }
405  } else {
406  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
407  $data = $contLang ? $contLang->normalize( $data ) :
408  UtfNormal\Validator::cleanUp( $data );
409  }
410  return $data;
411  }
412 
421  private function getGPCVal( $arr, $name, $default ) {
422  # PHP is so nice to not touch input data, except sometimes:
423  # https://www.php.net/variables.external#language.variables.external.dot-in-names
424  # Work around PHP *feature* to avoid *bugs* elsewhere.
425  $name = strtr( $name, '.', '_' );
426 
427  if ( !isset( $arr[$name] ) ) {
428  return $default;
429  }
430 
431  $data = $arr[$name];
432  # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
433  $isAsciiStr = ( is_string( $data ) && preg_match( '/[^\x20-\x7E]/', $data ) === 0 );
434  if ( !$isAsciiStr ) {
435  if ( isset( $_GET[$name] ) && is_string( $data ) ) {
436  # Check for alternate/legacy character encoding.
437  $data = MediaWikiServices::getInstance()
438  ->getContentLanguage()
439  ->checkTitleEncoding( $data );
440  }
441  $data = $this->normalizeUnicode( $data );
442  }
443 
444  return $data;
445  }
446 
459  public function getRawVal( $name, $default = null ) {
460  $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
461  if ( isset( $this->data[$name] ) && !is_array( $this->data[$name] ) ) {
462  $val = $this->data[$name];
463  } else {
464  $val = $default;
465  }
466  if ( is_null( $val ) ) {
467  return $val;
468  } else {
469  return (string)$val;
470  }
471  }
472 
483  public function getVal( $name, $default = null ) {
484  $val = $this->getGPCVal( $this->data, $name, $default );
485  if ( is_array( $val ) ) {
486  $val = $default;
487  }
488  if ( is_null( $val ) ) {
489  return $val;
490  } else {
491  return (string)$val;
492  }
493  }
494 
502  public function setVal( $key, $value ) {
503  $ret = $this->data[$key] ?? null;
504  $this->data[$key] = $value;
505  return $ret;
506  }
507 
514  public function unsetVal( $key ) {
515  if ( !isset( $this->data[$key] ) ) {
516  $ret = null;
517  } else {
518  $ret = $this->data[$key];
519  unset( $this->data[$key] );
520  }
521  return $ret;
522  }
523 
533  public function getArray( $name, $default = null ) {
534  $val = $this->getGPCVal( $this->data, $name, $default );
535  if ( is_null( $val ) ) {
536  return null;
537  } else {
538  return (array)$val;
539  }
540  }
541 
552  public function getIntArray( $name, $default = null ) {
553  $val = $this->getArray( $name, $default );
554  if ( is_array( $val ) ) {
555  $val = array_map( 'intval', $val );
556  }
557  return $val;
558  }
559 
569  public function getInt( $name, $default = 0 ) {
570  return intval( $this->getRawVal( $name, $default ) );
571  }
572 
581  public function getIntOrNull( $name ) {
582  $val = $this->getRawVal( $name );
583  return is_numeric( $val )
584  ? intval( $val )
585  : null;
586  }
587 
598  public function getFloat( $name, $default = 0.0 ) {
599  return floatval( $this->getRawVal( $name, $default ) );
600  }
601 
611  public function getBool( $name, $default = false ) {
612  return (bool)$this->getRawVal( $name, $default );
613  }
614 
624  public function getFuzzyBool( $name, $default = false ) {
625  return $this->getBool( $name, $default )
626  && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
627  }
628 
637  public function getCheck( $name ) {
638  # Checkboxes and buttons are only present when clicked
639  # Presence connotes truth, absence false
640  return $this->getRawVal( $name, null ) !== null;
641  }
642 
653  public function getText( $name, $default = '' ) {
654  $val = $this->getVal( $name, $default );
655  return str_replace( "\r\n", "\n", $val );
656  }
657 
665  public function getValues() {
666  $names = func_get_args();
667  if ( count( $names ) == 0 ) {
668  $names = array_keys( $this->data );
669  }
670 
671  $retVal = [];
672  foreach ( $names as $name ) {
673  $value = $this->getGPCVal( $this->data, $name, null );
674  if ( !is_null( $value ) ) {
675  $retVal[$name] = $value;
676  }
677  }
678  return $retVal;
679  }
680 
687  public function getValueNames( $exclude = [] ) {
688  return array_diff( array_keys( $this->getValues() ), $exclude );
689  }
690 
698  public function getQueryValues() {
700  }
701 
711  public function getQueryValuesOnly() {
712  return $this->queryParams;
713  }
714 
723  public function getPostValues() {
724  return $_POST;
725  }
726 
734  public function getRawQueryString() {
735  return $_SERVER['QUERY_STRING'];
736  }
737 
744  public function getRawPostString() {
745  if ( !$this->wasPosted() ) {
746  return '';
747  }
748  return $this->getRawInput();
749  }
750 
758  public function getRawInput() {
759  static $input = null;
760  if ( $input === null ) {
761  $input = file_get_contents( 'php://input' );
762  }
763  return $input;
764  }
765 
771  public function getMethod() {
772  return $_SERVER['REQUEST_METHOD'] ?? 'GET';
773  }
774 
784  public function wasPosted() {
785  return $this->getMethod() == 'POST';
786  }
787 
798  public function getSession() {
799  if ( $this->sessionId !== null ) {
800  $session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
801  if ( $session ) {
802  return $session;
803  }
804  }
805 
806  $session = SessionManager::singleton()->getSessionForRequest( $this );
807  $this->sessionId = $session->getSessionId();
808  return $session;
809  }
810 
817  public function setSessionId( SessionId $sessionId ) {
818  $this->sessionId = $sessionId;
819  }
820 
827  public function getSessionId() {
828  return $this->sessionId;
829  }
830 
839  public function getCookie( $key, $prefix = null, $default = null ) {
840  if ( $prefix === null ) {
841  global $wgCookiePrefix;
842  $prefix = $wgCookiePrefix;
843  }
844  return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
845  }
846 
854  public static function getGlobalRequestURL() {
855  // This method is called on fatal errors; it should not depend on anything complex.
856 
857  if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
858  $base = $_SERVER['REQUEST_URI'];
859  } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
860  && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
861  ) {
862  // Probably IIS; doesn't set REQUEST_URI
863  $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
864  } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
865  $base = $_SERVER['SCRIPT_NAME'];
866  if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
867  $base .= '?' . $_SERVER['QUERY_STRING'];
868  }
869  } else {
870  // This shouldn't happen!
871  throw new MWException( "Web server doesn't provide either " .
872  "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
873  "of your web server configuration to https://phabricator.wikimedia.org/" );
874  }
875  // User-agents should not send a fragment with the URI, but
876  // if they do, and the web server passes it on to us, we
877  // need to strip it or we get false-positive redirect loops
878  // or weird output URLs
879  $hash = strpos( $base, '#' );
880  if ( $hash !== false ) {
881  $base = substr( $base, 0, $hash );
882  }
883 
884  if ( $base[0] == '/' ) {
885  // More than one slash will look like it is protocol relative
886  return preg_replace( '!^/+!', '/', $base );
887  } else {
888  // We may get paths with a host prepended; strip it.
889  return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
890  }
891  }
892 
900  public function getRequestURL() {
901  return self::getGlobalRequestURL();
902  }
903 
914  public function getFullRequestURL() {
915  // Pass an explicit PROTO constant instead of PROTO_CURRENT so that we
916  // do not rely on state from the global $wgRequest object (which it would,
917  // via wfGetServerUrl/wfExpandUrl/$wgRequest->protocol).
918  if ( $this->getProtocol() === 'http' ) {
919  return wfGetServerUrl( PROTO_HTTP ) . $this->getRequestURL();
920  } else {
921  return wfGetServerUrl( PROTO_HTTPS ) . $this->getRequestURL();
922  }
923  }
924 
930  public function appendQueryValue( $key, $value ) {
931  return $this->appendQueryArray( [ $key => $value ] );
932  }
933 
940  public function appendQueryArray( $array ) {
941  $newquery = $this->getQueryValues();
942  unset( $newquery['title'] );
943  $newquery = array_merge( $newquery, $array );
944 
945  return wfArrayToCgi( $newquery );
946  }
947 
957  public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
958  global $wgUser;
959 
960  $limit = $this->getInt( 'limit', 0 );
961  if ( $limit < 0 ) {
962  $limit = 0;
963  }
964  if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
965  $limit = $wgUser->getIntOption( $optionname );
966  }
967  if ( $limit <= 0 ) {
968  $limit = $deflimit;
969  }
970  if ( $limit > 5000 ) {
971  $limit = 5000; # We have *some* limits...
972  }
973 
974  $offset = $this->getInt( 'offset', 0 );
975  if ( $offset < 0 ) {
976  $offset = 0;
977  }
978 
979  return [ $limit, $offset ];
980  }
981 
988  public function getFileTempname( $key ) {
989  $file = new WebRequestUpload( $this, $key );
990  return $file->getTempName();
991  }
992 
999  public function getUploadError( $key ) {
1000  $file = new WebRequestUpload( $this, $key );
1001  return $file->getError();
1002  }
1003 
1015  public function getFileName( $key ) {
1016  $file = new WebRequestUpload( $this, $key );
1017  return $file->getName();
1018  }
1019 
1026  public function getUpload( $key ) {
1027  return new WebRequestUpload( $this, $key );
1028  }
1029 
1036  public function response() {
1037  /* Lazy initialization of response object for this request */
1038  if ( !is_object( $this->response ) ) {
1039  $class = ( $this instanceof FauxRequest ) ? FauxResponse::class : WebResponse::class;
1040  $this->response = new $class();
1041  }
1042  return $this->response;
1043  }
1044 
1048  protected function initHeaders() {
1049  if ( count( $this->headers ) ) {
1050  return;
1051  }
1052 
1053  $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
1054  if ( $apacheHeaders ) {
1055  foreach ( $apacheHeaders as $tempName => $tempValue ) {
1056  $this->headers[strtoupper( $tempName )] = $tempValue;
1057  }
1058  } else {
1059  foreach ( $_SERVER as $name => $value ) {
1060  if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
1061  $name = str_replace( '_', '-', substr( $name, 5 ) );
1062  $this->headers[$name] = $value;
1063  } elseif ( $name === 'CONTENT_LENGTH' ) {
1064  $this->headers['CONTENT-LENGTH'] = $value;
1065  }
1066  }
1067  }
1068  }
1069 
1075  public function getAllHeaders() {
1076  $this->initHeaders();
1077  return $this->headers;
1078  }
1079 
1092  public function getHeader( $name, $flags = 0 ) {
1093  $this->initHeaders();
1094  $name = strtoupper( $name );
1095  if ( !isset( $this->headers[$name] ) ) {
1096  return false;
1097  }
1098  $value = $this->headers[$name];
1099  if ( $flags & self::GETHEADER_LIST ) {
1100  $value = array_map( 'trim', explode( ',', $value ) );
1101  }
1102  return $value;
1103  }
1104 
1112  public function getSessionData( $key ) {
1113  return $this->getSession()->get( $key );
1114  }
1115 
1123  public function setSessionData( $key, $data ) {
1124  $this->getSession()->set( $key, $data );
1125  }
1126 
1137  public function checkUrlExtension( $extWhitelist = [] ) {
1138  $extWhitelist[] = 'php';
1139  if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1140  if ( !$this->wasPosted() ) {
1141  $newUrl = IEUrlExtension::fixUrlForIE6(
1142  $this->getFullRequestURL(), $extWhitelist );
1143  if ( $newUrl !== false ) {
1144  $this->doSecurityRedirect( $newUrl );
1145  return false;
1146  }
1147  }
1148  throw new HttpError( 403,
1149  'Invalid file extension found in the path info or query string.' );
1150  }
1151  return true;
1152  }
1153 
1161  protected function doSecurityRedirect( $url ) {
1162  header( 'Location: ' . $url );
1163  header( 'Content-Type: text/html' );
1164  $encUrl = htmlspecialchars( $url );
1165  echo <<<HTML
1166 <!DOCTYPE html>
1167 <html>
1168 <head>
1169 <title>Security redirect</title>
1170 </head>
1171 <body>
1172 <h1>Security redirect</h1>
1173 <p>
1174 We can't serve non-HTML content from the URL you have requested, because
1175 Internet Explorer would interpret it as an incorrect and potentially dangerous
1176 content type.</p>
1177 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1178 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1179 Explorer from seeing a bogus file extension.
1180 </p>
1181 </body>
1182 </html>
1183 HTML;
1184  echo "\n";
1185  return true;
1186  }
1187 
1197  public function getAcceptLang() {
1198  // Modified version of code found at
1199  // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1200  $acceptLang = $this->getHeader( 'Accept-Language' );
1201  if ( !$acceptLang ) {
1202  return [];
1203  }
1204 
1205  // Return the language codes in lower case
1206  $acceptLang = strtolower( $acceptLang );
1207 
1208  // Break up string into pieces (languages and q factors)
1209  $lang_parse = null;
1210  preg_match_all(
1211  '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1212  $acceptLang,
1213  $lang_parse
1214  );
1215 
1216  if ( !count( $lang_parse[1] ) ) {
1217  return [];
1218  }
1219 
1220  $langcodes = $lang_parse[1];
1221  $qvalues = $lang_parse[4];
1222  $indices = range( 0, count( $lang_parse[1] ) - 1 );
1223 
1224  // Set default q factor to 1
1225  foreach ( $indices as $index ) {
1226  if ( $qvalues[$index] === '' ) {
1227  $qvalues[$index] = 1;
1228  } elseif ( $qvalues[$index] == 0 ) {
1229  unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1230  }
1231  }
1232 
1233  // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1234  array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1235 
1236  // Create a list like "en" => 0.8
1237  $langs = array_combine( $langcodes, $qvalues );
1238 
1239  return $langs;
1240  }
1241 
1250  protected function getRawIP() {
1251  if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1252  return null;
1253  }
1254 
1255  if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1256  throw new MWException( __METHOD__
1257  . " : Could not determine the remote IP address due to multiple values." );
1258  } else {
1259  $ipchain = $_SERVER['REMOTE_ADDR'];
1260  }
1261 
1262  return IP::canonicalize( $ipchain );
1263  }
1264 
1274  public function getIP() {
1275  global $wgUsePrivateIPs;
1276 
1277  # Return cached result
1278  if ( $this->ip !== null ) {
1279  return $this->ip;
1280  }
1281 
1282  # collect the originating ips
1283  $ip = $this->getRawIP();
1284  if ( !$ip ) {
1285  throw new MWException( 'Unable to determine IP.' );
1286  }
1287 
1288  # Append XFF
1289  $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1290  if ( $forwardedFor !== false ) {
1291  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1292  $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1293  $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1294  $ipchain = array_reverse( $ipchain );
1295  array_unshift( $ipchain, $ip );
1296 
1297  # Step through XFF list and find the last address in the list which is a
1298  # trusted server. Set $ip to the IP address given by that trusted server,
1299  # unless the address is not sensible (e.g. private). However, prefer private
1300  # IP addresses over proxy servers controlled by this site (more sensible).
1301  # Note that some XFF values might be "unknown" with Squid/Varnish.
1302  foreach ( $ipchain as $i => $curIP ) {
1303  $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1304  if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1305  || !$proxyLookup->isTrustedProxy( $curIP )
1306  ) {
1307  break; // IP is not valid/trusted or does not point to anything
1308  }
1309  if (
1310  IP::isPublic( $ipchain[$i + 1] ) ||
1311  $wgUsePrivateIPs ||
1312  $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1313  ) {
1314  // Follow the next IP according to the proxy
1315  $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1316  if ( !$nextIP && $isConfigured ) {
1317  // We have not yet made it past CDN/proxy servers of this site,
1318  // so either they are misconfigured or there is some IP spoofing.
1319  throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1320  }
1321  $ip = $nextIP;
1322  // keep traversing the chain
1323  continue;
1324  }
1325  break;
1326  }
1327  }
1328 
1329  # Allow extensions to improve our guess
1330  Hooks::run( 'GetIP', [ &$ip ] );
1331 
1332  if ( !$ip ) {
1333  throw new MWException( "Unable to determine IP." );
1334  }
1335 
1336  wfDebug( "IP: $ip\n" );
1337  $this->ip = $ip;
1338  return $ip;
1339  }
1340 
1346  public function setIP( $ip ) {
1347  $this->ip = $ip;
1348  }
1349 
1362  public function hasSafeMethod() {
1363  if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1364  return false; // CLI mode
1365  }
1366 
1367  return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1368  }
1369 
1388  public function isSafeRequest() {
1389  if ( $this->markedAsSafe && $this->wasPosted() ) {
1390  return true; // marked as a "safe" POST
1391  }
1392 
1393  return $this->hasSafeMethod();
1394  }
1395 
1406  public function markAsSafeRequest() {
1407  $this->markedAsSafe = true;
1408  }
1409 }
PathRouter\add
add( $path, $params=[], $options=[])
Add a new path pattern to the path router.
Definition: PathRouter.php:158
WebRequest\initHeaders
initHeaders()
Initialise the header list.
Definition: WebRequest.php:1048
WebRequest\$sessionId
SessionId null $sessionId
Session ID to use for this request.
Definition: WebRequest.php:108
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
WebRequest\getSessionData
getSessionData( $key)
Get data from the session.
Definition: WebRequest.php:1112
WebRequest\$headers
array $headers
Lazy-initialized request headers indexed by upper-case header name.
Definition: WebRequest.php:65
$wgActionPaths
$wgActionPaths
Definition: img_auth.php:48
WebRequest\getValueNames
getValueNames( $exclude=[])
Returns the names of all input values excluding those in $exclude.
Definition: WebRequest.php:687
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
IP\combineHostAndPort
static combineHostAndPort( $host, $port, $defaultPort=false)
Given a host name and a port, combine them into host/port string like you might find in a URL.
Definition: IP.php:302
WebRequest\$data
array $data
The parameters from $_GET, $_POST and the path router.
Definition: WebRequest.php:47
WebRequest\getSessionId
getSessionId()
Get the session id for this request, if any.
Definition: WebRequest.php:827
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:185
WebRequest\$queryParams
$queryParams
The parameters from $_GET only.
Definition: WebRequest.php:59
WebRequest\appendQueryValue
appendQueryValue( $key, $value)
Definition: WebRequest.php:930
WebRequest\interpolateTitle
interpolateTitle()
Check for title, action, and/or variant data in the URL and interpolate it into the GET variables.
Definition: WebRequest.php:352
WebRequest\setSessionId
setSessionId(SessionId $sessionId)
Set the session for this request.
Definition: WebRequest.php:817
WebRequest\getElapsedTime
getElapsedTime()
Get the number of seconds to have elapsed since request start, in fractional seconds,...
Definition: WebRequest.php:291
WebRequest\getIntOrNull
getIntOrNull( $name)
Fetch an integer value from the input or return null if empty.
Definition: WebRequest.php:581
IP
A collection of public static functions to play with IP address and IP ranges.
Definition: IP.php:67
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
WebRequest\getRawPostString
getRawPostString()
Return the contents of the POST with no decoding.
Definition: WebRequest.php:744
WebRequest\detectProtocol
static detectProtocol()
Detect the protocol from $_SERVER.
Definition: WebRequest.php:274
WebRequest\getGPCVal
getGPCVal( $arr, $name, $default)
Fetch a value from the given array or return $default if it's not set.
Definition: WebRequest.php:421
$base
$base
Definition: generateLocalAutoload.php:11
HttpError
Show an error that looks like an HTTP server error.
Definition: HttpError.php:30
WebRequest\__construct
__construct()
Definition: WebRequest.php:116
WebRequest\getRawQueryString
getRawQueryString()
Return the contents of the Query with no decoding.
Definition: WebRequest.php:734
WebRequest\appendQueryArray
appendQueryArray( $array)
Appends or replaces value of query variables.
Definition: WebRequest.php:940
$wgAllowExternalReqID
$wgAllowExternalReqID
Whether to respect/honour the request ID provided by the incoming request via the X-Request-Id header...
Definition: DefaultSettings.php:8446
PathRouter\getActionPaths
static getActionPaths(array $actionPaths, $articlePath)
Definition: PathRouter.php:411
WebRequest\getFileTempname
getFileTempname( $key)
Return the path to the temporary file where PHP has stored the upload.
Definition: WebRequest.php:988
$wgAssumeProxiesUseDefaultProtocolPorts
bool $wgAssumeProxiesUseDefaultProtocolPorts
When the wiki is running behind a proxy and this is set to true, assumes that the proxy exposes the w...
Definition: DefaultSettings.php:88
WebRequest\getText
getText( $name, $default='')
Fetch a text string from the given array or return $default if it's not set.
Definition: WebRequest.php:653
WebRequest\$protocol
string $protocol
Cached URL protocol.
Definition: WebRequest.php:101
WebRequest\getMethod
getMethod()
Get the HTTP method used for this request.
Definition: WebRequest.php:771
MWException
MediaWiki exception.
Definition: MWException.php:26
WebRequest\getFileName
getFileName( $key)
Return the original filename of the uploaded file, as reported by the submitting user agent.
Definition: WebRequest.php:1015
WebRequest\getQueryValuesOnly
getQueryValuesOnly()
Get the values passed in the query string only, not including the path router parameters.
Definition: WebRequest.php:711
MediaWiki\Session\Session
Manages data for an an authenticated session.
Definition: Session.php:48
WebRequest\setVal
setVal( $key, $value)
Set an arbitrary value into our get/post data.
Definition: WebRequest.php:502
WebRequest\$reqId
static string $reqId
The unique request ID.
Definition: WebRequest.php:77
$matches
$matches
Definition: NoLocalSettings.php:24
WebRequest\getRawInput
getRawInput()
Return the raw request body, with no processing.
Definition: WebRequest.php:758
WebRequest\getUpload
getUpload( $key)
Return a WebRequestUpload object corresponding to the key.
Definition: WebRequest.php:1026
WebRequest\getValues
getValues()
Extracts the given named values into an array.
Definition: WebRequest.php:665
WebRequest\getPathInfo
static getPathInfo( $want='all')
Extract relevant query arguments from the http request uri's path to be merged with the normal php pr...
Definition: WebRequest.php:141
WebRequest\getFullRequestURL
getFullRequestURL()
Return the request URI with the canonical service and hostname, path, and query string.
Definition: WebRequest.php:914
WebRequest\getArray
getArray( $name, $default=null)
Fetch an array from the input or return $default if it's not set.
Definition: WebRequest.php:533
WebRequest\$response
WebResponse $response
Lazy-init response object.
Definition: WebRequest.php:83
WebRequest\getAllHeaders
getAllHeaders()
Get an array containing all request headers.
Definition: WebRequest.php:1075
WebRequestUpload
Object to access the $_FILES array.
Definition: WebRequestUpload.php:30
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:200
WebRequest\normalizeUnicode
normalizeUnicode( $data)
Recursively normalizes UTF-8 strings in the given array.
Definition: WebRequest.php:400
WebRequest\getRawVal
getRawVal( $name, $default=null)
Fetch a scalar from the input without normalization, or return $default if it's not set.
Definition: WebRequest.php:459
IEUrlExtension\areServerVarsBad
static areServerVarsBad( $vars, $extWhitelist=[])
Check a subset of $_SERVER (or the whole of $_SERVER if you like) to see if it indicates that the req...
Definition: IEUrlExtension.php:62
WebRequest\getCheck
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
Definition: WebRequest.php:637
WebRequest\getProtocol
getProtocol()
Get the current URL protocol (http or https)
Definition: WebRequest.php:338
WebRequest\getSession
getSession()
Return the session for this request.
Definition: WebRequest.php:798
WebRequest\response
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
Definition: WebRequest.php:1036
IP\splitHostAndPort
static splitHostAndPort( $both)
Given a host/port string, like one might find in the host part of a URL per RFC 2732,...
Definition: IP.php:253
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:50
WebRequest\getLimitOffset
getLimitOffset( $deflimit=50, $optionname='rclimit')
Check for limit and offset parameters on the input, and return sensible defaults if not given.
Definition: WebRequest.php:957
WebRequest\checkUrlExtension
checkUrlExtension( $extWhitelist=[])
Check if Internet Explorer will detect an incorrect cache extension in PATH_INFO or QUERY_STRING.
Definition: WebRequest.php:1137
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:199
WebRequest\getIntArray
getIntArray( $name, $default=null)
Fetch an array of integers, or return $default if it's not set.
Definition: WebRequest.php:552
WebRequest\$requestTime
float $requestTime
The timestamp of the start of the request, with microsecond precision.
Definition: WebRequest.php:95
IEUrlExtension\fixUrlForIE6
static fixUrlForIE6( $url, $extWhitelist=[])
Returns a variant of $url which will pass isUrlExtensionBad() but has the same GET parameters,...
Definition: IEUrlExtension.php:140
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:431
WebRequest\$markedAsSafe
bool $markedAsSafe
Whether this HTTP request is "safe" (even if it is an HTTP post)
Definition: WebRequest.php:111
WebRequest\getCookie
getCookie( $key, $prefix=null, $default=null)
Get a cookie from the $_COOKIE jar.
Definition: WebRequest.php:839
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
WebRequest\getUploadError
getUploadError( $key)
Return the upload error or 0.
Definition: WebRequest.php:999
WebRequest\$queryAndPathParams
array $queryAndPathParams
The parameters from $_GET.
Definition: WebRequest.php:54
$wgArticlePath
$wgArticlePath
Definition: img_auth.php:47
WebRequest\setSessionData
setSessionData( $key, $data)
Set session data.
Definition: WebRequest.php:1123
WebRequest\doSecurityRedirect
doSecurityRedirect( $url)
Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in IE 6.
Definition: WebRequest.php:1161
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:71
WebRequest\getVal
getVal( $name, $default=null)
Fetch a scalar from the input or return $default if it's not set.
Definition: WebRequest.php:483
WebRequest\getInt
getInt( $name, $default=0)
Fetch an integer value from the input or return $default if not set.
Definition: WebRequest.php:569
MediaWiki\Session\SessionId
Value object holding the session ID in a manner that can be globally updated.
Definition: SessionId.php:38
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:303
$path
$path
Definition: NoLocalSettings.php:25
WebRequest\getFloat
getFloat( $name, $default=0.0)
Fetch a floating point value from the input or return $default if not set.
Definition: WebRequest.php:598
WebRequest\detectServer
static detectServer()
Work out an appropriate URL prefix containing scheme and host, based on information detected from $_S...
Definition: WebRequest.php:228
WebRequest\getHeader
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
Definition: WebRequest.php:1092
WebRequest\getGlobalRequestURL
static getGlobalRequestURL()
Return the path and query string portion of the main request URI.
Definition: WebRequest.php:854
WebRequest\$ip
string $ip
Cached client IP address.
Definition: WebRequest.php:89
WebRequest\getPostValues
getPostValues()
Get the values passed via POST.
Definition: WebRequest.php:723
WebRequest\wasPosted
wasPosted()
Returns true if the present request was reached by a POST operation, false otherwise (GET,...
Definition: WebRequest.php:784
WebRequest\unsetVal
unsetVal( $key)
Unset an arbitrary value from our get/post data.
Definition: WebRequest.php:514
wfGetServerUrl
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
Definition: GlobalFunctions.php:569
WebRequest\getRequestURL
getRequestURL()
Return the path and query string portion of the request URI.
Definition: WebRequest.php:900
WebRequest\overrideRequestId
static overrideRequestId( $id)
Override the unique request ID.
Definition: WebRequest.php:330
WebRequest\extractTitle
static extractTitle( $path, $bases, $key=false)
URL rewriting function; tries to extract page title and, optionally, one other fixed parameter value ...
Definition: WebRequest.php:374
WebResponse
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:28
WebRequest\getQueryValues
getQueryValues()
Get the values passed in the query string and the path router parameters.
Definition: WebRequest.php:698
WebRequest\getFuzzyBool
getFuzzyBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
Definition: WebRequest.php:624
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
$wgVariantArticlePath
$wgVariantArticlePath
Like $wgArticlePath, but on multi-variant wikis, this provides a path format that describes which par...
Definition: DefaultSettings.php:3162
PathRouter
PathRouter class.
Definition: PathRouter.php:73
$wgCookiePrefix
$wgCookiePrefix
Cookies generated by MediaWiki have names starting with this prefix.
Definition: DefaultSettings.php:6054
Language
Internationalisation code.
Definition: Language.php:37
WebRequest\getBool
getBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
Definition: WebRequest.php:611
$wgUsePathInfo
$wgUsePathInfo
Whether to support URLs like index.php/Page_title These often break when PHP is set up in CGI mode.
Definition: DefaultSettings.php:156
wfArrayToCgi
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
Definition: GlobalFunctions.php:347
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:274