MediaWiki REL1_39
GlobalFunctions.php
Go to the documentation of this file.
1<?php
29use Wikimedia\AtEase\AtEase;
31use Wikimedia\RequestTimeout\RequestTimeout;
32use Wikimedia\WrappedString;
33
44function wfLoadExtension( $ext, $path = null ) {
45 if ( !$path ) {
47 $path = "$wgExtensionDirectory/$ext/extension.json";
48 }
49 ExtensionRegistry::getInstance()->queue( $path );
50}
51
65function wfLoadExtensions( array $exts ) {
67 $registry = ExtensionRegistry::getInstance();
68 foreach ( $exts as $ext ) {
69 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
70 }
71}
72
81function wfLoadSkin( $skin, $path = null ) {
82 if ( !$path ) {
83 global $wgStyleDirectory;
84 $path = "$wgStyleDirectory/$skin/skin.json";
85 }
86 ExtensionRegistry::getInstance()->queue( $path );
87}
88
96function wfLoadSkins( array $skins ) {
97 global $wgStyleDirectory;
98 $registry = ExtensionRegistry::getInstance();
99 foreach ( $skins as $skin ) {
100 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
101 }
102}
103
110function wfArrayDiff2( $arr1, $arr2 ) {
115 $comparator = static function ( $a, $b ): int {
116 if ( is_string( $a ) && is_string( $b ) ) {
117 return strcmp( $a, $b );
118 }
119 if ( !is_array( $a ) && !is_array( $b ) ) {
120 throw new InvalidArgumentException(
121 'This function assumes that array elements are all strings or all arrays'
122 );
123 }
124 if ( count( $a ) !== count( $b ) ) {
125 return count( $a ) <=> count( $b );
126 } else {
127 reset( $a );
128 reset( $b );
129 while ( key( $a ) !== null && key( $b ) !== null ) {
130 $valueA = current( $a );
131 $valueB = current( $b );
132 $cmp = strcmp( $valueA, $valueB );
133 if ( $cmp !== 0 ) {
134 return $cmp;
135 }
136 next( $a );
137 next( $b );
138 }
139 return 0;
140 }
141 };
142 return array_udiff( $arr1, $arr2, $comparator );
143}
144
164function wfMergeErrorArrays( ...$args ) {
165 $out = [];
166 foreach ( $args as $errors ) {
167 foreach ( $errors as $params ) {
168 $originalParams = $params;
169 if ( $params[0] instanceof MessageSpecifier ) {
170 $msg = $params[0];
171 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
172 }
173 # @todo FIXME: Sometimes get nested arrays for $params,
174 # which leads to E_NOTICEs
175 $spec = implode( "\t", $params );
176 $out[$spec] = $originalParams;
177 }
178 }
179 return array_values( $out );
180}
181
191function wfArrayInsertAfter( array $array, array $insert, $after ) {
192 // Find the offset of the element to insert after.
193 $keys = array_keys( $array );
194 $offsetByKey = array_flip( $keys );
195
196 if ( !\array_key_exists( $after, $offsetByKey ) ) {
197 return $array;
198 }
199 $offset = $offsetByKey[$after];
200
201 // Insert at the specified offset
202 $before = array_slice( $array, 0, $offset + 1, true );
203 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
204
205 $output = $before + $insert + $after;
206
207 return $output;
208}
209
218function wfObjectToArray( $objOrArray, $recursive = true ) {
219 $array = [];
220 if ( is_object( $objOrArray ) ) {
221 $objOrArray = get_object_vars( $objOrArray );
222 }
223 foreach ( $objOrArray as $key => $value ) {
224 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
225 $value = wfObjectToArray( $value );
226 }
227
228 $array[$key] = $value;
229 }
230
231 return $array;
232}
233
244function wfRandom() {
245 // The maximum random value is "only" 2^31-1, so get two random
246 // values to reduce the chance of dupes
247 $max = mt_getrandmax() + 1;
248 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
249 return $rand;
250}
251
262function wfRandomString( $length = 32 ) {
263 $str = '';
264 for ( $n = 0; $n < $length; $n += 7 ) {
265 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
266 }
267 return substr( $str, 0, $length );
268}
269
297function wfUrlencode( $s ) {
298 static $needle;
299
300 if ( $s === null ) {
301 // Reset $needle for testing.
302 $needle = null;
303 return '';
304 }
305
306 if ( $needle === null ) {
307 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
308 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
309 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
310 ) {
311 $needle[] = '%3A';
312 }
313 }
314
315 $s = urlencode( $s );
316 $s = str_ireplace(
317 $needle,
318 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
319 $s
320 );
321
322 return $s;
323}
324
335function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
336 if ( $array2 !== null ) {
337 $array1 += $array2;
338 }
339
340 $cgi = '';
341 foreach ( $array1 as $key => $value ) {
342 if ( $value !== null && $value !== false ) {
343 if ( $cgi != '' ) {
344 $cgi .= '&';
345 }
346 if ( $prefix !== '' ) {
347 $key = $prefix . "[$key]";
348 }
349 if ( is_array( $value ) ) {
350 $firstTime = true;
351 foreach ( $value as $k => $v ) {
352 $cgi .= $firstTime ? '' : '&';
353 if ( is_array( $v ) ) {
354 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
355 } else {
356 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
357 }
358 $firstTime = false;
359 }
360 } else {
361 if ( is_object( $value ) ) {
362 $value = $value->__toString();
363 }
364 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
365 }
366 }
367 }
368 return $cgi;
369}
370
380function wfCgiToArray( $query ) {
381 if ( isset( $query[0] ) && $query[0] == '?' ) {
382 $query = substr( $query, 1 );
383 }
384 $bits = explode( '&', $query );
385 $ret = [];
386 foreach ( $bits as $bit ) {
387 if ( $bit === '' ) {
388 continue;
389 }
390 if ( strpos( $bit, '=' ) === false ) {
391 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
392 $key = $bit;
393 $value = '';
394 } else {
395 list( $key, $value ) = explode( '=', $bit );
396 }
397 $key = urldecode( $key );
398 $value = urldecode( $value );
399 if ( strpos( $key, '[' ) !== false ) {
400 $keys = array_reverse( explode( '[', $key ) );
401 $key = array_pop( $keys );
402 $temp = $value;
403 foreach ( $keys as $k ) {
404 $k = substr( $k, 0, -1 );
405 $temp = [ $k => $temp ];
406 }
407 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
408 $ret[$key] = array_merge( $ret[$key], $temp );
409 } else {
410 $ret[$key] = $temp;
411 }
412 } else {
413 $ret[$key] = $value;
414 }
415 }
416 return $ret;
417}
418
427function wfAppendQuery( $url, $query ) {
428 if ( is_array( $query ) ) {
429 $query = wfArrayToCgi( $query );
430 }
431 if ( $query != '' ) {
432 // Remove the fragment, if there is one
433 $fragment = false;
434 $hashPos = strpos( $url, '#' );
435 if ( $hashPos !== false ) {
436 $fragment = substr( $url, $hashPos );
437 $url = substr( $url, 0, $hashPos );
438 }
439
440 // Add parameter
441 if ( strpos( $url, '?' ) === false ) {
442 $url .= '?';
443 } else {
444 $url .= '&';
445 }
446 $url .= $query;
447
448 // Put the fragment back
449 if ( $fragment !== false ) {
450 $url .= $fragment;
451 }
452 }
453 return $url;
454}
455
464
465 if ( MediaWikiServices::hasInstance() ) {
466 $services = MediaWikiServices::getInstance();
467 if ( $services->hasService( 'UrlUtils' ) ) {
468 return $services->getUrlUtils();
469 }
470 }
471
472 return new UrlUtils( [
473 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
474 // implementations implicitly converted it to an empty string (presumably by mistake).
475 // Preserve the old behavior for compatibility.
476 UrlUtils::SERVER => $wgServer ?? '',
477 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
478 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
479 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
480 : WebRequest::detectProtocol(),
481 UrlUtils::HTTPS_PORT => $wgHttpsPort,
482 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
483 ] );
484}
485
507function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
508 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
509}
510
520function wfGetServerUrl( $proto ) {
521 return wfGetUrlUtils()->getServer( $proto ) ?? '';
522}
523
536function wfAssembleUrl( $urlParts ) {
537 return wfGetUrlUtils()->assemble( (array)$urlParts );
538}
539
551function wfRemoveDotSegments( $urlPath ) {
552 return wfGetUrlUtils()->removeDotSegments( (string)$urlPath );
553}
554
563function wfUrlProtocols( $includeProtocolRelative = true ) {
564 $method = $includeProtocolRelative ? 'validProtocols' : 'validAbsoluteProtocols';
565 return wfGetUrlUtils()->$method();
566}
567
576 return wfGetUrlUtils()->validAbsoluteProtocols();
577}
578
605function wfParseUrl( $url ) {
606 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
607}
608
618function wfExpandIRI( $url ) {
619 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
620}
621
630function wfMatchesDomainList( $url, $domains ) {
631 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
632}
633
654function wfDebug( $text, $dest = 'all', array $context = [] ) {
656
657 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
658 return;
659 }
660
661 $text = trim( $text );
662
663 if ( $wgDebugLogPrefix !== '' ) {
664 $context['prefix'] = $wgDebugLogPrefix;
665 }
666 $context['private'] = ( $dest === false || $dest === 'private' );
667
668 $logger = LoggerFactory::getInstance( 'wfDebug' );
669 $logger->debug( $text, $context );
670}
671
677 static $cache;
678 if ( $cache !== null ) {
679 return $cache;
680 }
681 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
682 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
683 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
684 || MW_ENTRY_POINT === 'load'
685 ) {
686 $cache = true;
687 } else {
688 $cache = false;
689 }
690 return $cache;
691}
692
718function wfDebugLog(
719 $logGroup, $text, $dest = 'all', array $context = []
720) {
721 $text = trim( $text );
722
723 $logger = LoggerFactory::getInstance( $logGroup );
724 $context['private'] = ( $dest === false || $dest === 'private' );
725 $logger->info( $text, $context );
726}
727
736function wfLogDBError( $text, array $context = [] ) {
737 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
738 $logger->error( trim( $text ), $context );
739}
740
757function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
758 if ( !is_string( $version ) && $version !== false ) {
759 throw new InvalidArgumentException(
760 "MediaWiki version must either be a string or false. " .
761 "Example valid version: '1.33'"
762 );
763 }
764
765 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
766}
767
788function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
789 MWDebug::deprecatedMsg( $msg, $version, $component,
790 $callerOffset === false ? false : $callerOffset + 1 );
791}
792
803function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
804 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
805}
806
816function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
817 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
818}
819
824 wfDeprecated( __FUNCTION__, '1.38' );
825 $profiler = Profiler::instance();
826 $profiler->logData();
827
828 // Send out any buffered statsd metrics as needed
829 MediaWiki::emitBufferedStatsdData(
830 MediaWikiServices::getInstance()->getStatsdDataFactory(),
831 MediaWikiServices::getInstance()->getMainConfig()
832 );
833}
834
842function wfReadOnly() {
843 wfDeprecated( __FUNCTION__, '1.38' );
844 return MediaWikiServices::getInstance()->getReadOnlyMode()
845 ->isReadOnly();
846}
847
859 wfDeprecated( __FUNCTION__, '1.38' );
860 return MediaWikiServices::getInstance()->getReadOnlyMode()
861 ->getReason();
862}
863
879function wfGetLangObj( $langcode = false ) {
880 # Identify which language to get or create a language object for.
881 # Using is_object here due to Stub objects.
882 if ( is_object( $langcode ) ) {
883 # Great, we already have the object (hopefully)!
884 return $langcode;
885 }
886
887 global $wgLanguageCode;
888 $services = MediaWikiServices::getInstance();
889 if ( $langcode === true || $langcode === $wgLanguageCode ) {
890 # $langcode is the language code of the wikis content language object.
891 # or it is a boolean and value is true
892 return $services->getContentLanguage();
893 }
894
895 global $wgLang;
896 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
897 # $langcode is the language code of user language object.
898 # or it was a boolean and value is false
899 return $wgLang;
900 }
901
902 $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
903 if ( in_array( $langcode, $validCodes ) ) {
904 # $langcode corresponds to a valid language.
905 return $services->getLanguageFactory()->getLanguage( $langcode );
906 }
907
908 # $langcode is a string, but not a valid language code; use content language.
909 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
910 return $services->getContentLanguage();
911}
912
934function wfMessage( $key, ...$params ) {
935 if ( is_array( $key ) ) {
936 // Fallback keys are not allowed in message specifiers
937 $message = wfMessageFallback( ...$key );
938 } else {
939 $message = Message::newFromSpecifier( $key );
940 }
941
942 // We call Message::params() to reduce code duplication
943 if ( $params ) {
944 $message->params( ...$params );
945 }
946
947 return $message;
948}
949
962function wfMessageFallback( ...$keys ) {
964}
965
974function wfMsgReplaceArgs( $message, $args ) {
975 # Fix windows line-endings
976 # Some messages are split with explode("\n", $msg)
977 $message = str_replace( "\r", '', $message );
978
979 // Replace arguments
980 if ( is_array( $args ) && $args ) {
981 if ( is_array( $args[0] ) ) {
982 $args = array_values( $args[0] );
983 }
984 $replacementKeys = [];
985 foreach ( $args as $n => $param ) {
986 $replacementKeys['$' . ( $n + 1 )] = $param;
987 }
988 $message = strtr( $message, $replacementKeys );
989 }
990
991 return $message;
992}
993
1002function wfHostname() {
1003 // Hostname overriding
1004 global $wgOverrideHostname;
1005 if ( $wgOverrideHostname !== false ) {
1006 return $wgOverrideHostname;
1007 }
1008
1009 return php_uname( 'n' ) ?: 'unknown';
1010}
1011
1022function wfReportTime( $nonce = null ) {
1023 global $wgShowHostnames;
1024
1025 $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1026 // seconds to milliseconds
1027 $responseTime = round( $elapsed * 1000 );
1028 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1029 if ( $wgShowHostnames ) {
1030 $reportVars['wgHostname'] = wfHostname();
1031 }
1032
1033 return (
1034 ResourceLoader::makeInlineScript(
1035 ResourceLoader::makeConfigSetScript( $reportVars ),
1036 $nonce
1037 )
1038 );
1039}
1040
1051function wfDebugBacktrace( $limit = 0 ) {
1052 static $disabled = null;
1053
1054 if ( $disabled === null ) {
1055 $disabled = !function_exists( 'debug_backtrace' );
1056 if ( $disabled ) {
1057 wfDebug( "debug_backtrace() is disabled" );
1058 }
1059 }
1060 if ( $disabled ) {
1061 return [];
1062 }
1063
1064 if ( $limit ) {
1065 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1066 } else {
1067 return array_slice( debug_backtrace(), 1 );
1068 }
1069}
1070
1079function wfBacktrace( $raw = null ) {
1080 global $wgCommandLineMode;
1081
1082 if ( $raw === null ) {
1083 $raw = $wgCommandLineMode;
1084 }
1085
1086 if ( $raw ) {
1087 $frameFormat = "%s line %s calls %s()\n";
1088 $traceFormat = "%s";
1089 } else {
1090 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1091 $traceFormat = "<ul>\n%s</ul>\n";
1092 }
1093
1094 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1095 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1096 $line = $frame['line'] ?? '-';
1097 $call = $frame['function'];
1098 if ( !empty( $frame['class'] ) ) {
1099 $call = $frame['class'] . $frame['type'] . $call;
1100 }
1101 return sprintf( $frameFormat, $file, $line, $call );
1102 }, wfDebugBacktrace() );
1103
1104 return sprintf( $traceFormat, implode( '', $frames ) );
1105}
1106
1116function wfGetCaller( $level = 2 ) {
1117 $backtrace = wfDebugBacktrace( $level + 1 );
1118 if ( isset( $backtrace[$level] ) ) {
1119 return wfFormatStackFrame( $backtrace[$level] );
1120 } else {
1121 return 'unknown';
1122 }
1123}
1124
1132function wfGetAllCallers( $limit = 3 ) {
1133 $trace = array_reverse( wfDebugBacktrace() );
1134 if ( !$limit || $limit > count( $trace ) - 1 ) {
1135 $limit = count( $trace ) - 1;
1136 }
1137 $trace = array_slice( $trace, -$limit - 1, $limit );
1138 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1139}
1140
1147function wfFormatStackFrame( $frame ) {
1148 if ( !isset( $frame['function'] ) ) {
1149 return 'NO_FUNCTION_GIVEN';
1150 }
1151 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1152 $frame['class'] . $frame['type'] . $frame['function'] :
1153 $frame['function'];
1154}
1155
1156/* Some generic result counters, pulled out of SearchEngine */
1157
1165function wfShowingResults( $offset, $limit ) {
1166 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1167}
1168
1178function wfClientAcceptsGzip( $force = false ) {
1179 static $result = null;
1180 if ( $result === null || $force ) {
1181 $result = false;
1182 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1183 # @todo FIXME: We may want to disallow some broken browsers
1184 $m = [];
1185 if ( preg_match(
1186 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1187 $_SERVER['HTTP_ACCEPT_ENCODING'],
1188 $m
1189 )
1190 ) {
1191 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1192 return $result;
1193 }
1194 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1195 $result = true;
1196 }
1197 }
1198 }
1199 return $result;
1200}
1201
1212function wfEscapeWikiText( $text ) {
1213 global $wgEnableMagicLinks;
1214 static $repl = null, $repl2 = null;
1215 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1216 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1217 // in those situations
1218 $repl = [
1219 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1220 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1221 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1222 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1223 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1224 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1225 "\n " => "\n&#32;", "\r " => "\r&#32;",
1226 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1227 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1228 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1229 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1230 '__' => '_&#95;', '://' => '&#58;//',
1231 ];
1232
1233 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1234 // We have to catch everything "\s" matches in PCRE
1235 foreach ( $magicLinks as $magic ) {
1236 $repl["$magic "] = "$magic&#32;";
1237 $repl["$magic\t"] = "$magic&#9;";
1238 $repl["$magic\r"] = "$magic&#13;";
1239 $repl["$magic\n"] = "$magic&#10;";
1240 $repl["$magic\f"] = "$magic&#12;";
1241 }
1242
1243 // And handle protocols that don't use "://"
1244 global $wgUrlProtocols;
1245 $repl2 = [];
1246 foreach ( $wgUrlProtocols as $prot ) {
1247 if ( substr( $prot, -1 ) === ':' ) {
1248 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1249 }
1250 }
1251 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1252 }
1253 $text = substr( strtr( "\n$text", $repl ), 1 );
1254 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
1255 $text = preg_replace( $repl2, '$1&#58;', $text );
1256 return $text;
1257}
1258
1269function wfSetVar( &$dest, $source, $force = false ) {
1270 $temp = $dest;
1271 if ( $source !== null || $force ) {
1272 $dest = $source;
1273 }
1274 return $temp;
1275}
1276
1286function wfSetBit( &$dest, $bit, $state = true ) {
1287 $temp = (bool)( $dest & $bit );
1288 if ( $state !== null ) {
1289 if ( $state ) {
1290 $dest |= $bit;
1291 } else {
1292 $dest &= ~$bit;
1293 }
1294 }
1295 return $temp;
1296}
1297
1304function wfVarDump( $var ) {
1305 global $wgOut;
1306 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1307 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1308 print $s;
1309 } else {
1310 $wgOut->addHTML( $s );
1311 }
1312}
1313
1321function wfHttpError( $code, $label, $desc ) {
1322 global $wgOut;
1323 HttpStatus::header( $code );
1324 if ( $wgOut ) {
1325 $wgOut->disable();
1326 $wgOut->sendCacheControl();
1327 }
1328
1329 MediaWiki\HeaderCallback::warnIfHeadersSent();
1330 header( 'Content-type: text/html; charset=utf-8' );
1331 ob_start();
1332 print '<!DOCTYPE html>' .
1333 '<html><head><title>' .
1334 htmlspecialchars( $label ) .
1335 '</title></head><body><h1>' .
1336 htmlspecialchars( $label ) .
1337 '</h1><p>' .
1338 nl2br( htmlspecialchars( $desc ) ) .
1339 "</p></body></html>\n";
1340 header( 'Content-Length: ' . ob_get_length() );
1341 ob_end_flush();
1342}
1343
1361function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1362 while ( $status = ob_get_status() ) {
1363 if ( isset( $status['flags'] ) ) {
1364 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1365 $deleteable = ( $status['flags'] & $flags ) === $flags;
1366 } elseif ( isset( $status['del'] ) ) {
1367 $deleteable = $status['del'];
1368 } else {
1369 // Guess that any PHP-internal setting can't be removed.
1370 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1371 }
1372 if ( !$deleteable ) {
1373 // Give up, and hope the result doesn't break
1374 // output behavior.
1375 break;
1376 }
1377 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1378 // Unit testing barrier to prevent this function from breaking PHPUnit.
1379 break;
1380 }
1381 if ( !ob_end_clean() ) {
1382 // Could not remove output buffer handler; abort now
1383 // to avoid getting in some kind of infinite loop.
1384 break;
1385 }
1386 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1387 // Reset the 'Content-Encoding' field set by this handler
1388 // so we can start fresh.
1389 header_remove( 'Content-Encoding' );
1390 break;
1391 }
1392 }
1393}
1394
1410 wfDeprecated( __FUNCTION__, '1.36' );
1411 wfResetOutputBuffers( false );
1412}
1413
1424function 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
1440function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1441 if ( $ts === null ) {
1442 return null;
1443 } else {
1444 return wfTimestamp( $outputtype, $ts );
1445 }
1446}
1447
1453function wfTimestampNow() {
1454 return MWTimestamp::now( TS_MW );
1455}
1456
1462function wfIsWindows() {
1463 return PHP_OS_FAMILY === 'Windows';
1464}
1465
1472function wfIsCLI() {
1473 return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1474}
1475
1487function wfTempDir() {
1488 global $wgTmpDirectory;
1489
1490 if ( $wgTmpDirectory !== false ) {
1491 return $wgTmpDirectory;
1492 }
1493
1494 return TempFSFile::getUsableTempDirectory();
1495}
1496
1506function 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
1549function 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
1574function 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
1603function wfIniGetBool( $setting ) {
1604 return wfStringToBool( ini_get( $setting ) );
1605}
1606
1619function 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
1641function wfEscapeShellArg( ...$args ) {
1642 return Shell::escape( ...$args );
1643}
1644
1669function 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
1722function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1723 return wfShellExec( $cmd, $retval, $environ, $limits,
1724 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1725}
1726
1742function 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
1767function 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
1851function 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
1875function 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
1942function 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
1963 wfDeprecated( __FUNCTION__, '1.39' );
1964 global $wgMiserMode;
1965 return $wgMiserMode
1966 || ( SiteStats::pages() > 100000
1967 && SiteStats::edits() > 1000000
1968 && SiteStats::users() > 10000 );
1969}
1970
1979function wfScript( $script = 'index' ) {
1981 if ( $script === 'index' ) {
1982 return $wgScript;
1983 } elseif ( $script === 'load' ) {
1984 return $wgLoadScript;
1985 } else {
1986 return "{$wgScriptPath}/{$script}.php";
1987 }
1988}
1989
1997function wfBoolToStr( $value ) {
1998 return $value ? 'true' : 'false';
1999}
2000
2006function wfGetNull() {
2007 return wfIsWindows() ? 'NUL' : '/dev/null';
2008}
2009
2019 global $wgIllegalFileChars;
2020 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2021 $name = preg_replace(
2022 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2023 '-',
2024 $name
2025 );
2026 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2027 $name = wfBaseName( $name );
2028 return $name;
2029}
2030
2037function wfMemoryLimit( $newLimit ) {
2038 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2039 // If the INI config is already unlimited, there is nothing larger
2040 if ( $oldLimit != -1 ) {
2041 $newLimit = wfShorthandToInteger( (string)$newLimit );
2042 if ( $newLimit == -1 ) {
2043 wfDebug( "Removing PHP's memory limit" );
2044 AtEase::suppressWarnings();
2045 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
2046 ini_set( 'memory_limit', $newLimit );
2047 AtEase::restoreWarnings();
2048 } elseif ( $newLimit > $oldLimit ) {
2049 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2050 AtEase::suppressWarnings();
2051 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
2052 ini_set( 'memory_limit', $newLimit );
2053 AtEase::restoreWarnings();
2054 }
2055 }
2056}
2057
2066
2067 $timeout = RequestTimeout::singleton();
2068 $timeLimit = $timeout->getWallTimeLimit();
2069 if ( $timeLimit !== INF ) {
2070 // RequestTimeout library is active
2071 if ( $wgTransactionalTimeLimit > $timeLimit ) {
2072 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2073 }
2074 } else {
2075 // Fallback case, likely $wgRequestTimeLimit === null
2076 $timeLimit = (int)ini_get( 'max_execution_time' );
2077 // Note that CLI scripts use 0
2078 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2079 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2080 }
2081 }
2082 ignore_user_abort( true ); // ignore client disconnects
2083
2084 return $timeLimit;
2085}
2086
2094function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2095 $string = trim( $string ?? '' );
2096 if ( $string === '' ) {
2097 return $default;
2098 }
2099 $last = $string[strlen( $string ) - 1];
2100 $val = intval( $string );
2101 switch ( $last ) {
2102 case 'g':
2103 case 'G':
2104 $val *= 1024;
2105 // break intentionally missing
2106 case 'm':
2107 case 'M':
2108 $val *= 1024;
2109 // break intentionally missing
2110 case 'k':
2111 case 'K':
2112 $val *= 1024;
2113 }
2114
2115 return $val;
2116}
2117
2132function wfUnpack( $format, $data, $length = false ) {
2133 if ( $length !== false ) {
2134 $realLen = strlen( $data );
2135 if ( $realLen < $length ) {
2136 throw new MWException( "Tried to use wfUnpack on a "
2137 . "string of length $realLen, but needed one "
2138 . "of at least length $length."
2139 );
2140 }
2141 }
2142
2143 AtEase::suppressWarnings();
2144 $result = unpack( $format, $data );
2145 AtEase::restoreWarnings();
2146
2147 if ( $result === false ) {
2148 // If it cannot extract the packed data.
2149 throw new MWException( "unpack could not unpack binary data" );
2150 }
2151 return $result;
2152}
2153
2161function wfIsInfinity( $str ) {
2162 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2163 return in_array( $str, ExpiryDef::INFINITY_VALS );
2164}
2165
2180function wfThumbIsStandard( File $file, array $params ) {
2182
2183 $multipliers = [ 1 ];
2184 if ( $wgResponsiveImages ) {
2185 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2186 // @see Linker::processResponsiveImages
2187 $multipliers[] = 1.5;
2188 $multipliers[] = 2;
2189 }
2190
2191 $handler = $file->getHandler();
2192 if ( !$handler || !isset( $params['width'] ) ) {
2193 return false;
2194 }
2195
2196 $basicParams = [];
2197 if ( isset( $params['page'] ) ) {
2198 $basicParams['page'] = $params['page'];
2199 }
2200
2201 $thumbLimits = [];
2202 $imageLimits = [];
2203 // Expand limits to account for multipliers
2204 foreach ( $multipliers as $multiplier ) {
2205 $thumbLimits = array_merge( $thumbLimits, array_map(
2206 static function ( $width ) use ( $multiplier ) {
2207 return round( $width * $multiplier );
2208 }, $wgThumbLimits )
2209 );
2210 $imageLimits = array_merge( $imageLimits, array_map(
2211 static function ( $pair ) use ( $multiplier ) {
2212 return [
2213 round( $pair[0] * $multiplier ),
2214 round( $pair[1] * $multiplier ),
2215 ];
2216 }, $wgImageLimits )
2217 );
2218 }
2219
2220 // Check if the width matches one of $wgThumbLimits
2221 if ( in_array( $params['width'], $thumbLimits ) ) {
2222 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2223 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2224 $handler->normaliseParams( $file, $normalParams );
2225 } else {
2226 // If not, then check if the width matches one of $wgImageLimits
2227 $match = false;
2228 foreach ( $imageLimits as $pair ) {
2229 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2230 // Decide whether the thumbnail should be scaled on width or height.
2231 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2232 $handler->normaliseParams( $file, $normalParams );
2233 // Check if this standard thumbnail size maps to the given width
2234 if ( $normalParams['width'] == $params['width'] ) {
2235 $match = true;
2236 break;
2237 }
2238 }
2239 if ( !$match ) {
2240 return false; // not standard for description pages
2241 }
2242 }
2243
2244 // Check that the given values for non-page, non-width, params are just defaults
2245 foreach ( $params as $key => $value ) {
2246 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2247 return false;
2248 }
2249 }
2250
2251 return true;
2252}
2253
2266function wfArrayPlus2d( array $baseArray, array $newValues ) {
2267 // First merge items that are in both arrays
2268 foreach ( $baseArray as $name => &$groupVal ) {
2269 if ( isset( $newValues[$name] ) ) {
2270 $groupVal += $newValues[$name];
2271 }
2272 }
2273 // Now add items that didn't exist yet
2274 $baseArray += $newValues;
2275
2276 return $baseArray;
2277}
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).
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.
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...
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.
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.
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.
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:67
MediaWiki exception.
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
expand(string $url, $defaultProto=PROTO_FALLBACK)
Expand a potentially local URL to a fully-qualified URL.
Definition UrlUtils.php:118
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 edits()
Definition SiteStats.php:95
static users()
static pages()
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
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.
$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.
$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.
$wgCanonicalServer
Config variable stub for the CanonicalServer setting, for use by phpdoc and IDEs.
$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.
$wgHttpsPort
Config variable stub for the HttpsPort setting, for use by phpdoc and IDEs.
while(( $__line=Maintenance::readconsole()) !==false) print
Definition eval.php:69
$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