MediaWiki 1.43.1
GlobalFunctions.php
Go to the documentation of this file.
1<?php
35use Wikimedia\AtEase\AtEase;
40use Wikimedia\RequestTimeout\RequestTimeout;
41
52function wfLoadExtension( $ext, $path = null ) {
53 if ( !$path ) {
55 $path = "$wgExtensionDirectory/$ext/extension.json";
56 }
57 ExtensionRegistry::getInstance()->queue( $path );
58}
59
73function wfLoadExtensions( array $exts ) {
75 $registry = ExtensionRegistry::getInstance();
76 foreach ( $exts as $ext ) {
77 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
78 }
79}
80
89function wfLoadSkin( $skin, $path = null ) {
90 if ( !$path ) {
91 global $wgStyleDirectory;
92 $path = "$wgStyleDirectory/$skin/skin.json";
93 }
94 ExtensionRegistry::getInstance()->queue( $path );
95}
96
104function wfLoadSkins( array $skins ) {
105 global $wgStyleDirectory;
106 $registry = ExtensionRegistry::getInstance();
107 foreach ( $skins as $skin ) {
108 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
109 }
110}
111
119function wfArrayDiff2( $arr1, $arr2 ) {
120 wfDeprecated( __FUNCTION__, '1.43' );
125 $comparator = static function ( $a, $b ): int {
126 if ( is_string( $a ) && is_string( $b ) ) {
127 return strcmp( $a, $b );
128 }
129 if ( !is_array( $a ) && !is_array( $b ) ) {
130 throw new InvalidArgumentException(
131 'This function assumes that array elements are all strings or all arrays'
132 );
133 }
134 if ( count( $a ) !== count( $b ) ) {
135 return count( $a ) <=> count( $b );
136 } else {
137 reset( $a );
138 reset( $b );
139 while ( key( $a ) !== null && key( $b ) !== null ) {
140 $valueA = current( $a );
141 $valueB = current( $b );
142 $cmp = strcmp( $valueA, $valueB );
143 if ( $cmp !== 0 ) {
144 return $cmp;
145 }
146 next( $a );
147 next( $b );
148 }
149 return 0;
150 }
151 };
152 return array_udiff( $arr1, $arr2, $comparator );
153}
154
175function wfMergeErrorArrays( ...$args ) {
176 wfDeprecated( __FUNCTION__, '1.43' );
177 $out = [];
178 foreach ( $args as $errors ) {
179 foreach ( $errors as $params ) {
180 $originalParams = $params;
181 if ( $params[0] instanceof MessageSpecifier ) {
182 $params = [ $params[0]->getKey(), ...$params[0]->getParams() ];
183 }
184 # @todo FIXME: Sometimes get nested arrays for $params,
185 # which leads to E_NOTICEs
186 $spec = implode( "\t", $params );
187 $out[$spec] = $originalParams;
188 }
189 }
190 return array_values( $out );
191}
192
202function wfArrayInsertAfter( array $array, array $insert, $after ) {
203 // Find the offset of the element to insert after.
204 $keys = array_keys( $array );
205 $offsetByKey = array_flip( $keys );
206
207 if ( !\array_key_exists( $after, $offsetByKey ) ) {
208 return $array;
209 }
210 $offset = $offsetByKey[$after];
211
212 // Insert at the specified offset
213 $before = array_slice( $array, 0, $offset + 1, true );
214 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
215
216 $output = $before + $insert + $after;
217
218 return $output;
219}
220
229function wfObjectToArray( $objOrArray, $recursive = true ) {
230 $array = [];
231 if ( is_object( $objOrArray ) ) {
232 $objOrArray = get_object_vars( $objOrArray );
233 }
234 foreach ( $objOrArray as $key => $value ) {
235 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
236 $value = wfObjectToArray( $value );
237 }
238
239 $array[$key] = $value;
240 }
241
242 return $array;
243}
244
255function wfRandom() {
256 // The maximum random value is "only" 2^31-1, so get two random
257 // values to reduce the chance of dupes
258 $max = mt_getrandmax() + 1;
259 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
260 return $rand;
261}
262
273function wfRandomString( $length = 32 ) {
274 $str = '';
275 for ( $n = 0; $n < $length; $n += 7 ) {
276 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
277 }
278 return substr( $str, 0, $length );
279}
280
308function wfUrlencode( $s ) {
309 static $needle;
310
311 if ( $s === null ) {
312 // Reset $needle for testing.
313 $needle = null;
314 return '';
315 }
316
317 if ( $needle === null ) {
318 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
319 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
320 !str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
321 ) {
322 $needle[] = '%3A';
323 }
324 }
325
326 $s = urlencode( $s );
327 $s = str_ireplace(
328 $needle,
329 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
330 $s
331 );
332
333 return $s;
334}
335
346function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
347 if ( $array2 !== null ) {
348 $array1 += $array2;
349 }
350
351 $cgi = '';
352 foreach ( $array1 as $key => $value ) {
353 if ( $value !== null && $value !== false ) {
354 if ( $cgi != '' ) {
355 $cgi .= '&';
356 }
357 if ( $prefix !== '' ) {
358 $key = $prefix . "[$key]";
359 }
360 if ( is_array( $value ) ) {
361 $firstTime = true;
362 foreach ( $value as $k => $v ) {
363 $cgi .= $firstTime ? '' : '&';
364 if ( is_array( $v ) ) {
365 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
366 } else {
367 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
368 }
369 $firstTime = false;
370 }
371 } else {
372 if ( is_object( $value ) ) {
373 $value = $value->__toString();
374 }
375 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
376 }
377 }
378 }
379 return $cgi;
380}
381
391function wfCgiToArray( $query ) {
392 if ( isset( $query[0] ) && $query[0] == '?' ) {
393 $query = substr( $query, 1 );
394 }
395 $bits = explode( '&', $query );
396 $ret = [];
397 foreach ( $bits as $bit ) {
398 if ( $bit === '' ) {
399 continue;
400 }
401 if ( strpos( $bit, '=' ) === false ) {
402 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
403 $key = $bit;
404 $value = '';
405 } else {
406 [ $key, $value ] = explode( '=', $bit );
407 }
408 $key = urldecode( $key );
409 $value = urldecode( $value );
410 if ( strpos( $key, '[' ) !== false ) {
411 $keys = array_reverse( explode( '[', $key ) );
412 $key = array_pop( $keys );
413 $temp = $value;
414 foreach ( $keys as $k ) {
415 $k = substr( $k, 0, -1 );
416 $temp = [ $k => $temp ];
417 }
418 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
419 $ret[$key] = array_merge( $ret[$key], $temp );
420 } else {
421 $ret[$key] = $temp;
422 }
423 } else {
424 $ret[$key] = $value;
425 }
426 }
427 return $ret;
428}
429
438function wfAppendQuery( $url, $query ) {
439 if ( is_array( $query ) ) {
440 $query = wfArrayToCgi( $query );
441 }
442 if ( $query != '' ) {
443 // Remove the fragment, if there is one
444 $fragment = false;
445 $hashPos = strpos( $url, '#' );
446 if ( $hashPos !== false ) {
447 $fragment = substr( $url, $hashPos );
448 $url = substr( $url, 0, $hashPos );
449 }
450
451 // Add parameter
452 if ( strpos( $url, '?' ) === false ) {
453 $url .= '?';
454 } else {
455 $url .= '&';
456 }
457 $url .= $query;
458
459 // Put the fragment back
460 if ( $fragment !== false ) {
461 $url .= $fragment;
462 }
463 }
464 return $url;
465}
466
475
476 if ( MediaWikiServices::hasInstance() ) {
477 $services = MediaWikiServices::getInstance();
478 if ( $services->hasService( 'UrlUtils' ) ) {
479 return $services->getUrlUtils();
480 }
481 }
482
483 return new UrlUtils( [
484 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
485 // implementations implicitly converted it to an empty string (presumably by mistake).
486 // Preserve the old behavior for compatibility.
487 UrlUtils::SERVER => $wgServer ?? '',
488 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
489 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
490 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
491 : WebRequest::detectProtocol(),
492 UrlUtils::HTTPS_PORT => $wgHttpsPort,
493 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
494 ] );
495}
496
524function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
525 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
526}
527
537function wfGetServerUrl( $proto ) {
538 wfDeprecated( __FUNCTION__, '1.39' );
539
540 return wfGetUrlUtils()->getServer( $proto ) ?? '';
541}
542
555function wfAssembleUrl( $urlParts ) {
556 return UrlUtils::assemble( (array)$urlParts );
557}
558
567function wfUrlProtocols( $includeProtocolRelative = true ) {
568 wfDeprecated( __FUNCTION__, '1.39' );
569
570 return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() :
571 wfGetUrlUtils()->validAbsoluteProtocols();
572}
573
582 return wfGetUrlUtils()->validAbsoluteProtocols();
583}
584
611function wfParseUrl( $url ) {
612 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
613}
614
624function wfExpandIRI( $url ) {
625 wfDeprecated( __FUNCTION__, '1.39' );
626
627 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
628}
629
638function wfMatchesDomainList( $url, $domains ) {
639 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
640}
641
662function wfDebug( $text, $dest = 'all', array $context = [] ) {
664
665 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
666 return;
667 }
668
669 $text = trim( $text );
670
671 if ( $wgDebugLogPrefix !== '' ) {
672 $context['prefix'] = $wgDebugLogPrefix;
673 }
674 $context['private'] = ( $dest === false || $dest === 'private' );
675
676 $logger = LoggerFactory::getInstance( 'wfDebug' );
677 $logger->debug( $text, $context );
678}
679
685 static $cache;
686 if ( $cache !== null ) {
687 return $cache;
688 }
689 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
690 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
691 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
692 || MW_ENTRY_POINT === 'load'
693 ) {
694 $cache = true;
695 } else {
696 $cache = false;
697 }
698 return $cache;
699}
700
726function wfDebugLog(
727 $logGroup, $text, $dest = 'all', array $context = []
728) {
729 $text = trim( $text );
730
731 $logger = LoggerFactory::getInstance( $logGroup );
732 $context['private'] = ( $dest === false || $dest === 'private' );
733 $logger->info( $text, $context );
734}
735
744function wfLogDBError( $text, array $context = [] ) {
745 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
746 $logger->error( trim( $text ), $context );
747}
748
765function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
766 if ( !is_string( $version ) && $version !== false ) {
767 throw new InvalidArgumentException(
768 "MediaWiki version must either be a string or false. " .
769 "Example valid version: '1.33'"
770 );
771 }
772
773 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
774}
775
796function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
797 MWDebug::deprecatedMsg( $msg, $version, $component,
798 $callerOffset === false ? false : $callerOffset + 1 );
799}
800
811function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
812 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
813}
814
824function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
825 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
826}
827
849function wfMessage( $key, ...$params ) {
850 if ( is_array( $key ) ) {
851 // Fallback keys are not allowed in message specifiers
852 $message = wfMessageFallback( ...$key );
853 } else {
854 $message = Message::newFromSpecifier( $key );
855 }
856
857 // We call Message::params() to reduce code duplication
858 if ( $params ) {
859 $message->params( ...$params );
860 }
861
862 return $message;
863}
864
877function wfMessageFallback( ...$keys ) {
878 return Message::newFallbackSequence( ...$keys );
879}
880
889function wfMsgReplaceArgs( $message, $args ) {
890 # Fix windows line-endings
891 # Some messages are split with explode("\n", $msg)
892 $message = str_replace( "\r", '', $message );
893
894 // Replace arguments
895 if ( is_array( $args ) && $args ) {
896 if ( is_array( $args[0] ) ) {
897 $args = array_values( $args[0] );
898 }
899 $replacementKeys = [];
900 foreach ( $args as $n => $param ) {
901 $replacementKeys['$' . ( $n + 1 )] = $param;
902 }
903 $message = strtr( $message, $replacementKeys );
904 }
905
906 return $message;
907}
908
917function wfHostname() {
918 // Hostname overriding
919 global $wgOverrideHostname;
920 if ( $wgOverrideHostname !== false ) {
921 return $wgOverrideHostname;
922 }
923
924 return php_uname( 'n' ) ?: 'unknown';
925}
926
937function wfDebugBacktrace( $limit = 0 ) {
938 static $disabled = null;
939
940 if ( $disabled === null ) {
941 $disabled = !function_exists( 'debug_backtrace' );
942 if ( $disabled ) {
943 wfDebug( "debug_backtrace() is disabled" );
944 }
945 }
946 if ( $disabled ) {
947 return [];
948 }
949
950 if ( $limit ) {
951 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
952 } else {
953 return array_slice( debug_backtrace(), 1 );
954 }
955}
956
965function wfBacktrace( $raw = null ) {
966 $raw ??= MW_ENTRY_POINT === 'cli';
967 if ( $raw ) {
968 $frameFormat = "%s line %s calls %s()\n";
969 $traceFormat = "%s";
970 } else {
971 $frameFormat = "<li>%s line %s calls %s()</li>\n";
972 $traceFormat = "<ul>\n%s</ul>\n";
973 }
974
975 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
976 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
977 $line = $frame['line'] ?? '-';
978 $call = $frame['function'];
979 if ( !empty( $frame['class'] ) ) {
980 $call = $frame['class'] . $frame['type'] . $call;
981 }
982 return sprintf( $frameFormat, $file, $line, $call );
983 }, wfDebugBacktrace() );
984
985 return sprintf( $traceFormat, implode( '', $frames ) );
986}
987
998function wfGetCaller( $level = 2 ) {
999 $backtrace = wfDebugBacktrace( $level + 1 );
1000 if ( isset( $backtrace[$level] ) ) {
1001 return wfFormatStackFrame( $backtrace[$level] );
1002 } else {
1003 return 'unknown';
1004 }
1005}
1006
1014function wfGetAllCallers( $limit = 3 ) {
1015 $trace = array_reverse( wfDebugBacktrace() );
1016 if ( !$limit || $limit > count( $trace ) - 1 ) {
1017 $limit = count( $trace ) - 1;
1018 }
1019 $trace = array_slice( $trace, -$limit - 1, $limit );
1020 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1021}
1022
1035function wfFormatStackFrame( $frame ) {
1036 if ( !isset( $frame['function'] ) ) {
1037 return 'NO_FUNCTION_GIVEN';
1038 }
1039 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1040 $frame['class'] . $frame['type'] . $frame['function'] :
1041 $frame['function'];
1042}
1043
1053function wfClientAcceptsGzip( $force = false ) {
1054 static $result = null;
1055 if ( $result === null || $force ) {
1056 $result = false;
1057 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1058 # @todo FIXME: We may want to disallow some broken browsers
1059 $m = [];
1060 if ( preg_match(
1061 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1062 $_SERVER['HTTP_ACCEPT_ENCODING'],
1063 $m
1064 )
1065 ) {
1066 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1067 return $result;
1068 }
1069 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1070 $result = true;
1071 }
1072 }
1073 }
1074 return $result;
1075}
1076
1087function wfEscapeWikiText( $input ): string {
1088 global $wgEnableMagicLinks;
1089 static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
1090 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1091 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1092 // in those situations
1093 $repl = [
1094 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1095 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1096 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1097 ';' => '&#59;', // a token inside language converter brackets
1098 '!!' => '&#33;!', // a token inside table context
1099 "\n!" => "\n&#33;", "\r!" => "\r&#33;", // a token inside table context
1100 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1101 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1102 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1103 "\n " => "\n&#32;", "\r " => "\r&#32;",
1104 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1105 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1106 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1107 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1108 '__' => '_&#95;', '://' => '&#58;//',
1109 '~~~' => '~~&#126;', // protect from PST, just to be safe(r)
1110 ];
1111
1112 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1113 // We have to catch everything "\s" matches in PCRE
1114 foreach ( $magicLinks as $magic ) {
1115 $repl["$magic "] = "$magic&#32;";
1116 $repl["$magic\t"] = "$magic&#9;";
1117 $repl["$magic\r"] = "$magic&#13;";
1118 $repl["$magic\n"] = "$magic&#10;";
1119 $repl["$magic\f"] = "$magic&#12;";
1120 }
1121 // Additionally escape the following characters at the beginning of the
1122 // string, in case they merge to form tokens when spliced into a
1123 // string. Tokens like -{ {{ [[ {| etc are already escaped because
1124 // the second character is escaped above, but the following tokens
1125 // are handled here: |+ |- __FOO__ ~~~
1126 $repl3 = [
1127 '+' => '&#43;', '-' => '&#45;', '_' => '&#95;', '~' => '&#126;',
1128 ];
1129 // Similarly, protect the following characters at the end of the
1130 // string, which could turn form the start of `__FOO__` or `~~~~`
1131 // A trailing newline could also form the unintended start of a
1132 // paragraph break if it is glued to a newline in the following
1133 // context.
1134 $repl4 = [
1135 '_' => '&#95;', '~' => '&#126;',
1136 "\n" => "&#10;", "\r" => "&#13;",
1137 "\t" => "&#9;", // "\n\t\n" is treated like "\n\n"
1138 ];
1139
1140 // And handle protocols that don't use "://"
1141 global $wgUrlProtocols;
1142 $repl2 = [];
1143 foreach ( $wgUrlProtocols as $prot ) {
1144 if ( substr( $prot, -1 ) === ':' ) {
1145 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1146 }
1147 }
1148 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1149 }
1150 // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
1151 '@phan-var string $repl2';
1152 '@phan-var string $repl3';
1153 '@phan-var string $repl4';
1154 // This will also stringify input in case it's not a string
1155 $text = substr( strtr( "\n$input", $repl ), 1 );
1156 if ( $text === '' ) {
1157 return $text;
1158 }
1159 $first = strtr( $text[0], $repl3 ); // protect first character
1160 if ( strlen( $text ) > 1 ) {
1161 $text = $first . substr( $text, 1, -1 ) .
1162 strtr( substr( $text, -1 ), $repl4 ); // protect last character
1163 } else {
1164 // special case for single-character strings
1165 $text = strtr( $first, $repl4 ); // protect last character
1166 }
1167 $text = preg_replace( $repl2, '$1&#58;', $text );
1168 return $text;
1169}
1170
1181function wfSetVar( &$dest, $source, $force = false ) {
1182 $temp = $dest;
1183 if ( $source !== null || $force ) {
1184 $dest = $source;
1185 }
1186 return $temp;
1187}
1188
1198function wfSetBit( &$dest, $bit, $state = true ) {
1199 $temp = (bool)( $dest & $bit );
1200 if ( $state !== null ) {
1201 if ( $state ) {
1202 $dest |= $bit;
1203 } else {
1204 $dest &= ~$bit;
1205 }
1206 }
1207 return $temp;
1208}
1209
1216function wfVarDump( $var ) {
1217 global $wgOut;
1218 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1219 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1220 print $s;
1221 } else {
1222 $wgOut->addHTML( $s );
1223 }
1224}
1225
1233function wfHttpError( $code, $label, $desc ) {
1234 global $wgOut;
1235 HttpStatus::header( $code );
1236 if ( $wgOut ) {
1237 $wgOut->disable();
1238 $wgOut->sendCacheControl();
1239 }
1240
1241 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1242 header( 'Content-type: text/html; charset=utf-8' );
1243 ob_start();
1244 print '<!DOCTYPE html>' .
1245 '<html><head><title>' .
1246 htmlspecialchars( $label ) .
1247 '</title></head><body><h1>' .
1248 htmlspecialchars( $label ) .
1249 '</h1><p>' .
1250 nl2br( htmlspecialchars( $desc ) ) .
1251 "</p></body></html>\n";
1252 header( 'Content-Length: ' . ob_get_length() );
1253 ob_end_flush();
1254}
1255
1276function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1277 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
1278 while ( $status = ob_get_status() ) {
1279 if ( isset( $status['flags'] ) ) {
1280 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1281 $deleteable = ( $status['flags'] & $flags ) === $flags;
1282 } elseif ( isset( $status['del'] ) ) {
1283 $deleteable = $status['del'];
1284 } else {
1285 // Guess that any PHP-internal setting can't be removed.
1286 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1287 }
1288 if ( !$deleteable ) {
1289 // Give up, and hope the result doesn't break
1290 // output behavior.
1291 break;
1292 }
1293 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1294 // Unit testing barrier to prevent this function from breaking PHPUnit.
1295 break;
1296 }
1297 if ( !ob_end_clean() ) {
1298 // Could not remove output buffer handler; abort now
1299 // to avoid getting in some kind of infinite loop.
1300 break;
1301 }
1302 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1303 // Reset the 'Content-Encoding' field set by this handler
1304 // so we can start fresh.
1305 header_remove( 'Content-Encoding' );
1306 break;
1307 }
1308 }
1309}
1310
1321function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1322 $ret = MWTimestamp::convert( $outputtype, $ts );
1323 if ( $ret === false ) {
1324 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1325 }
1326 return $ret;
1327}
1328
1337function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1338 if ( $ts === null ) {
1339 return null;
1340 } else {
1341 return wfTimestamp( $outputtype, $ts );
1342 }
1343}
1344
1350function wfTimestampNow() {
1351 return MWTimestamp::now( TS_MW );
1352}
1353
1365function wfTempDir() {
1366 global $wgTmpDirectory;
1367
1368 if ( $wgTmpDirectory !== false ) {
1369 return $wgTmpDirectory;
1370 }
1371
1372 return TempFSFile::getUsableTempDirectory();
1373}
1374
1383function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1384 global $wgDirectoryMode;
1385
1386 if ( FileBackend::isStoragePath( $dir ) ) {
1387 throw new LogicException( __FUNCTION__ . " given storage path '$dir'." );
1388 }
1389 if ( $caller !== null ) {
1390 wfDebug( "$caller: called wfMkdirParents($dir)" );
1391 }
1392 if ( strval( $dir ) === '' ) {
1393 return true;
1394 }
1395
1396 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1397 $mode ??= $wgDirectoryMode;
1398
1399 // Turn off the normal warning, we're doing our own below
1400 // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis.
1401 //
1402 // Repeat existence check if creation failed so that we silently recover in case of
1403 // a race condition where another request created it since the first check.
1404 //
1405 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1406 $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir );
1407 if ( !$ok ) {
1408 trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING );
1409 }
1410
1411 return $ok;
1412}
1413
1419function wfRecursiveRemoveDir( $dir ) {
1420 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1421 if ( is_dir( $dir ) ) {
1422 $objects = scandir( $dir );
1423 foreach ( $objects as $object ) {
1424 if ( $object != "." && $object != ".." ) {
1425 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1426 wfRecursiveRemoveDir( $dir . '/' . $object );
1427 } else {
1428 unlink( $dir . '/' . $object );
1429 }
1430 }
1431 }
1432 rmdir( $dir );
1433 }
1434}
1435
1442function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1443 $accForFormat = $acc >= 0 ? $acc : 0;
1444 $ret = sprintf( "%.{$accForFormat}f", $nr );
1445 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1446}
1447
1471function wfIniGetBool( $setting ) {
1472 return wfStringToBool( ini_get( $setting ) );
1473}
1474
1487function wfStringToBool( $val ) {
1488 $val = strtolower( $val );
1489 // 'on' and 'true' can't have whitespace around them, but '1' can.
1490 return $val == 'on'
1491 || $val == 'true'
1492 || $val == 'yes'
1493 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1494}
1495
1509function wfEscapeShellArg( ...$args ) {
1510 return Shell::escape( ...$args );
1511}
1512
1537function wfShellExec( $cmd, &$retval = null, $environ = [],
1538 $limits = [], $options = []
1539) {
1540 if ( Shell::isDisabled() ) {
1541 $retval = 1;
1542 // Backwards compatibility be upon us...
1543 return 'Unable to run external programs, proc_open() is disabled.';
1544 }
1545
1546 if ( is_array( $cmd ) ) {
1547 $cmd = Shell::escape( $cmd );
1548 }
1549
1550 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1551 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1552
1553 try {
1554 $result = Shell::command( [] )
1555 ->unsafeParams( (array)$cmd )
1556 ->environment( $environ )
1557 ->limits( $limits )
1558 ->includeStderr( $includeStderr )
1559 ->profileMethod( $profileMethod )
1560 // For b/c
1561 ->restrict( Shell::RESTRICT_NONE )
1562 ->execute();
1563 } catch ( ProcOpenError $ex ) {
1564 $retval = -1;
1565 return '';
1566 }
1567
1568 $retval = $result->getExitCode();
1569
1570 return $result->getStdout();
1571}
1572
1590function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1591 return wfShellExec( $cmd, $retval, $environ, $limits,
1592 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1593}
1594
1610function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1611 global $wgPhpCli;
1612 // Give site config file a chance to run the script in a wrapper.
1613 // The caller may likely want to call wfBasename() on $script.
1614 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1615 ->onWfShellWikiCmd( $script, $parameters, $options );
1616 $cmd = [ $options['php'] ?? $wgPhpCli ];
1617 if ( isset( $options['wrapper'] ) ) {
1618 $cmd[] = $options['wrapper'];
1619 }
1620 $cmd[] = $script;
1621 // Escape each parameter for shell
1622 return Shell::escape( array_merge( $cmd, $parameters ) );
1623}
1624
1641function wfMerge(
1642 string $old,
1643 string $mine,
1644 string $yours,
1645 ?string &$simplisticMergeAttempt,
1646 ?string &$mergeLeftovers = null
1647): bool {
1648 global $wgDiff3;
1649
1650 # This check may also protect against code injection in
1651 # case of broken installations.
1652 AtEase::suppressWarnings();
1653 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1654 AtEase::restoreWarnings();
1655
1656 if ( !$haveDiff3 ) {
1657 wfDebug( "diff3 not found" );
1658 return false;
1659 }
1660
1661 # Make temporary files
1662 $td = wfTempDir();
1663 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1664 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1665 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1666
1667 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1668 # a newline character. To avoid this, we normalize the trailing whitespace before
1669 # creating the diff.
1670
1671 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1672 fclose( $oldtextFile );
1673 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1674 fclose( $mytextFile );
1675 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1676 fclose( $yourtextFile );
1677
1678 # Check for a conflict
1679 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1680 $oldtextName, $yourtextName );
1681 $handle = popen( $cmd, 'r' );
1682
1683 $mergeLeftovers = '';
1684 do {
1685 $data = fread( $handle, 8192 );
1686 if ( strlen( $data ) == 0 ) {
1687 break;
1688 }
1689 $mergeLeftovers .= $data;
1690 } while ( true );
1691 pclose( $handle );
1692
1693 $conflict = $mergeLeftovers !== '';
1694
1695 # Merge differences automatically where possible, preferring "my" text for conflicts.
1696 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1697 $oldtextName, $yourtextName );
1698 $handle = popen( $cmd, 'r' );
1699 $simplisticMergeAttempt = '';
1700 do {
1701 $data = fread( $handle, 8192 );
1702 if ( strlen( $data ) == 0 ) {
1703 break;
1704 }
1705 $simplisticMergeAttempt .= $data;
1706 } while ( true );
1707 pclose( $handle );
1708 unlink( $mytextName );
1709 unlink( $oldtextName );
1710 unlink( $yourtextName );
1711
1712 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1713 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1714 $conflict = true;
1715 }
1716 return !$conflict;
1717}
1718
1731function wfBaseName( $path, $suffix = '' ) {
1732 if ( $suffix == '' ) {
1733 $encSuffix = '';
1734 } else {
1735 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1736 }
1737
1738 $matches = [];
1739 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1740 return $matches[1];
1741 } else {
1742 return '';
1743 }
1744}
1745
1755function wfRelativePath( $path, $from ) {
1756 // Normalize mixed input on Windows...
1757 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1758 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1759
1760 // Trim trailing slashes -- fix for drive root
1761 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1762 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1763
1764 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1765 $against = explode( DIRECTORY_SEPARATOR, $from );
1766
1767 if ( $pieces[0] !== $against[0] ) {
1768 // Non-matching Windows drive letters?
1769 // Return a full path.
1770 return $path;
1771 }
1772
1773 // Trim off common prefix
1774 while ( count( $pieces ) && count( $against )
1775 && $pieces[0] == $against[0] ) {
1776 array_shift( $pieces );
1777 array_shift( $against );
1778 }
1779
1780 // relative dots to bump us to the parent
1781 while ( count( $against ) ) {
1782 array_unshift( $pieces, '..' );
1783 array_shift( $against );
1784 }
1785
1786 $pieces[] = wfBaseName( $path );
1787
1788 return implode( DIRECTORY_SEPARATOR, $pieces );
1789}
1790
1828function wfGetDB( $db, $groups = [], $wiki = false ) {
1829 wfDeprecated( __FUNCTION__, '1.39' );
1830
1831 if ( $wiki === false ) {
1832 return MediaWikiServices::getInstance()
1833 ->getDBLoadBalancer()
1834 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1835 } else {
1836 return MediaWikiServices::getInstance()
1837 ->getDBLoadBalancerFactory()
1838 ->getMainLB( $wiki )
1839 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1840 }
1841}
1842
1852function wfScript( $script = 'index' ) {
1854 if ( $script === 'index' ) {
1855 return $wgScript;
1856 } elseif ( $script === 'load' ) {
1857 return $wgLoadScript;
1858 } else {
1859 return "{$wgScriptPath}/{$script}.php";
1860 }
1861}
1862
1870function wfBoolToStr( $value ) {
1871 return $value ? 'true' : 'false';
1872}
1873
1879function wfGetNull() {
1880 return wfIsWindows() ? 'NUL' : '/dev/null';
1881}
1882
1892 global $wgIllegalFileChars;
1893 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1894 $name = preg_replace(
1895 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1896 '-',
1897 $name
1898 );
1899 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1900 $name = wfBaseName( $name );
1901 return $name;
1902}
1903
1910function wfMemoryLimit( $newLimit ) {
1911 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1912 // If the INI config is already unlimited, there is nothing larger
1913 if ( $oldLimit != -1 ) {
1914 $newLimit = wfShorthandToInteger( (string)$newLimit );
1915 if ( $newLimit == -1 ) {
1916 wfDebug( "Removing PHP's memory limit" );
1917 AtEase::suppressWarnings();
1918 ini_set( 'memory_limit', $newLimit );
1919 AtEase::restoreWarnings();
1920 } elseif ( $newLimit > $oldLimit ) {
1921 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1922 AtEase::suppressWarnings();
1923 ini_set( 'memory_limit', $newLimit );
1924 AtEase::restoreWarnings();
1925 }
1926 }
1927}
1928
1937
1938 $timeout = RequestTimeout::singleton();
1939 $timeLimit = $timeout->getWallTimeLimit();
1940 if ( $timeLimit !== INF ) {
1941 // RequestTimeout library is active
1942 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1943 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1944 }
1945 } else {
1946 // Fallback case, likely $wgRequestTimeLimit === null
1947 $timeLimit = (int)ini_get( 'max_execution_time' );
1948 // Note that CLI scripts use 0
1949 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
1950 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1951 }
1952 }
1953 ignore_user_abort( true ); // ignore client disconnects
1954
1955 return $timeLimit;
1956}
1957
1965function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
1966 $string = trim( $string ?? '' );
1967 if ( $string === '' ) {
1968 return $default;
1969 }
1970 $last = $string[strlen( $string ) - 1];
1971 $val = intval( $string );
1972 switch ( $last ) {
1973 case 'g':
1974 case 'G':
1975 $val *= 1024;
1976 // break intentionally missing
1977 case 'm':
1978 case 'M':
1979 $val *= 1024;
1980 // break intentionally missing
1981 case 'k':
1982 case 'K':
1983 $val *= 1024;
1984 }
1985
1986 return $val;
1987}
1988
1996function wfIsInfinity( $str ) {
1997 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
1998 return in_array( $str, ExpiryDef::INFINITY_VALS );
1999}
2000
2015function wfThumbIsStandard( File $file, array $params ) {
2017
2018 $multipliers = [ 1 ];
2019 if ( $wgResponsiveImages ) {
2020 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2021 // @see Linker::processResponsiveImages
2022 $multipliers[] = 1.5;
2023 $multipliers[] = 2;
2024 }
2025
2026 $handler = $file->getHandler();
2027 if ( !$handler || !isset( $params['width'] ) ) {
2028 return false;
2029 }
2030
2031 $basicParams = [];
2032 if ( isset( $params['page'] ) ) {
2033 $basicParams['page'] = $params['page'];
2034 }
2035
2036 $thumbLimits = [];
2037 $imageLimits = [];
2038 // Expand limits to account for multipliers
2039 foreach ( $multipliers as $multiplier ) {
2040 $thumbLimits = array_merge( $thumbLimits, array_map(
2041 static function ( $width ) use ( $multiplier ) {
2042 return round( $width * $multiplier );
2043 }, $wgThumbLimits )
2044 );
2045 $imageLimits = array_merge( $imageLimits, array_map(
2046 static function ( $pair ) use ( $multiplier ) {
2047 return [
2048 round( $pair[0] * $multiplier ),
2049 round( $pair[1] * $multiplier ),
2050 ];
2051 }, $wgImageLimits )
2052 );
2053 }
2054
2055 // Check if the width matches one of $wgThumbLimits
2056 if ( in_array( $params['width'], $thumbLimits ) ) {
2057 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2058 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2059 $handler->normaliseParams( $file, $normalParams );
2060 } else {
2061 // If not, then check if the width matches one of $wgImageLimits
2062 $match = false;
2063 foreach ( $imageLimits as $pair ) {
2064 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2065 // Decide whether the thumbnail should be scaled on width or height.
2066 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2067 $handler->normaliseParams( $file, $normalParams );
2068 // Check if this standard thumbnail size maps to the given width
2069 if ( $normalParams['width'] == $params['width'] ) {
2070 $match = true;
2071 break;
2072 }
2073 }
2074 if ( !$match ) {
2075 return false; // not standard for description pages
2076 }
2077 }
2078
2079 // Check that the given values for non-page, non-width, params are just defaults
2080 foreach ( $params as $key => $value ) {
2081 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2082 return false;
2083 }
2084 }
2085
2086 return true;
2087}
2088
2101function wfArrayPlus2d( array $baseArray, array $newValues ) {
2102 // First merge items that are in both arrays
2103 foreach ( $baseArray as $name => &$groupVal ) {
2104 if ( isset( $newValues[$name] ) ) {
2105 $groupVal += $newValues[$name];
2106 }
2107 }
2108 // Now add items that didn't exist yet
2109 $baseArray += $newValues;
2110
2111 return $baseArray;
2112}
wfIsWindows()
Check if the operating system is Windows.
const PROTO_CURRENT
Definition Defines.php:209
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.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfArrayDiff2( $arr1, $arr2)
Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfGetUrlUtils()
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL using $wgServer (or one of its alternatives).
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfPercent( $nr, int $acc=2, bool $round=true)
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfGetNull()
Get a platform-independent path to the null file, e.g.
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a 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:420
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgOut
Definition Setup.php:541
array $params
The job parameters.
const MW_ENTRY_POINT
Definition api.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:1568
Debug toolbar.
Definition MWDebug.php:48
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:156
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
Library for creating and parsing MW-style timestamps.
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).
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