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