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 
34 use Wikimedia\AtEase\AtEase;
36 use Wikimedia\RequestTimeout\RequestTimeout;
37 use Wikimedia\WrappedString;
38 
49 function wfLoadExtension( $ext, $path = null ) {
50  if ( !$path ) {
51  global $wgExtensionDirectory;
52  $path = "$wgExtensionDirectory/$ext/extension.json";
53  }
55 }
56 
70 function wfLoadExtensions( array $exts ) {
71  global $wgExtensionDirectory;
72  $registry = ExtensionRegistry::getInstance();
73  foreach ( $exts as $ext ) {
74  $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
75  }
76 }
77 
86 function wfLoadSkin( $skin, $path = null ) {
87  if ( !$path ) {
88  global $wgStyleDirectory;
89  $path = "$wgStyleDirectory/$skin/skin.json";
90  }
92 }
93 
101 function wfLoadSkins( array $skins ) {
102  global $wgStyleDirectory;
103  $registry = ExtensionRegistry::getInstance();
104  foreach ( $skins as $skin ) {
105  $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
106  }
107 }
108 
115 function wfArrayDiff2( $arr1, $arr2 ) {
120  $comparator = static function ( $a, $b ): int {
121  if ( is_string( $a ) && is_string( $b ) ) {
122  return strcmp( $a, $b );
123  }
124  if ( !is_array( $a ) && !is_array( $b ) ) {
125  throw new InvalidArgumentException(
126  'This function assumes that array elements are all strings or all arrays'
127  );
128  }
129  if ( count( $a ) !== count( $b ) ) {
130  return count( $a ) <=> count( $b );
131  } else {
132  reset( $a );
133  reset( $b );
134  while ( key( $a ) !== null && key( $b ) !== null ) {
135  $valueA = current( $a );
136  $valueB = current( $b );
137  $cmp = strcmp( $valueA, $valueB );
138  if ( $cmp !== 0 ) {
139  return $cmp;
140  }
141  next( $a );
142  next( $b );
143  }
144  return 0;
145  }
146  };
147  return array_udiff( $arr1, $arr2, $comparator );
148 }
149 
169 function wfMergeErrorArrays( ...$args ) {
170  $out = [];
171  foreach ( $args as $errors ) {
172  foreach ( $errors as $params ) {
173  $originalParams = $params;
174  if ( $params[0] instanceof MessageSpecifier ) {
175  $msg = $params[0];
176  $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
177  }
178  # @todo FIXME: Sometimes get nested arrays for $params,
179  # which leads to E_NOTICEs
180  $spec = implode( "\t", $params );
181  $out[$spec] = $originalParams;
182  }
183  }
184  return array_values( $out );
185 }
186 
196 function wfArrayInsertAfter( array $array, array $insert, $after ) {
197  // Find the offset of the element to insert after.
198  $keys = array_keys( $array );
199  $offsetByKey = array_flip( $keys );
200 
201  if ( !\array_key_exists( $after, $offsetByKey ) ) {
202  return $array;
203  }
204  $offset = $offsetByKey[$after];
205 
206  // Insert at the specified offset
207  $before = array_slice( $array, 0, $offset + 1, true );
208  $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
209 
210  $output = $before + $insert + $after;
211 
212  return $output;
213 }
214 
223 function wfObjectToArray( $objOrArray, $recursive = true ) {
224  $array = [];
225  if ( is_object( $objOrArray ) ) {
226  $objOrArray = get_object_vars( $objOrArray );
227  }
228  foreach ( $objOrArray as $key => $value ) {
229  if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
230  $value = wfObjectToArray( $value );
231  }
232 
233  $array[$key] = $value;
234  }
235 
236  return $array;
237 }
238 
249 function wfRandom() {
250  // The maximum random value is "only" 2^31-1, so get two random
251  // values to reduce the chance of dupes
252  $max = mt_getrandmax() + 1;
253  $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
254  return $rand;
255 }
256 
267 function wfRandomString( $length = 32 ) {
268  $str = '';
269  for ( $n = 0; $n < $length; $n += 7 ) {
270  $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
271  }
272  return substr( $str, 0, $length );
273 }
274 
302 function wfUrlencode( $s ) {
303  static $needle;
304 
305  if ( $s === null ) {
306  // Reset $needle for testing.
307  $needle = null;
308  return '';
309  }
310 
311  if ( $needle === null ) {
312  $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
313  if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
314  ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
315  ) {
316  $needle[] = '%3A';
317  }
318  }
319 
320  $s = urlencode( $s );
321  $s = str_ireplace(
322  $needle,
323  [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
324  $s
325  );
326 
327  return $s;
328 }
329 
340 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
341  if ( $array2 !== null ) {
342  $array1 += $array2;
343  }
344 
345  $cgi = '';
346  foreach ( $array1 as $key => $value ) {
347  if ( $value !== null && $value !== false ) {
348  if ( $cgi != '' ) {
349  $cgi .= '&';
350  }
351  if ( $prefix !== '' ) {
352  $key = $prefix . "[$key]";
353  }
354  if ( is_array( $value ) ) {
355  $firstTime = true;
356  foreach ( $value as $k => $v ) {
357  $cgi .= $firstTime ? '' : '&';
358  if ( is_array( $v ) ) {
359  $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
360  } else {
361  $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
362  }
363  $firstTime = false;
364  }
365  } else {
366  if ( is_object( $value ) ) {
367  $value = $value->__toString();
368  }
369  $cgi .= urlencode( $key ) . '=' . urlencode( $value );
370  }
371  }
372  }
373  return $cgi;
374 }
375 
385 function wfCgiToArray( $query ) {
386  if ( isset( $query[0] ) && $query[0] == '?' ) {
387  $query = substr( $query, 1 );
388  }
389  $bits = explode( '&', $query );
390  $ret = [];
391  foreach ( $bits as $bit ) {
392  if ( $bit === '' ) {
393  continue;
394  }
395  if ( strpos( $bit, '=' ) === false ) {
396  // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
397  $key = $bit;
398  $value = '';
399  } else {
400  [ $key, $value ] = explode( '=', $bit );
401  }
402  $key = urldecode( $key );
403  $value = urldecode( $value );
404  if ( strpos( $key, '[' ) !== false ) {
405  $keys = array_reverse( explode( '[', $key ) );
406  $key = array_pop( $keys );
407  $temp = $value;
408  foreach ( $keys as $k ) {
409  $k = substr( $k, 0, -1 );
410  $temp = [ $k => $temp ];
411  }
412  if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
413  $ret[$key] = array_merge( $ret[$key], $temp );
414  } else {
415  $ret[$key] = $temp;
416  }
417  } else {
418  $ret[$key] = $value;
419  }
420  }
421  return $ret;
422 }
423 
432 function wfAppendQuery( $url, $query ) {
433  if ( is_array( $query ) ) {
434  $query = wfArrayToCgi( $query );
435  }
436  if ( $query != '' ) {
437  // Remove the fragment, if there is one
438  $fragment = false;
439  $hashPos = strpos( $url, '#' );
440  if ( $hashPos !== false ) {
441  $fragment = substr( $url, $hashPos );
442  $url = substr( $url, 0, $hashPos );
443  }
444 
445  // Add parameter
446  if ( strpos( $url, '?' ) === false ) {
447  $url .= '?';
448  } else {
449  $url .= '&';
450  }
451  $url .= $query;
452 
453  // Put the fragment back
454  if ( $fragment !== false ) {
455  $url .= $fragment;
456  }
457  }
458  return $url;
459 }
460 
466 function wfGetUrlUtils(): UrlUtils {
469 
470  if ( MediaWikiServices::hasInstance() ) {
471  $services = MediaWikiServices::getInstance();
472  if ( $services->hasService( 'UrlUtils' ) ) {
473  return $services->getUrlUtils();
474  }
475  }
476 
477  return new UrlUtils( [
478  // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
479  // implementations implicitly converted it to an empty string (presumably by mistake).
480  // Preserve the old behavior for compatibility.
481  UrlUtils::SERVER => $wgServer ?? '',
482  UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
483  UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
484  UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
486  UrlUtils::HTTPS_PORT => $wgHttpsPort,
487  UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
488  ] );
489 }
490 
512 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
513  return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
514 }
515 
525 function wfGetServerUrl( $proto ) {
526  return wfGetUrlUtils()->getServer( $proto ) ?? '';
527 }
528 
541 function wfAssembleUrl( $urlParts ) {
542  return wfGetUrlUtils()->assemble( (array)$urlParts );
543 }
544 
556 function wfRemoveDotSegments( $urlPath ) {
557  return wfGetUrlUtils()->removeDotSegments( (string)$urlPath );
558 }
559 
568 function wfUrlProtocols( $includeProtocolRelative = true ) {
569  $method = $includeProtocolRelative ? 'validProtocols' : 'validAbsoluteProtocols';
570  return wfGetUrlUtils()->$method();
571 }
572 
581  return wfGetUrlUtils()->validAbsoluteProtocols();
582 }
583 
610 function wfParseUrl( $url ) {
611  return wfGetUrlUtils()->parse( (string)$url ) ?? false;
612 }
613 
623 function wfExpandIRI( $url ) {
624  return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
625 }
626 
635 function wfMatchesDomainList( $url, $domains ) {
636  return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
637 }
638 
659 function wfDebug( $text, $dest = 'all', array $context = [] ) {
661 
662  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
663  return;
664  }
665 
666  $text = trim( $text );
667 
668  if ( $wgDebugLogPrefix !== '' ) {
669  $context['prefix'] = $wgDebugLogPrefix;
670  }
671  $context['private'] = ( $dest === false || $dest === 'private' );
672 
673  $logger = LoggerFactory::getInstance( 'wfDebug' );
674  $logger->debug( $text, $context );
675 }
676 
681 function wfIsDebugRawPage() {
682  static $cache;
683  if ( $cache !== null ) {
684  return $cache;
685  }
686  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
687  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
688  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
689  || MW_ENTRY_POINT === 'load'
690  ) {
691  $cache = true;
692  } else {
693  $cache = false;
694  }
695  return $cache;
696 }
697 
723 function wfDebugLog(
724  $logGroup, $text, $dest = 'all', array $context = []
725 ) {
726  $text = trim( $text );
727 
728  $logger = LoggerFactory::getInstance( $logGroup );
729  $context['private'] = ( $dest === false || $dest === 'private' );
730  $logger->info( $text, $context );
731 }
732 
741 function wfLogDBError( $text, array $context = [] ) {
742  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
743  $logger->error( trim( $text ), $context );
744 }
745 
762 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
763  if ( !is_string( $version ) && $version !== false ) {
764  throw new InvalidArgumentException(
765  "MediaWiki version must either be a string or false. " .
766  "Example valid version: '1.33'"
767  );
768  }
769 
770  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
771 }
772 
793 function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
794  MWDebug::deprecatedMsg( $msg, $version, $component,
795  $callerOffset === false ? false : $callerOffset + 1 );
796 }
797 
808 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
809  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
810 }
811 
821 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
822  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
823 }
824 
840 function wfGetLangObj( $langcode = false ) {
841  # Identify which language to get or create a language object for.
842  # Using is_object here due to Stub objects.
843  if ( is_object( $langcode ) ) {
844  # Great, we already have the object (hopefully)!
845  return $langcode;
846  }
847 
848  global $wgLanguageCode;
849  $services = MediaWikiServices::getInstance();
850  if ( $langcode === true || $langcode === $wgLanguageCode ) {
851  # $langcode is the language code of the wikis content language object.
852  # or it is a boolean and value is true
853  return $services->getContentLanguage();
854  }
855 
856  global $wgLang;
857  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
858  # $langcode is the language code of user language object.
859  # or it was a boolean and value is false
860  return $wgLang;
861  }
862 
863  $languageNames = $services->getLanguageNameUtils()->getLanguageNames();
864  // FIXME: Can we use isSupportedLanguage here?
865  if ( isset( $languageNames[$langcode] ) ) {
866  # $langcode corresponds to a valid language.
867  return $services->getLanguageFactory()->getLanguage( $langcode );
868  }
869 
870  # $langcode is a string, but not a valid language code; use content language.
871  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
872  return $services->getContentLanguage();
873 }
874 
896 function wfMessage( $key, ...$params ) {
897  if ( is_array( $key ) ) {
898  // Fallback keys are not allowed in message specifiers
899  $message = wfMessageFallback( ...$key );
900  } else {
901  $message = Message::newFromSpecifier( $key );
902  }
903 
904  // We call Message::params() to reduce code duplication
905  if ( $params ) {
906  $message->params( ...$params );
907  }
908 
909  return $message;
910 }
911 
924 function wfMessageFallback( ...$keys ) {
925  return Message::newFallbackSequence( ...$keys );
926 }
927 
936 function wfMsgReplaceArgs( $message, $args ) {
937  # Fix windows line-endings
938  # Some messages are split with explode("\n", $msg)
939  $message = str_replace( "\r", '', $message );
940 
941  // Replace arguments
942  if ( is_array( $args ) && $args ) {
943  if ( is_array( $args[0] ) ) {
944  $args = array_values( $args[0] );
945  }
946  $replacementKeys = [];
947  foreach ( $args as $n => $param ) {
948  $replacementKeys['$' . ( $n + 1 )] = $param;
949  }
950  $message = strtr( $message, $replacementKeys );
951  }
952 
953  return $message;
954 }
955 
964 function wfHostname() {
965  // Hostname overriding
966  global $wgOverrideHostname;
967  if ( $wgOverrideHostname !== false ) {
968  return $wgOverrideHostname;
969  }
970 
971  return php_uname( 'n' ) ?: 'unknown';
972 }
973 
984 function wfReportTime( $nonce = null ) {
985  global $wgShowHostnames;
986 
987  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
988  // seconds to milliseconds
989  $responseTime = round( $elapsed * 1000 );
990  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
991  if ( $wgShowHostnames ) {
992  $reportVars['wgHostname'] = wfHostname();
993  }
994 
995  return (
996  ResourceLoader::makeInlineScript(
997  ResourceLoader::makeConfigSetScript( $reportVars ),
998  $nonce
999  )
1000  );
1001 }
1002 
1013 function wfDebugBacktrace( $limit = 0 ) {
1014  static $disabled = null;
1015 
1016  if ( $disabled === null ) {
1017  $disabled = !function_exists( 'debug_backtrace' );
1018  if ( $disabled ) {
1019  wfDebug( "debug_backtrace() is disabled" );
1020  }
1021  }
1022  if ( $disabled ) {
1023  return [];
1024  }
1025 
1026  if ( $limit ) {
1027  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1028  } else {
1029  return array_slice( debug_backtrace(), 1 );
1030  }
1031 }
1032 
1041 function wfBacktrace( $raw = null ) {
1042  global $wgCommandLineMode;
1043 
1044  if ( $raw ?? $wgCommandLineMode ) {
1045  $frameFormat = "%s line %s calls %s()\n";
1046  $traceFormat = "%s";
1047  } else {
1048  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1049  $traceFormat = "<ul>\n%s</ul>\n";
1050  }
1051 
1052  $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1053  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1054  $line = $frame['line'] ?? '-';
1055  $call = $frame['function'];
1056  if ( !empty( $frame['class'] ) ) {
1057  $call = $frame['class'] . $frame['type'] . $call;
1058  }
1059  return sprintf( $frameFormat, $file, $line, $call );
1060  }, wfDebugBacktrace() );
1061 
1062  return sprintf( $traceFormat, implode( '', $frames ) );
1063 }
1064 
1074 function wfGetCaller( $level = 2 ) {
1075  $backtrace = wfDebugBacktrace( $level + 1 );
1076  if ( isset( $backtrace[$level] ) ) {
1077  return wfFormatStackFrame( $backtrace[$level] );
1078  } else {
1079  return 'unknown';
1080  }
1081 }
1082 
1090 function wfGetAllCallers( $limit = 3 ) {
1091  $trace = array_reverse( wfDebugBacktrace() );
1092  if ( !$limit || $limit > count( $trace ) - 1 ) {
1093  $limit = count( $trace ) - 1;
1094  }
1095  $trace = array_slice( $trace, -$limit - 1, $limit );
1096  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1097 }
1098 
1105 function wfFormatStackFrame( $frame ) {
1106  if ( !isset( $frame['function'] ) ) {
1107  return 'NO_FUNCTION_GIVEN';
1108  }
1109  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1110  $frame['class'] . $frame['type'] . $frame['function'] :
1111  $frame['function'];
1112 }
1113 
1114 /* Some generic result counters, pulled out of SearchEngine */
1115 
1124 function wfShowingResults( $offset, $limit ) {
1125  wfDeprecated( __FUNCTION__, '1.40' );
1126  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1127 }
1128 
1138 function wfClientAcceptsGzip( $force = false ) {
1139  static $result = null;
1140  if ( $result === null || $force ) {
1141  $result = false;
1142  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1143  # @todo FIXME: We may want to disallow some broken browsers
1144  $m = [];
1145  if ( preg_match(
1146  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1147  $_SERVER['HTTP_ACCEPT_ENCODING'],
1148  $m
1149  )
1150  ) {
1151  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1152  return $result;
1153  }
1154  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1155  $result = true;
1156  }
1157  }
1158  }
1159  return $result;
1160 }
1161 
1172 function wfEscapeWikiText( $text ) {
1173  global $wgEnableMagicLinks;
1174  static $repl = null, $repl2 = null;
1175  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1176  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1177  // in those situations
1178  $repl = [
1179  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1180  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1181  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1182  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1183  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1184  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1185  "\n " => "\n&#32;", "\r " => "\r&#32;",
1186  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1187  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1188  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1189  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1190  '__' => '_&#95;', '://' => '&#58;//',
1191  ];
1192 
1193  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1194  // We have to catch everything "\s" matches in PCRE
1195  foreach ( $magicLinks as $magic ) {
1196  $repl["$magic "] = "$magic&#32;";
1197  $repl["$magic\t"] = "$magic&#9;";
1198  $repl["$magic\r"] = "$magic&#13;";
1199  $repl["$magic\n"] = "$magic&#10;";
1200  $repl["$magic\f"] = "$magic&#12;";
1201  }
1202 
1203  // And handle protocols that don't use "://"
1204  global $wgUrlProtocols;
1205  $repl2 = [];
1206  foreach ( $wgUrlProtocols as $prot ) {
1207  if ( substr( $prot, -1 ) === ':' ) {
1208  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1209  }
1210  }
1211  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1212  }
1213  $text = substr( strtr( "\n$text", $repl ), 1 );
1214  // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
1215  $text = preg_replace( $repl2, '$1&#58;', $text );
1216  return $text;
1217 }
1218 
1229 function wfSetVar( &$dest, $source, $force = false ) {
1230  $temp = $dest;
1231  if ( $source !== null || $force ) {
1232  $dest = $source;
1233  }
1234  return $temp;
1235 }
1236 
1246 function wfSetBit( &$dest, $bit, $state = true ) {
1247  $temp = (bool)( $dest & $bit );
1248  if ( $state !== null ) {
1249  if ( $state ) {
1250  $dest |= $bit;
1251  } else {
1252  $dest &= ~$bit;
1253  }
1254  }
1255  return $temp;
1256 }
1257 
1264 function wfVarDump( $var ) {
1265  global $wgOut;
1266  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1267  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1268  print $s;
1269  } else {
1270  $wgOut->addHTML( $s );
1271  }
1272 }
1273 
1281 function wfHttpError( $code, $label, $desc ) {
1282  global $wgOut;
1283  HttpStatus::header( $code );
1284  if ( $wgOut ) {
1285  $wgOut->disable();
1286  $wgOut->sendCacheControl();
1287  }
1288 
1289  \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1290  header( 'Content-type: text/html; charset=utf-8' );
1291  ob_start();
1292  print '<!DOCTYPE html>' .
1293  '<html><head><title>' .
1294  htmlspecialchars( $label ) .
1295  '</title></head><body><h1>' .
1296  htmlspecialchars( $label ) .
1297  '</h1><p>' .
1298  nl2br( htmlspecialchars( $desc ) ) .
1299  "</p></body></html>\n";
1300  header( 'Content-Length: ' . ob_get_length() );
1301  ob_end_flush();
1302 }
1303 
1321 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1322  while ( $status = ob_get_status() ) {
1323  if ( isset( $status['flags'] ) ) {
1324  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1325  $deleteable = ( $status['flags'] & $flags ) === $flags;
1326  } elseif ( isset( $status['del'] ) ) {
1327  $deleteable = $status['del'];
1328  } else {
1329  // Guess that any PHP-internal setting can't be removed.
1330  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1331  }
1332  if ( !$deleteable ) {
1333  // Give up, and hope the result doesn't break
1334  // output behavior.
1335  break;
1336  }
1337  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1338  // Unit testing barrier to prevent this function from breaking PHPUnit.
1339  break;
1340  }
1341  if ( !ob_end_clean() ) {
1342  // Could not remove output buffer handler; abort now
1343  // to avoid getting in some kind of infinite loop.
1344  break;
1345  }
1346  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1347  // Reset the 'Content-Encoding' field set by this handler
1348  // so we can start fresh.
1349  header_remove( 'Content-Encoding' );
1350  break;
1351  }
1352  }
1353 }
1354 
1370  wfDeprecated( __FUNCTION__, '1.36' );
1371  wfResetOutputBuffers( false );
1372 }
1373 
1384 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1385  $ret = MWTimestamp::convert( $outputtype, $ts );
1386  if ( $ret === false ) {
1387  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1388  }
1389  return $ret;
1390 }
1391 
1400 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1401  if ( $ts === null ) {
1402  return null;
1403  } else {
1404  return wfTimestamp( $outputtype, $ts );
1405  }
1406 }
1407 
1413 function wfTimestampNow() {
1414  return MWTimestamp::now( TS_MW );
1415 }
1416 
1422 function wfIsWindows() {
1423  return PHP_OS_FAMILY === 'Windows';
1424 }
1425 
1432 function wfIsCLI() {
1433  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1434 }
1435 
1447 function wfTempDir() {
1448  global $wgTmpDirectory;
1449 
1450  if ( $wgTmpDirectory !== false ) {
1451  return $wgTmpDirectory;
1452  }
1453 
1455 }
1456 
1466 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1467  global $wgDirectoryMode;
1468 
1469  if ( FileBackend::isStoragePath( $dir ) ) {
1470  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1471  }
1472 
1473  if ( $caller !== null ) {
1474  wfDebug( "$caller: called wfMkdirParents($dir)" );
1475  }
1476 
1477  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1478  return true;
1479  }
1480 
1481  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1482 
1483  if ( $mode === null ) {
1484  $mode = $wgDirectoryMode;
1485  }
1486 
1487  // Turn off the normal warning, we're doing our own below
1488  AtEase::suppressWarnings();
1489  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1490  AtEase::restoreWarnings();
1491 
1492  if ( !$ok ) {
1493  // directory may have been created on another request since we last checked
1494  if ( is_dir( $dir ) ) {
1495  return true;
1496  }
1497 
1498  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1499  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1500  }
1501  return $ok;
1502 }
1503 
1509 function wfRecursiveRemoveDir( $dir ) {
1510  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1511  if ( is_dir( $dir ) ) {
1512  $objects = scandir( $dir );
1513  foreach ( $objects as $object ) {
1514  if ( $object != "." && $object != ".." ) {
1515  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1516  wfRecursiveRemoveDir( $dir . '/' . $object );
1517  } else {
1518  unlink( $dir . '/' . $object );
1519  }
1520  }
1521  }
1522  reset( $objects );
1523  rmdir( $dir );
1524  }
1525 }
1526 
1533 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1534  $accForFormat = $acc >= 0 ? $acc : 0;
1535  $ret = sprintf( "%.{$accForFormat}f", $nr );
1536  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1537 }
1538 
1562 function wfIniGetBool( $setting ) {
1563  return wfStringToBool( ini_get( $setting ) );
1564 }
1565 
1578 function wfStringToBool( $val ) {
1579  $val = strtolower( $val );
1580  // 'on' and 'true' can't have whitespace around them, but '1' can.
1581  return $val == 'on'
1582  || $val == 'true'
1583  || $val == 'yes'
1584  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1585 }
1586 
1600 function wfEscapeShellArg( ...$args ) {
1601  return Shell::escape( ...$args );
1602 }
1603 
1628 function wfShellExec( $cmd, &$retval = null, $environ = [],
1629  $limits = [], $options = []
1630 ) {
1631  if ( Shell::isDisabled() ) {
1632  $retval = 1;
1633  // Backwards compatibility be upon us...
1634  return 'Unable to run external programs, proc_open() is disabled.';
1635  }
1636 
1637  if ( is_array( $cmd ) ) {
1638  $cmd = Shell::escape( $cmd );
1639  }
1640 
1641  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1642  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1643 
1644  try {
1645  $result = Shell::command( [] )
1646  ->unsafeParams( (array)$cmd )
1647  ->environment( $environ )
1648  ->limits( $limits )
1649  ->includeStderr( $includeStderr )
1650  ->profileMethod( $profileMethod )
1651  // For b/c
1652  ->restrict( Shell::RESTRICT_NONE )
1653  ->execute();
1654  } catch ( ProcOpenError $ex ) {
1655  $retval = -1;
1656  return '';
1657  }
1658 
1659  $retval = $result->getExitCode();
1660 
1661  return $result->getStdout();
1662 }
1663 
1681 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1682  return wfShellExec( $cmd, $retval, $environ, $limits,
1683  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1684 }
1685 
1701 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1702  global $wgPhpCli;
1703  // Give site config file a chance to run the script in a wrapper.
1704  // The caller may likely want to call wfBasename() on $script.
1705  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1706  $cmd = [ $options['php'] ?? $wgPhpCli ];
1707  if ( isset( $options['wrapper'] ) ) {
1708  $cmd[] = $options['wrapper'];
1709  }
1710  $cmd[] = $script;
1711  // Escape each parameter for shell
1712  return Shell::escape( array_merge( $cmd, $parameters ) );
1713 }
1714 
1726 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
1727  global $wgDiff3;
1728 
1729  # This check may also protect against code injection in
1730  # case of broken installations.
1731  AtEase::suppressWarnings();
1732  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1733  AtEase::restoreWarnings();
1734 
1735  if ( !$haveDiff3 ) {
1736  wfDebug( "diff3 not found" );
1737  return false;
1738  }
1739 
1740  # Make temporary files
1741  $td = wfTempDir();
1742  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1743  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1744  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1745 
1746  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1747  # a newline character. To avoid this, we normalize the trailing whitespace before
1748  # creating the diff.
1749 
1750  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1751  fclose( $oldtextFile );
1752  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1753  fclose( $mytextFile );
1754  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1755  fclose( $yourtextFile );
1756 
1757  # Check for a conflict
1758  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
1759  $oldtextName, $yourtextName );
1760  $handle = popen( $cmd, 'r' );
1761 
1762  $mergeAttemptResult = '';
1763  do {
1764  $data = fread( $handle, 8192 );
1765  if ( strlen( $data ) == 0 ) {
1766  break;
1767  }
1768  $mergeAttemptResult .= $data;
1769  } while ( true );
1770  pclose( $handle );
1771 
1772  $conflict = $mergeAttemptResult !== '';
1773 
1774  # Merge differences
1775  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
1776  $oldtextName, $yourtextName );
1777  $handle = popen( $cmd, 'r' );
1778  $result = '';
1779  do {
1780  $data = fread( $handle, 8192 );
1781  if ( strlen( $data ) == 0 ) {
1782  break;
1783  }
1784  $result .= $data;
1785  } while ( true );
1786  pclose( $handle );
1787  unlink( $mytextName );
1788  unlink( $oldtextName );
1789  unlink( $yourtextName );
1790 
1791  if ( $result === '' && $old !== '' && !$conflict ) {
1792  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1793  $conflict = true;
1794  }
1795  return !$conflict;
1796 }
1797 
1810 function wfBaseName( $path, $suffix = '' ) {
1811  if ( $suffix == '' ) {
1812  $encSuffix = '';
1813  } else {
1814  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1815  }
1816 
1817  $matches = [];
1818  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1819  return $matches[1];
1820  } else {
1821  return '';
1822  }
1823 }
1824 
1834 function wfRelativePath( $path, $from ) {
1835  // Normalize mixed input on Windows...
1836  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1837  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1838 
1839  // Trim trailing slashes -- fix for drive root
1840  $path = rtrim( $path, DIRECTORY_SEPARATOR );
1841  $from = rtrim( $from, DIRECTORY_SEPARATOR );
1842 
1843  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1844  $against = explode( DIRECTORY_SEPARATOR, $from );
1845 
1846  if ( $pieces[0] !== $against[0] ) {
1847  // Non-matching Windows drive letters?
1848  // Return a full path.
1849  return $path;
1850  }
1851 
1852  // Trim off common prefix
1853  while ( count( $pieces ) && count( $against )
1854  && $pieces[0] == $against[0] ) {
1855  array_shift( $pieces );
1856  array_shift( $against );
1857  }
1858 
1859  // relative dots to bump us to the parent
1860  while ( count( $against ) ) {
1861  array_unshift( $pieces, '..' );
1862  array_shift( $against );
1863  }
1864 
1865  $pieces[] = wfBaseName( $path );
1866 
1867  return implode( DIRECTORY_SEPARATOR, $pieces );
1868 }
1869 
1901 function wfGetDB( $db, $groups = [], $wiki = false ) {
1902  if ( $wiki === false ) {
1903  return MediaWikiServices::getInstance()
1904  ->getDBLoadBalancer()
1905  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1906  } else {
1907  return MediaWikiServices::getInstance()
1908  ->getDBLoadBalancerFactory()
1909  ->getMainLB( $wiki )
1910  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1911  }
1912 }
1913 
1922 function wfScript( $script = 'index' ) {
1924  if ( $script === 'index' ) {
1925  return $wgScript;
1926  } elseif ( $script === 'load' ) {
1927  return $wgLoadScript;
1928  } else {
1929  return "{$wgScriptPath}/{$script}.php";
1930  }
1931 }
1932 
1940 function wfBoolToStr( $value ) {
1941  return $value ? 'true' : 'false';
1942 }
1943 
1949 function wfGetNull() {
1950  return wfIsWindows() ? 'NUL' : '/dev/null';
1951 }
1952 
1961 function wfStripIllegalFilenameChars( $name ) {
1962  global $wgIllegalFileChars;
1963  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1964  $name = preg_replace(
1965  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1966  '-',
1967  $name
1968  );
1969  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1970  $name = wfBaseName( $name );
1971  return $name;
1972 }
1973 
1980 function wfMemoryLimit( $newLimit ) {
1981  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1982  // If the INI config is already unlimited, there is nothing larger
1983  if ( $oldLimit != -1 ) {
1984  $newLimit = wfShorthandToInteger( (string)$newLimit );
1985  if ( $newLimit == -1 ) {
1986  wfDebug( "Removing PHP's memory limit" );
1987  AtEase::suppressWarnings();
1988  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1989  ini_set( 'memory_limit', $newLimit );
1990  AtEase::restoreWarnings();
1991  } elseif ( $newLimit > $oldLimit ) {
1992  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1993  AtEase::suppressWarnings();
1994  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1995  ini_set( 'memory_limit', $newLimit );
1996  AtEase::restoreWarnings();
1997  }
1998  }
1999 }
2000 
2009 
2010  $timeout = RequestTimeout::singleton();
2011  $timeLimit = $timeout->getWallTimeLimit();
2012  if ( $timeLimit !== INF ) {
2013  // RequestTimeout library is active
2014  if ( $wgTransactionalTimeLimit > $timeLimit ) {
2015  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2016  }
2017  } else {
2018  // Fallback case, likely $wgRequestTimeLimit === null
2019  $timeLimit = (int)ini_get( 'max_execution_time' );
2020  // Note that CLI scripts use 0
2021  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2022  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2023  }
2024  }
2025  ignore_user_abort( true ); // ignore client disconnects
2026 
2027  return $timeLimit;
2028 }
2029 
2037 function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2038  $string = trim( $string ?? '' );
2039  if ( $string === '' ) {
2040  return $default;
2041  }
2042  $last = $string[strlen( $string ) - 1];
2043  $val = intval( $string );
2044  switch ( $last ) {
2045  case 'g':
2046  case 'G':
2047  $val *= 1024;
2048  // break intentionally missing
2049  case 'm':
2050  case 'M':
2051  $val *= 1024;
2052  // break intentionally missing
2053  case 'k':
2054  case 'K':
2055  $val *= 1024;
2056  }
2057 
2058  return $val;
2059 }
2060 
2075 function wfUnpack( $format, $data, $length = false ) {
2076  if ( $length !== false ) {
2077  $realLen = strlen( $data );
2078  if ( $realLen < $length ) {
2079  throw new MWException( "Tried to use wfUnpack on a "
2080  . "string of length $realLen, but needed one "
2081  . "of at least length $length."
2082  );
2083  }
2084  }
2085 
2086  AtEase::suppressWarnings();
2087  $result = unpack( $format, $data );
2088  AtEase::restoreWarnings();
2089 
2090  if ( $result === false ) {
2091  // If it cannot extract the packed data.
2092  throw new MWException( "unpack could not unpack binary data" );
2093  }
2094  return $result;
2095 }
2096 
2104 function wfIsInfinity( $str ) {
2105  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2106  return in_array( $str, ExpiryDef::INFINITY_VALS );
2107 }
2108 
2123 function wfThumbIsStandard( File $file, array $params ) {
2125 
2126  $multipliers = [ 1 ];
2127  if ( $wgResponsiveImages ) {
2128  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2129  // @see Linker::processResponsiveImages
2130  $multipliers[] = 1.5;
2131  $multipliers[] = 2;
2132  }
2133 
2134  $handler = $file->getHandler();
2135  if ( !$handler || !isset( $params['width'] ) ) {
2136  return false;
2137  }
2138 
2139  $basicParams = [];
2140  if ( isset( $params['page'] ) ) {
2141  $basicParams['page'] = $params['page'];
2142  }
2143 
2144  $thumbLimits = [];
2145  $imageLimits = [];
2146  // Expand limits to account for multipliers
2147  foreach ( $multipliers as $multiplier ) {
2148  $thumbLimits = array_merge( $thumbLimits, array_map(
2149  static function ( $width ) use ( $multiplier ) {
2150  return round( $width * $multiplier );
2151  }, $wgThumbLimits )
2152  );
2153  $imageLimits = array_merge( $imageLimits, array_map(
2154  static function ( $pair ) use ( $multiplier ) {
2155  return [
2156  round( $pair[0] * $multiplier ),
2157  round( $pair[1] * $multiplier ),
2158  ];
2159  }, $wgImageLimits )
2160  );
2161  }
2162 
2163  // Check if the width matches one of $wgThumbLimits
2164  if ( in_array( $params['width'], $thumbLimits ) ) {
2165  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2166  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2167  $handler->normaliseParams( $file, $normalParams );
2168  } else {
2169  // If not, then check if the width matches one of $wgImageLimits
2170  $match = false;
2171  foreach ( $imageLimits as $pair ) {
2172  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2173  // Decide whether the thumbnail should be scaled on width or height.
2174  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2175  $handler->normaliseParams( $file, $normalParams );
2176  // Check if this standard thumbnail size maps to the given width
2177  if ( $normalParams['width'] == $params['width'] ) {
2178  $match = true;
2179  break;
2180  }
2181  }
2182  if ( !$match ) {
2183  return false; // not standard for description pages
2184  }
2185  }
2186 
2187  // Check that the given values for non-page, non-width, params are just defaults
2188  foreach ( $params as $key => $value ) {
2189  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2190  return false;
2191  }
2192  }
2193 
2194  return true;
2195 }
2196 
2209 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2210  // First merge items that are in both arrays
2211  foreach ( $baseArray as $name => &$groupVal ) {
2212  if ( isset( $newValues[$name] ) ) {
2213  $groupVal += $newValues[$name];
2214  }
2215  }
2216  // Now add items that didn't exist yet
2217  $baseArray += $newValues;
2218 
2219  return $baseArray;
2220 }
const PROTO_CURRENT
Definition: Defines.php:198
global $wgCommandLineMode
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
wfVarDump( $var)
A wrapper around the PHP function var_export().
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfTempDir()
Tries to get the system directory for temporary files.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfLoadExtension( $ext, $path=null)
Load an extension.
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfArrayDiff2( $arr1, $arr2)
Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfGetUrlUtils()
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfPercent( $nr, int $acc=2, bool $round=true)
wfReportTime( $nonce=null)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
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...
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfGetNull()
Get a platform-independent path to the null file, e.g.
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfShowingResults( $offset, $limit)
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
wfLoadSkin( $skin, $path=null)
Load a skin.
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
wfFormatStackFrame( $frame)
Return a string representation of frame.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfIsWindows()
Check if the operating system is Windows.
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfLoadExtensions(array $exts)
Load multiple extensions at once.
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
wfArrayInsertAfter(array $array, array $insert, $after)
Insert an array into another array after the specified key.
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
wfIsCLI()
Check if we are running from the commandline.
$matches
global $wgRequest
Definition: Setup.php:388
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgOut
Definition: Setup.php:508
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:508
const MW_ENTRY_POINT
Definition: api.php:41
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:67
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
static warning( $msg, $callerOffset=1, $level=E_USER_NOTICE, $log='auto')
Adds a warning entry to the log.
Definition: MWDebug.php:183
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition: MWDebug.php:224
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: MWDebug.php:306
MediaWiki exception.
Definition: MWException.php:30
PSR-3 logger instance factory.
Service locator for MediaWiki core services.
ResourceLoader is a loading system for JavaScript and CSS resources.
Executes shell commands.
Definition: Shell.php:46
Stub object for the user language.
A service to expand, parse, and otherwise manipulate URLs.
Definition: UrlUtils.php:17
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:459
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:425
static getUsableTempDirectory()
Definition: TempFSFile.php:79
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:737
static detectProtocol()
Detect the protocol from $_SERVER.
Definition: WebRequest.php:312
Type definition for expiry timestamps.
Definition: ExpiryDef.php:17
$wgLanguageCode
Config variable stub for the LanguageCode setting, for use by phpdoc and IDEs.
$wgScript
Config variable stub for the Script setting, for use by phpdoc and IDEs.
Definition: config-vars.php:73
$wgInternalServer
Config variable stub for the InternalServer setting, for use by phpdoc and IDEs.
$wgThumbLimits
Config variable stub for the ThumbLimits setting, for use by phpdoc and IDEs.
$wgDebugLogPrefix
Config variable stub for the DebugLogPrefix setting, for use by phpdoc and IDEs.
$wgPhpCli
Config variable stub for the PhpCli setting, for use by phpdoc and IDEs.
$wgOverrideHostname
Config variable stub for the OverrideHostname setting, for use by phpdoc and IDEs.
$wgImageLimits
Config variable stub for the ImageLimits setting, for use by phpdoc and IDEs.
$wgShowHostnames
Config variable stub for the ShowHostnames setting, for use by phpdoc and IDEs.
$wgTmpDirectory
Config variable stub for the TmpDirectory setting, for use by phpdoc and IDEs.
$wgStyleDirectory
Config variable stub for the StyleDirectory setting, for use by phpdoc and IDEs.
$wgTransactionalTimeLimit
Config variable stub for the TransactionalTimeLimit setting, for use by phpdoc and IDEs.
$wgIllegalFileChars
Config variable stub for the IllegalFileChars setting, for use by phpdoc and IDEs.
$wgDirectoryMode
Config variable stub for the DirectoryMode setting, for use by phpdoc and IDEs.
$wgDiff3
Config variable stub for the Diff3 setting, for use by phpdoc and IDEs.
$wgUrlProtocols
Config variable stub for the UrlProtocols setting, for use by phpdoc and IDEs.
$wgResponsiveImages
Config variable stub for the ResponsiveImages setting, for use by phpdoc and IDEs.
$wgDebugRawPage
Config variable stub for the DebugRawPage setting, for use by phpdoc and IDEs.
$wgEnableMagicLinks
Config variable stub for the EnableMagicLinks setting, for use by phpdoc and IDEs.
$wgScriptPath
Config variable stub for the ScriptPath setting, for use by phpdoc and IDEs.
Definition: config-vars.php:61
$wgExtensionDirectory
Config variable stub for the ExtensionDirectory setting, for use by phpdoc and IDEs.
$wgLoadScript
Config variable stub for the LoadScript setting, for use by phpdoc and IDEs.
Definition: config-vars.php:79
$wgCanonicalServer
Config variable stub for the CanonicalServer setting, for use by phpdoc and IDEs.
Definition: config-vars.php:31
$wgServer
Config variable stub for the Server setting, for use by phpdoc and IDEs.
Definition: config-vars.php:25
$wgHttpsPort
Config variable stub for the HttpsPort setting, for use by phpdoc and IDEs.
Definition: config-vars.php:49
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
$source
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
if(!is_readable( $file)) $ext
Definition: router.php:48