MediaWiki master
GlobalFunctions.php
Go to the documentation of this file.
1<?php
34use Wikimedia\AtEase\AtEase;
36use Wikimedia\RequestTimeout\RequestTimeout;
37
48function wfLoadExtension( $ext, $path = null ) {
49 if ( !$path ) {
51 $path = "$wgExtensionDirectory/$ext/extension.json";
52 }
53 ExtensionRegistry::getInstance()->queue( $path );
54}
55
69function wfLoadExtensions( array $exts ) {
71 $registry = ExtensionRegistry::getInstance();
72 foreach ( $exts as $ext ) {
73 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
74 }
75}
76
85function wfLoadSkin( $skin, $path = null ) {
86 if ( !$path ) {
87 global $wgStyleDirectory;
88 $path = "$wgStyleDirectory/$skin/skin.json";
89 }
90 ExtensionRegistry::getInstance()->queue( $path );
91}
92
100function wfLoadSkins( array $skins ) {
101 global $wgStyleDirectory;
102 $registry = ExtensionRegistry::getInstance();
103 foreach ( $skins as $skin ) {
104 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
105 }
106}
107
114function wfArrayDiff2( $arr1, $arr2 ) {
119 $comparator = static function ( $a, $b ): int {
120 if ( is_string( $a ) && is_string( $b ) ) {
121 return strcmp( $a, $b );
122 }
123 if ( !is_array( $a ) && !is_array( $b ) ) {
124 throw new InvalidArgumentException(
125 'This function assumes that array elements are all strings or all arrays'
126 );
127 }
128 if ( count( $a ) !== count( $b ) ) {
129 return count( $a ) <=> count( $b );
130 } else {
131 reset( $a );
132 reset( $b );
133 while ( key( $a ) !== null && key( $b ) !== null ) {
134 $valueA = current( $a );
135 $valueB = current( $b );
136 $cmp = strcmp( $valueA, $valueB );
137 if ( $cmp !== 0 ) {
138 return $cmp;
139 }
140 next( $a );
141 next( $b );
142 }
143 return 0;
144 }
145 };
146 return array_udiff( $arr1, $arr2, $comparator );
147}
148
168function wfMergeErrorArrays( ...$args ) {
169 $out = [];
170 foreach ( $args as $errors ) {
171 foreach ( $errors as $params ) {
172 $originalParams = $params;
173 if ( $params[0] instanceof MessageSpecifier ) {
174 $params = [ $params[0]->getKey(), ...$params[0]->getParams() ];
175 }
176 # @todo FIXME: Sometimes get nested arrays for $params,
177 # which leads to E_NOTICEs
178 $spec = implode( "\t", $params );
179 $out[$spec] = $originalParams;
180 }
181 }
182 return array_values( $out );
183}
184
194function wfArrayInsertAfter( array $array, array $insert, $after ) {
195 // Find the offset of the element to insert after.
196 $keys = array_keys( $array );
197 $offsetByKey = array_flip( $keys );
198
199 if ( !\array_key_exists( $after, $offsetByKey ) ) {
200 return $array;
201 }
202 $offset = $offsetByKey[$after];
203
204 // Insert at the specified offset
205 $before = array_slice( $array, 0, $offset + 1, true );
206 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
207
208 $output = $before + $insert + $after;
209
210 return $output;
211}
212
221function wfObjectToArray( $objOrArray, $recursive = true ) {
222 $array = [];
223 if ( is_object( $objOrArray ) ) {
224 $objOrArray = get_object_vars( $objOrArray );
225 }
226 foreach ( $objOrArray as $key => $value ) {
227 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
228 $value = wfObjectToArray( $value );
229 }
230
231 $array[$key] = $value;
232 }
233
234 return $array;
235}
236
247function wfRandom() {
248 // The maximum random value is "only" 2^31-1, so get two random
249 // values to reduce the chance of dupes
250 $max = mt_getrandmax() + 1;
251 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
252 return $rand;
253}
254
265function wfRandomString( $length = 32 ) {
266 $str = '';
267 for ( $n = 0; $n < $length; $n += 7 ) {
268 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
269 }
270 return substr( $str, 0, $length );
271}
272
300function wfUrlencode( $s ) {
301 static $needle;
302
303 if ( $s === null ) {
304 // Reset $needle for testing.
305 $needle = null;
306 return '';
307 }
308
309 if ( $needle === null ) {
310 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
311 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
312 !str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
313 ) {
314 $needle[] = '%3A';
315 }
316 }
317
318 $s = urlencode( $s );
319 $s = str_ireplace(
320 $needle,
321 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
322 $s
323 );
324
325 return $s;
326}
327
338function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
339 if ( $array2 !== null ) {
340 $array1 += $array2;
341 }
342
343 $cgi = '';
344 foreach ( $array1 as $key => $value ) {
345 if ( $value !== null && $value !== false ) {
346 if ( $cgi != '' ) {
347 $cgi .= '&';
348 }
349 if ( $prefix !== '' ) {
350 $key = $prefix . "[$key]";
351 }
352 if ( is_array( $value ) ) {
353 $firstTime = true;
354 foreach ( $value as $k => $v ) {
355 $cgi .= $firstTime ? '' : '&';
356 if ( is_array( $v ) ) {
357 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
358 } else {
359 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
360 }
361 $firstTime = false;
362 }
363 } else {
364 if ( is_object( $value ) ) {
365 $value = $value->__toString();
366 }
367 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
368 }
369 }
370 }
371 return $cgi;
372}
373
383function wfCgiToArray( $query ) {
384 if ( isset( $query[0] ) && $query[0] == '?' ) {
385 $query = substr( $query, 1 );
386 }
387 $bits = explode( '&', $query );
388 $ret = [];
389 foreach ( $bits as $bit ) {
390 if ( $bit === '' ) {
391 continue;
392 }
393 if ( strpos( $bit, '=' ) === false ) {
394 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
395 $key = $bit;
396 $value = '';
397 } else {
398 [ $key, $value ] = explode( '=', $bit );
399 }
400 $key = urldecode( $key );
401 $value = urldecode( $value );
402 if ( strpos( $key, '[' ) !== false ) {
403 $keys = array_reverse( explode( '[', $key ) );
404 $key = array_pop( $keys );
405 $temp = $value;
406 foreach ( $keys as $k ) {
407 $k = substr( $k, 0, -1 );
408 $temp = [ $k => $temp ];
409 }
410 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
411 $ret[$key] = array_merge( $ret[$key], $temp );
412 } else {
413 $ret[$key] = $temp;
414 }
415 } else {
416 $ret[$key] = $value;
417 }
418 }
419 return $ret;
420}
421
430function wfAppendQuery( $url, $query ) {
431 if ( is_array( $query ) ) {
432 $query = wfArrayToCgi( $query );
433 }
434 if ( $query != '' ) {
435 // Remove the fragment, if there is one
436 $fragment = false;
437 $hashPos = strpos( $url, '#' );
438 if ( $hashPos !== false ) {
439 $fragment = substr( $url, $hashPos );
440 $url = substr( $url, 0, $hashPos );
441 }
442
443 // Add parameter
444 if ( strpos( $url, '?' ) === false ) {
445 $url .= '?';
446 } else {
447 $url .= '&';
448 }
449 $url .= $query;
450
451 // Put the fragment back
452 if ( $fragment !== false ) {
453 $url .= $fragment;
454 }
455 }
456 return $url;
457}
458
467
468 if ( MediaWikiServices::hasInstance() ) {
469 $services = MediaWikiServices::getInstance();
470 if ( $services->hasService( 'UrlUtils' ) ) {
471 return $services->getUrlUtils();
472 }
473 }
474
475 return new UrlUtils( [
476 // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old
477 // implementations implicitly converted it to an empty string (presumably by mistake).
478 // Preserve the old behavior for compatibility.
479 UrlUtils::SERVER => $wgServer ?? '',
480 UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '',
481 UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '',
482 UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol()
483 : WebRequest::detectProtocol(),
484 UrlUtils::HTTPS_PORT => $wgHttpsPort,
485 UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols,
486 ] );
487}
488
516function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
517 return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false;
518}
519
529function wfGetServerUrl( $proto ) {
530 return wfGetUrlUtils()->getServer( $proto ) ?? '';
531}
532
545function wfAssembleUrl( $urlParts ) {
546 return UrlUtils::assemble( (array)$urlParts );
547}
548
559function wfRemoveDotSegments( $urlPath ) {
560 return UrlUtils::removeDotSegments( (string)$urlPath );
561}
562
571function wfUrlProtocols( $includeProtocolRelative = true ) {
572 return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() :
573 wfGetUrlUtils()->validAbsoluteProtocols();
574}
575
584 return wfGetUrlUtils()->validAbsoluteProtocols();
585}
586
613function wfParseUrl( $url ) {
614 return wfGetUrlUtils()->parse( (string)$url ) ?? false;
615}
616
626function wfExpandIRI( $url ) {
627 return wfGetUrlUtils()->expandIRI( (string)$url ) ?? '';
628}
629
638function wfMatchesDomainList( $url, $domains ) {
639 return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains );
640}
641
662function wfDebug( $text, $dest = 'all', array $context = [] ) {
664
665 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
666 return;
667 }
668
669 $text = trim( $text );
670
671 if ( $wgDebugLogPrefix !== '' ) {
672 $context['prefix'] = $wgDebugLogPrefix;
673 }
674 $context['private'] = ( $dest === false || $dest === 'private' );
675
676 $logger = LoggerFactory::getInstance( 'wfDebug' );
677 $logger->debug( $text, $context );
678}
679
685 static $cache;
686 if ( $cache !== null ) {
687 return $cache;
688 }
689 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
690 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
691 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
692 || MW_ENTRY_POINT === 'load'
693 ) {
694 $cache = true;
695 } else {
696 $cache = false;
697 }
698 return $cache;
699}
700
726function wfDebugLog(
727 $logGroup, $text, $dest = 'all', array $context = []
728) {
729 $text = trim( $text );
730
731 $logger = LoggerFactory::getInstance( $logGroup );
732 $context['private'] = ( $dest === false || $dest === 'private' );
733 $logger->info( $text, $context );
734}
735
744function wfLogDBError( $text, array $context = [] ) {
745 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
746 $logger->error( trim( $text ), $context );
747}
748
765function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
766 if ( !is_string( $version ) && $version !== false ) {
767 throw new InvalidArgumentException(
768 "MediaWiki version must either be a string or false. " .
769 "Example valid version: '1.33'"
770 );
771 }
772
773 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
774}
775
796function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
797 MWDebug::deprecatedMsg( $msg, $version, $component,
798 $callerOffset === false ? false : $callerOffset + 1 );
799}
800
811function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
812 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
813}
814
824function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
825 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
826}
827
844function wfGetLangObj( $langcode = false ) {
845 wfDeprecated( __FUNCTION__, '1.41' );
846 # Identify which language to get or create a language object for.
847 # Using is_object here due to Stub objects.
848 if ( is_object( $langcode ) ) {
849 # Great, we already have the object (hopefully)!
850 return $langcode;
851 }
852
853 global $wgLanguageCode;
854 $services = MediaWikiServices::getInstance();
855 if ( $langcode === true || $langcode === $wgLanguageCode ) {
856 # $langcode is the language code of the wikis content language object.
857 # or it is a boolean and value is true
858 return $services->getContentLanguage();
859 }
860
861 global $wgLang;
862 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
863 # $langcode is the language code of user language object.
864 # or it was a boolean and value is false
865 return $wgLang;
866 }
867
868 $languageNames = $services->getLanguageNameUtils()->getLanguageNames();
869 // FIXME: Can we use isSupportedLanguage here?
870 if ( isset( $languageNames[$langcode] ) ) {
871 # $langcode corresponds to a valid language.
872 return $services->getLanguageFactory()->getLanguage( $langcode );
873 }
874
875 # $langcode is a string, but not a valid language code; use content language.
876 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
877 return $services->getContentLanguage();
878}
879
901function wfMessage( $key, ...$params ) {
902 if ( is_array( $key ) ) {
903 // Fallback keys are not allowed in message specifiers
904 $message = wfMessageFallback( ...$key );
905 } else {
906 $message = Message::newFromSpecifier( $key );
907 }
908
909 // We call Message::params() to reduce code duplication
910 if ( $params ) {
911 $message->params( ...$params );
912 }
913
914 return $message;
915}
916
929function wfMessageFallback( ...$keys ) {
930 return Message::newFallbackSequence( ...$keys );
931}
932
941function wfMsgReplaceArgs( $message, $args ) {
942 # Fix windows line-endings
943 # Some messages are split with explode("\n", $msg)
944 $message = str_replace( "\r", '', $message );
945
946 // Replace arguments
947 if ( is_array( $args ) && $args ) {
948 if ( is_array( $args[0] ) ) {
949 $args = array_values( $args[0] );
950 }
951 $replacementKeys = [];
952 foreach ( $args as $n => $param ) {
953 $replacementKeys['$' . ( $n + 1 )] = $param;
954 }
955 $message = strtr( $message, $replacementKeys );
956 }
957
958 return $message;
959}
960
969function wfHostname() {
970 // Hostname overriding
971 global $wgOverrideHostname;
972 if ( $wgOverrideHostname !== false ) {
973 return $wgOverrideHostname;
974 }
975
976 return php_uname( 'n' ) ?: 'unknown';
977}
978
989function wfDebugBacktrace( $limit = 0 ) {
990 static $disabled = null;
991
992 if ( $disabled === null ) {
993 $disabled = !function_exists( 'debug_backtrace' );
994 if ( $disabled ) {
995 wfDebug( "debug_backtrace() is disabled" );
996 }
997 }
998 if ( $disabled ) {
999 return [];
1000 }
1001
1002 if ( $limit ) {
1003 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1004 } else {
1005 return array_slice( debug_backtrace(), 1 );
1006 }
1007}
1008
1017function wfBacktrace( $raw = null ) {
1018 $raw ??= MW_ENTRY_POINT === 'cli';
1019 if ( $raw ) {
1020 $frameFormat = "%s line %s calls %s()\n";
1021 $traceFormat = "%s";
1022 } else {
1023 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1024 $traceFormat = "<ul>\n%s</ul>\n";
1025 }
1026
1027 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1028 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1029 $line = $frame['line'] ?? '-';
1030 $call = $frame['function'];
1031 if ( !empty( $frame['class'] ) ) {
1032 $call = $frame['class'] . $frame['type'] . $call;
1033 }
1034 return sprintf( $frameFormat, $file, $line, $call );
1035 }, wfDebugBacktrace() );
1036
1037 return sprintf( $traceFormat, implode( '', $frames ) );
1038}
1039
1049function wfGetCaller( $level = 2 ) {
1050 $backtrace = wfDebugBacktrace( $level + 1 );
1051 if ( isset( $backtrace[$level] ) ) {
1052 return wfFormatStackFrame( $backtrace[$level] );
1053 } else {
1054 return 'unknown';
1055 }
1056}
1057
1065function wfGetAllCallers( $limit = 3 ) {
1066 $trace = array_reverse( wfDebugBacktrace() );
1067 if ( !$limit || $limit > count( $trace ) - 1 ) {
1068 $limit = count( $trace ) - 1;
1069 }
1070 $trace = array_slice( $trace, -$limit - 1, $limit );
1071 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1072}
1073
1080function wfFormatStackFrame( $frame ) {
1081 if ( !isset( $frame['function'] ) ) {
1082 return 'NO_FUNCTION_GIVEN';
1083 }
1084 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1085 $frame['class'] . $frame['type'] . $frame['function'] :
1086 $frame['function'];
1087}
1088
1098function wfClientAcceptsGzip( $force = false ) {
1099 static $result = null;
1100 if ( $result === null || $force ) {
1101 $result = false;
1102 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1103 # @todo FIXME: We may want to disallow some broken browsers
1104 $m = [];
1105 if ( preg_match(
1106 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1107 $_SERVER['HTTP_ACCEPT_ENCODING'],
1108 $m
1109 )
1110 ) {
1111 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1112 return $result;
1113 }
1114 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1115 $result = true;
1116 }
1117 }
1118 }
1119 return $result;
1120}
1121
1132function wfEscapeWikiText( $input ): string {
1133 global $wgEnableMagicLinks;
1134 static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
1135 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1136 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1137 // in those situations
1138 $repl = [
1139 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1140 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1141 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1142 ';' => '&#59;', // a token inside language converter brackets
1143 '!!' => '&#33;!', // a token inside table context
1144 "\n!" => "\n&#33;", "\r!" => "\r&#33;", // a token inside table context
1145 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1146 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1147 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1148 "\n " => "\n&#32;", "\r " => "\r&#32;",
1149 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1150 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1151 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1152 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1153 '__' => '_&#95;', '://' => '&#58;//',
1154 '~~~' => '~~&#126;', // protect from PST, just to be safe(r)
1155 ];
1156
1157 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1158 // We have to catch everything "\s" matches in PCRE
1159 foreach ( $magicLinks as $magic ) {
1160 $repl["$magic "] = "$magic&#32;";
1161 $repl["$magic\t"] = "$magic&#9;";
1162 $repl["$magic\r"] = "$magic&#13;";
1163 $repl["$magic\n"] = "$magic&#10;";
1164 $repl["$magic\f"] = "$magic&#12;";
1165 }
1166 // Additionally escape the following characters at the beginning of the
1167 // string, in case they merge to form tokens when spliced into a
1168 // string. Tokens like -{ {{ [[ {| etc are already escaped because
1169 // the second character is escaped above, but the following tokens
1170 // are handled here: |+ |- __FOO__ ~~~
1171 $repl3 = [
1172 '+' => '&#43;', '-' => '&#45;', '_' => '&#95;', '~' => '&#126;',
1173 ];
1174 // Similarly, protect the following characters at the end of the
1175 // string, which could turn form the start of `__FOO__` or `~~~~`
1176 // A trailing newline could also form the unintended start of a
1177 // paragraph break if it is glued to a newline in the following
1178 // context.
1179 $repl4 = [
1180 '_' => '&#95;', '~' => '&#126;',
1181 "\n" => "&#10;", "\r" => "&#13;",
1182 "\t" => "&#9;", // "\n\t\n" is treated like "\n\n"
1183 ];
1184
1185 // And handle protocols that don't use "://"
1186 global $wgUrlProtocols;
1187 $repl2 = [];
1188 foreach ( $wgUrlProtocols as $prot ) {
1189 if ( substr( $prot, -1 ) === ':' ) {
1190 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1191 }
1192 }
1193 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1194 }
1195 // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
1196 '@phan-var string $repl2';
1197 '@phan-var string $repl3';
1198 '@phan-var string $repl4';
1199 // This will also stringify input in case it's not a string
1200 $text = substr( strtr( "\n$input", $repl ), 1 );
1201 if ( $text === '' ) {
1202 return $text;
1203 }
1204 $first = strtr( $text[0], $repl3 ); // protect first character
1205 if ( strlen( $text ) > 1 ) {
1206 $text = $first . substr( $text, 1, -1 ) .
1207 strtr( substr( $text, -1 ), $repl4 ); // protect last character
1208 } else {
1209 // special case for single-character strings
1210 $text = strtr( $first, $repl4 ); // protect last character
1211 }
1212 $text = preg_replace( $repl2, '$1&#58;', $text );
1213 return $text;
1214}
1215
1226function wfSetVar( &$dest, $source, $force = false ) {
1227 $temp = $dest;
1228 if ( $source !== null || $force ) {
1229 $dest = $source;
1230 }
1231 return $temp;
1232}
1233
1243function wfSetBit( &$dest, $bit, $state = true ) {
1244 $temp = (bool)( $dest & $bit );
1245 if ( $state !== null ) {
1246 if ( $state ) {
1247 $dest |= $bit;
1248 } else {
1249 $dest &= ~$bit;
1250 }
1251 }
1252 return $temp;
1253}
1254
1261function wfVarDump( $var ) {
1262 global $wgOut;
1263 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1264 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1265 print $s;
1266 } else {
1267 $wgOut->addHTML( $s );
1268 }
1269}
1270
1278function wfHttpError( $code, $label, $desc ) {
1279 global $wgOut;
1280 HttpStatus::header( $code );
1281 if ( $wgOut ) {
1282 $wgOut->disable();
1283 $wgOut->sendCacheControl();
1284 }
1285
1286 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
1287 header( 'Content-type: text/html; charset=utf-8' );
1288 ob_start();
1289 print '<!DOCTYPE html>' .
1290 '<html><head><title>' .
1291 htmlspecialchars( $label ) .
1292 '</title></head><body><h1>' .
1293 htmlspecialchars( $label ) .
1294 '</h1><p>' .
1295 nl2br( htmlspecialchars( $desc ) ) .
1296 "</p></body></html>\n";
1297 header( 'Content-Length: ' . ob_get_length() );
1298 ob_end_flush();
1299}
1300
1321function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1322 while ( $status = ob_get_status() ) {
1323 if ( isset( $status['flags'] ) ) {
1324 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1325 $deleteable = ( $status['flags'] & $flags ) === $flags;
1326 } elseif ( isset( $status['del'] ) ) {
1327 $deleteable = $status['del'];
1328 } else {
1329 // Guess that any PHP-internal setting can't be removed.
1330 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1331 }
1332 if ( !$deleteable ) {
1333 // Give up, and hope the result doesn't break
1334 // output behavior.
1335 break;
1336 }
1337 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1338 // Unit testing barrier to prevent this function from breaking PHPUnit.
1339 break;
1340 }
1341 if ( !ob_end_clean() ) {
1342 // Could not remove output buffer handler; abort now
1343 // to avoid getting in some kind of infinite loop.
1344 break;
1345 }
1346 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1347 // Reset the 'Content-Encoding' field set by this handler
1348 // so we can start fresh.
1349 header_remove( 'Content-Encoding' );
1350 break;
1351 }
1352 }
1353}
1354
1365function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1366 $ret = MWTimestamp::convert( $outputtype, $ts );
1367 if ( $ret === false ) {
1368 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1369 }
1370 return $ret;
1371}
1372
1381function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1382 if ( $ts === null ) {
1383 return null;
1384 } else {
1385 return wfTimestamp( $outputtype, $ts );
1386 }
1387}
1388
1394function wfTimestampNow() {
1395 return MWTimestamp::now( TS_MW );
1396}
1397
1409function wfTempDir() {
1410 global $wgTmpDirectory;
1411
1412 if ( $wgTmpDirectory !== false ) {
1413 return $wgTmpDirectory;
1414 }
1415
1416 return TempFSFile::getUsableTempDirectory();
1417}
1418
1427function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1428 global $wgDirectoryMode;
1429
1430 if ( FileBackend::isStoragePath( $dir ) ) {
1431 throw new LogicException( __FUNCTION__ . " given storage path '$dir'." );
1432 }
1433 if ( $caller !== null ) {
1434 wfDebug( "$caller: called wfMkdirParents($dir)" );
1435 }
1436 if ( strval( $dir ) === '' ) {
1437 return true;
1438 }
1439
1440 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1441 $mode ??= $wgDirectoryMode;
1442
1443 // Turn off the normal warning, we're doing our own below
1444 // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis.
1445 //
1446 // Repeat existence check if creation failed so that we silently recover in case of
1447 // a race condition where another request created it since the first check.
1448 //
1449 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1450 $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir );
1451 if ( !$ok ) {
1452 trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING );
1453 }
1454
1455 return $ok;
1456}
1457
1463function wfRecursiveRemoveDir( $dir ) {
1464 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1465 if ( is_dir( $dir ) ) {
1466 $objects = scandir( $dir );
1467 foreach ( $objects as $object ) {
1468 if ( $object != "." && $object != ".." ) {
1469 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1470 wfRecursiveRemoveDir( $dir . '/' . $object );
1471 } else {
1472 unlink( $dir . '/' . $object );
1473 }
1474 }
1475 }
1476 rmdir( $dir );
1477 }
1478}
1479
1486function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1487 $accForFormat = $acc >= 0 ? $acc : 0;
1488 $ret = sprintf( "%.{$accForFormat}f", $nr );
1489 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1490}
1491
1515function wfIniGetBool( $setting ) {
1516 return wfStringToBool( ini_get( $setting ) );
1517}
1518
1531function wfStringToBool( $val ) {
1532 $val = strtolower( $val );
1533 // 'on' and 'true' can't have whitespace around them, but '1' can.
1534 return $val == 'on'
1535 || $val == 'true'
1536 || $val == 'yes'
1537 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1538}
1539
1553function wfEscapeShellArg( ...$args ) {
1554 return Shell::escape( ...$args );
1555}
1556
1581function wfShellExec( $cmd, &$retval = null, $environ = [],
1582 $limits = [], $options = []
1583) {
1584 if ( Shell::isDisabled() ) {
1585 $retval = 1;
1586 // Backwards compatibility be upon us...
1587 return 'Unable to run external programs, proc_open() is disabled.';
1588 }
1589
1590 if ( is_array( $cmd ) ) {
1591 $cmd = Shell::escape( $cmd );
1592 }
1593
1594 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1595 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1596
1597 try {
1598 $result = Shell::command( [] )
1599 ->unsafeParams( (array)$cmd )
1600 ->environment( $environ )
1601 ->limits( $limits )
1602 ->includeStderr( $includeStderr )
1603 ->profileMethod( $profileMethod )
1604 // For b/c
1605 ->restrict( Shell::RESTRICT_NONE )
1606 ->execute();
1607 } catch ( ProcOpenError $ex ) {
1608 $retval = -1;
1609 return '';
1610 }
1611
1612 $retval = $result->getExitCode();
1613
1614 return $result->getStdout();
1615}
1616
1634function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1635 return wfShellExec( $cmd, $retval, $environ, $limits,
1636 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1637}
1638
1654function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1655 global $wgPhpCli;
1656 // Give site config file a chance to run the script in a wrapper.
1657 // The caller may likely want to call wfBasename() on $script.
1658 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1659 ->onWfShellWikiCmd( $script, $parameters, $options );
1660 $cmd = [ $options['php'] ?? $wgPhpCli ];
1661 if ( isset( $options['wrapper'] ) ) {
1662 $cmd[] = $options['wrapper'];
1663 }
1664 $cmd[] = $script;
1665 // Escape each parameter for shell
1666 return Shell::escape( array_merge( $cmd, $parameters ) );
1667}
1668
1685function wfMerge(
1686 string $old,
1687 string $mine,
1688 string $yours,
1689 ?string &$simplisticMergeAttempt,
1690 string &$mergeLeftovers = null
1691): bool {
1692 global $wgDiff3;
1693
1694 # This check may also protect against code injection in
1695 # case of broken installations.
1696 AtEase::suppressWarnings();
1697 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1698 AtEase::restoreWarnings();
1699
1700 if ( !$haveDiff3 ) {
1701 wfDebug( "diff3 not found" );
1702 return false;
1703 }
1704
1705 # Make temporary files
1706 $td = wfTempDir();
1707 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1708 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1709 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1710
1711 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1712 # a newline character. To avoid this, we normalize the trailing whitespace before
1713 # creating the diff.
1714
1715 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1716 fclose( $oldtextFile );
1717 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1718 fclose( $mytextFile );
1719 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1720 fclose( $yourtextFile );
1721
1722 # Check for a conflict
1723 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1724 $oldtextName, $yourtextName );
1725 $handle = popen( $cmd, 'r' );
1726
1727 $mergeLeftovers = '';
1728 do {
1729 $data = fread( $handle, 8192 );
1730 if ( strlen( $data ) == 0 ) {
1731 break;
1732 }
1733 $mergeLeftovers .= $data;
1734 } while ( true );
1735 pclose( $handle );
1736
1737 $conflict = $mergeLeftovers !== '';
1738
1739 # Merge differences automatically where possible, preferring "my" text for conflicts.
1740 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1741 $oldtextName, $yourtextName );
1742 $handle = popen( $cmd, 'r' );
1743 $simplisticMergeAttempt = '';
1744 do {
1745 $data = fread( $handle, 8192 );
1746 if ( strlen( $data ) == 0 ) {
1747 break;
1748 }
1749 $simplisticMergeAttempt .= $data;
1750 } while ( true );
1751 pclose( $handle );
1752 unlink( $mytextName );
1753 unlink( $oldtextName );
1754 unlink( $yourtextName );
1755
1756 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1757 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1758 $conflict = true;
1759 }
1760 return !$conflict;
1761}
1762
1775function wfBaseName( $path, $suffix = '' ) {
1776 if ( $suffix == '' ) {
1777 $encSuffix = '';
1778 } else {
1779 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1780 }
1781
1782 $matches = [];
1783 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1784 return $matches[1];
1785 } else {
1786 return '';
1787 }
1788}
1789
1799function wfRelativePath( $path, $from ) {
1800 // Normalize mixed input on Windows...
1801 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1802 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1803
1804 // Trim trailing slashes -- fix for drive root
1805 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1806 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1807
1808 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1809 $against = explode( DIRECTORY_SEPARATOR, $from );
1810
1811 if ( $pieces[0] !== $against[0] ) {
1812 // Non-matching Windows drive letters?
1813 // Return a full path.
1814 return $path;
1815 }
1816
1817 // Trim off common prefix
1818 while ( count( $pieces ) && count( $against )
1819 && $pieces[0] == $against[0] ) {
1820 array_shift( $pieces );
1821 array_shift( $against );
1822 }
1823
1824 // relative dots to bump us to the parent
1825 while ( count( $against ) ) {
1826 array_unshift( $pieces, '..' );
1827 array_shift( $against );
1828 }
1829
1830 $pieces[] = wfBaseName( $path );
1831
1832 return implode( DIRECTORY_SEPARATOR, $pieces );
1833}
1834
1866function wfGetDB( $db, $groups = [], $wiki = false ) {
1867 if ( $wiki === false ) {
1868 return MediaWikiServices::getInstance()
1869 ->getDBLoadBalancer()
1870 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1871 } else {
1872 return MediaWikiServices::getInstance()
1873 ->getDBLoadBalancerFactory()
1874 ->getMainLB( $wiki )
1875 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
1876 }
1877}
1878
1888function wfScript( $script = 'index' ) {
1890 if ( $script === 'index' ) {
1891 return $wgScript;
1892 } elseif ( $script === 'load' ) {
1893 return $wgLoadScript;
1894 } else {
1895 return "{$wgScriptPath}/{$script}.php";
1896 }
1897}
1898
1906function wfBoolToStr( $value ) {
1907 return $value ? 'true' : 'false';
1908}
1909
1915function wfGetNull() {
1916 return wfIsWindows() ? 'NUL' : '/dev/null';
1917}
1918
1928 global $wgIllegalFileChars;
1929 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1930 $name = preg_replace(
1931 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1932 '-',
1933 $name
1934 );
1935 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1936 $name = wfBaseName( $name );
1937 return $name;
1938}
1939
1946function wfMemoryLimit( $newLimit ) {
1947 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1948 // If the INI config is already unlimited, there is nothing larger
1949 if ( $oldLimit != -1 ) {
1950 $newLimit = wfShorthandToInteger( (string)$newLimit );
1951 if ( $newLimit == -1 ) {
1952 wfDebug( "Removing PHP's memory limit" );
1953 AtEase::suppressWarnings();
1954 ini_set( 'memory_limit', $newLimit );
1955 AtEase::restoreWarnings();
1956 } elseif ( $newLimit > $oldLimit ) {
1957 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1958 AtEase::suppressWarnings();
1959 ini_set( 'memory_limit', $newLimit );
1960 AtEase::restoreWarnings();
1961 }
1962 }
1963}
1964
1973
1974 $timeout = RequestTimeout::singleton();
1975 $timeLimit = $timeout->getWallTimeLimit();
1976 if ( $timeLimit !== INF ) {
1977 // RequestTimeout library is active
1978 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1979 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1980 }
1981 } else {
1982 // Fallback case, likely $wgRequestTimeLimit === null
1983 $timeLimit = (int)ini_get( 'max_execution_time' );
1984 // Note that CLI scripts use 0
1985 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
1986 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1987 }
1988 }
1989 ignore_user_abort( true ); // ignore client disconnects
1990
1991 return $timeLimit;
1992}
1993
2001function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2002 $string = trim( $string ?? '' );
2003 if ( $string === '' ) {
2004 return $default;
2005 }
2006 $last = $string[strlen( $string ) - 1];
2007 $val = intval( $string );
2008 switch ( $last ) {
2009 case 'g':
2010 case 'G':
2011 $val *= 1024;
2012 // break intentionally missing
2013 case 'm':
2014 case 'M':
2015 $val *= 1024;
2016 // break intentionally missing
2017 case 'k':
2018 case 'K':
2019 $val *= 1024;
2020 }
2021
2022 return $val;
2023}
2024
2040function wfUnpack( $format, $data, $length = false ) {
2041 wfDeprecated( __FUNCTION__, '1.42' );
2042 try {
2043 return StringUtils::unpack( (string)$format, (string)$data, $length );
2044 } catch ( UnpackFailedException $e ) {
2045 throw new MWException( $e->getMessage(), 0, $e );
2046 }
2047}
2048
2056function wfIsInfinity( $str ) {
2057 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2058 return in_array( $str, ExpiryDef::INFINITY_VALS );
2059}
2060
2075function wfThumbIsStandard( File $file, array $params ) {
2077
2078 $multipliers = [ 1 ];
2079 if ( $wgResponsiveImages ) {
2080 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2081 // @see Linker::processResponsiveImages
2082 $multipliers[] = 1.5;
2083 $multipliers[] = 2;
2084 }
2085
2086 $handler = $file->getHandler();
2087 if ( !$handler || !isset( $params['width'] ) ) {
2088 return false;
2089 }
2090
2091 $basicParams = [];
2092 if ( isset( $params['page'] ) ) {
2093 $basicParams['page'] = $params['page'];
2094 }
2095
2096 $thumbLimits = [];
2097 $imageLimits = [];
2098 // Expand limits to account for multipliers
2099 foreach ( $multipliers as $multiplier ) {
2100 $thumbLimits = array_merge( $thumbLimits, array_map(
2101 static function ( $width ) use ( $multiplier ) {
2102 return round( $width * $multiplier );
2103 }, $wgThumbLimits )
2104 );
2105 $imageLimits = array_merge( $imageLimits, array_map(
2106 static function ( $pair ) use ( $multiplier ) {
2107 return [
2108 round( $pair[0] * $multiplier ),
2109 round( $pair[1] * $multiplier ),
2110 ];
2111 }, $wgImageLimits )
2112 );
2113 }
2114
2115 // Check if the width matches one of $wgThumbLimits
2116 if ( in_array( $params['width'], $thumbLimits ) ) {
2117 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2118 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2119 $handler->normaliseParams( $file, $normalParams );
2120 } else {
2121 // If not, then check if the width matches one of $wgImageLimits
2122 $match = false;
2123 foreach ( $imageLimits as $pair ) {
2124 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2125 // Decide whether the thumbnail should be scaled on width or height.
2126 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2127 $handler->normaliseParams( $file, $normalParams );
2128 // Check if this standard thumbnail size maps to the given width
2129 if ( $normalParams['width'] == $params['width'] ) {
2130 $match = true;
2131 break;
2132 }
2133 }
2134 if ( !$match ) {
2135 return false; // not standard for description pages
2136 }
2137 }
2138
2139 // Check that the given values for non-page, non-width, params are just defaults
2140 foreach ( $params as $key => $value ) {
2141 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2142 return false;
2143 }
2144 }
2145
2146 return true;
2147}
2148
2161function wfArrayPlus2d( array $baseArray, array $newValues ) {
2162 // First merge items that are in both arrays
2163 foreach ( $baseArray as $name => &$groupVal ) {
2164 if ( isset( $newValues[$name] ) ) {
2165 $groupVal += $newValues[$name];
2166 }
2167 }
2168 // Now add items that didn't exist yet
2169 $baseArray += $newValues;
2170
2171 return $baseArray;
2172}
wfIsWindows()
Check if the operating system is Windows.
const PROTO_CURRENT
Definition Defines.php:205
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:415
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli') $wgLang
Definition Setup.php:536
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli') $wgOut
Definition Setup.php:536
array $params
The job parameters.
const MW_ENTRY_POINT
Definition api.php:35
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:73
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1548
MediaWiki exception.
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 WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Executes shell commands.
Definition Shell.php:46
Stub object for the user language.
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
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