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 
854 function wfGetLangObj( $langcode = false ) {
855  # Identify which language to get or create a language object for.
856  # Using is_object here due to Stub objects.
857  if ( is_object( $langcode ) ) {
858  # Great, we already have the object (hopefully)!
859  return $langcode;
860  }
861 
862  global $wgLanguageCode;
863  $services = MediaWikiServices::getInstance();
864  if ( $langcode === true || $langcode === $wgLanguageCode ) {
865  # $langcode is the language code of the wikis content language object.
866  # or it is a boolean and value is true
867  return $services->getContentLanguage();
868  }
869 
870  global $wgLang;
871  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
872  # $langcode is the language code of user language object.
873  # or it was a boolean and value is false
874  return $wgLang;
875  }
876 
877  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
878  if ( in_array( $langcode, $validCodes ) ) {
879  # $langcode corresponds to a valid language.
880  return $services->getLanguageFactory()->getLanguage( $langcode );
881  }
882 
883  # $langcode is a string, but not a valid language code; use content language.
884  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
885  return $services->getContentLanguage();
886 }
887 
909 function wfMessage( $key, ...$params ) {
910  if ( is_array( $key ) ) {
911  // Fallback keys are not allowed in message specifiers
912  $message = wfMessageFallback( ...$key );
913  } else {
914  $message = Message::newFromSpecifier( $key );
915  }
916 
917  // We call Message::params() to reduce code duplication
918  if ( $params ) {
919  $message->params( ...$params );
920  }
921 
922  return $message;
923 }
924 
937 function wfMessageFallback( ...$keys ) {
938  return Message::newFallbackSequence( ...$keys );
939 }
940 
949 function wfMsgReplaceArgs( $message, $args ) {
950  # Fix windows line-endings
951  # Some messages are split with explode("\n", $msg)
952  $message = str_replace( "\r", '', $message );
953 
954  // Replace arguments
955  if ( is_array( $args ) && $args ) {
956  if ( is_array( $args[0] ) ) {
957  $args = array_values( $args[0] );
958  }
959  $replacementKeys = [];
960  foreach ( $args as $n => $param ) {
961  $replacementKeys['$' . ( $n + 1 )] = $param;
962  }
963  $message = strtr( $message, $replacementKeys );
964  }
965 
966  return $message;
967 }
968 
977 function wfHostname() {
978  // Hostname overriding
979  global $wgOverrideHostname;
980  if ( $wgOverrideHostname !== false ) {
981  return $wgOverrideHostname;
982  }
983 
984  return php_uname( 'n' ) ?: 'unknown';
985 }
986 
997 function wfReportTime( $nonce = null ) {
998  global $wgShowHostnames;
999 
1000  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1001  // seconds to milliseconds
1002  $responseTime = round( $elapsed * 1000 );
1003  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1004  if ( $wgShowHostnames ) {
1005  $reportVars['wgHostname'] = wfHostname();
1006  }
1007 
1008  return (
1009  ResourceLoader::makeInlineScript(
1010  ResourceLoader::makeConfigSetScript( $reportVars ),
1011  $nonce
1012  )
1013  );
1014 }
1015 
1026 function wfDebugBacktrace( $limit = 0 ) {
1027  static $disabled = null;
1028 
1029  if ( $disabled === null ) {
1030  $disabled = !function_exists( 'debug_backtrace' );
1031  if ( $disabled ) {
1032  wfDebug( "debug_backtrace() is disabled" );
1033  }
1034  }
1035  if ( $disabled ) {
1036  return [];
1037  }
1038 
1039  if ( $limit ) {
1040  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1041  } else {
1042  return array_slice( debug_backtrace(), 1 );
1043  }
1044 }
1045 
1054 function wfBacktrace( $raw = null ) {
1055  global $wgCommandLineMode;
1056 
1057  if ( $raw === null ) {
1058  $raw = $wgCommandLineMode;
1059  }
1060 
1061  if ( $raw ) {
1062  $frameFormat = "%s line %s calls %s()\n";
1063  $traceFormat = "%s";
1064  } else {
1065  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1066  $traceFormat = "<ul>\n%s</ul>\n";
1067  }
1068 
1069  $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1070  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1071  $line = $frame['line'] ?? '-';
1072  $call = $frame['function'];
1073  if ( !empty( $frame['class'] ) ) {
1074  $call = $frame['class'] . $frame['type'] . $call;
1075  }
1076  return sprintf( $frameFormat, $file, $line, $call );
1077  }, wfDebugBacktrace() );
1078 
1079  return sprintf( $traceFormat, implode( '', $frames ) );
1080 }
1081 
1091 function wfGetCaller( $level = 2 ) {
1092  $backtrace = wfDebugBacktrace( $level + 1 );
1093  if ( isset( $backtrace[$level] ) ) {
1094  return wfFormatStackFrame( $backtrace[$level] );
1095  } else {
1096  return 'unknown';
1097  }
1098 }
1099 
1107 function wfGetAllCallers( $limit = 3 ) {
1108  $trace = array_reverse( wfDebugBacktrace() );
1109  if ( !$limit || $limit > count( $trace ) - 1 ) {
1110  $limit = count( $trace ) - 1;
1111  }
1112  $trace = array_slice( $trace, -$limit - 1, $limit );
1113  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1114 }
1115 
1122 function wfFormatStackFrame( $frame ) {
1123  if ( !isset( $frame['function'] ) ) {
1124  return 'NO_FUNCTION_GIVEN';
1125  }
1126  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1127  $frame['class'] . $frame['type'] . $frame['function'] :
1128  $frame['function'];
1129 }
1130 
1131 /* Some generic result counters, pulled out of SearchEngine */
1132 
1140 function wfShowingResults( $offset, $limit ) {
1141  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1142 }
1143 
1153 function wfClientAcceptsGzip( $force = false ) {
1154  static $result = null;
1155  if ( $result === null || $force ) {
1156  $result = false;
1157  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1158  # @todo FIXME: We may want to disallow some broken browsers
1159  $m = [];
1160  if ( preg_match(
1161  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1162  $_SERVER['HTTP_ACCEPT_ENCODING'],
1163  $m
1164  )
1165  ) {
1166  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1167  return $result;
1168  }
1169  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1170  $result = true;
1171  }
1172  }
1173  }
1174  return $result;
1175 }
1176 
1187 function wfEscapeWikiText( $text ) {
1188  global $wgEnableMagicLinks;
1189  static $repl = null, $repl2 = null;
1190  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1191  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1192  // in those situations
1193  $repl = [
1194  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1195  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1196  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1197  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1198  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1199  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1200  "\n " => "\n&#32;", "\r " => "\r&#32;",
1201  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1202  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1203  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1204  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1205  '__' => '_&#95;', '://' => '&#58;//',
1206  ];
1207 
1208  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1209  // We have to catch everything "\s" matches in PCRE
1210  foreach ( $magicLinks as $magic ) {
1211  $repl["$magic "] = "$magic&#32;";
1212  $repl["$magic\t"] = "$magic&#9;";
1213  $repl["$magic\r"] = "$magic&#13;";
1214  $repl["$magic\n"] = "$magic&#10;";
1215  $repl["$magic\f"] = "$magic&#12;";
1216  }
1217 
1218  // And handle protocols that don't use "://"
1219  global $wgUrlProtocols;
1220  $repl2 = [];
1221  foreach ( $wgUrlProtocols as $prot ) {
1222  if ( substr( $prot, -1 ) === ':' ) {
1223  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1224  }
1225  }
1226  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1227  }
1228  $text = substr( strtr( "\n$text", $repl ), 1 );
1229  // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
1230  $text = preg_replace( $repl2, '$1&#58;', $text );
1231  return $text;
1232 }
1233 
1244 function wfSetVar( &$dest, $source, $force = false ) {
1245  $temp = $dest;
1246  if ( $source !== null || $force ) {
1247  $dest = $source;
1248  }
1249  return $temp;
1250 }
1251 
1261 function wfSetBit( &$dest, $bit, $state = true ) {
1262  $temp = (bool)( $dest & $bit );
1263  if ( $state !== null ) {
1264  if ( $state ) {
1265  $dest |= $bit;
1266  } else {
1267  $dest &= ~$bit;
1268  }
1269  }
1270  return $temp;
1271 }
1272 
1279 function wfVarDump( $var ) {
1280  global $wgOut;
1281  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1282  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1283  print $s;
1284  } else {
1285  $wgOut->addHTML( $s );
1286  }
1287 }
1288 
1296 function wfHttpError( $code, $label, $desc ) {
1297  global $wgOut;
1298  HttpStatus::header( $code );
1299  if ( $wgOut ) {
1300  $wgOut->disable();
1301  $wgOut->sendCacheControl();
1302  }
1303 
1305  header( 'Content-type: text/html; charset=utf-8' );
1306  ob_start();
1307  print '<!DOCTYPE html>' .
1308  '<html><head><title>' .
1309  htmlspecialchars( $label ) .
1310  '</title></head><body><h1>' .
1311  htmlspecialchars( $label ) .
1312  '</h1><p>' .
1313  nl2br( htmlspecialchars( $desc ) ) .
1314  "</p></body></html>\n";
1315  header( 'Content-Length: ' . ob_get_length() );
1316  ob_end_flush();
1317 }
1318 
1336 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1337  while ( $status = ob_get_status() ) {
1338  if ( isset( $status['flags'] ) ) {
1339  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1340  $deleteable = ( $status['flags'] & $flags ) === $flags;
1341  } elseif ( isset( $status['del'] ) ) {
1342  $deleteable = $status['del'];
1343  } else {
1344  // Guess that any PHP-internal setting can't be removed.
1345  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1346  }
1347  if ( !$deleteable ) {
1348  // Give up, and hope the result doesn't break
1349  // output behavior.
1350  break;
1351  }
1352  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1353  // Unit testing barrier to prevent this function from breaking PHPUnit.
1354  break;
1355  }
1356  if ( !ob_end_clean() ) {
1357  // Could not remove output buffer handler; abort now
1358  // to avoid getting in some kind of infinite loop.
1359  break;
1360  }
1361  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1362  // Reset the 'Content-Encoding' field set by this handler
1363  // so we can start fresh.
1364  header_remove( 'Content-Encoding' );
1365  break;
1366  }
1367  }
1368 }
1369 
1385  wfDeprecated( __FUNCTION__, '1.36' );
1386  wfResetOutputBuffers( false );
1387 }
1388 
1399 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1400  $ret = MWTimestamp::convert( $outputtype, $ts );
1401  if ( $ret === false ) {
1402  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1403  }
1404  return $ret;
1405 }
1406 
1415 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1416  if ( $ts === null ) {
1417  return null;
1418  } else {
1419  return wfTimestamp( $outputtype, $ts );
1420  }
1421 }
1422 
1428 function wfTimestampNow() {
1429  return MWTimestamp::now( TS_MW );
1430 }
1431 
1437 function wfIsWindows() {
1438  return PHP_OS_FAMILY === 'Windows';
1439 }
1440 
1447 function wfIsCLI() {
1448  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1449 }
1450 
1462 function wfTempDir() {
1463  global $wgTmpDirectory;
1464 
1465  if ( $wgTmpDirectory !== false ) {
1466  return $wgTmpDirectory;
1467  }
1468 
1470 }
1471 
1481 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1482  global $wgDirectoryMode;
1483 
1484  if ( FileBackend::isStoragePath( $dir ) ) {
1485  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1486  }
1487 
1488  if ( $caller !== null ) {
1489  wfDebug( "$caller: called wfMkdirParents($dir)" );
1490  }
1491 
1492  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1493  return true;
1494  }
1495 
1496  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1497 
1498  if ( $mode === null ) {
1499  $mode = $wgDirectoryMode;
1500  }
1501 
1502  // Turn off the normal warning, we're doing our own below
1503  AtEase::suppressWarnings();
1504  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1505  AtEase::restoreWarnings();
1506 
1507  if ( !$ok ) {
1508  // directory may have been created on another request since we last checked
1509  if ( is_dir( $dir ) ) {
1510  return true;
1511  }
1512 
1513  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1514  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1515  }
1516  return $ok;
1517 }
1518 
1524 function wfRecursiveRemoveDir( $dir ) {
1525  wfDebug( __FUNCTION__ . "( $dir )" );
1526  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1527  if ( is_dir( $dir ) ) {
1528  $objects = scandir( $dir );
1529  foreach ( $objects as $object ) {
1530  if ( $object != "." && $object != ".." ) {
1531  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1532  wfRecursiveRemoveDir( $dir . '/' . $object );
1533  } else {
1534  unlink( $dir . '/' . $object );
1535  }
1536  }
1537  }
1538  reset( $objects );
1539  rmdir( $dir );
1540  }
1541 }
1542 
1549 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1550  $accForFormat = $acc >= 0 ? $acc : 0;
1551  $ret = sprintf( "%.{$accForFormat}f", $nr );
1552  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1553 }
1554 
1578 function wfIniGetBool( $setting ) {
1579  return wfStringToBool( ini_get( $setting ) );
1580 }
1581 
1594 function wfStringToBool( $val ) {
1595  $val = strtolower( $val );
1596  // 'on' and 'true' can't have whitespace around them, but '1' can.
1597  return $val == 'on'
1598  || $val == 'true'
1599  || $val == 'yes'
1600  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1601 }
1602 
1616 function wfEscapeShellArg( ...$args ) {
1617  return Shell::escape( ...$args );
1618 }
1619 
1644 function wfShellExec( $cmd, &$retval = null, $environ = [],
1645  $limits = [], $options = []
1646 ) {
1647  if ( Shell::isDisabled() ) {
1648  $retval = 1;
1649  // Backwards compatibility be upon us...
1650  return 'Unable to run external programs, proc_open() is disabled.';
1651  }
1652 
1653  if ( is_array( $cmd ) ) {
1654  $cmd = Shell::escape( $cmd );
1655  }
1656 
1657  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1658  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1659 
1660  try {
1661  $result = Shell::command( [] )
1662  ->unsafeParams( (array)$cmd )
1663  ->environment( $environ )
1664  ->limits( $limits )
1665  ->includeStderr( $includeStderr )
1666  ->profileMethod( $profileMethod )
1667  // For b/c
1668  ->restrict( Shell::RESTRICT_NONE )
1669  ->execute();
1670  } catch ( ProcOpenError $ex ) {
1671  $retval = -1;
1672  return '';
1673  }
1674 
1675  $retval = $result->getExitCode();
1676 
1677  return $result->getStdout();
1678 }
1679 
1697 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1698  return wfShellExec( $cmd, $retval, $environ, $limits,
1699  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1700 }
1701 
1717 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1718  global $wgPhpCli;
1719  // Give site config file a chance to run the script in a wrapper.
1720  // The caller may likely want to call wfBasename() on $script.
1721  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1722  $cmd = [ $options['php'] ?? $wgPhpCli ];
1723  if ( isset( $options['wrapper'] ) ) {
1724  $cmd[] = $options['wrapper'];
1725  }
1726  $cmd[] = $script;
1727  // Escape each parameter for shell
1728  return Shell::escape( array_merge( $cmd, $parameters ) );
1729 }
1730 
1742 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
1743  global $wgDiff3;
1744 
1745  # This check may also protect against code injection in
1746  # case of broken installations.
1747  AtEase::suppressWarnings();
1748  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1749  AtEase::restoreWarnings();
1750 
1751  if ( !$haveDiff3 ) {
1752  wfDebug( "diff3 not found" );
1753  return false;
1754  }
1755 
1756  # Make temporary files
1757  $td = wfTempDir();
1758  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1759  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1760  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1761 
1762  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1763  # a newline character. To avoid this, we normalize the trailing whitespace before
1764  # creating the diff.
1765 
1766  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1767  fclose( $oldtextFile );
1768  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1769  fclose( $mytextFile );
1770  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1771  fclose( $yourtextFile );
1772 
1773  # Check for a conflict
1774  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
1775  $oldtextName, $yourtextName );
1776  $handle = popen( $cmd, 'r' );
1777 
1778  $mergeAttemptResult = '';
1779  do {
1780  $data = fread( $handle, 8192 );
1781  if ( strlen( $data ) == 0 ) {
1782  break;
1783  }
1784  $mergeAttemptResult .= $data;
1785  } while ( true );
1786  pclose( $handle );
1787 
1788  $conflict = $mergeAttemptResult !== '';
1789 
1790  # Merge differences
1791  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
1792  $oldtextName, $yourtextName );
1793  $handle = popen( $cmd, 'r' );
1794  $result = '';
1795  do {
1796  $data = fread( $handle, 8192 );
1797  if ( strlen( $data ) == 0 ) {
1798  break;
1799  }
1800  $result .= $data;
1801  } while ( true );
1802  pclose( $handle );
1803  unlink( $mytextName );
1804  unlink( $oldtextName );
1805  unlink( $yourtextName );
1806 
1807  if ( $result === '' && $old !== '' && !$conflict ) {
1808  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1809  $conflict = true;
1810  }
1811  return !$conflict;
1812 }
1813 
1826 function wfBaseName( $path, $suffix = '' ) {
1827  if ( $suffix == '' ) {
1828  $encSuffix = '';
1829  } else {
1830  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1831  }
1832 
1833  $matches = [];
1834  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1835  return $matches[1];
1836  } else {
1837  return '';
1838  }
1839 }
1840 
1850 function wfRelativePath( $path, $from ) {
1851  // Normalize mixed input on Windows...
1852  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1853  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1854 
1855  // Trim trailing slashes -- fix for drive root
1856  $path = rtrim( $path, DIRECTORY_SEPARATOR );
1857  $from = rtrim( $from, DIRECTORY_SEPARATOR );
1858 
1859  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1860  $against = explode( DIRECTORY_SEPARATOR, $from );
1861 
1862  if ( $pieces[0] !== $against[0] ) {
1863  // Non-matching Windows drive letters?
1864  // Return a full path.
1865  return $path;
1866  }
1867 
1868  // Trim off common prefix
1869  while ( count( $pieces ) && count( $against )
1870  && $pieces[0] == $against[0] ) {
1871  array_shift( $pieces );
1872  array_shift( $against );
1873  }
1874 
1875  // relative dots to bump us to the parent
1876  while ( count( $against ) ) {
1877  array_unshift( $pieces, '..' );
1878  array_shift( $against );
1879  }
1880 
1881  $pieces[] = wfBaseName( $path );
1882 
1883  return implode( DIRECTORY_SEPARATOR, $pieces );
1884 }
1885 
1917 function wfGetDB( $db, $groups = [], $wiki = false ) {
1918  if ( $wiki === false ) {
1919  return MediaWikiServices::getInstance()
1920  ->getDBLoadBalancer()
1921  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1922  } else {
1923  return MediaWikiServices::getInstance()
1924  ->getDBLoadBalancerFactory()
1925  ->getMainLB( $wiki )
1926  ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1927  }
1928 }
1929 
1938 function wfScript( $script = 'index' ) {
1940  if ( $script === 'index' ) {
1941  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable False positive
1942  return $wgScript;
1943  } elseif ( $script === 'load' ) {
1944  return $wgLoadScript;
1945  } else {
1946  return "{$wgScriptPath}/{$script}.php";
1947  }
1948 }
1949 
1957 function wfBoolToStr( $value ) {
1958  return $value ? 'true' : 'false';
1959 }
1960 
1966 function wfGetNull() {
1967  return wfIsWindows() ? 'NUL' : '/dev/null';
1968 }
1969 
1978 function wfStripIllegalFilenameChars( $name ) {
1979  global $wgIllegalFileChars;
1980  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1981  $name = preg_replace(
1982  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1983  '-',
1984  $name
1985  );
1986  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1987  $name = wfBaseName( $name );
1988  return $name;
1989 }
1990 
1997 function wfMemoryLimit( $newLimit ) {
1998  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1999  // If the INI config is already unlimited, there is nothing larger
2000  if ( $oldLimit != -1 ) {
2001  $newLimit = wfShorthandToInteger( (string)$newLimit );
2002  if ( $newLimit == -1 ) {
2003  wfDebug( "Removing PHP's memory limit" );
2004  AtEase::suppressWarnings();
2005  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
2006  ini_set( 'memory_limit', $newLimit );
2007  AtEase::restoreWarnings();
2008  } elseif ( $newLimit > $oldLimit ) {
2009  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2010  AtEase::suppressWarnings();
2011  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
2012  ini_set( 'memory_limit', $newLimit );
2013  AtEase::restoreWarnings();
2014  }
2015  }
2016 }
2017 
2026 
2027  $timeout = RequestTimeout::singleton();
2028  $timeLimit = $timeout->getWallTimeLimit();
2029  if ( $timeLimit !== INF ) {
2030  // RequestTimeout library is active
2031  if ( $wgTransactionalTimeLimit > $timeLimit ) {
2032  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2033  }
2034  } else {
2035  // Fallback case, likely $wgRequestTimeLimit === null
2036  $timeLimit = (int)ini_get( 'max_execution_time' );
2037  // Note that CLI scripts use 0
2038  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2039  $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2040  }
2041  }
2042  ignore_user_abort( true ); // ignore client disconnects
2043 
2044  return $timeLimit;
2045 }
2046 
2054 function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2055  $string = trim( $string ?? '' );
2056  if ( $string === '' ) {
2057  return $default;
2058  }
2059  $last = $string[strlen( $string ) - 1];
2060  $val = intval( $string );
2061  switch ( $last ) {
2062  case 'g':
2063  case 'G':
2064  $val *= 1024;
2065  // break intentionally missing
2066  case 'm':
2067  case 'M':
2068  $val *= 1024;
2069  // break intentionally missing
2070  case 'k':
2071  case 'K':
2072  $val *= 1024;
2073  }
2074 
2075  return $val;
2076 }
2077 
2092 function wfUnpack( $format, $data, $length = false ) {
2093  if ( $length !== false ) {
2094  $realLen = strlen( $data );
2095  if ( $realLen < $length ) {
2096  throw new MWException( "Tried to use wfUnpack on a "
2097  . "string of length $realLen, but needed one "
2098  . "of at least length $length."
2099  );
2100  }
2101  }
2102 
2103  AtEase::suppressWarnings();
2104  $result = unpack( $format, $data );
2105  AtEase::restoreWarnings();
2106 
2107  if ( $result === false ) {
2108  // If it cannot extract the packed data.
2109  throw new MWException( "unpack could not unpack binary data" );
2110  }
2111  return $result;
2112 }
2113 
2121 function wfIsInfinity( $str ) {
2122  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2123  return in_array( $str, ExpiryDef::INFINITY_VALS );
2124 }
2125 
2140 function wfThumbIsStandard( File $file, array $params ) {
2142 
2143  $multipliers = [ 1 ];
2144  if ( $wgResponsiveImages ) {
2145  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2146  // @see Linker::processResponsiveImages
2147  $multipliers[] = 1.5;
2148  $multipliers[] = 2;
2149  }
2150 
2151  $handler = $file->getHandler();
2152  if ( !$handler || !isset( $params['width'] ) ) {
2153  return false;
2154  }
2155 
2156  $basicParams = [];
2157  if ( isset( $params['page'] ) ) {
2158  $basicParams['page'] = $params['page'];
2159  }
2160 
2161  $thumbLimits = [];
2162  $imageLimits = [];
2163  // Expand limits to account for multipliers
2164  foreach ( $multipliers as $multiplier ) {
2165  $thumbLimits = array_merge( $thumbLimits, array_map(
2166  static function ( $width ) use ( $multiplier ) {
2167  return round( $width * $multiplier );
2168  }, $wgThumbLimits )
2169  );
2170  $imageLimits = array_merge( $imageLimits, array_map(
2171  static function ( $pair ) use ( $multiplier ) {
2172  return [
2173  round( $pair[0] * $multiplier ),
2174  round( $pair[1] * $multiplier ),
2175  ];
2176  }, $wgImageLimits )
2177  );
2178  }
2179 
2180  // Check if the width matches one of $wgThumbLimits
2181  if ( in_array( $params['width'], $thumbLimits ) ) {
2182  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2183  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2184  $handler->normaliseParams( $file, $normalParams );
2185  } else {
2186  // If not, then check if the width matches one of $wgImageLimits
2187  $match = false;
2188  foreach ( $imageLimits as $pair ) {
2189  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2190  // Decide whether the thumbnail should be scaled on width or height.
2191  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2192  $handler->normaliseParams( $file, $normalParams );
2193  // Check if this standard thumbnail size maps to the given width
2194  if ( $normalParams['width'] == $params['width'] ) {
2195  $match = true;
2196  break;
2197  }
2198  }
2199  if ( !$match ) {
2200  return false; // not standard for description pages
2201  }
2202  }
2203 
2204  // Check that the given values for non-page, non-width, params are just defaults
2205  foreach ( $params as $key => $value ) {
2206  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2207  return false;
2208  }
2209  }
2210 
2211  return true;
2212 }
2213 
2226 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2227  // First merge items that are in both arrays
2228  foreach ( $baseArray as $name => &$groupVal ) {
2229  if ( isset( $newValues[$name] ) ) {
2230  $groupVal += $newValues[$name];
2231  }
2232  }
2233  // Now add items that didn't exist yet
2234  $baseArray += $newValues;
2235 
2236  return $baseArray;
2237 }
const PROTO_CURRENT
Definition: Defines.php:198
global $wgCommandLineMode
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
wfVarDump( $var)
A wrapper around the PHP function var_export().
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfTempDir()
Tries to get the system directory for temporary files.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfLoadExtension( $ext, $path=null)
Load an extension.
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfArrayDiff2( $arr1, $arr2)
Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfGetUrlUtils()
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfPercent( $nr, int $acc=2, bool $round=true)
wfReportTime( $nonce=null)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfGetNull()
Get a platform-independent path to the null file, e.g.
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfShowingResults( $offset, $limit)
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
wfLoadSkin( $skin, $path=null)
Load a skin.
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
wfFormatStackFrame( $frame)
Return a string representation of frame.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfIsWindows()
Check if the operating system is Windows.
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfLoadExtensions(array $exts)
Load multiple extensions at once.
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
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:377
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgOut
Definition: Setup.php:497
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:497
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:183
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition: MWDebug.php:224
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: MWDebug.php:306
MediaWiki exception.
Definition: MWException.php:29
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
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
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:1152
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:456
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:422
static instance()
Singleton.
Definition: Profiler.php:69
static getUsableTempDirectory()
Definition: TempFSFile.php:80
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:734
static detectProtocol()
Detect the protocol from $_SERVER.
Definition: WebRequest.php:313
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
$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