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 
149  public static function getPathInfo( $want = 'all' ) {
150  // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
151  // And also by Apache 2.x, double slashes are converted to single slashes.
152  // So we will use REQUEST_URI if possible.
153  if ( isset( $_SERVER['REQUEST_URI'] ) ) {
154  // Slurp out the path portion to examine...
155  $url = $_SERVER['REQUEST_URI'];
156  if ( !preg_match( '!^https?://!', $url ) ) {
157  $url = 'http://unused' . $url;
158  }
159  $a = parse_url( $url );
160  if ( !$a ) {
161  return [];
162  }
163  $path = $a['path'] ?? '';
164 
165  global $wgScript;
166  if ( $path == $wgScript && $want !== 'all' ) {
167  // Script inside a rewrite path?
168  // Abort to keep from breaking...
169  return [];
170  }
171 
172  $router = new PathRouter;
173 
174  // Raw PATH_INFO style
175  $router->add( "$wgScript/$1" );
176 
177  global $wgArticlePath;
178  if ( $wgArticlePath ) {
179  $router->validateRoute( $wgArticlePath, 'wgArticlePath' );
180  $router->add( $wgArticlePath );
181  }
182 
183  global $wgActionPaths;
185  if ( $articlePaths ) {
186  $router->add( $articlePaths, [ 'action' => '$key' ] );
187  }
188 
189  global $wgVariantArticlePath;
190  if ( $wgVariantArticlePath ) {
191  $router->validateRoute( $wgVariantArticlePath, 'wgVariantArticlePath' );
192  $router->add( $wgVariantArticlePath,
193  [ 'variant' => '$2' ],
194  [ '$2' => MediaWikiServices::getInstance()->getContentLanguage()->
195  getVariants() ]
196  );
197  }
198 
199  Hooks::runner()->onWebRequestPathInfoRouter( $router );
200 
201  $matches = $router->parse( $path );
202  } else {
203  global $wgUsePathInfo;
204  $matches = [];
205  if ( $wgUsePathInfo ) {
206  if ( !empty( $_SERVER['ORIG_PATH_INFO'] ) ) {
207  // Mangled PATH_INFO
208  // https://bugs.php.net/bug.php?id=31892
209  // Also reported when ini_get('cgi.fix_pathinfo')==false
210  $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
211  } elseif ( !empty( $_SERVER['PATH_INFO'] ) ) {
212  // Regular old PATH_INFO yay
213  $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
214  }
215  }
216  }
217 
218  return $matches;
219  }
220 
232  public static function getRequestPathSuffix( $basePath ) {
233  $basePath = rtrim( $basePath, '/' ) . '/';
234  $requestUrl = self::getGlobalRequestURL();
235  $qpos = strpos( $requestUrl, '?' );
236  if ( $qpos !== false ) {
237  $requestPath = substr( $requestUrl, 0, $qpos );
238  } else {
239  $requestPath = $requestUrl;
240  }
241  if ( substr( $requestPath, 0, strlen( $basePath ) ) !== $basePath ) {
242  return false;
243  }
244  return rawurldecode( substr( $requestPath, strlen( $basePath ) ) );
245  }
246 
253  public static function detectServer() {
255 
256  $proto = self::detectProtocol();
257  $stdPort = $proto === 'https' ? 443 : 80;
258 
259  $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
260  $host = 'localhost';
261  $port = $stdPort;
262  foreach ( $varNames as $varName ) {
263  if ( !isset( $_SERVER[$varName] ) ) {
264  continue;
265  }
266 
267  $parts = IPUtils::splitHostAndPort( $_SERVER[$varName] );
268  if ( !$parts ) {
269  // Invalid, do not use
270  continue;
271  }
272 
273  $host = $parts[0];
274  if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
275  // T72021: Assume that upstream proxy is running on the default
276  // port based on the protocol. We have no reliable way to determine
277  // the actual port in use upstream.
278  $port = $stdPort;
279  } elseif ( $parts[1] === false ) {
280  if ( isset( $_SERVER['SERVER_PORT'] ) ) {
281  $port = $_SERVER['SERVER_PORT'];
282  } // else leave it as $stdPort
283  } else {
284  $port = $parts[1];
285  }
286  break;
287  }
288 
289  return $proto . '://' . IPUtils::combineHostAndPort( $host, $port, $stdPort );
290  }
291 
299  public static function detectProtocol() {
300  if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
301  ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
302  $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
303  return 'https';
304  } else {
305  return 'http';
306  }
307  }
308 
316  public function getElapsedTime() {
317  return microtime( true ) - $this->requestTime;
318  }
319 
328  public static function getRequestId() {
329  // This method is called from various error handlers and should be kept simple.
330 
331  if ( !self::$reqId ) {
332  global $wgAllowExternalReqID;
334  ? RequestContext::getMain()->getRequest()->getHeader( 'X-Request-Id' )
335  : null;
336  if ( !$id ) {
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  // T18019: title interpolation on API queries is useless and sometimes harmful
376  if ( defined( 'MW_API' ) ) {
377  return;
378  }
379 
380  $matches = self::getPathInfo( 'title' );
381  foreach ( $matches as $key => $val ) {
382  $this->data[$key] = $this->queryAndPathParams[$key] = $val;
383  }
384  }
385 
396  public static function extractTitle( $path, $bases, $key = false ) {
397  foreach ( (array)$bases as $keyValue => $base ) {
398  // Find the part after $wgArticlePath
399  $base = str_replace( '$1', '', $base );
400  $baseLen = strlen( $base );
401  if ( substr( $path, 0, $baseLen ) == $base ) {
402  $raw = substr( $path, $baseLen );
403  if ( $raw !== '' ) {
404  $matches = [ 'title' => rawurldecode( $raw ) ];
405  if ( $key ) {
406  $matches[$key] = $keyValue;
407  }
408  return $matches;
409  }
410  }
411  }
412  return [];
413  }
414 
422  public function normalizeUnicode( $data ) {
423  if ( is_array( $data ) ) {
424  foreach ( $data as $key => $val ) {
425  $data[$key] = $this->normalizeUnicode( $val );
426  }
427  } else {
428  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
429  $data = $contLang->normalize( $data );
430  }
431  return $data;
432  }
433 
442  private function getGPCVal( $arr, $name, $default ) {
443  # PHP is so nice to not touch input data, except sometimes:
444  # https://www.php.net/variables.external#language.variables.external.dot-in-names
445  # Work around PHP *feature* to avoid *bugs* elsewhere.
446  $name = strtr( $name, '.', '_' );
447 
448  if ( !isset( $arr[$name] ) ) {
449  return $default;
450  }
451 
452  $data = $arr[$name];
453  # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
454  $isAsciiStr = ( is_string( $data ) && preg_match( '/[^\x20-\x7E]/', $data ) === 0 );
455  if ( !$isAsciiStr ) {
456  if ( isset( $_GET[$name] ) && is_string( $data ) ) {
457  # Check for alternate/legacy character encoding.
458  $data = MediaWikiServices::getInstance()
459  ->getContentLanguage()
460  ->checkTitleEncoding( $data );
461  }
462  $data = $this->normalizeUnicode( $data );
463  }
464 
465  return $data;
466  }
467 
480  public function getRawVal( $name, $default = null ) {
481  $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
482  if ( isset( $this->data[$name] ) && !is_array( $this->data[$name] ) ) {
483  $val = $this->data[$name];
484  } else {
485  $val = $default;
486  }
487  if ( $val === null ) {
488  return $val;
489  } else {
490  return (string)$val;
491  }
492  }
493 
504  public function getVal( $name, $default = null ) {
505  $val = $this->getGPCVal( $this->data, $name, $default );
506  if ( is_array( $val ) ) {
507  $val = $default;
508  }
509  if ( $val === null ) {
510  return $val;
511  } else {
512  return (string)$val;
513  }
514  }
515 
523  public function setVal( $key, $value ) {
524  $ret = $this->data[$key] ?? null;
525  $this->data[$key] = $value;
526  return $ret;
527  }
528 
535  public function unsetVal( $key ) {
536  if ( !isset( $this->data[$key] ) ) {
537  $ret = null;
538  } else {
539  $ret = $this->data[$key];
540  unset( $this->data[$key] );
541  }
542  return $ret;
543  }
544 
554  public function getArray( $name, $default = null ) {
555  $val = $this->getGPCVal( $this->data, $name, $default );
556  if ( $val === null ) {
557  return null;
558  } else {
559  return (array)$val;
560  }
561  }
562 
573  public function getIntArray( $name, $default = null ) {
574  $val = $this->getArray( $name, $default );
575  if ( is_array( $val ) ) {
576  $val = array_map( 'intval', $val );
577  }
578  return $val;
579  }
580 
590  public function getInt( $name, $default = 0 ) {
591  return intval( $this->getRawVal( $name, $default ) );
592  }
593 
602  public function getIntOrNull( $name ) {
603  $val = $this->getRawVal( $name );
604  return is_numeric( $val )
605  ? intval( $val )
606  : null;
607  }
608 
619  public function getFloat( $name, $default = 0.0 ) {
620  return floatval( $this->getRawVal( $name, $default ) );
621  }
622 
632  public function getBool( $name, $default = false ) {
633  return (bool)$this->getRawVal( $name, $default );
634  }
635 
645  public function getFuzzyBool( $name, $default = false ) {
646  return $this->getBool( $name, $default )
647  && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
648  }
649 
658  public function getCheck( $name ) {
659  # Checkboxes and buttons are only present when clicked
660  # Presence connotes truth, absence false
661  return $this->getRawVal( $name, null ) !== null;
662  }
663 
674  public function getText( $name, $default = '' ) {
675  $val = $this->getVal( $name, $default );
676  return str_replace( "\r\n", "\n", $val );
677  }
678 
686  public function getValues() {
687  $names = func_get_args();
688  if ( count( $names ) == 0 ) {
689  $names = array_keys( $this->data );
690  }
691 
692  $retVal = [];
693  foreach ( $names as $name ) {
694  $value = $this->getGPCVal( $this->data, $name, null );
695  if ( $value !== null ) {
696  $retVal[$name] = $value;
697  }
698  }
699  return $retVal;
700  }
701 
708  public function getValueNames( $exclude = [] ) {
709  return array_diff( array_keys( $this->getValues() ), $exclude );
710  }
711 
719  public function getQueryValues() {
721  }
722 
732  public function getQueryValuesOnly() {
733  return $this->queryParams;
734  }
735 
744  public function getPostValues() {
745  return $_POST;
746  }
747 
755  public function getRawQueryString() {
756  return $_SERVER['QUERY_STRING'];
757  }
758 
765  public function getRawPostString() {
766  if ( !$this->wasPosted() ) {
767  return '';
768  }
769  return $this->getRawInput();
770  }
771 
779  public function getRawInput() {
780  static $input = null;
781  if ( $input === null ) {
782  $input = file_get_contents( 'php://input' );
783  }
784  return $input;
785  }
786 
792  public function getMethod() {
793  return $_SERVER['REQUEST_METHOD'] ?? 'GET';
794  }
795 
805  public function wasPosted() {
806  return $this->getMethod() == 'POST';
807  }
808 
819  public function getSession() {
820  if ( $this->sessionId !== null ) {
821  $session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
822  if ( $session ) {
823  return $session;
824  }
825  }
826 
827  $session = SessionManager::singleton()->getSessionForRequest( $this );
828  $this->sessionId = $session->getSessionId();
829  return $session;
830  }
831 
838  public function setSessionId( SessionId $sessionId ) {
839  $this->sessionId = $sessionId;
840  }
841 
848  public function getSessionId() {
849  return $this->sessionId;
850  }
851 
860  public function getCookie( $key, $prefix = null, $default = null ) {
861  if ( $prefix === null ) {
862  global $wgCookiePrefix;
863  $prefix = $wgCookiePrefix;
864  }
865  $name = $prefix . $key;
866  // Work around mangling of $_COOKIE
867  $name = strtr( $name, '.', '_' );
868  if ( isset( $_COOKIE[$name] ) ) {
869  return $_COOKIE[$name];
870  } else {
871  return $default;
872  }
873  }
874 
883  public function getCrossSiteCookie( $key, $prefix = '', $default = null ) {
885  $name = $prefix . $key;
886  // Work around mangling of $_COOKIE
887  $name = strtr( $name, '.', '_' );
888  if ( isset( $_COOKIE[$name] ) ) {
889  return $_COOKIE[$name];
890  }
892  $legacyName = $prefix . "ss0-" . $key;
893  $legacyName = strtr( $legacyName, '.', '_' );
894  if ( isset( $_COOKIE[$legacyName] ) ) {
895  return $_COOKIE[$legacyName];
896  }
897  }
898  return $default;
899  }
900 
908  public static function getGlobalRequestURL() {
909  // This method is called on fatal errors; it should not depend on anything complex.
910 
911  if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
912  $base = $_SERVER['REQUEST_URI'];
913  } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
914  && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
915  ) {
916  // Probably IIS; doesn't set REQUEST_URI
917  $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
918  } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
919  $base = $_SERVER['SCRIPT_NAME'];
920  if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
921  $base .= '?' . $_SERVER['QUERY_STRING'];
922  }
923  } else {
924  // This shouldn't happen!
925  throw new MWException( "Web server doesn't provide either " .
926  "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
927  "of your web server configuration to https://phabricator.wikimedia.org/" );
928  }
929  // User-agents should not send a fragment with the URI, but
930  // if they do, and the web server passes it on to us, we
931  // need to strip it or we get false-positive redirect loops
932  // or weird output URLs
933  $hash = strpos( $base, '#' );
934  if ( $hash !== false ) {
935  $base = substr( $base, 0, $hash );
936  }
937 
938  if ( $base[0] == '/' ) {
939  // More than one slash will look like it is protocol relative
940  return preg_replace( '!^/+!', '/', $base );
941  } else {
942  // We may get paths with a host prepended; strip it.
943  return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
944  }
945  }
946 
954  public function getRequestURL() {
955  return self::getGlobalRequestURL();
956  }
957 
968  public function getFullRequestURL() {
969  // Pass an explicit PROTO constant instead of PROTO_CURRENT so that we
970  // do not rely on state from the global $wgRequest object (which it would,
971  // via wfGetServerUrl/wfExpandUrl/$wgRequest->protocol).
972  if ( $this->getProtocol() === 'http' ) {
973  return wfGetServerUrl( PROTO_HTTP ) . $this->getRequestURL();
974  } else {
975  return wfGetServerUrl( PROTO_HTTPS ) . $this->getRequestURL();
976  }
977  }
978 
984  public function appendQueryValue( $key, $value ) {
985  return $this->appendQueryArray( [ $key => $value ] );
986  }
987 
994  public function appendQueryArray( $array ) {
995  $newquery = $this->getQueryValues();
996  unset( $newquery['title'] );
997  $newquery = array_merge( $newquery, $array );
998 
999  return wfArrayToCgi( $newquery );
1000  }
1001 
1012  public function getLimitOffsetForUser( User $user, $deflimit = 50, $optionname = 'rclimit' ) {
1013  $limit = $this->getInt( 'limit', 0 );
1014  if ( $limit < 0 ) {
1015  $limit = 0;
1016  }
1017  if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
1018  $limit = $user->getIntOption( $optionname );
1019  }
1020  if ( $limit <= 0 ) {
1021  $limit = $deflimit;
1022  }
1023  if ( $limit > 5000 ) {
1024  $limit = 5000; # We have *some* limits...
1025  }
1026 
1027  $offset = $this->getInt( 'offset', 0 );
1028  if ( $offset < 0 ) {
1029  $offset = 0;
1030  }
1031 
1032  return [ $limit, $offset ];
1033  }
1034 
1041  public function getFileTempname( $key ) {
1042  $file = new WebRequestUpload( $this, $key );
1043  return $file->getTempName();
1044  }
1045 
1052  public function getUploadError( $key ) {
1053  $file = new WebRequestUpload( $this, $key );
1054  return $file->getError();
1055  }
1056 
1068  public function getFileName( $key ) {
1069  $file = new WebRequestUpload( $this, $key );
1070  return $file->getName();
1071  }
1072 
1079  public function getUpload( $key ) {
1080  return new WebRequestUpload( $this, $key );
1081  }
1082 
1089  public function response() {
1090  /* Lazy initialization of response object for this request */
1091  if ( !is_object( $this->response ) ) {
1092  $class = ( $this instanceof FauxRequest ) ? FauxResponse::class : WebResponse::class;
1093  $this->response = new $class();
1094  }
1095  return $this->response;
1096  }
1097 
1101  protected function initHeaders() {
1102  if ( count( $this->headers ) ) {
1103  return;
1104  }
1105 
1106  $this->headers = array_change_key_case( getallheaders(), CASE_UPPER );
1107  }
1108 
1114  public function getAllHeaders() {
1115  $this->initHeaders();
1116  return $this->headers;
1117  }
1118 
1131  public function getHeader( $name, $flags = 0 ) {
1132  $this->initHeaders();
1133  $name = strtoupper( $name );
1134  if ( !isset( $this->headers[$name] ) ) {
1135  return false;
1136  }
1137  $value = $this->headers[$name];
1138  if ( $flags & self::GETHEADER_LIST ) {
1139  $value = array_map( 'trim', explode( ',', $value ) );
1140  }
1141  return $value;
1142  }
1143 
1151  public function getSessionData( $key ) {
1152  return $this->getSession()->get( $key );
1153  }
1154 
1160  public function setSessionData( $key, $data ) {
1161  $this->getSession()->set( $key, $data );
1162  }
1163 
1173  public function checkUrlExtension( $extWhitelist = [] ) {
1174  wfDeprecated( __METHOD__, '1.35' );
1175  return true;
1176  }
1177 
1191  public function getAcceptLang() {
1192  // Modified version of code found at
1193  // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1194  $acceptLang = $this->getHeader( 'Accept-Language' );
1195  if ( !$acceptLang ) {
1196  return [];
1197  }
1198 
1199  // Return the language codes in lower case
1200  $acceptLang = strtolower( $acceptLang );
1201 
1202  // Break up string into pieces (languages and q factors)
1203  if ( !preg_match_all(
1204  '/
1205  # a language code or a star is required
1206  ([a-z]{1,8}(?:-[a-z]{1,8})*|\*)
1207  # from here everything is optional
1208  \s*
1209  (?:
1210  # this accepts only numbers in the range ;q=0.000 to ;q=1.000
1211  ;\s*q\s*=\s*
1212  (1(?:\.0{0,3})?|0(?:\.\d{0,3})?)?
1213  )?
1214  /x',
1215  $acceptLang,
1216  $matches,
1217  PREG_SET_ORDER
1218  ) ) {
1219  return [];
1220  }
1221 
1222  // Create a list like "en" => 0.8
1223  $langs = [];
1224  foreach ( $matches as $match ) {
1225  $languageCode = $match[1];
1226  // When not present, the default value is 1
1227  $qValue = (float)( $match[2] ?? 1.0 );
1228  if ( $qValue ) {
1229  $langs[$languageCode] = $qValue;
1230  }
1231  }
1232 
1233  // Sort list by qValue
1234  arsort( $langs, SORT_NUMERIC );
1235  return $langs;
1236  }
1237 
1246  protected function getRawIP() {
1247  if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1248  return null;
1249  }
1250 
1251  if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1252  throw new MWException( __METHOD__
1253  . " : Could not determine the remote IP address due to multiple values." );
1254  } else {
1255  $ipchain = $_SERVER['REMOTE_ADDR'];
1256  }
1257 
1258  return IPUtils::canonicalize( $ipchain );
1259  }
1260 
1270  public function getIP() {
1271  global $wgUsePrivateIPs;
1272 
1273  # Return cached result
1274  if ( $this->ip !== null ) {
1275  return $this->ip;
1276  }
1277 
1278  # collect the originating ips
1279  $ip = $this->getRawIP();
1280  if ( !$ip ) {
1281  throw new MWException( 'Unable to determine IP.' );
1282  }
1283 
1284  # Append XFF
1285  $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1286  if ( $forwardedFor !== false ) {
1287  $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1288  $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1289  $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1290  $ipchain = array_reverse( $ipchain );
1291  array_unshift( $ipchain, $ip );
1292 
1293  # Step through XFF list and find the last address in the list which is a
1294  # trusted server. Set $ip to the IP address given by that trusted server,
1295  # unless the address is not sensible (e.g. private). However, prefer private
1296  # IP addresses over proxy servers controlled by this site (more sensible).
1297  # Note that some XFF values might be "unknown" with Squid/Varnish.
1298  foreach ( $ipchain as $i => $curIP ) {
1299  $curIP = IPUtils::sanitizeIP( IPUtils::canonicalize( $curIP ) );
1300  if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1301  || !$proxyLookup->isTrustedProxy( $curIP )
1302  ) {
1303  break; // IP is not valid/trusted or does not point to anything
1304  }
1305  if (
1306  IPUtils::isPublic( $ipchain[$i + 1] ) ||
1307  $wgUsePrivateIPs ||
1308  $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1309  ) {
1310  // Follow the next IP according to the proxy
1311  $nextIP = IPUtils::canonicalize( $ipchain[$i + 1] );
1312  if ( !$nextIP && $isConfigured ) {
1313  // We have not yet made it past CDN/proxy servers of this site,
1314  // so either they are misconfigured or there is some IP spoofing.
1315  throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1316  }
1317  $ip = $nextIP;
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 
1341  public function setIP( $ip ) {
1342  $this->ip = $ip;
1343  }
1344 
1357  public function hasSafeMethod() {
1358  if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1359  return false; // CLI mode
1360  }
1361 
1362  return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1363  }
1364 
1383  public function isSafeRequest() {
1384  if ( $this->markedAsSafe && $this->wasPosted() ) {
1385  return true; // marked as a "safe" POST
1386  }
1387 
1388  return $this->hasSafeMethod();
1389  }
1390 
1401  public function markAsSafeRequest() {
1402  $this->markedAsSafe = true;
1403  }
1404 }
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:1101
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:1151
WebRequest\getValueNames
getValueNames( $exclude=[])
Returns the names of all input values excluding those in $exclude.
Definition: WebRequest.php:708
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:203
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
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:232
WebRequest\getSessionId
getSessionId()
Get the session id for this request, if any.
Definition: WebRequest.php:848
$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:2619
WebRequest\appendQueryValue
appendQueryValue( $key, $value)
Definition: WebRequest.php:984
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:838
WebRequest\getAcceptLang
getAcceptLang()
Parse the Accept-Language header sent by the client into an array.
Definition: WebRequest.php:1191
WebRequest\getElapsedTime
getElapsedTime()
Get the number of seconds to have elapsed since request start, in fractional seconds,...
Definition: WebRequest.php:316
WebRequest\getIntOrNull
getIntOrNull( $name)
Fetch an integer value from the input or return null if empty.
Definition: WebRequest.php:602
$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:765
WebRequest\detectProtocol
static detectProtocol()
Detect the protocol from $_SERVER.
Definition: WebRequest.php:299
WebRequest\getGPCVal
getGPCVal( $arr, $name, $default)
Fetch a value from the given array or return $default if it's not set.
Definition: WebRequest.php:442
$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:6530
WebRequest\hasSafeMethod
hasSafeMethod()
Check if this request uses a "safe" HTTP method.
Definition: WebRequest.php:1357
$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:755
WebRequest\appendQueryArray
appendQueryArray( $array)
Appends or replaces value of query variables.
Definition: WebRequest.php:994
$wgAllowExternalReqID
$wgAllowExternalReqID
Whether to respect/honour the request ID provided by the incoming request via the X-Request-Id header...
Definition: DefaultSettings.php:8934
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:1041
$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:1383
WebRequest\getText
getText( $name, $default='')
Fetch a text string from the given array or return $default if it's not set.
Definition: WebRequest.php:674
WebRequest\$protocol
string $protocol
Cached URL protocol.
Definition: WebRequest.php:102
WebRequest\getMethod
getMethod()
Get the HTTP method used for this request.
Definition: WebRequest.php:792
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:1068
WebRequest\getQueryValuesOnly
getQueryValuesOnly()
Get the values passed in the query string only, not including the path router parameters.
Definition: WebRequest.php:732
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1033
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:523
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:779
WebRequest\getUpload
getUpload( $key)
Return a WebRequestUpload object corresponding to the key.
Definition: WebRequest.php:1079
WebRequest\$queryParams
string[] $queryParams
The parameters from $_GET only.
Definition: WebRequest.php:60
WebRequest\getValues
getValues()
Extracts the given named values into an array.
Definition: WebRequest.php:686
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:149
WebRequest\getFullRequestURL
getFullRequestURL()
Return the request URI with the canonical service and hostname, path, and query string.
Definition: WebRequest.php:968
WebRequest\getArray
getArray( $name, $default=null)
Fetch an array from the input or return $default if it's not set.
Definition: WebRequest.php:554
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:1401
WebRequest\getAllHeaders
getAllHeaders()
Get an array containing all request headers.
Definition: WebRequest.php:1114
WebRequestUpload
Object to access the $_FILES array.
Definition: WebRequestUpload.php:30
WebRequest\normalizeUnicode
normalizeUnicode( $data)
Recursively normalizes UTF-8 strings in the given array.
Definition: WebRequest.php:422
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:480
WebRequest\getCheck
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
Definition: WebRequest.php:658
WebRequest\getProtocol
getProtocol()
Get the current URL protocol (http or https)
Definition: WebRequest.php:360
WebRequest\setIP
setIP( $ip)
Definition: WebRequest.php:1341
WebRequest\getSession
getSession()
Return the session for this request.
Definition: WebRequest.php:819
WebRequest\response
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
Definition: WebRequest.php:1089
$wgUsePrivateIPs
$wgUsePrivateIPs
Should forwarded Private IPs be accepted?
Definition: DefaultSettings.php:3081
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:53
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
WebRequest\getCrossSiteCookie
getCrossSiteCookie( $key, $prefix='', $default=null)
Get a cookie set with SameSite=None possibly with a legacy fallback cookie.
Definition: WebRequest.php:883
WebRequest\checkUrlExtension
checkUrlExtension( $extWhitelist=[])
This function formerly did a security check to prevent an XSS vulnerability in IE6,...
Definition: WebRequest.php:1173
WebRequest\getIntArray
getIntArray( $name, $default=null)
Fetch an array of integers, or return $default if it's not set.
Definition: WebRequest.php:573
WebRequest\$requestTime
float $requestTime
The timestamp of the start of the request, with microsecond precision.
Definition: WebRequest.php:96
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:476
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:860
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:1270
WebRequest\getUploadError
getUploadError( $key)
Return the upload error or 0.
Definition: WebRequest.php:1052
$wgArticlePath
$wgArticlePath
The URL path for primary article page views.
Definition: DefaultSettings.php:264
WebRequest\setSessionData
setSessionData( $key, $data)
Definition: WebRequest.php:1160
$wgActionPaths
$wgActionPaths
To set 'pretty' URL paths for actions other than plain page views, add to this array.
Definition: DefaultSettings.php:451
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:504
WebRequest\getInt
getInt( $name, $default=0)
Fetch an integer value from the input or return $default if not set.
Definition: WebRequest.php:590
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 unique request ID.
Definition: WebRequest.php:328
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:1012
$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:619
WebRequest\detectServer
static detectServer()
Work out an appropriate URL prefix containing scheme and host, based on information detected from $_S...
Definition: WebRequest.php:253
WebRequest\getHeader
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
Definition: WebRequest.php:1131
WebRequest\getGlobalRequestURL
static getGlobalRequestURL()
Return the path and query string portion of the main request URI.
Definition: WebRequest.php:908
WebRequest\$ip
string $ip
Cached client IP address.
Definition: WebRequest.php:90
WebRequest\getPostValues
getPostValues()
Get the values passed via POST.
Definition: WebRequest.php:744
WebRequest\wasPosted
wasPosted()
Returns true if the present request was reached by a POST operation, false otherwise (GET,...
Definition: WebRequest.php:805
WebRequest\unsetVal
unsetVal( $key)
Unset an arbitrary value from our get/post data.
Definition: WebRequest.php:535
wfGetServerUrl
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
Definition: GlobalFunctions.php:572
WebRequest\getRequestURL
getRequestURL()
Return the path and query string portion of the request URI.
Definition: WebRequest.php:954
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:396
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:1246
WebRequest\getQueryValues
getQueryValues()
Get the values passed in the query string and the path router parameters.
Definition: WebRequest.php:719
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:63
WebRequest\getFuzzyBool
getFuzzyBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
Definition: WebRequest.php:645
$wgVariantArticlePath
$wgVariantArticlePath
Like $wgArticlePath, but on multi-variant wikis, this provides a path format that describes which par...
Definition: DefaultSettings.php:3300
PathRouter
PathRouter class.
Definition: PathRouter.php:73
$wgCookiePrefix
$wgCookiePrefix
Cookies generated by MediaWiki have names starting with this prefix.
Definition: DefaultSettings.php:6501
WebRequest\getBool
getBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
Definition: WebRequest.php:632
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:202
$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:350
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:277