MediaWiki master
GlobalFunctions.php
Go to the documentation of this file.
1<?php
36use 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
171function wfMergeErrorArrays( ...$args ) {
172 $out = [];
173 foreach ( $args as $errors ) {
174 foreach ( $errors as $params ) {
175 $originalParams = $params;
176 if ( $params[0] instanceof MessageSpecifier ) {
177 $params = [ $params[0]->getKey(), ...$params[0]->getParams() ];
178 }
179 # @todo FIXME: Sometimes get nested arrays for $params,
180 # which leads to E_NOTICEs
181 $spec = implode( "\t", $params );
182 $out[$spec] = $originalParams;
183 }
184 }
185 return array_values( $out );
186}
187
197function wfArrayInsertAfter( array $array, array $insert, $after ) {
198 // Find the offset of the element to insert after.
199 $keys = array_keys( $array );
200 $offsetByKey = array_flip( $keys );
201
202 if ( !\array_key_exists( $after, $offsetByKey ) ) {
203 return $array;
204 }
205 $offset = $offsetByKey[$after];
206
207 // Insert at the specified offset
208 $before = array_slice( $array, 0, $offset + 1, true );
209 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
210
211 $output = $before + $insert + $after;
212
213 return $output;
214}
215
224function wfObjectToArray( $objOrArray, $recursive = true ) {
225 $array = [];
226 if ( is_object( $objOrArray ) ) {
227 $objOrArray = get_object_vars( $objOrArray );
228 }
229 foreach ( $objOrArray as $key => $value ) {
230 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
231 $value = wfObjectToArray( $value );
232 }
233
234 $array[$key] = $value;
235 }
236
237 return $array;
238}
239
250function wfRandom() {
251 // The maximum random value is "only" 2^31-1, so get two random
252 // values to reduce the chance of dupes
253 $max = mt_getrandmax() + 1;
254 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
255 return $rand;
256}
257
268function wfRandomString( $length = 32 ) {
269 $str = '';
270 for ( $n = 0; $n < $length; $n += 7 ) {
271 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
272 }
273 return substr( $str, 0, $length );
274}
275
303function wfUrlencode( $s ) {
304 static $needle;
305
306 if ( $s === null ) {
307 // Reset $needle for testing.
308 $needle = null;
309 return '';
310 }
311
312 if ( $needle === null ) {
313 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
314 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
315 !str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
316 ) {
317 $needle[] = '%3A';
318 }
319 }
320
321 $s = urlencode( $s );
322 $s = str_ireplace(
323 $needle,
324 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
325 $s
326 );
327
328 return $s;
329}
330
341function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
342 if ( $array2 !== null ) {
343 $array1 += $array2;
344 }
345
346 $cgi = '';
347 foreach ( $array1 as $key => $value ) {
348 if ( $value !== null && $value !== false ) {
349 if ( $cgi != '' ) {
350 $cgi .= '&';
351 }
352 if ( $prefix !== '' ) {
353 $key = $prefix . "[$key]";
354 }
355 if ( is_array( $value ) ) {
356 $firstTime = true;
357 foreach ( $value as $k => $v ) {
358 $cgi .= $firstTime ? '' : '&';
359 if ( is_array( $v ) ) {
360 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
361 } else {
362 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
363 }
364 $firstTime = false;
365 }
366 } else {
367 if ( is_object( $value ) ) {
368 $value = $value->__toString();
369 }
370 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
371 }
372 }
373 }
374 return $cgi;
375}
376
386function wfCgiToArray( $query ) {
387 if ( isset( $query[0] ) && $query[0] == '?' ) {
388 $query = substr( $query, 1 );
389 }
390 $bits = explode( '&', $query );
391 $ret = [];
392 foreach ( $bits as $bit ) {
393 if ( $bit === '' ) {
394 continue;
395 }
396 if ( strpos( $bit, '=' ) === false ) {
397 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
398 $key = $bit;
399 $value = '';
400 } else {
401 [ $key, $value ] = explode( '=', $bit );
402 }
403 $key = urldecode( $key );
404 $value = urldecode( $value );
405 if ( strpos( $key, '[' ) !== false ) {
406 $keys = array_reverse( explode( '[', $key ) );
407 $key = array_pop( $keys );
408 $temp = $value;
409 foreach ( $keys as $k ) {
410 $k = substr( $k, 0, -1 );
411 $temp = [ $k => $temp ];
412 }
413 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
414 $ret[$key] = array_merge( $ret[$key], $temp );
415 } else {
416 $ret[$key] = $temp;
417 }
418 } else {
419 $ret[$key] = $value;
420 }
421 }
422 return $ret;
423}
424
433function wfAppendQuery( $url, $query ) {
434 if ( is_array( $query ) ) {
435 $query = wfArrayToCgi( $query );
436 }
437 if ( $query != '' ) {
438 // Remove the fragment, if there is one
439 $fragment = false;
440 $hashPos = strpos( $url, '#' );
441 if ( $hashPos !== false ) {
442 $fragment = substr( $url, $hashPos );
443 $url = substr( $url, 0, $hashPos );
444 }
445
446 // Add parameter
447 if ( strpos( $url, '?' ) === false ) {
448 $url .= '?';
449 } else {
450 $url .= '&';
451 }
452 $url .= $query;
453
454 // Put the fragment back
455 if ( $fragment !== false ) {
456 $url .= $fragment;
457 }
458 }
459 return $url;
460}
461
470
471 if ( MediaWikiServices::hasInstance() ) {
472 $services = MediaWikiServices::getInstance();
473 if ( $services->hasService( 'UrlUtils' ) ) {
474 return $services->getUrlUtils();
475 }
476 }
477
478 return new UrlUtils( [
479 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
480 // implementations implicitly converted it to an empty string (presumably by mistake).
481 // Preserve the old behavior for compatibility.
482 UrlUtils::SERVER => $wgServer ?? '',
483 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
484 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
485 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
486 : WebRequest::detectProtocol(),
487 UrlUtils::HTTPS_PORT => $wgHttpsPort,
488 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
489 ] );
490}
491
519function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
520 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
521}
522
532function wfGetServerUrl( $proto ) {
533 return wfGetUrlUtils()->getServer( $proto ) ?? '';
534}
535
548function wfAssembleUrl( $urlParts ) {
549 return UrlUtils::assemble( (array)$urlParts );
550}
551
562function wfRemoveDotSegments( $urlPath ) {
563 return UrlUtils::removeDotSegments( (string)$urlPath );
564}
565
574function wfUrlProtocols( $includeProtocolRelative = true ) {
575 return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() :
576 wfGetUrlUtils()->validAbsoluteProtocols();
577}
578
587 return wfGetUrlUtils()->validAbsoluteProtocols();
588}
589
616function wfParseUrl( $url ) {
617 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
618}
619
629function wfExpandIRI( $url ) {
630 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
631}
632
641function wfMatchesDomainList( $url, $domains ) {
642 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
643}
644
665function wfDebug( $text, $dest = 'all', array $context = [] ) {
667
668 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
669 return;
670 }
671
672 $text = trim( $text );
673
674 if ( $wgDebugLogPrefix !== '' ) {
675 $context['prefix'] = $wgDebugLogPrefix;
676 }
677 $context['private'] = ( $dest === false || $dest === 'private' );
678
679 $logger = LoggerFactory::getInstance( 'wfDebug' );
680 $logger->debug( $text, $context );
681}
682
688 static $cache;
689 if ( $cache !== null ) {
690 return $cache;
691 }
692 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
693 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
694 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
695 || MW_ENTRY_POINT === 'load'
696 ) {
697 $cache = true;
698 } else {
699 $cache = false;
700 }
701 return $cache;
702}
703
729function wfDebugLog(
730 $logGroup, $text, $dest = 'all', array $context = []
731) {
732 $text = trim( $text );
733
734 $logger = LoggerFactory::getInstance( $logGroup );
735 $context['private'] = ( $dest === false || $dest === 'private' );
736 $logger->info( $text, $context );
737}
738
747function wfLogDBError( $text, array $context = [] ) {
748 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
749 $logger->error( trim( $text ), $context );
750}
751
768function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
769 if ( !is_string( $version ) && $version !== false ) {
770 throw new InvalidArgumentException(
771 "MediaWiki version must either be a string or false. " .
772 "Example valid version: '1.33'"
773 );
774 }
775
776 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
777}
778
799function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
800 MWDebug::deprecatedMsg( $msg, $version, $component,
801 $callerOffset === false ? false : $callerOffset + 1 );
802}
803
814function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
815 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
816}
817
827function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
828 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
829}
830
847function wfGetLangObj( $langcode = false ) {
848 wfDeprecated( __FUNCTION__, '1.41' );
849 # Identify which language to get or create a language object for.
850 # Using is_object here due to Stub objects.
851 if ( is_object( $langcode ) ) {
852 # Great, we already have the object (hopefully)!
853 return $langcode;
854 }
855
856 global $wgLanguageCode;
857 $services = MediaWikiServices::getInstance();
858 if ( $langcode === true || $langcode === $wgLanguageCode ) {
859 # $langcode is the language code of the wikis content language object.
860 # or it is a boolean and value is true
861 return $services->getContentLanguage();
862 }
863
864 global $wgLang;
865 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
866 # $langcode is the language code of user language object.
867 # or it was a boolean and value is false
868 return $wgLang;
869 }
870
871 $languageNames = $services->getLanguageNameUtils()->getLanguageNames();
872 // FIXME: Can we use isSupportedLanguage here?
873 if ( isset( $languageNames[$langcode] ) ) {
874 # $langcode corresponds to a valid language.
875 return $services->getLanguageFactory()->getLanguage( $langcode );
876 }
877
878 # $langcode is a string, but not a valid language code; use content language.
879 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
880 return $services->getContentLanguage();
881}
882
904function wfMessage( $key, ...$params ) {
905 if ( is_array( $key ) ) {
906 // Fallback keys are not allowed in message specifiers
907 $message = wfMessageFallback( ...$key );
908 } else {
909 $message = Message::newFromSpecifier( $key );
910 }
911
912 // We call Message::params() to reduce code duplication
913 if ( $params ) {
914 $message->params( ...$params );
915 }
916
917 return $message;
918}
919
932function wfMessageFallback( ...$keys ) {
933 return Message::newFallbackSequence( ...$keys );
934}
935
944function wfMsgReplaceArgs( $message, $args ) {
945 # Fix windows line-endings
946 # Some messages are split with explode("\n", $msg)
947 $message = str_replace( "\r", '', $message );
948
949 // Replace arguments
950 if ( is_array( $args ) && $args ) {
951 if ( is_array( $args[0] ) ) {
952 $args = array_values( $args[0] );
953 }
954 $replacementKeys = [];
955 foreach ( $args as $n => $param ) {
956 $replacementKeys['$' . ( $n + 1 )] = $param;
957 }
958 $message = strtr( $message, $replacementKeys );
959 }
960
961 return $message;
962}
963
972function wfHostname() {
973 // Hostname overriding
974 global $wgOverrideHostname;
975 if ( $wgOverrideHostname !== false ) {
976 return $wgOverrideHostname;
977 }
978
979 return php_uname( 'n' ) ?: 'unknown';
980}
981
992function wfDebugBacktrace( $limit = 0 ) {
993 static $disabled = null;
994
995 if ( $disabled === null ) {
996 $disabled = !function_exists( 'debug_backtrace' );
997 if ( $disabled ) {
998 wfDebug( "debug_backtrace() is disabled" );
999 }
1000 }
1001 if ( $disabled ) {
1002 return [];
1003 }
1004
1005 if ( $limit ) {
1006 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1007 } else {
1008 return array_slice( debug_backtrace(), 1 );
1009 }
1010}
1011
1020function wfBacktrace( $raw = null ) {
1021 $raw ??= MW_ENTRY_POINT === 'cli';
1022 if ( $raw ) {
1023 $frameFormat = "%s line %s calls %s()\n";
1024 $traceFormat = "%s";
1025 } else {
1026 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1027 $traceFormat = "<ul>\n%s</ul>\n";
1028 }
1029
1030 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1031 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1032 $line = $frame['line'] ?? '-';
1033 $call = $frame['function'];
1034 if ( !empty( $frame['class'] ) ) {
1035 $call = $frame['class'] . $frame['type'] . $call;
1036 }
1037 return sprintf( $frameFormat, $file, $line, $call );
1038 }, wfDebugBacktrace() );
1039
1040 return sprintf( $traceFormat, implode( '', $frames ) );
1041}
1042
1053function wfGetCaller( $level = 2 ) {
1054 $backtrace = wfDebugBacktrace( $level + 1 );
1055 if ( isset( $backtrace[$level] ) ) {
1056 return wfFormatStackFrame( $backtrace[$level] );
1057 } else {
1058 return 'unknown';
1059 }
1060}
1061
1069function wfGetAllCallers( $limit = 3 ) {
1070 $trace = array_reverse( wfDebugBacktrace() );
1071 if ( !$limit || $limit > count( $trace ) - 1 ) {
1072 $limit = count( $trace ) - 1;
1073 }
1074 $trace = array_slice( $trace, -$limit - 1, $limit );
1075 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1076}
1077
1090function wfFormatStackFrame( $frame ) {
1091 if ( !isset( $frame['function'] ) ) {
1092 return 'NO_FUNCTION_GIVEN';
1093 }
1094 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1095 $frame['class'] . $frame['type'] . $frame['function'] :
1096 $frame['function'];
1097}
1098
1108function wfClientAcceptsGzip( $force = false ) {
1109 static $result = null;
1110 if ( $result === null || $force ) {
1111 $result = false;
1112 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1113 # @todo FIXME: We may want to disallow some broken browsers
1114 $m = [];
1115 if ( preg_match(
1116 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1117 $_SERVER['HTTP_ACCEPT_ENCODING'],
1118 $m
1119 )
1120 ) {
1121 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1122 return $result;
1123 }
1124 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1125 $result = true;
1126 }
1127 }
1128 }
1129 return $result;
1130}
1131
1142function wfEscapeWikiText( $input ): string {
1143 global $wgEnableMagicLinks;
1144 static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
1145 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1146 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1147 // in those situations
1148 $repl = [
1149 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1150 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1151 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1152 ';' => '&#59;', // a token inside language converter brackets
1153 '!!' => '&#33;!', // a token inside table context
1154 "\n!" => "\n&#33;", "\r!" => "\r&#33;", // a token inside table context
1155 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1156 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1157 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1158 "\n " => "\n&#32;", "\r " => "\r&#32;",
1159 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1160 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1161 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1162 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1163 '__' => '_&#95;', '://' => '&#58;//',
1164 '~~~' => '~~&#126;', // protect from PST, just to be safe(r)
1165 ];
1166
1167 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1168 // We have to catch everything "\s" matches in PCRE
1169 foreach ( $magicLinks as $magic ) {
1170 $repl["$magic "] = "$magic&#32;";
1171 $repl["$magic\t"] = "$magic&#9;";
1172 $repl["$magic\r"] = "$magic&#13;";
1173 $repl["$magic\n"] = "$magic&#10;";
1174 $repl["$magic\f"] = "$magic&#12;";
1175 }
1176 // Additionally escape the following characters at the beginning of the
1177 // string, in case they merge to form tokens when spliced into a
1178 // string. Tokens like -{ {{ [[ {| etc are already escaped because
1179 // the second character is escaped above, but the following tokens
1180 // are handled here: |+ |- __FOO__ ~~~
1181 $repl3 = [
1182 '+' => '&#43;', '-' => '&#45;', '_' => '&#95;', '~' => '&#126;',
1183 ];
1184 // Similarly, protect the following characters at the end of the
1185 // string, which could turn form the start of `__FOO__` or `~~~~`
1186 // A trailing newline could also form the unintended start of a
1187 // paragraph break if it is glued to a newline in the following
1188 // context.
1189 $repl4 = [
1190 '_' => '&#95;', '~' => '&#126;',
1191 "\n" => "&#10;", "\r" => "&#13;",
1192 "\t" => "&#9;", // "\n\t\n" is treated like "\n\n"
1193 ];
1194
1195 // And handle protocols that don't use "://"
1196 global $wgUrlProtocols;
1197 $repl2 = [];
1198 foreach ( $wgUrlProtocols as $prot ) {
1199 if ( substr( $prot, -1 ) === ':' ) {
1200 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1201 }
1202 }
1203 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1204 }
1205 // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
1206 '@phan-var string $repl2';
1207 '@phan-var string $repl3';
1208 '@phan-var string $repl4';
1209 // This will also stringify input in case it's not a string
1210 $text = substr( strtr( "\n$input", $repl ), 1 );
1211 if ( $text === '' ) {
1212 return $text;
1213 }
1214 $first = strtr( $text[0], $repl3 ); // protect first character
1215 if ( strlen( $text ) > 1 ) {
1216 $text = $first . substr( $text, 1, -1 ) .
1217 strtr( substr( $text, -1 ), $repl4 ); // protect last character
1218 } else {
1219 // special case for single-character strings
1220 $text = strtr( $first, $repl4 ); // protect last character
1221 }
1222 $text = preg_replace( $repl2, '$1&#58;', $text );
1223 return $text;
1224}
1225
1236function wfSetVar( &$dest, $source, $force = false ) {
1237 $temp = $dest;
1238 if ( $source !== null || $force ) {
1239 $dest = $source;
1240 }
1241 return $temp;
1242}
1243
1253function wfSetBit( &$dest, $bit, $state = true ) {
1254 $temp = (bool)( $dest & $bit );
1255 if ( $state !== null ) {
1256 if ( $state ) {
1257 $dest |= $bit;
1258 } else {
1259 $dest &= ~$bit;
1260 }
1261 }
1262 return $temp;
1263}
1264
1271function wfVarDump( $var ) {
1272 global $wgOut;
1273 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1274 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1275 print $s;
1276 } else {
1277 $wgOut->addHTML( $s );
1278 }
1279}
1280
1288function wfHttpError( $code, $label, $desc ) {
1289 global $wgOut;
1290 HttpStatus::header( $code );
1291 if ( $wgOut ) {
1292 $wgOut->disable();
1293 $wgOut->sendCacheControl();
1294 }
1295
1296 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1297 header( 'Content-type: text/html; charset=utf-8' );
1298 ob_start();
1299 print '<!DOCTYPE html>' .
1300 '<html><head><title>' .
1301 htmlspecialchars( $label ) .
1302 '</title></head><body><h1>' .
1303 htmlspecialchars( $label ) .
1304 '</h1><p>' .
1305 nl2br( htmlspecialchars( $desc ) ) .
1306 "</p></body></html>\n";
1307 header( 'Content-Length: ' . ob_get_length() );
1308 ob_end_flush();
1309}
1310
1331function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1332 while ( $status = ob_get_status() ) {
1333 if ( isset( $status['flags'] ) ) {
1334 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1335 $deleteable = ( $status['flags'] & $flags ) === $flags;
1336 } elseif ( isset( $status['del'] ) ) {
1337 $deleteable = $status['del'];
1338 } else {
1339 // Guess that any PHP-internal setting can't be removed.
1340 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1341 }
1342 if ( !$deleteable ) {
1343 // Give up, and hope the result doesn't break
1344 // output behavior.
1345 break;
1346 }
1347 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1348 // Unit testing barrier to prevent this function from breaking PHPUnit.
1349 break;
1350 }
1351 if ( !ob_end_clean() ) {
1352 // Could not remove output buffer handler; abort now
1353 // to avoid getting in some kind of infinite loop.
1354 break;
1355 }
1356 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1357 // Reset the 'Content-Encoding' field set by this handler
1358 // so we can start fresh.
1359 header_remove( 'Content-Encoding' );
1360 break;
1361 }
1362 }
1363}
1364
1375function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1376 $ret = MWTimestamp::convert( $outputtype, $ts );
1377 if ( $ret === false ) {
1378 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1379 }
1380 return $ret;
1381}
1382
1391function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1392 if ( $ts === null ) {
1393 return null;
1394 } else {
1395 return wfTimestamp( $outputtype, $ts );
1396 }
1397}
1398
1404function wfTimestampNow() {
1405 return MWTimestamp::now( TS_MW );
1406}
1407
1419function wfTempDir() {
1420 global $wgTmpDirectory;
1421
1422 if ( $wgTmpDirectory !== false ) {
1423 return $wgTmpDirectory;
1424 }
1425
1426 return TempFSFile::getUsableTempDirectory();
1427}
1428
1437function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1438 global $wgDirectoryMode;
1439
1440 if ( FileBackend::isStoragePath( $dir ) ) {
1441 throw new LogicException( __FUNCTION__ . " given storage path '$dir'." );
1442 }
1443 if ( $caller !== null ) {
1444 wfDebug( "$caller: called wfMkdirParents($dir)" );
1445 }
1446 if ( strval( $dir ) === '' ) {
1447 return true;
1448 }
1449
1450 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1451 $mode ??= $wgDirectoryMode;
1452
1453 // Turn off the normal warning, we're doing our own below
1454 // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis.
1455 //
1456 // Repeat existence check if creation failed so that we silently recover in case of
1457 // a race condition where another request created it since the first check.
1458 //
1459 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1460 $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir );
1461 if ( !$ok ) {
1462 trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING );
1463 }
1464
1465 return $ok;
1466}
1467
1473function wfRecursiveRemoveDir( $dir ) {
1474 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1475 if ( is_dir( $dir ) ) {
1476 $objects = scandir( $dir );
1477 foreach ( $objects as $object ) {
1478 if ( $object != "." && $object != ".." ) {
1479 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1480 wfRecursiveRemoveDir( $dir . '/' . $object );
1481 } else {
1482 unlink( $dir . '/' . $object );
1483 }
1484 }
1485 }
1486 rmdir( $dir );
1487 }
1488}
1489
1496function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1497 $accForFormat = $acc >= 0 ? $acc : 0;
1498 $ret = sprintf( "%.{$accForFormat}f", $nr );
1499 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1500}
1501
1525function wfIniGetBool( $setting ) {
1526 return wfStringToBool( ini_get( $setting ) );
1527}
1528
1541function wfStringToBool( $val ) {
1542 $val = strtolower( $val );
1543 // 'on' and 'true' can't have whitespace around them, but '1' can.
1544 return $val == 'on'
1545 || $val == 'true'
1546 || $val == 'yes'
1547 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1548}
1549
1563function wfEscapeShellArg( ...$args ) {
1564 return Shell::escape( ...$args );
1565}
1566
1591function wfShellExec( $cmd, &$retval = null, $environ = [],
1592 $limits = [], $options = []
1593) {
1594 if ( Shell::isDisabled() ) {
1595 $retval = 1;
1596 // Backwards compatibility be upon us...
1597 return 'Unable to run external programs, proc_open() is disabled.';
1598 }
1599
1600 if ( is_array( $cmd ) ) {
1601 $cmd = Shell::escape( $cmd );
1602 }
1603
1604 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1605 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1606
1607 try {
1608 $result = Shell::command( [] )
1609 ->unsafeParams( (array)$cmd )
1610 ->environment( $environ )
1611 ->limits( $limits )
1612 ->includeStderr( $includeStderr )
1613 ->profileMethod( $profileMethod )
1614 // For b/c
1615 ->restrict( Shell::RESTRICT_NONE )
1616 ->execute();
1617 } catch ( ProcOpenError $ex ) {
1618 $retval = -1;
1619 return '';
1620 }
1621
1622 $retval = $result->getExitCode();
1623
1624 return $result->getStdout();
1625}
1626
1644function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1645 return wfShellExec( $cmd, $retval, $environ, $limits,
1646 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1647}
1648
1664function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1665 global $wgPhpCli;
1666 // Give site config file a chance to run the script in a wrapper.
1667 // The caller may likely want to call wfBasename() on $script.
1668 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1669 ->onWfShellWikiCmd( $script, $parameters, $options );
1670 $cmd = [ $options['php'] ?? $wgPhpCli ];
1671 if ( isset( $options['wrapper'] ) ) {
1672 $cmd[] = $options['wrapper'];
1673 }
1674 $cmd[] = $script;
1675 // Escape each parameter for shell
1676 return Shell::escape( array_merge( $cmd, $parameters ) );
1677}
1678
1695function wfMerge(
1696 string $old,
1697 string $mine,
1698 string $yours,
1699 ?string &$simplisticMergeAttempt,
1700 string &$mergeLeftovers = null
1701): bool {
1702 global $wgDiff3;
1703
1704 # This check may also protect against code injection in
1705 # case of broken installations.
1706 AtEase::suppressWarnings();
1707 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1708 AtEase::restoreWarnings();
1709
1710 if ( !$haveDiff3 ) {
1711 wfDebug( "diff3 not found" );
1712 return false;
1713 }
1714
1715 # Make temporary files
1716 $td = wfTempDir();
1717 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1718 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1719 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1720
1721 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1722 # a newline character. To avoid this, we normalize the trailing whitespace before
1723 # creating the diff.
1724
1725 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1726 fclose( $oldtextFile );
1727 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1728 fclose( $mytextFile );
1729 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1730 fclose( $yourtextFile );
1731
1732 # Check for a conflict
1733 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1734 $oldtextName, $yourtextName );
1735 $handle = popen( $cmd, 'r' );
1736
1737 $mergeLeftovers = '';
1738 do {
1739 $data = fread( $handle, 8192 );
1740 if ( strlen( $data ) == 0 ) {
1741 break;
1742 }
1743 $mergeLeftovers .= $data;
1744 } while ( true );
1745 pclose( $handle );
1746
1747 $conflict = $mergeLeftovers !== '';
1748
1749 # Merge differences automatically where possible, preferring "my" text for conflicts.
1750 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1751 $oldtextName, $yourtextName );
1752 $handle = popen( $cmd, 'r' );
1753 $simplisticMergeAttempt = '';
1754 do {
1755 $data = fread( $handle, 8192 );
1756 if ( strlen( $data ) == 0 ) {
1757 break;
1758 }
1759 $simplisticMergeAttempt .= $data;
1760 } while ( true );
1761 pclose( $handle );
1762 unlink( $mytextName );
1763 unlink( $oldtextName );
1764 unlink( $yourtextName );
1765
1766 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1767 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1768 $conflict = true;
1769 }
1770 return !$conflict;
1771}
1772
1785function wfBaseName( $path, $suffix = '' ) {
1786 if ( $suffix == '' ) {
1787 $encSuffix = '';
1788 } else {
1789 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1790 }
1791
1792 $matches = [];
1793 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1794 return $matches[1];
1795 } else {
1796 return '';
1797 }
1798}
1799
1809function wfRelativePath( $path, $from ) {
1810 // Normalize mixed input on Windows...
1811 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1812 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1813
1814 // Trim trailing slashes -- fix for drive root
1815 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1816 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1817
1818 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1819 $against = explode( DIRECTORY_SEPARATOR, $from );
1820
1821 if ( $pieces[0] !== $against[0] ) {
1822 // Non-matching Windows drive letters?
1823 // Return a full path.
1824 return $path;
1825 }
1826
1827 // Trim off common prefix
1828 while ( count( $pieces ) && count( $against )
1829 && $pieces[0] == $against[0] ) {
1830 array_shift( $pieces );
1831 array_shift( $against );
1832 }
1833
1834 // relative dots to bump us to the parent
1835 while ( count( $against ) ) {
1836 array_unshift( $pieces, '..' );
1837 array_shift( $against );
1838 }
1839
1840 $pieces[] = wfBaseName( $path );
1841
1842 return implode( DIRECTORY_SEPARATOR, $pieces );
1843}
1844
1882function wfGetDB( $db, $groups = [], $wiki = false ) {
1883 wfDeprecated( __FUNCTION__, '1.39' );
1884
1885 if ( $wiki === false ) {
1886 return MediaWikiServices::getInstance()
1887 ->getDBLoadBalancer()
1888 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1889 } else {
1890 return MediaWikiServices::getInstance()
1891 ->getDBLoadBalancerFactory()
1892 ->getMainLB( $wiki )
1893 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1894 }
1895}
1896
1906function wfScript( $script = 'index' ) {
1908 if ( $script === 'index' ) {
1909 return $wgScript;
1910 } elseif ( $script === 'load' ) {
1911 return $wgLoadScript;
1912 } else {
1913 return "{$wgScriptPath}/{$script}.php";
1914 }
1915}
1916
1924function wfBoolToStr( $value ) {
1925 return $value ? 'true' : 'false';
1926}
1927
1933function wfGetNull() {
1934 return wfIsWindows() ? 'NUL' : '/dev/null';
1935}
1936
1946 global $wgIllegalFileChars;
1947 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1948 $name = preg_replace(
1949 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1950 '-',
1951 $name
1952 );
1953 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1954 $name = wfBaseName( $name );
1955 return $name;
1956}
1957
1964function wfMemoryLimit( $newLimit ) {
1965 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1966 // If the INI config is already unlimited, there is nothing larger
1967 if ( $oldLimit != -1 ) {
1968 $newLimit = wfShorthandToInteger( (string)$newLimit );
1969 if ( $newLimit == -1 ) {
1970 wfDebug( "Removing PHP's memory limit" );
1971 AtEase::suppressWarnings();
1972 ini_set( 'memory_limit', $newLimit );
1973 AtEase::restoreWarnings();
1974 } elseif ( $newLimit > $oldLimit ) {
1975 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1976 AtEase::suppressWarnings();
1977 ini_set( 'memory_limit', $newLimit );
1978 AtEase::restoreWarnings();
1979 }
1980 }
1981}
1982
1991
1992 $timeout = RequestTimeout::singleton();
1993 $timeLimit = $timeout->getWallTimeLimit();
1994 if ( $timeLimit !== INF ) {
1995 // RequestTimeout library is active
1996 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1997 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1998 }
1999 } else {
2000 // Fallback case, likely $wgRequestTimeLimit === null
2001 $timeLimit = (int)ini_get( 'max_execution_time' );
2002 // Note that CLI scripts use 0
2003 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2004 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2005 }
2006 }
2007 ignore_user_abort( true ); // ignore client disconnects
2008
2009 return $timeLimit;
2010}
2011
2019function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2020 $string = trim( $string ?? '' );
2021 if ( $string === '' ) {
2022 return $default;
2023 }
2024 $last = $string[strlen( $string ) - 1];
2025 $val = intval( $string );
2026 switch ( $last ) {
2027 case 'g':
2028 case 'G':
2029 $val *= 1024;
2030 // break intentionally missing
2031 case 'm':
2032 case 'M':
2033 $val *= 1024;
2034 // break intentionally missing
2035 case 'k':
2036 case 'K':
2037 $val *= 1024;
2038 }
2039
2040 return $val;
2041}
2042
2058function wfUnpack( $format, $data, $length = false ) {
2059 wfDeprecated( __FUNCTION__, '1.42' );
2060 try {
2061 return StringUtils::unpack( (string)$format, (string)$data, $length );
2062 } catch ( UnpackFailedException $e ) {
2063 throw new MWException( $e->getMessage(), 0, $e );
2064 }
2065}
2066
2074function wfIsInfinity( $str ) {
2075 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2076 return in_array( $str, ExpiryDef::INFINITY_VALS );
2077}
2078
2093function wfThumbIsStandard( File $file, array $params ) {
2095
2096 $multipliers = [ 1 ];
2097 if ( $wgResponsiveImages ) {
2098 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2099 // @see Linker::processResponsiveImages
2100 $multipliers[] = 1.5;
2101 $multipliers[] = 2;
2102 }
2103
2104 $handler = $file->getHandler();
2105 if ( !$handler || !isset( $params['width'] ) ) {
2106 return false;
2107 }
2108
2109 $basicParams = [];
2110 if ( isset( $params['page'] ) ) {
2111 $basicParams['page'] = $params['page'];
2112 }
2113
2114 $thumbLimits = [];
2115 $imageLimits = [];
2116 // Expand limits to account for multipliers
2117 foreach ( $multipliers as $multiplier ) {
2118 $thumbLimits = array_merge( $thumbLimits, array_map(
2119 static function ( $width ) use ( $multiplier ) {
2120 return round( $width * $multiplier );
2121 }, $wgThumbLimits )
2122 );
2123 $imageLimits = array_merge( $imageLimits, array_map(
2124 static function ( $pair ) use ( $multiplier ) {
2125 return [
2126 round( $pair[0] * $multiplier ),
2127 round( $pair[1] * $multiplier ),
2128 ];
2129 }, $wgImageLimits )
2130 );
2131 }
2132
2133 // Check if the width matches one of $wgThumbLimits
2134 if ( in_array( $params['width'], $thumbLimits ) ) {
2135 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2136 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2137 $handler->normaliseParams( $file, $normalParams );
2138 } else {
2139 // If not, then check if the width matches one of $wgImageLimits
2140 $match = false;
2141 foreach ( $imageLimits as $pair ) {
2142 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2143 // Decide whether the thumbnail should be scaled on width or height.
2144 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2145 $handler->normaliseParams( $file, $normalParams );
2146 // Check if this standard thumbnail size maps to the given width
2147 if ( $normalParams['width'] == $params['width'] ) {
2148 $match = true;
2149 break;
2150 }
2151 }
2152 if ( !$match ) {
2153 return false; // not standard for description pages
2154 }
2155 }
2156
2157 // Check that the given values for non-page, non-width, params are just defaults
2158 foreach ( $params as $key => $value ) {
2159 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2160 return false;
2161 }
2162 }
2163
2164 return true;
2165}
2166
2179function wfArrayPlus2d( array $baseArray, array $newValues ) {
2180 // First merge items that are in both arrays
2181 foreach ( $baseArray as $name => &$groupVal ) {
2182 if ( isset( $newValues[$name] ) ) {
2183 $groupVal += $newValues[$name];
2184 }
2185 }
2186 // Now add items that didn't exist yet
2187 $baseArray += $newValues;
2188
2189 return $baseArray;
2190}
wfIsWindows()
Check if the operating system is Windows.
const PROTO_CURRENT
Definition Defines.php:208
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
wfVarDump( $var)
A wrapper around the PHP function var_export().
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfTempDir()
Tries to get the system directory for temporary files.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg()
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
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.
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
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:417
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
Definition Setup.php:538
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgOut
Definition Setup.php:538
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:1549
MediaWiki exception.
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:158
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Executes shell commands.
Definition Shell.php:46
Stub object for the user language.
Represents a title within MediaWiki.
Definition Title.php:79
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
$wgLanguageCode
Config variable stub for the LanguageCode setting, for use by phpdoc and IDEs.
$wgScript
Config variable stub for the Script setting, for use by phpdoc and IDEs.
$wgInternalServer
Config variable stub for the InternalServer setting, for use by phpdoc and IDEs.
$wgThumbLimits
Config variable stub for the ThumbLimits setting, for use by phpdoc and IDEs.
$wgDebugLogPrefix
Config variable stub for the DebugLogPrefix setting, for use by phpdoc and IDEs.
$wgPhpCli
Config variable stub for the PhpCli setting, for use by phpdoc and IDEs.
$wgOverrideHostname
Config variable stub for the OverrideHostname setting, for use by phpdoc and IDEs.
$wgImageLimits
Config variable stub for the ImageLimits setting, for use by phpdoc and IDEs.
$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