MediaWiki REL1_41
GlobalFunctions.php
Go to the documentation of this file.
1<?php
34use Wikimedia\AtEase\AtEase;
36use Wikimedia\RequestTimeout\RequestTimeout;
37use Wikimedia\WrappedString;
38
49function wfLoadExtension( $ext, $path = null ) {
50 if ( !$path ) {
52 $path = "$wgExtensionDirectory/$ext/extension.json";
53 }
54 ExtensionRegistry::getInstance()->queue( $path );
55}
56
70function wfLoadExtensions( array $exts ) {
72 $registry = ExtensionRegistry::getInstance();
73 foreach ( $exts as $ext ) {
74 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
75 }
76}
77
86function wfLoadSkin( $skin, $path = null ) {
87 if ( !$path ) {
88 global $wgStyleDirectory;
89 $path = "$wgStyleDirectory/$skin/skin.json";
90 }
91 ExtensionRegistry::getInstance()->queue( $path );
92}
93
101function wfLoadSkins( array $skins ) {
102 global $wgStyleDirectory;
103 $registry = ExtensionRegistry::getInstance();
104 foreach ( $skins as $skin ) {
105 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
106 }
107}
108
115function wfArrayDiff2( $arr1, $arr2 ) {
120 $comparator = static function ( $a, $b ): int {
121 if ( is_string( $a ) && is_string( $b ) ) {
122 return strcmp( $a, $b );
123 }
124 if ( !is_array( $a ) && !is_array( $b ) ) {
125 throw new InvalidArgumentException(
126 'This function assumes that array elements are all strings or all arrays'
127 );
128 }
129 if ( count( $a ) !== count( $b ) ) {
130 return count( $a ) <=> count( $b );
131 } else {
132 reset( $a );
133 reset( $b );
134 while ( key( $a ) !== null && key( $b ) !== null ) {
135 $valueA = current( $a );
136 $valueB = current( $b );
137 $cmp = strcmp( $valueA, $valueB );
138 if ( $cmp !== 0 ) {
139 return $cmp;
140 }
141 next( $a );
142 next( $b );
143 }
144 return 0;
145 }
146 };
147 return array_udiff( $arr1, $arr2, $comparator );
148}
149
169function wfMergeErrorArrays( ...$args ) {
170 $out = [];
171 foreach ( $args as $errors ) {
172 foreach ( $errors as $params ) {
173 $originalParams = $params;
174 if ( $params[0] instanceof MessageSpecifier ) {
175 $msg = $params[0];
176 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
177 }
178 # @todo FIXME: Sometimes get nested arrays for $params,
179 # which leads to E_NOTICEs
180 $spec = implode( "\t", $params );
181 $out[$spec] = $originalParams;
182 }
183 }
184 return array_values( $out );
185}
186
196function wfArrayInsertAfter( array $array, array $insert, $after ) {
197 // Find the offset of the element to insert after.
198 $keys = array_keys( $array );
199 $offsetByKey = array_flip( $keys );
200
201 if ( !\array_key_exists( $after, $offsetByKey ) ) {
202 return $array;
203 }
204 $offset = $offsetByKey[$after];
205
206 // Insert at the specified offset
207 $before = array_slice( $array, 0, $offset + 1, true );
208 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
209
210 $output = $before + $insert + $after;
211
212 return $output;
213}
214
223function wfObjectToArray( $objOrArray, $recursive = true ) {
224 $array = [];
225 if ( is_object( $objOrArray ) ) {
226 $objOrArray = get_object_vars( $objOrArray );
227 }
228 foreach ( $objOrArray as $key => $value ) {
229 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
230 $value = wfObjectToArray( $value );
231 }
232
233 $array[$key] = $value;
234 }
235
236 return $array;
237}
238
249function wfRandom() {
250 // The maximum random value is "only" 2^31-1, so get two random
251 // values to reduce the chance of dupes
252 $max = mt_getrandmax() + 1;
253 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
254 return $rand;
255}
256
267function wfRandomString( $length = 32 ) {
268 $str = '';
269 for ( $n = 0; $n < $length; $n += 7 ) {
270 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
271 }
272 return substr( $str, 0, $length );
273}
274
302function wfUrlencode( $s ) {
303 static $needle;
304
305 if ( $s === null ) {
306 // Reset $needle for testing.
307 $needle = null;
308 return '';
309 }
310
311 if ( $needle === null ) {
312 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
313 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
314 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
315 ) {
316 $needle[] = '%3A';
317 }
318 }
319
320 $s = urlencode( $s );
321 $s = str_ireplace(
322 $needle,
323 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
324 $s
325 );
326
327 return $s;
328}
329
340function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
341 if ( $array2 !== null ) {
342 $array1 += $array2;
343 }
344
345 $cgi = '';
346 foreach ( $array1 as $key => $value ) {
347 if ( $value !== null && $value !== false ) {
348 if ( $cgi != '' ) {
349 $cgi .= '&';
350 }
351 if ( $prefix !== '' ) {
352 $key = $prefix . "[$key]";
353 }
354 if ( is_array( $value ) ) {
355 $firstTime = true;
356 foreach ( $value as $k => $v ) {
357 $cgi .= $firstTime ? '' : '&';
358 if ( is_array( $v ) ) {
359 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
360 } else {
361 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
362 }
363 $firstTime = false;
364 }
365 } else {
366 if ( is_object( $value ) ) {
367 $value = $value->__toString();
368 }
369 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
370 }
371 }
372 }
373 return $cgi;
374}
375
385function wfCgiToArray( $query ) {
386 if ( isset( $query[0] ) && $query[0] == '?' ) {
387 $query = substr( $query, 1 );
388 }
389 $bits = explode( '&', $query );
390 $ret = [];
391 foreach ( $bits as $bit ) {
392 if ( $bit === '' ) {
393 continue;
394 }
395 if ( strpos( $bit, '=' ) === false ) {
396 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
397 $key = $bit;
398 $value = '';
399 } else {
400 [ $key, $value ] = explode( '=', $bit );
401 }
402 $key = urldecode( $key );
403 $value = urldecode( $value );
404 if ( strpos( $key, '[' ) !== false ) {
405 $keys = array_reverse( explode( '[', $key ) );
406 $key = array_pop( $keys );
407 $temp = $value;
408 foreach ( $keys as $k ) {
409 $k = substr( $k, 0, -1 );
410 $temp = [ $k => $temp ];
411 }
412 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
413 $ret[$key] = array_merge( $ret[$key], $temp );
414 } else {
415 $ret[$key] = $temp;
416 }
417 } else {
418 $ret[$key] = $value;
419 }
420 }
421 return $ret;
422}
423
432function wfAppendQuery( $url, $query ) {
433 if ( is_array( $query ) ) {
434 $query = wfArrayToCgi( $query );
435 }
436 if ( $query != '' ) {
437 // Remove the fragment, if there is one
438 $fragment = false;
439 $hashPos = strpos( $url, '#' );
440 if ( $hashPos !== false ) {
441 $fragment = substr( $url, $hashPos );
442 $url = substr( $url, 0, $hashPos );
443 }
444
445 // Add parameter
446 if ( strpos( $url, '?' ) === false ) {
447 $url .= '?';
448 } else {
449 $url .= '&';
450 }
451 $url .= $query;
452
453 // Put the fragment back
454 if ( $fragment !== false ) {
455 $url .= $fragment;
456 }
457 }
458 return $url;
459}
460
469
470 if ( MediaWikiServices::hasInstance() ) {
471 $services = MediaWikiServices::getInstance();
472 if ( $services->hasService( 'UrlUtils' ) ) {
473 return $services->getUrlUtils();
474 }
475 }
476
477 return new UrlUtils( [
478 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
479 // implementations implicitly converted it to an empty string (presumably by mistake).
480 // Preserve the old behavior for compatibility.
481 UrlUtils::SERVER => $wgServer ?? '',
482 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
483 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
484 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
485 : WebRequest::detectProtocol(),
486 UrlUtils::HTTPS_PORT => $wgHttpsPort,
487 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
488 ] );
489}
490
518function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
519 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
520}
521
531function wfGetServerUrl( $proto ) {
532 return wfGetUrlUtils()->getServer( $proto ) ?? '';
533}
534
547function wfAssembleUrl( $urlParts ) {
548 return UrlUtils::assemble( (array)$urlParts );
549}
550
561function wfRemoveDotSegments( $urlPath ) {
562 return UrlUtils::removeDotSegments( (string)$urlPath );
563}
564
573function wfUrlProtocols( $includeProtocolRelative = true ) {
574 $method = $includeProtocolRelative ? 'validProtocols' : 'validAbsoluteProtocols';
575 return wfGetUrlUtils()->$method();
576}
577
586 return wfGetUrlUtils()->validAbsoluteProtocols();
587}
588
615function wfParseUrl( $url ) {
616 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
617}
618
628function wfExpandIRI( $url ) {
629 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
630}
631
640function wfMatchesDomainList( $url, $domains ) {
641 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
642}
643
664function wfDebug( $text, $dest = 'all', array $context = [] ) {
666
667 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
668 return;
669 }
670
671 $text = trim( $text );
672
673 if ( $wgDebugLogPrefix !== '' ) {
674 $context['prefix'] = $wgDebugLogPrefix;
675 }
676 $context['private'] = ( $dest === false || $dest === 'private' );
677
678 $logger = LoggerFactory::getInstance( 'wfDebug' );
679 $logger->debug( $text, $context );
680}
681
687 static $cache;
688 if ( $cache !== null ) {
689 return $cache;
690 }
691 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
692 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
693 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
694 || MW_ENTRY_POINT === 'load'
695 ) {
696 $cache = true;
697 } else {
698 $cache = false;
699 }
700 return $cache;
701}
702
728function wfDebugLog(
729 $logGroup, $text, $dest = 'all', array $context = []
730) {
731 $text = trim( $text );
732
733 $logger = LoggerFactory::getInstance( $logGroup );
734 $context['private'] = ( $dest === false || $dest === 'private' );
735 $logger->info( $text, $context );
736}
737
746function wfLogDBError( $text, array $context = [] ) {
747 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
748 $logger->error( trim( $text ), $context );
749}
750
767function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
768 if ( !is_string( $version ) && $version !== false ) {
769 throw new InvalidArgumentException(
770 "MediaWiki version must either be a string or false. " .
771 "Example valid version: '1.33'"
772 );
773 }
774
775 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
776}
777
798function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
799 MWDebug::deprecatedMsg( $msg, $version, $component,
800 $callerOffset === false ? false : $callerOffset + 1 );
801}
802
813function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
814 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
815}
816
826function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
827 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
828}
829
846function wfGetLangObj( $langcode = false ) {
847 wfDeprecated( __FUNCTION__, '1.41' );
848 # Identify which language to get or create a language object for.
849 # Using is_object here due to Stub objects.
850 if ( is_object( $langcode ) ) {
851 # Great, we already have the object (hopefully)!
852 return $langcode;
853 }
854
855 global $wgLanguageCode;
856 $services = MediaWikiServices::getInstance();
857 if ( $langcode === true || $langcode === $wgLanguageCode ) {
858 # $langcode is the language code of the wikis content language object.
859 # or it is a boolean and value is true
860 return $services->getContentLanguage();
861 }
862
863 global $wgLang;
864 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
865 # $langcode is the language code of user language object.
866 # or it was a boolean and value is false
867 return $wgLang;
868 }
869
870 $languageNames = $services->getLanguageNameUtils()->getLanguageNames();
871 // FIXME: Can we use isSupportedLanguage here?
872 if ( isset( $languageNames[$langcode] ) ) {
873 # $langcode corresponds to a valid language.
874 return $services->getLanguageFactory()->getLanguage( $langcode );
875 }
876
877 # $langcode is a string, but not a valid language code; use content language.
878 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
879 return $services->getContentLanguage();
880}
881
903function wfMessage( $key, ...$params ) {
904 if ( is_array( $key ) ) {
905 // Fallback keys are not allowed in message specifiers
906 $message = wfMessageFallback( ...$key );
907 } else {
908 $message = Message::newFromSpecifier( $key );
909 }
910
911 // We call Message::params() to reduce code duplication
912 if ( $params ) {
913 $message->params( ...$params );
914 }
915
916 return $message;
917}
918
931function wfMessageFallback( ...$keys ) {
932 return Message::newFallbackSequence( ...$keys );
933}
934
943function wfMsgReplaceArgs( $message, $args ) {
944 # Fix windows line-endings
945 # Some messages are split with explode("\n", $msg)
946 $message = str_replace( "\r", '', $message );
947
948 // Replace arguments
949 if ( is_array( $args ) && $args ) {
950 if ( is_array( $args[0] ) ) {
951 $args = array_values( $args[0] );
952 }
953 $replacementKeys = [];
954 foreach ( $args as $n => $param ) {
955 $replacementKeys['$' . ( $n + 1 )] = $param;
956 }
957 $message = strtr( $message, $replacementKeys );
958 }
959
960 return $message;
961}
962
971function wfHostname() {
972 // Hostname overriding
973 global $wgOverrideHostname;
974 if ( $wgOverrideHostname !== false ) {
975 return $wgOverrideHostname;
976 }
977
978 return php_uname( 'n' ) ?: 'unknown';
979}
980
993function wfReportTime( $nonce = null, $triggerWarnings = true ) {
994 global $wgShowHostnames;
995
996 if ( $triggerWarnings ) {
997 wfDeprecated( __FUNCTION__, '1.40' );
998 }
999 $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1000 // seconds to milliseconds
1001 $responseTime = round( $elapsed * 1000 );
1002 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1003 if ( $wgShowHostnames ) {
1004 $reportVars['wgHostname'] = wfHostname();
1005 }
1006
1007 return (
1008 ResourceLoader::makeInlineScript(
1009 ResourceLoader::makeConfigSetScript( $reportVars )
1010 )
1011 );
1012}
1013
1024function wfDebugBacktrace( $limit = 0 ) {
1025 static $disabled = null;
1026
1027 if ( $disabled === null ) {
1028 $disabled = !function_exists( 'debug_backtrace' );
1029 if ( $disabled ) {
1030 wfDebug( "debug_backtrace() is disabled" );
1031 }
1032 }
1033 if ( $disabled ) {
1034 return [];
1035 }
1036
1037 if ( $limit ) {
1038 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1039 } else {
1040 return array_slice( debug_backtrace(), 1 );
1041 }
1042}
1043
1052function wfBacktrace( $raw = null ) {
1053 global $wgCommandLineMode;
1054
1055 if ( $raw ?? $wgCommandLineMode ) {
1056 $frameFormat = "%s line %s calls %s()\n";
1057 $traceFormat = "%s";
1058 } else {
1059 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1060 $traceFormat = "<ul>\n%s</ul>\n";
1061 }
1062
1063 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1064 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1065 $line = $frame['line'] ?? '-';
1066 $call = $frame['function'];
1067 if ( !empty( $frame['class'] ) ) {
1068 $call = $frame['class'] . $frame['type'] . $call;
1069 }
1070 return sprintf( $frameFormat, $file, $line, $call );
1071 }, wfDebugBacktrace() );
1072
1073 return sprintf( $traceFormat, implode( '', $frames ) );
1074}
1075
1085function wfGetCaller( $level = 2 ) {
1086 $backtrace = wfDebugBacktrace( $level + 1 );
1087 if ( isset( $backtrace[$level] ) ) {
1088 return wfFormatStackFrame( $backtrace[$level] );
1089 } else {
1090 return 'unknown';
1091 }
1092}
1093
1101function wfGetAllCallers( $limit = 3 ) {
1102 $trace = array_reverse( wfDebugBacktrace() );
1103 if ( !$limit || $limit > count( $trace ) - 1 ) {
1104 $limit = count( $trace ) - 1;
1105 }
1106 $trace = array_slice( $trace, -$limit - 1, $limit );
1107 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1108}
1109
1116function wfFormatStackFrame( $frame ) {
1117 if ( !isset( $frame['function'] ) ) {
1118 return 'NO_FUNCTION_GIVEN';
1119 }
1120 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1121 $frame['class'] . $frame['type'] . $frame['function'] :
1122 $frame['function'];
1123}
1124
1134function wfClientAcceptsGzip( $force = false ) {
1135 static $result = null;
1136 if ( $result === null || $force ) {
1137 $result = false;
1138 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1139 # @todo FIXME: We may want to disallow some broken browsers
1140 $m = [];
1141 if ( preg_match(
1142 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1143 $_SERVER['HTTP_ACCEPT_ENCODING'],
1144 $m
1145 )
1146 ) {
1147 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1148 return $result;
1149 }
1150 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1151 $result = true;
1152 }
1153 }
1154 }
1155 return $result;
1156}
1157
1168function wfEscapeWikiText( $text ) {
1169 global $wgEnableMagicLinks;
1170 static $repl = null, $repl2 = null;
1171 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1172 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1173 // in those situations
1174 $repl = [
1175 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1176 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1177 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1178 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1179 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1180 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1181 "\n " => "\n&#32;", "\r " => "\r&#32;",
1182 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1183 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1184 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1185 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1186 '__' => '_&#95;', '://' => '&#58;//',
1187 ];
1188
1189 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1190 // We have to catch everything "\s" matches in PCRE
1191 foreach ( $magicLinks as $magic ) {
1192 $repl["$magic "] = "$magic&#32;";
1193 $repl["$magic\t"] = "$magic&#9;";
1194 $repl["$magic\r"] = "$magic&#13;";
1195 $repl["$magic\n"] = "$magic&#10;";
1196 $repl["$magic\f"] = "$magic&#12;";
1197 }
1198
1199 // And handle protocols that don't use "://"
1200 global $wgUrlProtocols;
1201 $repl2 = [];
1202 foreach ( $wgUrlProtocols as $prot ) {
1203 if ( substr( $prot, -1 ) === ':' ) {
1204 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1205 }
1206 }
1207 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1208 }
1209 $text = substr( strtr( "\n$text", $repl ), 1 );
1210 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
1211 $text = preg_replace( $repl2, '$1&#58;', $text );
1212 return $text;
1213}
1214
1225function wfSetVar( &$dest, $source, $force = false ) {
1226 $temp = $dest;
1227 if ( $source !== null || $force ) {
1228 $dest = $source;
1229 }
1230 return $temp;
1231}
1232
1242function wfSetBit( &$dest, $bit, $state = true ) {
1243 $temp = (bool)( $dest & $bit );
1244 if ( $state !== null ) {
1245 if ( $state ) {
1246 $dest |= $bit;
1247 } else {
1248 $dest &= ~$bit;
1249 }
1250 }
1251 return $temp;
1252}
1253
1260function wfVarDump( $var ) {
1261 global $wgOut;
1262 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1263 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1264 print $s;
1265 } else {
1266 $wgOut->addHTML( $s );
1267 }
1268}
1269
1277function wfHttpError( $code, $label, $desc ) {
1278 global $wgOut;
1279 HttpStatus::header( $code );
1280 if ( $wgOut ) {
1281 $wgOut->disable();
1282 $wgOut->sendCacheControl();
1283 }
1284
1285 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1286 header( 'Content-type: text/html; charset=utf-8' );
1287 ob_start();
1288 print '<!DOCTYPE html>' .
1289 '<html><head><title>' .
1290 htmlspecialchars( $label ) .
1291 '</title></head><body><h1>' .
1292 htmlspecialchars( $label ) .
1293 '</h1><p>' .
1294 nl2br( htmlspecialchars( $desc ) ) .
1295 "</p></body></html>\n";
1296 header( 'Content-Length: ' . ob_get_length() );
1297 ob_end_flush();
1298}
1299
1320function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1321 while ( $status = ob_get_status() ) {
1322 if ( isset( $status['flags'] ) ) {
1323 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1324 $deleteable = ( $status['flags'] & $flags ) === $flags;
1325 } elseif ( isset( $status['del'] ) ) {
1326 $deleteable = $status['del'];
1327 } else {
1328 // Guess that any PHP-internal setting can't be removed.
1329 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1330 }
1331 if ( !$deleteable ) {
1332 // Give up, and hope the result doesn't break
1333 // output behavior.
1334 break;
1335 }
1336 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1337 // Unit testing barrier to prevent this function from breaking PHPUnit.
1338 break;
1339 }
1340 if ( !ob_end_clean() ) {
1341 // Could not remove output buffer handler; abort now
1342 // to avoid getting in some kind of infinite loop.
1343 break;
1344 }
1345 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1346 // Reset the 'Content-Encoding' field set by this handler
1347 // so we can start fresh.
1348 header_remove( 'Content-Encoding' );
1349 break;
1350 }
1351 }
1352}
1353
1364function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1365 $ret = MWTimestamp::convert( $outputtype, $ts );
1366 if ( $ret === false ) {
1367 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1368 }
1369 return $ret;
1370}
1371
1380function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1381 if ( $ts === null ) {
1382 return null;
1383 } else {
1384 return wfTimestamp( $outputtype, $ts );
1385 }
1386}
1387
1393function wfTimestampNow() {
1394 return MWTimestamp::now( TS_MW );
1395}
1396
1408function wfTempDir() {
1409 global $wgTmpDirectory;
1410
1411 if ( $wgTmpDirectory !== false ) {
1412 return $wgTmpDirectory;
1413 }
1414
1415 return TempFSFile::getUsableTempDirectory();
1416}
1417
1427function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1428 global $wgDirectoryMode;
1429
1430 if ( FileBackend::isStoragePath( $dir ) ) {
1431 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1432 }
1433
1434 if ( $caller !== null ) {
1435 wfDebug( "$caller: called wfMkdirParents($dir)" );
1436 }
1437
1438 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1439 return true;
1440 }
1441
1442 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1443
1444 if ( $mode === null ) {
1445 $mode = $wgDirectoryMode;
1446 }
1447
1448 // Turn off the normal warning, we're doing our own below
1449 AtEase::suppressWarnings();
1450 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1451 AtEase::restoreWarnings();
1452
1453 if ( !$ok ) {
1454 // directory may have been created on another request since we last checked
1455 if ( is_dir( $dir ) ) {
1456 return true;
1457 }
1458
1459 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1460 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1461 }
1462 return $ok;
1463}
1464
1470function wfRecursiveRemoveDir( $dir ) {
1471 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1472 if ( is_dir( $dir ) ) {
1473 $objects = scandir( $dir );
1474 foreach ( $objects as $object ) {
1475 if ( $object != "." && $object != ".." ) {
1476 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1477 wfRecursiveRemoveDir( $dir . '/' . $object );
1478 } else {
1479 unlink( $dir . '/' . $object );
1480 }
1481 }
1482 }
1483 rmdir( $dir );
1484 }
1485}
1486
1493function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1494 $accForFormat = $acc >= 0 ? $acc : 0;
1495 $ret = sprintf( "%.{$accForFormat}f", $nr );
1496 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1497}
1498
1522function wfIniGetBool( $setting ) {
1523 return wfStringToBool( ini_get( $setting ) );
1524}
1525
1538function wfStringToBool( $val ) {
1539 $val = strtolower( $val );
1540 // 'on' and 'true' can't have whitespace around them, but '1' can.
1541 return $val == 'on'
1542 || $val == 'true'
1543 || $val == 'yes'
1544 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1545}
1546
1560function wfEscapeShellArg( ...$args ) {
1561 return Shell::escape( ...$args );
1562}
1563
1588function wfShellExec( $cmd, &$retval = null, $environ = [],
1589 $limits = [], $options = []
1590) {
1591 if ( Shell::isDisabled() ) {
1592 $retval = 1;
1593 // Backwards compatibility be upon us...
1594 return 'Unable to run external programs, proc_open() is disabled.';
1595 }
1596
1597 if ( is_array( $cmd ) ) {
1598 $cmd = Shell::escape( $cmd );
1599 }
1600
1601 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1602 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1603
1604 try {
1605 $result = Shell::command( [] )
1606 ->unsafeParams( (array)$cmd )
1607 ->environment( $environ )
1608 ->limits( $limits )
1609 ->includeStderr( $includeStderr )
1610 ->profileMethod( $profileMethod )
1611 // For b/c
1612 ->restrict( Shell::RESTRICT_NONE )
1613 ->execute();
1614 } catch ( ProcOpenError $ex ) {
1615 $retval = -1;
1616 return '';
1617 }
1618
1619 $retval = $result->getExitCode();
1620
1621 return $result->getStdout();
1622}
1623
1641function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1642 return wfShellExec( $cmd, $retval, $environ, $limits,
1643 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1644}
1645
1661function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1662 global $wgPhpCli;
1663 // Give site config file a chance to run the script in a wrapper.
1664 // The caller may likely want to call wfBasename() on $script.
1665 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1666 ->onWfShellWikiCmd( $script, $parameters, $options );
1667 $cmd = [ $options['php'] ?? $wgPhpCli ];
1668 if ( isset( $options['wrapper'] ) ) {
1669 $cmd[] = $options['wrapper'];
1670 }
1671 $cmd[] = $script;
1672 // Escape each parameter for shell
1673 return Shell::escape( array_merge( $cmd, $parameters ) );
1674}
1675
1692function wfMerge(
1693 string $old,
1694 string $mine,
1695 string $yours,
1696 ?string &$simplisticMergeAttempt,
1697 string &$mergeLeftovers = null
1698): bool {
1699 global $wgDiff3;
1700
1701 # This check may also protect against code injection in
1702 # case of broken installations.
1703 AtEase::suppressWarnings();
1704 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1705 AtEase::restoreWarnings();
1706
1707 if ( !$haveDiff3 ) {
1708 wfDebug( "diff3 not found" );
1709 return false;
1710 }
1711
1712 # Make temporary files
1713 $td = wfTempDir();
1714 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1715 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1716 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1717
1718 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1719 # a newline character. To avoid this, we normalize the trailing whitespace before
1720 # creating the diff.
1721
1722 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1723 fclose( $oldtextFile );
1724 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1725 fclose( $mytextFile );
1726 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1727 fclose( $yourtextFile );
1728
1729 # Check for a conflict
1730 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1731 $oldtextName, $yourtextName );
1732 $handle = popen( $cmd, 'r' );
1733
1734 $mergeLeftovers = '';
1735 do {
1736 $data = fread( $handle, 8192 );
1737 if ( strlen( $data ) == 0 ) {
1738 break;
1739 }
1740 $mergeLeftovers .= $data;
1741 } while ( true );
1742 pclose( $handle );
1743
1744 $conflict = $mergeLeftovers !== '';
1745
1746 # Merge differences automatically where possible, preferring "my" text for conflicts.
1747 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1748 $oldtextName, $yourtextName );
1749 $handle = popen( $cmd, 'r' );
1750 $simplisticMergeAttempt = '';
1751 do {
1752 $data = fread( $handle, 8192 );
1753 if ( strlen( $data ) == 0 ) {
1754 break;
1755 }
1756 $simplisticMergeAttempt .= $data;
1757 } while ( true );
1758 pclose( $handle );
1759 unlink( $mytextName );
1760 unlink( $oldtextName );
1761 unlink( $yourtextName );
1762
1763 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1764 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1765 $conflict = true;
1766 }
1767 return !$conflict;
1768}
1769
1782function wfBaseName( $path, $suffix = '' ) {
1783 if ( $suffix == '' ) {
1784 $encSuffix = '';
1785 } else {
1786 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1787 }
1788
1789 $matches = [];
1790 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1791 return $matches[1];
1792 } else {
1793 return '';
1794 }
1795}
1796
1806function wfRelativePath( $path, $from ) {
1807 // Normalize mixed input on Windows...
1808 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1809 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1810
1811 // Trim trailing slashes -- fix for drive root
1812 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1813 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1814
1815 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1816 $against = explode( DIRECTORY_SEPARATOR, $from );
1817
1818 if ( $pieces[0] !== $against[0] ) {
1819 // Non-matching Windows drive letters?
1820 // Return a full path.
1821 return $path;
1822 }
1823
1824 // Trim off common prefix
1825 while ( count( $pieces ) && count( $against )
1826 && $pieces[0] == $against[0] ) {
1827 array_shift( $pieces );
1828 array_shift( $against );
1829 }
1830
1831 // relative dots to bump us to the parent
1832 while ( count( $against ) ) {
1833 array_unshift( $pieces, '..' );
1834 array_shift( $against );
1835 }
1836
1837 $pieces[] = wfBaseName( $path );
1838
1839 return implode( DIRECTORY_SEPARATOR, $pieces );
1840}
1841
1873function wfGetDB( $db, $groups = [], $wiki = false ) {
1874 if ( $wiki === false ) {
1875 return MediaWikiServices::getInstance()
1876 ->getDBLoadBalancer()
1877 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1878 } else {
1879 return MediaWikiServices::getInstance()
1880 ->getDBLoadBalancerFactory()
1881 ->getMainLB( $wiki )
1882 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1883 }
1884}
1885
1895function wfScript( $script = 'index' ) {
1897 if ( $script === 'index' ) {
1898 return $wgScript;
1899 } elseif ( $script === 'load' ) {
1900 return $wgLoadScript;
1901 } else {
1902 return "{$wgScriptPath}/{$script}.php";
1903 }
1904}
1905
1913function wfBoolToStr( $value ) {
1914 return $value ? 'true' : 'false';
1915}
1916
1922function wfGetNull() {
1923 return wfIsWindows() ? 'NUL' : '/dev/null';
1924}
1925
1935 global $wgIllegalFileChars;
1936 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1937 $name = preg_replace(
1938 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1939 '-',
1940 $name
1941 );
1942 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1943 $name = wfBaseName( $name );
1944 return $name;
1945}
1946
1953function wfMemoryLimit( $newLimit ) {
1954 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1955 // If the INI config is already unlimited, there is nothing larger
1956 if ( $oldLimit != -1 ) {
1957 $newLimit = wfShorthandToInteger( (string)$newLimit );
1958 if ( $newLimit == -1 ) {
1959 wfDebug( "Removing PHP's memory limit" );
1960 AtEase::suppressWarnings();
1961 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1962 ini_set( 'memory_limit', $newLimit );
1963 AtEase::restoreWarnings();
1964 } elseif ( $newLimit > $oldLimit ) {
1965 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1966 AtEase::suppressWarnings();
1967 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1968 ini_set( 'memory_limit', $newLimit );
1969 AtEase::restoreWarnings();
1970 }
1971 }
1972}
1973
1982
1983 $timeout = RequestTimeout::singleton();
1984 $timeLimit = $timeout->getWallTimeLimit();
1985 if ( $timeLimit !== INF ) {
1986 // RequestTimeout library is active
1987 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1988 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1989 }
1990 } else {
1991 // Fallback case, likely $wgRequestTimeLimit === null
1992 $timeLimit = (int)ini_get( 'max_execution_time' );
1993 // Note that CLI scripts use 0
1994 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
1995 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1996 }
1997 }
1998 ignore_user_abort( true ); // ignore client disconnects
1999
2000 return $timeLimit;
2001}
2002
2010function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2011 $string = trim( $string ?? '' );
2012 if ( $string === '' ) {
2013 return $default;
2014 }
2015 $last = $string[strlen( $string ) - 1];
2016 $val = intval( $string );
2017 switch ( $last ) {
2018 case 'g':
2019 case 'G':
2020 $val *= 1024;
2021 // break intentionally missing
2022 case 'm':
2023 case 'M':
2024 $val *= 1024;
2025 // break intentionally missing
2026 case 'k':
2027 case 'K':
2028 $val *= 1024;
2029 }
2030
2031 return $val;
2032}
2033
2048function wfUnpack( $format, $data, $length = false ) {
2049 if ( $length !== false ) {
2050 $realLen = strlen( $data );
2051 if ( $realLen < $length ) {
2052 throw new MWException( "Tried to use wfUnpack on a "
2053 . "string of length $realLen, but needed one "
2054 . "of at least length $length."
2055 );
2056 }
2057 }
2058
2059 AtEase::suppressWarnings();
2060 $result = unpack( $format, $data );
2061 AtEase::restoreWarnings();
2062
2063 if ( $result === false ) {
2064 // If it cannot extract the packed data.
2065 throw new MWException( "unpack could not unpack binary data" );
2066 }
2067 return $result;
2068}
2069
2077function wfIsInfinity( $str ) {
2078 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2079 return in_array( $str, ExpiryDef::INFINITY_VALS );
2080}
2081
2096function wfThumbIsStandard( File $file, array $params ) {
2098
2099 $multipliers = [ 1 ];
2100 if ( $wgResponsiveImages ) {
2101 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2102 // @see Linker::processResponsiveImages
2103 $multipliers[] = 1.5;
2104 $multipliers[] = 2;
2105 }
2106
2107 $handler = $file->getHandler();
2108 if ( !$handler || !isset( $params['width'] ) ) {
2109 return false;
2110 }
2111
2112 $basicParams = [];
2113 if ( isset( $params['page'] ) ) {
2114 $basicParams['page'] = $params['page'];
2115 }
2116
2117 $thumbLimits = [];
2118 $imageLimits = [];
2119 // Expand limits to account for multipliers
2120 foreach ( $multipliers as $multiplier ) {
2121 $thumbLimits = array_merge( $thumbLimits, array_map(
2122 static function ( $width ) use ( $multiplier ) {
2123 return round( $width * $multiplier );
2124 }, $wgThumbLimits )
2125 );
2126 $imageLimits = array_merge( $imageLimits, array_map(
2127 static function ( $pair ) use ( $multiplier ) {
2128 return [
2129 round( $pair[0] * $multiplier ),
2130 round( $pair[1] * $multiplier ),
2131 ];
2132 }, $wgImageLimits )
2133 );
2134 }
2135
2136 // Check if the width matches one of $wgThumbLimits
2137 if ( in_array( $params['width'], $thumbLimits ) ) {
2138 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2139 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2140 $handler->normaliseParams( $file, $normalParams );
2141 } else {
2142 // If not, then check if the width matches one of $wgImageLimits
2143 $match = false;
2144 foreach ( $imageLimits as $pair ) {
2145 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2146 // Decide whether the thumbnail should be scaled on width or height.
2147 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2148 $handler->normaliseParams( $file, $normalParams );
2149 // Check if this standard thumbnail size maps to the given width
2150 if ( $normalParams['width'] == $params['width'] ) {
2151 $match = true;
2152 break;
2153 }
2154 }
2155 if ( !$match ) {
2156 return false; // not standard for description pages
2157 }
2158 }
2159
2160 // Check that the given values for non-page, non-width, params are just defaults
2161 foreach ( $params as $key => $value ) {
2162 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2163 return false;
2164 }
2165 }
2166
2167 return true;
2168}
2169
2182function wfArrayPlus2d( array $baseArray, array $newValues ) {
2183 // First merge items that are in both arrays
2184 foreach ( $baseArray as $name => &$groupVal ) {
2185 if ( isset( $newValues[$name] ) ) {
2186 $groupVal += $newValues[$name];
2187 }
2188 }
2189 // Now add items that didn't exist yet
2190 $baseArray += $newValues;
2191
2192 return $baseArray;
2193}
wfIsWindows()
Check if the operating system is Windows.
const PROTO_CURRENT
Definition Defines.php:196
if(MW_ENTRY_POINT==='index') 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()
wfReportTime( $nonce=null, $triggerWarnings=true)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfLoadExtension( $ext, $path=null)
Load an extension.
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfArrayDiff2( $arr1, $arr2)
Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfGetUrlUtils()
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL using $wgServer (or one of its alternatives).
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfPercent( $nr, int $acc=2, bool $round=true)
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfGetNull()
Get a platform-independent path to the null file, e.g.
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
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 URL path to a MediaWiki entry point.
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfLoadExtensions(array $exts)
Load multiple extensions at once.
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
wfArrayInsertAfter(array $array, array $insert, $after)
Insert an array into another array after the specified key.
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
global $wgRequest
Definition Setup.php:414
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode $wgLang
Definition Setup.php:535
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode $wgOut
Definition Setup.php:535
const MW_ENTRY_POINT
Definition api.php:44
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:70
MediaWiki exception.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Create PSR-3 logger objects.
Service locator for MediaWiki core services.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
ResourceLoader is a loading system for JavaScript and CSS resources.
Executes shell commands.
Definition Shell.php:46
Stub object for the user language.
Represents a title within MediaWiki.
Definition Title.php:76
Library for creating and parsing MW-style timestamps.
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 using $wgServer (or one of its alternatives).
Definition UrlUtils.php:125
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition Message.php:461
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition Message.php:427
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.
$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.
$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