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] ) && is_array( $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 
997 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
998  if ( !is_string( $version ) && $version !== false ) {
999  throw new InvalidArgumentException(
1000  "MediaWiki version must either be a string or false. " .
1001  "Example valid version: '1.33'"
1002  );
1003  }
1004 
1005  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1006 }
1007 
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  $profiler = Profiler::instance();
1066  $profiler->logData();
1067 
1068  // Send out any buffered statsd metrics as needed
1070  MediaWikiServices::getInstance()->getStatsdDataFactory(),
1071  MediaWikiServices::getInstance()->getMainConfig()
1072  );
1073 }
1074 
1085 function wfIncrStats( $key, $count = 1 ) {
1086  wfDeprecated( __FUNCTION__, '1.36' );
1087  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1088  $stats->updateCount( $key, $count );
1089 }
1090 
1098 function wfReadOnly() {
1099  return MediaWikiServices::getInstance()->getReadOnlyMode()
1100  ->isReadOnly();
1101 }
1102 
1113 function wfReadOnlyReason() {
1114  return MediaWikiServices::getInstance()->getReadOnlyMode()
1115  ->getReason();
1116 }
1117 
1133 function wfGetLangObj( $langcode = false ) {
1134  # Identify which language to get or create a language object for.
1135  # Using is_object here due to Stub objects.
1136  if ( is_object( $langcode ) ) {
1137  # Great, we already have the object (hopefully)!
1138  return $langcode;
1139  }
1140 
1141  global $wgLanguageCode;
1142  $services = MediaWikiServices::getInstance();
1143  if ( $langcode === true || $langcode === $wgLanguageCode ) {
1144  # $langcode is the language code of the wikis content language object.
1145  # or it is a boolean and value is true
1146  return $services->getContentLanguage();
1147  }
1148 
1149  global $wgLang;
1150  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1151  # $langcode is the language code of user language object.
1152  # or it was a boolean and value is false
1153  return $wgLang;
1154  }
1155 
1156  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1157  if ( in_array( $langcode, $validCodes ) ) {
1158  # $langcode corresponds to a valid language.
1159  return $services->getLanguageFactory()->getLanguage( $langcode );
1160  }
1161 
1162  # $langcode is a string, but not a valid language code; use content language.
1163  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1164  return $services->getContentLanguage();
1165 }
1166 
1183 function wfMessage( $key, ...$params ) {
1184  $message = new Message( $key );
1185 
1186  // We call Message::params() to reduce code duplication
1187  if ( $params ) {
1188  $message->params( ...$params );
1189  }
1190 
1191  return $message;
1192 }
1193 
1206 function wfMessageFallback( ...$keys ) {
1207  return Message::newFallbackSequence( ...$keys );
1208 }
1209 
1218 function wfMsgReplaceArgs( $message, $args ) {
1219  # Fix windows line-endings
1220  # Some messages are split with explode("\n", $msg)
1221  $message = str_replace( "\r", '', $message );
1222 
1223  // Replace arguments
1224  if ( is_array( $args ) && $args ) {
1225  if ( is_array( $args[0] ) ) {
1226  $args = array_values( $args[0] );
1227  }
1228  $replacementKeys = [];
1229  foreach ( $args as $n => $param ) {
1230  $replacementKeys['$' . ( $n + 1 )] = $param;
1231  }
1232  $message = strtr( $message, $replacementKeys );
1233  }
1234 
1235  return $message;
1236 }
1237 
1246 function wfHostname() {
1247  // Hostname overriding
1248  global $wgOverrideHostname;
1249  if ( $wgOverrideHostname !== false ) {
1250  return $wgOverrideHostname;
1251  }
1252 
1253  return php_uname( 'n' ) ?: 'unknown';
1254 }
1255 
1266 function wfReportTime( $nonce = null ) {
1267  global $wgShowHostnames;
1268 
1269  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1270  // seconds to milliseconds
1271  $responseTime = round( $elapsed * 1000 );
1272  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1273  if ( $wgShowHostnames ) {
1274  $reportVars['wgHostname'] = wfHostname();
1275  }
1276 
1277  return (
1279  ResourceLoader::makeConfigSetScript( $reportVars ),
1280  $nonce
1281  )
1282  );
1283 }
1284 
1295 function wfDebugBacktrace( $limit = 0 ) {
1296  static $disabled = null;
1297 
1298  if ( $disabled === null ) {
1299  $disabled = !function_exists( 'debug_backtrace' );
1300  if ( $disabled ) {
1301  wfDebug( "debug_backtrace() is disabled" );
1302  }
1303  }
1304  if ( $disabled ) {
1305  return [];
1306  }
1307 
1308  if ( $limit ) {
1309  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1310  } else {
1311  return array_slice( debug_backtrace(), 1 );
1312  }
1313 }
1314 
1323 function wfBacktrace( $raw = null ) {
1324  global $wgCommandLineMode;
1325 
1326  if ( $raw === null ) {
1327  $raw = $wgCommandLineMode;
1328  }
1329 
1330  if ( $raw ) {
1331  $frameFormat = "%s line %s calls %s()\n";
1332  $traceFormat = "%s";
1333  } else {
1334  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1335  $traceFormat = "<ul>\n%s</ul>\n";
1336  }
1337 
1338  $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1339  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1340  $line = $frame['line'] ?? '-';
1341  $call = $frame['function'];
1342  if ( !empty( $frame['class'] ) ) {
1343  $call = $frame['class'] . $frame['type'] . $call;
1344  }
1345  return sprintf( $frameFormat, $file, $line, $call );
1346  }, wfDebugBacktrace() );
1347 
1348  return sprintf( $traceFormat, implode( '', $frames ) );
1349 }
1350 
1360 function wfGetCaller( $level = 2 ) {
1361  $backtrace = wfDebugBacktrace( $level + 1 );
1362  if ( isset( $backtrace[$level] ) ) {
1363  return wfFormatStackFrame( $backtrace[$level] );
1364  } else {
1365  return 'unknown';
1366  }
1367 }
1368 
1376 function wfGetAllCallers( $limit = 3 ) {
1377  $trace = array_reverse( wfDebugBacktrace() );
1378  if ( !$limit || $limit > count( $trace ) - 1 ) {
1379  $limit = count( $trace ) - 1;
1380  }
1381  $trace = array_slice( $trace, -$limit - 1, $limit );
1382  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1383 }
1384 
1391 function wfFormatStackFrame( $frame ) {
1392  if ( !isset( $frame['function'] ) ) {
1393  return 'NO_FUNCTION_GIVEN';
1394  }
1395  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1396  $frame['class'] . $frame['type'] . $frame['function'] :
1397  $frame['function'];
1398 }
1399 
1400 /* Some generic result counters, pulled out of SearchEngine */
1401 
1409 function wfShowingResults( $offset, $limit ) {
1410  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1411 }
1412 
1422 function wfClientAcceptsGzip( $force = false ) {
1423  static $result = null;
1424  if ( $result === null || $force ) {
1425  $result = false;
1426  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1427  # @todo FIXME: We may want to disallow some broken browsers
1428  $m = [];
1429  if ( preg_match(
1430  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1431  $_SERVER['HTTP_ACCEPT_ENCODING'],
1432  $m
1433  )
1434  ) {
1435  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
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 
1665 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1666  $ret = MWTimestamp::convert( $outputtype, $ts );
1667  if ( $ret === false ) {
1668  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1669  }
1670  return $ret;
1671 }
1672 
1681 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1682  if ( $ts === null ) {
1683  return null;
1684  } else {
1685  return wfTimestamp( $outputtype, $ts );
1686  }
1687 }
1688 
1694 function wfTimestampNow() {
1695  return MWTimestamp::now( TS_MW );
1696 }
1697 
1703 function wfIsWindows() {
1704  return PHP_OS_FAMILY === 'Windows';
1705 }
1706 
1713 function wfIsCLI() {
1714  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1715 }
1716 
1728 function wfTempDir() {
1729  global $wgTmpDirectory;
1730 
1731  if ( $wgTmpDirectory !== false ) {
1732  return $wgTmpDirectory;
1733  }
1734 
1736 }
1737 
1747 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1748  global $wgDirectoryMode;
1749 
1750  if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1751  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1752  }
1753 
1754  if ( $caller !== null ) {
1755  wfDebug( "$caller: called wfMkdirParents($dir)" );
1756  }
1757 
1758  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1759  return true;
1760  }
1761 
1762  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1763 
1764  if ( $mode === null ) {
1765  $mode = $wgDirectoryMode;
1766  }
1767 
1768  // Turn off the normal warning, we're doing our own below
1769  AtEase::suppressWarnings();
1770  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1771  AtEase::restoreWarnings();
1772 
1773  if ( !$ok ) {
1774  // directory may have been created on another request since we last checked
1775  if ( is_dir( $dir ) ) {
1776  return true;
1777  }
1778 
1779  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1780  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1781  }
1782  return $ok;
1783 }
1784 
1790 function wfRecursiveRemoveDir( $dir ) {
1791  wfDebug( __FUNCTION__ . "( $dir )" );
1792  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1793  if ( is_dir( $dir ) ) {
1794  $objects = scandir( $dir );
1795  foreach ( $objects as $object ) {
1796  if ( $object != "." && $object != ".." ) {
1797  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1798  wfRecursiveRemoveDir( $dir . '/' . $object );
1799  } else {
1800  unlink( $dir . '/' . $object );
1801  }
1802  }
1803  }
1804  reset( $objects );
1805  rmdir( $dir );
1806  }
1807 }
1808 
1815 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1816  $accForFormat = $acc >= 0 ? $acc : 0;
1817  $ret = sprintf( "%.${accForFormat}f", $nr );
1818  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1819 }
1820 
1844 function wfIniGetBool( $setting ) {
1845  return wfStringToBool( ini_get( $setting ) );
1846 }
1847 
1860 function wfStringToBool( $val ) {
1861  $val = strtolower( $val );
1862  // 'on' and 'true' can't have whitespace around them, but '1' can.
1863  return $val == 'on'
1864  || $val == 'true'
1865  || $val == 'yes'
1866  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1867 }
1868 
1882 function wfEscapeShellArg( ...$args ) {
1883  return Shell::escape( ...$args );
1884 }
1885 
1910 function wfShellExec( $cmd, &$retval = null, $environ = [],
1911  $limits = [], $options = []
1912 ) {
1913  if ( Shell::isDisabled() ) {
1914  $retval = 1;
1915  // Backwards compatibility be upon us...
1916  return 'Unable to run external programs, proc_open() is disabled.';
1917  }
1918 
1919  if ( is_array( $cmd ) ) {
1920  $cmd = Shell::escape( $cmd );
1921  }
1922 
1923  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1924  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1925 
1926  try {
1927  $result = Shell::command( [] )
1928  ->unsafeParams( (array)$cmd )
1929  ->environment( $environ )
1930  ->limits( $limits )
1931  ->includeStderr( $includeStderr )
1932  ->profileMethod( $profileMethod )
1933  // For b/c
1934  ->restrict( Shell::RESTRICT_NONE )
1935  ->execute();
1936  } catch ( ProcOpenError $ex ) {
1937  $retval = -1;
1938  return '';
1939  }
1940 
1941  $retval = $result->getExitCode();
1942 
1943  return $result->getStdout();
1944 }
1945 
1963 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1964  return wfShellExec( $cmd, $retval, $environ, $limits,
1965  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1966 }
1967 
1983 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1984  global $wgPhpCli;
1985  // Give site config file a chance to run the script in a wrapper.
1986  // The caller may likely want to call wfBasename() on $script.
1987  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1988  $cmd = [ $options['php'] ?? $wgPhpCli ];
1989  if ( isset( $options['wrapper'] ) ) {
1990  $cmd[] = $options['wrapper'];
1991  }
1992  $cmd[] = $script;
1993  // Escape each parameter for shell
1994  return Shell::escape( array_merge( $cmd, $parameters ) );
1995 }
1996 
2008 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2009  global $wgDiff3;
2010 
2011  # This check may also protect against code injection in
2012  # case of broken installations.
2013  AtEase::suppressWarnings();
2014  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2015  AtEase::restoreWarnings();
2016 
2017  if ( !$haveDiff3 ) {
2018  wfDebug( "diff3 not found" );
2019  return false;
2020  }
2021 
2022  # Make temporary files
2023  $td = wfTempDir();
2024  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2025  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2026  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2027 
2028  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2029  # a newline character. To avoid this, we normalize the trailing whitespace before
2030  # creating the diff.
2031 
2032  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2033  fclose( $oldtextFile );
2034  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2035  fclose( $mytextFile );
2036  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2037  fclose( $yourtextFile );
2038 
2039  # Check for a conflict
2040  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2041  $oldtextName, $yourtextName );
2042  $handle = popen( $cmd, 'r' );
2043 
2044  $mergeAttemptResult = '';
2045  do {
2046  $data = fread( $handle, 8192 );
2047  if ( strlen( $data ) == 0 ) {
2048  break;
2049  }
2050  $mergeAttemptResult .= $data;
2051  } while ( true );
2052  pclose( $handle );
2053 
2054  $conflict = $mergeAttemptResult !== '';
2055 
2056  # Merge differences
2057  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2058  $oldtextName, $yourtextName );
2059  $handle = popen( $cmd, 'r' );
2060  $result = '';
2061  do {
2062  $data = fread( $handle, 8192 );
2063  if ( strlen( $data ) == 0 ) {
2064  break;
2065  }
2066  $result .= $data;
2067  } while ( true );
2068  pclose( $handle );
2069  unlink( $mytextName );
2070  unlink( $oldtextName );
2071  unlink( $yourtextName );
2072 
2073  if ( $result === '' && $old !== '' && !$conflict ) {
2074  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2075  $conflict = true;
2076  }
2077  return !$conflict;
2078 }
2079 
2092 function wfBaseName( $path, $suffix = '' ) {
2093  if ( $suffix == '' ) {
2094  $encSuffix = '';
2095  } else {
2096  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2097  }
2098 
2099  $matches = [];
2100  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2101  return $matches[1];
2102  } else {
2103  return '';
2104  }
2105 }
2106 
2116 function wfRelativePath( $path, $from ) {
2117  // Normalize mixed input on Windows...
2118  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2119  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2120 
2121  // Trim trailing slashes -- fix for drive root
2122  $path = rtrim( $path, DIRECTORY_SEPARATOR );
2123  $from = rtrim( $from, DIRECTORY_SEPARATOR );
2124 
2125  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2126  $against = explode( DIRECTORY_SEPARATOR, $from );
2127 
2128  if ( $pieces[0] !== $against[0] ) {
2129  // Non-matching Windows drive letters?
2130  // Return a full path.
2131  return $path;
2132  }
2133 
2134  // Trim off common prefix
2135  while ( count( $pieces ) && count( $against )
2136  && $pieces[0] == $against[0] ) {
2137  array_shift( $pieces );
2138  array_shift( $against );
2139  }
2140 
2141  // relative dots to bump us to the parent
2142  while ( count( $against ) ) {
2143  array_unshift( $pieces, '..' );
2144  array_shift( $against );
2145  }
2146 
2147  $pieces[] = wfBaseName( $path );
2148 
2149  return implode( DIRECTORY_SEPARATOR, $pieces );
2150 }
2151 
2159 function wfWikiID() {
2160  global $wgDBprefix, $wgDBname;
2161 
2162  if ( $wgDBprefix ) {
2163  return "$wgDBname-$wgDBprefix";
2164  } else {
2165  return $wgDBname;
2166  }
2167 }
2168 
2200 function wfGetDB( $db, $groups = [], $wiki = false ) {
2201  if ( $wiki === false ) {
2202  return MediaWikiServices::getInstance()
2203  ->getDBLoadBalancer()
2204  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2205  } else {
2206  return MediaWikiServices::getInstance()
2207  ->getDBLoadBalancerFactory()
2208  ->getMainLB( $wiki )
2209  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2210  }
2211 }
2212 
2223 function wfGetLB( $wiki = false ) {
2224  wfDeprecated( __FUNCTION__, '1.27' );
2225  if ( $wiki === false ) {
2226  // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
2227  return MediaWikiServices::getInstance()->getDBLoadBalancer();
2228  } else {
2229  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2230  // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
2231  return $factory->getMainLB( $wiki );
2232  }
2233 }
2234 
2242 function wfFindFile( $title, $options = [] ) {
2243  wfDeprecated( __FUNCTION__, '1.34' );
2244  return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2245 }
2246 
2255 function wfLocalFile( $title ) {
2256  wfDeprecated( __FUNCTION__, '1.34' );
2257  return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2258 }
2259 
2267  global $wgMiserMode;
2268  return $wgMiserMode
2269  || ( SiteStats::pages() > 100000
2270  && SiteStats::edits() > 1000000
2271  && SiteStats::users() > 10000 );
2272 }
2273 
2282 function wfScript( $script = 'index' ) {
2284  if ( $script === 'index' ) {
2285  return $wgScript;
2286  } elseif ( $script === 'load' ) {
2287  return $wgLoadScript;
2288  } else {
2289  return "{$wgScriptPath}/{$script}.php";
2290  }
2291 }
2292 
2299 function wfGetScriptUrl() {
2300  wfDeprecated( __FUNCTION__, '1.35' );
2301  if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2302  /* as it was called, minus the query string.
2303  *
2304  * Some sites use Apache rewrite rules to handle subdomains,
2305  * and have PHP set up in a weird way that causes PHP_SELF
2306  * to contain the rewritten URL instead of the one that the
2307  * outside world sees.
2308  *
2309  * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2310  * provides containing the "before" URL.
2311  */
2312  return $_SERVER['SCRIPT_NAME'];
2313  } else {
2314  return $_SERVER['URL'];
2315  }
2316 }
2317 
2325 function wfBoolToStr( $value ) {
2326  return $value ? 'true' : 'false';
2327 }
2328 
2334 function wfGetNull() {
2335  return wfIsWindows() ? 'NUL' : '/dev/null';
2336 }
2337 
2346 function wfStripIllegalFilenameChars( $name ) {
2347  global $wgIllegalFileChars;
2348  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2349  $name = preg_replace(
2350  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2351  '-',
2352  $name
2353  );
2354  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2355  $name = wfBaseName( $name );
2356  return $name;
2357 }
2358 
2365 function wfMemoryLimit( $newLimit ) {
2366  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2367  // If the INI config is already unlimited, there is nothing larger
2368  if ( $oldLimit != -1 ) {
2369  $newLimit = wfShorthandToInteger( $newLimit );
2370  if ( $newLimit == -1 ) {
2371  wfDebug( "Removing PHP's memory limit" );
2372  Wikimedia\suppressWarnings();
2373  ini_set( 'memory_limit', $newLimit );
2374  Wikimedia\restoreWarnings();
2375  } elseif ( $newLimit > $oldLimit ) {
2376  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2377  Wikimedia\suppressWarnings();
2378  ini_set( 'memory_limit', $newLimit );
2379  Wikimedia\restoreWarnings();
2380  }
2381  }
2382 }
2383 
2392 
2393  $timeout = RequestTimeout::singleton();
2394  $timeLimit = $timeout->getWallTimeLimit();
2395  if ( $timeLimit !== INF ) {
2396  // RequestTimeout library is active
2397  if ( $wgTransactionalTimeLimit > $timeLimit ) {
2398  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2399  }
2400  } else {
2401  // Fallback case, likely $wgRequestTimeLimit === null
2402  $timeLimit = (int)ini_get( 'max_execution_time' );
2403  // Note that CLI scripts use 0
2404  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2405  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2406  }
2407  }
2408  ignore_user_abort( true ); // ignore client disconnects
2409 
2410  return $timeLimit;
2411 }
2412 
2420 function wfShorthandToInteger( $string = '', $default = -1 ) {
2421  $string = trim( $string );
2422  if ( $string === '' ) {
2423  return $default;
2424  }
2425  $last = $string[strlen( $string ) - 1];
2426  $val = intval( $string );
2427  switch ( $last ) {
2428  case 'g':
2429  case 'G':
2430  $val *= 1024;
2431  // break intentionally missing
2432  case 'm':
2433  case 'M':
2434  $val *= 1024;
2435  // break intentionally missing
2436  case 'k':
2437  case 'K':
2438  $val *= 1024;
2439  }
2440 
2441  return $val;
2442 }
2443 
2451 function wfGetCache( $cacheType ) {
2452  return ObjectCache::getInstance( $cacheType );
2453 }
2454 
2461 function wfGetMainCache() {
2463 }
2464 
2479 function wfUnpack( $format, $data, $length = false ) {
2480  if ( $length !== false ) {
2481  $realLen = strlen( $data );
2482  if ( $realLen < $length ) {
2483  throw new MWException( "Tried to use wfUnpack on a "
2484  . "string of length $realLen, but needed one "
2485  . "of at least length $length."
2486  );
2487  }
2488  }
2489 
2490  Wikimedia\suppressWarnings();
2491  $result = unpack( $format, $data );
2492  Wikimedia\restoreWarnings();
2493 
2494  if ( $result === false ) {
2495  // If it cannot extract the packed data.
2496  throw new MWException( "unpack could not unpack binary data" );
2497  }
2498  return $result;
2499 }
2500 
2510 function wfCanIPUseHTTPS( $ip ) {
2511  wfDeprecated( __FUNCTION__, '1.37' );
2512  return true;
2513 }
2514 
2522 function wfIsInfinity( $str ) {
2523  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2524  return in_array( $str, ExpiryDef::INFINITY_VALS );
2525 }
2526 
2541 function wfThumbIsStandard( File $file, array $params ) {
2543 
2544  $multipliers = [ 1 ];
2545  if ( $wgResponsiveImages ) {
2546  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2547  // @see Linker::processResponsiveImages
2548  $multipliers[] = 1.5;
2549  $multipliers[] = 2;
2550  }
2551 
2552  $handler = $file->getHandler();
2553  if ( !$handler || !isset( $params['width'] ) ) {
2554  return false;
2555  }
2556 
2557  $basicParams = [];
2558  if ( isset( $params['page'] ) ) {
2559  $basicParams['page'] = $params['page'];
2560  }
2561 
2562  $thumbLimits = [];
2563  $imageLimits = [];
2564  // Expand limits to account for multipliers
2565  foreach ( $multipliers as $multiplier ) {
2566  $thumbLimits = array_merge( $thumbLimits, array_map(
2567  static function ( $width ) use ( $multiplier ) {
2568  return round( $width * $multiplier );
2569  }, $wgThumbLimits )
2570  );
2571  $imageLimits = array_merge( $imageLimits, array_map(
2572  static function ( $pair ) use ( $multiplier ) {
2573  return [
2574  round( $pair[0] * $multiplier ),
2575  round( $pair[1] * $multiplier ),
2576  ];
2577  }, $wgImageLimits )
2578  );
2579  }
2580 
2581  // Check if the width matches one of $wgThumbLimits
2582  if ( in_array( $params['width'], $thumbLimits ) ) {
2583  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2584  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2585  $handler->normaliseParams( $file, $normalParams );
2586  } else {
2587  // If not, then check if the width matchs one of $wgImageLimits
2588  $match = false;
2589  foreach ( $imageLimits as $pair ) {
2590  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2591  // Decide whether the thumbnail should be scaled on width or height.
2592  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2593  $handler->normaliseParams( $file, $normalParams );
2594  // Check if this standard thumbnail size maps to the given width
2595  if ( $normalParams['width'] == $params['width'] ) {
2596  $match = true;
2597  break;
2598  }
2599  }
2600  if ( !$match ) {
2601  return false; // not standard for description pages
2602  }
2603  }
2604 
2605  // Check that the given values for non-page, non-width, params are just defaults
2606  foreach ( $params as $key => $value ) {
2607  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2608  return false;
2609  }
2610  }
2611 
2612  return true;
2613 }
2614 
2627 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2628  // First merge items that are in both arrays
2629  foreach ( $baseArray as $name => &$groupVal ) {
2630  if ( isset( $newValues[$name] ) ) {
2631  $groupVal += $newValues[$name];
2632  }
2633  }
2634  // Now add items that didn't exist yet
2635  $baseArray += $newValues;
2636 
2637  return $baseArray;
2638 }
$wgPhpCli
$wgPhpCli
Executable path of the PHP cli binary.
Definition: DefaultSettings.php:9560
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:1206
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1652
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:2510
ResourceLoader\makeConfigSetScript
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
Definition: ResourceLoader.php:1620
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:273
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:1185
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:1770
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:7256
wfThumbIsStandard
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
Definition: GlobalFunctions.php:2541
$wgTmpDirectory
$wgTmpDirectory
The local filesystem path to a temporary directory.
Definition: DefaultSettings.php:454
wfArrayPlus2d
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
Definition: GlobalFunctions.php:2627
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:2060
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:1747
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:200
$wgRequest
$wgRequest
Definition: Setup.php:705
$wgDiff3
$wgDiff3
Path to the GNU diff3 utility.
Definition: DefaultSettings.php:7807
wfMerge
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
Definition: GlobalFunctions.php:2008
wfDebugBacktrace
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
Definition: GlobalFunctions.php:1295
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:2223
wfFormatStackFrame
wfFormatStackFrame( $frame)
Return a string representation of frame.
Definition: GlobalFunctions.php:1391
ResourceLoader\makeInlineScript
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
Definition: ResourceLoader.php:1593
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:206
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:1665
SiteStats\pages
static pages()
Definition: SiteStats.php:112
wfUnpack
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
Definition: GlobalFunctions.php:2479
MessageSpecifier
Definition: MessageSpecifier.php:24
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:7426
wfMemoryLimit
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
Definition: GlobalFunctions.php:2365
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:2299
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2092
wfQueriesMustScale
wfQueriesMustScale()
Should low-performance queries be disabled?
Definition: GlobalFunctions.php:2266
$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:1246
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1098
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1218
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1183
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:1860
$wgTransactionalTimeLimit
$wgTransactionalTimeLimit
The request time limit for "slow" write requests that should not be interrupted due to the risk of da...
Definition: DefaultSettings.php:2602
$wgDebugLogPrefix
$wgDebugLogPrefix
Prefix for debug log lines.
Definition: DefaultSettings.php:7242
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:834
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:2080
wfShellWikiCmd
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:1983
wfBoolToStr
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
Definition: GlobalFunctions.php:2325
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:134
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:1266
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:2461
MWException
MediaWiki exception.
Definition: MWException.php:29
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2346
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Definition: GlobalFunctions.php:997
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:2282
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:1085
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:2390
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2200
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:214
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:1681
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:1133
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:2451
$wgEnableMagicLinks
$wgEnableMagicLinks
Enable the magic links feature of automatically turning ISBN xxx, PMID xxx, RFC xxx into links.
Definition: DefaultSettings.php:5067
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1694
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:1815
$wgCanonicalServer
$wgCanonicalServer
Canonical URL of the server, to use in IRC feeds and notification e-mails.
Definition: DefaultSettings.php:119
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:2159
$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:1422
$wgUrlProtocols
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
Definition: DefaultSettings.php:4881
$wgExtensionDirectory
$wgExtensionDirectory
Filesystem extensions directory.
Definition: DefaultSettings.php:250
wfIsCLI
wfIsCLI()
Check if we are running from the commandline.
Definition: GlobalFunctions.php:1713
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1703
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:110
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:3434
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2522
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1762
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:546
wfGetNull
wfGetNull()
Get a platform-independent path to the null file, e.g.
Definition: GlobalFunctions.php:2334
TempFSFile\getUsableTempDirectory
static getUsableTempDirectory()
Definition: TempFSFile.php:80
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1844
$wgOverrideHostname
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
Definition: DefaultSettings.php:7433
PROTO_INTERNAL
const PROTO_INTERNAL
Definition: Defines.php:197
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:2242
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1376
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:2420
$wgImageLimits
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
Definition: DefaultSettings.php:1638
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:1728
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2624
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:1113
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:1790
$wgHttpsPort
$wgHttpsPort
For installations where the canonical server is HTTP but HTTPS is optionally supported,...
Definition: DefaultSettings.php:147
$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:1323
wfEscapeShellArg
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
Definition: GlobalFunctions.php:1882
$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:2116
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:736
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:839
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:178
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:2255
Message\newFallbackSequence
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:432
wfShowingResults
wfShowingResults( $offset, $limit)
Definition: GlobalFunctions.php:1409
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:1360
$wgStyleDirectory
$wgStyleDirectory
Filesystem stylesheets directory.
Definition: DefaultSettings.php:257
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:303
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:3250
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:1963
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:1910
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