MediaWiki 1.40.4
GlobalFunctions.php
Go to the documentation of this file.
1<?php
31use Wikimedia\AtEase\AtEase;
33use Wikimedia\RequestTimeout\RequestTimeout;
34use Wikimedia\WrappedString;
35
46function wfLoadExtension( $ext, $path = null ) {
47 if ( !$path ) {
49 $path = "$wgExtensionDirectory/$ext/extension.json";
50 }
51 ExtensionRegistry::getInstance()->queue( $path );
52}
53
67function wfLoadExtensions( array $exts ) {
69 $registry = ExtensionRegistry::getInstance();
70 foreach ( $exts as $ext ) {
71 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
72 }
73}
74
83function wfLoadSkin( $skin, $path = null ) {
84 if ( !$path ) {
85 global $wgStyleDirectory;
86 $path = "$wgStyleDirectory/$skin/skin.json";
87 }
88 ExtensionRegistry::getInstance()->queue( $path );
89}
90
98function wfLoadSkins( array $skins ) {
99 global $wgStyleDirectory;
100 $registry = ExtensionRegistry::getInstance();
101 foreach ( $skins as $skin ) {
102 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
103 }
104}
105
112function wfArrayDiff2( $arr1, $arr2 ) {
117 $comparator = static function ( $a, $b ): int {
118 if ( is_string( $a ) && is_string( $b ) ) {
119 return strcmp( $a, $b );
120 }
121 if ( !is_array( $a ) && !is_array( $b ) ) {
122 throw new InvalidArgumentException(
123 'This function assumes that array elements are all strings or all arrays'
124 );
125 }
126 if ( count( $a ) !== count( $b ) ) {
127 return count( $a ) <=> count( $b );
128 } else {
129 reset( $a );
130 reset( $b );
131 while ( key( $a ) !== null && key( $b ) !== null ) {
132 $valueA = current( $a );
133 $valueB = current( $b );
134 $cmp = strcmp( $valueA, $valueB );
135 if ( $cmp !== 0 ) {
136 return $cmp;
137 }
138 next( $a );
139 next( $b );
140 }
141 return 0;
142 }
143 };
144 return array_udiff( $arr1, $arr2, $comparator );
145}
146
166function wfMergeErrorArrays( ...$args ) {
167 $out = [];
168 foreach ( $args as $errors ) {
169 foreach ( $errors as $params ) {
170 $originalParams = $params;
171 if ( $params[0] instanceof MessageSpecifier ) {
172 $msg = $params[0];
173 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
174 }
175 # @todo FIXME: Sometimes get nested arrays for $params,
176 # which leads to E_NOTICEs
177 $spec = implode( "\t", $params );
178 $out[$spec] = $originalParams;
179 }
180 }
181 return array_values( $out );
182}
183
193function wfArrayInsertAfter( array $array, array $insert, $after ) {
194 // Find the offset of the element to insert after.
195 $keys = array_keys( $array );
196 $offsetByKey = array_flip( $keys );
197
198 if ( !\array_key_exists( $after, $offsetByKey ) ) {
199 return $array;
200 }
201 $offset = $offsetByKey[$after];
202
203 // Insert at the specified offset
204 $before = array_slice( $array, 0, $offset + 1, true );
205 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
206
207 $output = $before + $insert + $after;
208
209 return $output;
210}
211
220function wfObjectToArray( $objOrArray, $recursive = true ) {
221 $array = [];
222 if ( is_object( $objOrArray ) ) {
223 $objOrArray = get_object_vars( $objOrArray );
224 }
225 foreach ( $objOrArray as $key => $value ) {
226 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
227 $value = wfObjectToArray( $value );
228 }
229
230 $array[$key] = $value;
231 }
232
233 return $array;
234}
235
246function wfRandom() {
247 // The maximum random value is "only" 2^31-1, so get two random
248 // values to reduce the chance of dupes
249 $max = mt_getrandmax() + 1;
250 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
251 return $rand;
252}
253
264function wfRandomString( $length = 32 ) {
265 $str = '';
266 for ( $n = 0; $n < $length; $n += 7 ) {
267 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
268 }
269 return substr( $str, 0, $length );
270}
271
299function wfUrlencode( $s ) {
300 static $needle;
301
302 if ( $s === null ) {
303 // Reset $needle for testing.
304 $needle = null;
305 return '';
306 }
307
308 if ( $needle === null ) {
309 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
310 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
311 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
312 ) {
313 $needle[] = '%3A';
314 }
315 }
316
317 $s = urlencode( $s );
318 $s = str_ireplace(
319 $needle,
320 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
321 $s
322 );
323
324 return $s;
325}
326
337function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
338 if ( $array2 !== null ) {
339 $array1 += $array2;
340 }
341
342 $cgi = '';
343 foreach ( $array1 as $key => $value ) {
344 if ( $value !== null && $value !== false ) {
345 if ( $cgi != '' ) {
346 $cgi .= '&';
347 }
348 if ( $prefix !== '' ) {
349 $key = $prefix . "[$key]";
350 }
351 if ( is_array( $value ) ) {
352 $firstTime = true;
353 foreach ( $value as $k => $v ) {
354 $cgi .= $firstTime ? '' : '&';
355 if ( is_array( $v ) ) {
356 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
357 } else {
358 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
359 }
360 $firstTime = false;
361 }
362 } else {
363 if ( is_object( $value ) ) {
364 $value = $value->__toString();
365 }
366 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
367 }
368 }
369 }
370 return $cgi;
371}
372
382function wfCgiToArray( $query ) {
383 if ( isset( $query[0] ) && $query[0] == '?' ) {
384 $query = substr( $query, 1 );
385 }
386 $bits = explode( '&', $query );
387 $ret = [];
388 foreach ( $bits as $bit ) {
389 if ( $bit === '' ) {
390 continue;
391 }
392 if ( strpos( $bit, '=' ) === false ) {
393 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
394 $key = $bit;
395 $value = '';
396 } else {
397 [ $key, $value ] = explode( '=', $bit );
398 }
399 $key = urldecode( $key );
400 $value = urldecode( $value );
401 if ( strpos( $key, '[' ) !== false ) {
402 $keys = array_reverse( explode( '[', $key ) );
403 $key = array_pop( $keys );
404 $temp = $value;
405 foreach ( $keys as $k ) {
406 $k = substr( $k, 0, -1 );
407 $temp = [ $k => $temp ];
408 }
409 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
410 $ret[$key] = array_merge( $ret[$key], $temp );
411 } else {
412 $ret[$key] = $temp;
413 }
414 } else {
415 $ret[$key] = $value;
416 }
417 }
418 return $ret;
419}
420
429function wfAppendQuery( $url, $query ) {
430 if ( is_array( $query ) ) {
431 $query = wfArrayToCgi( $query );
432 }
433 if ( $query != '' ) {
434 // Remove the fragment, if there is one
435 $fragment = false;
436 $hashPos = strpos( $url, '#' );
437 if ( $hashPos !== false ) {
438 $fragment = substr( $url, $hashPos );
439 $url = substr( $url, 0, $hashPos );
440 }
441
442 // Add parameter
443 if ( strpos( $url, '?' ) === false ) {
444 $url .= '?';
445 } else {
446 $url .= '&';
447 }
448 $url .= $query;
449
450 // Put the fragment back
451 if ( $fragment !== false ) {
452 $url .= $fragment;
453 }
454 }
455 return $url;
456}
457
466
467 if ( MediaWikiServices::hasInstance() ) {
468 $services = MediaWikiServices::getInstance();
469 if ( $services->hasService( 'UrlUtils' ) ) {
470 return $services->getUrlUtils();
471 }
472 }
473
474 return new UrlUtils( [
475 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
476 // implementations implicitly converted it to an empty string (presumably by mistake).
477 // Preserve the old behavior for compatibility.
478 UrlUtils::SERVER => $wgServer ?? '',
479 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
480 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
481 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
482 : WebRequest::detectProtocol(),
483 UrlUtils::HTTPS_PORT => $wgHttpsPort,
484 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
485 ] );
486}
487
509function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
510 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
511}
512
522function wfGetServerUrl( $proto ) {
523 return wfGetUrlUtils()->getServer( $proto ) ?? '';
524}
525
538function wfAssembleUrl( $urlParts ) {
539 return wfGetUrlUtils()->assemble( (array)$urlParts );
540}
541
553function wfRemoveDotSegments( $urlPath ) {
554 return wfGetUrlUtils()->removeDotSegments( (string)$urlPath );
555}
556
565function wfUrlProtocols( $includeProtocolRelative = true ) {
566 $method = $includeProtocolRelative ? 'validProtocols' : 'validAbsoluteProtocols';
567 return wfGetUrlUtils()->$method();
568}
569
578 return wfGetUrlUtils()->validAbsoluteProtocols();
579}
580
607function wfParseUrl( $url ) {
608 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
609}
610
620function wfExpandIRI( $url ) {
621 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
622}
623
632function wfMatchesDomainList( $url, $domains ) {
633 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
634}
635
656function wfDebug( $text, $dest = 'all', array $context = [] ) {
658
659 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
660 return;
661 }
662
663 $text = trim( $text );
664
665 if ( $wgDebugLogPrefix !== '' ) {
666 $context['prefix'] = $wgDebugLogPrefix;
667 }
668 $context['private'] = ( $dest === false || $dest === 'private' );
669
670 $logger = LoggerFactory::getInstance( 'wfDebug' );
671 $logger->debug( $text, $context );
672}
673
679 static $cache;
680 if ( $cache !== null ) {
681 return $cache;
682 }
683 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
684 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
685 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
686 || MW_ENTRY_POINT === 'load'
687 ) {
688 $cache = true;
689 } else {
690 $cache = false;
691 }
692 return $cache;
693}
694
720function wfDebugLog(
721 $logGroup, $text, $dest = 'all', array $context = []
722) {
723 $text = trim( $text );
724
725 $logger = LoggerFactory::getInstance( $logGroup );
726 $context['private'] = ( $dest === false || $dest === 'private' );
727 $logger->info( $text, $context );
728}
729
738function wfLogDBError( $text, array $context = [] ) {
739 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
740 $logger->error( trim( $text ), $context );
741}
742
759function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
760 if ( !is_string( $version ) && $version !== false ) {
761 throw new InvalidArgumentException(
762 "MediaWiki version must either be a string or false. " .
763 "Example valid version: '1.33'"
764 );
765 }
766
767 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
768}
769
790function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
791 MWDebug::deprecatedMsg( $msg, $version, $component,
792 $callerOffset === false ? false : $callerOffset + 1 );
793}
794
805function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
806 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
807}
808
818function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
819 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
820}
821
837function wfGetLangObj( $langcode = false ) {
838 # Identify which language to get or create a language object for.
839 # Using is_object here due to Stub objects.
840 if ( is_object( $langcode ) ) {
841 # Great, we already have the object (hopefully)!
842 return $langcode;
843 }
844
845 global $wgLanguageCode;
846 $services = MediaWikiServices::getInstance();
847 if ( $langcode === true || $langcode === $wgLanguageCode ) {
848 # $langcode is the language code of the wikis content language object.
849 # or it is a boolean and value is true
850 return $services->getContentLanguage();
851 }
852
853 global $wgLang;
854 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
855 # $langcode is the language code of user language object.
856 # or it was a boolean and value is false
857 return $wgLang;
858 }
859
860 $languageNames = $services->getLanguageNameUtils()->getLanguageNames();
861 // FIXME: Can we use isSupportedLanguage here?
862 if ( isset( $languageNames[$langcode] ) ) {
863 # $langcode corresponds to a valid language.
864 return $services->getLanguageFactory()->getLanguage( $langcode );
865 }
866
867 # $langcode is a string, but not a valid language code; use content language.
868 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
869 return $services->getContentLanguage();
870}
871
893function wfMessage( $key, ...$params ) {
894 if ( is_array( $key ) ) {
895 // Fallback keys are not allowed in message specifiers
896 $message = wfMessageFallback( ...$key );
897 } else {
898 $message = Message::newFromSpecifier( $key );
899 }
900
901 // We call Message::params() to reduce code duplication
902 if ( $params ) {
903 $message->params( ...$params );
904 }
905
906 return $message;
907}
908
921function wfMessageFallback( ...$keys ) {
923}
924
933function wfMsgReplaceArgs( $message, $args ) {
934 # Fix windows line-endings
935 # Some messages are split with explode("\n", $msg)
936 $message = str_replace( "\r", '', $message );
937
938 // Replace arguments
939 if ( is_array( $args ) && $args ) {
940 if ( is_array( $args[0] ) ) {
941 $args = array_values( $args[0] );
942 }
943 $replacementKeys = [];
944 foreach ( $args as $n => $param ) {
945 $replacementKeys['$' . ( $n + 1 )] = $param;
946 }
947 $message = strtr( $message, $replacementKeys );
948 }
949
950 return $message;
951}
952
961function wfHostname() {
962 // Hostname overriding
963 global $wgOverrideHostname;
964 if ( $wgOverrideHostname !== false ) {
965 return $wgOverrideHostname;
966 }
967
968 return php_uname( 'n' ) ?: 'unknown';
969}
970
982function wfReportTime( $nonce = null ) {
983 global $wgShowHostnames;
984
985 $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
986 // seconds to milliseconds
987 $responseTime = round( $elapsed * 1000 );
988 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
989 if ( $wgShowHostnames ) {
990 $reportVars['wgHostname'] = wfHostname();
991 }
992
993 return (
994 ResourceLoader::makeInlineScript(
995 ResourceLoader::makeConfigSetScript( $reportVars ),
996 $nonce
997 )
998 );
999}
1000
1011function wfDebugBacktrace( $limit = 0 ) {
1012 static $disabled = null;
1013
1014 if ( $disabled === null ) {
1015 $disabled = !function_exists( 'debug_backtrace' );
1016 if ( $disabled ) {
1017 wfDebug( "debug_backtrace() is disabled" );
1018 }
1019 }
1020 if ( $disabled ) {
1021 return [];
1022 }
1023
1024 if ( $limit ) {
1025 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1026 } else {
1027 return array_slice( debug_backtrace(), 1 );
1028 }
1029}
1030
1039function wfBacktrace( $raw = null ) {
1040 global $wgCommandLineMode;
1041
1042 if ( $raw ?? $wgCommandLineMode ) {
1043 $frameFormat = "%s line %s calls %s()\n";
1044 $traceFormat = "%s";
1045 } else {
1046 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1047 $traceFormat = "<ul>\n%s</ul>\n";
1048 }
1049
1050 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1051 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1052 $line = $frame['line'] ?? '-';
1053 $call = $frame['function'];
1054 if ( !empty( $frame['class'] ) ) {
1055 $call = $frame['class'] . $frame['type'] . $call;
1056 }
1057 return sprintf( $frameFormat, $file, $line, $call );
1058 }, wfDebugBacktrace() );
1059
1060 return sprintf( $traceFormat, implode( '', $frames ) );
1061}
1062
1072function wfGetCaller( $level = 2 ) {
1073 $backtrace = wfDebugBacktrace( $level + 1 );
1074 if ( isset( $backtrace[$level] ) ) {
1075 return wfFormatStackFrame( $backtrace[$level] );
1076 } else {
1077 return 'unknown';
1078 }
1079}
1080
1088function wfGetAllCallers( $limit = 3 ) {
1089 $trace = array_reverse( wfDebugBacktrace() );
1090 if ( !$limit || $limit > count( $trace ) - 1 ) {
1091 $limit = count( $trace ) - 1;
1092 }
1093 $trace = array_slice( $trace, -$limit - 1, $limit );
1094 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1095}
1096
1103function wfFormatStackFrame( $frame ) {
1104 if ( !isset( $frame['function'] ) ) {
1105 return 'NO_FUNCTION_GIVEN';
1106 }
1107 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1108 $frame['class'] . $frame['type'] . $frame['function'] :
1109 $frame['function'];
1110}
1111
1112/* Some generic result counters, pulled out of SearchEngine */
1113
1122function wfShowingResults( $offset, $limit ) {
1123 wfDeprecated( __FUNCTION__, '1.40' );
1124 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1125}
1126
1136function wfClientAcceptsGzip( $force = false ) {
1137 static $result = null;
1138 if ( $result === null || $force ) {
1139 $result = false;
1140 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1141 # @todo FIXME: We may want to disallow some broken browsers
1142 $m = [];
1143 if ( preg_match(
1144 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1145 $_SERVER['HTTP_ACCEPT_ENCODING'],
1146 $m
1147 )
1148 ) {
1149 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1150 return $result;
1151 }
1152 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1153 $result = true;
1154 }
1155 }
1156 }
1157 return $result;
1158}
1159
1170function wfEscapeWikiText( $text ) {
1171 global $wgEnableMagicLinks;
1172 static $repl = null, $repl2 = null;
1173 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1174 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1175 // in those situations
1176 $repl = [
1177 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1178 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1179 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1180 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1181 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1182 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1183 "\n " => "\n&#32;", "\r " => "\r&#32;",
1184 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1185 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1186 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1187 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1188 '__' => '_&#95;', '://' => '&#58;//',
1189 ];
1190
1191 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1192 // We have to catch everything "\s" matches in PCRE
1193 foreach ( $magicLinks as $magic ) {
1194 $repl["$magic "] = "$magic&#32;";
1195 $repl["$magic\t"] = "$magic&#9;";
1196 $repl["$magic\r"] = "$magic&#13;";
1197 $repl["$magic\n"] = "$magic&#10;";
1198 $repl["$magic\f"] = "$magic&#12;";
1199 }
1200
1201 // And handle protocols that don't use "://"
1202 global $wgUrlProtocols;
1203 $repl2 = [];
1204 foreach ( $wgUrlProtocols as $prot ) {
1205 if ( substr( $prot, -1 ) === ':' ) {
1206 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1207 }
1208 }
1209 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1210 }
1211 $text = substr( strtr( "\n$text", $repl ), 1 );
1212 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
1213 $text = preg_replace( $repl2, '$1&#58;', $text );
1214 return $text;
1215}
1216
1227function wfSetVar( &$dest, $source, $force = false ) {
1228 $temp = $dest;
1229 if ( $source !== null || $force ) {
1230 $dest = $source;
1231 }
1232 return $temp;
1233}
1234
1244function wfSetBit( &$dest, $bit, $state = true ) {
1245 $temp = (bool)( $dest & $bit );
1246 if ( $state !== null ) {
1247 if ( $state ) {
1248 $dest |= $bit;
1249 } else {
1250 $dest &= ~$bit;
1251 }
1252 }
1253 return $temp;
1254}
1255
1262function wfVarDump( $var ) {
1263 global $wgOut;
1264 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1265 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1266 print $s;
1267 } else {
1268 $wgOut->addHTML( $s );
1269 }
1270}
1271
1279function wfHttpError( $code, $label, $desc ) {
1280 global $wgOut;
1281 HttpStatus::header( $code );
1282 if ( $wgOut ) {
1283 $wgOut->disable();
1284 $wgOut->sendCacheControl();
1285 }
1286
1287 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1288 header( 'Content-type: text/html; charset=utf-8' );
1289 ob_start();
1290 print '<!DOCTYPE html>' .
1291 '<html><head><title>' .
1292 htmlspecialchars( $label ) .
1293 '</title></head><body><h1>' .
1294 htmlspecialchars( $label ) .
1295 '</h1><p>' .
1296 nl2br( htmlspecialchars( $desc ) ) .
1297 "</p></body></html>\n";
1298 header( 'Content-Length: ' . ob_get_length() );
1299 ob_end_flush();
1300}
1301
1319function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1320 while ( $status = ob_get_status() ) {
1321 if ( isset( $status['flags'] ) ) {
1322 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1323 $deleteable = ( $status['flags'] & $flags ) === $flags;
1324 } elseif ( isset( $status['del'] ) ) {
1325 $deleteable = $status['del'];
1326 } else {
1327 // Guess that any PHP-internal setting can't be removed.
1328 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1329 }
1330 if ( !$deleteable ) {
1331 // Give up, and hope the result doesn't break
1332 // output behavior.
1333 break;
1334 }
1335 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1336 // Unit testing barrier to prevent this function from breaking PHPUnit.
1337 break;
1338 }
1339 if ( !ob_end_clean() ) {
1340 // Could not remove output buffer handler; abort now
1341 // to avoid getting in some kind of infinite loop.
1342 break;
1343 }
1344 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1345 // Reset the 'Content-Encoding' field set by this handler
1346 // so we can start fresh.
1347 header_remove( 'Content-Encoding' );
1348 break;
1349 }
1350 }
1351}
1352
1368 wfDeprecated( __FUNCTION__, '1.36' );
1369 wfResetOutputBuffers( false );
1370}
1371
1382function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1383 $ret = MWTimestamp::convert( $outputtype, $ts );
1384 if ( $ret === false ) {
1385 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1386 }
1387 return $ret;
1388}
1389
1398function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1399 if ( $ts === null ) {
1400 return null;
1401 } else {
1402 return wfTimestamp( $outputtype, $ts );
1403 }
1404}
1405
1411function wfTimestampNow() {
1412 return MWTimestamp::now( TS_MW );
1413}
1414
1426function wfTempDir() {
1427 global $wgTmpDirectory;
1428
1429 if ( $wgTmpDirectory !== false ) {
1430 return $wgTmpDirectory;
1431 }
1432
1433 return TempFSFile::getUsableTempDirectory();
1434}
1435
1445function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1446 global $wgDirectoryMode;
1447
1448 if ( FileBackend::isStoragePath( $dir ) ) {
1449 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1450 }
1451
1452 if ( $caller !== null ) {
1453 wfDebug( "$caller: called wfMkdirParents($dir)" );
1454 }
1455
1456 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1457 return true;
1458 }
1459
1460 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1461
1462 if ( $mode === null ) {
1463 $mode = $wgDirectoryMode;
1464 }
1465
1466 // Turn off the normal warning, we're doing our own below
1467 AtEase::suppressWarnings();
1468 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1469 AtEase::restoreWarnings();
1470
1471 if ( !$ok ) {
1472 // directory may have been created on another request since we last checked
1473 if ( is_dir( $dir ) ) {
1474 return true;
1475 }
1476
1477 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1478 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1479 }
1480 return $ok;
1481}
1482
1488function wfRecursiveRemoveDir( $dir ) {
1489 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1490 if ( is_dir( $dir ) ) {
1491 $objects = scandir( $dir );
1492 foreach ( $objects as $object ) {
1493 if ( $object != "." && $object != ".." ) {
1494 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1495 wfRecursiveRemoveDir( $dir . '/' . $object );
1496 } else {
1497 unlink( $dir . '/' . $object );
1498 }
1499 }
1500 }
1501 reset( $objects );
1502 rmdir( $dir );
1503 }
1504}
1505
1512function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1513 $accForFormat = $acc >= 0 ? $acc : 0;
1514 $ret = sprintf( "%.{$accForFormat}f", $nr );
1515 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1516}
1517
1541function wfIniGetBool( $setting ) {
1542 return wfStringToBool( ini_get( $setting ) );
1543}
1544
1557function wfStringToBool( $val ) {
1558 $val = strtolower( $val );
1559 // 'on' and 'true' can't have whitespace around them, but '1' can.
1560 return $val == 'on'
1561 || $val == 'true'
1562 || $val == 'yes'
1563 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1564}
1565
1579function wfEscapeShellArg( ...$args ) {
1580 return Shell::escape( ...$args );
1581}
1582
1607function wfShellExec( $cmd, &$retval = null, $environ = [],
1608 $limits = [], $options = []
1609) {
1610 if ( Shell::isDisabled() ) {
1611 $retval = 1;
1612 // Backwards compatibility be upon us...
1613 return 'Unable to run external programs, proc_open() is disabled.';
1614 }
1615
1616 if ( is_array( $cmd ) ) {
1617 $cmd = Shell::escape( $cmd );
1618 }
1619
1620 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1621 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1622
1623 try {
1624 $result = Shell::command( [] )
1625 ->unsafeParams( (array)$cmd )
1626 ->environment( $environ )
1627 ->limits( $limits )
1628 ->includeStderr( $includeStderr )
1629 ->profileMethod( $profileMethod )
1630 // For b/c
1631 ->restrict( Shell::RESTRICT_NONE )
1632 ->execute();
1633 } catch ( ProcOpenError $ex ) {
1634 $retval = -1;
1635 return '';
1636 }
1637
1638 $retval = $result->getExitCode();
1639
1640 return $result->getStdout();
1641}
1642
1660function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1661 return wfShellExec( $cmd, $retval, $environ, $limits,
1662 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1663}
1664
1680function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1681 global $wgPhpCli;
1682 // Give site config file a chance to run the script in a wrapper.
1683 // The caller may likely want to call wfBasename() on $script.
1684 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1685 $cmd = [ $options['php'] ?? $wgPhpCli ];
1686 if ( isset( $options['wrapper'] ) ) {
1687 $cmd[] = $options['wrapper'];
1688 }
1689 $cmd[] = $script;
1690 // Escape each parameter for shell
1691 return Shell::escape( array_merge( $cmd, $parameters ) );
1692}
1693
1710function wfMerge(
1711 string $old,
1712 string $mine,
1713 string $yours,
1714 ?string &$simplisticMergeAttempt,
1715 string &$mergeLeftovers = null
1716): bool {
1717 global $wgDiff3;
1718
1719 # This check may also protect against code injection in
1720 # case of broken installations.
1721 AtEase::suppressWarnings();
1722 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1723 AtEase::restoreWarnings();
1724
1725 if ( !$haveDiff3 ) {
1726 wfDebug( "diff3 not found" );
1727 return false;
1728 }
1729
1730 # Make temporary files
1731 $td = wfTempDir();
1732 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1733 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1734 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1735
1736 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1737 # a newline character. To avoid this, we normalize the trailing whitespace before
1738 # creating the diff.
1739
1740 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1741 fclose( $oldtextFile );
1742 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1743 fclose( $mytextFile );
1744 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1745 fclose( $yourtextFile );
1746
1747 # Check for a conflict
1748 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1749 $oldtextName, $yourtextName );
1750 $handle = popen( $cmd, 'r' );
1751
1752 $mergeLeftovers = '';
1753 do {
1754 $data = fread( $handle, 8192 );
1755 if ( strlen( $data ) == 0 ) {
1756 break;
1757 }
1758 $mergeLeftovers .= $data;
1759 } while ( true );
1760 pclose( $handle );
1761
1762 $conflict = $mergeLeftovers !== '';
1763
1764 # Merge differences automatically where possible, preferring "my" text for conflicts.
1765 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1766 $oldtextName, $yourtextName );
1767 $handle = popen( $cmd, 'r' );
1768 $simplisticMergeAttempt = '';
1769 do {
1770 $data = fread( $handle, 8192 );
1771 if ( strlen( $data ) == 0 ) {
1772 break;
1773 }
1774 $simplisticMergeAttempt .= $data;
1775 } while ( true );
1776 pclose( $handle );
1777 unlink( $mytextName );
1778 unlink( $oldtextName );
1779 unlink( $yourtextName );
1780
1781 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1782 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1783 $conflict = true;
1784 }
1785 return !$conflict;
1786}
1787
1800function wfBaseName( $path, $suffix = '' ) {
1801 if ( $suffix == '' ) {
1802 $encSuffix = '';
1803 } else {
1804 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1805 }
1806
1807 $matches = [];
1808 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1809 return $matches[1];
1810 } else {
1811 return '';
1812 }
1813}
1814
1824function wfRelativePath( $path, $from ) {
1825 // Normalize mixed input on Windows...
1826 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1827 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1828
1829 // Trim trailing slashes -- fix for drive root
1830 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1831 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1832
1833 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1834 $against = explode( DIRECTORY_SEPARATOR, $from );
1835
1836 if ( $pieces[0] !== $against[0] ) {
1837 // Non-matching Windows drive letters?
1838 // Return a full path.
1839 return $path;
1840 }
1841
1842 // Trim off common prefix
1843 while ( count( $pieces ) && count( $against )
1844 && $pieces[0] == $against[0] ) {
1845 array_shift( $pieces );
1846 array_shift( $against );
1847 }
1848
1849 // relative dots to bump us to the parent
1850 while ( count( $against ) ) {
1851 array_unshift( $pieces, '..' );
1852 array_shift( $against );
1853 }
1854
1855 $pieces[] = wfBaseName( $path );
1856
1857 return implode( DIRECTORY_SEPARATOR, $pieces );
1858}
1859
1891function wfGetDB( $db, $groups = [], $wiki = false ) {
1892 if ( $wiki === false ) {
1893 return MediaWikiServices::getInstance()
1894 ->getDBLoadBalancer()
1895 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1896 } else {
1897 return MediaWikiServices::getInstance()
1898 ->getDBLoadBalancerFactory()
1899 ->getMainLB( $wiki )
1900 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1901 }
1902}
1903
1912function wfScript( $script = 'index' ) {
1914 if ( $script === 'index' ) {
1915 return $wgScript;
1916 } elseif ( $script === 'load' ) {
1917 return $wgLoadScript;
1918 } else {
1919 return "{$wgScriptPath}/{$script}.php";
1920 }
1921}
1922
1930function wfBoolToStr( $value ) {
1931 return $value ? 'true' : 'false';
1932}
1933
1939function wfGetNull() {
1940 return wfIsWindows() ? 'NUL' : '/dev/null';
1941}
1942
1952 global $wgIllegalFileChars;
1953 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1954 $name = preg_replace(
1955 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1956 '-',
1957 $name
1958 );
1959 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1960 $name = wfBaseName( $name );
1961 return $name;
1962}
1963
1970function wfMemoryLimit( $newLimit ) {
1971 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1972 // If the INI config is already unlimited, there is nothing larger
1973 if ( $oldLimit != -1 ) {
1974 $newLimit = wfShorthandToInteger( (string)$newLimit );
1975 if ( $newLimit == -1 ) {
1976 wfDebug( "Removing PHP's memory limit" );
1977 AtEase::suppressWarnings();
1978 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1979 ini_set( 'memory_limit', $newLimit );
1980 AtEase::restoreWarnings();
1981 } elseif ( $newLimit > $oldLimit ) {
1982 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1983 AtEase::suppressWarnings();
1984 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
1985 ini_set( 'memory_limit', $newLimit );
1986 AtEase::restoreWarnings();
1987 }
1988 }
1989}
1990
1999
2000 $timeout = RequestTimeout::singleton();
2001 $timeLimit = $timeout->getWallTimeLimit();
2002 if ( $timeLimit !== INF ) {
2003 // RequestTimeout library is active
2004 if ( $wgTransactionalTimeLimit > $timeLimit ) {
2005 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2006 }
2007 } else {
2008 // Fallback case, likely $wgRequestTimeLimit === null
2009 $timeLimit = (int)ini_get( 'max_execution_time' );
2010 // Note that CLI scripts use 0
2011 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2012 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2013 }
2014 }
2015 ignore_user_abort( true ); // ignore client disconnects
2016
2017 return $timeLimit;
2018}
2019
2027function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2028 $string = trim( $string ?? '' );
2029 if ( $string === '' ) {
2030 return $default;
2031 }
2032 $last = $string[strlen( $string ) - 1];
2033 $val = intval( $string );
2034 switch ( $last ) {
2035 case 'g':
2036 case 'G':
2037 $val *= 1024;
2038 // break intentionally missing
2039 case 'm':
2040 case 'M':
2041 $val *= 1024;
2042 // break intentionally missing
2043 case 'k':
2044 case 'K':
2045 $val *= 1024;
2046 }
2047
2048 return $val;
2049}
2050
2065function wfUnpack( $format, $data, $length = false ) {
2066 if ( $length !== false ) {
2067 $realLen = strlen( $data );
2068 if ( $realLen < $length ) {
2069 throw new MWException( "Tried to use wfUnpack on a "
2070 . "string of length $realLen, but needed one "
2071 . "of at least length $length."
2072 );
2073 }
2074 }
2075
2076 AtEase::suppressWarnings();
2077 $result = unpack( $format, $data );
2078 AtEase::restoreWarnings();
2079
2080 if ( $result === false ) {
2081 // If it cannot extract the packed data.
2082 throw new MWException( "unpack could not unpack binary data" );
2083 }
2084 return $result;
2085}
2086
2094function wfIsInfinity( $str ) {
2095 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2096 return in_array( $str, ExpiryDef::INFINITY_VALS );
2097}
2098
2113function wfThumbIsStandard( File $file, array $params ) {
2115
2116 $multipliers = [ 1 ];
2117 if ( $wgResponsiveImages ) {
2118 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2119 // @see Linker::processResponsiveImages
2120 $multipliers[] = 1.5;
2121 $multipliers[] = 2;
2122 }
2123
2124 $handler = $file->getHandler();
2125 if ( !$handler || !isset( $params['width'] ) ) {
2126 return false;
2127 }
2128
2129 $basicParams = [];
2130 if ( isset( $params['page'] ) ) {
2131 $basicParams['page'] = $params['page'];
2132 }
2133
2134 $thumbLimits = [];
2135 $imageLimits = [];
2136 // Expand limits to account for multipliers
2137 foreach ( $multipliers as $multiplier ) {
2138 $thumbLimits = array_merge( $thumbLimits, array_map(
2139 static function ( $width ) use ( $multiplier ) {
2140 return round( $width * $multiplier );
2141 }, $wgThumbLimits )
2142 );
2143 $imageLimits = array_merge( $imageLimits, array_map(
2144 static function ( $pair ) use ( $multiplier ) {
2145 return [
2146 round( $pair[0] * $multiplier ),
2147 round( $pair[1] * $multiplier ),
2148 ];
2149 }, $wgImageLimits )
2150 );
2151 }
2152
2153 // Check if the width matches one of $wgThumbLimits
2154 if ( in_array( $params['width'], $thumbLimits ) ) {
2155 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2156 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2157 $handler->normaliseParams( $file, $normalParams );
2158 } else {
2159 // If not, then check if the width matches one of $wgImageLimits
2160 $match = false;
2161 foreach ( $imageLimits as $pair ) {
2162 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2163 // Decide whether the thumbnail should be scaled on width or height.
2164 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2165 $handler->normaliseParams( $file, $normalParams );
2166 // Check if this standard thumbnail size maps to the given width
2167 if ( $normalParams['width'] == $params['width'] ) {
2168 $match = true;
2169 break;
2170 }
2171 }
2172 if ( !$match ) {
2173 return false; // not standard for description pages
2174 }
2175 }
2176
2177 // Check that the given values for non-page, non-width, params are just defaults
2178 foreach ( $params as $key => $value ) {
2179 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2180 return false;
2181 }
2182 }
2183
2184 return true;
2185}
2186
2199function wfArrayPlus2d( array $baseArray, array $newValues ) {
2200 // First merge items that are in both arrays
2201 foreach ( $baseArray as $name => &$groupVal ) {
2202 if ( isset( $newValues[$name] ) ) {
2203 $groupVal += $newValues[$name];
2204 }
2205 }
2206 // Now add items that didn't exist yet
2207 $baseArray += $newValues;
2208
2209 return $baseArray;
2210}
wfIsWindows()
Check if the operating system is Windows.
const PROTO_CURRENT
Definition Defines.php:198
global $wgCommandLineMode
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
wfVarDump( $var)
A wrapper around the PHP function var_export().
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfTempDir()
Tries to get the system directory for temporary files.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfLoadExtension( $ext, $path=null)
Load an extension.
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfArrayDiff2( $arr1, $arr2)
Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfGetUrlUtils()
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfPercent( $nr, int $acc=2, bool $round=true)
wfReportTime( $nonce=null)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfGetNull()
Get a platform-independent path to the null file, e.g.
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfShowingResults( $offset, $limit)
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
wfLoadSkin( $skin, $path=null)
Load a skin.
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
wfFormatStackFrame( $frame)
Return a string representation of frame.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
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:407
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode $wgOut
Definition Setup.php:527
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode $wgLang
Definition Setup.php:527
const MW_ENTRY_POINT
Definition api.php:42
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:68
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
Stub object for the user language.
Represents a title within MediaWiki.
Definition Title.php:82
A service to expand, parse, and otherwise manipulate URLs.
Definition UrlUtils.php:17
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:460
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition Message.php:426
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.
$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