MediaWiki master
GlobalFunctions.php
Go to the documentation of this file.
1<?php
22use Wikimedia\AtEase\AtEase;
29use Wikimedia\RequestTimeout\RequestTimeout;
30use Wikimedia\Timestamp\ConvertibleTimestamp;
31use Wikimedia\Timestamp\TimestampFormat as TS;
32
43function wfLoadExtension( $ext, $path = null ) {
44 if ( !$path ) {
46 $path = "$wgExtensionDirectory/$ext/extension.json";
47 }
48 ExtensionRegistry::getInstance()->queue( $path );
49}
50
64function wfLoadExtensions( array $exts ) {
66 $registry = ExtensionRegistry::getInstance();
67 foreach ( $exts as $ext ) {
68 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
69 }
70}
71
80function wfLoadSkin( $skin, $path = null ) {
81 if ( !$path ) {
82 global $wgStyleDirectory;
83 $path = "$wgStyleDirectory/$skin/skin.json";
84 }
85 ExtensionRegistry::getInstance()->queue( $path );
86}
87
95function wfLoadSkins( array $skins ) {
96 global $wgStyleDirectory;
97 $registry = ExtensionRegistry::getInstance();
98 foreach ( $skins as $skin ) {
99 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
100 }
101}
102
110function wfArrayDiff2( $arr1, $arr2 ) {
111 wfDeprecated( __FUNCTION__, '1.43' );
116 $comparator = static function ( $a, $b ): int {
117 if ( is_string( $a ) && is_string( $b ) ) {
118 return strcmp( $a, $b );
119 }
120 if ( !is_array( $a ) && !is_array( $b ) ) {
121 throw new InvalidArgumentException(
122 'This function assumes that array elements are all strings or all arrays'
123 );
124 }
125 if ( count( $a ) !== count( $b ) ) {
126 return count( $a ) <=> count( $b );
127 } else {
128 reset( $a );
129 reset( $b );
130 while ( key( $a ) !== null && key( $b ) !== null ) {
131 $valueA = current( $a );
132 $valueB = current( $b );
133 $cmp = strcmp( $valueA, $valueB );
134 if ( $cmp !== 0 ) {
135 return $cmp;
136 }
137 next( $a );
138 next( $b );
139 }
140 return 0;
141 }
142 };
143 return array_udiff( $arr1, $arr2, $comparator );
144}
145
166function wfMergeErrorArrays( ...$args ) {
167 wfDeprecated( __FUNCTION__, '1.43' );
168 $out = [];
169 foreach ( $args as $errors ) {
170 foreach ( $errors as $params ) {
171 $originalParams = $params;
172 if ( $params[0] instanceof MessageSpecifier ) {
173 $params = [ $params[0]->getKey(), ...$params[0]->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 !str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
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 ( !str_contains( $bit, '=' ) ) {
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 ( str_contains( $key, '[' ) ) {
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 ( !str_contains( $url, '?' ) ) {
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
515function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
516 wfDeprecated( __FUNCTION__, '1.39' );
517
518 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
519}
520
533function wfAssembleUrl( $urlParts ) {
534 wfDeprecated( __FUNCTION__, '1.39' );
535
536 return UrlUtils::assemble( (array)$urlParts );
537}
538
547function wfUrlProtocols( $includeProtocolRelative = true ) {
548 wfDeprecated( __FUNCTION__, '1.39' );
549
550 return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() :
551 wfGetUrlUtils()->validAbsoluteProtocols();
552}
553
562 wfDeprecated( __FUNCTION__, '1.39' );
563
564 return wfGetUrlUtils()->validAbsoluteProtocols();
565}
566
593function wfParseUrl( $url ) {
594 wfDeprecated( __FUNCTION__, '1.39' );
595
596 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
597}
598
607function wfMatchesDomainList( $url, $domains ) {
608 wfDeprecated( __FUNCTION__, '1.39' );
609
610 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
611}
612
633function wfDebug( $text, $dest = 'all', array $context = [] ) {
635
636 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
637 return;
638 }
639
640 $text = trim( $text );
641
642 if ( $wgDebugLogPrefix !== '' ) {
643 $context['prefix'] = $wgDebugLogPrefix;
644 }
645 $context['private'] = ( $dest === false || $dest === 'private' );
646
647 $logger = LoggerFactory::getInstance( 'wfDebug' );
648 $logger->debug( $text, $context );
649}
650
656 static $cache;
657 if ( $cache !== null ) {
658 return $cache;
659 }
660 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
661 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
662 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
663 || MW_ENTRY_POINT === 'load'
664 ) {
665 $cache = true;
666 } else {
667 $cache = false;
668 }
669 return $cache;
670}
671
697function wfDebugLog(
698 $logGroup, $text, $dest = 'all', array $context = []
699) {
700 $text = trim( $text );
701
702 $logger = LoggerFactory::getInstance( $logGroup );
703 $context['private'] = ( $dest === false || $dest === 'private' );
704 $logger->info( $text, $context );
705}
706
715function wfLogDBError( $text, array $context = [] ) {
716 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
717 $logger->error( trim( $text ), $context );
718}
719
736function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
737 if ( !is_string( $version ) && $version !== false ) {
738 throw new InvalidArgumentException(
739 "MediaWiki version must either be a string or false. " .
740 "Example valid version: '1.33'"
741 );
742 }
743
744 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
745}
746
767function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
768 MWDebug::deprecatedMsg( $msg, $version, $component,
769 $callerOffset === false ? false : $callerOffset + 1 );
770}
771
782function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
783 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
784}
785
795function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
796 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
797}
798
821function wfMessage( $key, ...$params ) {
822 if ( is_array( $key ) ) {
823 // Fallback keys are not allowed in message specifiers
824 $message = wfMessageFallback( ...$key );
825 } else {
826 $message = Message::newFromSpecifier( $key );
827 }
828
829 // We call Message::params() to reduce code duplication
830 if ( $params ) {
831 $message->params( ...$params );
832 }
833
834 return $message;
835}
836
849function wfMessageFallback( ...$keys ) {
850 return Message::newFallbackSequence( ...$keys );
851}
852
861function wfMsgReplaceArgs( $message, $args ) {
862 # Fix windows line-endings
863 # Some messages are split with explode("\n", $msg)
864 $message = str_replace( "\r", '', $message );
865
866 // Replace arguments
867 if ( is_array( $args ) && $args ) {
868 if ( is_array( $args[0] ) ) {
869 $args = array_values( $args[0] );
870 }
871 $replacementKeys = [];
872 foreach ( $args as $n => $param ) {
873 $replacementKeys['$' . ( $n + 1 )] = $param;
874 }
875 $message = strtr( $message, $replacementKeys );
876 }
877
878 return $message;
879}
880
889function wfHostname() {
890 // Hostname overriding
891 global $wgOverrideHostname;
892 if ( $wgOverrideHostname !== false ) {
893 return $wgOverrideHostname;
894 }
895
896 return php_uname( 'n' ) ?: 'unknown';
897}
898
909function wfDebugBacktrace( $limit = 0 ) {
910 static $disabled = null;
911
912 if ( $disabled === null ) {
913 $disabled = !function_exists( 'debug_backtrace' );
914 if ( $disabled ) {
915 wfDebug( "debug_backtrace() is disabled" );
916 }
917 }
918 if ( $disabled ) {
919 return [];
920 }
921
922 if ( $limit ) {
923 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
924 } else {
925 return array_slice( debug_backtrace(), 1 );
926 }
927}
928
937function wfBacktrace( $raw = null ) {
938 $raw ??= MW_ENTRY_POINT === 'cli';
939 if ( $raw ) {
940 $frameFormat = "%s line %s calls %s()\n";
941 $traceFormat = "%s";
942 } else {
943 $frameFormat = "<li>%s line %s calls %s()</li>\n";
944 $traceFormat = "<ul>\n%s</ul>\n";
945 }
946
947 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
948 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
949 $line = $frame['line'] ?? '-';
950 $call = $frame['function'];
951 if ( !empty( $frame['class'] ) ) {
952 $call = $frame['class'] . $frame['type'] . $call;
953 }
954 return sprintf( $frameFormat, $file, $line, $call );
955 }, wfDebugBacktrace() );
956
957 return sprintf( $traceFormat, implode( '', $frames ) );
958}
959
970function wfGetCaller( $level = 2 ) {
971 $backtrace = wfDebugBacktrace( $level + 1 );
972 if ( isset( $backtrace[$level] ) ) {
973 return wfFormatStackFrame( $backtrace[$level] );
974 } else {
975 return 'unknown';
976 }
977}
978
986function wfGetAllCallers( $limit = 3 ) {
987 $limit = $limit ? $limit + 1 : 0;
988 // Strip the own "wfGetAllCallers" from the list
989 $trace = array_reverse( array_slice( wfDebugBacktrace( $limit ), 1 ) );
990 return implode( '/', array_map( wfFormatStackFrame( ... ), $trace ) );
991}
992
1005function wfFormatStackFrame( $frame ) {
1006 if ( !isset( $frame['function'] ) ) {
1007 return 'NO_FUNCTION_GIVEN';
1008 }
1009 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1010 $frame['class'] . $frame['type'] . $frame['function'] :
1011 $frame['function'];
1012}
1013
1023function wfClientAcceptsGzip( $force = false ) {
1024 static $result = null;
1025 if ( $result === null || $force ) {
1026 $result = false;
1027 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1028 # @todo FIXME: We may want to disallow some broken browsers
1029 $m = [];
1030 if ( preg_match(
1031 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1032 $_SERVER['HTTP_ACCEPT_ENCODING'],
1033 $m
1034 )
1035 ) {
1036 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1037 return $result;
1038 }
1039 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1040 $result = true;
1041 }
1042 }
1043 }
1044 return $result;
1045}
1046
1057function wfEscapeWikiText( $input ): string {
1058 global $wgEnableMagicLinks;
1059 static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
1060 if ( $repl === null || defined( 'MW_PHPUNIT_TEST' ) ) {
1061 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1062 // in those situations
1063 $repl = [
1064 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1065 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1066 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1067 ';' => '&#59;', // a token inside language converter brackets
1068 '!!' => '&#33;!', // a token inside table context
1069 "\n!" => "\n&#33;", "\r!" => "\r&#33;", // a token inside table context
1070 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1071 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1072 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1073 "\n " => "\n&#32;", "\r " => "\r&#32;",
1074 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1075 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1076 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1077 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1078 '__' => '_&#95;', '://' => '&#58;//',
1079 // Japanese magic words start w/ wide underscore
1080 '_' => '&#xFF3F;',
1081 '~~~' => '~~&#126;', // protect from PST, just to be safe(r)
1082 ];
1083
1084 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1085 // We have to catch everything "\s" matches in PCRE
1086 foreach ( $magicLinks as $magic ) {
1087 $repl["$magic "] = "$magic&#32;";
1088 $repl["$magic\t"] = "$magic&#9;";
1089 $repl["$magic\r"] = "$magic&#13;";
1090 $repl["$magic\n"] = "$magic&#10;";
1091 $repl["$magic\f"] = "$magic&#12;";
1092 }
1093 // Additionally escape the following characters at the beginning of the
1094 // string, in case they merge to form tokens when spliced into a
1095 // string. Tokens like -{ {{ [[ {| etc are already escaped because
1096 // the second character is escaped above, but the following tokens
1097 // are handled here: |+ |- __FOO__ ~~~
1098 // (Only single-byte characters can go here; multibyte characters
1099 // like 'wide underscore' must go into $repl above.)
1100 $repl3 = [
1101 '+' => '&#43;', '-' => '&#45;', '_' => '&#95;', '~' => '&#126;',
1102 ];
1103 // Similarly, protect the following characters at the end of the
1104 // string, which could turn form the start of `__FOO__` or `~~~~`
1105 // A trailing newline could also form the unintended start of a
1106 // paragraph break if it is glued to a newline in the following
1107 // context. Again, only single-byte characters can be protected
1108 // here; 'wide underscore' is protected by $repl above.
1109 $repl4 = [
1110 '_' => '&#95;', '~' => '&#126;',
1111 "\n" => "&#10;", "\r" => "&#13;",
1112 "\t" => "&#9;", // "\n\t\n" is treated like "\n\n"
1113 ];
1114
1115 // And handle protocols that don't use "://"
1116 global $wgUrlProtocols;
1117 $repl2 = [];
1118 foreach ( $wgUrlProtocols as $prot ) {
1119 if ( substr( $prot, -1 ) === ':' ) {
1120 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1121 }
1122 }
1123 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1124 }
1125 // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
1126 '@phan-var string $repl2';
1127 '@phan-var string $repl3';
1128 '@phan-var string $repl4';
1129 // This will also stringify input in case it's not a string
1130 $text = substr( strtr( "\n$input", $repl ), 1 );
1131 if ( $text === '' ) {
1132 return $text;
1133 }
1134 $first = strtr( $text[0], $repl3 ); // protect first character
1135 if ( strlen( $text ) > 1 ) {
1136 $text = $first . substr( $text, 1, -1 ) .
1137 strtr( substr( $text, -1 ), $repl4 ); // protect last character
1138 } else {
1139 // special case for single-character strings
1140 $text = strtr( $first, $repl4 ); // protect last character
1141 }
1142 $text = preg_replace( $repl2, '$1&#58;', $text );
1143 return $text;
1144}
1145
1156function wfSetVar( &$dest, $source, $force = false ) {
1157 $temp = $dest;
1158 if ( $source !== null || $force ) {
1159 $dest = $source;
1160 }
1161 return $temp;
1162}
1163
1173function wfSetBit( &$dest, $bit, $state = true ) {
1174 $temp = (bool)( $dest & $bit );
1175 if ( $state !== null ) {
1176 if ( $state ) {
1177 $dest |= $bit;
1178 } else {
1179 $dest &= ~$bit;
1180 }
1181 }
1182 return $temp;
1183}
1184
1191function wfVarDump( $var ) {
1192 global $wgOut;
1193 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1194 if ( headers_sent() || $wgOut === null || !is_object( $wgOut ) ) {
1195 print $s;
1196 } else {
1197 $wgOut->addHTML( $s );
1198 }
1199}
1200
1208function wfHttpError( $code, $label, $desc ) {
1209 global $wgOut;
1210 HttpStatus::header( $code );
1211 if ( $wgOut ) {
1212 $wgOut->disable();
1213 $wgOut->sendCacheControl();
1214 }
1215
1216 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1217 header( 'Content-type: text/html; charset=utf-8' );
1218 ContentSecurityPolicy::sendRestrictiveHeader();
1219 ob_start();
1220 print '<!DOCTYPE html>' .
1221 '<html><head><title>' .
1222 htmlspecialchars( $label ) .
1223 '</title><meta name="color-scheme" content="light dark" /></head><body><h1>' .
1224 htmlspecialchars( $label ) .
1225 '</h1><p>' .
1226 nl2br( htmlspecialchars( $desc ) ) .
1227 "</p></body></html>\n";
1228 header( 'Content-Length: ' . ob_get_length() );
1229 ob_end_flush();
1230}
1231
1252function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1253 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
1254 while ( $status = ob_get_status() ) {
1255 if ( isset( $status['flags'] ) ) {
1256 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1257 $deleteable = ( $status['flags'] & $flags ) === $flags;
1258 } elseif ( isset( $status['del'] ) ) {
1259 $deleteable = $status['del'];
1260 } else {
1261 // Guess that any PHP-internal setting can't be removed.
1262 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1263 }
1264 if ( !$deleteable ) {
1265 // Give up, and hope the result doesn't break
1266 // output behavior.
1267 break;
1268 }
1269 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1270 // Unit testing barrier to prevent this function from breaking PHPUnit.
1271 break;
1272 }
1273 if ( !ob_end_clean() ) {
1274 // Could not remove output buffer handler; abort now
1275 // to avoid getting in some kind of infinite loop.
1276 break;
1277 }
1278 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1279 // Reset the 'Content-Encoding' field set by this handler
1280 // so we can start fresh.
1281 header_remove( 'Content-Encoding' );
1282 break;
1283 }
1284 }
1285}
1286
1297function wfTimestamp( $outputtype = TS::UNIX, $ts = 0 ) {
1298 $ret = ConvertibleTimestamp::convert( $outputtype, $ts );
1299 if ( $ret === false ) {
1300 if ( $outputtype instanceof TS ) {
1301 $outputtype = $outputtype->name;
1302 }
1303 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1304 }
1305 return $ret;
1306}
1307
1316function wfTimestampOrNull( $outputtype = TS::UNIX, $ts = null ) {
1317 if ( $ts === null ) {
1318 return null;
1319 } else {
1320 return wfTimestamp( $outputtype, $ts );
1321 }
1322}
1323
1329function wfTimestampNow() {
1330 return ConvertibleTimestamp::now( TS::MW );
1331}
1332
1344function wfTempDir() {
1345 global $wgTmpDirectory;
1346
1347 if ( $wgTmpDirectory !== false ) {
1348 return $wgTmpDirectory;
1349 }
1350
1351 return TempFSFile::getUsableTempDirectory();
1352}
1353
1362function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1363 global $wgDirectoryMode;
1364
1365 if ( FileBackend::isStoragePath( $dir ) ) {
1366 throw new LogicException( __FUNCTION__ . " given storage path '$dir'." );
1367 }
1368 if ( $caller !== null ) {
1369 wfDebug( "$caller: called wfMkdirParents($dir)" );
1370 }
1371 if ( strval( $dir ) === '' ) {
1372 return true;
1373 }
1374
1375 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1376 $mode ??= $wgDirectoryMode;
1377
1378 // Turn off the normal warning, we're doing our own below
1379 // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis.
1380 //
1381 // Repeat existence check if creation failed so that we silently recover in case of
1382 // a race condition where another request created it since the first check.
1383 //
1384 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1385 $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir );
1386 if ( !$ok ) {
1387 trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING );
1388 }
1389
1390 return $ok;
1391}
1392
1398function wfRecursiveRemoveDir( $dir ) {
1399 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1400 if ( is_dir( $dir ) ) {
1401 $objects = scandir( $dir );
1402 foreach ( $objects as $object ) {
1403 if ( $object != "." && $object != ".." ) {
1404 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1405 wfRecursiveRemoveDir( $dir . '/' . $object );
1406 } else {
1407 unlink( $dir . '/' . $object );
1408 }
1409 }
1410 }
1411 rmdir( $dir );
1412 }
1413}
1414
1421function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1422 $accForFormat = $acc >= 0 ? $acc : 0;
1423 $ret = sprintf( "%.{$accForFormat}f", $nr );
1424 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1425}
1426
1450function wfIniGetBool( $setting ) {
1451 return wfStringToBool( ini_get( $setting ) );
1452}
1453
1466function wfStringToBool( $val ) {
1467 $val = strtolower( $val );
1468 // 'on' and 'true' can't have whitespace around them, but '1' can.
1469 return $val == 'on'
1470 || $val == 'true'
1471 || $val == 'yes'
1472 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1473}
1474
1488function wfEscapeShellArg( ...$args ) {
1489 return Shell::escape( ...$args );
1490}
1491
1516function wfShellExec( $cmd, &$retval = null, $environ = [],
1517 $limits = [], $options = []
1518) {
1519 if ( Shell::isDisabled() ) {
1520 $retval = 1;
1521 // Backwards compatibility be upon us...
1522 return 'Unable to run external programs, proc_open() is disabled.';
1523 }
1524
1525 if ( is_array( $cmd ) ) {
1526 $cmd = Shell::escape( $cmd );
1527 }
1528
1529 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1530 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1531
1532 try {
1533 $result = Shell::command( [] )
1534 ->unsafeParams( (array)$cmd )
1535 ->environment( $environ )
1536 ->limits( $limits )
1537 ->includeStderr( $includeStderr )
1538 ->profileMethod( $profileMethod )
1539 // For b/c
1540 ->restrict( Shell::RESTRICT_NONE )
1541 ->execute();
1542 } catch ( ProcOpenError ) {
1543 $retval = -1;
1544 return '';
1545 }
1546
1547 $retval = $result->getExitCode();
1548
1549 return $result->getStdout();
1550}
1551
1569function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1570 return wfShellExec( $cmd, $retval, $environ, $limits,
1571 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1572}
1573
1589function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1590 global $wgPhpCli;
1591 // Give site config file a chance to run the script in a wrapper.
1592 // The caller may likely want to call wfBasename() on $script.
1593 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1594 ->onWfShellWikiCmd( $script, $parameters, $options );
1595 $cmd = [ $options['php'] ?? $wgPhpCli ];
1596 if ( isset( $options['wrapper'] ) ) {
1597 $cmd[] = $options['wrapper'];
1598 }
1599 $cmd[] = $script;
1600 // Escape each parameter for shell
1601 return Shell::escape( array_merge( $cmd, $parameters ) );
1602}
1603
1620function wfMerge(
1621 string $old,
1622 string $mine,
1623 string $yours,
1624 ?string &$simplisticMergeAttempt,
1625 ?string &$mergeLeftovers = null
1626): bool {
1627 global $wgDiff3;
1628
1629 # This check may also protect against code injection in
1630 # case of broken installations.
1631 AtEase::suppressWarnings();
1632 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1633 AtEase::restoreWarnings();
1634
1635 if ( !$haveDiff3 ) {
1636 wfDebug( "diff3 not found" );
1637 return false;
1638 }
1639
1640 # Make temporary files
1641 $td = wfTempDir();
1642 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1643 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1644 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1645
1646 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1647 # a newline character. To avoid this, we normalize the trailing whitespace before
1648 # creating the diff.
1649
1650 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1651 fclose( $oldtextFile );
1652 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1653 fclose( $mytextFile );
1654 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1655 fclose( $yourtextFile );
1656
1657 # Check for a conflict
1658 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1659 $oldtextName, $yourtextName );
1660 $handle = popen( $cmd, 'r' );
1661
1662 $mergeLeftovers = '';
1663 do {
1664 $data = fread( $handle, 8192 );
1665 if ( $data === false || $data === '' ) {
1666 break;
1667 }
1668 $mergeLeftovers .= $data;
1669 } while ( true );
1670 pclose( $handle );
1671
1672 $conflict = $mergeLeftovers !== '';
1673
1674 # Merge differences automatically where possible, preferring "my" text for conflicts.
1675 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1676 $oldtextName, $yourtextName );
1677 $handle = popen( $cmd, 'r' );
1678 $simplisticMergeAttempt = '';
1679 do {
1680 $data = fread( $handle, 8192 );
1681 if ( $data === false || $data === '' ) {
1682 break;
1683 }
1684 $simplisticMergeAttempt .= $data;
1685 } while ( true );
1686 pclose( $handle );
1687 unlink( $mytextName );
1688 unlink( $oldtextName );
1689 unlink( $yourtextName );
1690
1691 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1692 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1693 $conflict = true;
1694 }
1695 return !$conflict;
1696}
1697
1710function wfBaseName( $path, $suffix = '' ) {
1711 if ( $suffix == '' ) {
1712 $encSuffix = '';
1713 } else {
1714 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1715 }
1716
1717 $matches = [];
1718 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1719 return $matches[1];
1720 } else {
1721 return '';
1722 }
1723}
1724
1734function wfRelativePath( $path, $from ) {
1735 // Normalize mixed input on Windows...
1736 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1737 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1738
1739 // Trim trailing slashes -- fix for drive root
1740 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1741 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1742
1743 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1744 $against = explode( DIRECTORY_SEPARATOR, $from );
1745
1746 if ( $pieces[0] !== $against[0] ) {
1747 // Non-matching Windows drive letters?
1748 // Return a full path.
1749 return $path;
1750 }
1751
1752 // Trim off common prefix
1753 while ( count( $pieces ) && count( $against )
1754 && $pieces[0] == $against[0] ) {
1755 array_shift( $pieces );
1756 array_shift( $against );
1757 }
1758
1759 // relative dots to bump us to the parent
1760 while ( count( $against ) ) {
1761 array_unshift( $pieces, '..' );
1762 array_shift( $against );
1763 }
1764
1765 $pieces[] = wfBaseName( $path );
1766
1767 return implode( DIRECTORY_SEPARATOR, $pieces );
1768}
1769
1779function wfScript( $script = 'index' ) {
1781 if ( $script === 'index' ) {
1782 return $wgScript;
1783 } elseif ( $script === 'load' ) {
1784 return $wgLoadScript;
1785 } else {
1786 return "{$wgScriptPath}/{$script}.php";
1787 }
1788}
1789
1797function wfBoolToStr( $value ) {
1798 return $value ? 'true' : 'false';
1799}
1800
1806function wfGetNull() {
1807 return wfIsWindows() ? 'NUL' : '/dev/null';
1808}
1809
1819 global $wgIllegalFileChars;
1820 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1821 $name = preg_replace(
1822 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1823 '-',
1824 $name
1825 );
1826 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1827 $name = wfBaseName( $name );
1828 return $name;
1829}
1830
1837function wfMemoryLimit( $newLimit ) {
1838 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1839 // If the INI config is already unlimited, there is nothing larger
1840 if ( $oldLimit != -1 ) {
1841 $newLimit = wfShorthandToInteger( (string)$newLimit );
1842 if ( $newLimit == -1 ) {
1843 wfDebug( "Removing PHP's memory limit" );
1844 AtEase::suppressWarnings();
1845 ini_set( 'memory_limit', $newLimit );
1846 AtEase::restoreWarnings();
1847 } elseif ( $newLimit > $oldLimit ) {
1848 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1849 AtEase::suppressWarnings();
1850 ini_set( 'memory_limit', $newLimit );
1851 AtEase::restoreWarnings();
1852 }
1853 }
1854}
1855
1864
1865 $timeout = RequestTimeout::singleton();
1866 $timeLimit = $timeout->getWallTimeLimit();
1867 if ( $timeLimit !== INF ) {
1868 // RequestTimeout library is active
1869 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1870 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1871 }
1872 } else {
1873 // Fallback case, likely $wgRequestTimeLimit === null
1874 $timeLimit = (int)ini_get( 'max_execution_time' );
1875 // Note that CLI scripts use 0
1876 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
1877 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1878 }
1879 }
1880 ignore_user_abort( true ); // ignore client disconnects
1881
1882 return $timeLimit;
1883}
1884
1892function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
1893 $string = trim( $string ?? '' );
1894 if ( $string === '' ) {
1895 return $default;
1896 }
1897 $last = substr( $string, -1 );
1898 $val = intval( $string );
1899 switch ( $last ) {
1900 case 'g':
1901 case 'G':
1902 $val *= 1024;
1903 // break intentionally missing
1904 case 'm':
1905 case 'M':
1906 $val *= 1024;
1907 // break intentionally missing
1908 case 'k':
1909 case 'K':
1910 $val *= 1024;
1911 }
1912
1913 return $val;
1914}
1915
1923function wfIsInfinity( $str ) {
1924 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
1925 return in_array( $str, ExpiryDef::INFINITY_VALS );
1926}
1927
1942function wfThumbIsStandard( File $file, array $params ) {
1944
1945 $multipliers = [ 1 ];
1946 if ( $wgResponsiveImages ) {
1947 // These available sizes are hardcoded currently elsewhere in MediaWiki.
1948 // @see Linker::processResponsiveImages
1949 $multipliers[] = 1.5;
1950 $multipliers[] = 2;
1951 }
1952
1953 $handler = $file->getHandler();
1954 if ( !$handler || !isset( $params['width'] ) ) {
1955 return false;
1956 }
1957
1958 $basicParams = [];
1959 if ( isset( $params['page'] ) ) {
1960 $basicParams['page'] = $params['page'];
1961 }
1962
1963 $thumbLimits = [];
1964 $imageLimits = [];
1965 // Expand limits to account for multipliers
1966 foreach ( $multipliers as $multiplier ) {
1967 $thumbLimits = array_merge( $thumbLimits, array_map(
1968 static function ( $width ) use ( $multiplier ) {
1969 return round( $width * $multiplier );
1970 }, $wgThumbLimits )
1971 );
1972 $imageLimits = array_merge( $imageLimits, array_map(
1973 static function ( $pair ) use ( $multiplier ) {
1974 return [
1975 round( $pair[0] * $multiplier ),
1976 round( $pair[1] * $multiplier ),
1977 ];
1978 }, $wgImageLimits )
1979 );
1980 }
1981
1982 // Check if the width matches one of $wgThumbLimits
1983 if ( in_array( $params['width'], $thumbLimits ) ) {
1984 $normalParams = $basicParams + [ 'width' => $params['width'] ];
1985 // Append any default values to the map (e.g. "lossy", "lossless", ...)
1986 $handler->normaliseParams( $file, $normalParams );
1987 } else {
1988 // If not, then check if the width matches one of $wgImageLimits
1989 $match = false;
1990 foreach ( $imageLimits as $pair ) {
1991 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
1992 // Decide whether the thumbnail should be scaled on width or height.
1993 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
1994 $handler->normaliseParams( $file, $normalParams );
1995 // Check if this standard thumbnail size maps to the given width
1996 if ( $normalParams['width'] == $params['width'] ) {
1997 $match = true;
1998 break;
1999 }
2000 }
2001 if ( !$match ) {
2002 return false; // not standard for description pages
2003 }
2004 }
2005
2006 // Check that the given values for non-page, non-width, params are just defaults
2007 foreach ( $params as $key => $value ) {
2008 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2009 return false;
2010 }
2011 }
2012
2013 return true;
2014}
2015
2028function wfArrayPlus2d( array $baseArray, array $newValues ) {
2029 // First merge items that are in both arrays
2030 foreach ( $baseArray as $name => &$groupVal ) {
2031 if ( isset( $newValues[$name] ) ) {
2032 $groupVal += $newValues[$name];
2033 }
2034 }
2035 // Now add items that didn't exist yet
2036 $baseArray += $newValues;
2037
2038 return $baseArray;
2039}
wfIsWindows()
Check if the operating system is Windows.
const PROTO_CURRENT
Definition Defines.php:222
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().
wfTimestampOrNull( $outputtype=TS::UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
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.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
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.
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...
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 partial regular expression of recognized URL protocols, e.g.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, ?string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
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.
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
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.
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.
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:434
if(MW_ENTRY_POINT==='index') if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgOut
Definition Setup.php:551
const MW_ENTRY_POINT
Definition api.php:21
Debug toolbar.
Definition MWDebug.php:35
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:79
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1619
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 Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:144
Load JSON files, and uses a Processor to extract information.
Handle sending Content-Security-Policy headers.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Executes shell commands.
Definition Shell.php:32
Represents a title within MediaWiki.
Definition Title.php:69
A service to expand, parse, and otherwise manipulate URLs.
Definition UrlUtils.php:16
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
Base class for all file backend classes (including multi-write backends).
Value object representing a message parameter with one of the types from {.
Type definition for expiry timestamps.
Definition ExpiryDef.php:18
$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.
$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