MediaWiki master
GlobalFunctions.php
Go to the documentation of this file.
1<?php
35use Wikimedia\AtEase\AtEase;
41use Wikimedia\RequestTimeout\RequestTimeout;
42use Wikimedia\Timestamp\ConvertibleTimestamp;
43
54function wfLoadExtension( $ext, $path = null ) {
55 if ( !$path ) {
57 $path = "$wgExtensionDirectory/$ext/extension.json";
58 }
59 ExtensionRegistry::getInstance()->queue( $path );
60}
61
75function wfLoadExtensions( array $exts ) {
77 $registry = ExtensionRegistry::getInstance();
78 foreach ( $exts as $ext ) {
79 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
80 }
81}
82
91function wfLoadSkin( $skin, $path = null ) {
92 if ( !$path ) {
93 global $wgStyleDirectory;
94 $path = "$wgStyleDirectory/$skin/skin.json";
95 }
96 ExtensionRegistry::getInstance()->queue( $path );
97}
98
106function wfLoadSkins( array $skins ) {
107 global $wgStyleDirectory;
108 $registry = ExtensionRegistry::getInstance();
109 foreach ( $skins as $skin ) {
110 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
111 }
112}
113
121function wfArrayDiff2( $arr1, $arr2 ) {
122 wfDeprecated( __FUNCTION__, '1.43' );
127 $comparator = static function ( $a, $b ): int {
128 if ( is_string( $a ) && is_string( $b ) ) {
129 return strcmp( $a, $b );
130 }
131 if ( !is_array( $a ) && !is_array( $b ) ) {
132 throw new InvalidArgumentException(
133 'This function assumes that array elements are all strings or all arrays'
134 );
135 }
136 if ( count( $a ) !== count( $b ) ) {
137 return count( $a ) <=> count( $b );
138 } else {
139 reset( $a );
140 reset( $b );
141 while ( key( $a ) !== null && key( $b ) !== null ) {
142 $valueA = current( $a );
143 $valueB = current( $b );
144 $cmp = strcmp( $valueA, $valueB );
145 if ( $cmp !== 0 ) {
146 return $cmp;
147 }
148 next( $a );
149 next( $b );
150 }
151 return 0;
152 }
153 };
154 return array_udiff( $arr1, $arr2, $comparator );
155}
156
177function wfMergeErrorArrays( ...$args ) {
178 wfDeprecated( __FUNCTION__, '1.43' );
179 $out = [];
180 foreach ( $args as $errors ) {
181 foreach ( $errors as $params ) {
182 $originalParams = $params;
183 if ( $params[0] instanceof MessageSpecifier ) {
184 $params = [ $params[0]->getKey(), ...$params[0]->getParams() ];
185 }
186 # @todo FIXME: Sometimes get nested arrays for $params,
187 # which leads to E_NOTICEs
188 $spec = implode( "\t", $params );
189 $out[$spec] = $originalParams;
190 }
191 }
192 return array_values( $out );
193}
194
204function wfArrayInsertAfter( array $array, array $insert, $after ) {
205 // Find the offset of the element to insert after.
206 $keys = array_keys( $array );
207 $offsetByKey = array_flip( $keys );
208
209 if ( !\array_key_exists( $after, $offsetByKey ) ) {
210 return $array;
211 }
212 $offset = $offsetByKey[$after];
213
214 // Insert at the specified offset
215 $before = array_slice( $array, 0, $offset + 1, true );
216 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
217
218 $output = $before + $insert + $after;
219
220 return $output;
221}
222
231function wfObjectToArray( $objOrArray, $recursive = true ) {
232 $array = [];
233 if ( is_object( $objOrArray ) ) {
234 $objOrArray = get_object_vars( $objOrArray );
235 }
236 foreach ( $objOrArray as $key => $value ) {
237 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
238 $value = wfObjectToArray( $value );
239 }
240
241 $array[$key] = $value;
242 }
243
244 return $array;
245}
246
257function wfRandom() {
258 // The maximum random value is "only" 2^31-1, so get two random
259 // values to reduce the chance of dupes
260 $max = mt_getrandmax() + 1;
261 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
262 return $rand;
263}
264
275function wfRandomString( $length = 32 ) {
276 $str = '';
277 for ( $n = 0; $n < $length; $n += 7 ) {
278 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
279 }
280 return substr( $str, 0, $length );
281}
282
310function wfUrlencode( $s ) {
311 static $needle;
312
313 if ( $s === null ) {
314 // Reset $needle for testing.
315 $needle = null;
316 return '';
317 }
318
319 if ( $needle === null ) {
320 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
321 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
322 !str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
323 ) {
324 $needle[] = '%3A';
325 }
326 }
327
328 $s = urlencode( $s );
329 $s = str_ireplace(
330 $needle,
331 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
332 $s
333 );
334
335 return $s;
336}
337
348function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
349 if ( $array2 !== null ) {
350 $array1 += $array2;
351 }
352
353 $cgi = '';
354 foreach ( $array1 as $key => $value ) {
355 if ( $value !== null && $value !== false ) {
356 if ( $cgi != '' ) {
357 $cgi .= '&';
358 }
359 if ( $prefix !== '' ) {
360 $key = $prefix . "[$key]";
361 }
362 if ( is_array( $value ) ) {
363 $firstTime = true;
364 foreach ( $value as $k => $v ) {
365 $cgi .= $firstTime ? '' : '&';
366 if ( is_array( $v ) ) {
367 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
368 } else {
369 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
370 }
371 $firstTime = false;
372 }
373 } else {
374 if ( is_object( $value ) ) {
375 $value = $value->__toString();
376 }
377 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
378 }
379 }
380 }
381 return $cgi;
382}
383
393function wfCgiToArray( $query ) {
394 if ( isset( $query[0] ) && $query[0] == '?' ) {
395 $query = substr( $query, 1 );
396 }
397 $bits = explode( '&', $query );
398 $ret = [];
399 foreach ( $bits as $bit ) {
400 if ( $bit === '' ) {
401 continue;
402 }
403 if ( strpos( $bit, '=' ) === false ) {
404 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
405 $key = $bit;
406 $value = '';
407 } else {
408 [ $key, $value ] = explode( '=', $bit );
409 }
410 $key = urldecode( $key );
411 $value = urldecode( $value );
412 if ( strpos( $key, '[' ) !== false ) {
413 $keys = array_reverse( explode( '[', $key ) );
414 $key = array_pop( $keys );
415 $temp = $value;
416 foreach ( $keys as $k ) {
417 $k = substr( $k, 0, -1 );
418 $temp = [ $k => $temp ];
419 }
420 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
421 $ret[$key] = array_merge( $ret[$key], $temp );
422 } else {
423 $ret[$key] = $temp;
424 }
425 } else {
426 $ret[$key] = $value;
427 }
428 }
429 return $ret;
430}
431
440function wfAppendQuery( $url, $query ) {
441 if ( is_array( $query ) ) {
442 $query = wfArrayToCgi( $query );
443 }
444 if ( $query != '' ) {
445 // Remove the fragment, if there is one
446 $fragment = false;
447 $hashPos = strpos( $url, '#' );
448 if ( $hashPos !== false ) {
449 $fragment = substr( $url, $hashPos );
450 $url = substr( $url, 0, $hashPos );
451 }
452
453 // Add parameter
454 if ( strpos( $url, '?' ) === false ) {
455 $url .= '?';
456 } else {
457 $url .= '&';
458 }
459 $url .= $query;
460
461 // Put the fragment back
462 if ( $fragment !== false ) {
463 $url .= $fragment;
464 }
465 }
466 return $url;
467}
468
477
478 if ( MediaWikiServices::hasInstance() ) {
479 $services = MediaWikiServices::getInstance();
480 if ( $services->hasService( 'UrlUtils' ) ) {
481 return $services->getUrlUtils();
482 }
483 }
484
485 return new UrlUtils( [
486 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
487 // implementations implicitly converted it to an empty string (presumably by mistake).
488 // Preserve the old behavior for compatibility.
489 UrlUtils::SERVER => $wgServer ?? '',
490 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
491 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
492 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
493 : WebRequest::detectProtocol(),
494 UrlUtils::HTTPS_PORT => $wgHttpsPort,
495 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
496 ] );
497}
498
526function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
527 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
528}
529
539function wfGetServerUrl( $proto ) {
540 wfDeprecated( __FUNCTION__, '1.39' );
541
542 return wfGetUrlUtils()->getServer( $proto ) ?? '';
543}
544
557function wfAssembleUrl( $urlParts ) {
558 wfDeprecated( __FUNCTION__, '1.39' );
559
560 return UrlUtils::assemble( (array)$urlParts );
561}
562
571function wfUrlProtocols( $includeProtocolRelative = true ) {
572 wfDeprecated( __FUNCTION__, '1.39' );
573
574 return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() :
575 wfGetUrlUtils()->validAbsoluteProtocols();
576}
577
586 wfDeprecated( __FUNCTION__, '1.39' );
587
588 return wfGetUrlUtils()->validAbsoluteProtocols();
589}
590
617function wfParseUrl( $url ) {
618 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
619}
620
630function wfExpandIRI( $url ) {
631 wfDeprecated( __FUNCTION__, '1.39' );
632
633 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
634}
635
644function wfMatchesDomainList( $url, $domains ) {
645 wfDeprecated( __FUNCTION__, '1.39' );
646
647 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
648}
649
670function wfDebug( $text, $dest = 'all', array $context = [] ) {
672
673 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
674 return;
675 }
676
677 $text = trim( $text );
678
679 if ( $wgDebugLogPrefix !== '' ) {
680 $context['prefix'] = $wgDebugLogPrefix;
681 }
682 $context['private'] = ( $dest === false || $dest === 'private' );
683
684 $logger = LoggerFactory::getInstance( 'wfDebug' );
685 $logger->debug( $text, $context );
686}
687
693 static $cache;
694 if ( $cache !== null ) {
695 return $cache;
696 }
697 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
698 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
699 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
700 || MW_ENTRY_POINT === 'load'
701 ) {
702 $cache = true;
703 } else {
704 $cache = false;
705 }
706 return $cache;
707}
708
734function wfDebugLog(
735 $logGroup, $text, $dest = 'all', array $context = []
736) {
737 $text = trim( $text );
738
739 $logger = LoggerFactory::getInstance( $logGroup );
740 $context['private'] = ( $dest === false || $dest === 'private' );
741 $logger->info( $text, $context );
742}
743
752function wfLogDBError( $text, array $context = [] ) {
753 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
754 $logger->error( trim( $text ), $context );
755}
756
773function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
774 if ( !is_string( $version ) && $version !== false ) {
775 throw new InvalidArgumentException(
776 "MediaWiki version must either be a string or false. " .
777 "Example valid version: '1.33'"
778 );
779 }
780
781 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
782}
783
804function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
805 MWDebug::deprecatedMsg( $msg, $version, $component,
806 $callerOffset === false ? false : $callerOffset + 1 );
807}
808
819function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
820 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
821}
822
832function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
833 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
834}
835
858function wfMessage( $key, ...$params ) {
859 if ( is_array( $key ) ) {
860 // Fallback keys are not allowed in message specifiers
861 $message = wfMessageFallback( ...$key );
862 } else {
863 $message = Message::newFromSpecifier( $key );
864 }
865
866 // We call Message::params() to reduce code duplication
867 if ( $params ) {
868 $message->params( ...$params );
869 }
870
871 return $message;
872}
873
886function wfMessageFallback( ...$keys ) {
887 return Message::newFallbackSequence( ...$keys );
888}
889
898function wfMsgReplaceArgs( $message, $args ) {
899 # Fix windows line-endings
900 # Some messages are split with explode("\n", $msg)
901 $message = str_replace( "\r", '', $message );
902
903 // Replace arguments
904 if ( is_array( $args ) && $args ) {
905 if ( is_array( $args[0] ) ) {
906 $args = array_values( $args[0] );
907 }
908 $replacementKeys = [];
909 foreach ( $args as $n => $param ) {
910 $replacementKeys['$' . ( $n + 1 )] = $param;
911 }
912 $message = strtr( $message, $replacementKeys );
913 }
914
915 return $message;
916}
917
926function wfHostname() {
927 // Hostname overriding
928 global $wgOverrideHostname;
929 if ( $wgOverrideHostname !== false ) {
930 return $wgOverrideHostname;
931 }
932
933 return php_uname( 'n' ) ?: 'unknown';
934}
935
946function wfDebugBacktrace( $limit = 0 ) {
947 static $disabled = null;
948
949 if ( $disabled === null ) {
950 $disabled = !function_exists( 'debug_backtrace' );
951 if ( $disabled ) {
952 wfDebug( "debug_backtrace() is disabled" );
953 }
954 }
955 if ( $disabled ) {
956 return [];
957 }
958
959 if ( $limit ) {
960 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
961 } else {
962 return array_slice( debug_backtrace(), 1 );
963 }
964}
965
974function wfBacktrace( $raw = null ) {
975 $raw ??= MW_ENTRY_POINT === 'cli';
976 if ( $raw ) {
977 $frameFormat = "%s line %s calls %s()\n";
978 $traceFormat = "%s";
979 } else {
980 $frameFormat = "<li>%s line %s calls %s()</li>\n";
981 $traceFormat = "<ul>\n%s</ul>\n";
982 }
983
984 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
985 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
986 $line = $frame['line'] ?? '-';
987 $call = $frame['function'];
988 if ( !empty( $frame['class'] ) ) {
989 $call = $frame['class'] . $frame['type'] . $call;
990 }
991 return sprintf( $frameFormat, $file, $line, $call );
992 }, wfDebugBacktrace() );
993
994 return sprintf( $traceFormat, implode( '', $frames ) );
995}
996
1007function wfGetCaller( $level = 2 ) {
1008 $backtrace = wfDebugBacktrace( $level + 1 );
1009 if ( isset( $backtrace[$level] ) ) {
1010 return wfFormatStackFrame( $backtrace[$level] );
1011 } else {
1012 return 'unknown';
1013 }
1014}
1015
1023function wfGetAllCallers( $limit = 3 ) {
1024 $trace = array_reverse( wfDebugBacktrace() );
1025 if ( !$limit || $limit > count( $trace ) - 1 ) {
1026 $limit = count( $trace ) - 1;
1027 }
1028 $trace = array_slice( $trace, -$limit - 1, $limit );
1029 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1030}
1031
1044function wfFormatStackFrame( $frame ) {
1045 if ( !isset( $frame['function'] ) ) {
1046 return 'NO_FUNCTION_GIVEN';
1047 }
1048 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1049 $frame['class'] . $frame['type'] . $frame['function'] :
1050 $frame['function'];
1051}
1052
1062function wfClientAcceptsGzip( $force = false ) {
1063 static $result = null;
1064 if ( $result === null || $force ) {
1065 $result = false;
1066 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1067 # @todo FIXME: We may want to disallow some broken browsers
1068 $m = [];
1069 if ( preg_match(
1070 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1071 $_SERVER['HTTP_ACCEPT_ENCODING'],
1072 $m
1073 )
1074 ) {
1075 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1076 return $result;
1077 }
1078 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1079 $result = true;
1080 }
1081 }
1082 }
1083 return $result;
1084}
1085
1096function wfEscapeWikiText( $input ): string {
1097 global $wgEnableMagicLinks;
1098 static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
1099 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1100 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1101 // in those situations
1102 $repl = [
1103 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1104 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1105 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1106 ';' => '&#59;', // a token inside language converter brackets
1107 '!!' => '&#33;!', // a token inside table context
1108 "\n!" => "\n&#33;", "\r!" => "\r&#33;", // a token inside table context
1109 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1110 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1111 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1112 "\n " => "\n&#32;", "\r " => "\r&#32;",
1113 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1114 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1115 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1116 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1117 '__' => '_&#95;', '://' => '&#58;//',
1118 '~~~' => '~~&#126;', // protect from PST, just to be safe(r)
1119 ];
1120
1121 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1122 // We have to catch everything "\s" matches in PCRE
1123 foreach ( $magicLinks as $magic ) {
1124 $repl["$magic "] = "$magic&#32;";
1125 $repl["$magic\t"] = "$magic&#9;";
1126 $repl["$magic\r"] = "$magic&#13;";
1127 $repl["$magic\n"] = "$magic&#10;";
1128 $repl["$magic\f"] = "$magic&#12;";
1129 }
1130 // Additionally escape the following characters at the beginning of the
1131 // string, in case they merge to form tokens when spliced into a
1132 // string. Tokens like -{ {{ [[ {| etc are already escaped because
1133 // the second character is escaped above, but the following tokens
1134 // are handled here: |+ |- __FOO__ ~~~
1135 $repl3 = [
1136 '+' => '&#43;', '-' => '&#45;', '_' => '&#95;', '~' => '&#126;',
1137 ];
1138 // Similarly, protect the following characters at the end of the
1139 // string, which could turn form the start of `__FOO__` or `~~~~`
1140 // A trailing newline could also form the unintended start of a
1141 // paragraph break if it is glued to a newline in the following
1142 // context.
1143 $repl4 = [
1144 '_' => '&#95;', '~' => '&#126;',
1145 "\n" => "&#10;", "\r" => "&#13;",
1146 "\t" => "&#9;", // "\n\t\n" is treated like "\n\n"
1147 ];
1148
1149 // And handle protocols that don't use "://"
1150 global $wgUrlProtocols;
1151 $repl2 = [];
1152 foreach ( $wgUrlProtocols as $prot ) {
1153 if ( substr( $prot, -1 ) === ':' ) {
1154 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1155 }
1156 }
1157 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1158 }
1159 // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
1160 '@phan-var string $repl2';
1161 '@phan-var string $repl3';
1162 '@phan-var string $repl4';
1163 // This will also stringify input in case it's not a string
1164 $text = substr( strtr( "\n$input", $repl ), 1 );
1165 if ( $text === '' ) {
1166 return $text;
1167 }
1168 $first = strtr( $text[0], $repl3 ); // protect first character
1169 if ( strlen( $text ) > 1 ) {
1170 $text = $first . substr( $text, 1, -1 ) .
1171 strtr( substr( $text, -1 ), $repl4 ); // protect last character
1172 } else {
1173 // special case for single-character strings
1174 $text = strtr( $first, $repl4 ); // protect last character
1175 }
1176 $text = preg_replace( $repl2, '$1&#58;', $text );
1177 return $text;
1178}
1179
1190function wfSetVar( &$dest, $source, $force = false ) {
1191 $temp = $dest;
1192 if ( $source !== null || $force ) {
1193 $dest = $source;
1194 }
1195 return $temp;
1196}
1197
1207function wfSetBit( &$dest, $bit, $state = true ) {
1208 $temp = (bool)( $dest & $bit );
1209 if ( $state !== null ) {
1210 if ( $state ) {
1211 $dest |= $bit;
1212 } else {
1213 $dest &= ~$bit;
1214 }
1215 }
1216 return $temp;
1217}
1218
1225function wfVarDump( $var ) {
1226 global $wgOut;
1227 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1228 if ( headers_sent() || $wgOut === null || !is_object( $wgOut ) ) {
1229 print $s;
1230 } else {
1231 $wgOut->addHTML( $s );
1232 }
1233}
1234
1242function wfHttpError( $code, $label, $desc ) {
1243 global $wgOut;
1244 HttpStatus::header( $code );
1245 if ( $wgOut ) {
1246 $wgOut->disable();
1247 $wgOut->sendCacheControl();
1248 }
1249
1250 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1251 header( 'Content-type: text/html; charset=utf-8' );
1252 ob_start();
1253 print '<!DOCTYPE html>' .
1254 '<html><head><title>' .
1255 htmlspecialchars( $label ) .
1256 '</title><meta name="color-scheme" content="light dark" /></head><body><h1>' .
1257 htmlspecialchars( $label ) .
1258 '</h1><p>' .
1259 nl2br( htmlspecialchars( $desc ) ) .
1260 "</p></body></html>\n";
1261 header( 'Content-Length: ' . ob_get_length() );
1262 ob_end_flush();
1263}
1264
1285function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1286 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
1287 while ( $status = ob_get_status() ) {
1288 if ( isset( $status['flags'] ) ) {
1289 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1290 $deleteable = ( $status['flags'] & $flags ) === $flags;
1291 } elseif ( isset( $status['del'] ) ) {
1292 $deleteable = $status['del'];
1293 } else {
1294 // Guess that any PHP-internal setting can't be removed.
1295 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1296 }
1297 if ( !$deleteable ) {
1298 // Give up, and hope the result doesn't break
1299 // output behavior.
1300 break;
1301 }
1302 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1303 // Unit testing barrier to prevent this function from breaking PHPUnit.
1304 break;
1305 }
1306 if ( !ob_end_clean() ) {
1307 // Could not remove output buffer handler; abort now
1308 // to avoid getting in some kind of infinite loop.
1309 break;
1310 }
1311 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1312 // Reset the 'Content-Encoding' field set by this handler
1313 // so we can start fresh.
1314 header_remove( 'Content-Encoding' );
1315 break;
1316 }
1317 }
1318}
1319
1330function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1331 $ret = ConvertibleTimestamp::convert( $outputtype, $ts );
1332 if ( $ret === false ) {
1333 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1334 }
1335 return $ret;
1336}
1337
1346function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1347 if ( $ts === null ) {
1348 return null;
1349 } else {
1350 return wfTimestamp( $outputtype, $ts );
1351 }
1352}
1353
1359function wfTimestampNow() {
1360 return ConvertibleTimestamp::now( TS_MW );
1361}
1362
1374function wfTempDir() {
1375 global $wgTmpDirectory;
1376
1377 if ( $wgTmpDirectory !== false ) {
1378 return $wgTmpDirectory;
1379 }
1380
1381 return TempFSFile::getUsableTempDirectory();
1382}
1383
1392function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1393 global $wgDirectoryMode;
1394
1395 if ( FileBackend::isStoragePath( $dir ) ) {
1396 throw new LogicException( __FUNCTION__ . " given storage path '$dir'." );
1397 }
1398 if ( $caller !== null ) {
1399 wfDebug( "$caller: called wfMkdirParents($dir)" );
1400 }
1401 if ( strval( $dir ) === '' ) {
1402 return true;
1403 }
1404
1405 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1406 $mode ??= $wgDirectoryMode;
1407
1408 // Turn off the normal warning, we're doing our own below
1409 // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis.
1410 //
1411 // Repeat existence check if creation failed so that we silently recover in case of
1412 // a race condition where another request created it since the first check.
1413 //
1414 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1415 $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir );
1416 if ( !$ok ) {
1417 trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING );
1418 }
1419
1420 return $ok;
1421}
1422
1428function wfRecursiveRemoveDir( $dir ) {
1429 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1430 if ( is_dir( $dir ) ) {
1431 $objects = scandir( $dir );
1432 foreach ( $objects as $object ) {
1433 if ( $object != "." && $object != ".." ) {
1434 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1435 wfRecursiveRemoveDir( $dir . '/' . $object );
1436 } else {
1437 unlink( $dir . '/' . $object );
1438 }
1439 }
1440 }
1441 rmdir( $dir );
1442 }
1443}
1444
1451function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1452 $accForFormat = $acc >= 0 ? $acc : 0;
1453 $ret = sprintf( "%.{$accForFormat}f", $nr );
1454 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1455}
1456
1480function wfIniGetBool( $setting ) {
1481 return wfStringToBool( ini_get( $setting ) );
1482}
1483
1496function wfStringToBool( $val ) {
1497 $val = strtolower( $val );
1498 // 'on' and 'true' can't have whitespace around them, but '1' can.
1499 return $val == 'on'
1500 || $val == 'true'
1501 || $val == 'yes'
1502 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1503}
1504
1518function wfEscapeShellArg( ...$args ) {
1519 return Shell::escape( ...$args );
1520}
1521
1546function wfShellExec( $cmd, &$retval = null, $environ = [],
1547 $limits = [], $options = []
1548) {
1549 if ( Shell::isDisabled() ) {
1550 $retval = 1;
1551 // Backwards compatibility be upon us...
1552 return 'Unable to run external programs, proc_open() is disabled.';
1553 }
1554
1555 if ( is_array( $cmd ) ) {
1556 $cmd = Shell::escape( $cmd );
1557 }
1558
1559 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1560 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1561
1562 try {
1563 $result = Shell::command( [] )
1564 ->unsafeParams( (array)$cmd )
1565 ->environment( $environ )
1566 ->limits( $limits )
1567 ->includeStderr( $includeStderr )
1568 ->profileMethod( $profileMethod )
1569 // For b/c
1570 ->restrict( Shell::RESTRICT_NONE )
1571 ->execute();
1572 } catch ( ProcOpenError $ex ) {
1573 $retval = -1;
1574 return '';
1575 }
1576
1577 $retval = $result->getExitCode();
1578
1579 return $result->getStdout();
1580}
1581
1599function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1600 return wfShellExec( $cmd, $retval, $environ, $limits,
1601 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1602}
1603
1619function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1620 global $wgPhpCli;
1621 // Give site config file a chance to run the script in a wrapper.
1622 // The caller may likely want to call wfBasename() on $script.
1623 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1624 ->onWfShellWikiCmd( $script, $parameters, $options );
1625 $cmd = [ $options['php'] ?? $wgPhpCli ];
1626 if ( isset( $options['wrapper'] ) ) {
1627 $cmd[] = $options['wrapper'];
1628 }
1629 $cmd[] = $script;
1630 // Escape each parameter for shell
1631 return Shell::escape( array_merge( $cmd, $parameters ) );
1632}
1633
1650function wfMerge(
1651 string $old,
1652 string $mine,
1653 string $yours,
1654 ?string &$simplisticMergeAttempt,
1655 ?string &$mergeLeftovers = null
1656): bool {
1657 global $wgDiff3;
1658
1659 # This check may also protect against code injection in
1660 # case of broken installations.
1661 AtEase::suppressWarnings();
1662 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1663 AtEase::restoreWarnings();
1664
1665 if ( !$haveDiff3 ) {
1666 wfDebug( "diff3 not found" );
1667 return false;
1668 }
1669
1670 # Make temporary files
1671 $td = wfTempDir();
1672 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1673 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1674 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1675
1676 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1677 # a newline character. To avoid this, we normalize the trailing whitespace before
1678 # creating the diff.
1679
1680 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1681 fclose( $oldtextFile );
1682 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1683 fclose( $mytextFile );
1684 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1685 fclose( $yourtextFile );
1686
1687 # Check for a conflict
1688 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1689 $oldtextName, $yourtextName );
1690 $handle = popen( $cmd, 'r' );
1691
1692 $mergeLeftovers = '';
1693 do {
1694 $data = fread( $handle, 8192 );
1695 if ( $data === false || $data === '' ) {
1696 break;
1697 }
1698 $mergeLeftovers .= $data;
1699 } while ( true );
1700 pclose( $handle );
1701
1702 $conflict = $mergeLeftovers !== '';
1703
1704 # Merge differences automatically where possible, preferring "my" text for conflicts.
1705 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1706 $oldtextName, $yourtextName );
1707 $handle = popen( $cmd, 'r' );
1708 $simplisticMergeAttempt = '';
1709 do {
1710 $data = fread( $handle, 8192 );
1711 if ( $data === false || $data === '' ) {
1712 break;
1713 }
1714 $simplisticMergeAttempt .= $data;
1715 } while ( true );
1716 pclose( $handle );
1717 unlink( $mytextName );
1718 unlink( $oldtextName );
1719 unlink( $yourtextName );
1720
1721 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1722 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1723 $conflict = true;
1724 }
1725 return !$conflict;
1726}
1727
1740function wfBaseName( $path, $suffix = '' ) {
1741 if ( $suffix == '' ) {
1742 $encSuffix = '';
1743 } else {
1744 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1745 }
1746
1747 $matches = [];
1748 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1749 return $matches[1];
1750 } else {
1751 return '';
1752 }
1753}
1754
1764function wfRelativePath( $path, $from ) {
1765 // Normalize mixed input on Windows...
1766 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1767 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1768
1769 // Trim trailing slashes -- fix for drive root
1770 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1771 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1772
1773 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1774 $against = explode( DIRECTORY_SEPARATOR, $from );
1775
1776 if ( $pieces[0] !== $against[0] ) {
1777 // Non-matching Windows drive letters?
1778 // Return a full path.
1779 return $path;
1780 }
1781
1782 // Trim off common prefix
1783 while ( count( $pieces ) && count( $against )
1784 && $pieces[0] == $against[0] ) {
1785 array_shift( $pieces );
1786 array_shift( $against );
1787 }
1788
1789 // relative dots to bump us to the parent
1790 while ( count( $against ) ) {
1791 array_unshift( $pieces, '..' );
1792 array_shift( $against );
1793 }
1794
1795 $pieces[] = wfBaseName( $path );
1796
1797 return implode( DIRECTORY_SEPARATOR, $pieces );
1798}
1799
1809function wfScript( $script = 'index' ) {
1811 if ( $script === 'index' ) {
1812 return $wgScript;
1813 } elseif ( $script === 'load' ) {
1814 return $wgLoadScript;
1815 } else {
1816 return "{$wgScriptPath}/{$script}.php";
1817 }
1818}
1819
1827function wfBoolToStr( $value ) {
1828 return $value ? 'true' : 'false';
1829}
1830
1836function wfGetNull() {
1837 return wfIsWindows() ? 'NUL' : '/dev/null';
1838}
1839
1849 global $wgIllegalFileChars;
1850 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1851 $name = preg_replace(
1852 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1853 '-',
1854 $name
1855 );
1856 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1857 $name = wfBaseName( $name );
1858 return $name;
1859}
1860
1867function wfMemoryLimit( $newLimit ) {
1868 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1869 // If the INI config is already unlimited, there is nothing larger
1870 if ( $oldLimit != -1 ) {
1871 $newLimit = wfShorthandToInteger( (string)$newLimit );
1872 if ( $newLimit == -1 ) {
1873 wfDebug( "Removing PHP's memory limit" );
1874 AtEase::suppressWarnings();
1875 ini_set( 'memory_limit', $newLimit );
1876 AtEase::restoreWarnings();
1877 } elseif ( $newLimit > $oldLimit ) {
1878 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1879 AtEase::suppressWarnings();
1880 ini_set( 'memory_limit', $newLimit );
1881 AtEase::restoreWarnings();
1882 }
1883 }
1884}
1885
1894
1895 $timeout = RequestTimeout::singleton();
1896 $timeLimit = $timeout->getWallTimeLimit();
1897 if ( $timeLimit !== INF ) {
1898 // RequestTimeout library is active
1899 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1900 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1901 }
1902 } else {
1903 // Fallback case, likely $wgRequestTimeLimit === null
1904 $timeLimit = (int)ini_get( 'max_execution_time' );
1905 // Note that CLI scripts use 0
1906 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
1907 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1908 }
1909 }
1910 ignore_user_abort( true ); // ignore client disconnects
1911
1912 return $timeLimit;
1913}
1914
1922function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
1923 $string = trim( $string ?? '' );
1924 if ( $string === '' ) {
1925 return $default;
1926 }
1927 $last = $string[strlen( $string ) - 1];
1928 $val = intval( $string );
1929 switch ( $last ) {
1930 case 'g':
1931 case 'G':
1932 $val *= 1024;
1933 // break intentionally missing
1934 case 'm':
1935 case 'M':
1936 $val *= 1024;
1937 // break intentionally missing
1938 case 'k':
1939 case 'K':
1940 $val *= 1024;
1941 }
1942
1943 return $val;
1944}
1945
1953function wfIsInfinity( $str ) {
1954 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
1955 return in_array( $str, ExpiryDef::INFINITY_VALS );
1956}
1957
1972function wfThumbIsStandard( File $file, array $params ) {
1974
1975 $multipliers = [ 1 ];
1976 if ( $wgResponsiveImages ) {
1977 // These available sizes are hardcoded currently elsewhere in MediaWiki.
1978 // @see Linker::processResponsiveImages
1979 $multipliers[] = 1.5;
1980 $multipliers[] = 2;
1981 }
1982
1983 $handler = $file->getHandler();
1984 if ( !$handler || !isset( $params['width'] ) ) {
1985 return false;
1986 }
1987
1988 $basicParams = [];
1989 if ( isset( $params['page'] ) ) {
1990 $basicParams['page'] = $params['page'];
1991 }
1992
1993 $thumbLimits = [];
1994 $imageLimits = [];
1995 // Expand limits to account for multipliers
1996 foreach ( $multipliers as $multiplier ) {
1997 $thumbLimits = array_merge( $thumbLimits, array_map(
1998 static function ( $width ) use ( $multiplier ) {
1999 return round( $width * $multiplier );
2000 }, $wgThumbLimits )
2001 );
2002 $imageLimits = array_merge( $imageLimits, array_map(
2003 static function ( $pair ) use ( $multiplier ) {
2004 return [
2005 round( $pair[0] * $multiplier ),
2006 round( $pair[1] * $multiplier ),
2007 ];
2008 }, $wgImageLimits )
2009 );
2010 }
2011
2012 // Check if the width matches one of $wgThumbLimits
2013 if ( in_array( $params['width'], $thumbLimits ) ) {
2014 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2015 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2016 $handler->normaliseParams( $file, $normalParams );
2017 } else {
2018 // If not, then check if the width matches one of $wgImageLimits
2019 $match = false;
2020 foreach ( $imageLimits as $pair ) {
2021 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2022 // Decide whether the thumbnail should be scaled on width or height.
2023 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2024 $handler->normaliseParams( $file, $normalParams );
2025 // Check if this standard thumbnail size maps to the given width
2026 if ( $normalParams['width'] == $params['width'] ) {
2027 $match = true;
2028 break;
2029 }
2030 }
2031 if ( !$match ) {
2032 return false; // not standard for description pages
2033 }
2034 }
2035
2036 // Check that the given values for non-page, non-width, params are just defaults
2037 foreach ( $params as $key => $value ) {
2038 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2039 return false;
2040 }
2041 }
2042
2043 return true;
2044}
2045
2058function wfArrayPlus2d( array $baseArray, array $newValues ) {
2059 // First merge items that are in both arrays
2060 foreach ( $baseArray as $name => &$groupVal ) {
2061 if ( isset( $newValues[$name] ) ) {
2062 $groupVal += $newValues[$name];
2063 }
2064 }
2065 // Now add items that didn't exist yet
2066 $baseArray += $newValues;
2067
2068 return $baseArray;
2069}
wfIsWindows()
Check if the operating system is Windows.
const PROTO_CURRENT
Definition Defines.php:236
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
wfVarDump( $var)
A wrapper around the PHP function var_export().
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfTempDir()
Tries to get the system directory for temporary files.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
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...
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfGetUrlUtils()
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL using $wgServer (or one of its alternatives).
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfPercent( $nr, int $acc=2, bool $round=true)
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfGetNull()
Get a platform-independent path to the null file, e.g.
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a 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.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
wfFormatStackFrame( $frame)
Return a string representation of frame.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfScript( $script='index')
Get the URL path to a MediaWiki entry point.
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfLoadExtensions(array $exts)
Load multiple extensions at once.
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
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:441
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgOut
Definition Setup.php:562
const MW_ENTRY_POINT
Definition api.php:35
Debug toolbar.
Definition MWDebug.php:49
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:93
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1636
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:157
Load JSON files, and uses a Processor to extract information.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Executes shell commands.
Definition Shell.php:46
Represents a title within MediaWiki.
Definition Title.php:78
A service to expand, parse, and otherwise manipulate URLs.
Definition UrlUtils.php:16
expand(string $url, $defaultProto=PROTO_FALLBACK)
Expand a potentially local URL to a fully-qualified URL using $wgServer (or one of its alternatives).
Definition UrlUtils.php:124
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 that consists of a list of values.
Type definition for expiry timestamps.
Definition ExpiryDef.php:17
$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