MediaWiki  master
GlobalFunctions.php
Go to the documentation of this file.
1 <?php
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( $arr1, $arr2 ) {
118  $comparator = static function ( $a, $b ): int {
119  if ( is_string( $a ) && is_string( $b ) ) {
120  return strcmp( $a, $b );
121  }
122  if ( !is_array( $a ) && !is_array( $b ) ) {
123  throw new InvalidArgumentException(
124  'This function assumes that array elements are all strings or all arrays'
125  );
126  }
127  if ( count( $a ) !== count( $b ) ) {
128  return count( $a ) <=> count( $b );
129  } else {
130  reset( $a );
131  reset( $b );
132  while ( key( $a ) !== null && key( $b ) !== null ) {
133  $valueA = current( $a );
134  $valueB = current( $b );
135  $cmp = strcmp( $valueA, $valueB );
136  if ( $cmp !== 0 ) {
137  return $cmp;
138  }
139  next( $a );
140  next( $b );
141  }
142  return 0;
143  }
144  };
145  return array_udiff( $arr1, $arr2, $comparator );
146 }
147 
167 function wfMergeErrorArrays( ...$args ) {
168  $out = [];
169  foreach ( $args as $errors ) {
170  foreach ( $errors as $params ) {
171  $originalParams = $params;
172  if ( $params[0] instanceof MessageSpecifier ) {
173  $msg = $params[0];
174  $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
175  }
176  # @todo FIXME: Sometimes get nested arrays for $params,
177  # which leads to E_NOTICEs
178  $spec = implode( "\t", $params );
179  $out[$spec] = $originalParams;
180  }
181  }
182  return array_values( $out );
183 }
184 
194 function wfArrayInsertAfter( array $array, array $insert, $after ) {
195  // Find the offset of the element to insert after.
196  $keys = array_keys( $array );
197  $offsetByKey = array_flip( $keys );
198 
199  if ( !\array_key_exists( $after, $offsetByKey ) ) {
200  return $array;
201  }
202  $offset = $offsetByKey[$after];
203 
204  // Insert at the specified offset
205  $before = array_slice( $array, 0, $offset + 1, true );
206  $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
207 
208  $output = $before + $insert + $after;
209 
210  return $output;
211 }
212 
221 function wfObjectToArray( $objOrArray, $recursive = true ) {
222  $array = [];
223  if ( is_object( $objOrArray ) ) {
224  $objOrArray = get_object_vars( $objOrArray );
225  }
226  foreach ( $objOrArray as $key => $value ) {
227  if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
228  $value = wfObjectToArray( $value );
229  }
230 
231  $array[$key] = $value;
232  }
233 
234  return $array;
235 }
236 
247 function wfRandom() {
248  // The maximum random value is "only" 2^31-1, so get two random
249  // values to reduce the chance of dupes
250  $max = mt_getrandmax() + 1;
251  $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
252  return $rand;
253 }
254 
265 function wfRandomString( $length = 32 ) {
266  $str = '';
267  for ( $n = 0; $n < $length; $n += 7 ) {
268  $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
269  }
270  return substr( $str, 0, $length );
271 }
272 
300 function wfUrlencode( $s ) {
301  static $needle;
302 
303  if ( $s === null ) {
304  // Reset $needle for testing.
305  $needle = null;
306  return '';
307  }
308 
309  if ( $needle === null ) {
310  $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
311  if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
312  ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
313  ) {
314  $needle[] = '%3A';
315  }
316  }
317 
318  $s = urlencode( $s );
319  $s = str_ireplace(
320  $needle,
321  [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
322  $s
323  );
324 
325  return $s;
326 }
327 
338 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
339  if ( $array2 !== null ) {
340  $array1 += $array2;
341  }
342 
343  $cgi = '';
344  foreach ( $array1 as $key => $value ) {
345  if ( $value !== null && $value !== false ) {
346  if ( $cgi != '' ) {
347  $cgi .= '&';
348  }
349  if ( $prefix !== '' ) {
350  $key = $prefix . "[$key]";
351  }
352  if ( is_array( $value ) ) {
353  $firstTime = true;
354  foreach ( $value as $k => $v ) {
355  $cgi .= $firstTime ? '' : '&';
356  if ( is_array( $v ) ) {
357  $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
358  } else {
359  $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
360  }
361  $firstTime = false;
362  }
363  } else {
364  if ( is_object( $value ) ) {
365  $value = $value->__toString();
366  }
367  $cgi .= urlencode( $key ) . '=' . urlencode( $value );
368  }
369  }
370  }
371  return $cgi;
372 }
373 
383 function wfCgiToArray( $query ) {
384  if ( isset( $query[0] ) && $query[0] == '?' ) {
385  $query = substr( $query, 1 );
386  }
387  $bits = explode( '&', $query );
388  $ret = [];
389  foreach ( $bits as $bit ) {
390  if ( $bit === '' ) {
391  continue;
392  }
393  if ( strpos( $bit, '=' ) === false ) {
394  // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
395  $key = $bit;
396  $value = '';
397  } else {
398  [ $key, $value ] = explode( '=', $bit );
399  }
400  $key = urldecode( $key );
401  $value = urldecode( $value );
402  if ( strpos( $key, '[' ) !== false ) {
403  $keys = array_reverse( explode( '[', $key ) );
404  $key = array_pop( $keys );
405  $temp = $value;
406  foreach ( $keys as $k ) {
407  $k = substr( $k, 0, -1 );
408  $temp = [ $k => $temp ];
409  }
410  if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
411  $ret[$key] = array_merge( $ret[$key], $temp );
412  } else {
413  $ret[$key] = $temp;
414  }
415  } else {
416  $ret[$key] = $value;
417  }
418  }
419  return $ret;
420 }
421 
430 function wfAppendQuery( $url, $query ) {
431  if ( is_array( $query ) ) {
432  $query = wfArrayToCgi( $query );
433  }
434  if ( $query != '' ) {
435  // Remove the fragment, if there is one
436  $fragment = false;
437  $hashPos = strpos( $url, '#' );
438  if ( $hashPos !== false ) {
439  $fragment = substr( $url, $hashPos );
440  $url = substr( $url, 0, $hashPos );
441  }
442 
443  // Add parameter
444  if ( strpos( $url, '?' ) === false ) {
445  $url .= '?';
446  } else {
447  $url .= '&';
448  }
449  $url .= $query;
450 
451  // Put the fragment back
452  if ( $fragment !== false ) {
453  $url .= $fragment;
454  }
455  }
456  return $url;
457 }
458 
464 function wfGetUrlUtils(): UrlUtils {
467 
468  if ( MediaWikiServices::hasInstance() ) {
469  $services = MediaWikiServices::getInstance();
470  if ( $services->hasService( 'UrlUtils' ) ) {
471  return $services->getUrlUtils();
472  }
473  }
474 
475  return new UrlUtils( [
476  // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
477  // implementations implicitly converted it to an empty string (presumably by mistake).
478  // Preserve the old behavior for compatibility.
479  UrlUtils::SERVER => $wgServer ?? '',
480  UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
481  UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
482  UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
484  UrlUtils::HTTPS_PORT => $wgHttpsPort,
485  UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
486  ] );
487 }
488 
516 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
517  return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
518 }
519 
529 function wfGetServerUrl( $proto ) {
530  return wfGetUrlUtils()->getServer( $proto ) ?? '';
531 }
532 
545 function wfAssembleUrl( $urlParts ) {
546  return wfGetUrlUtils()->assemble( (array)$urlParts );
547 }
548 
560 function wfRemoveDotSegments( $urlPath ) {
561  return wfGetUrlUtils()->removeDotSegments( (string)$urlPath );
562 }
563 
572 function wfUrlProtocols( $includeProtocolRelative = true ) {
573  $method = $includeProtocolRelative ? 'validProtocols' : 'validAbsoluteProtocols';
574  return wfGetUrlUtils()->$method();
575 }
576 
585  return wfGetUrlUtils()->validAbsoluteProtocols();
586 }
587 
614 function wfParseUrl( $url ) {
615  return wfGetUrlUtils()->parse( (string)$url ) ?? false;
616 }
617 
627 function wfExpandIRI( $url ) {
628  return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
629 }
630 
639 function wfMatchesDomainList( $url, $domains ) {
640  return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
641 }
642 
663 function wfDebug( $text, $dest = 'all', array $context = [] ) {
665 
666  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
667  return;
668  }
669 
670  $text = trim( $text );
671 
672  if ( $wgDebugLogPrefix !== '' ) {
673  $context['prefix'] = $wgDebugLogPrefix;
674  }
675  $context['private'] = ( $dest === false || $dest === 'private' );
676 
677  $logger = LoggerFactory::getInstance( 'wfDebug' );
678  $logger->debug( $text, $context );
679 }
680 
685 function wfIsDebugRawPage() {
686  static $cache;
687  if ( $cache !== null ) {
688  return $cache;
689  }
690  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
691  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
692  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
693  || MW_ENTRY_POINT === 'load'
694  ) {
695  $cache = true;
696  } else {
697  $cache = false;
698  }
699  return $cache;
700 }
701 
727 function wfDebugLog(
728  $logGroup, $text, $dest = 'all', array $context = []
729 ) {
730  $text = trim( $text );
731 
732  $logger = LoggerFactory::getInstance( $logGroup );
733  $context['private'] = ( $dest === false || $dest === 'private' );
734  $logger->info( $text, $context );
735 }
736 
745 function wfLogDBError( $text, array $context = [] ) {
746  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
747  $logger->error( trim( $text ), $context );
748 }
749 
766 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
767  if ( !is_string( $version ) && $version !== false ) {
768  throw new InvalidArgumentException(
769  "MediaWiki version must either be a string or false. " .
770  "Example valid version: '1.33'"
771  );
772  }
773 
774  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
775 }
776 
797 function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
798  MWDebug::deprecatedMsg( $msg, $version, $component,
799  $callerOffset === false ? false : $callerOffset + 1 );
800 }
801 
812 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
813  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
814 }
815 
825 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
826  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
827 }
828 
845 function wfGetLangObj( $langcode = false ) {
846  wfDeprecated( __FUNCTION__, '1.41' );
847  # Identify which language to get or create a language object for.
848  # Using is_object here due to Stub objects.
849  if ( is_object( $langcode ) ) {
850  # Great, we already have the object (hopefully)!
851  return $langcode;
852  }
853 
854  global $wgLanguageCode;
855  $services = MediaWikiServices::getInstance();
856  if ( $langcode === true || $langcode === $wgLanguageCode ) {
857  # $langcode is the language code of the wikis content language object.
858  # or it is a boolean and value is true
859  return $services->getContentLanguage();
860  }
861 
862  global $wgLang;
863  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
864  # $langcode is the language code of user language object.
865  # or it was a boolean and value is false
866  return $wgLang;
867  }
868 
869  $languageNames = $services->getLanguageNameUtils()->getLanguageNames();
870  // FIXME: Can we use isSupportedLanguage here?
871  if ( isset( $languageNames[$langcode] ) ) {
872  # $langcode corresponds to a valid language.
873  return $services->getLanguageFactory()->getLanguage( $langcode );
874  }
875 
876  # $langcode is a string, but not a valid language code; use content language.
877  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
878  return $services->getContentLanguage();
879 }
880 
902 function wfMessage( $key, ...$params ) {
903  if ( is_array( $key ) ) {
904  // Fallback keys are not allowed in message specifiers
905  $message = wfMessageFallback( ...$key );
906  } else {
907  $message = Message::newFromSpecifier( $key );
908  }
909 
910  // We call Message::params() to reduce code duplication
911  if ( $params ) {
912  $message->params( ...$params );
913  }
914 
915  return $message;
916 }
917 
930 function wfMessageFallback( ...$keys ) {
931  return Message::newFallbackSequence( ...$keys );
932 }
933 
942 function wfMsgReplaceArgs( $message, $args ) {
943  # Fix windows line-endings
944  # Some messages are split with explode("\n", $msg)
945  $message = str_replace( "\r", '', $message );
946 
947  // Replace arguments
948  if ( is_array( $args ) && $args ) {
949  if ( is_array( $args[0] ) ) {
950  $args = array_values( $args[0] );
951  }
952  $replacementKeys = [];
953  foreach ( $args as $n => $param ) {
954  $replacementKeys['$' . ( $n + 1 )] = $param;
955  }
956  $message = strtr( $message, $replacementKeys );
957  }
958 
959  return $message;
960 }
961 
970 function wfHostname() {
971  // Hostname overriding
972  global $wgOverrideHostname;
973  if ( $wgOverrideHostname !== false ) {
974  return $wgOverrideHostname;
975  }
976 
977  return php_uname( 'n' ) ?: 'unknown';
978 }
979 
991 function wfReportTime( $nonce = null ) {
992  global $wgShowHostnames;
993 
994  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
995  // seconds to milliseconds
996  $responseTime = round( $elapsed * 1000 );
997  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
998  if ( $wgShowHostnames ) {
999  $reportVars['wgHostname'] = wfHostname();
1000  }
1001 
1002  return (
1003  ResourceLoader::makeInlineScript(
1004  ResourceLoader::makeConfigSetScript( $reportVars ),
1005  $nonce
1006  )
1007  );
1008 }
1009 
1020 function wfDebugBacktrace( $limit = 0 ) {
1021  static $disabled = null;
1022 
1023  if ( $disabled === null ) {
1024  $disabled = !function_exists( 'debug_backtrace' );
1025  if ( $disabled ) {
1026  wfDebug( "debug_backtrace() is disabled" );
1027  }
1028  }
1029  if ( $disabled ) {
1030  return [];
1031  }
1032 
1033  if ( $limit ) {
1034  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1035  } else {
1036  return array_slice( debug_backtrace(), 1 );
1037  }
1038 }
1039 
1048 function wfBacktrace( $raw = null ) {
1049  global $wgCommandLineMode;
1050 
1051  if ( $raw ?? $wgCommandLineMode ) {
1052  $frameFormat = "%s line %s calls %s()\n";
1053  $traceFormat = "%s";
1054  } else {
1055  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1056  $traceFormat = "<ul>\n%s</ul>\n";
1057  }
1058 
1059  $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1060  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1061  $line = $frame['line'] ?? '-';
1062  $call = $frame['function'];
1063  if ( !empty( $frame['class'] ) ) {
1064  $call = $frame['class'] . $frame['type'] . $call;
1065  }
1066  return sprintf( $frameFormat, $file, $line, $call );
1067  }, wfDebugBacktrace() );
1068 
1069  return sprintf( $traceFormat, implode( '', $frames ) );
1070 }
1071 
1081 function wfGetCaller( $level = 2 ) {
1082  $backtrace = wfDebugBacktrace( $level + 1 );
1083  if ( isset( $backtrace[$level] ) ) {
1084  return wfFormatStackFrame( $backtrace[$level] );
1085  } else {
1086  return 'unknown';
1087  }
1088 }
1089 
1097 function wfGetAllCallers( $limit = 3 ) {
1098  $trace = array_reverse( wfDebugBacktrace() );
1099  if ( !$limit || $limit > count( $trace ) - 1 ) {
1100  $limit = count( $trace ) - 1;
1101  }
1102  $trace = array_slice( $trace, -$limit - 1, $limit );
1103  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1104 }
1105 
1112 function wfFormatStackFrame( $frame ) {
1113  if ( !isset( $frame['function'] ) ) {
1114  return 'NO_FUNCTION_GIVEN';
1115  }
1116  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1117  $frame['class'] . $frame['type'] . $frame['function'] :
1118  $frame['function'];
1119 }
1120 
1130 function wfClientAcceptsGzip( $force = false ) {
1131  static $result = null;
1132  if ( $result === null || $force ) {
1133  $result = false;
1134  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1135  # @todo FIXME: We may want to disallow some broken browsers
1136  $m = [];
1137  if ( preg_match(
1138  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1139  $_SERVER['HTTP_ACCEPT_ENCODING'],
1140  $m
1141  )
1142  ) {
1143  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1144  return $result;
1145  }
1146  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1147  $result = true;
1148  }
1149  }
1150  }
1151  return $result;
1152 }
1153 
1164 function wfEscapeWikiText( $text ) {
1165  global $wgEnableMagicLinks;
1166  static $repl = null, $repl2 = null;
1167  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1168  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1169  // in those situations
1170  $repl = [
1171  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1172  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1173  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1174  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1175  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1176  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1177  "\n " => "\n&#32;", "\r " => "\r&#32;",
1178  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1179  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1180  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1181  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1182  '__' => '_&#95;', '://' => '&#58;//',
1183  ];
1184 
1185  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1186  // We have to catch everything "\s" matches in PCRE
1187  foreach ( $magicLinks as $magic ) {
1188  $repl["$magic "] = "$magic&#32;";
1189  $repl["$magic\t"] = "$magic&#9;";
1190  $repl["$magic\r"] = "$magic&#13;";
1191  $repl["$magic\n"] = "$magic&#10;";
1192  $repl["$magic\f"] = "$magic&#12;";
1193  }
1194 
1195  // And handle protocols that don't use "://"
1196  global $wgUrlProtocols;
1197  $repl2 = [];
1198  foreach ( $wgUrlProtocols as $prot ) {
1199  if ( substr( $prot, -1 ) === ':' ) {
1200  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1201  }
1202  }
1203  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1204  }
1205  $text = substr( strtr( "\n$text", $repl ), 1 );
1206  // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
1207  $text = preg_replace( $repl2, '$1&#58;', $text );
1208  return $text;
1209 }
1210 
1221 function wfSetVar( &$dest, $source, $force = false ) {
1222  $temp = $dest;
1223  if ( $source !== null || $force ) {
1224  $dest = $source;
1225  }
1226  return $temp;
1227 }
1228 
1238 function wfSetBit( &$dest, $bit, $state = true ) {
1239  $temp = (bool)( $dest & $bit );
1240  if ( $state !== null ) {
1241  if ( $state ) {
1242  $dest |= $bit;
1243  } else {
1244  $dest &= ~$bit;
1245  }
1246  }
1247  return $temp;
1248 }
1249 
1256 function wfVarDump( $var ) {
1257  global $wgOut;
1258  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1259  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1260  print $s;
1261  } else {
1262  $wgOut->addHTML( $s );
1263  }
1264 }
1265 
1273 function wfHttpError( $code, $label, $desc ) {
1274  global $wgOut;
1275  HttpStatus::header( $code );
1276  if ( $wgOut ) {
1277  $wgOut->disable();
1278  $wgOut->sendCacheControl();
1279  }
1280 
1281  \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1282  header( 'Content-type: text/html; charset=utf-8' );
1283  ob_start();
1284  print '<!DOCTYPE html>' .
1285  '<html><head><title>' .
1286  htmlspecialchars( $label ) .
1287  '</title></head><body><h1>' .
1288  htmlspecialchars( $label ) .
1289  '</h1><p>' .
1290  nl2br( htmlspecialchars( $desc ) ) .
1291  "</p></body></html>\n";
1292  header( 'Content-Length: ' . ob_get_length() );
1293  ob_end_flush();
1294 }
1295 
1313 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1314  while ( $status = ob_get_status() ) {
1315  if ( isset( $status['flags'] ) ) {
1316  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1317  $deleteable = ( $status['flags'] & $flags ) === $flags;
1318  } elseif ( isset( $status['del'] ) ) {
1319  $deleteable = $status['del'];
1320  } else {
1321  // Guess that any PHP-internal setting can't be removed.
1322  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1323  }
1324  if ( !$deleteable ) {
1325  // Give up, and hope the result doesn't break
1326  // output behavior.
1327  break;
1328  }
1329  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1330  // Unit testing barrier to prevent this function from breaking PHPUnit.
1331  break;
1332  }
1333  if ( !ob_end_clean() ) {
1334  // Could not remove output buffer handler; abort now
1335  // to avoid getting in some kind of infinite loop.
1336  break;
1337  }
1338  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1339  // Reset the 'Content-Encoding' field set by this handler
1340  // so we can start fresh.
1341  header_remove( 'Content-Encoding' );
1342  break;
1343  }
1344  }
1345 }
1346 
1362  wfDeprecated( __FUNCTION__, '1.36' );
1363  wfResetOutputBuffers( false );
1364 }
1365 
1376 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1377  $ret = MWTimestamp::convert( $outputtype, $ts );
1378  if ( $ret === false ) {
1379  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1380  }
1381  return $ret;
1382 }
1383 
1392 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1393  if ( $ts === null ) {
1394  return null;
1395  } else {
1396  return wfTimestamp( $outputtype, $ts );
1397  }
1398 }
1399 
1405 function wfTimestampNow() {
1406  return MWTimestamp::now( TS_MW );
1407 }
1408 
1420 function wfTempDir() {
1421  global $wgTmpDirectory;
1422 
1423  if ( $wgTmpDirectory !== false ) {
1424  return $wgTmpDirectory;
1425  }
1426 
1428 }
1429 
1439 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1440  global $wgDirectoryMode;
1441 
1442  if ( FileBackend::isStoragePath( $dir ) ) {
1443  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1444  }
1445 
1446  if ( $caller !== null ) {
1447  wfDebug( "$caller: called wfMkdirParents($dir)" );
1448  }
1449 
1450  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1451  return true;
1452  }
1453 
1454  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1455 
1456  if ( $mode === null ) {
1457  $mode = $wgDirectoryMode;
1458  }
1459 
1460  // Turn off the normal warning, we're doing our own below
1461  AtEase::suppressWarnings();
1462  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1463  AtEase::restoreWarnings();
1464 
1465  if ( !$ok ) {
1466  // directory may have been created on another request since we last checked
1467  if ( is_dir( $dir ) ) {
1468  return true;
1469  }
1470 
1471  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1472  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1473  }
1474  return $ok;
1475 }
1476 
1482 function wfRecursiveRemoveDir( $dir ) {
1483  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1484  if ( is_dir( $dir ) ) {
1485  $objects = scandir( $dir );
1486  foreach ( $objects as $object ) {
1487  if ( $object != "." && $object != ".." ) {
1488  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1489  wfRecursiveRemoveDir( $dir . '/' . $object );
1490  } else {
1491  unlink( $dir . '/' . $object );
1492  }
1493  }
1494  }
1495  rmdir( $dir );
1496  }
1497 }
1498 
1505 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1506  $accForFormat = $acc >= 0 ? $acc : 0;
1507  $ret = sprintf( "%.{$accForFormat}f", $nr );
1508  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1509 }
1510 
1534 function wfIniGetBool( $setting ) {
1535  return wfStringToBool( ini_get( $setting ) );
1536 }
1537 
1550 function wfStringToBool( $val ) {
1551  $val = strtolower( $val );
1552  // 'on' and 'true' can't have whitespace around them, but '1' can.
1553  return $val == 'on'
1554  || $val == 'true'
1555  || $val == 'yes'
1556  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1557 }
1558 
1572 function wfEscapeShellArg( ...$args ) {
1573  return Shell::escape( ...$args );
1574 }
1575 
1600 function wfShellExec( $cmd, &$retval = null, $environ = [],
1601  $limits = [], $options = []
1602 ) {
1603  if ( Shell::isDisabled() ) {
1604  $retval = 1;
1605  // Backwards compatibility be upon us...
1606  return 'Unable to run external programs, proc_open() is disabled.';
1607  }
1608 
1609  if ( is_array( $cmd ) ) {
1610  $cmd = Shell::escape( $cmd );
1611  }
1612 
1613  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1614  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1615 
1616  try {
1617  $result = Shell::command( [] )
1618  ->unsafeParams( (array)$cmd )
1619  ->environment( $environ )
1620  ->limits( $limits )
1621  ->includeStderr( $includeStderr )
1622  ->profileMethod( $profileMethod )
1623  // For b/c
1624  ->restrict( Shell::RESTRICT_NONE )
1625  ->execute();
1626  } catch ( ProcOpenError $ex ) {
1627  $retval = -1;
1628  return '';
1629  }
1630 
1631  $retval = $result->getExitCode();
1632 
1633  return $result->getStdout();
1634 }
1635 
1653 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1654  return wfShellExec( $cmd, $retval, $environ, $limits,
1655  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1656 }
1657 
1673 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1674  global $wgPhpCli;
1675  // Give site config file a chance to run the script in a wrapper.
1676  // The caller may likely want to call wfBasename() on $script.
1677  ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1678  ->onWfShellWikiCmd( $script, $parameters, $options );
1679  $cmd = [ $options['php'] ?? $wgPhpCli ];
1680  if ( isset( $options['wrapper'] ) ) {
1681  $cmd[] = $options['wrapper'];
1682  }
1683  $cmd[] = $script;
1684  // Escape each parameter for shell
1685  return Shell::escape( array_merge( $cmd, $parameters ) );
1686 }
1687 
1704 function wfMerge(
1705  string $old,
1706  string $mine,
1707  string $yours,
1708  ?string &$simplisticMergeAttempt,
1709  string &$mergeLeftovers = null
1710 ): bool {
1711  global $wgDiff3;
1712 
1713  # This check may also protect against code injection in
1714  # case of broken installations.
1715  AtEase::suppressWarnings();
1716  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1717  AtEase::restoreWarnings();
1718 
1719  if ( !$haveDiff3 ) {
1720  wfDebug( "diff3 not found" );
1721  return false;
1722  }
1723 
1724  # Make temporary files
1725  $td = wfTempDir();
1726  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1727  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1728  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1729 
1730  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1731  # a newline character. To avoid this, we normalize the trailing whitespace before
1732  # creating the diff.
1733 
1734  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1735  fclose( $oldtextFile );
1736  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1737  fclose( $mytextFile );
1738  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1739  fclose( $yourtextFile );
1740 
1741  # Check for a conflict
1742  $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1743  $oldtextName, $yourtextName );
1744  $handle = popen( $cmd, 'r' );
1745 
1746  $mergeLeftovers = '';
1747  do {
1748  $data = fread( $handle, 8192 );
1749  if ( strlen( $data ) == 0 ) {
1750  break;
1751  }
1752  $mergeLeftovers .= $data;
1753  } while ( true );
1754  pclose( $handle );
1755 
1756  $conflict = $mergeLeftovers !== '';
1757 
1758  # Merge differences automatically where possible, preferring "my" text for conflicts.
1759  $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1760  $oldtextName, $yourtextName );
1761  $handle = popen( $cmd, 'r' );
1762  $simplisticMergeAttempt = '';
1763  do {
1764  $data = fread( $handle, 8192 );
1765  if ( strlen( $data ) == 0 ) {
1766  break;
1767  }
1768  $simplisticMergeAttempt .= $data;
1769  } while ( true );
1770  pclose( $handle );
1771  unlink( $mytextName );
1772  unlink( $oldtextName );
1773  unlink( $yourtextName );
1774 
1775  if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1776  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1777  $conflict = true;
1778  }
1779  return !$conflict;
1780 }
1781 
1794 function wfBaseName( $path, $suffix = '' ) {
1795  if ( $suffix == '' ) {
1796  $encSuffix = '';
1797  } else {
1798  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1799  }
1800 
1801  $matches = [];
1802  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1803  return $matches[1];
1804  } else {
1805  return '';
1806  }
1807 }
1808 
1818 function wfRelativePath( $path, $from ) {
1819  // Normalize mixed input on Windows...
1820  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1821  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1822 
1823  // Trim trailing slashes -- fix for drive root
1824  $path = rtrim( $path, DIRECTORY_SEPARATOR );
1825  $from = rtrim( $from, DIRECTORY_SEPARATOR );
1826 
1827  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1828  $against = explode( DIRECTORY_SEPARATOR, $from );
1829 
1830  if ( $pieces[0] !== $against[0] ) {
1831  // Non-matching Windows drive letters?
1832  // Return a full path.
1833  return $path;
1834  }
1835 
1836  // Trim off common prefix
1837  while ( count( $pieces ) && count( $against )
1838  && $pieces[0] == $against[0] ) {
1839  array_shift( $pieces );
1840  array_shift( $against );
1841  }
1842 
1843  // relative dots to bump us to the parent
1844  while ( count( $against ) ) {
1845  array_unshift( $pieces, '..' );
1846  array_shift( $against );
1847  }
1848 
1849  $pieces[] = wfBaseName( $path );
1850 
1851  return implode( DIRECTORY_SEPARATOR, $pieces );
1852 }
1853 
1885 function wfGetDB( $db, $groups = [], $wiki = false ) {
1886  if ( $wiki === false ) {
1887  return MediaWikiServices::getInstance()
1888  ->getDBLoadBalancer()
1889  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1890  } else {
1891  return MediaWikiServices::getInstance()
1892  ->getDBLoadBalancerFactory()
1893  ->getMainLB( $wiki )
1894  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1895  }
1896 }
1897 
1906 function wfScript( $script = 'index' ) {
1908  if ( $script === 'index' ) {
1909  return $wgScript;
1910  } elseif ( $script === 'load' ) {
1911  return $wgLoadScript;
1912  } else {
1913  return "{$wgScriptPath}/{$script}.php";
1914  }
1915 }
1916 
1924 function wfBoolToStr( $value ) {
1925  return $value ? 'true' : 'false';
1926 }
1927 
1933 function wfGetNull() {
1934  return wfIsWindows() ? 'NUL' : '/dev/null';
1935 }
1936 
1945 function wfStripIllegalFilenameChars( $name ) {
1946  global $wgIllegalFileChars;
1947  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1948  $name = preg_replace(
1949  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1950  '-',
1951  $name
1952  );
1953  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1954  $name = wfBaseName( $name );
1955  return $name;
1956 }
1957 
1964 function wfMemoryLimit( $newLimit ) {
1965  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1966  // If the INI config is already unlimited, there is nothing larger
1967  if ( $oldLimit != -1 ) {
1968  $newLimit = wfShorthandToInteger( (string)$newLimit );
1969  if ( $newLimit == -1 ) {
1970  wfDebug( "Removing PHP's memory limit" );
1971  AtEase::suppressWarnings();
1972  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1973  ini_set( 'memory_limit', $newLimit );
1974  AtEase::restoreWarnings();
1975  } elseif ( $newLimit > $oldLimit ) {
1976  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1977  AtEase::suppressWarnings();
1978  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1979  ini_set( 'memory_limit', $newLimit );
1980  AtEase::restoreWarnings();
1981  }
1982  }
1983 }
1984 
1993 
1994  $timeout = RequestTimeout::singleton();
1995  $timeLimit = $timeout->getWallTimeLimit();
1996  if ( $timeLimit !== INF ) {
1997  // RequestTimeout library is active
1998  if ( $wgTransactionalTimeLimit > $timeLimit ) {
1999  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2000  }
2001  } else {
2002  // Fallback case, likely $wgRequestTimeLimit === null
2003  $timeLimit = (int)ini_get( 'max_execution_time' );
2004  // Note that CLI scripts use 0
2005  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2006  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2007  }
2008  }
2009  ignore_user_abort( true ); // ignore client disconnects
2010 
2011  return $timeLimit;
2012 }
2013 
2021 function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2022  $string = trim( $string ?? '' );
2023  if ( $string === '' ) {
2024  return $default;
2025  }
2026  $last = $string[strlen( $string ) - 1];
2027  $val = intval( $string );
2028  switch ( $last ) {
2029  case 'g':
2030  case 'G':
2031  $val *= 1024;
2032  // break intentionally missing
2033  case 'm':
2034  case 'M':
2035  $val *= 1024;
2036  // break intentionally missing
2037  case 'k':
2038  case 'K':
2039  $val *= 1024;
2040  }
2041 
2042  return $val;
2043 }
2044 
2059 function wfUnpack( $format, $data, $length = false ) {
2060  if ( $length !== false ) {
2061  $realLen = strlen( $data );
2062  if ( $realLen < $length ) {
2063  throw new MWException( "Tried to use wfUnpack on a "
2064  . "string of length $realLen, but needed one "
2065  . "of at least length $length."
2066  );
2067  }
2068  }
2069 
2070  AtEase::suppressWarnings();
2071  $result = unpack( $format, $data );
2072  AtEase::restoreWarnings();
2073 
2074  if ( $result === false ) {
2075  // If it cannot extract the packed data.
2076  throw new MWException( "unpack could not unpack binary data" );
2077  }
2078  return $result;
2079 }
2080 
2088 function wfIsInfinity( $str ) {
2089  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2090  return in_array( $str, ExpiryDef::INFINITY_VALS );
2091 }
2092 
2107 function wfThumbIsStandard( File $file, array $params ) {
2109 
2110  $multipliers = [ 1 ];
2111  if ( $wgResponsiveImages ) {
2112  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2113  // @see Linker::processResponsiveImages
2114  $multipliers[] = 1.5;
2115  $multipliers[] = 2;
2116  }
2117 
2118  $handler = $file->getHandler();
2119  if ( !$handler || !isset( $params['width'] ) ) {
2120  return false;
2121  }
2122 
2123  $basicParams = [];
2124  if ( isset( $params['page'] ) ) {
2125  $basicParams['page'] = $params['page'];
2126  }
2127 
2128  $thumbLimits = [];
2129  $imageLimits = [];
2130  // Expand limits to account for multipliers
2131  foreach ( $multipliers as $multiplier ) {
2132  $thumbLimits = array_merge( $thumbLimits, array_map(
2133  static function ( $width ) use ( $multiplier ) {
2134  return round( $width * $multiplier );
2135  }, $wgThumbLimits )
2136  );
2137  $imageLimits = array_merge( $imageLimits, array_map(
2138  static function ( $pair ) use ( $multiplier ) {
2139  return [
2140  round( $pair[0] * $multiplier ),
2141  round( $pair[1] * $multiplier ),
2142  ];
2143  }, $wgImageLimits )
2144  );
2145  }
2146 
2147  // Check if the width matches one of $wgThumbLimits
2148  if ( in_array( $params['width'], $thumbLimits ) ) {
2149  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2150  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2151  $handler->normaliseParams( $file, $normalParams );
2152  } else {
2153  // If not, then check if the width matches one of $wgImageLimits
2154  $match = false;
2155  foreach ( $imageLimits as $pair ) {
2156  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2157  // Decide whether the thumbnail should be scaled on width or height.
2158  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2159  $handler->normaliseParams( $file, $normalParams );
2160  // Check if this standard thumbnail size maps to the given width
2161  if ( $normalParams['width'] == $params['width'] ) {
2162  $match = true;
2163  break;
2164  }
2165  }
2166  if ( !$match ) {
2167  return false; // not standard for description pages
2168  }
2169  }
2170 
2171  // Check that the given values for non-page, non-width, params are just defaults
2172  foreach ( $params as $key => $value ) {
2173  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2174  return false;
2175  }
2176  }
2177 
2178  return true;
2179 }
2180 
2193 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2194  // First merge items that are in both arrays
2195  foreach ( $baseArray as $name => &$groupVal ) {
2196  if ( isset( $newValues[$name] ) ) {
2197  $groupVal += $newValues[$name];
2198  }
2199  }
2200  // Now add items that didn't exist yet
2201  $baseArray += $newValues;
2202 
2203  return $baseArray;
2204 }
wfIsWindows()
Check if the operating system is Windows.
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()
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
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 using $wgServer (or one of its alternatives).
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...
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...
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.
$matches
global $wgRequest
Definition: Setup.php:409
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgOut
Definition: Setup.php:529
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:529
const MW_ENTRY_POINT
Definition: api.php:44
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:68
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:184
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition: MWDebug.php:225
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: MWDebug.php:307
MediaWiki exception.
Definition: MWException.php:32
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:566
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.
Represents a title within MediaWiki.
Definition: Title.php:82
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:460
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:426
static getUsableTempDirectory()
Definition: TempFSFile.php:87
static detectProtocol()
Detect the protocol from $_SERVER.
Definition: WebRequest.php:315
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
$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