MediaWiki master
GlobalFunctions.php
Go to the documentation of this file.
1<?php
8
11use MediaWiki\FileRepo\File\File;
15use MediaWiki\Message\Message;
18use MediaWiki\Shell\Shell;
19use MediaWiki\Title\Title;
20use Wikimedia\ArrayUtils\ArrayUtils;
21use Wikimedia\FileBackend\FileBackend;
22use Wikimedia\FileBackend\FSFile\TempFSFile;
25use Wikimedia\Message\MessageParam;
26use Wikimedia\Message\MessageSpecifier;
28use Wikimedia\RequestTimeout\RequestTimeout;
29use Wikimedia\Timestamp\ConvertibleTimestamp;
30use Wikimedia\Timestamp\TimestampFormat as TS;
31
42function wfLoadExtension( $ext, $path = null ) {
43 if ( !$path ) {
45 $path = "$wgExtensionDirectory/$ext/extension.json";
46 }
47 ExtensionRegistry::getInstance()->queue( $path );
48}
49
63function wfLoadExtensions( array $exts ) {
65 $registry = ExtensionRegistry::getInstance();
66 foreach ( $exts as $ext ) {
67 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
68 }
69}
70
79function wfLoadSkin( $skin, $path = null ) {
80 if ( !$path ) {
81 global $wgStyleDirectory;
82 $path = "$wgStyleDirectory/$skin/skin.json";
83 }
84 ExtensionRegistry::getInstance()->queue( $path );
85}
86
94function wfLoadSkins( array $skins ) {
95 global $wgStyleDirectory;
96 $registry = ExtensionRegistry::getInstance();
97 foreach ( $skins as $skin ) {
98 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
99 }
100}
101
112function wfArrayInsertAfter( array $array, array $insert, $after ) {
113 wfDeprecated( __FUNCTION__, '1.46' );
114 return ArrayUtils::insertAfter( $array, $insert, $after );
115}
116
125function wfObjectToArray( $objOrArray, $recursive = true ) {
126 $array = [];
127 if ( is_object( $objOrArray ) ) {
128 $objOrArray = get_object_vars( $objOrArray );
129 }
130 foreach ( $objOrArray as $key => $value ) {
131 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
132 $value = wfObjectToArray( $value );
133 }
134
135 $array[$key] = $value;
136 }
137
138 return $array;
139}
140
151function wfRandom() {
152 // The maximum random value is "only" 2^31-1, so get two random
153 // values to reduce the chance of dupes
154 $max = mt_getrandmax() + 1;
155 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
156 return $rand;
157}
158
169function wfRandomString( $length = 32 ) {
170 $str = '';
171 for ( $n = 0; $n < $length; $n += 7 ) {
172 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
173 }
174 return substr( $str, 0, $length );
175}
176
201function wfUrlencode( $s ) {
202 return str_ireplace(
203 [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E', '%3A' ],
204 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
205 urlencode( $s )
206 );
207}
208
219function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
220 if ( $array2 !== null ) {
221 $array1 += $array2;
222 }
223
224 $cgi = '';
225 foreach ( $array1 as $key => $value ) {
226 if ( $value !== null && $value !== false ) {
227 if ( $cgi != '' ) {
228 $cgi .= '&';
229 }
230 if ( $prefix !== '' ) {
231 $key = $prefix . "[$key]";
232 }
233 if ( is_array( $value ) ) {
234 $firstTime = true;
235 foreach ( $value as $k => $v ) {
236 $cgi .= $firstTime ? '' : '&';
237 if ( is_array( $v ) ) {
238 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
239 } else {
240 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
241 }
242 $firstTime = false;
243 }
244 } else {
245 if ( is_object( $value ) ) {
246 $value = $value->__toString();
247 }
248 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
249 }
250 }
251 }
252 return $cgi;
253}
254
264function wfCgiToArray( $query ) {
265 if ( isset( $query[0] ) && $query[0] == '?' ) {
266 $query = substr( $query, 1 );
267 }
268 $bits = explode( '&', $query );
269 $ret = [];
270 foreach ( $bits as $bit ) {
271 if ( $bit === '' ) {
272 continue;
273 }
274 if ( !str_contains( $bit, '=' ) ) {
275 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
276 $key = $bit;
277 $value = '';
278 } else {
279 [ $key, $value ] = explode( '=', $bit );
280 }
281 $key = urldecode( $key );
282 $value = urldecode( $value );
283 if ( str_contains( $key, '[' ) ) {
284 $keys = array_reverse( explode( '[', $key ) );
285 $key = array_pop( $keys );
286 $temp = $value;
287 foreach ( $keys as $k ) {
288 $k = substr( $k, 0, -1 );
289 $temp = [ $k => $temp ];
290 }
291 if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
292 $ret[$key] = array_merge( $ret[$key], $temp );
293 } else {
294 $ret[$key] = $temp;
295 }
296 } else {
297 $ret[$key] = $value;
298 }
299 }
300 return $ret;
301}
302
311function wfAppendQuery( $url, $query ) {
312 if ( is_array( $query ) ) {
313 $query = wfArrayToCgi( $query );
314 }
315 if ( $query != '' ) {
316 // Remove the fragment, if there is one
317 $fragment = false;
318 $hashPos = strpos( $url, '#' );
319 if ( $hashPos !== false ) {
320 $fragment = substr( $url, $hashPos );
321 $url = substr( $url, 0, $hashPos );
322 }
323
324 // Add parameter
325 if ( !str_contains( $url, '?' ) ) {
326 $url .= '?';
327 } else {
328 $url .= '&';
329 }
330 $url .= $query;
331
332 // Put the fragment back
333 if ( $fragment !== false ) {
334 $url .= $fragment;
335 }
336 }
337 return $url;
338}
339
360function wfDebug( $text, $dest = 'all', array $context = [] ) {
362
363 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
364 return;
365 }
366
367 $text = trim( $text );
368
369 if ( $wgDebugLogPrefix !== '' ) {
370 $context['prefix'] = $wgDebugLogPrefix;
371 }
372 $context['private'] = ( $dest === false || $dest === 'private' );
373
374 $logger = LoggerFactory::getInstance( 'wfDebug' );
375 $logger->debug( $text, $context );
376}
377
383 static $cache;
384 if ( $cache !== null ) {
385 return $cache;
386 }
387 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
388 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
389 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
390 || MW_ENTRY_POINT === 'load'
391 ) {
392 $cache = true;
393 } else {
394 $cache = false;
395 }
396 return $cache;
397}
398
424function wfDebugLog(
425 $logGroup, $text, $dest = 'all', array $context = []
426) {
427 $text = trim( $text );
428
429 $logger = LoggerFactory::getInstance( $logGroup );
430 $context['private'] = ( $dest === false || $dest === 'private' );
431 $logger->info( $text, $context );
432}
433
442function wfLogDBError( $text, array $context = [] ) {
443 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
444 $logger->error( trim( $text ), $context );
445}
446
463function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
464 if ( !is_string( $version ) && $version !== false ) {
465 throw new InvalidArgumentException(
466 "MediaWiki version must either be a string or false. " .
467 "Example valid version: '1.33'"
468 );
469 }
470
471 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
472}
473
494function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
495 MWDebug::deprecatedMsg( $msg, $version, $component,
496 $callerOffset === false ? false : $callerOffset + 1 );
497}
498
509function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
510 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
511}
512
522function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
523 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
524}
525
548function wfMessage( $key, ...$params ) {
549 if ( is_array( $key ) ) {
550 // Fallback keys are not allowed in message specifiers
551 $message = wfMessageFallback( ...$key );
552 } else {
553 $message = Message::newFromSpecifier( $key );
554 }
555
556 // We call Message::params() to reduce code duplication
557 if ( $params ) {
558 $message->params( ...$params );
559 }
560
561 return $message;
562}
563
576function wfMessageFallback( ...$keys ) {
577 return Message::newFallbackSequence( ...$keys );
578}
579
588function wfMsgReplaceArgs( $message, $args ) {
589 # Fix windows line-endings
590 # Some messages are split with explode("\n", $msg)
591 $message = str_replace( "\r", '', $message );
592
593 // Replace arguments
594 if ( is_array( $args ) && $args ) {
595 if ( is_array( $args[0] ) ) {
596 $args = array_values( $args[0] );
597 }
598 $replacementKeys = [];
599 foreach ( $args as $n => $param ) {
600 $replacementKeys['$' . ( $n + 1 )] = $param;
601 }
602 $message = strtr( $message, $replacementKeys );
603 }
604
605 return $message;
606}
607
616function wfHostname() {
617 // Hostname overriding
618 global $wgOverrideHostname;
619 if ( $wgOverrideHostname !== false ) {
620 return $wgOverrideHostname;
621 }
622
623 return php_uname( 'n' ) ?: 'unknown';
624}
625
636function wfDebugBacktrace( $limit = 0 ) {
637 static $disabled = null;
638
639 if ( $disabled === null ) {
640 $disabled = !function_exists( 'debug_backtrace' );
641 if ( $disabled ) {
642 wfDebug( "debug_backtrace() is disabled" );
643 }
644 }
645 if ( $disabled ) {
646 return [];
647 }
648
649 if ( $limit ) {
650 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
651 } else {
652 return array_slice( debug_backtrace(), 1 );
653 }
654}
655
664function wfBacktrace( $raw = null ) {
665 $raw ??= MW_ENTRY_POINT === 'cli';
666 if ( $raw ) {
667 $frameFormat = "%s line %s calls %s()\n";
668 $traceFormat = "%s";
669 } else {
670 $frameFormat = "<li>%s line %s calls %s()</li>\n";
671 $traceFormat = "<ul>\n%s</ul>\n";
672 }
673
674 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
675 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
676 $line = $frame['line'] ?? '-';
677 $call = $frame['function'];
678 if ( !empty( $frame['class'] ) ) {
679 $call = $frame['class'] . $frame['type'] . $call;
680 }
681 return sprintf( $frameFormat, $file, $line, $call );
682 }, wfDebugBacktrace() );
683
684 return sprintf( $traceFormat, implode( '', $frames ) );
685}
686
697function wfGetCaller( $level = 2 ) {
698 $backtrace = wfDebugBacktrace( $level + 1 );
699 if ( isset( $backtrace[$level] ) ) {
700 return wfFormatStackFrame( $backtrace[$level] );
701 } else {
702 return 'unknown';
703 }
704}
705
713function wfGetAllCallers( $limit = 3 ) {
714 $limit = $limit ? $limit + 1 : 0;
715 // Strip the own "wfGetAllCallers" from the list
716 $trace = array_reverse( array_slice( wfDebugBacktrace( $limit ), 1 ) );
717 return implode( '/', array_map( wfFormatStackFrame( ... ), $trace ) );
718}
719
732function wfFormatStackFrame( $frame ) {
733 if ( !isset( $frame['function'] ) ) {
734 return 'NO_FUNCTION_GIVEN';
735 }
736 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
737 $frame['class'] . $frame['type'] . $frame['function'] :
738 $frame['function'];
739}
740
750function wfClientAcceptsGzip( $force = false ) {
751 static $result = null;
752 if ( $result === null || $force ) {
753 $result = false;
754 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
755 # @todo FIXME: We may want to disallow some broken browsers
756 $m = [];
757 if ( preg_match(
758 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
759 $_SERVER['HTTP_ACCEPT_ENCODING'],
760 $m
761 )
762 ) {
763 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
764 return $result;
765 }
766 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
767 $result = true;
768 }
769 }
770 }
771 return $result;
772}
773
784function wfEscapeWikiText( $input ): string {
785 global $wgEnableMagicLinks;
786 static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
787 if ( $repl === null || defined( 'MW_PHPUNIT_TEST' ) ) {
788 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
789 // in those situations
790 $repl = [
791 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
792 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
793 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
794 ';' => '&#59;', // a token inside language converter brackets
795 '!!' => '&#33;!', // a token inside table context
796 "\n!" => "\n&#33;", "\r!" => "\r&#33;", // a token inside table context
797 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
798 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
799 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
800 "\n " => "\n&#32;", "\r " => "\r&#32;",
801 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
802 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
803 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
804 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
805 '__' => '_&#95;', '://' => '&#58;//',
806 // Japanese magic words start w/ wide underscore
807 '_' => '&#xFF3F;',
808 '~~~' => '~~&#126;', // protect from PST, just to be safe(r)
809 ];
810
811 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
812 // We have to catch everything "\s" matches in PCRE
813 foreach ( $magicLinks as $magic ) {
814 $repl["$magic "] = "$magic&#32;";
815 $repl["$magic\t"] = "$magic&#9;";
816 $repl["$magic\r"] = "$magic&#13;";
817 $repl["$magic\n"] = "$magic&#10;";
818 $repl["$magic\f"] = "$magic&#12;";
819 }
820 // Additionally escape the following characters at the beginning of the
821 // string, in case they merge to form tokens when spliced into a
822 // string. Tokens like -{ {{ [[ {| etc are already escaped because
823 // the second character is escaped above, but the following tokens
824 // are handled here: |+ |- __FOO__ ~~~
825 // (Only single-byte characters can go here; multibyte characters
826 // like 'wide underscore' must go into $repl above.)
827 $repl3 = [
828 '+' => '&#43;', '-' => '&#45;', '_' => '&#95;', '~' => '&#126;',
829 ];
830 // Similarly, protect the following characters at the end of the
831 // string, which could turn form the start of `__FOO__` or `~~~~`
832 // A trailing newline could also form the unintended start of a
833 // paragraph break if it is glued to a newline in the following
834 // context. Again, only single-byte characters can be protected
835 // here; 'wide underscore' is protected by $repl above.
836 $repl4 = [
837 '_' => '&#95;', '~' => '&#126;',
838 "\n" => "&#10;", "\r" => "&#13;",
839 "\t" => "&#9;", // "\n\t\n" is treated like "\n\n"
840 ];
841
842 // And handle protocols that don't use "://"
843 global $wgUrlProtocols;
844 $repl2 = [];
845 foreach ( $wgUrlProtocols as $prot ) {
846 if ( substr( $prot, -1 ) === ':' ) {
847 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
848 }
849 }
850 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
851 }
852 // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
853 '@phan-var string $repl2';
854 '@phan-var string $repl3';
855 '@phan-var string $repl4';
856 // This will also stringify input in case it's not a string
857 $text = substr( strtr( "\n$input", $repl ), 1 );
858 if ( $text === '' ) {
859 return $text;
860 }
861 $first = strtr( $text[0], $repl3 ); // protect first character
862 if ( strlen( $text ) > 1 ) {
863 $text = $first . substr( $text, 1, -1 ) .
864 strtr( substr( $text, -1 ), $repl4 ); // protect last character
865 } else {
866 // special case for single-character strings
867 $text = strtr( $first, $repl4 ); // protect last character
868 }
869 $text = preg_replace( $repl2, '$1&#58;', $text );
870 return $text;
871}
872
883function wfSetVar( &$dest, $source, $force = false ) {
884 $temp = $dest;
885 if ( $source !== null || $force ) {
886 $dest = $source;
887 }
888 return $temp;
889}
890
900function wfSetBit( &$dest, $bit, $state = true ) {
901 $temp = (bool)( $dest & $bit );
902 if ( $state !== null ) {
903 if ( $state ) {
904 $dest |= $bit;
905 } else {
906 $dest &= ~$bit;
907 }
908 }
909 return $temp;
910}
911
918function wfVarDump( $var ) {
919 global $wgOut;
920 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
921 if ( HttpHeader::headersSent() || $wgOut === null || !is_object( $wgOut ) ) {
922 print $s;
923 } else {
924 $wgOut->addHTML( $s );
925 }
926}
927
935function wfHttpError( $code, $label, $desc ) {
936 global $wgOut;
937 HttpStatus::header( $code );
938 if ( $wgOut ) {
939 $wgOut->disable();
940 $wgOut->sendCacheControl();
941 }
942
944 HttpHeader::send( 'Content-type: text/html; charset=utf-8' );
945 ContentSecurityPolicy::sendRestrictiveHeader();
946 ob_start();
947 print '<!DOCTYPE html>' .
948 '<html><head><title>' .
949 htmlspecialchars( $label ) .
950 '</title><meta name="color-scheme" content="light dark" /></head><body><h1>' .
951 htmlspecialchars( $label ) .
952 '</h1><p>' .
953 nl2br( htmlspecialchars( $desc ) ) .
954 "</p></body></html>\n";
955 HttpHeader::send( 'Content-Length: ' . ob_get_length() );
956 ob_end_flush();
957}
958
981function wfResetOutputBuffers( $resetGzipEncoding = true ) {
982 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
983 return;
984 }
985 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
986 while ( $status = ob_get_status() ) {
987 if ( isset( $status['flags'] ) ) {
988 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
989 $deletable = ( $status['flags'] & $flags ) === $flags;
990 } elseif ( isset( $status['del'] ) ) {
991 $deletable = $status['del'];
992 } else {
993 // Guess that any PHP-internal setting can't be removed.
994 $deletable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
995 }
996 if ( !$deletable ) {
997 // Give up, and hope the result doesn't break
998 // output behavior.
999 break;
1000 }
1001 if ( !ob_end_clean() ) {
1002 // Could not remove output buffer handler; abort now
1003 // to avoid getting in some kind of infinite loop.
1004 break;
1005 }
1006 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1007 // Reset the 'Content-Encoding' field set by this handler
1008 // so we can start fresh.
1009 header_remove( 'Content-Encoding' );
1010 break;
1011 }
1012 }
1013}
1014
1025function wfTimestamp( $outputtype = TS::UNIX, $ts = 0 ) {
1026 $ret = ConvertibleTimestamp::convert( $outputtype, $ts );
1027 if ( $ret === false ) {
1028 if ( $outputtype instanceof TS ) {
1029 $outputtype = $outputtype->name;
1030 }
1031 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1032 }
1033 return $ret;
1034}
1035
1044function wfTimestampOrNull( $outputtype = TS::UNIX, $ts = null ) {
1045 if ( $ts === null ) {
1046 return null;
1047 } else {
1048 return wfTimestamp( $outputtype, $ts );
1049 }
1050}
1051
1057function wfTimestampNow() {
1058 return ConvertibleTimestamp::now( TS::MW );
1059}
1060
1072function wfTempDir() {
1073 global $wgTmpDirectory;
1074
1075 if ( $wgTmpDirectory !== false ) {
1076 return $wgTmpDirectory;
1077 }
1078
1079 return TempFSFile::getUsableTempDirectory();
1080}
1081
1090function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1091 global $wgDirectoryMode;
1092
1093 if ( FileBackend::isStoragePath( $dir ) ) {
1094 throw new LogicException( __FUNCTION__ . " given storage path '$dir'." );
1095 }
1096 if ( $caller !== null ) {
1097 wfDebug( "$caller: called wfMkdirParents($dir)" );
1098 }
1099 if ( strval( $dir ) === '' ) {
1100 return true;
1101 }
1102
1103 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1104 $mode ??= $wgDirectoryMode;
1105
1106 // Turn off the normal warning, we're doing our own below
1107 // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis.
1108 //
1109 // Repeat existence check if creation failed so that we silently recover in case of
1110 // a race condition where another request created it since the first check.
1111 //
1112 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1113 $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir );
1114 if ( !$ok ) {
1115 trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING );
1116 }
1117
1118 return $ok;
1119}
1120
1126function wfRecursiveRemoveDir( $dir ) {
1127 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1128 if ( is_dir( $dir ) ) {
1129 $objects = scandir( $dir );
1130 foreach ( $objects as $object ) {
1131 if ( $object != "." && $object != ".." ) {
1132 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1133 wfRecursiveRemoveDir( $dir . '/' . $object );
1134 } else {
1135 unlink( $dir . '/' . $object );
1136 }
1137 }
1138 }
1139 rmdir( $dir );
1140 }
1141}
1142
1152function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1153 wfDeprecated( __FUNCTION__, '1.46' );
1154 $accForFormat = $acc >= 0 ? $acc : 0;
1155 $ret = sprintf( "%.{$accForFormat}f", $nr );
1156 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1157}
1158
1182function wfIniGetBool( $setting ) {
1183 return wfStringToBool( ini_get( $setting ) );
1184}
1185
1198function wfStringToBool( $val ) {
1199 $val = strtolower( $val );
1200 // 'on' and 'true' can't have whitespace around them, but '1' can.
1201 return $val == 'on'
1202 || $val == 'true'
1203 || $val == 'yes'
1204 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1205}
1206
1220function wfEscapeShellArg( ...$args ) {
1221 wfDeprecated( __FUNCTION__, '1.30' );
1222 return Shell::escape( ...$args );
1223}
1224
1249function wfShellExec( $cmd, &$retval = null, $environ = [],
1250 $limits = [], $options = []
1251) {
1252 wfDeprecated( __FUNCTION__, '1.30' );
1253 if ( Shell::isDisabled() ) {
1254 $retval = 1;
1255 // Backwards compatibility be upon us...
1256 return 'Unable to run external programs, proc_open() is disabled.';
1257 }
1258
1259 if ( is_array( $cmd ) ) {
1260 $cmd = Shell::escape( $cmd );
1261 }
1262
1263 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1264 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1265
1266 try {
1267 $result = Shell::command( [] )
1268 ->unsafeParams( (array)$cmd )
1269 ->environment( $environ )
1270 ->limits( $limits )
1271 ->includeStderr( $includeStderr )
1272 ->profileMethod( $profileMethod )
1273 // For b/c
1274 ->restrict( Shell::RESTRICT_NONE )
1275 ->execute();
1276 } catch ( ProcOpenError ) {
1277 $retval = -1;
1278 return '';
1279 }
1280
1281 $retval = $result->getExitCode();
1282
1283 return $result->getStdout();
1284}
1285
1303function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1304 wfDeprecated( __FUNCTION__, '1.30' );
1305 return wfShellExec( $cmd, $retval, $environ, $limits,
1306 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1307}
1308
1324function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1325 wfDeprecated( __FUNCTION__, '1.30' );
1326 global $wgPhpCli;
1327 // Give site config file a chance to run the script in a wrapper.
1328 // The caller may likely want to call wfBasename() on $script.
1329 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
1330 ->onWfShellWikiCmd( $script, $parameters, $options );
1331 $cmd = [ $options['php'] ?? $wgPhpCli ];
1332 if ( isset( $options['wrapper'] ) ) {
1333 $cmd[] = $options['wrapper'];
1334 }
1335 $cmd[] = $script;
1336 // Escape each parameter for shell
1337 return Shell::escape( array_merge( $cmd, $parameters ) );
1338}
1339
1356function wfMerge(
1357 string $old,
1358 string $mine,
1359 string $yours,
1360 ?string &$simplisticMergeAttempt,
1361 ?string &$mergeLeftovers = null
1362): bool {
1363 global $wgDiff3;
1364
1365 # This check may also protect against code injection in
1366 # case of broken installations.
1367 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1368 $haveDiff3 = $wgDiff3 && @file_exists( $wgDiff3 );
1369
1370 if ( !$haveDiff3 ) {
1371 wfDebug( "diff3 not found" );
1372 return false;
1373 }
1374
1375 # Make temporary files
1376 $td = wfTempDir();
1377 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1378 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1379 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1380
1381 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
1382 # a newline character. To avoid this, we normalize the trailing whitespace before
1383 # creating the diff.
1384
1385 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
1386 fclose( $oldtextFile );
1387 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
1388 fclose( $mytextFile );
1389 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
1390 fclose( $yourtextFile );
1391
1392 # Check for a conflict
1393 $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName,
1394 $oldtextName, $yourtextName );
1395 $handle = popen( $cmd, 'r' );
1396
1397 $mergeLeftovers = '';
1398 do {
1399 $data = fread( $handle, 8192 );
1400 if ( $data === false || $data === '' ) {
1401 break;
1402 }
1403 $mergeLeftovers .= $data;
1404 } while ( true );
1405 pclose( $handle );
1406
1407 $conflict = $mergeLeftovers !== '';
1408
1409 # Merge differences automatically where possible, preferring "my" text for conflicts.
1410 $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName,
1411 $oldtextName, $yourtextName );
1412 $handle = popen( $cmd, 'r' );
1413 $simplisticMergeAttempt = '';
1414 do {
1415 $data = fread( $handle, 8192 );
1416 if ( $data === false || $data === '' ) {
1417 break;
1418 }
1419 $simplisticMergeAttempt .= $data;
1420 } while ( true );
1421 pclose( $handle );
1422 unlink( $mytextName );
1423 unlink( $oldtextName );
1424 unlink( $yourtextName );
1425
1426 if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) {
1427 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
1428 $conflict = true;
1429 }
1430 return !$conflict;
1431}
1432
1445function wfBaseName( $path, $suffix = '' ) {
1446 if ( $suffix == '' ) {
1447 $encSuffix = '';
1448 } else {
1449 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
1450 }
1451
1452 $matches = [];
1453 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1454 return $matches[1];
1455 } else {
1456 return '';
1457 }
1458}
1459
1469function wfRelativePath( $path, $from ) {
1470 // Normalize mixed input on Windows...
1471 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1472 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1473
1474 // Trim trailing slashes -- fix for drive root
1475 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1476 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1477
1478 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1479 $against = explode( DIRECTORY_SEPARATOR, $from );
1480
1481 if ( $pieces[0] !== $against[0] ) {
1482 // Non-matching Windows drive letters?
1483 // Return a full path.
1484 return $path;
1485 }
1486
1487 // Trim off common prefix
1488 while ( count( $pieces ) && count( $against )
1489 && $pieces[0] == $against[0] ) {
1490 array_shift( $pieces );
1491 array_shift( $against );
1492 }
1493
1494 // relative dots to bump us to the parent
1495 while ( count( $against ) ) {
1496 array_unshift( $pieces, '..' );
1497 array_shift( $against );
1498 }
1499
1500 $pieces[] = wfBaseName( $path );
1501
1502 return implode( DIRECTORY_SEPARATOR, $pieces );
1503}
1504
1514function wfScript( $script = 'index' ) {
1516 if ( $script === 'index' ) {
1517 return $wgScript;
1518 } elseif ( $script === 'load' ) {
1519 return $wgLoadScript;
1520 } else {
1521 return "{$wgScriptPath}/{$script}.php";
1522 }
1523}
1524
1532function wfBoolToStr( $value ) {
1533 return $value ? 'true' : 'false';
1534}
1535
1541function wfGetNull() {
1542 return wfIsWindows() ? 'NUL' : '/dev/null';
1543}
1544
1554 global $wgIllegalFileChars;
1555 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
1556 $name = preg_replace(
1557 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
1558 '-',
1559 $name
1560 );
1561 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
1562 $name = wfBaseName( $name );
1563 return $name;
1564}
1565
1572function wfMemoryLimit( $newLimit ) {
1573 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
1574 // If the INI config is already unlimited, there is nothing larger
1575 if ( $oldLimit != -1 ) {
1576 $newLimit = wfShorthandToInteger( (string)$newLimit );
1577 if ( $newLimit == -1 ) {
1578 wfDebug( "Removing PHP's memory limit" );
1579 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1580 @ini_set( 'memory_limit', $newLimit );
1581 } elseif ( $newLimit > $oldLimit ) {
1582 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
1583 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1584 @ini_set( 'memory_limit', $newLimit );
1585 }
1586 }
1587}
1588
1597
1598 $timeout = RequestTimeout::singleton();
1599 $timeLimit = $timeout->getWallTimeLimit();
1600 if ( $timeLimit !== INF ) {
1601 // RequestTimeout library is active
1602 if ( $wgTransactionalTimeLimit > $timeLimit ) {
1603 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1604 }
1605 } else {
1606 // Fallback case, likely $wgRequestTimeLimit === null
1607 $timeLimit = (int)ini_get( 'max_execution_time' );
1608 // Note that CLI scripts use 0
1609 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
1610 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
1611 }
1612 }
1613 ignore_user_abort( true ); // ignore client disconnects
1614
1615 return $timeLimit;
1616}
1617
1625function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
1626 $string = trim( $string ?? '' );
1627 if ( $string === '' ) {
1628 return $default;
1629 }
1630 $last = substr( $string, -1 );
1631 $val = intval( $string );
1632 switch ( $last ) {
1633 case 'g':
1634 case 'G':
1635 $val *= 1024;
1636 // break intentionally missing
1637 case 'm':
1638 case 'M':
1639 $val *= 1024;
1640 // break intentionally missing
1641 case 'k':
1642 case 'K':
1643 $val *= 1024;
1644 }
1645
1646 return $val;
1647}
1648
1656function wfIsInfinity( $str ) {
1657 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
1658 return in_array( $str, ExpiryDef::INFINITY_VALS );
1659}
1660
1675function wfThumbIsStandard( File $file, array $params ) {
1677
1678 $multipliers = [ 1 ];
1679 if ( $wgResponsiveImages ) {
1680 // These available sizes are hardcoded currently elsewhere in MediaWiki.
1681 // @see Linker::processResponsiveImages
1682 $multipliers[] = 2;
1683 }
1684
1685 $handler = $file->getHandler();
1686 if ( !$handler || !isset( $params['width'] ) ) {
1687 return false;
1688 }
1689
1690 $basicParams = [];
1691 if ( isset( $params['page'] ) ) {
1692 $basicParams['page'] = $params['page'];
1693 }
1694
1695 $thumbLimits = [];
1696 $imageLimits = [];
1697 // Expand limits to account for multipliers
1698 foreach ( $multipliers as $multiplier ) {
1699 $thumbLimits = array_merge( $thumbLimits, array_map(
1700 static function ( $width ) use ( $multiplier ) {
1701 return round( $width * $multiplier );
1702 }, $wgThumbLimits )
1703 );
1704 $imageLimits = array_merge( $imageLimits, array_map(
1705 static function ( $pair ) use ( $multiplier ) {
1706 return [
1707 round( $pair[0] * $multiplier ),
1708 round( $pair[1] * $multiplier ),
1709 ];
1710 }, $wgImageLimits )
1711 );
1712 }
1713
1714 // Check if the width matches one of $wgThumbLimits
1715 if ( in_array( $params['width'], $thumbLimits ) ) {
1716 $normalParams = $basicParams + [ 'width' => $params['width'] ];
1717 // Append any default values to the map (e.g. "lossy", "lossless", ...)
1718 $handler->normaliseParams( $file, $normalParams );
1719 } else {
1720 // If not, then check if the width matches one of $wgImageLimits
1721 $match = false;
1722 foreach ( $imageLimits as $pair ) {
1723 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
1724 // Decide whether the thumbnail should be scaled on width or height.
1725 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
1726 $handler->normaliseParams( $file, $normalParams );
1727 // Check if this standard thumbnail size maps to the given width
1728 if ( $normalParams['width'] == $params['width'] ) {
1729 $match = true;
1730 break;
1731 }
1732 }
1733 if ( !$match ) {
1734 return false; // not standard for description pages
1735 }
1736 }
1737
1738 // Check that the given values for non-page, non-width, params are just defaults
1739 foreach ( $params as $key => $value ) {
1740 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
1741 return false;
1742 }
1743 }
1744
1745 return true;
1746}
1747
1761function wfArrayPlus2d( array $baseArray, array $newValues ) {
1762 wfDeprecated( __FUNCTION__, '1.46' );
1763 return ArrayUtils::arrayPlus2d( $baseArray, $newValues );
1764}
1765
1770function wfUnserializeMissingClass( string $className ): void {
1771 LoggerFactory::getInstance( 'unserialize' )->error( 'Could not unserialize class {class}', [
1772 'class' => $className,
1773 'exception' => new RuntimeException( __FUNCTION__ ),
1774 ] );
1775 // This will trigger a "PHP Warning: unserialize(): Function wfUnserializeMissingClass()
1776 // hasn't defined the class it was called for" warning; we don't care about that.
1777}
wfIsWindows()
Check if the operating system is Windows.
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().
wfTimestampOrNull( $outputtype=TS::UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
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,...
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.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
wfEscapeShellArg(... $args)
Locale-independent version of escapeshellarg().
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
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.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
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.
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.
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
wfMerge(string $old, string $mine, string $yours, ?string &$simplisticMergeAttempt, ?string &$mergeLeftovers=null)
wfMerge attempts to merge differences between three texts.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfTransactionalTimeLimit()
Raise the request time limit to $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
wfLoadSkin( $skin, $path=null)
Load a skin.
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
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...
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfUnserializeMissingClass(string $className)
Logs missing classes when unserializing.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
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.
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
if(MW_ENTRY_POINT==='index') if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli') global $wgOut
Definition Setup.php:529
const MW_ENTRY_POINT
Definition api.php:21
Debug toolbar.
Definition MWDebug.php:35
getHandler(?Language $lang=null)
Get a MediaHandler instance for this file.
Definition File.php:1648
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.
Load JSON files, and uses a Processor to extract information.
Handle sending Content-Security-Policy headers.
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
This class wraps the native header functions in such a way that no headers are sent during PHPUnit te...
Type definition for expiry timestamps.
Definition ExpiryDef.php:18
$wgScript
Config variable stub for the Script 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.
$source