MediaWiki master
GlobalFunctions.php
Go to the documentation of this file.
1<?php
35use Wikimedia\AtEase\AtEase;
39use Wikimedia\RequestTimeout\RequestTimeout;
40
51function wfLoadExtension( $ext, $path = null ) {
52 if ( !$path ) {
54 $path = "$wgExtensionDirectory/$ext/extension.json";
55 }
56 ExtensionRegistry::getInstance()->queue( $path );
57}
58
72function wfLoadExtensions( array $exts ) {
74 $registry = ExtensionRegistry::getInstance();
75 foreach ( $exts as $ext ) {
76 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
77 }
78}
79
88function wfLoadSkin( $skin, $path = null ) {
89 if ( !$path ) {
90 global $wgStyleDirectory;
91 $path = "$wgStyleDirectory/$skin/skin.json";
92 }
93 ExtensionRegistry::getInstance()->queue( $path );
94}
95
103function wfLoadSkins( array $skins ) {
104 global $wgStyleDirectory;
105 $registry = ExtensionRegistry::getInstance();
106 foreach ( $skins as $skin ) {
107 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
108 }
109}
110
117function wfArrayDiff2( $arr1, $arr2 ) {
122 $comparator = static function ( $a, $b ): int {
123 if ( is_string( $a ) && is_string( $b ) ) {
124 return strcmp( $a, $b );
125 }
126 if ( !is_array( $a ) && !is_array( $b ) ) {
127 throw new InvalidArgumentException(
128 'This function assumes that array elements are all strings or all arrays'
129 );
130 }
131 if ( count( $a ) !== count( $b ) ) {
132 return count( $a ) <=> count( $b );
133 } else {
134 reset( $a );
135 reset( $b );
136 while ( key( $a ) !== null && key( $b ) !== null ) {
137 $valueA = current( $a );
138 $valueB = current( $b );
139 $cmp = strcmp( $valueA, $valueB );
140 if ( $cmp !== 0 ) {
141 return $cmp;
142 }
143 next( $a );
144 next( $b );
145 }
146 return 0;
147 }
148 };
149 return array_udiff( $arr1, $arr2, $comparator );
150}
151
172function wfMergeErrorArrays( ...$args ) {
173 wfDeprecated( __FUNCTION__, '1.43' );
174 $out = [];
175 foreach ( $args as $errors ) {
176 foreach ( $errors as $params ) {
177 $originalParams = $params;
178 if ( $params[0] instanceof MessageSpecifier ) {
179 $params = [ $params[0]->getKey(), ...$params[0]->getParams() ];
180 }
181 # @todo FIXME: Sometimes get nested arrays for $params,
182 # which leads to E_NOTICEs
183 $spec = implode( "\t", $params );
184 $out[$spec] = $originalParams;
185 }
186 }
187 return array_values( $out );
188}
189
199function wfArrayInsertAfter( array $array, array $insert, $after ) {
200 // Find the offset of the element to insert after.
201 $keys = array_keys( $array );
202 $offsetByKey = array_flip( $keys );
203
204 if ( !\array_key_exists( $after, $offsetByKey ) ) {
205 return $array;
206 }
207 $offset = $offsetByKey[$after];
208
209 // Insert at the specified offset
210 $before = array_slice( $array, 0, $offset + 1, true );
211 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
212
213 $output = $before + $insert + $after;
214
215 return $output;
216}
217
226function wfObjectToArray( $objOrArray, $recursive = true ) {
227 $array = [];
228 if ( is_object( $objOrArray ) ) {
229 $objOrArray = get_object_vars( $objOrArray );
230 }
231 foreach ( $objOrArray as $key => $value ) {
232 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
233 $value = wfObjectToArray( $value );
234 }
235
236 $array[$key] = $value;
237 }
238
239 return $array;
240}
241
252function wfRandom() {
253 // The maximum random value is "only" 2^31-1, so get two random
254 // values to reduce the chance of dupes
255 $max = mt_getrandmax() + 1;
256 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
257 return $rand;
258}
259
270function wfRandomString( $length = 32 ) {
271 $str = '';
272 for ( $n = 0; $n < $length; $n += 7 ) {
273 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
274 }
275 return substr( $str, 0, $length );
276}
277
305function wfUrlencode( $s ) {
306 static $needle;
307
308 if ( $s === null ) {
309 // Reset $needle for testing.
310 $needle = null;
311 return '';
312 }
313
314 if ( $needle === null ) {
315 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
316 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
317 !str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
318 ) {
319 $needle[] = '%3A';
320 }
321 }
322
323 $s = urlencode( $s );
324 $s = str_ireplace(
325 $needle,
326 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
327 $s
328 );
329
330 return $s;
331}
332
343function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
344 if ( $array2 !== null ) {
345 $array1 += $array2;
346 }
347
348 $cgi = '';
349 foreach ( $array1 as $key => $value ) {
350 if ( $value !== null && $value !== false ) {
351 if ( $cgi != '' ) {
352 $cgi .= '&';
353 }
354 if ( $prefix !== '' ) {
355 $key = $prefix . "[$key]";
356 }
357 if ( is_array( $value ) ) {
358 $firstTime = true;
359 foreach ( $value as $k => $v ) {
360 $cgi .= $firstTime ? '' : '&';
361 if ( is_array( $v ) ) {
362 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
363 } else {
364 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
365 }
366 $firstTime = false;
367 }
368 } else {
369 if ( is_object( $value ) ) {
370 $value = $value->__toString();
371 }
372 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
373 }
374 }
375 }
376 return $cgi;
377}
378
388function wfCgiToArray( $query ) {
389 if ( isset( $query[0] ) && $query[0] == '?' ) {
390 $query = substr( $query, 1 );
391 }
392 $bits = explode( '&', $query );
393 $ret = [];
394 foreach ( $bits as $bit ) {
395 if ( $bit === '' ) {
396 continue;
397 }
398 if ( strpos( $bit, '=' ) === false ) {
399 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
400 $key = $bit;
401 $value = '';
402 } else {
403 [ $key, $value ] = explode( '=', $bit );
404 }
405 $key = urldecode( $key );
406 $value = urldecode( $value );
407 if ( strpos( $key, '[' ) !== false ) {
408 $keys = array_reverse( explode( '[', $key ) );
409 $key = array_pop( $keys );
410 $temp = $value;
411 foreach ( $keys as $k ) {
412 $k = substr( $k, 0, -1 );
413 $temp = [ $k => $temp ];
414 }
415 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
416 $ret[$key] = array_merge( $ret[$key], $temp );
417 } else {
418 $ret[$key] = $temp;
419 }
420 } else {
421 $ret[$key] = $value;
422 }
423 }
424 return $ret;
425}
426
435function wfAppendQuery( $url, $query ) {
436 if ( is_array( $query ) ) {
437 $query = wfArrayToCgi( $query );
438 }
439 if ( $query != '' ) {
440 // Remove the fragment, if there is one
441 $fragment = false;
442 $hashPos = strpos( $url, '#' );
443 if ( $hashPos !== false ) {
444 $fragment = substr( $url, $hashPos );
445 $url = substr( $url, 0, $hashPos );
446 }
447
448 // Add parameter
449 if ( strpos( $url, '?' ) === false ) {
450 $url .= '?';
451 } else {
452 $url .= '&';
453 }
454 $url .= $query;
455
456 // Put the fragment back
457 if ( $fragment !== false ) {
458 $url .= $fragment;
459 }
460 }
461 return $url;
462}
463
472
473 if ( MediaWikiServices::hasInstance() ) {
474 $services = MediaWikiServices::getInstance();
475 if ( $services->hasService( 'UrlUtils' ) ) {
476 return $services->getUrlUtils();
477 }
478 }
479
480 return new UrlUtils( [
481 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
482 // implementations implicitly converted it to an empty string (presumably by mistake).
483 // Preserve the old behavior for compatibility.
484 UrlUtils::SERVER => $wgServer ?? '',
485 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
486 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
487 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
488 : WebRequest::detectProtocol(),
489 UrlUtils::HTTPS_PORT => $wgHttpsPort,
490 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
491 ] );
492}
493
521function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
522 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
523}
524
534function wfGetServerUrl( $proto ) {
535 wfDeprecated( __FUNCTION__, '1.39' );
536
537 return wfGetUrlUtils()->getServer( $proto ) ?? '';
538}
539
552function wfAssembleUrl( $urlParts ) {
553 return UrlUtils::assemble( (array)$urlParts );
554}
555
564function wfUrlProtocols( $includeProtocolRelative = true ) {
565 wfDeprecated( __FUNCTION__, '1.39' );
566
567 return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() :
568 wfGetUrlUtils()->validAbsoluteProtocols();
569}
570
579 return wfGetUrlUtils()->validAbsoluteProtocols();
580}
581
608function wfParseUrl( $url ) {
609 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
610}
611
621function wfExpandIRI( $url ) {
622 wfDeprecated( __FUNCTION__, '1.39' );
623
624 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
625}
626
635function wfMatchesDomainList( $url, $domains ) {
636 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
637}
638
659function wfDebug( $text, $dest = 'all', array $context = [] ) {
661
662 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
663 return;
664 }
665
666 $text = trim( $text );
667
668 if ( $wgDebugLogPrefix !== '' ) {
669 $context['prefix'] = $wgDebugLogPrefix;
670 }
671 $context['private'] = ( $dest === false || $dest === 'private' );
672
673 $logger = LoggerFactory::getInstance( 'wfDebug' );
674 $logger->debug( $text, $context );
675}
676
682 static $cache;
683 if ( $cache !== null ) {
684 return $cache;
685 }
686 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
687 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
688 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
689 || MW_ENTRY_POINT === 'load'
690 ) {
691 $cache = true;
692 } else {
693 $cache = false;
694 }
695 return $cache;
696}
697
723function wfDebugLog(
724 $logGroup, $text, $dest = 'all', array $context = []
725) {
726 $text = trim( $text );
727
728 $logger = LoggerFactory::getInstance( $logGroup );
729 $context['private'] = ( $dest === false || $dest === 'private' );
730 $logger->info( $text, $context );
731}
732
741function wfLogDBError( $text, array $context = [] ) {
742 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
743 $logger->error( trim( $text ), $context );
744}
745
762function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
763 if ( !is_string( $version ) && $version !== false ) {
764 throw new InvalidArgumentException(
765 "MediaWiki version must either be a string or false. " .
766 "Example valid version: '1.33'"
767 );
768 }
769
770 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
771}
772
793function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
794 MWDebug::deprecatedMsg( $msg, $version, $component,
795 $callerOffset === false ? false : $callerOffset + 1 );
796}
797
808function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
809 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
810}
811
821function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
822 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
823}
824
846function wfMessage( $key, ...$params ) {
847 if ( is_array( $key ) ) {
848 // Fallback keys are not allowed in message specifiers
849 $message = wfMessageFallback( ...$key );
850 } else {
851 $message = Message::newFromSpecifier( $key );
852 }
853
854 // We call Message::params() to reduce code duplication
855 if ( $params ) {
856 $message->params( ...$params );
857 }
858
859 return $message;
860}
861
874function wfMessageFallback( ...$keys ) {
875 return Message::newFallbackSequence( ...$keys );
876}
877
886function wfMsgReplaceArgs( $message, $args ) {
887 # Fix windows line-endings
888 # Some messages are split with explode("\n", $msg)
889 $message = str_replace( "\r", '', $message );
890
891 // Replace arguments
892 if ( is_array( $args ) && $args ) {
893 if ( is_array( $args[0] ) ) {
894 $args = array_values( $args[0] );
895 }
896 $replacementKeys = [];
897 foreach ( $args as $n => $param ) {
898 $replacementKeys['$' . ( $n + 1 )] = $param;
899 }
900 $message = strtr( $message, $replacementKeys );
901 }
902
903 return $message;
904}
905
914function wfHostname() {
915 // Hostname overriding
916 global $wgOverrideHostname;
917 if ( $wgOverrideHostname !== false ) {
918 return $wgOverrideHostname;
919 }
920
921 return php_uname( 'n' ) ?: 'unknown';
922}
923
934function wfDebugBacktrace( $limit = 0 ) {
935 static $disabled = null;
936
937 if ( $disabled === null ) {
938 $disabled = !function_exists( 'debug_backtrace' );
939 if ( $disabled ) {
940 wfDebug( "debug_backtrace() is disabled" );
941 }
942 }
943 if ( $disabled ) {
944 return [];
945 }
946
947 if ( $limit ) {
948 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
949 } else {
950 return array_slice( debug_backtrace(), 1 );
951 }
952}
953
962function wfBacktrace( $raw = null ) {
963 $raw ??= MW_ENTRY_POINT === 'cli';
964 if ( $raw ) {
965 $frameFormat = "%s line %s calls %s()\n";
966 $traceFormat = "%s";
967 } else {
968 $frameFormat = "<li>%s line %s calls %s()</li>\n";
969 $traceFormat = "<ul>\n%s</ul>\n";
970 }
971
972 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
973 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
974 $line = $frame['line'] ?? '-';
975 $call = $frame['function'];
976 if ( !empty( $frame['class'] ) ) {
977 $call = $frame['class'] . $frame['type'] . $call;
978 }
979 return sprintf( $frameFormat, $file, $line, $call );
980 }, wfDebugBacktrace() );
981
982 return sprintf( $traceFormat, implode( '', $frames ) );
983}
984
995function wfGetCaller( $level = 2 ) {
996 $backtrace = wfDebugBacktrace( $level + 1 );
997 if ( isset( $backtrace[$level] ) ) {
998 return wfFormatStackFrame( $backtrace[$level] );
999 } else {
1000 return 'unknown';
1001 }
1002}
1003
1011function wfGetAllCallers( $limit = 3 ) {
1012 $trace = array_reverse( wfDebugBacktrace() );
1013 if ( !$limit || $limit > count( $trace ) - 1 ) {
1014 $limit = count( $trace ) - 1;
1015 }
1016 $trace = array_slice( $trace, -$limit - 1, $limit );
1017 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1018}
1019
1032function wfFormatStackFrame( $frame ) {
1033 if ( !isset( $frame['function'] ) ) {
1034 return 'NO_FUNCTION_GIVEN';
1035 }
1036 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1037 $frame['class'] . $frame['type'] . $frame['function'] :
1038 $frame['function'];
1039}
1040
1050function wfClientAcceptsGzip( $force = false ) {
1051 static $result = null;
1052 if ( $result === null || $force ) {
1053 $result = false;
1054 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1055 # @todo FIXME: We may want to disallow some broken browsers
1056 $m = [];
1057 if ( preg_match(
1058 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1059 $_SERVER['HTTP_ACCEPT_ENCODING'],
1060 $m
1061 )
1062 ) {
1063 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1064 return $result;
1065 }
1066 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1067 $result = true;
1068 }
1069 }
1070 }
1071 return $result;
1072}
1073
1084function wfEscapeWikiText( $input ): string {
1085 global $wgEnableMagicLinks;
1086 static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
1087 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1088 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1089 // in those situations
1090 $repl = [
1091 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1092 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1093 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1094 ';' => '&#59;', // a token inside language converter brackets
1095 '!!' => '&#33;!', // a token inside table context
1096 "\n!" => "\n&#33;", "\r!" => "\r&#33;", // a token inside table context
1097 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1098 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1099 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1100 "\n " => "\n&#32;", "\r " => "\r&#32;",
1101 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1102 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1103 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1104 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1105 '__' => '_&#95;', '://' => '&#58;//',
1106 '~~~' => '~~&#126;', // protect from PST, just to be safe(r)
1107 ];
1108
1109 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1110 // We have to catch everything "\s" matches in PCRE
1111 foreach ( $magicLinks as $magic ) {
1112 $repl["$magic "] = "$magic&#32;";
1113 $repl["$magic\t"] = "$magic&#9;";
1114 $repl["$magic\r"] = "$magic&#13;";
1115 $repl["$magic\n"] = "$magic&#10;";
1116 $repl["$magic\f"] = "$magic&#12;";
1117 }
1118 // Additionally escape the following characters at the beginning of the
1119 // string, in case they merge to form tokens when spliced into a
1120 // string. Tokens like -{ {{ [[ {| etc are already escaped because
1121 // the second character is escaped above, but the following tokens
1122 // are handled here: |+ |- __FOO__ ~~~
1123 $repl3 = [
1124 '+' => '&#43;', '-' => '&#45;', '_' => '&#95;', '~' => '&#126;',
1125 ];
1126 // Similarly, protect the following characters at the end of the
1127 // string, which could turn form the start of `__FOO__` or `~~~~`
1128 // A trailing newline could also form the unintended start of a
1129 // paragraph break if it is glued to a newline in the following
1130 // context.
1131 $repl4 = [
1132 '_' => '&#95;', '~' => '&#126;',
1133 "\n" => "&#10;", "\r" => "&#13;",
1134 "\t" => "&#9;", // "\n\t\n" is treated like "\n\n"
1135 ];
1136
1137 // And handle protocols that don't use "://"
1138 global $wgUrlProtocols;
1139 $repl2 = [];
1140 foreach ( $wgUrlProtocols as $prot ) {
1141 if ( substr( $prot, -1 ) === ':' ) {
1142 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1143 }
1144 }
1145 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1146 }
1147 // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
1148 '@phan-var string $repl2';
1149 '@phan-var string $repl3';
1150 '@phan-var string $repl4';
1151 // This will also stringify input in case it's not a string
1152 $text = substr( strtr( "\n$input", $repl ), 1 );
1153 if ( $text === '' ) {
1154 return $text;
1155 }
1156 $first = strtr( $text[0], $repl3 ); // protect first character
1157 if ( strlen( $text ) > 1 ) {
1158 $text = $first . substr( $text, 1, -1 ) .
1159 strtr( substr( $text, -1 ), $repl4 ); // protect last character
1160 } else {
1161 // special case for single-character strings
1162 $text = strtr( $first, $repl4 ); // protect last character
1163 }
1164 $text = preg_replace( $repl2, '$1&#58;', $text );
1165 return $text;
1166}
1167
1178function wfSetVar( &$dest, $source, $force = false ) {
1179 $temp = $dest;
1180 if ( $source !== null || $force ) {
1181 $dest = $source;
1182 }
1183 return $temp;
1184}
1185
1195function wfSetBit( &$dest, $bit, $state = true ) {
1196 $temp = (bool)( $dest & $bit );
1197 if ( $state !== null ) {
1198 if ( $state ) {
1199 $dest |= $bit;
1200 } else {
1201 $dest &= ~$bit;
1202 }
1203 }
1204 return $temp;
1205}
1206
1213function wfVarDump( $var ) {
1214 global $wgOut;
1215 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1216 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1217 print $s;
1218 } else {
1219 $wgOut->addHTML( $s );
1220 }
1221}
1222
1230function wfHttpError( $code, $label, $desc ) {
1231 global $wgOut;
1232 HttpStatus::header( $code );
1233 if ( $wgOut ) {
1234 $wgOut->disable();
1235 $wgOut->sendCacheControl();
1236 }
1237
1238 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1239 header( 'Content-type: text/html; charset=utf-8' );
1240 ob_start();
1241 print '<!DOCTYPE html>' .
1242 '<html><head><title>' .
1243 htmlspecialchars( $label ) .
1244 '</title></head><body><h1>' .
1245 htmlspecialchars( $label ) .
1246 '</h1><p>' .
1247 nl2br( htmlspecialchars( $desc ) ) .
1248 "</p></body></html>\n";
1249 header( 'Content-Length: ' . ob_get_length() );
1250 ob_end_flush();
1251}
1252
1273function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1274 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
1275 while ( $status = ob_get_status() ) {
1276 if ( isset( $status['flags'] ) ) {
1277 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1278 $deleteable = ( $status['flags'] & $flags ) === $flags;
1279 } elseif ( isset( $status['del'] ) ) {
1280 $deleteable = $status['del'];
1281 } else {
1282 // Guess that any PHP-internal setting can't be removed.
1283 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1284 }
1285 if ( !$deleteable ) {
1286 // Give up, and hope the result doesn't break
1287 // output behavior.
1288 break;
1289 }
1290 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1291 // Unit testing barrier to prevent this function from breaking PHPUnit.
1292 break;
1293 }
1294 if ( !ob_end_clean() ) {
1295 // Could not remove output buffer handler; abort now
1296 // to avoid getting in some kind of infinite loop.
1297 break;
1298 }
1299 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1300 // Reset the 'Content-Encoding' field set by this handler
1301 // so we can start fresh.
1302 header_remove( 'Content-Encoding' );
1303 break;
1304 }
1305 }
1306}
1307
1318function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1319 $ret = MWTimestamp::convert( $outputtype, $ts );
1320 if ( $ret === false ) {
1321 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1322 }
1323 return $ret;
1324}
1325
1334function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1335 if ( $ts === null ) {
1336 return null;
1337 } else {
1338 return wfTimestamp( $outputtype, $ts );
1339 }
1340}
1341
1347function wfTimestampNow() {
1348 return MWTimestamp::now( TS_MW );
1349}
1350
1362function wfTempDir() {
1363 global $wgTmpDirectory;
1364
1365 if ( $wgTmpDirectory !== false ) {
1366 return $wgTmpDirectory;
1367 }
1368
1369 return TempFSFile::getUsableTempDirectory();
1370}
1371
1380function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1381 global $wgDirectoryMode;
1382
1383 if ( FileBackend::isStoragePath( $dir ) ) {
1384 throw new LogicException( __FUNCTION__ . " given storage path '$dir'." );
1385 }
1386 if ( $caller !== null ) {
1387 wfDebug( "$caller: called wfMkdirParents($dir)" );
1388 }
1389 if ( strval( $dir ) === '' ) {
1390 return true;
1391 }
1392
1393 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1394 $mode ??= $wgDirectoryMode;
1395
1396 // Turn off the normal warning, we're doing our own below
1397 // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis.
1398 //
1399 // Repeat existence check if creation failed so that we silently recover in case of
1400 // a race condition where another request created it since the first check.
1401 //
1402 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1403 $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir );
1404 if ( !$ok ) {
1405 trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING );
1406 }
1407
1408 return $ok;
1409}
1410
1416function wfRecursiveRemoveDir( $dir ) {
1417 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1418 if ( is_dir( $dir ) ) {
1419 $objects = scandir( $dir );
1420 foreach ( $objects as $object ) {
1421 if ( $object != "." && $object != ".." ) {
1422 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1423 wfRecursiveRemoveDir( $dir . '/' . $object );
1424 } else {
1425 unlink( $dir . '/' . $object );
1426 }
1427 }
1428 }
1429 rmdir( $dir );
1430 }
1431}
1432
1439function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1440 $accForFormat = $acc >= 0 ? $acc : 0;
1441 $ret = sprintf( "%.{$accForFormat}f", $nr );
1442 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1443}
1444
1468function wfIniGetBool( $setting ) {
1469 return wfStringToBool( ini_get( $setting ) );
1470}
1471
1484function wfStringToBool( $val ) {
1485 $val = strtolower( $val );
1486 // 'on' and 'true' can't have whitespace around them, but '1' can.
1487 return $val == 'on'
1488 || $val == 'true'
1489 || $val == 'yes'
1490 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1491}
1492
1506function wfEscapeShellArg( ...$args ) {
1507 return Shell::escape( ...$args );
1508}
1509
1534function wfShellExec( $cmd, &$retval = null, $environ = [],
1535 $limits = [], $options = []
1536) {
1537 if ( Shell::isDisabled() ) {
1538 $retval = 1;
1539 // Backwards compatibility be upon us...
1540 return 'Unable to run external programs, proc_open() is disabled.';
1541 }
1542
1543 if ( is_array( $cmd ) ) {
1544 $cmd = Shell::escape( $cmd );
1545 }
1546
1547 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1548 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1549
1550 try {
1551 $result = Shell::command( [] )
1552 ->unsafeParams( (array)$cmd )
1553 ->environment( $environ )
1554 ->limits( $limits )
1555 ->includeStderr( $includeStderr )
1556 ->profileMethod( $profileMethod )
1557 // For b/c
1558 ->restrict( Shell::RESTRICT_NONE )
1559 ->execute();
1560 } catch ( ProcOpenError $ex ) {
1561 $retval = -1;
1562 return '';
1563 }
1564
1565 $retval = $result->getExitCode();
1566
1567 return $result->getStdout();
1568}
1569
1587function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1588 return wfShellExec( $cmd, $retval, $environ, $limits,
1589 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1590}
1591
1607function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1608 global $wgPhpCli;
1609 // Give site config file a chance to run the script in a wrapper.
1610 // The caller may likely want to call wfBasename() on $script.
1611 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1612 ->onWfShellWikiCmd( $script, $parameters, $options );
1613 $cmd = [ $options['php'] ?? $wgPhpCli ];
1614 if ( isset( $options['wrapper'] ) ) {
1615 $cmd[] = $options['wrapper'];
1616 }
1617 $cmd[] = $script;
1618 // Escape each parameter for shell
1619 return Shell::escape( array_merge( $cmd, $parameters ) );
1620}
1621
1638function wfMerge(
1639 string $old,
1640 string $mine,
1641 string $yours,
1642 ?string &$simplisticMergeAttempt,
1643 string &$mergeLeftovers = null
1644): bool {
1645 global $wgDiff3;
1646
1647 # This check may also protect against code injection in
1648 # case of broken installations.
1649 AtEase::suppressWarnings();
1650 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1651 AtEase::restoreWarnings();
1652
1653 if ( !$haveDiff3 ) {
1654 wfDebug( "diff3 not found" );
1655 return false;
1656 }
1657
1658 # Make temporary files
1659 $td = wfTempDir();
1660 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1661 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1662 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1663
1664 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1665 # a newline character. To avoid this, we normalize the trailing whitespace before
1666 # creating the diff.
1667
1668 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1669 fclose( $oldtextFile );
1670 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1671 fclose( $mytextFile );
1672 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1673 fclose( $yourtextFile );
1674
1675 # Check for a conflict
1676 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1677 $oldtextName, $yourtextName );
1678 $handle = popen( $cmd, 'r' );
1679
1680 $mergeLeftovers = '';
1681 do {
1682 $data = fread( $handle, 8192 );
1683 if ( strlen( $data ) == 0 ) {
1684 break;
1685 }
1686 $mergeLeftovers .= $data;
1687 } while ( true );
1688 pclose( $handle );
1689
1690 $conflict = $mergeLeftovers !== '';
1691
1692 # Merge differences automatically where possible, preferring "my" text for conflicts.
1693 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1694 $oldtextName, $yourtextName );
1695 $handle = popen( $cmd, 'r' );
1696 $simplisticMergeAttempt = '';
1697 do {
1698 $data = fread( $handle, 8192 );
1699 if ( strlen( $data ) == 0 ) {
1700 break;
1701 }
1702 $simplisticMergeAttempt .= $data;
1703 } while ( true );
1704 pclose( $handle );
1705 unlink( $mytextName );
1706 unlink( $oldtextName );
1707 unlink( $yourtextName );
1708
1709 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1710 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1711 $conflict = true;
1712 }
1713 return !$conflict;
1714}
1715
1728function wfBaseName( $path, $suffix = '' ) {
1729 if ( $suffix == '' ) {
1730 $encSuffix = '';
1731 } else {
1732 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1733 }
1734
1735 $matches = [];
1736 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1737 return $matches[1];
1738 } else {
1739 return '';
1740 }
1741}
1742
1752function wfRelativePath( $path, $from ) {
1753 // Normalize mixed input on Windows...
1754 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1755 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1756
1757 // Trim trailing slashes -- fix for drive root
1758 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1759 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1760
1761 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1762 $against = explode( DIRECTORY_SEPARATOR, $from );
1763
1764 if ( $pieces[0] !== $against[0] ) {
1765 // Non-matching Windows drive letters?
1766 // Return a full path.
1767 return $path;
1768 }
1769
1770 // Trim off common prefix
1771 while ( count( $pieces ) && count( $against )
1772 && $pieces[0] == $against[0] ) {
1773 array_shift( $pieces );
1774 array_shift( $against );
1775 }
1776
1777 // relative dots to bump us to the parent
1778 while ( count( $against ) ) {
1779 array_unshift( $pieces, '..' );
1780 array_shift( $against );
1781 }
1782
1783 $pieces[] = wfBaseName( $path );
1784
1785 return implode( DIRECTORY_SEPARATOR, $pieces );
1786}
1787
1825function wfGetDB( $db, $groups = [], $wiki = false ) {
1826 wfDeprecated( __FUNCTION__, '1.39' );
1827
1828 if ( $wiki === false ) {
1829 return MediaWikiServices::getInstance()
1830 ->getDBLoadBalancer()
1831 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1832 } else {
1833 return MediaWikiServices::getInstance()
1834 ->getDBLoadBalancerFactory()
1835 ->getMainLB( $wiki )
1836 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1837 }
1838}
1839
1849function wfScript( $script = 'index' ) {
1851 if ( $script === 'index' ) {
1852 return $wgScript;
1853 } elseif ( $script === 'load' ) {
1854 return $wgLoadScript;
1855 } else {
1856 return "{$wgScriptPath}/{$script}.php";
1857 }
1858}
1859
1867function wfBoolToStr( $value ) {
1868 return $value ? 'true' : 'false';
1869}
1870
1876function wfGetNull() {
1877 return wfIsWindows() ? 'NUL' : '/dev/null';
1878}
1879
1889 global $wgIllegalFileChars;
1890 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1891 $name = preg_replace(
1892 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1893 '-',
1894 $name
1895 );
1896 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1897 $name = wfBaseName( $name );
1898 return $name;
1899}
1900
1907function wfMemoryLimit( $newLimit ) {
1908 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1909 // If the INI config is already unlimited, there is nothing larger
1910 if ( $oldLimit != -1 ) {
1911 $newLimit = wfShorthandToInteger( (string)$newLimit );
1912 if ( $newLimit == -1 ) {
1913 wfDebug( "Removing PHP's memory limit" );
1914 AtEase::suppressWarnings();
1915 ini_set( 'memory_limit', $newLimit );
1916 AtEase::restoreWarnings();
1917 } elseif ( $newLimit > $oldLimit ) {
1918 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1919 AtEase::suppressWarnings();
1920 ini_set( 'memory_limit', $newLimit );
1921 AtEase::restoreWarnings();
1922 }
1923 }
1924}
1925
1934
1935 $timeout = RequestTimeout::singleton();
1936 $timeLimit = $timeout->getWallTimeLimit();
1937 if ( $timeLimit !== INF ) {
1938 // RequestTimeout library is active
1939 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1940 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1941 }
1942 } else {
1943 // Fallback case, likely $wgRequestTimeLimit === null
1944 $timeLimit = (int)ini_get( 'max_execution_time' );
1945 // Note that CLI scripts use 0
1946 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
1947 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1948 }
1949 }
1950 ignore_user_abort( true ); // ignore client disconnects
1951
1952 return $timeLimit;
1953}
1954
1962function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
1963 $string = trim( $string ?? '' );
1964 if ( $string === '' ) {
1965 return $default;
1966 }
1967 $last = $string[strlen( $string ) - 1];
1968 $val = intval( $string );
1969 switch ( $last ) {
1970 case 'g':
1971 case 'G':
1972 $val *= 1024;
1973 // break intentionally missing
1974 case 'm':
1975 case 'M':
1976 $val *= 1024;
1977 // break intentionally missing
1978 case 'k':
1979 case 'K':
1980 $val *= 1024;
1981 }
1982
1983 return $val;
1984}
1985
1993function wfIsInfinity( $str ) {
1994 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
1995 return in_array( $str, ExpiryDef::INFINITY_VALS );
1996}
1997
2012function wfThumbIsStandard( File $file, array $params ) {
2014
2015 $multipliers = [ 1 ];
2016 if ( $wgResponsiveImages ) {
2017 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2018 // @see Linker::processResponsiveImages
2019 $multipliers[] = 1.5;
2020 $multipliers[] = 2;
2021 }
2022
2023 $handler = $file->getHandler();
2024 if ( !$handler || !isset( $params['width'] ) ) {
2025 return false;
2026 }
2027
2028 $basicParams = [];
2029 if ( isset( $params['page'] ) ) {
2030 $basicParams['page'] = $params['page'];
2031 }
2032
2033 $thumbLimits = [];
2034 $imageLimits = [];
2035 // Expand limits to account for multipliers
2036 foreach ( $multipliers as $multiplier ) {
2037 $thumbLimits = array_merge( $thumbLimits, array_map(
2038 static function ( $width ) use ( $multiplier ) {
2039 return round( $width * $multiplier );
2040 }, $wgThumbLimits )
2041 );
2042 $imageLimits = array_merge( $imageLimits, array_map(
2043 static function ( $pair ) use ( $multiplier ) {
2044 return [
2045 round( $pair[0] * $multiplier ),
2046 round( $pair[1] * $multiplier ),
2047 ];
2048 }, $wgImageLimits )
2049 );
2050 }
2051
2052 // Check if the width matches one of $wgThumbLimits
2053 if ( in_array( $params['width'], $thumbLimits ) ) {
2054 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2055 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2056 $handler->normaliseParams( $file, $normalParams );
2057 } else {
2058 // If not, then check if the width matches one of $wgImageLimits
2059 $match = false;
2060 foreach ( $imageLimits as $pair ) {
2061 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2062 // Decide whether the thumbnail should be scaled on width or height.
2063 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2064 $handler->normaliseParams( $file, $normalParams );
2065 // Check if this standard thumbnail size maps to the given width
2066 if ( $normalParams['width'] == $params['width'] ) {
2067 $match = true;
2068 break;
2069 }
2070 }
2071 if ( !$match ) {
2072 return false; // not standard for description pages
2073 }
2074 }
2075
2076 // Check that the given values for non-page, non-width, params are just defaults
2077 foreach ( $params as $key => $value ) {
2078 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2079 return false;
2080 }
2081 }
2082
2083 return true;
2084}
2085
2098function wfArrayPlus2d( array $baseArray, array $newValues ) {
2099 // First merge items that are in both arrays
2100 foreach ( $baseArray as $name => &$groupVal ) {
2101 if ( isset( $newValues[$name] ) ) {
2102 $groupVal += $newValues[$name];
2103 }
2104 }
2105 // Now add items that didn't exist yet
2106 $baseArray += $newValues;
2107
2108 return $baseArray;
2109}
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()
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
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...
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:419
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgOut
Definition Setup.php:540
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:74
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1551
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:150
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
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