MediaWiki  master
WebRequest.php
Go to the documentation of this file.
1 <?php
30 use Wikimedia\IPUtils;
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 
60  protected $queryParams;
61 
66  protected $headers = [];
67 
72  public const GETHEADER_LIST = 1;
73 
78  private static $reqId;
79 
84  private $response;
85 
90  private $ip;
91 
96  protected $requestTime;
97 
102  protected $protocol;
103 
112  protected $sessionId = null;
113 
115  protected $markedAsSafe = false;
116 
120  public function __construct() {
121  $this->requestTime = $_SERVER['REQUEST_TIME_FLOAT'];
122 
123  // POST overrides GET data
124  // We don't use $_REQUEST here to avoid interference from cookies...
125  $this->data = $_POST + $_GET;
126 
127  $this->queryAndPathParams = $this->queryParams = $_GET;
128  }
129 
150  protected static function getPathInfo( $want = 'all' ) {
151  // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
152  // And also by Apache 2.x, double slashes are converted to single slashes.
153  // So we will use REQUEST_URI if possible.
154  if ( isset( $_SERVER['REQUEST_URI'] ) ) {
155  // Slurp out the path portion to examine...
156  $url = $_SERVER['REQUEST_URI'];
157  if ( !preg_match( '!^https?://!', $url ) ) {
158  $url = 'http://unused' . $url;
159  }
160  $a = parse_url( $url );
161  if ( !$a ) {
162  return [];
163  }
164  $path = $a['path'] ?? '';
165 
166  global $wgScript;
167  if ( $path == $wgScript && $want !== 'all' ) {
168  // Script inside a rewrite path?
169  // Abort to keep from breaking...
170  return [];
171  }
172 
173  $router = new PathRouter;
174 
175  // Raw PATH_INFO style
176  $router->add( "$wgScript/$1" );
177 
178  global $wgArticlePath;
179  if ( $wgArticlePath ) {
180  $router->validateRoute( $wgArticlePath, 'wgArticlePath' );
181  $router->add( $wgArticlePath );
182  }
183 
184  global $wgActionPaths;
186  if ( $articlePaths ) {
187  $router->add( $articlePaths, [ 'action' => '$key' ] );
188  }
189 
190  global $wgVariantArticlePath;
191  if ( $wgVariantArticlePath ) {
192  $router->validateRoute( $wgVariantArticlePath, 'wgVariantArticlePath' );
193  $router->add( $wgVariantArticlePath,
194  [ 'variant' => '$2' ],
195  [ '$2' => MediaWikiServices::getInstance()->getContentLanguage()->
196  getVariants() ]
197  );
198  }
199 
200  Hooks::runner()->onWebRequestPathInfoRouter( $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 
233  public static function getRequestPathSuffix( $basePath ) {
234  $basePath = rtrim( $basePath, '/' ) . '/';
235  $requestUrl = self::getGlobalRequestURL();
236  $qpos = strpos( $requestUrl, '?' );
237  if ( $qpos !== false ) {
238  $requestPath = substr( $requestUrl, 0, $qpos );
239  } else {
240  $requestPath = $requestUrl;
241  }
242  if ( substr( $requestPath, 0, strlen( $basePath ) ) !== $basePath ) {
243  return false;
244  }
245  return rawurldecode( substr( $requestPath, strlen( $basePath ) ) );
246  }
247 
254  public static function detectServer() {
256 
257  $proto = self::detectProtocol();
258  $stdPort = $proto === 'https' ? 443 : 80;
259 
260  $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
261  $host = 'localhost';
262  $port = $stdPort;
263  foreach ( $varNames as $varName ) {
264  if ( !isset( $_SERVER[$varName] ) ) {
265  continue;
266  }
267 
268  $parts = IPUtils::splitHostAndPort( $_SERVER[$varName] );
269  if ( !$parts ) {
270  // Invalid, do not use
271  continue;
272  }
273 
274  $host = $parts[0];
275  if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
276  // T72021: Assume that upstream proxy is running on the default
277  // port based on the protocol. We have no reliable way to determine
278  // the actual port in use upstream.
279  $port = $stdPort;
280  } elseif ( $parts[1] === false ) {
281  if ( isset( $_SERVER['SERVER_PORT'] ) ) {
282  $port = $_SERVER['SERVER_PORT'];
283  } // else leave it as $stdPort
284  } else {
285  $port = $parts[1];
286  }
287  break;
288  }
289 
290  return $proto . '://' . IPUtils::combineHostAndPort( $host, $port, $stdPort );
291  }
292 
300  public static function detectProtocol() {
301  if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
302  ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
303  $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
304  return 'https';
305  } else {
306  return 'http';
307  }
308  }
309 
317  public function getElapsedTime() {
318  return microtime( true ) - $this->requestTime;
319  }
320 
330  public static function getRequestId() {
331  // This method is called from various error handlers and MUST be kept simple and stateless.
332  if ( !self::$reqId ) {
333  global $wgAllowExternalReqID;
334  if ( $wgAllowExternalReqID ) {
335  $id = $_SERVER['HTTP_X_REQUEST_ID'] ?? $_SERVER['UNIQUE_ID'] ?? wfRandomString( 24 );
336  } else {
337  $id = $_SERVER['UNIQUE_ID'] ?? wfRandomString( 24 );
338  }
339  self::$reqId = $id;
340  }
341 
342  return self::$reqId;
343  }
344 
352  public static function overrideRequestId( $id ) {
353  self::$reqId = $id;
354  }
355 
360  public function getProtocol() {
361  if ( $this->protocol === null ) {
362  $this->protocol = self::detectProtocol();
363  }
364  return $this->protocol;
365  }
366 
374  public function interpolateTitle() {
375  $matches = self::getPathInfo( 'title' );
376  foreach ( $matches as $key => $val ) {
377  $this->data[$key] = $this->queryAndPathParams[$key] = $val;
378  }
379  }
380 
391  public static function extractTitle( $path, $bases, $key = false ) {
392  foreach ( (array)$bases as $keyValue => $base ) {
393  // Find the part after $wgArticlePath
394  $base = str_replace( '$1', '', $base );
395  $baseLen = strlen( $base );
396  if ( substr( $path, 0, $baseLen ) == $base ) {
397  $raw = substr( $path, $baseLen );
398  if ( $raw !== '' ) {
399  $matches = [ 'title' => rawurldecode( $raw ) ];
400  if ( $key ) {
401  $matches[$key] = $keyValue;
402  }
403  return $matches;
404  }
405  }
406  }
407  return [];
408  }
409 
417  public function normalizeUnicode( $data ) {
418  if ( is_array( $data ) ) {
419  foreach ( $data as $key => $val ) {
420  $data[$key] = $this->normalizeUnicode( $val );
421  }
422  } else {
423  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
424  $data = $contLang->normalize( $data );
425  }
426  return $data;
427  }
428 
437  private function getGPCVal( $arr, $name, $default ) {
438  # PHP is so nice to not touch input data, except sometimes:
439  # https://www.php.net/variables.external#language.variables.external.dot-in-names
440  # Work around PHP *feature* to avoid *bugs* elsewhere.
441  $name = strtr( $name, '.', '_' );
442 
443  if ( !isset( $arr[$name] ) ) {
444  return $default;
445  }
446 
447  $data = $arr[$name];
448  # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
449  $isAsciiStr = ( is_string( $data ) && preg_match( '/[^\x20-\x7E]/', $data ) === 0 );
450  if ( !$isAsciiStr ) {
451  if ( isset( $_GET[$name] ) && is_string( $data ) ) {
452  # Check for alternate/legacy character encoding.
453  $data = MediaWikiServices::getInstance()
454  ->getContentLanguage()
455  ->checkTitleEncoding( $data );
456  }
457  $data = $this->normalizeUnicode( $data );
458  }
459 
460  return $data;
461  }
462 
475  public function getRawVal( $name, $default = null ) {
476  $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
477  if ( isset( $this->data[$name] ) && !is_array( $this->data[$name] ) ) {
478  $val = $this->data[$name];
479  } else {
480  $val = $default;
481  }
482  if ( $val === null ) {
483  return $val;
484  } else {
485  return (string)$val;
486  }
487  }
488 
499  public function getVal( $name, $default = null ) {
500  $val = $this->getGPCVal( $this->data, $name, $default );
501  if ( is_array( $val ) ) {
502  $val = $default;
503  }
504  if ( $val === null ) {
505  return $val;
506  } else {
507  return (string)$val;
508  }
509  }
510 
518  public function setVal( $key, $value ) {
519  $ret = $this->data[$key] ?? null;
520  $this->data[$key] = $value;
521  return $ret;
522  }
523 
530  public function unsetVal( $key ) {
531  if ( !isset( $this->data[$key] ) ) {
532  $ret = null;
533  } else {
534  $ret = $this->data[$key];
535  unset( $this->data[$key] );
536  }
537  return $ret;
538  }
539 
549  public function getArray( $name, $default = null ) {
550  $val = $this->getGPCVal( $this->data, $name, $default );
551  if ( $val === null ) {
552  return null;
553  } else {
554  return (array)$val;
555  }
556  }
557 
568  public function getIntArray( $name, $default = null ) {
569  $val = $this->getArray( $name, $default );
570  if ( is_array( $val ) ) {
571  $val = array_map( 'intval', $val );
572  }
573  return $val;
574  }
575 
585  public function getInt( $name, $default = 0 ) {
586  return intval( $this->getRawVal( $name, $default ) );
587  }
588 
597  public function getIntOrNull( $name ) {
598  $val = $this->getRawVal( $name );
599  return is_numeric( $val )
600  ? intval( $val )
601  : null;
602  }
603 
614  public function getFloat( $name, $default = 0.0 ) {
615  return floatval( $this->getRawVal( $name, $default ) );
616  }
617 
627  public function getBool( $name, $default = false ) {
628  return (bool)$this->getRawVal( $name, $default );
629  }
630 
640  public function getFuzzyBool( $name, $default = false ) {
641  return $this->getBool( $name, $default )
642  && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
643  }
644 
653  public function getCheck( $name ) {
654  # Checkboxes and buttons are only present when clicked
655  # Presence connotes truth, absence false
656  return $this->getRawVal( $name, null ) !== null;
657  }
658 
669  public function getText( $name, $default = '' ) {
670  $val = $this->getVal( $name, $default );
671  return str_replace( "\r\n", "\n", $val );
672  }
673 
681  public function getValues( ...$names ) {
682  if ( $names === [] ) {
683  $names = array_keys( $this->data );
684  }
685 
686  $retVal = [];
687  foreach ( $names as $name ) {
688  $value = $this->getGPCVal( $this->data, $name, null );
689  if ( $value !== null ) {
690  $retVal[$name] = $value;
691  }
692  }
693  return $retVal;
694  }
695 
702  public function getValueNames( $exclude = [] ) {
703  return array_diff( array_keys( $this->getValues() ), $exclude );
704  }
705 
713  public function getQueryValues() {
715  }
716 
726  public function getQueryValuesOnly() {
727  return $this->queryParams;
728  }
729 
738  public function getPostValues() {
739  return $_POST;
740  }
741 
749  public function getRawQueryString() {
750  return $_SERVER['QUERY_STRING'];
751  }
752 
759  public function getRawPostString() {
760  if ( !$this->wasPosted() ) {
761  return '';
762  }
763  return $this->getRawInput();
764  }
765 
773  public function getRawInput() {
774  static $input = null;
775  if ( $input === null ) {
776  $input = file_get_contents( 'php://input' );
777  }
778  return $input;
779  }
780 
786  public function getMethod() {
787  return $_SERVER['REQUEST_METHOD'] ?? 'GET';
788  }
789 
799  public function wasPosted() {
800  return $this->getMethod() == 'POST';
801  }
802 
813  public function getSession() {
814  if ( $this->sessionId !== null ) {
815  $session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
816  if ( $session ) {
817  return $session;
818  }
819  }
820 
821  $session = SessionManager::singleton()->getSessionForRequest( $this );
822  $this->sessionId = $session->getSessionId();
823  return $session;
824  }
825 
832  public function setSessionId( SessionId $sessionId ) {
833  $this->sessionId = $sessionId;
834  }
835 
842  public function getSessionId() {
843  return $this->sessionId;
844  }
845 
854  public function getCookie( $key, $prefix = null, $default = null ) {
855  if ( $prefix === null ) {
856  global $wgCookiePrefix;
857  $prefix = $wgCookiePrefix;
858  }
859  $name = $prefix . $key;
860  // Work around mangling of $_COOKIE
861  $name = strtr( $name, '.', '_' );
862  if ( isset( $_COOKIE[$name] ) ) {
863  return $_COOKIE[$name];
864  } else {
865  return $default;
866  }
867  }
868 
877  public function getCrossSiteCookie( $key, $prefix = '', $default = null ) {
879  $name = $prefix . $key;
880  // Work around mangling of $_COOKIE
881  $name = strtr( $name, '.', '_' );
882  if ( isset( $_COOKIE[$name] ) ) {
883  return $_COOKIE[$name];
884  }
886  $legacyName = $prefix . "ss0-" . $key;
887  $legacyName = strtr( $legacyName, '.', '_' );
888  if ( isset( $_COOKIE[$legacyName] ) ) {
889  return $_COOKIE[$legacyName];
890  }
891  }
892  return $default;
893  }
894 
902  public static function getGlobalRequestURL() {
903  // This method is called on fatal errors; it should not depend on anything complex.
904 
905  if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
906  $base = $_SERVER['REQUEST_URI'];
907  } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
908  && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
909  ) {
910  // Probably IIS; doesn't set REQUEST_URI
911  $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
912  } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
913  $base = $_SERVER['SCRIPT_NAME'];
914  if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
915  $base .= '?' . $_SERVER['QUERY_STRING'];
916  }
917  } else {
918  // This shouldn't happen!
919  throw new MWException( "Web server doesn't provide either " .
920  "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
921  "of your web server configuration to https://phabricator.wikimedia.org/" );
922  }
923  // User-agents should not send a fragment with the URI, but
924  // if they do, and the web server passes it on to us, we
925  // need to strip it or we get false-positive redirect loops
926  // or weird output URLs
927  $hash = strpos( $base, '#' );
928  if ( $hash !== false ) {
929  $base = substr( $base, 0, $hash );
930  }
931 
932  if ( $base[0] == '/' ) {
933  // More than one slash will look like it is protocol relative
934  return preg_replace( '!^/+!', '/', $base );
935  } else {
936  // We may get paths with a host prepended; strip it.
937  return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
938  }
939  }
940 
948  public function getRequestURL() {
949  return self::getGlobalRequestURL();
950  }
951 
962  public function getFullRequestURL() {
963  // Pass an explicit PROTO constant instead of PROTO_CURRENT so that we
964  // do not rely on state from the global $wgRequest object (which it would,
965  // via wfGetServerUrl/wfExpandUrl/$wgRequest->protocol).
966  if ( $this->getProtocol() === 'http' ) {
967  return wfGetServerUrl( PROTO_HTTP ) . $this->getRequestURL();
968  } else {
969  return wfGetServerUrl( PROTO_HTTPS ) . $this->getRequestURL();
970  }
971  }
972 
978  public function appendQueryValue( $key, $value ) {
979  return $this->appendQueryArray( [ $key => $value ] );
980  }
981 
988  public function appendQueryArray( $array ) {
989  $newquery = $this->getQueryValues();
990  unset( $newquery['title'] );
991  $newquery = array_merge( $newquery, $array );
992 
993  return wfArrayToCgi( $newquery );
994  }
995 
1006  public function getLimitOffsetForUser( User $user, $deflimit = 50, $optionname = 'rclimit' ) {
1007  $limit = $this->getInt( 'limit', 0 );
1008  if ( $limit < 0 ) {
1009  $limit = 0;
1010  }
1011  if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
1012  $limit = $user->getIntOption( $optionname );
1013  }
1014  if ( $limit <= 0 ) {
1015  $limit = $deflimit;
1016  }
1017  if ( $limit > 5000 ) {
1018  $limit = 5000; # We have *some* limits...
1019  }
1020 
1021  $offset = $this->getInt( 'offset', 0 );
1022  if ( $offset < 0 ) {
1023  $offset = 0;
1024  }
1025 
1026  return [ $limit, $offset ];
1027  }
1028 
1035  public function getFileTempname( $key ) {
1036  return $this->getUpload( $key )->getTempName();
1037  }
1038 
1045  public function getUploadError( $key ) {
1046  return $this->getUpload( $key )->getError();
1047  }
1048 
1060  public function getFileName( $key ) {
1061  return $this->getUpload( $key )->getName();
1062  }
1063 
1070  public function getUpload( $key ) {
1071  return new WebRequestUpload( $this, $key );
1072  }
1073 
1080  public function response() {
1081  /* Lazy initialization of response object for this request */
1082  if ( !is_object( $this->response ) ) {
1083  $class = ( $this instanceof FauxRequest ) ? FauxResponse::class : WebResponse::class;
1084  $this->response = new $class();
1085  }
1086  return $this->response;
1087  }
1088 
1092  protected function initHeaders() {
1093  if ( count( $this->headers ) ) {
1094  return;
1095  }
1096 
1097  $this->headers = array_change_key_case( getallheaders(), CASE_UPPER );
1098  }
1099 
1105  public function getAllHeaders() {
1106  $this->initHeaders();
1107  return $this->headers;
1108  }
1109 
1122  public function getHeader( $name, $flags = 0 ) {
1123  $this->initHeaders();
1124  $name = strtoupper( $name );
1125  if ( !isset( $this->headers[$name] ) ) {
1126  return false;
1127  }
1128  $value = $this->headers[$name];
1129  if ( $flags & self::GETHEADER_LIST ) {
1130  $value = array_map( 'trim', explode( ',', $value ) );
1131  }
1132  return $value;
1133  }
1134 
1142  public function getSessionData( $key ) {
1143  return $this->getSession()->get( $key );
1144  }
1145 
1151  public function setSessionData( $key, $data ) {
1152  $this->getSession()->set( $key, $data );
1153  }
1154 
1164  public function checkUrlExtension( $extList = [] ) {
1165  wfDeprecated( __METHOD__, '1.35' );
1166  return true;
1167  }
1168 
1182  public function getAcceptLang() {
1183  // Modified version of code found at
1184  // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1185  $acceptLang = $this->getHeader( 'Accept-Language' );
1186  if ( !$acceptLang ) {
1187  return [];
1188  }
1189 
1190  // Return the language codes in lower case
1191  $acceptLang = strtolower( $acceptLang );
1192 
1193  // Break up string into pieces (languages and q factors)
1194  if ( !preg_match_all(
1195  '/
1196  # a language code or a star is required
1197  ([a-z]{1,8}(?:-[a-z]{1,8})*|\*)
1198  # from here everything is optional
1199  \s*
1200  (?:
1201  # this accepts only numbers in the range ;q=0.000 to ;q=1.000
1202  ;\s*q\s*=\s*
1203  (1(?:\.0{0,3})?|0(?:\.\d{0,3})?)?
1204  )?
1205  /x',
1206  $acceptLang,
1207  $matches,
1208  PREG_SET_ORDER
1209  ) ) {
1210  return [];
1211  }
1212 
1213  // Create a list like "en" => 0.8
1214  $langs = [];
1215  foreach ( $matches as $match ) {
1216  $languageCode = $match[1];
1217  // When not present, the default value is 1
1218  $qValue = (float)( $match[2] ?? 1.0 );
1219  if ( $qValue ) {
1220  $langs[$languageCode] = $qValue;
1221  }
1222  }
1223 
1224  // Sort list by qValue
1225  arsort( $langs, SORT_NUMERIC );
1226  return $langs;
1227  }
1228 
1237  protected function getRawIP() {
1238  if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1239  return null;
1240  }
1241 
1242  if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1243  throw new MWException( __METHOD__
1244  . " : Could not determine the remote IP address due to multiple values." );
1245  } else {
1246  $ipchain = $_SERVER['REMOTE_ADDR'];
1247  }
1248 
1249  return IPUtils::canonicalize( $ipchain );
1250  }
1251 
1261  public function getIP() {
1262  global $wgUsePrivateIPs;
1263 
1264  # Return cached result
1265  if ( $this->ip !== null ) {
1266  return $this->ip;
1267  }
1268 
1269  # collect the originating ips
1270  $ip = $this->getRawIP();
1271  if ( !$ip ) {
1272  throw new MWException( 'Unable to determine IP.' );
1273  }
1274 
1275  # Append XFF
1276  $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1277  if ( $forwardedFor !== false ) {
1278  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1279  $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1280  $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1281  $ipchain = array_reverse( $ipchain );
1282  array_unshift( $ipchain, $ip );
1283 
1284  # Step through XFF list and find the last address in the list which is a
1285  # trusted server. Set $ip to the IP address given by that trusted server,
1286  # unless the address is not sensible (e.g. private). However, prefer private
1287  # IP addresses over proxy servers controlled by this site (more sensible).
1288  # Note that some XFF values might be "unknown" with Squid/Varnish.
1289  foreach ( $ipchain as $i => $curIP ) {
1290  $curIP = IPUtils::sanitizeIP(
1291  IPUtils::canonicalize(
1292  self::canonicalizeIPv6LoopbackAddress( $curIP )
1293  )
1294  );
1295  if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1296  || !$proxyLookup->isTrustedProxy( $curIP )
1297  ) {
1298  break; // IP is not valid/trusted or does not point to anything
1299  }
1300  if (
1301  IPUtils::isPublic( $ipchain[$i + 1] ) ||
1302  $wgUsePrivateIPs ||
1303  $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1304  ) {
1305  $nextIP = $ipchain[$i + 1];
1306 
1307  // Follow the next IP according to the proxy
1308  $nextIP = IPUtils::canonicalize(
1309  self::canonicalizeIPv6LoopbackAddress( $nextIP )
1310  );
1311  if ( !$nextIP && $isConfigured ) {
1312  // We have not yet made it past CDN/proxy servers of this site,
1313  // so either they are misconfigured or there is some IP spoofing.
1314  throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1315  }
1316  $ip = $nextIP;
1317 
1318  // keep traversing the chain
1319  continue;
1320  }
1321  break;
1322  }
1323  }
1324 
1325  # Allow extensions to improve our guess
1326  Hooks::runner()->onGetIP( $ip );
1327 
1328  if ( !$ip ) {
1329  throw new MWException( "Unable to determine IP." );
1330  }
1331 
1332  $this->ip = $ip;
1333  return $ip;
1334  }
1335 
1344  public static function canonicalizeIPv6LoopbackAddress( $ip ) {
1345  // Code moved from IPUtils library. See T248237#6614927
1346  $m = [];
1347  if ( preg_match( '/^0*' . IPUtils::RE_IPV6_GAP . '1$/', $ip, $m ) ) {
1348  return '127.0.0.1';
1349  }
1350  return $ip;
1351  }
1352 
1358  public function setIP( $ip ) {
1359  $this->ip = $ip;
1360  }
1361 
1374  public function hasSafeMethod() {
1375  if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1376  return false; // CLI mode
1377  }
1378 
1379  return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1380  }
1381 
1400  public function isSafeRequest() {
1401  if ( $this->markedAsSafe && $this->wasPosted() ) {
1402  return true; // marked as a "safe" POST
1403  }
1404 
1405  return $this->hasSafeMethod();
1406  }
1407 
1418  public function markAsSafeRequest() {
1419  $this->markedAsSafe = true;
1420  }
1421 }
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:1092
WebRequest\$sessionId
SessionId null $sessionId
Session ID to use for this request.
Definition: WebRequest.php:112
WebRequest\$headers
string[] $headers
Lazy-initialized request headers indexed by upper-case header name.
Definition: WebRequest.php:66
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:35
WebRequest\getSessionData
getSessionData( $key)
Get data from the session.
Definition: WebRequest.php:1142
WebRequest\getValueNames
getValueNames( $exclude=[])
Returns the names of all input values excluding those in $exclude.
Definition: WebRequest.php:702
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:193
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:186
WebRequest\$data
array $data
The parameters from $_GET, $_POST and the path router.
Definition: WebRequest.php:47
WebRequest\getRequestPathSuffix
static getRequestPathSuffix( $basePath)
If the request URL matches a given base path, extract the path part of the request URL after that bas...
Definition: WebRequest.php:233
WebRequest\getSessionId
getSessionId()
Get the session id for this request, if any.
Definition: WebRequest.php:842
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:204
User\getIntOption
getIntOption( $oname, $defaultOverride=0)
Get the user's current setting for a given option, as an integer value.
Definition: User.php:2600
WebRequest\appendQueryValue
appendQueryValue( $key, $value)
Definition: WebRequest.php:978
WebRequest\interpolateTitle
interpolateTitle()
Check for title, action, and/or variant data in the URL and interpolate it into the GET variables.
Definition: WebRequest.php:374
WebRequest\setSessionId
setSessionId(SessionId $sessionId)
Set the session for this request.
Definition: WebRequest.php:832
WebRequest\getAcceptLang
getAcceptLang()
Parse the Accept-Language header sent by the client into an array.
Definition: WebRequest.php:1182
WebRequest\getElapsedTime
getElapsedTime()
Get the number of seconds to have elapsed since request start, in fractional seconds,...
Definition: WebRequest.php:317
RE_IPV6_GAP
const RE_IPV6_GAP
For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
Definition: IP.php:64
WebRequest\getIntOrNull
getIntOrNull( $name)
Fetch an integer value from the input or return null if empty.
Definition: WebRequest.php:597
WebRequest\getRawPostString
getRawPostString()
Return the contents of the POST with no decoding.
Definition: WebRequest.php:759
WebRequest\detectProtocol
static detectProtocol()
Detect the protocol from $_SERVER.
Definition: WebRequest.php:300
WebRequest\getGPCVal
getGPCVal( $arr, $name, $default)
Fetch a value from the given array or return $default if it's not set.
Definition: WebRequest.php:437
$wgUseSameSiteLegacyCookies
bool $wgUseSameSiteLegacyCookies
If true, when a cross-site cookie with SameSite=None is sent, a legacy cookie with an "ss0" prefix wi...
Definition: DefaultSettings.php:7212
WebRequest\hasSafeMethod
hasSafeMethod()
Check if this request uses a "safe" HTTP method.
Definition: WebRequest.php:1374
$base
$base
Definition: generateLocalAutoload.php:11
WebRequest\$queryAndPathParams
string[] $queryAndPathParams
The parameters from $_GET.
Definition: WebRequest.php:54
WebRequest\__construct
__construct()
Definition: WebRequest.php:120
WebRequest\getRawQueryString
getRawQueryString()
Return the contents of the Query with no decoding.
Definition: WebRequest.php:749
WebRequest\appendQueryArray
appendQueryArray( $array)
Appends or replaces value of query variables.
Definition: WebRequest.php:988
$wgAllowExternalReqID
$wgAllowExternalReqID
Whether to respect/honour the request ID provided by the incoming request via the X-Request-Id header...
Definition: DefaultSettings.php:9698
PathRouter\getActionPaths
static getActionPaths(array $actionPaths, $articlePath)
Definition: PathRouter.php:430
WebRequest\getFileTempname
getFileTempname( $key)
Return the path to the temporary file where PHP has stored the upload.
Definition: WebRequest.php:1035
$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:132
WebRequest\isSafeRequest
isSafeRequest()
Whether this request should be identified as being "safe".
Definition: WebRequest.php:1400
WebRequest\getText
getText( $name, $default='')
Fetch a text string from the given array or return $default if it's not set.
Definition: WebRequest.php:669
WebRequest\$protocol
string $protocol
Cached URL protocol.
Definition: WebRequest.php:102
WebRequest\canonicalizeIPv6LoopbackAddress
static canonicalizeIPv6LoopbackAddress( $ip)
Converts ::1 (IPv6 loopback address) to 127.0.0.1 (IPv4 loopback address); assists in matching truste...
Definition: WebRequest.php:1344
WebRequest\getMethod
getMethod()
Get the HTTP method used for this request.
Definition: WebRequest.php:786
MWException
MediaWiki exception.
Definition: MWException.php:29
WebRequest\getFileName
getFileName( $key)
Return the original filename of the uploaded file, as reported by the submitting user agent.
Definition: WebRequest.php:1060
WebRequest\getQueryValuesOnly
getQueryValuesOnly()
Get the values passed in the query string only, not including the path router parameters.
Definition: WebRequest.php:726
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:996
MediaWiki\Session\Session
Manages data for an authenticated session.
Definition: Session.php:48
WebRequest\setVal
setVal( $key, $value)
Set an arbitrary value into our get/post data.
Definition: WebRequest.php:518
WebRequest\$reqId
static string $reqId
The unique request ID.
Definition: WebRequest.php:78
$matches
$matches
Definition: NoLocalSettings.php:24
WebRequest\getRawInput
getRawInput()
Return the raw request body, with no processing.
Definition: WebRequest.php:773
WebRequest\getUpload
getUpload( $key)
Return a WebRequestUpload object corresponding to the key.
Definition: WebRequest.php:1070
WebRequest\$queryParams
string[] $queryParams
The parameters from $_GET only.
Definition: WebRequest.php:60
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:150
WebRequest\getFullRequestURL
getFullRequestURL()
Return the request URI with the canonical service and hostname, path, and query string.
Definition: WebRequest.php:962
WebRequest\getArray
getArray( $name, $default=null)
Fetch an array from the input or return $default if it's not set.
Definition: WebRequest.php:549
WebRequest\$response
WebResponse $response
Lazy-init response object.
Definition: WebRequest.php:84
WebRequest\markAsSafeRequest
markAsSafeRequest()
Mark this request as identified as being nullipotent even if it is a POST request.
Definition: WebRequest.php:1418
WebRequest\getAllHeaders
getAllHeaders()
Get an array containing all request headers.
Definition: WebRequest.php:1105
WebRequestUpload
Object to access the $_FILES array.
Definition: WebRequestUpload.php:33
WebRequest\normalizeUnicode
normalizeUnicode( $data)
Recursively normalizes UTF-8 strings in the given array.
Definition: WebRequest.php:417
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:475
WebRequest\checkUrlExtension
checkUrlExtension( $extList=[])
This function formerly did a security check to prevent an XSS vulnerability in IE6,...
Definition: WebRequest.php:1164
WebRequest\getCheck
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
Definition: WebRequest.php:653
WebRequest\getProtocol
getProtocol()
Get the current URL protocol (http or https)
Definition: WebRequest.php:360
WebRequest\setIP
setIP( $ip)
Definition: WebRequest.php:1358
WebRequest\getSession
getSession()
Return the session for this request.
Definition: WebRequest.php:813
WebRequest\response
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
Definition: WebRequest.php:1080
$wgUsePrivateIPs
$wgUsePrivateIPs
Should forwarded Private IPs be accepted?
Definition: DefaultSettings.php:3421
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:83
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
WebRequest\getCrossSiteCookie
getCrossSiteCookie( $key, $prefix='', $default=null)
Get a cookie set with SameSite=None possibly with a legacy fallback cookie.
Definition: WebRequest.php:877
WebRequest\getIntArray
getIntArray( $name, $default=null)
Fetch an array of integers, or return $default if it's not set.
Definition: WebRequest.php:568
WebRequest\$requestTime
float $requestTime
The timestamp of the start of the request, with microsecond precision.
Definition: WebRequest.php:96
WebRequest\getValues
getValues(... $names)
Extracts the (given) named values into an array.
Definition: WebRequest.php:681
WebRequest\$markedAsSafe
bool $markedAsSafe
Whether this HTTP request is "safe" (even if it is an HTTP post)
Definition: WebRequest.php:115
WebRequest\getCookie
getCookie( $key, $prefix=null, $default=null)
Get a cookie from the $_COOKIE jar.
Definition: WebRequest.php:854
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
WebRequest\getIP
getIP()
Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of...
Definition: WebRequest.php:1261
WebRequest\getUploadError
getUploadError( $key)
Return the upload error or 0.
Definition: WebRequest.php:1045
$wgArticlePath
$wgArticlePath
The URL path for primary article page views.
Definition: DefaultSettings.php:264
WebRequest\setSessionData
setSessionData( $key, $data)
Definition: WebRequest.php:1151
$wgActionPaths
$wgActionPaths
To set 'pretty' URL paths for actions other than plain page views, add to this array.
Definition: DefaultSettings.php:488
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:72
WebRequest\getVal
getVal( $name, $default=null)
Fetch a scalar from the input or return $default if it's not set.
Definition: WebRequest.php:499
WebRequest\getInt
getInt( $name, $default=0)
Fetch an integer value from the input or return $default if not set.
Definition: WebRequest.php:585
MediaWiki\Session\SessionId
Value object holding the session ID in a manner that can be globally updated.
Definition: SessionId.php:40
WebRequest\getRequestId
static getRequestId()
Get the current request ID.
Definition: WebRequest.php:330
WebRequest\getLimitOffsetForUser
getLimitOffsetForUser(User $user, $deflimit=50, $optionname='rclimit')
Check for limit and offset parameters on the input, and return sensible defaults if not given.
Definition: WebRequest.php:1006
$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:614
WebRequest\detectServer
static detectServer()
Work out an appropriate URL prefix containing scheme and host, based on information detected from $_S...
Definition: WebRequest.php:254
WebRequest\getHeader
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
Definition: WebRequest.php:1122
WebRequest\getGlobalRequestURL
static getGlobalRequestURL()
Return the path and query string portion of the main request URI.
Definition: WebRequest.php:902
WebRequest\$ip
string $ip
Cached client IP address.
Definition: WebRequest.php:90
WebRequest\getPostValues
getPostValues()
Get the values passed via POST.
Definition: WebRequest.php:738
WebRequest\wasPosted
wasPosted()
Returns true if the present request was reached by a POST operation, false otherwise (GET,...
Definition: WebRequest.php:799
WebRequest\unsetVal
unsetVal( $key)
Unset an arbitrary value from our get/post data.
Definition: WebRequest.php:530
wfGetServerUrl
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
Definition: GlobalFunctions.php:552
WebRequest\getRequestURL
getRequestURL()
Return the path and query string portion of the request URI.
Definition: WebRequest.php:948
WebRequest\overrideRequestId
static overrideRequestId( $id)
Override the unique request ID.
Definition: WebRequest.php:352
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:391
WebResponse
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:30
WebRequest\getRawIP
getRawIP()
Fetch the raw IP from the request.
Definition: WebRequest.php:1237
WebRequest\getQueryValues
getQueryValues()
Get the values passed in the query string and the path router parameters.
Definition: WebRequest.php:713
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:68
WebRequest\getFuzzyBool
getFuzzyBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
Definition: WebRequest.php:640
$wgVariantArticlePath
$wgVariantArticlePath
Like $wgArticlePath, but on multi-variant wikis, this provides a path format that describes which par...
Definition: DefaultSettings.php:3634
PathRouter
PathRouter class.
Definition: PathRouter.php:73
$wgCookiePrefix
$wgCookiePrefix
Cookies generated by MediaWiki have names starting with this prefix.
Definition: DefaultSettings.php:7183
WebRequest\getBool
getBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
Definition: WebRequest.php:627
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:192
$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:195
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:330
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:257