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 
33 use Wikimedia\AtEase\AtEase;
35 use Wikimedia\RequestTimeout\RequestTimeout;
36 use Wikimedia\WrappedString;
37 
48 function wfLoadExtension( $ext, $path = null ) {
49  if ( !$path ) {
50  global $wgExtensionDirectory;
51  $path = "$wgExtensionDirectory/$ext/extension.json";
52  }
54 }
55 
69 function wfLoadExtensions( array $exts ) {
70  global $wgExtensionDirectory;
71  $registry = ExtensionRegistry::getInstance();
72  foreach ( $exts as $ext ) {
73  $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
74  }
75 }
76 
85 function wfLoadSkin( $skin, $path = null ) {
86  if ( !$path ) {
87  global $wgStyleDirectory;
88  $path = "$wgStyleDirectory/$skin/skin.json";
89  }
91 }
92 
100 function wfLoadSkins( array $skins ) {
101  global $wgStyleDirectory;
102  $registry = ExtensionRegistry::getInstance();
103  foreach ( $skins as $skin ) {
104  $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
105  }
106 }
107 
114 function wfArrayDiff2( $arr1, $arr2 ) {
119  $comparator = static function ( $a, $b ): int {
120  if ( is_string( $a ) && is_string( $b ) ) {
121  return strcmp( $a, $b );
122  }
123  if ( !is_array( $a ) && !is_array( $b ) ) {
124  throw new InvalidArgumentException(
125  'This function assumes that array elements are all strings or all arrays'
126  );
127  }
128  if ( count( $a ) !== count( $b ) ) {
129  return count( $a ) <=> count( $b );
130  } else {
131  reset( $a );
132  reset( $b );
133  while ( key( $a ) !== null && key( $b ) !== null ) {
134  $valueA = current( $a );
135  $valueB = current( $b );
136  $cmp = strcmp( $valueA, $valueB );
137  if ( $cmp !== 0 ) {
138  return $cmp;
139  }
140  next( $a );
141  next( $b );
142  }
143  return 0;
144  }
145  };
146  return array_udiff( $arr1, $arr2, $comparator );
147 }
148 
168 function wfMergeErrorArrays( ...$args ) {
169  $out = [];
170  foreach ( $args as $errors ) {
171  foreach ( $errors as $params ) {
172  $originalParams = $params;
173  if ( $params[0] instanceof MessageSpecifier ) {
174  $msg = $params[0];
175  $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
176  }
177  # @todo FIXME: Sometimes get nested arrays for $params,
178  # which leads to E_NOTICEs
179  $spec = implode( "\t", $params );
180  $out[$spec] = $originalParams;
181  }
182  }
183  return array_values( $out );
184 }
185 
195 function wfArrayInsertAfter( array $array, array $insert, $after ) {
196  // Find the offset of the element to insert after.
197  $keys = array_keys( $array );
198  $offsetByKey = array_flip( $keys );
199 
200  if ( !\array_key_exists( $after, $offsetByKey ) ) {
201  return $array;
202  }
203  $offset = $offsetByKey[$after];
204 
205  // Insert at the specified offset
206  $before = array_slice( $array, 0, $offset + 1, true );
207  $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
208 
209  $output = $before + $insert + $after;
210 
211  return $output;
212 }
213 
222 function wfObjectToArray( $objOrArray, $recursive = true ) {
223  $array = [];
224  if ( is_object( $objOrArray ) ) {
225  $objOrArray = get_object_vars( $objOrArray );
226  }
227  foreach ( $objOrArray as $key => $value ) {
228  if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
229  $value = wfObjectToArray( $value );
230  }
231 
232  $array[$key] = $value;
233  }
234 
235  return $array;
236 }
237 
248 function wfRandom() {
249  // The maximum random value is "only" 2^31-1, so get two random
250  // values to reduce the chance of dupes
251  $max = mt_getrandmax() + 1;
252  $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
253  return $rand;
254 }
255 
266 function wfRandomString( $length = 32 ) {
267  $str = '';
268  for ( $n = 0; $n < $length; $n += 7 ) {
269  $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
270  }
271  return substr( $str, 0, $length );
272 }
273 
301 function wfUrlencode( $s ) {
302  static $needle;
303 
304  if ( $s === null ) {
305  // Reset $needle for testing.
306  $needle = null;
307  return '';
308  }
309 
310  if ( $needle === null ) {
311  $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
312  if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
313  ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
314  ) {
315  $needle[] = '%3A';
316  }
317  }
318 
319  $s = urlencode( $s );
320  $s = str_ireplace(
321  $needle,
322  [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
323  $s
324  );
325 
326  return $s;
327 }
328 
339 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
340  if ( $array2 !== null ) {
341  $array1 += $array2;
342  }
343 
344  $cgi = '';
345  foreach ( $array1 as $key => $value ) {
346  if ( $value !== null && $value !== false ) {
347  if ( $cgi != '' ) {
348  $cgi .= '&';
349  }
350  if ( $prefix !== '' ) {
351  $key = $prefix . "[$key]";
352  }
353  if ( is_array( $value ) ) {
354  $firstTime = true;
355  foreach ( $value as $k => $v ) {
356  $cgi .= $firstTime ? '' : '&';
357  if ( is_array( $v ) ) {
358  $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
359  } else {
360  $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
361  }
362  $firstTime = false;
363  }
364  } else {
365  if ( is_object( $value ) ) {
366  $value = $value->__toString();
367  }
368  $cgi .= urlencode( $key ) . '=' . urlencode( $value );
369  }
370  }
371  }
372  return $cgi;
373 }
374 
384 function wfCgiToArray( $query ) {
385  if ( isset( $query[0] ) && $query[0] == '?' ) {
386  $query = substr( $query, 1 );
387  }
388  $bits = explode( '&', $query );
389  $ret = [];
390  foreach ( $bits as $bit ) {
391  if ( $bit === '' ) {
392  continue;
393  }
394  if ( strpos( $bit, '=' ) === false ) {
395  // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
396  $key = $bit;
397  $value = '';
398  } else {
399  list( $key, $value ) = explode( '=', $bit );
400  }
401  $key = urldecode( $key );
402  $value = urldecode( $value );
403  if ( strpos( $key, '[' ) !== false ) {
404  $keys = array_reverse( explode( '[', $key ) );
405  $key = array_pop( $keys );
406  $temp = $value;
407  foreach ( $keys as $k ) {
408  $k = substr( $k, 0, -1 );
409  $temp = [ $k => $temp ];
410  }
411  if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
412  $ret[$key] = array_merge( $ret[$key], $temp );
413  } else {
414  $ret[$key] = $temp;
415  }
416  } else {
417  $ret[$key] = $value;
418  }
419  }
420  return $ret;
421 }
422 
431 function wfAppendQuery( $url, $query ) {
432  if ( is_array( $query ) ) {
433  $query = wfArrayToCgi( $query );
434  }
435  if ( $query != '' ) {
436  // Remove the fragment, if there is one
437  $fragment = false;
438  $hashPos = strpos( $url, '#' );
439  if ( $hashPos !== false ) {
440  $fragment = substr( $url, $hashPos );
441  $url = substr( $url, 0, $hashPos );
442  }
443 
444  // Add parameter
445  if ( strpos( $url, '?' ) === false ) {
446  $url .= '?';
447  } else {
448  $url .= '&';
449  }
450  $url .= $query;
451 
452  // Put the fragment back
453  if ( $fragment !== false ) {
454  $url .= $fragment;
455  }
456  }
457  return $url;
458 }
459 
465 function wfGetUrlUtils(): UrlUtils {
468 
469  if ( MediaWikiServices::hasInstance() ) {
470  $services = MediaWikiServices::getInstance();
471  if ( $services->hasService( 'UrlUtils' ) ) {
472  return $services->getUrlUtils();
473  }
474  }
475 
476  return new UrlUtils( [
477  // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
478  // implementations implicitly converted it to an empty string (presumably by mistake).
479  // Preserve the old behavior for compatibility.
480  UrlUtils::SERVER => $wgServer ?? '',
481  UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
482  UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
483  UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
485  UrlUtils::HTTPS_PORT => $wgHttpsPort,
486  UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
487  ] );
488 }
489 
511 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
512  return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
513 }
514 
524 function wfGetServerUrl( $proto ) {
525  return wfGetUrlUtils()->getServer( $proto ) ?? '';
526 }
527 
540 function wfAssembleUrl( $urlParts ) {
541  return wfGetUrlUtils()->assemble( (array)$urlParts );
542 }
543 
555 function wfRemoveDotSegments( $urlPath ) {
556  return wfGetUrlUtils()->removeDotSegments( (string)$urlPath );
557 }
558 
567 function wfUrlProtocols( $includeProtocolRelative = true ) {
568  $method = $includeProtocolRelative ? 'validProtocols' : 'validAbsoluteProtocols';
569  return wfGetUrlUtils()->$method();
570 }
571 
580  return wfGetUrlUtils()->validAbsoluteProtocols();
581 }
582 
609 function wfParseUrl( $url ) {
610  return wfGetUrlUtils()->parse( (string)$url ) ?? false;
611 }
612 
622 function wfExpandIRI( $url ) {
623  return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
624 }
625 
634 function wfMatchesDomainList( $url, $domains ) {
635  return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
636 }
637 
658 function wfDebug( $text, $dest = 'all', array $context = [] ) {
660 
661  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
662  return;
663  }
664 
665  $text = trim( $text );
666 
667  if ( $wgDebugLogPrefix !== '' ) {
668  $context['prefix'] = $wgDebugLogPrefix;
669  }
670  $context['private'] = ( $dest === false || $dest === 'private' );
671 
672  $logger = LoggerFactory::getInstance( 'wfDebug' );
673  $logger->debug( $text, $context );
674 }
675 
680 function wfIsDebugRawPage() {
681  static $cache;
682  if ( $cache !== null ) {
683  return $cache;
684  }
685  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
686  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
687  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
688  || MW_ENTRY_POINT === 'load'
689  ) {
690  $cache = true;
691  } else {
692  $cache = false;
693  }
694  return $cache;
695 }
696 
722 function wfDebugLog(
723  $logGroup, $text, $dest = 'all', array $context = []
724 ) {
725  $text = trim( $text );
726 
727  $logger = LoggerFactory::getInstance( $logGroup );
728  $context['private'] = ( $dest === false || $dest === 'private' );
729  $logger->info( $text, $context );
730 }
731 
740 function wfLogDBError( $text, array $context = [] ) {
741  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
742  $logger->error( trim( $text ), $context );
743 }
744 
761 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
762  if ( !is_string( $version ) && $version !== false ) {
763  throw new InvalidArgumentException(
764  "MediaWiki version must either be a string or false. " .
765  "Example valid version: '1.33'"
766  );
767  }
768 
769  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
770 }
771 
792 function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
793  MWDebug::deprecatedMsg( $msg, $version, $component,
794  $callerOffset === false ? false : $callerOffset + 1 );
795 }
796 
807 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
808  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
809 }
810 
820 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
821  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
822 }
823 
827 function wfLogProfilingData() {
828  wfDeprecated( __FUNCTION__, '1.38' );
829  $profiler = Profiler::instance();
830  $profiler->logData();
831 
832  // Send out any buffered statsd metrics as needed
834  MediaWikiServices::getInstance()->getStatsdDataFactory(),
835  MediaWikiServices::getInstance()->getMainConfig()
836  );
837 }
838 
846 function wfReadOnly() {
847  return MediaWikiServices::getInstance()->getReadOnlyMode()
848  ->isReadOnly();
849 }
850 
861 function wfReadOnlyReason() {
862  return MediaWikiServices::getInstance()->getReadOnlyMode()
863  ->getReason();
864 }
865 
881 function wfGetLangObj( $langcode = false ) {
882  # Identify which language to get or create a language object for.
883  # Using is_object here due to Stub objects.
884  if ( is_object( $langcode ) ) {
885  # Great, we already have the object (hopefully)!
886  return $langcode;
887  }
888 
889  global $wgLanguageCode;
890  $services = MediaWikiServices::getInstance();
891  if ( $langcode === true || $langcode === $wgLanguageCode ) {
892  # $langcode is the language code of the wikis content language object.
893  # or it is a boolean and value is true
894  return $services->getContentLanguage();
895  }
896 
897  global $wgLang;
898  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
899  # $langcode is the language code of user language object.
900  # or it was a boolean and value is false
901  return $wgLang;
902  }
903 
904  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
905  if ( in_array( $langcode, $validCodes ) ) {
906  # $langcode corresponds to a valid language.
907  return $services->getLanguageFactory()->getLanguage( $langcode );
908  }
909 
910  # $langcode is a string, but not a valid language code; use content language.
911  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
912  return $services->getContentLanguage();
913 }
914 
936 function wfMessage( $key, ...$params ) {
937  if ( is_array( $key ) ) {
938  // Fallback keys are not allowed in message specifiers
939  $message = wfMessageFallback( ...$key );
940  } else {
941  $message = Message::newFromSpecifier( $key );
942  }
943 
944  // We call Message::params() to reduce code duplication
945  if ( $params ) {
946  $message->params( ...$params );
947  }
948 
949  return $message;
950 }
951 
964 function wfMessageFallback( ...$keys ) {
965  return Message::newFallbackSequence( ...$keys );
966 }
967 
976 function wfMsgReplaceArgs( $message, $args ) {
977  # Fix windows line-endings
978  # Some messages are split with explode("\n", $msg)
979  $message = str_replace( "\r", '', $message );
980 
981  // Replace arguments
982  if ( is_array( $args ) && $args ) {
983  if ( is_array( $args[0] ) ) {
984  $args = array_values( $args[0] );
985  }
986  $replacementKeys = [];
987  foreach ( $args as $n => $param ) {
988  $replacementKeys['$' . ( $n + 1 )] = $param;
989  }
990  $message = strtr( $message, $replacementKeys );
991  }
992 
993  return $message;
994 }
995 
1004 function wfHostname() {
1005  // Hostname overriding
1006  global $wgOverrideHostname;
1007  if ( $wgOverrideHostname !== false ) {
1008  return $wgOverrideHostname;
1009  }
1010 
1011  return php_uname( 'n' ) ?: 'unknown';
1012 }
1013 
1024 function wfReportTime( $nonce = null ) {
1025  global $wgShowHostnames;
1026 
1027  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1028  // seconds to milliseconds
1029  $responseTime = round( $elapsed * 1000 );
1030  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1031  if ( $wgShowHostnames ) {
1032  $reportVars['wgHostname'] = wfHostname();
1033  }
1034 
1035  return (
1037  ResourceLoader::makeConfigSetScript( $reportVars ),
1038  $nonce
1039  )
1040  );
1041 }
1042 
1053 function wfDebugBacktrace( $limit = 0 ) {
1054  static $disabled = null;
1055 
1056  if ( $disabled === null ) {
1057  $disabled = !function_exists( 'debug_backtrace' );
1058  if ( $disabled ) {
1059  wfDebug( "debug_backtrace() is disabled" );
1060  }
1061  }
1062  if ( $disabled ) {
1063  return [];
1064  }
1065 
1066  if ( $limit ) {
1067  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1068  } else {
1069  return array_slice( debug_backtrace(), 1 );
1070  }
1071 }
1072 
1081 function wfBacktrace( $raw = null ) {
1082  global $wgCommandLineMode;
1083 
1084  if ( $raw === null ) {
1085  $raw = $wgCommandLineMode;
1086  }
1087 
1088  if ( $raw ) {
1089  $frameFormat = "%s line %s calls %s()\n";
1090  $traceFormat = "%s";
1091  } else {
1092  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1093  $traceFormat = "<ul>\n%s</ul>\n";
1094  }
1095 
1096  $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1097  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1098  $line = $frame['line'] ?? '-';
1099  $call = $frame['function'];
1100  if ( !empty( $frame['class'] ) ) {
1101  $call = $frame['class'] . $frame['type'] . $call;
1102  }
1103  return sprintf( $frameFormat, $file, $line, $call );
1104  }, wfDebugBacktrace() );
1105 
1106  return sprintf( $traceFormat, implode( '', $frames ) );
1107 }
1108 
1118 function wfGetCaller( $level = 2 ) {
1119  $backtrace = wfDebugBacktrace( $level + 1 );
1120  if ( isset( $backtrace[$level] ) ) {
1121  return wfFormatStackFrame( $backtrace[$level] );
1122  } else {
1123  return 'unknown';
1124  }
1125 }
1126 
1134 function wfGetAllCallers( $limit = 3 ) {
1135  $trace = array_reverse( wfDebugBacktrace() );
1136  if ( !$limit || $limit > count( $trace ) - 1 ) {
1137  $limit = count( $trace ) - 1;
1138  }
1139  $trace = array_slice( $trace, -$limit - 1, $limit );
1140  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1141 }
1142 
1149 function wfFormatStackFrame( $frame ) {
1150  if ( !isset( $frame['function'] ) ) {
1151  return 'NO_FUNCTION_GIVEN';
1152  }
1153  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1154  $frame['class'] . $frame['type'] . $frame['function'] :
1155  $frame['function'];
1156 }
1157 
1158 /* Some generic result counters, pulled out of SearchEngine */
1159 
1167 function wfShowingResults( $offset, $limit ) {
1168  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1169 }
1170 
1180 function wfClientAcceptsGzip( $force = false ) {
1181  static $result = null;
1182  if ( $result === null || $force ) {
1183  $result = false;
1184  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1185  # @todo FIXME: We may want to disallow some broken browsers
1186  $m = [];
1187  if ( preg_match(
1188  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1189  $_SERVER['HTTP_ACCEPT_ENCODING'],
1190  $m
1191  )
1192  ) {
1193  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1194  return $result;
1195  }
1196  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1197  $result = true;
1198  }
1199  }
1200  }
1201  return $result;
1202 }
1203 
1214 function wfEscapeWikiText( $text ) {
1215  global $wgEnableMagicLinks;
1216  static $repl = null, $repl2 = null;
1217  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1218  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1219  // in those situations
1220  $repl = [
1221  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1222  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1223  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1224  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1225  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1226  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1227  "\n " => "\n&#32;", "\r " => "\r&#32;",
1228  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1229  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1230  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1231  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1232  '__' => '_&#95;', '://' => '&#58;//',
1233  ];
1234 
1235  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1236  // We have to catch everything "\s" matches in PCRE
1237  foreach ( $magicLinks as $magic ) {
1238  $repl["$magic "] = "$magic&#32;";
1239  $repl["$magic\t"] = "$magic&#9;";
1240  $repl["$magic\r"] = "$magic&#13;";
1241  $repl["$magic\n"] = "$magic&#10;";
1242  $repl["$magic\f"] = "$magic&#12;";
1243  }
1244 
1245  // And handle protocols that don't use "://"
1246  global $wgUrlProtocols;
1247  $repl2 = [];
1248  foreach ( $wgUrlProtocols as $prot ) {
1249  if ( substr( $prot, -1 ) === ':' ) {
1250  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1251  }
1252  }
1253  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1254  }
1255  $text = substr( strtr( "\n$text", $repl ), 1 );
1256  // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
1257  $text = preg_replace( $repl2, '$1&#58;', $text );
1258  return $text;
1259 }
1260 
1271 function wfSetVar( &$dest, $source, $force = false ) {
1272  $temp = $dest;
1273  if ( $source !== null || $force ) {
1274  $dest = $source;
1275  }
1276  return $temp;
1277 }
1278 
1288 function wfSetBit( &$dest, $bit, $state = true ) {
1289  $temp = (bool)( $dest & $bit );
1290  if ( $state !== null ) {
1291  if ( $state ) {
1292  $dest |= $bit;
1293  } else {
1294  $dest &= ~$bit;
1295  }
1296  }
1297  return $temp;
1298 }
1299 
1306 function wfVarDump( $var ) {
1307  global $wgOut;
1308  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1309  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1310  print $s;
1311  } else {
1312  $wgOut->addHTML( $s );
1313  }
1314 }
1315 
1323 function wfHttpError( $code, $label, $desc ) {
1324  global $wgOut;
1325  HttpStatus::header( $code );
1326  if ( $wgOut ) {
1327  $wgOut->disable();
1328  $wgOut->sendCacheControl();
1329  }
1330 
1332  header( 'Content-type: text/html; charset=utf-8' );
1333  ob_start();
1334  print '<!DOCTYPE html>' .
1335  '<html><head><title>' .
1336  htmlspecialchars( $label ) .
1337  '</title></head><body><h1>' .
1338  htmlspecialchars( $label ) .
1339  '</h1><p>' .
1340  nl2br( htmlspecialchars( $desc ) ) .
1341  "</p></body></html>\n";
1342  header( 'Content-Length: ' . ob_get_length() );
1343  ob_end_flush();
1344 }
1345 
1363 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1364  while ( $status = ob_get_status() ) {
1365  if ( isset( $status['flags'] ) ) {
1366  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1367  $deleteable = ( $status['flags'] & $flags ) === $flags;
1368  } elseif ( isset( $status['del'] ) ) {
1369  $deleteable = $status['del'];
1370  } else {
1371  // Guess that any PHP-internal setting can't be removed.
1372  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1373  }
1374  if ( !$deleteable ) {
1375  // Give up, and hope the result doesn't break
1376  // output behavior.
1377  break;
1378  }
1379  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1380  // Unit testing barrier to prevent this function from breaking PHPUnit.
1381  break;
1382  }
1383  if ( !ob_end_clean() ) {
1384  // Could not remove output buffer handler; abort now
1385  // to avoid getting in some kind of infinite loop.
1386  break;
1387  }
1388  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1389  // Reset the 'Content-Encoding' field set by this handler
1390  // so we can start fresh.
1391  header_remove( 'Content-Encoding' );
1392  break;
1393  }
1394  }
1395 }
1396 
1412  wfDeprecated( __FUNCTION__, '1.36' );
1413  wfResetOutputBuffers( false );
1414 }
1415 
1424 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1425  $ret = MWTimestamp::convert( $outputtype, $ts );
1426  if ( $ret === false ) {
1427  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1428  }
1429  return $ret;
1430 }
1431 
1440 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1441  if ( $ts === null ) {
1442  return null;
1443  } else {
1444  return wfTimestamp( $outputtype, $ts );
1445  }
1446 }
1447 
1453 function wfTimestampNow() {
1454  return MWTimestamp::now( TS_MW );
1455 }
1456 
1462 function wfIsWindows() {
1463  return PHP_OS_FAMILY === 'Windows';
1464 }
1465 
1472 function wfIsCLI() {
1473  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1474 }
1475 
1487 function wfTempDir() {
1488  global $wgTmpDirectory;
1489 
1490  if ( $wgTmpDirectory !== false ) {
1491  return $wgTmpDirectory;
1492  }
1493 
1495 }
1496 
1506 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1507  global $wgDirectoryMode;
1508 
1509  if ( FileBackend::isStoragePath( $dir ) ) {
1510  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1511  }
1512 
1513  if ( $caller !== null ) {
1514  wfDebug( "$caller: called wfMkdirParents($dir)" );
1515  }
1516 
1517  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1518  return true;
1519  }
1520 
1521  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1522 
1523  if ( $mode === null ) {
1524  $mode = $wgDirectoryMode;
1525  }
1526 
1527  // Turn off the normal warning, we're doing our own below
1528  AtEase::suppressWarnings();
1529  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1530  AtEase::restoreWarnings();
1531 
1532  if ( !$ok ) {
1533  // directory may have been created on another request since we last checked
1534  if ( is_dir( $dir ) ) {
1535  return true;
1536  }
1537 
1538  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1539  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1540  }
1541  return $ok;
1542 }
1543 
1549 function wfRecursiveRemoveDir( $dir ) {
1550  wfDebug( __FUNCTION__ . "( $dir )" );
1551  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1552  if ( is_dir( $dir ) ) {
1553  $objects = scandir( $dir );
1554  foreach ( $objects as $object ) {
1555  if ( $object != "." && $object != ".." ) {
1556  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1557  wfRecursiveRemoveDir( $dir . '/' . $object );
1558  } else {
1559  unlink( $dir . '/' . $object );
1560  }
1561  }
1562  }
1563  reset( $objects );
1564  rmdir( $dir );
1565  }
1566 }
1567 
1574 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1575  $accForFormat = $acc >= 0 ? $acc : 0;
1576  $ret = sprintf( "%.${accForFormat}f", $nr );
1577  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1578 }
1579 
1603 function wfIniGetBool( $setting ) {
1604  return wfStringToBool( ini_get( $setting ) );
1605 }
1606 
1619 function wfStringToBool( $val ) {
1620  $val = strtolower( $val );
1621  // 'on' and 'true' can't have whitespace around them, but '1' can.
1622  return $val == 'on'
1623  || $val == 'true'
1624  || $val == 'yes'
1625  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1626 }
1627 
1641 function wfEscapeShellArg( ...$args ) {
1642  return Shell::escape( ...$args );
1643 }
1644 
1669 function wfShellExec( $cmd, &$retval = null, $environ = [],
1670  $limits = [], $options = []
1671 ) {
1672  if ( Shell::isDisabled() ) {
1673  $retval = 1;
1674  // Backwards compatibility be upon us...
1675  return 'Unable to run external programs, proc_open() is disabled.';
1676  }
1677 
1678  if ( is_array( $cmd ) ) {
1679  $cmd = Shell::escape( $cmd );
1680  }
1681 
1682  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1683  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1684 
1685  try {
1686  $result = Shell::command( [] )
1687  ->unsafeParams( (array)$cmd )
1688  ->environment( $environ )
1689  ->limits( $limits )
1690  ->includeStderr( $includeStderr )
1691  ->profileMethod( $profileMethod )
1692  // For b/c
1693  ->restrict( Shell::RESTRICT_NONE )
1694  ->execute();
1695  } catch ( ProcOpenError $ex ) {
1696  $retval = -1;
1697  return '';
1698  }
1699 
1700  $retval = $result->getExitCode();
1701 
1702  return $result->getStdout();
1703 }
1704 
1722 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1723  return wfShellExec( $cmd, $retval, $environ, $limits,
1724  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1725 }
1726 
1742 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1743  global $wgPhpCli;
1744  // Give site config file a chance to run the script in a wrapper.
1745  // The caller may likely want to call wfBasename() on $script.
1746  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1747  $cmd = [ $options['php'] ?? $wgPhpCli ];
1748  if ( isset( $options['wrapper'] ) ) {
1749  $cmd[] = $options['wrapper'];
1750  }
1751  $cmd[] = $script;
1752  // Escape each parameter for shell
1753  return Shell::escape( array_merge( $cmd, $parameters ) );
1754 }
1755 
1767 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
1768  global $wgDiff3;
1769 
1770  # This check may also protect against code injection in
1771  # case of broken installations.
1772  AtEase::suppressWarnings();
1773  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1774  AtEase::restoreWarnings();
1775 
1776  if ( !$haveDiff3 ) {
1777  wfDebug( "diff3 not found" );
1778  return false;
1779  }
1780 
1781  # Make temporary files
1782  $td = wfTempDir();
1783  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1784  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1785  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1786 
1787  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1788  # a newline character. To avoid this, we normalize the trailing whitespace before
1789  # creating the diff.
1790 
1791  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1792  fclose( $oldtextFile );
1793  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1794  fclose( $mytextFile );
1795  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1796  fclose( $yourtextFile );
1797 
1798  # Check for a conflict
1799  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
1800  $oldtextName, $yourtextName );
1801  $handle = popen( $cmd, 'r' );
1802 
1803  $mergeAttemptResult = '';
1804  do {
1805  $data = fread( $handle, 8192 );
1806  if ( strlen( $data ) == 0 ) {
1807  break;
1808  }
1809  $mergeAttemptResult .= $data;
1810  } while ( true );
1811  pclose( $handle );
1812 
1813  $conflict = $mergeAttemptResult !== '';
1814 
1815  # Merge differences
1816  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
1817  $oldtextName, $yourtextName );
1818  $handle = popen( $cmd, 'r' );
1819  $result = '';
1820  do {
1821  $data = fread( $handle, 8192 );
1822  if ( strlen( $data ) == 0 ) {
1823  break;
1824  }
1825  $result .= $data;
1826  } while ( true );
1827  pclose( $handle );
1828  unlink( $mytextName );
1829  unlink( $oldtextName );
1830  unlink( $yourtextName );
1831 
1832  if ( $result === '' && $old !== '' && !$conflict ) {
1833  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1834  $conflict = true;
1835  }
1836  return !$conflict;
1837 }
1838 
1851 function wfBaseName( $path, $suffix = '' ) {
1852  if ( $suffix == '' ) {
1853  $encSuffix = '';
1854  } else {
1855  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1856  }
1857 
1858  $matches = [];
1859  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1860  return $matches[1];
1861  } else {
1862  return '';
1863  }
1864 }
1865 
1875 function wfRelativePath( $path, $from ) {
1876  // Normalize mixed input on Windows...
1877  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1878  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1879 
1880  // Trim trailing slashes -- fix for drive root
1881  $path = rtrim( $path, DIRECTORY_SEPARATOR );
1882  $from = rtrim( $from, DIRECTORY_SEPARATOR );
1883 
1884  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1885  $against = explode( DIRECTORY_SEPARATOR, $from );
1886 
1887  if ( $pieces[0] !== $against[0] ) {
1888  // Non-matching Windows drive letters?
1889  // Return a full path.
1890  return $path;
1891  }
1892 
1893  // Trim off common prefix
1894  while ( count( $pieces ) && count( $against )
1895  && $pieces[0] == $against[0] ) {
1896  array_shift( $pieces );
1897  array_shift( $against );
1898  }
1899 
1900  // relative dots to bump us to the parent
1901  while ( count( $against ) ) {
1902  array_unshift( $pieces, '..' );
1903  array_shift( $against );
1904  }
1905 
1906  $pieces[] = wfBaseName( $path );
1907 
1908  return implode( DIRECTORY_SEPARATOR, $pieces );
1909 }
1910 
1942 function wfGetDB( $db, $groups = [], $wiki = false ) {
1943  if ( $wiki === false ) {
1944  return MediaWikiServices::getInstance()
1945  ->getDBLoadBalancer()
1946  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1947  } else {
1948  return MediaWikiServices::getInstance()
1949  ->getDBLoadBalancerFactory()
1950  ->getMainLB( $wiki )
1951  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1952  }
1953 }
1954 
1962 function wfFindFile( $title, $options = [] ) {
1963  wfDeprecated( __FUNCTION__, '1.34' );
1964  return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
1965 }
1966 
1975 function wfLocalFile( $title ) {
1976  wfDeprecated( __FUNCTION__, '1.34' );
1977  return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
1978 }
1979 
1987  global $wgMiserMode;
1988  return $wgMiserMode
1989  || ( SiteStats::pages() > 100000
1990  && SiteStats::edits() > 1000000
1991  && SiteStats::users() > 10000 );
1992 }
1993 
2002 function wfScript( $script = 'index' ) {
2004  if ( $script === 'index' ) {
2005  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable False positive
2006  return $wgScript;
2007  } elseif ( $script === 'load' ) {
2008  return $wgLoadScript;
2009  } else {
2010  return "{$wgScriptPath}/{$script}.php";
2011  }
2012 }
2013 
2020 function wfGetScriptUrl() {
2021  wfDeprecated( __FUNCTION__, '1.35' );
2022  if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2023  /* as it was called, minus the query string.
2024  *
2025  * Some sites use Apache rewrite rules to handle subdomains,
2026  * and have PHP set up in a weird way that causes PHP_SELF
2027  * to contain the rewritten URL instead of the one that the
2028  * outside world sees.
2029  *
2030  * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2031  * provides containing the "before" URL.
2032  */
2033  return $_SERVER['SCRIPT_NAME'];
2034  } else {
2035  return $_SERVER['URL'];
2036  }
2037 }
2038 
2046 function wfBoolToStr( $value ) {
2047  return $value ? 'true' : 'false';
2048 }
2049 
2055 function wfGetNull() {
2056  return wfIsWindows() ? 'NUL' : '/dev/null';
2057 }
2058 
2067 function wfStripIllegalFilenameChars( $name ) {
2068  global $wgIllegalFileChars;
2069  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2070  $name = preg_replace(
2071  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2072  '-',
2073  $name
2074  );
2075  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2076  $name = wfBaseName( $name );
2077  return $name;
2078 }
2079 
2086 function wfMemoryLimit( $newLimit ) {
2087  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2088  // If the INI config is already unlimited, there is nothing larger
2089  if ( $oldLimit != -1 ) {
2090  $newLimit = wfShorthandToInteger( (string)$newLimit );
2091  if ( $newLimit == -1 ) {
2092  wfDebug( "Removing PHP's memory limit" );
2093  AtEase::suppressWarnings();
2094  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
2095  ini_set( 'memory_limit', $newLimit );
2096  AtEase::restoreWarnings();
2097  } elseif ( $newLimit > $oldLimit ) {
2098  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2099  AtEase::suppressWarnings();
2100  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
2101  ini_set( 'memory_limit', $newLimit );
2102  AtEase::restoreWarnings();
2103  }
2104  }
2105 }
2106 
2115 
2116  $timeout = RequestTimeout::singleton();
2117  $timeLimit = $timeout->getWallTimeLimit();
2118  if ( $timeLimit !== INF ) {
2119  // RequestTimeout library is active
2120  if ( $wgTransactionalTimeLimit > $timeLimit ) {
2121  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2122  }
2123  } else {
2124  // Fallback case, likely $wgRequestTimeLimit === null
2125  $timeLimit = (int)ini_get( 'max_execution_time' );
2126  // Note that CLI scripts use 0
2127  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2128  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2129  }
2130  }
2131  ignore_user_abort( true ); // ignore client disconnects
2132 
2133  return $timeLimit;
2134 }
2135 
2143 function wfShorthandToInteger( $string = '', $default = -1 ) {
2144  $string = trim( $string );
2145  if ( $string === '' ) {
2146  return $default;
2147  }
2148  $last = $string[strlen( $string ) - 1];
2149  $val = intval( $string );
2150  switch ( $last ) {
2151  case 'g':
2152  case 'G':
2153  $val *= 1024;
2154  // break intentionally missing
2155  case 'm':
2156  case 'M':
2157  $val *= 1024;
2158  // break intentionally missing
2159  case 'k':
2160  case 'K':
2161  $val *= 1024;
2162  }
2163 
2164  return $val;
2165 }
2166 
2181 function wfUnpack( $format, $data, $length = false ) {
2182  if ( $length !== false ) {
2183  $realLen = strlen( $data );
2184  if ( $realLen < $length ) {
2185  throw new MWException( "Tried to use wfUnpack on a "
2186  . "string of length $realLen, but needed one "
2187  . "of at least length $length."
2188  );
2189  }
2190  }
2191 
2192  AtEase::suppressWarnings();
2193  $result = unpack( $format, $data );
2194  AtEase::restoreWarnings();
2195 
2196  if ( $result === false ) {
2197  // If it cannot extract the packed data.
2198  throw new MWException( "unpack could not unpack binary data" );
2199  }
2200  return $result;
2201 }
2202 
2212 function wfCanIPUseHTTPS( $ip ) {
2213  wfDeprecated( __FUNCTION__, '1.37' );
2214  return true;
2215 }
2216 
2224 function wfIsInfinity( $str ) {
2225  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2226  return in_array( $str, ExpiryDef::INFINITY_VALS );
2227 }
2228 
2243 function wfThumbIsStandard( File $file, array $params ) {
2245 
2246  $multipliers = [ 1 ];
2247  if ( $wgResponsiveImages ) {
2248  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2249  // @see Linker::processResponsiveImages
2250  $multipliers[] = 1.5;
2251  $multipliers[] = 2;
2252  }
2253 
2254  $handler = $file->getHandler();
2255  if ( !$handler || !isset( $params['width'] ) ) {
2256  return false;
2257  }
2258 
2259  $basicParams = [];
2260  if ( isset( $params['page'] ) ) {
2261  $basicParams['page'] = $params['page'];
2262  }
2263 
2264  $thumbLimits = [];
2265  $imageLimits = [];
2266  // Expand limits to account for multipliers
2267  foreach ( $multipliers as $multiplier ) {
2268  $thumbLimits = array_merge( $thumbLimits, array_map(
2269  static function ( $width ) use ( $multiplier ) {
2270  return round( $width * $multiplier );
2271  }, $wgThumbLimits )
2272  );
2273  $imageLimits = array_merge( $imageLimits, array_map(
2274  static function ( $pair ) use ( $multiplier ) {
2275  return [
2276  round( $pair[0] * $multiplier ),
2277  round( $pair[1] * $multiplier ),
2278  ];
2279  }, $wgImageLimits )
2280  );
2281  }
2282 
2283  // Check if the width matches one of $wgThumbLimits
2284  if ( in_array( $params['width'], $thumbLimits ) ) {
2285  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2286  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2287  $handler->normaliseParams( $file, $normalParams );
2288  } else {
2289  // If not, then check if the width matches one of $wgImageLimits
2290  $match = false;
2291  foreach ( $imageLimits as $pair ) {
2292  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2293  // Decide whether the thumbnail should be scaled on width or height.
2294  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2295  $handler->normaliseParams( $file, $normalParams );
2296  // Check if this standard thumbnail size maps to the given width
2297  if ( $normalParams['width'] == $params['width'] ) {
2298  $match = true;
2299  break;
2300  }
2301  }
2302  if ( !$match ) {
2303  return false; // not standard for description pages
2304  }
2305  }
2306 
2307  // Check that the given values for non-page, non-width, params are just defaults
2308  foreach ( $params as $key => $value ) {
2309  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2310  return false;
2311  }
2312  }
2313 
2314  return true;
2315 }
2316 
2329 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2330  // First merge items that are in both arrays
2331  foreach ( $baseArray as $name => &$groupVal ) {
2332  if ( isset( $newValues[$name] ) ) {
2333  $groupVal += $newValues[$name];
2334  }
2335  }
2336  // Now add items that didn't exist yet
2337  $baseArray += $newValues;
2338 
2339  return $baseArray;
2340 }
const PROTO_CURRENT
Definition: Defines.php:197
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).
wfReadOnly()
Check whether the wiki is in read-only mode.
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.
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...
wfLocalFile( $title)
Get an object referring to a locally registered file.
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)
wfFindFile( $title, $options=[])
Find a file.
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.
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
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...
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
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.
wfGetScriptUrl()
Get the script URL.
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.
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
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.
wfQueriesMustScale()
Should low-performance queries be disabled?
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,...
wfLogProfilingData()
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:365
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgOut
Definition: Setup.php:485
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:485
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:68
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:182
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition: MWDebug.php:223
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: MWDebug.php:305
MediaWiki exception.
Definition: MWException.php:31
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Executes shell commands.
Definition: Shell.php:46
A service to expand, parse, and otherwise manipulate URLs.
Definition: UrlUtils.php:17
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1172
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:457
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:423
static instance()
Singleton.
Definition: Profiler.php:69
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
static edits()
Definition: SiteStats.php:95
static users()
Definition: SiteStats.php:122
static pages()
Definition: SiteStats.php:113
static getUsableTempDirectory()
Definition: TempFSFile.php:80
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:733
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
$wgMiserMode
Config variable stub for the MiserMode setting, for use by phpdoc and IDEs.
$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
$line
Definition: mcc.php:119
$cache
Definition: mcc.php:33
if( $line===false) $args
Definition: mcc.php:124
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