MediaWiki  master
GlobalFunctions.php
Go to the documentation of this file.
1 <?php
23 if ( !defined( 'MEDIAWIKI' ) ) {
24  die( "This file is part of MediaWiki, it is not a valid entry point" );
25 }
26 
32 use Wikimedia\AtEase\AtEase;
34 use Wikimedia\RequestTimeout\RequestTimeout;
35 use Wikimedia\WrappedString;
36 
47 function wfLoadExtension( $ext, $path = null ) {
48  if ( !$path ) {
49  global $wgExtensionDirectory;
50  $path = "$wgExtensionDirectory/$ext/extension.json";
51  }
53 }
54 
68 function wfLoadExtensions( array $exts ) {
69  global $wgExtensionDirectory;
70  $registry = ExtensionRegistry::getInstance();
71  foreach ( $exts as $ext ) {
72  $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
73  }
74 }
75 
84 function wfLoadSkin( $skin, $path = null ) {
85  if ( !$path ) {
86  global $wgStyleDirectory;
87  $path = "$wgStyleDirectory/$skin/skin.json";
88  }
90 }
91 
99 function wfLoadSkins( array $skins ) {
100  global $wgStyleDirectory;
101  $registry = ExtensionRegistry::getInstance();
102  foreach ( $skins as $skin ) {
103  $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
104  }
105 }
106 
113 function wfArrayDiff2( $a, $b ) {
114  return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
115 }
116 
122 function wfArrayDiff2_cmp( $a, $b ) {
123  if ( is_string( $a ) && is_string( $b ) ) {
124  return strcmp( $a, $b );
125  } elseif ( count( $a ) !== count( $b ) ) {
126  return count( $a ) <=> count( $b );
127  } else {
128  reset( $a );
129  reset( $b );
130  while ( key( $a ) !== null && key( $b ) !== null ) {
131  $valueA = current( $a );
132  $valueB = current( $b );
133  $cmp = strcmp( $valueA, $valueB );
134  if ( $cmp !== 0 ) {
135  return $cmp;
136  }
137  next( $a );
138  next( $b );
139  }
140  return 0;
141  }
142 }
143 
163 function wfMergeErrorArrays( ...$args ) {
164  $out = [];
165  foreach ( $args as $errors ) {
166  foreach ( $errors as $params ) {
167  $originalParams = $params;
168  if ( $params[0] instanceof MessageSpecifier ) {
169  $msg = $params[0];
170  $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
171  }
172  # @todo FIXME: Sometimes get nested arrays for $params,
173  # which leads to E_NOTICEs
174  $spec = implode( "\t", $params );
175  $out[$spec] = $originalParams;
176  }
177  }
178  return array_values( $out );
179 }
180 
189 function wfArrayInsertAfter( array $array, array $insert, $after ) {
190  // Find the offset of the element to insert after.
191  $keys = array_keys( $array );
192  $offsetByKey = array_flip( $keys );
193 
194  $offset = $offsetByKey[$after];
195 
196  // Insert at the specified offset
197  $before = array_slice( $array, 0, $offset + 1, true );
198  $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
199 
200  $output = $before + $insert + $after;
201 
202  return $output;
203 }
204 
213 function wfObjectToArray( $objOrArray, $recursive = true ) {
214  $array = [];
215  if ( is_object( $objOrArray ) ) {
216  $objOrArray = get_object_vars( $objOrArray );
217  }
218  foreach ( $objOrArray as $key => $value ) {
219  if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
220  $value = wfObjectToArray( $value );
221  }
222 
223  $array[$key] = $value;
224  }
225 
226  return $array;
227 }
228 
239 function wfRandom() {
240  // The maximum random value is "only" 2^31-1, so get two random
241  // values to reduce the chance of dupes
242  $max = mt_getrandmax() + 1;
243  $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
244  return $rand;
245 }
246 
257 function wfRandomString( $length = 32 ) {
258  $str = '';
259  for ( $n = 0; $n < $length; $n += 7 ) {
260  $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
261  }
262  return substr( $str, 0, $length );
263 }
264 
292 function wfUrlencode( $s ) {
293  static $needle;
294 
295  if ( $s === null ) {
296  // Reset $needle for testing.
297  $needle = null;
298  return '';
299  }
300 
301  if ( $needle === null ) {
302  $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
303  if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
304  ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
305  ) {
306  $needle[] = '%3A';
307  }
308  }
309 
310  $s = urlencode( $s );
311  $s = str_ireplace(
312  $needle,
313  [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
314  $s
315  );
316 
317  return $s;
318 }
319 
330 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
331  if ( $array2 !== null ) {
332  $array1 += $array2;
333  }
334 
335  $cgi = '';
336  foreach ( $array1 as $key => $value ) {
337  if ( $value !== null && $value !== false ) {
338  if ( $cgi != '' ) {
339  $cgi .= '&';
340  }
341  if ( $prefix !== '' ) {
342  $key = $prefix . "[$key]";
343  }
344  if ( is_array( $value ) ) {
345  $firstTime = true;
346  foreach ( $value as $k => $v ) {
347  $cgi .= $firstTime ? '' : '&';
348  if ( is_array( $v ) ) {
349  $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
350  } else {
351  $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
352  }
353  $firstTime = false;
354  }
355  } else {
356  if ( is_object( $value ) ) {
357  $value = $value->__toString();
358  }
359  $cgi .= urlencode( $key ) . '=' . urlencode( $value );
360  }
361  }
362  }
363  return $cgi;
364 }
365 
375 function wfCgiToArray( $query ) {
376  if ( isset( $query[0] ) && $query[0] == '?' ) {
377  $query = substr( $query, 1 );
378  }
379  $bits = explode( '&', $query );
380  $ret = [];
381  foreach ( $bits as $bit ) {
382  if ( $bit === '' ) {
383  continue;
384  }
385  if ( strpos( $bit, '=' ) === false ) {
386  // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
387  $key = $bit;
388  $value = '';
389  } else {
390  list( $key, $value ) = explode( '=', $bit );
391  }
392  $key = urldecode( $key );
393  $value = urldecode( $value );
394  if ( strpos( $key, '[' ) !== false ) {
395  $keys = array_reverse( explode( '[', $key ) );
396  $key = array_pop( $keys );
397  $temp = $value;
398  foreach ( $keys as $k ) {
399  $k = substr( $k, 0, -1 );
400  $temp = [ $k => $temp ];
401  }
402  if ( isset( $ret[$key] ) ) {
403  $ret[$key] = array_merge( $ret[$key], $temp );
404  } else {
405  $ret[$key] = $temp;
406  }
407  } else {
408  $ret[$key] = $value;
409  }
410  }
411  return $ret;
412 }
413 
422 function wfAppendQuery( $url, $query ) {
423  if ( is_array( $query ) ) {
424  $query = wfArrayToCgi( $query );
425  }
426  if ( $query != '' ) {
427  // Remove the fragment, if there is one
428  $fragment = false;
429  $hashPos = strpos( $url, '#' );
430  if ( $hashPos !== false ) {
431  $fragment = substr( $url, $hashPos );
432  $url = substr( $url, 0, $hashPos );
433  }
434 
435  // Add parameter
436  if ( strpos( $url, '?' ) === false ) {
437  $url .= '?';
438  } else {
439  $url .= '&';
440  }
441  $url .= $query;
442 
443  // Put the fragment back
444  if ( $fragment !== false ) {
445  $url .= $fragment;
446  }
447  }
448  return $url;
449 }
450 
474 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
476  $wgHttpsPort;
477  if ( $defaultProto === PROTO_CANONICAL ) {
478  $serverUrl = $wgCanonicalServer;
479  } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
480  // Make $wgInternalServer fall back to $wgServer if not set
481  $serverUrl = $wgInternalServer;
482  } else {
483  $serverUrl = $wgServer;
484  if ( $defaultProto === PROTO_CURRENT ) {
485  $defaultProto = $wgRequest->getProtocol() . '://';
486  }
487  }
488 
489  // Analyze $serverUrl to obtain its protocol
490  $bits = wfParseUrl( $serverUrl );
491  $serverHasProto = $bits && $bits['scheme'] != '';
492 
493  if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
494  if ( $serverHasProto ) {
495  $defaultProto = $bits['scheme'] . '://';
496  } else {
497  // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
498  // This really isn't supposed to happen. Fall back to HTTP in this
499  // ridiculous case.
500  $defaultProto = PROTO_HTTP;
501  }
502  }
503 
504  $defaultProtoWithoutSlashes = $defaultProto !== null ? substr( $defaultProto, 0, -2 ) : '';
505 
506  if ( substr( $url, 0, 2 ) == '//' ) {
507  $url = $defaultProtoWithoutSlashes . $url;
508  } elseif ( substr( $url, 0, 1 ) == '/' ) {
509  // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
510  // otherwise leave it alone.
511  if ( $serverHasProto ) {
512  $url = $serverUrl . $url;
513  } else {
514  // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
515  // user to override the port number (T67184)
516  if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
517  if ( isset( $bits['port'] ) ) {
518  throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
519  }
520  $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
521  } else {
522  $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
523  }
524  }
525  }
526 
527  $bits = wfParseUrl( $url );
528 
529  if ( $bits && isset( $bits['path'] ) ) {
530  $bits['path'] = wfRemoveDotSegments( $bits['path'] );
531  return wfAssembleUrl( $bits );
532  } elseif ( $bits ) {
533  # No path to expand
534  return $url;
535  } elseif ( substr( $url, 0, 1 ) != '/' ) {
536  # URL is a relative path
537  return wfRemoveDotSegments( $url );
538  }
539 
540  # Expanded URL is not valid.
541  return false;
542 }
543 
552 function wfGetServerUrl( $proto ) {
553  $url = wfExpandUrl( '/', $proto );
554  return substr( $url, 0, -1 );
555 }
556 
570 function wfAssembleUrl( $urlParts ) {
571  $result = '';
572 
573  if ( isset( $urlParts['delimiter'] ) ) {
574  if ( isset( $urlParts['scheme'] ) ) {
575  $result .= $urlParts['scheme'];
576  }
577 
578  $result .= $urlParts['delimiter'];
579  }
580 
581  if ( isset( $urlParts['host'] ) ) {
582  if ( isset( $urlParts['user'] ) ) {
583  $result .= $urlParts['user'];
584  if ( isset( $urlParts['pass'] ) ) {
585  $result .= ':' . $urlParts['pass'];
586  }
587  $result .= '@';
588  }
589 
590  $result .= $urlParts['host'];
591 
592  if ( isset( $urlParts['port'] ) ) {
593  $result .= ':' . $urlParts['port'];
594  }
595  }
596 
597  if ( isset( $urlParts['path'] ) ) {
598  $result .= $urlParts['path'];
599  }
600 
601  if ( isset( $urlParts['query'] ) && $urlParts['query'] !== '' ) {
602  $result .= '?' . $urlParts['query'];
603  }
604 
605  if ( isset( $urlParts['fragment'] ) ) {
606  $result .= '#' . $urlParts['fragment'];
607  }
608 
609  return $result;
610 }
611 
624 function wfRemoveDotSegments( $urlPath ) {
625  $output = '';
626  $inputOffset = 0;
627  $inputLength = strlen( $urlPath );
628 
629  while ( $inputOffset < $inputLength ) {
630  $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
631  $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
632  $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
633  $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
634  $trimOutput = false;
635 
636  if ( $prefixLengthTwo == './' ) {
637  # Step A, remove leading "./"
638  $inputOffset += 2;
639  } elseif ( $prefixLengthThree == '../' ) {
640  # Step A, remove leading "../"
641  $inputOffset += 3;
642  } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
643  # Step B, replace leading "/.$" with "/"
644  $inputOffset += 1;
645  $urlPath[$inputOffset] = '/';
646  } elseif ( $prefixLengthThree == '/./' ) {
647  # Step B, replace leading "/./" with "/"
648  $inputOffset += 2;
649  } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
650  # Step C, replace leading "/..$" with "/" and
651  # remove last path component in output
652  $inputOffset += 2;
653  $urlPath[$inputOffset] = '/';
654  $trimOutput = true;
655  } elseif ( $prefixLengthFour == '/../' ) {
656  # Step C, replace leading "/../" with "/" and
657  # remove last path component in output
658  $inputOffset += 3;
659  $trimOutput = true;
660  } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
661  # Step D, remove "^.$"
662  $inputOffset += 1;
663  } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
664  # Step D, remove "^..$"
665  $inputOffset += 2;
666  } else {
667  # Step E, move leading path segment to output
668  if ( $prefixLengthOne == '/' ) {
669  $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
670  } else {
671  $slashPos = strpos( $urlPath, '/', $inputOffset );
672  }
673  if ( $slashPos === false ) {
674  $output .= substr( $urlPath, $inputOffset );
675  $inputOffset = $inputLength;
676  } else {
677  $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
678  $inputOffset += $slashPos - $inputOffset;
679  }
680  }
681 
682  if ( $trimOutput ) {
683  $slashPos = strrpos( $output, '/' );
684  if ( $slashPos === false ) {
685  $output = '';
686  } else {
687  $output = substr( $output, 0, $slashPos );
688  }
689  }
690  }
691 
692  return $output;
693 }
694 
702 function wfUrlProtocols( $includeProtocolRelative = true ) {
703  global $wgUrlProtocols;
704 
705  // Cache return values separately based on $includeProtocolRelative
706  static $withProtRel = null, $withoutProtRel = null;
707  $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
708  if ( $cachedValue !== null ) {
709  return $cachedValue;
710  }
711 
712  // Support old-style $wgUrlProtocols strings, for backwards compatibility
713  // with LocalSettings files from 1.5
714  if ( is_array( $wgUrlProtocols ) ) {
715  $protocols = [];
716  foreach ( $wgUrlProtocols as $protocol ) {
717  // Filter out '//' if !$includeProtocolRelative
718  if ( $includeProtocolRelative || $protocol !== '//' ) {
719  $protocols[] = preg_quote( $protocol, '/' );
720  }
721  }
722 
723  $retval = implode( '|', $protocols );
724  } else {
725  // Ignore $includeProtocolRelative in this case
726  // This case exists for pre-1.6 compatibility, and we can safely assume
727  // that '//' won't appear in a pre-1.6 config because protocol-relative
728  // URLs weren't supported until 1.18
729  $retval = $wgUrlProtocols;
730  }
731 
732  // Cache return value
733  if ( $includeProtocolRelative ) {
734  $withProtRel = $retval;
735  } else {
736  $withoutProtRel = $retval;
737  }
738  return $retval;
739 }
740 
748  return wfUrlProtocols( false );
749 }
750 
776 function wfParseUrl( $url ) {
777  global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
778 
779  // Protocol-relative URLs are handled really badly by parse_url(). It's so
780  // bad that the easiest way to handle them is to just prepend 'http:' and
781  // strip the protocol out later.
782  $wasRelative = substr( $url, 0, 2 ) == '//';
783  if ( $wasRelative ) {
784  $url = "http:$url";
785  }
786  $bits = parse_url( $url );
787  // parse_url() returns an array without scheme for some invalid URLs, e.g.
788  // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
789  if ( !$bits || !isset( $bits['scheme'] ) ) {
790  return false;
791  }
792 
793  // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
794  $bits['scheme'] = strtolower( $bits['scheme'] );
795 
796  // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
797  if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
798  $bits['delimiter'] = '://';
799  } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
800  $bits['delimiter'] = ':';
801  // parse_url detects for news: and mailto: the host part of an url as path
802  // We have to correct this wrong detection
803  if ( isset( $bits['path'] ) ) {
804  $bits['host'] = $bits['path'];
805  $bits['path'] = '';
806  }
807  } else {
808  return false;
809  }
810 
811  /* Provide an empty host for eg. file:/// urls (see T30627) */
812  if ( !isset( $bits['host'] ) ) {
813  $bits['host'] = '';
814 
815  // See T47069
816  if ( isset( $bits['path'] ) ) {
817  /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
818  if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
819  $bits['path'] = '/' . $bits['path'];
820  }
821  } else {
822  $bits['path'] = '';
823  }
824  }
825 
826  // If the URL was protocol-relative, fix scheme and delimiter
827  if ( $wasRelative ) {
828  $bits['scheme'] = '';
829  $bits['delimiter'] = '//';
830  }
831  return $bits;
832 }
833 
844 function wfExpandIRI( $url ) {
845  return preg_replace_callback(
846  '/((?:%[89A-F][0-9A-F])+)/i',
847  static function ( array $matches ) {
848  return urldecode( $matches[1] );
849  },
850  wfExpandUrl( $url )
851  );
852 }
853 
860 function wfMatchesDomainList( $url, $domains ) {
861  $bits = wfParseUrl( $url );
862  if ( is_array( $bits ) && isset( $bits['host'] ) ) {
863  $host = '.' . $bits['host'];
864  foreach ( (array)$domains as $domain ) {
865  $domain = '.' . $domain;
866  if ( substr( $host, -strlen( $domain ) ) === $domain ) {
867  return true;
868  }
869  }
870  }
871  return false;
872 }
873 
894 function wfDebug( $text, $dest = 'all', array $context = [] ) {
896 
897  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
898  return;
899  }
900 
901  $text = trim( $text );
902 
903  if ( $wgDebugLogPrefix !== '' ) {
904  $context['prefix'] = $wgDebugLogPrefix;
905  }
906  $context['private'] = ( $dest === false || $dest === 'private' );
907 
908  $logger = LoggerFactory::getInstance( 'wfDebug' );
909  $logger->debug( $text, $context );
910 }
911 
916 function wfIsDebugRawPage() {
917  static $cache;
918  if ( $cache !== null ) {
919  return $cache;
920  }
921  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
922  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
923  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
924  || MW_ENTRY_POINT === 'load'
925  ) {
926  $cache = true;
927  } else {
928  $cache = false;
929  }
930  return $cache;
931 }
932 
958 function wfDebugLog(
959  $logGroup, $text, $dest = 'all', array $context = []
960 ) {
961  $text = trim( $text );
962 
963  $logger = LoggerFactory::getInstance( $logGroup );
964  $context['private'] = ( $dest === false || $dest === 'private' );
965  $logger->info( $text, $context );
966 }
967 
976 function wfLogDBError( $text, array $context = [] ) {
977  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
978  $logger->error( trim( $text ), $context );
979 }
980 
996 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
997  if ( is_string( $version ) || $version === false ) {
998  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
999  } else {
1000  throw new InvalidArgumentException(
1001  "MediaWiki version must either be a string or false. " .
1002  "Example valid version: '1.33'"
1003  );
1004  }
1005 }
1006 
1028 function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
1029  MWDebug::deprecatedMsg( $msg, $version, $component,
1030  $callerOffset === false ? false : $callerOffset + 1 );
1031 }
1032 
1043 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1044  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1045 }
1046 
1056 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1057  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1058 }
1059 
1065  $context = RequestContext::getMain();
1066 
1067  $profiler = Profiler::instance();
1068  $profiler->setContext( $context );
1069  $profiler->logData();
1070 
1071  // Send out any buffered statsd metrics as needed
1073  MediaWikiServices::getInstance()->getStatsdDataFactory(),
1074  $context->getConfig()
1075  );
1076 }
1077 
1088 function wfIncrStats( $key, $count = 1 ) {
1089  wfDeprecated( __FUNCTION__, '1.36' );
1090  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1091  $stats->updateCount( $key, $count );
1092 }
1093 
1099 function wfReadOnly() {
1100  return MediaWikiServices::getInstance()->getReadOnlyMode()
1101  ->isReadOnly();
1102 }
1103 
1112 function wfReadOnlyReason() {
1113  return MediaWikiServices::getInstance()->getReadOnlyMode()
1114  ->getReason();
1115 }
1116 
1132 function wfGetLangObj( $langcode = false ) {
1133  # Identify which language to get or create a language object for.
1134  # Using is_object here due to Stub objects.
1135  if ( is_object( $langcode ) ) {
1136  # Great, we already have the object (hopefully)!
1137  return $langcode;
1138  }
1139 
1140  global $wgLanguageCode;
1141  $services = MediaWikiServices::getInstance();
1142  if ( $langcode === true || $langcode === $wgLanguageCode ) {
1143  # $langcode is the language code of the wikis content language object.
1144  # or it is a boolean and value is true
1145  return $services->getContentLanguage();
1146  }
1147 
1148  global $wgLang;
1149  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1150  # $langcode is the language code of user language object.
1151  # or it was a boolean and value is false
1152  return $wgLang;
1153  }
1154 
1155  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1156  if ( in_array( $langcode, $validCodes ) ) {
1157  # $langcode corresponds to a valid language.
1158  return $services->getLanguageFactory()->getLanguage( $langcode );
1159  }
1160 
1161  # $langcode is a string, but not a valid language code; use content language.
1162  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1163  return $services->getContentLanguage();
1164 }
1165 
1182 function wfMessage( $key, ...$params ) {
1183  $message = new Message( $key );
1184 
1185  // We call Message::params() to reduce code duplication
1186  if ( $params ) {
1187  $message->params( ...$params );
1188  }
1189 
1190  return $message;
1191 }
1192 
1205 function wfMessageFallback( ...$keys ) {
1206  return Message::newFallbackSequence( ...$keys );
1207 }
1208 
1217 function wfMsgReplaceArgs( $message, $args ) {
1218  # Fix windows line-endings
1219  # Some messages are split with explode("\n", $msg)
1220  $message = str_replace( "\r", '', $message );
1221 
1222  // Replace arguments
1223  if ( is_array( $args ) && $args ) {
1224  if ( is_array( $args[0] ) ) {
1225  $args = array_values( $args[0] );
1226  }
1227  $replacementKeys = [];
1228  foreach ( $args as $n => $param ) {
1229  $replacementKeys['$' . ( $n + 1 )] = $param;
1230  }
1231  $message = strtr( $message, $replacementKeys );
1232  }
1233 
1234  return $message;
1235 }
1236 
1245 function wfHostname() {
1246  // Hostname overriding
1247  global $wgOverrideHostname;
1248  if ( $wgOverrideHostname !== false ) {
1249  return $wgOverrideHostname;
1250  }
1251 
1252  return php_uname( 'n' ) ?: 'unknown';
1253 }
1254 
1265 function wfReportTime( $nonce = null ) {
1266  global $wgShowHostnames;
1267 
1268  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1269  // seconds to milliseconds
1270  $responseTime = round( $elapsed * 1000 );
1271  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1272  if ( $wgShowHostnames ) {
1273  $reportVars['wgHostname'] = wfHostname();
1274  }
1275 
1276  return (
1278  ResourceLoader::makeConfigSetScript( $reportVars ),
1279  $nonce
1280  )
1281  );
1282 }
1283 
1294 function wfDebugBacktrace( $limit = 0 ) {
1295  static $disabled = null;
1296 
1297  if ( $disabled === null ) {
1298  $disabled = !function_exists( 'debug_backtrace' );
1299  if ( $disabled ) {
1300  wfDebug( "debug_backtrace() is disabled" );
1301  }
1302  }
1303  if ( $disabled ) {
1304  return [];
1305  }
1306 
1307  if ( $limit ) {
1308  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1309  } else {
1310  return array_slice( debug_backtrace(), 1 );
1311  }
1312 }
1313 
1322 function wfBacktrace( $raw = null ) {
1323  global $wgCommandLineMode;
1324 
1325  if ( $raw === null ) {
1326  $raw = $wgCommandLineMode;
1327  }
1328 
1329  if ( $raw ) {
1330  $frameFormat = "%s line %s calls %s()\n";
1331  $traceFormat = "%s";
1332  } else {
1333  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1334  $traceFormat = "<ul>\n%s</ul>\n";
1335  }
1336 
1337  $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1338  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1339  $line = $frame['line'] ?? '-';
1340  $call = $frame['function'];
1341  if ( !empty( $frame['class'] ) ) {
1342  $call = $frame['class'] . $frame['type'] . $call;
1343  }
1344  return sprintf( $frameFormat, $file, $line, $call );
1345  }, wfDebugBacktrace() );
1346 
1347  return sprintf( $traceFormat, implode( '', $frames ) );
1348 }
1349 
1359 function wfGetCaller( $level = 2 ) {
1360  $backtrace = wfDebugBacktrace( $level + 1 );
1361  if ( isset( $backtrace[$level] ) ) {
1362  return wfFormatStackFrame( $backtrace[$level] );
1363  } else {
1364  return 'unknown';
1365  }
1366 }
1367 
1375 function wfGetAllCallers( $limit = 3 ) {
1376  $trace = array_reverse( wfDebugBacktrace() );
1377  if ( !$limit || $limit > count( $trace ) - 1 ) {
1378  $limit = count( $trace ) - 1;
1379  }
1380  $trace = array_slice( $trace, -$limit - 1, $limit );
1381  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1382 }
1383 
1390 function wfFormatStackFrame( $frame ) {
1391  if ( !isset( $frame['function'] ) ) {
1392  return 'NO_FUNCTION_GIVEN';
1393  }
1394  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1395  $frame['class'] . $frame['type'] . $frame['function'] :
1396  $frame['function'];
1397 }
1398 
1399 /* Some generic result counters, pulled out of SearchEngine */
1400 
1408 function wfShowingResults( $offset, $limit ) {
1409  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1410 }
1411 
1421 function wfClientAcceptsGzip( $force = false ) {
1422  static $result = null;
1423  if ( $result === null || $force ) {
1424  $result = false;
1425  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1426  # @todo FIXME: We may want to disallow some broken browsers
1427  $m = [];
1428  if ( preg_match(
1429  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1430  $_SERVER['HTTP_ACCEPT_ENCODING'],
1431  $m
1432  )
1433  ) {
1434  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1435  $result = false;
1436  return $result;
1437  }
1438  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1439  $result = true;
1440  }
1441  }
1442  }
1443  return $result;
1444 }
1445 
1456 function wfEscapeWikiText( $text ) {
1457  global $wgEnableMagicLinks;
1458  static $repl = null, $repl2 = null;
1459  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1460  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1461  // in those situations
1462  $repl = [
1463  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1464  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1465  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1466  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1467  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1468  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1469  "\n " => "\n&#32;", "\r " => "\r&#32;",
1470  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1471  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1472  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1473  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1474  '__' => '_&#95;', '://' => '&#58;//',
1475  ];
1476 
1477  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1478  // We have to catch everything "\s" matches in PCRE
1479  foreach ( $magicLinks as $magic ) {
1480  $repl["$magic "] = "$magic&#32;";
1481  $repl["$magic\t"] = "$magic&#9;";
1482  $repl["$magic\r"] = "$magic&#13;";
1483  $repl["$magic\n"] = "$magic&#10;";
1484  $repl["$magic\f"] = "$magic&#12;";
1485  }
1486 
1487  // And handle protocols that don't use "://"
1488  global $wgUrlProtocols;
1489  $repl2 = [];
1490  foreach ( $wgUrlProtocols as $prot ) {
1491  if ( substr( $prot, -1 ) === ':' ) {
1492  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1493  }
1494  }
1495  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1496  }
1497  $text = substr( strtr( "\n$text", $repl ), 1 );
1498  $text = preg_replace( $repl2, '$1&#58;', $text );
1499  return $text;
1500 }
1501 
1512 function wfSetVar( &$dest, $source, $force = false ) {
1513  $temp = $dest;
1514  if ( $source !== null || $force ) {
1515  $dest = $source;
1516  }
1517  return $temp;
1518 }
1519 
1529 function wfSetBit( &$dest, $bit, $state = true ) {
1530  $temp = (bool)( $dest & $bit );
1531  if ( $state !== null ) {
1532  if ( $state ) {
1533  $dest |= $bit;
1534  } else {
1535  $dest &= ~$bit;
1536  }
1537  }
1538  return $temp;
1539 }
1540 
1547 function wfVarDump( $var ) {
1548  global $wgOut;
1549  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1550  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1551  print $s;
1552  } else {
1553  $wgOut->addHTML( $s );
1554  }
1555 }
1556 
1564 function wfHttpError( $code, $label, $desc ) {
1565  global $wgOut;
1566  HttpStatus::header( $code );
1567  if ( $wgOut ) {
1568  $wgOut->disable();
1569  $wgOut->sendCacheControl();
1570  }
1571 
1573  header( 'Content-type: text/html; charset=utf-8' );
1574  ob_start();
1575  print '<!DOCTYPE html>' .
1576  '<html><head><title>' .
1577  htmlspecialchars( $label ) .
1578  '</title></head><body><h1>' .
1579  htmlspecialchars( $label ) .
1580  '</h1><p>' .
1581  nl2br( htmlspecialchars( $desc ) ) .
1582  "</p></body></html>\n";
1583  header( 'Content-Length: ' . ob_get_length() );
1584  ob_end_flush();
1585 }
1586 
1604 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1605  while ( $status = ob_get_status() ) {
1606  if ( isset( $status['flags'] ) ) {
1607  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1608  $deleteable = ( $status['flags'] & $flags ) === $flags;
1609  } elseif ( isset( $status['del'] ) ) {
1610  $deleteable = $status['del'];
1611  } else {
1612  // Guess that any PHP-internal setting can't be removed.
1613  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1614  }
1615  if ( !$deleteable ) {
1616  // Give up, and hope the result doesn't break
1617  // output behavior.
1618  break;
1619  }
1620  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1621  // Unit testing barrier to prevent this function from breaking PHPUnit.
1622  break;
1623  }
1624  if ( !ob_end_clean() ) {
1625  // Could not remove output buffer handler; abort now
1626  // to avoid getting in some kind of infinite loop.
1627  break;
1628  }
1629  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1630  // Reset the 'Content-Encoding' field set by this handler
1631  // so we can start fresh.
1632  header_remove( 'Content-Encoding' );
1633  break;
1634  }
1635  }
1636 }
1637 
1653  wfDeprecated( __FUNCTION__, '1.36' );
1654  wfResetOutputBuffers( false );
1655 }
1656 
1669 function mimeTypeMatch( $type, $avail ) {
1670  if ( array_key_exists( $type, $avail ) ) {
1671  return $type;
1672  } else {
1673  $mainType = explode( '/', $type )[0];
1674  if ( array_key_exists( "$mainType/*", $avail ) ) {
1675  return "$mainType/*";
1676  } elseif ( array_key_exists( '*/*', $avail ) ) {
1677  return '*/*';
1678  } else {
1679  return null;
1680  }
1681  }
1682 }
1683 
1692 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1693  $ret = MWTimestamp::convert( $outputtype, $ts );
1694  if ( $ret === false ) {
1695  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1696  }
1697  return $ret;
1698 }
1699 
1708 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1709  if ( $ts === null ) {
1710  return null;
1711  } else {
1712  return wfTimestamp( $outputtype, $ts );
1713  }
1714 }
1715 
1721 function wfTimestampNow() {
1722  return MWTimestamp::now( TS_MW );
1723 }
1724 
1730 function wfIsWindows() {
1731  return PHP_OS_FAMILY === 'Windows';
1732 }
1733 
1740 function wfIsCLI() {
1741  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1742 }
1743 
1755 function wfTempDir() {
1756  global $wgTmpDirectory;
1757 
1758  if ( $wgTmpDirectory !== false ) {
1759  return $wgTmpDirectory;
1760  }
1761 
1763 }
1764 
1774 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1775  global $wgDirectoryMode;
1776 
1777  if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1778  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1779  }
1780 
1781  if ( $caller !== null ) {
1782  wfDebug( "$caller: called wfMkdirParents($dir)" );
1783  }
1784 
1785  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1786  return true;
1787  }
1788 
1789  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1790 
1791  if ( $mode === null ) {
1792  $mode = $wgDirectoryMode;
1793  }
1794 
1795  // Turn off the normal warning, we're doing our own below
1796  AtEase::suppressWarnings();
1797  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1798  AtEase::restoreWarnings();
1799 
1800  if ( !$ok ) {
1801  // directory may have been created on another request since we last checked
1802  if ( is_dir( $dir ) ) {
1803  return true;
1804  }
1805 
1806  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1807  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1808  }
1809  return $ok;
1810 }
1811 
1817 function wfRecursiveRemoveDir( $dir ) {
1818  wfDebug( __FUNCTION__ . "( $dir )" );
1819  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1820  if ( is_dir( $dir ) ) {
1821  $objects = scandir( $dir );
1822  foreach ( $objects as $object ) {
1823  if ( $object != "." && $object != ".." ) {
1824  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1825  wfRecursiveRemoveDir( $dir . '/' . $object );
1826  } else {
1827  unlink( $dir . '/' . $object );
1828  }
1829  }
1830  }
1831  reset( $objects );
1832  rmdir( $dir );
1833  }
1834 }
1835 
1842 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1843  $accForFormat = $acc >= 0 ? $acc : 0;
1844  $ret = sprintf( "%.${accForFormat}f", $nr );
1845  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1846 }
1847 
1871 function wfIniGetBool( $setting ) {
1872  return wfStringToBool( ini_get( $setting ) );
1873 }
1874 
1887 function wfStringToBool( $val ) {
1888  $val = strtolower( $val );
1889  // 'on' and 'true' can't have whitespace around them, but '1' can.
1890  return $val == 'on'
1891  || $val == 'true'
1892  || $val == 'yes'
1893  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1894 }
1895 
1908 function wfEscapeShellArg( ...$args ) {
1909  return Shell::escape( ...$args );
1910 }
1911 
1936 function wfShellExec( $cmd, &$retval = null, $environ = [],
1937  $limits = [], $options = []
1938 ) {
1939  if ( Shell::isDisabled() ) {
1940  $retval = 1;
1941  // Backwards compatibility be upon us...
1942  return 'Unable to run external programs, proc_open() is disabled.';
1943  }
1944 
1945  if ( is_array( $cmd ) ) {
1946  $cmd = Shell::escape( $cmd );
1947  }
1948 
1949  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1950  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1951 
1952  try {
1953  $result = Shell::command( [] )
1954  ->unsafeParams( (array)$cmd )
1955  ->environment( $environ )
1956  ->limits( $limits )
1957  ->includeStderr( $includeStderr )
1958  ->profileMethod( $profileMethod )
1959  // For b/c
1960  ->restrict( Shell::RESTRICT_NONE )
1961  ->execute();
1962  } catch ( ProcOpenError $ex ) {
1963  $retval = -1;
1964  return '';
1965  }
1966 
1967  $retval = $result->getExitCode();
1968 
1969  return $result->getStdout();
1970 }
1971 
1989 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1990  return wfShellExec( $cmd, $retval, $environ, $limits,
1991  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1992 }
1993 
2009 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2010  global $wgPhpCli;
2011  // Give site config file a chance to run the script in a wrapper.
2012  // The caller may likely want to call wfBasename() on $script.
2013  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
2014  $cmd = [ $options['php'] ?? $wgPhpCli ];
2015  if ( isset( $options['wrapper'] ) ) {
2016  $cmd[] = $options['wrapper'];
2017  }
2018  $cmd[] = $script;
2019  // Escape each parameter for shell
2020  return Shell::escape( array_merge( $cmd, $parameters ) );
2021 }
2022 
2034 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2035  global $wgDiff3;
2036 
2037  # This check may also protect against code injection in
2038  # case of broken installations.
2039  AtEase::suppressWarnings();
2040  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2041  AtEase::restoreWarnings();
2042 
2043  if ( !$haveDiff3 ) {
2044  wfDebug( "diff3 not found" );
2045  return false;
2046  }
2047 
2048  # Make temporary files
2049  $td = wfTempDir();
2050  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2051  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2052  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2053 
2054  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2055  # a newline character. To avoid this, we normalize the trailing whitespace before
2056  # creating the diff.
2057 
2058  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2059  fclose( $oldtextFile );
2060  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2061  fclose( $mytextFile );
2062  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2063  fclose( $yourtextFile );
2064 
2065  # Check for a conflict
2066  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2067  $oldtextName, $yourtextName );
2068  $handle = popen( $cmd, 'r' );
2069 
2070  $mergeAttemptResult = '';
2071  do {
2072  $data = fread( $handle, 8192 );
2073  if ( strlen( $data ) == 0 ) {
2074  break;
2075  }
2076  $mergeAttemptResult .= $data;
2077  } while ( true );
2078  pclose( $handle );
2079 
2080  $conflict = $mergeAttemptResult !== '';
2081 
2082  # Merge differences
2083  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2084  $oldtextName, $yourtextName );
2085  $handle = popen( $cmd, 'r' );
2086  $result = '';
2087  do {
2088  $data = fread( $handle, 8192 );
2089  if ( strlen( $data ) == 0 ) {
2090  break;
2091  }
2092  $result .= $data;
2093  } while ( true );
2094  pclose( $handle );
2095  unlink( $mytextName );
2096  unlink( $oldtextName );
2097  unlink( $yourtextName );
2098 
2099  if ( $result === '' && $old !== '' && !$conflict ) {
2100  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2101  $conflict = true;
2102  }
2103  return !$conflict;
2104 }
2105 
2118 function wfBaseName( $path, $suffix = '' ) {
2119  if ( $suffix == '' ) {
2120  $encSuffix = '';
2121  } else {
2122  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2123  }
2124 
2125  $matches = [];
2126  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2127  return $matches[1];
2128  } else {
2129  return '';
2130  }
2131 }
2132 
2142 function wfRelativePath( $path, $from ) {
2143  // Normalize mixed input on Windows...
2144  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2145  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2146 
2147  // Trim trailing slashes -- fix for drive root
2148  $path = rtrim( $path, DIRECTORY_SEPARATOR );
2149  $from = rtrim( $from, DIRECTORY_SEPARATOR );
2150 
2151  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2152  $against = explode( DIRECTORY_SEPARATOR, $from );
2153 
2154  if ( $pieces[0] !== $against[0] ) {
2155  // Non-matching Windows drive letters?
2156  // Return a full path.
2157  return $path;
2158  }
2159 
2160  // Trim off common prefix
2161  while ( count( $pieces ) && count( $against )
2162  && $pieces[0] == $against[0] ) {
2163  array_shift( $pieces );
2164  array_shift( $against );
2165  }
2166 
2167  // relative dots to bump us to the parent
2168  while ( count( $against ) ) {
2169  array_unshift( $pieces, '..' );
2170  array_shift( $against );
2171  }
2172 
2173  $pieces[] = wfBaseName( $path );
2174 
2175  return implode( DIRECTORY_SEPARATOR, $pieces );
2176 }
2177 
2185 function wfWikiID() {
2186  global $wgDBprefix, $wgDBname;
2187 
2188  if ( $wgDBprefix ) {
2189  return "$wgDBname-$wgDBprefix";
2190  } else {
2191  return $wgDBname;
2192  }
2193 }
2194 
2226 function wfGetDB( $db, $groups = [], $wiki = false ) {
2227  if ( $wiki === false ) {
2228  return MediaWikiServices::getInstance()
2229  ->getDBLoadBalancer()
2230  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2231  } else {
2232  return MediaWikiServices::getInstance()
2233  ->getDBLoadBalancerFactory()
2234  ->getMainLB( $wiki )
2235  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2236  }
2237 }
2238 
2249 function wfGetLB( $wiki = false ) {
2250  wfDeprecated( __FUNCTION__, '1.27' );
2251  if ( $wiki === false ) {
2252  return MediaWikiServices::getInstance()->getDBLoadBalancer();
2253  } else {
2254  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2255  return $factory->getMainLB( $wiki );
2256  }
2257 }
2258 
2266 function wfFindFile( $title, $options = [] ) {
2267  wfDeprecated( __FUNCTION__, '1.34' );
2268  return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2269 }
2270 
2279 function wfLocalFile( $title ) {
2280  wfDeprecated( __FUNCTION__, '1.34' );
2281  return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2282 }
2283 
2291  global $wgMiserMode;
2292  return $wgMiserMode
2293  || ( SiteStats::pages() > 100000
2294  && SiteStats::edits() > 1000000
2295  && SiteStats::users() > 10000 );
2296 }
2297 
2306 function wfScript( $script = 'index' ) {
2308  if ( $script === 'index' ) {
2309  return $wgScript;
2310  } elseif ( $script === 'load' ) {
2311  return $wgLoadScript;
2312  } else {
2313  return "{$wgScriptPath}/{$script}.php";
2314  }
2315 }
2316 
2323 function wfGetScriptUrl() {
2324  wfDeprecated( __FUNCTION__, '1.35' );
2325  if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2326  /* as it was called, minus the query string.
2327  *
2328  * Some sites use Apache rewrite rules to handle subdomains,
2329  * and have PHP set up in a weird way that causes PHP_SELF
2330  * to contain the rewritten URL instead of the one that the
2331  * outside world sees.
2332  *
2333  * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2334  * provides containing the "before" URL.
2335  */
2336  return $_SERVER['SCRIPT_NAME'];
2337  } else {
2338  return $_SERVER['URL'];
2339  }
2340 }
2341 
2349 function wfBoolToStr( $value ) {
2350  return $value ? 'true' : 'false';
2351 }
2352 
2358 function wfGetNull() {
2359  return wfIsWindows() ? 'NUL' : '/dev/null';
2360 }
2361 
2370 function wfStripIllegalFilenameChars( $name ) {
2371  global $wgIllegalFileChars;
2372  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2373  $name = preg_replace(
2374  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2375  '-',
2376  $name
2377  );
2378  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2379  $name = wfBaseName( $name );
2380  return $name;
2381 }
2382 
2389 function wfMemoryLimit( $newLimit ) {
2390  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2391  // If the INI config is already unlimited, there is nothing larger
2392  if ( $oldLimit != -1 ) {
2393  $newLimit = wfShorthandToInteger( $newLimit );
2394  if ( $newLimit == -1 ) {
2395  wfDebug( "Removing PHP's memory limit" );
2396  Wikimedia\suppressWarnings();
2397  ini_set( 'memory_limit', $newLimit );
2398  Wikimedia\restoreWarnings();
2399  } elseif ( $newLimit > $oldLimit ) {
2400  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2401  Wikimedia\suppressWarnings();
2402  ini_set( 'memory_limit', $newLimit );
2403  Wikimedia\restoreWarnings();
2404  }
2405  }
2406 }
2407 
2416 
2417  $timeout = RequestTimeout::singleton();
2418  $timeLimit = $timeout->getWallTimeLimit();
2419  if ( $timeLimit !== INF ) {
2420  // RequestTimeout library is active
2421  if ( $wgTransactionalTimeLimit > $timeLimit ) {
2422  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2423  }
2424  } else {
2425  // Fallback case, likely $wgRequestTimeLimit === null
2426  $timeLimit = (int)ini_get( 'max_execution_time' );
2427  // Note that CLI scripts use 0
2428  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2429  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2430  }
2431  }
2432  ignore_user_abort( true ); // ignore client disconnects
2433 
2434  return $timeLimit;
2435 }
2436 
2444 function wfShorthandToInteger( $string = '', $default = -1 ) {
2445  $string = trim( $string );
2446  if ( $string === '' ) {
2447  return $default;
2448  }
2449  $last = $string[strlen( $string ) - 1];
2450  $val = intval( $string );
2451  switch ( $last ) {
2452  case 'g':
2453  case 'G':
2454  $val *= 1024;
2455  // break intentionally missing
2456  case 'm':
2457  case 'M':
2458  $val *= 1024;
2459  // break intentionally missing
2460  case 'k':
2461  case 'K':
2462  $val *= 1024;
2463  }
2464 
2465  return $val;
2466 }
2467 
2475 function wfGetCache( $cacheType ) {
2476  return ObjectCache::getInstance( $cacheType );
2477 }
2478 
2485 function wfGetMainCache() {
2487 }
2488 
2503 function wfUnpack( $format, $data, $length = false ) {
2504  if ( $length !== false ) {
2505  $realLen = strlen( $data );
2506  if ( $realLen < $length ) {
2507  throw new MWException( "Tried to use wfUnpack on a "
2508  . "string of length $realLen, but needed one "
2509  . "of at least length $length."
2510  );
2511  }
2512  }
2513 
2514  Wikimedia\suppressWarnings();
2515  $result = unpack( $format, $data );
2516  Wikimedia\restoreWarnings();
2517 
2518  if ( $result === false ) {
2519  // If it cannot extract the packed data.
2520  throw new MWException( "unpack could not unpack binary data" );
2521  }
2522  return $result;
2523 }
2524 
2534 function wfCanIPUseHTTPS( $ip ) {
2535  wfDeprecated( __FUNCTION__, '1.37' );
2536  return true;
2537 }
2538 
2546 function wfIsInfinity( $str ) {
2547  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2548  return in_array( $str, ExpiryDef::INFINITY_VALS );
2549 }
2550 
2565 function wfThumbIsStandard( File $file, array $params ) {
2567 
2568  $multipliers = [ 1 ];
2569  if ( $wgResponsiveImages ) {
2570  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2571  // @see Linker::processResponsiveImages
2572  $multipliers[] = 1.5;
2573  $multipliers[] = 2;
2574  }
2575 
2576  $handler = $file->getHandler();
2577  if ( !$handler || !isset( $params['width'] ) ) {
2578  return false;
2579  }
2580 
2581  $basicParams = [];
2582  if ( isset( $params['page'] ) ) {
2583  $basicParams['page'] = $params['page'];
2584  }
2585 
2586  $thumbLimits = [];
2587  $imageLimits = [];
2588  // Expand limits to account for multipliers
2589  foreach ( $multipliers as $multiplier ) {
2590  $thumbLimits = array_merge( $thumbLimits, array_map(
2591  static function ( $width ) use ( $multiplier ) {
2592  return round( $width * $multiplier );
2593  }, $wgThumbLimits )
2594  );
2595  $imageLimits = array_merge( $imageLimits, array_map(
2596  static function ( $pair ) use ( $multiplier ) {
2597  return [
2598  round( $pair[0] * $multiplier ),
2599  round( $pair[1] * $multiplier ),
2600  ];
2601  }, $wgImageLimits )
2602  );
2603  }
2604 
2605  // Check if the width matches one of $wgThumbLimits
2606  if ( in_array( $params['width'], $thumbLimits ) ) {
2607  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2608  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2609  $handler->normaliseParams( $file, $normalParams );
2610  } else {
2611  // If not, then check if the width matchs one of $wgImageLimits
2612  $match = false;
2613  foreach ( $imageLimits as $pair ) {
2614  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2615  // Decide whether the thumbnail should be scaled on width or height.
2616  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2617  $handler->normaliseParams( $file, $normalParams );
2618  // Check if this standard thumbnail size maps to the given width
2619  if ( $normalParams['width'] == $params['width'] ) {
2620  $match = true;
2621  break;
2622  }
2623  }
2624  if ( !$match ) {
2625  return false; // not standard for description pages
2626  }
2627  }
2628 
2629  // Check that the given values for non-page, non-width, params are just defaults
2630  foreach ( $params as $key => $value ) {
2631  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2632  return false;
2633  }
2634  }
2635 
2636  return true;
2637 }
2638 
2651 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2652  // First merge items that are in both arrays
2653  foreach ( $baseArray as $name => &$groupVal ) {
2654  if ( isset( $newValues[$name] ) ) {
2655  $groupVal += $newValues[$name];
2656  }
2657  }
2658  // Now add items that didn't exist yet
2659  $baseArray += $newValues;
2660 
2661  return $baseArray;
2662 }
$wgPhpCli
$wgPhpCli
Executable path of the PHP cli binary.
Definition: DefaultSettings.php:9543
wfArrayInsertAfter
wfArrayInsertAfter(array $array, array $insert, $after)
Insert array into another array after the specified KEY
Definition: GlobalFunctions.php:189
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:45
wfMergeErrorArrays
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
Definition: GlobalFunctions.php:163
wfResetOutputBuffers
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
Definition: GlobalFunctions.php:1604
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1205
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1638
wfCanIPUseHTTPS
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
Definition: GlobalFunctions.php:2534
ResourceLoader\makeConfigSetScript
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
Definition: ResourceLoader.php:1669
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:272
SiteStats\users
static users()
Definition: SiteStats.php:121
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1156
MediaWiki\ProcOpenError
@newable
Definition: ProcOpenError.php:28
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1756
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:193
$wgDebugRawPage
$wgDebugRawPage
If true, log debugging data from action=raw and load.php.
Definition: DefaultSettings.php:7279
wfThumbIsStandard
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
Definition: GlobalFunctions.php:2565
$wgTmpDirectory
$wgTmpDirectory
The local filesystem path to a temporary directory.
Definition: DefaultSettings.php:452
wfArrayPlus2d
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
Definition: GlobalFunctions.php:2651
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:2062
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:1774
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:186
$wgRequest
$wgRequest
Definition: Setup.php:681
$wgDiff3
$wgDiff3
Path to the GNU diff3 utility.
Definition: DefaultSettings.php:7782
wfMerge
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
Definition: GlobalFunctions.php:2034
wfDebugBacktrace
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
Definition: GlobalFunctions.php:1294
wfSetVar
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
Definition: GlobalFunctions.php:1512
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:2249
wfFormatStackFrame
wfFormatStackFrame( $frame)
Return a string representation of frame.
Definition: GlobalFunctions.php:1390
ResourceLoader\makeInlineScript
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
Definition: ResourceLoader.php:1642
wfRemoveDotSegments
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
Definition: GlobalFunctions.php:624
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:204
wfSetBit
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
Definition: GlobalFunctions.php:1529
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1692
SiteStats\pages
static pages()
Definition: SiteStats.php:112
wfUnpack
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
Definition: GlobalFunctions.php:2503
MessageSpecifier
Definition: MessageSpecifier.php:24
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:7449
wfMemoryLimit
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
Definition: GlobalFunctions.php:2389
wfObjectToArray
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
Definition: GlobalFunctions.php:213
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:292
wfArrayDiff2_cmp
wfArrayDiff2_cmp( $a, $b)
Definition: GlobalFunctions.php:122
wfGetScriptUrl
wfGetScriptUrl()
Get the script URL.
Definition: GlobalFunctions.php:2323
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2118
wfQueriesMustScale
wfQueriesMustScale()
Should low-performance queries be disabled?
Definition: GlobalFunctions.php:2290
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1245
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1099
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1217
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1182
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1056
wfStringToBool
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
Definition: GlobalFunctions.php:1887
$wgTransactionalTimeLimit
$wgTransactionalTimeLimit
The request time limit for "slow" write requests that should not be interrupted due to the risk of da...
Definition: DefaultSettings.php:2604
$wgDebugLogPrefix
$wgDebugLogPrefix
Prefix for debug log lines.
Definition: DefaultSettings.php:7265
wfExpandIRI
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
Definition: GlobalFunctions.php:844
$wgLang
$wgLang
Definition: Setup.php:807
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:958
$wgDBprefix
$wgDBprefix
Current wiki database table name prefix.
Definition: DefaultSettings.php:2082
wfShellWikiCmd
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:2009
wfBoolToStr
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
Definition: GlobalFunctions.php:2349
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:422
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
Wikimedia\ParamValidator\TypeDef\ExpiryDef
Type definition for expiry timestamps.
Definition: ExpiryDef.php:17
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:776
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:66
wfReportTime
wfReportTime( $nonce=null)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
Definition: GlobalFunctions.php:1265
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1028
wfGetMainCache
wfGetMainCache()
Get the main cache object.
Definition: GlobalFunctions.php:2485
MWException
MediaWiki exception.
Definition: MWException.php:29
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2370
mimeTypeMatch
mimeTypeMatch( $type, $avail)
Checks if a given MIME type matches any of the keys in the given array.
Definition: GlobalFunctions.php:1669
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:996
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2306
wfArrayDiff2
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
Definition: GlobalFunctions.php:113
wfIncrStats
wfIncrStats( $key, $count=1)
Increment a statistics counter.
Definition: GlobalFunctions.php:1088
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1525
wfTransactionalTimeLimit
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
Definition: GlobalFunctions.php:2414
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2226
wfUrlProtocolsWithoutProtRel
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
Definition: GlobalFunctions.php:747
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
$matches
$matches
Definition: NoLocalSettings.php:24
$wgLoadScript
$wgLoadScript
The URL path to load.php.
Definition: DefaultSettings.php:212
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:1708
ObjectCache\getInstance
static getInstance( $id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:74
$args
if( $line===false) $args
Definition: mcc.php:124
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1132
wfCgiToArray
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Definition: GlobalFunctions.php:375
wfLoadSkins
wfLoadSkins(array $skins)
Load multiple skins at once.
Definition: GlobalFunctions.php:99
$title
$title
Definition: testCompression.php:38
MWDebug\deprecated
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition: MWDebug.php:221
wfGetCache
wfGetCache( $cacheType)
Get a specific cache object.
Definition: GlobalFunctions.php:2475
$wgEnableMagicLinks
$wgEnableMagicLinks
Enable the magic links feature of automatically turning ISBN xxx, PMID xxx, RFC xxx into links.
Definition: DefaultSettings.php:5086
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1721
PROTO_CANONICAL
const PROTO_CANONICAL
Definition: Defines.php:196
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
wfPercent
wfPercent( $nr, int $acc=2, bool $round=true)
Definition: GlobalFunctions.php:1842
$wgCanonicalServer
$wgCanonicalServer
Canonical URL of the server, to use in IRC feeds and notification e-mails.
Definition: DefaultSettings.php:117
wfIsDebugRawPage
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
Definition: GlobalFunctions.php:916
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:195
wfUrlProtocols
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
Definition: GlobalFunctions.php:702
wfLoadExtensions
wfLoadExtensions(array $exts)
Load multiple extensions at once.
Definition: GlobalFunctions.php:68
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2185
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1652
wfClientAcceptsGzip
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
Definition: GlobalFunctions.php:1421
$wgUrlProtocols
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
Definition: DefaultSettings.php:4909
$wgExtensionDirectory
$wgExtensionDirectory
Filesystem extensions directory.
Definition: DefaultSettings.php:248
wfIsCLI
wfIsCLI()
Check if we are running from the commandline.
Definition: GlobalFunctions.php:1740
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1730
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:108
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
$line
$line
Definition: mcc.php:119
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:3445
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2546
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1748
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1456
wfVarDump
wfVarDump( $var)
A wrapper around the PHP function var_export().
Definition: GlobalFunctions.php:1547
$wgIllegalFileChars
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
Definition: DefaultSettings.php:544
wfGetNull
wfGetNull()
Get a platform-independent path to the null file, e.g.
Definition: GlobalFunctions.php:2358
TempFSFile\getUsableTempDirectory
static getUsableTempDirectory()
Definition: TempFSFile.php:80
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1871
$wgOverrideHostname
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
Definition: DefaultSettings.php:7456
PROTO_INTERNAL
const PROTO_INTERNAL
Definition: Defines.php:197
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:2266
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1375
wfLoadExtension
wfLoadExtension( $ext, $path=null)
Load an extension.
Definition: GlobalFunctions.php:47
wfLoadSkin
wfLoadSkin( $skin, $path=null)
Load a skin.
Definition: GlobalFunctions.php:84
wfShorthandToInteger
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
Definition: GlobalFunctions.php:2444
$wgImageLimits
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
Definition: DefaultSettings.php:1624
wfRandom
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
Definition: GlobalFunctions.php:239
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1755
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2626
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1564
wfReadOnlyReason
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
Definition: GlobalFunctions.php:1112
wfMatchesDomainList
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
Definition: GlobalFunctions.php:860
$cache
$cache
Definition: mcc.php:33
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
wfRecursiveRemoveDir
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:1817
$wgHttpsPort
$wgHttpsPort
For installations where the canonical server is HTTP but HTTPS is optionally supported,...
Definition: DefaultSettings.php:145
$path
$path
Definition: NoLocalSettings.php:25
Message
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:138
$keys
$keys
Definition: testCompression.php:72
wfBacktrace
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
Definition: GlobalFunctions.php:1322
wfEscapeShellArg
wfEscapeShellArg(... $args)
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:1908
$source
$source
Definition: mwdoc-filter.php:34
wfAssembleUrl
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
Definition: GlobalFunctions.php:570
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
wfRelativePath
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
Definition: GlobalFunctions.php:2142
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1043
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:766
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
MWDebug\warning
static warning( $msg, $callerOffset=1, $level=E_USER_NOTICE, $log='auto')
Adds a warning entry to the log.
Definition: MWDebug.php:180
$wgOut
$wgOut
Definition: Setup.php:812
wfGetServerUrl
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
Definition: GlobalFunctions.php:552
$wgScriptPath
$wgScriptPath
The path we should point to.
Definition: DefaultSettings.php:176
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:2279
Message\newFallbackSequence
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:440
wfShowingResults
wfShowingResults( $offset, $limit)
Definition: GlobalFunctions.php:1408
wfGetCaller
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Definition: GlobalFunctions.php:1359
$wgStyleDirectory
$wgStyleDirectory
Filesystem stylesheets directory.
Definition: DefaultSettings.php:255
wfLogDBError
wfLogDBError( $text, array $context=[])
Log for database errors.
Definition: GlobalFunctions.php:976
SiteStats\edits
static edits()
Definition: SiteStats.php:94
MWDebug\deprecatedMsg
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: MWDebug.php:304
MW_ENTRY_POINT
const MW_ENTRY_POINT
Definition: api.php:41
$wgInternalServer
$wgInternalServer
Internal server name as known to CDN, if different.
Definition: DefaultSettings.php:3252
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:192
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:474
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:1989
MediaWiki\HeaderCallback\warnIfHeadersSent
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
Definition: HeaderCallback.php:83
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1064
wfShellExec
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
Definition: GlobalFunctions.php:1936
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
$type
$type
Definition: testCompression.php:52