MediaWiki REL1_38
GlobalFunctions.php
Go to the documentation of this file.
1<?php
23if ( !defined( 'MEDIAWIKI' ) ) {
24 die( "This file is part of MediaWiki, it is not a valid entry point" );
25}
26
32use Wikimedia\AtEase\AtEase;
34use Wikimedia\RequestTimeout\RequestTimeout;
35use Wikimedia\WrappedString;
36
47function wfLoadExtension( $ext, $path = null ) {
48 if ( !$path ) {
50 $path = "$wgExtensionDirectory/$ext/extension.json";
51 }
52 ExtensionRegistry::getInstance()->queue( $path );
53}
54
68function wfLoadExtensions( array $exts ) {
70 $registry = ExtensionRegistry::getInstance();
71 foreach ( $exts as $ext ) {
72 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
73 }
74}
75
84function wfLoadSkin( $skin, $path = null ) {
85 if ( !$path ) {
86 global $wgStyleDirectory;
87 $path = "$wgStyleDirectory/$skin/skin.json";
88 }
89 ExtensionRegistry::getInstance()->queue( $path );
90}
91
99function wfLoadSkins( array $skins ) {
100 global $wgStyleDirectory;
101 $registry = ExtensionRegistry::getInstance();
102 foreach ( $skins as $skin ) {
103 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
104 }
105}
106
113function wfArrayDiff2( $arr1, $arr2 ) {
118 $comparator = static function ( $a, $b ): int {
119 if ( is_string( $a ) && is_string( $b ) ) {
120 return strcmp( $a, $b );
121 }
122 if ( !is_array( $a ) && !is_array( $b ) ) {
123 throw new InvalidArgumentException(
124 'This function assumes that array elements are all strings or all arrays'
125 );
126 }
127 if ( count( $a ) !== count( $b ) ) {
128 return count( $a ) <=> count( $b );
129 } else {
130 reset( $a );
131 reset( $b );
132 while ( key( $a ) !== null && key( $b ) !== null ) {
133 $valueA = current( $a );
134 $valueB = current( $b );
135 $cmp = strcmp( $valueA, $valueB );
136 if ( $cmp !== 0 ) {
137 return $cmp;
138 }
139 next( $a );
140 next( $b );
141 }
142 return 0;
143 }
144 };
145 return array_udiff( $arr1, $arr2, $comparator );
146}
147
167function wfMergeErrorArrays( ...$args ) {
168 $out = [];
169 foreach ( $args as $errors ) {
170 foreach ( $errors as $params ) {
171 $originalParams = $params;
172 if ( $params[0] instanceof MessageSpecifier ) {
173 $msg = $params[0];
174 $params = array_merge( [ $msg->getKey() ], $msg->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 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
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 list( $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
482function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
485 if ( $defaultProto === PROTO_CANONICAL ) {
486 $serverUrl = $wgCanonicalServer;
487 } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
488 // Make $wgInternalServer fall back to $wgServer if not set
489 $serverUrl = $wgInternalServer;
490 } else {
491 $serverUrl = $wgServer;
492 if ( $defaultProto === PROTO_CURRENT ) {
493 $defaultProto = $wgRequest->getProtocol() . '://';
494 }
495 }
496
497 // Analyze $serverUrl to obtain its protocol
498 $bits = wfParseUrl( $serverUrl );
499 $serverHasProto = $bits && $bits['scheme'] != '';
500
501 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
502 if ( $serverHasProto ) {
503 $defaultProto = $bits['scheme'] . '://';
504 } else {
505 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
506 // This really isn't supposed to happen. Fall back to HTTP in this
507 // ridiculous case.
508 $defaultProto = PROTO_HTTP;
509 }
510 }
511
512 $defaultProtoWithoutSlashes = $defaultProto !== null ? substr( $defaultProto, 0, -2 ) : '';
513
514 if ( substr( $url, 0, 2 ) == '//' ) {
515 $url = $defaultProtoWithoutSlashes . $url;
516 } elseif ( substr( $url, 0, 1 ) == '/' ) {
517 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
518 // otherwise leave it alone.
519 if ( $serverHasProto ) {
520 $url = $serverUrl . $url;
521 } else {
522 // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
523 // user to override the port number (T67184)
524 if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
525 if ( isset( $bits['port'] ) ) {
526 throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
527 }
528 $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
529 } else {
530 $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
531 }
532 }
533 }
534
535 $bits = wfParseUrl( $url );
536
537 if ( $bits && isset( $bits['path'] ) ) {
538 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
539 return wfAssembleUrl( $bits );
540 } elseif ( $bits ) {
541 # No path to expand
542 return $url;
543 } elseif ( substr( $url, 0, 1 ) != '/' ) {
544 # URL is a relative path
545 return wfRemoveDotSegments( $url );
546 }
547
548 # Expanded URL is not valid.
549 return false;
550}
551
560function wfGetServerUrl( $proto ) {
561 $url = wfExpandUrl( '/', $proto );
562 return substr( $url, 0, -1 );
563}
564
578function wfAssembleUrl( $urlParts ) {
579 $result = '';
580
581 if ( isset( $urlParts['delimiter'] ) ) {
582 if ( isset( $urlParts['scheme'] ) ) {
583 $result .= $urlParts['scheme'];
584 }
585
586 $result .= $urlParts['delimiter'];
587 }
588
589 if ( isset( $urlParts['host'] ) ) {
590 if ( isset( $urlParts['user'] ) ) {
591 $result .= $urlParts['user'];
592 if ( isset( $urlParts['pass'] ) ) {
593 $result .= ':' . $urlParts['pass'];
594 }
595 $result .= '@';
596 }
597
598 $result .= $urlParts['host'];
599
600 if ( isset( $urlParts['port'] ) ) {
601 $result .= ':' . $urlParts['port'];
602 }
603 }
604
605 if ( isset( $urlParts['path'] ) ) {
606 $result .= $urlParts['path'];
607 }
608
609 if ( isset( $urlParts['query'] ) && $urlParts['query'] !== '' ) {
610 $result .= '?' . $urlParts['query'];
611 }
612
613 if ( isset( $urlParts['fragment'] ) ) {
614 $result .= '#' . $urlParts['fragment'];
615 }
616
617 return $result;
618}
619
632function wfRemoveDotSegments( $urlPath ) {
633 $output = '';
634 $inputOffset = 0;
635 $inputLength = strlen( $urlPath );
636
637 while ( $inputOffset < $inputLength ) {
638 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
639 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
640 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
641 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
642 $trimOutput = false;
643
644 if ( $prefixLengthTwo == './' ) {
645 # Step A, remove leading "./"
646 $inputOffset += 2;
647 } elseif ( $prefixLengthThree == '../' ) {
648 # Step A, remove leading "../"
649 $inputOffset += 3;
650 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
651 # Step B, replace leading "/.$" with "/"
652 $inputOffset += 1;
653 $urlPath[$inputOffset] = '/';
654 } elseif ( $prefixLengthThree == '/./' ) {
655 # Step B, replace leading "/./" with "/"
656 $inputOffset += 2;
657 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
658 # Step C, replace leading "/..$" with "/" and
659 # remove last path component in output
660 $inputOffset += 2;
661 $urlPath[$inputOffset] = '/';
662 $trimOutput = true;
663 } elseif ( $prefixLengthFour == '/../' ) {
664 # Step C, replace leading "/../" with "/" and
665 # remove last path component in output
666 $inputOffset += 3;
667 $trimOutput = true;
668 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
669 # Step D, remove "^.$"
670 $inputOffset += 1;
671 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
672 # Step D, remove "^..$"
673 $inputOffset += 2;
674 } else {
675 # Step E, move leading path segment to output
676 if ( $prefixLengthOne == '/' ) {
677 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
678 } else {
679 $slashPos = strpos( $urlPath, '/', $inputOffset );
680 }
681 if ( $slashPos === false ) {
682 $output .= substr( $urlPath, $inputOffset );
683 $inputOffset = $inputLength;
684 } else {
685 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
686 $inputOffset += $slashPos - $inputOffset;
687 }
688 }
689
690 if ( $trimOutput ) {
691 $slashPos = strrpos( $output, '/' );
692 if ( $slashPos === false ) {
693 $output = '';
694 } else {
695 $output = substr( $output, 0, $slashPos );
696 }
697 }
698 }
699
700 return $output;
701}
702
710function wfUrlProtocols( $includeProtocolRelative = true ) {
711 global $wgUrlProtocols;
712
713 // Cache return values separately based on $includeProtocolRelative
714 static $withProtRel = null, $withoutProtRel = null;
715 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
716 if ( $cachedValue !== null ) {
717 return $cachedValue;
718 }
719
720 // Support old-style $wgUrlProtocols strings, for backwards compatibility
721 // with LocalSettings files from 1.5
722 if ( is_array( $wgUrlProtocols ) ) {
723 $protocols = [];
724 foreach ( $wgUrlProtocols as $protocol ) {
725 // Filter out '//' if !$includeProtocolRelative
726 if ( $includeProtocolRelative || $protocol !== '//' ) {
727 $protocols[] = preg_quote( $protocol, '/' );
728 }
729 }
730
731 $retval = implode( '|', $protocols );
732 } else {
733 // Ignore $includeProtocolRelative in this case
734 // This case exists for pre-1.6 compatibility, and we can safely assume
735 // that '//' won't appear in a pre-1.6 config because protocol-relative
736 // URLs weren't supported until 1.18
737 $retval = $wgUrlProtocols;
738 }
739
740 // Cache return value
741 if ( $includeProtocolRelative ) {
742 $withProtRel = $retval;
743 } else {
744 $withoutProtRel = $retval;
745 }
746 return $retval;
747}
748
756 return wfUrlProtocols( false );
757}
758
784function wfParseUrl( $url ) {
785 global $wgUrlProtocols; // Allow all protocols defined by the UrlProtocols setting.
786
787 // Protocol-relative URLs are handled really badly by parse_url(). It's so
788 // bad that the easiest way to handle them is to just prepend 'http:' and
789 // strip the protocol out later.
790 $wasRelative = substr( $url, 0, 2 ) == '//';
791 if ( $wasRelative ) {
792 $url = "http:$url";
793 }
794 $bits = parse_url( $url );
795 // parse_url() returns an array without scheme for some invalid URLs, e.g.
796 // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
797 if ( !$bits || !isset( $bits['scheme'] ) ) {
798 return false;
799 }
800
801 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
802 $bits['scheme'] = strtolower( $bits['scheme'] );
803
804 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
805 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
806 $bits['delimiter'] = '://';
807 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
808 $bits['delimiter'] = ':';
809 // parse_url detects for news: and mailto: the host part of an url as path
810 // We have to correct this wrong detection
811 if ( isset( $bits['path'] ) ) {
812 $bits['host'] = $bits['path'];
813 $bits['path'] = '';
814 }
815 } else {
816 return false;
817 }
818
819 /* Provide an empty host for eg. file:/// urls (see T30627) */
820 if ( !isset( $bits['host'] ) ) {
821 $bits['host'] = '';
822
823 // See T47069
824 if ( isset( $bits['path'] ) ) {
825 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
826 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
827 $bits['path'] = '/' . $bits['path'];
828 }
829 } else {
830 $bits['path'] = '';
831 }
832 }
833
834 // If the URL was protocol-relative, fix scheme and delimiter
835 if ( $wasRelative ) {
836 $bits['scheme'] = '';
837 $bits['delimiter'] = '//';
838 }
839 return $bits;
840}
841
852function wfExpandIRI( $url ) {
853 return preg_replace_callback(
854 '/((?:%[89A-F][0-9A-F])+)/i',
855 static function ( array $matches ) {
856 return urldecode( $matches[1] );
857 },
858 wfExpandUrl( $url )
859 );
860}
861
868function wfMatchesDomainList( $url, $domains ) {
869 $bits = wfParseUrl( $url );
870 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
871 $host = '.' . $bits['host'];
872 foreach ( (array)$domains as $domain ) {
873 $domain = '.' . $domain;
874 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
875 return true;
876 }
877 }
878 }
879 return false;
880}
881
902function wfDebug( $text, $dest = 'all', array $context = [] ) {
904
905 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
906 return;
907 }
908
909 $text = trim( $text );
910
911 if ( $wgDebugLogPrefix !== '' ) {
912 $context['prefix'] = $wgDebugLogPrefix;
913 }
914 $context['private'] = ( $dest === false || $dest === 'private' );
915
916 $logger = LoggerFactory::getInstance( 'wfDebug' );
917 $logger->debug( $text, $context );
918}
919
925 static $cache;
926 if ( $cache !== null ) {
927 return $cache;
928 }
929 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
930 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
931 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
932 || MW_ENTRY_POINT === 'load'
933 ) {
934 $cache = true;
935 } else {
936 $cache = false;
937 }
938 return $cache;
939}
940
966function wfDebugLog(
967 $logGroup, $text, $dest = 'all', array $context = []
968) {
969 $text = trim( $text );
970
971 $logger = LoggerFactory::getInstance( $logGroup );
972 $context['private'] = ( $dest === false || $dest === 'private' );
973 $logger->info( $text, $context );
974}
975
984function wfLogDBError( $text, array $context = [] ) {
985 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
986 $logger->error( trim( $text ), $context );
987}
988
1005function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1006 if ( !is_string( $version ) && $version !== false ) {
1007 throw new InvalidArgumentException(
1008 "MediaWiki version must either be a string or false. " .
1009 "Example valid version: '1.33'"
1010 );
1011 }
1012
1013 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1014}
1015
1036function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
1037 MWDebug::deprecatedMsg( $msg, $version, $component,
1038 $callerOffset === false ? false : $callerOffset + 1 );
1039}
1040
1051function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1052 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1053}
1054
1064function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1065 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1066}
1067
1072 wfDeprecated( __FUNCTION__, '1.38' );
1073 $profiler = Profiler::instance();
1074 $profiler->logData();
1075
1076 // Send out any buffered statsd metrics as needed
1077 MediaWiki::emitBufferedStatsdData(
1078 MediaWikiServices::getInstance()->getStatsdDataFactory(),
1079 MediaWikiServices::getInstance()->getMainConfig()
1080 );
1081}
1082
1090function wfReadOnly() {
1091 return MediaWikiServices::getInstance()->getReadOnlyMode()
1092 ->isReadOnly();
1093}
1094
1106 return MediaWikiServices::getInstance()->getReadOnlyMode()
1107 ->getReason();
1108}
1109
1125function wfGetLangObj( $langcode = false ) {
1126 # Identify which language to get or create a language object for.
1127 # Using is_object here due to Stub objects.
1128 if ( is_object( $langcode ) ) {
1129 # Great, we already have the object (hopefully)!
1130 return $langcode;
1131 }
1132
1133 global $wgLanguageCode;
1134 $services = MediaWikiServices::getInstance();
1135 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1136 # $langcode is the language code of the wikis content language object.
1137 # or it is a boolean and value is true
1138 return $services->getContentLanguage();
1139 }
1140
1141 global $wgLang;
1142 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1143 # $langcode is the language code of user language object.
1144 # or it was a boolean and value is false
1145 return $wgLang;
1146 }
1147
1148 $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1149 if ( in_array( $langcode, $validCodes ) ) {
1150 # $langcode corresponds to a valid language.
1151 return $services->getLanguageFactory()->getLanguage( $langcode );
1152 }
1153
1154 # $langcode is a string, but not a valid language code; use content language.
1155 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1156 return $services->getContentLanguage();
1157}
1158
1180function wfMessage( $key, ...$params ) {
1181 if ( is_array( $key ) ) {
1182 // Fallback keys are not allowed in message specifiers
1183 $message = wfMessageFallback( ...$key );
1184 } else {
1185 $message = Message::newFromSpecifier( $key );
1186 }
1187
1188 // We call Message::params() to reduce code duplication
1189 if ( $params ) {
1190 $message->params( ...$params );
1191 }
1192
1193 return $message;
1194}
1195
1208function wfMessageFallback( ...$keys ) {
1210}
1211
1220function wfMsgReplaceArgs( $message, $args ) {
1221 # Fix windows line-endings
1222 # Some messages are split with explode("\n", $msg)
1223 $message = str_replace( "\r", '', $message );
1224
1225 // Replace arguments
1226 if ( is_array( $args ) && $args ) {
1227 if ( is_array( $args[0] ) ) {
1228 $args = array_values( $args[0] );
1229 }
1230 $replacementKeys = [];
1231 foreach ( $args as $n => $param ) {
1232 $replacementKeys['$' . ( $n + 1 )] = $param;
1233 }
1234 $message = strtr( $message, $replacementKeys );
1235 }
1236
1237 return $message;
1238}
1239
1248function wfHostname() {
1249 // Hostname overriding
1250 global $wgOverrideHostname;
1251 if ( $wgOverrideHostname !== false ) {
1252 return $wgOverrideHostname;
1253 }
1254
1255 return php_uname( 'n' ) ?: 'unknown';
1256}
1257
1268function wfReportTime( $nonce = null ) {
1269 global $wgShowHostnames;
1270
1271 $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1272 // seconds to milliseconds
1273 $responseTime = round( $elapsed * 1000 );
1274 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1275 if ( $wgShowHostnames ) {
1276 $reportVars['wgHostname'] = wfHostname();
1277 }
1278
1279 return (
1282 $nonce
1283 )
1284 );
1285}
1286
1297function wfDebugBacktrace( $limit = 0 ) {
1298 static $disabled = null;
1299
1300 if ( $disabled === null ) {
1301 $disabled = !function_exists( 'debug_backtrace' );
1302 if ( $disabled ) {
1303 wfDebug( "debug_backtrace() is disabled" );
1304 }
1305 }
1306 if ( $disabled ) {
1307 return [];
1308 }
1309
1310 if ( $limit ) {
1311 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1312 } else {
1313 return array_slice( debug_backtrace(), 1 );
1314 }
1315}
1316
1325function wfBacktrace( $raw = null ) {
1326 global $wgCommandLineMode;
1327
1328 if ( $raw === null ) {
1329 $raw = $wgCommandLineMode;
1330 }
1331
1332 if ( $raw ) {
1333 $frameFormat = "%s line %s calls %s()\n";
1334 $traceFormat = "%s";
1335 } else {
1336 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1337 $traceFormat = "<ul>\n%s</ul>\n";
1338 }
1339
1340 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1341 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1342 $line = $frame['line'] ?? '-';
1343 $call = $frame['function'];
1344 if ( !empty( $frame['class'] ) ) {
1345 $call = $frame['class'] . $frame['type'] . $call;
1346 }
1347 return sprintf( $frameFormat, $file, $line, $call );
1348 }, wfDebugBacktrace() );
1349
1350 return sprintf( $traceFormat, implode( '', $frames ) );
1351}
1352
1362function wfGetCaller( $level = 2 ) {
1363 $backtrace = wfDebugBacktrace( $level + 1 );
1364 if ( isset( $backtrace[$level] ) ) {
1365 return wfFormatStackFrame( $backtrace[$level] );
1366 } else {
1367 return 'unknown';
1368 }
1369}
1370
1378function wfGetAllCallers( $limit = 3 ) {
1379 $trace = array_reverse( wfDebugBacktrace() );
1380 if ( !$limit || $limit > count( $trace ) - 1 ) {
1381 $limit = count( $trace ) - 1;
1382 }
1383 $trace = array_slice( $trace, -$limit - 1, $limit );
1384 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1385}
1386
1393function wfFormatStackFrame( $frame ) {
1394 if ( !isset( $frame['function'] ) ) {
1395 return 'NO_FUNCTION_GIVEN';
1396 }
1397 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1398 $frame['class'] . $frame['type'] . $frame['function'] :
1399 $frame['function'];
1400}
1401
1402/* Some generic result counters, pulled out of SearchEngine */
1403
1411function wfShowingResults( $offset, $limit ) {
1412 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1413}
1414
1424function wfClientAcceptsGzip( $force = false ) {
1425 static $result = null;
1426 if ( $result === null || $force ) {
1427 $result = false;
1428 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1429 # @todo FIXME: We may want to disallow some broken browsers
1430 $m = [];
1431 if ( preg_match(
1432 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1433 $_SERVER['HTTP_ACCEPT_ENCODING'],
1434 $m
1435 )
1436 ) {
1437 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1438 return $result;
1439 }
1440 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1441 $result = true;
1442 }
1443 }
1444 }
1445 return $result;
1446}
1447
1458function wfEscapeWikiText( $text ) {
1459 global $wgEnableMagicLinks;
1460 static $repl = null, $repl2 = null;
1461 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1462 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1463 // in those situations
1464 $repl = [
1465 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1466 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1467 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1468 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1469 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1470 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1471 "\n " => "\n&#32;", "\r " => "\r&#32;",
1472 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1473 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1474 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1475 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1476 '__' => '_&#95;', '://' => '&#58;//',
1477 ];
1478
1479 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1480 // We have to catch everything "\s" matches in PCRE
1481 foreach ( $magicLinks as $magic ) {
1482 $repl["$magic "] = "$magic&#32;";
1483 $repl["$magic\t"] = "$magic&#9;";
1484 $repl["$magic\r"] = "$magic&#13;";
1485 $repl["$magic\n"] = "$magic&#10;";
1486 $repl["$magic\f"] = "$magic&#12;";
1487 }
1488
1489 // And handle protocols that don't use "://"
1490 global $wgUrlProtocols;
1491 $repl2 = [];
1492 foreach ( $wgUrlProtocols as $prot ) {
1493 if ( substr( $prot, -1 ) === ':' ) {
1494 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1495 }
1496 }
1497 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1498 }
1499 $text = substr( strtr( "\n$text", $repl ), 1 );
1500 $text = preg_replace( $repl2, '$1&#58;', $text );
1501 return $text;
1502}
1503
1514function wfSetVar( &$dest, $source, $force = false ) {
1515 $temp = $dest;
1516 if ( $source !== null || $force ) {
1517 $dest = $source;
1518 }
1519 return $temp;
1520}
1521
1531function wfSetBit( &$dest, $bit, $state = true ) {
1532 $temp = (bool)( $dest & $bit );
1533 if ( $state !== null ) {
1534 if ( $state ) {
1535 $dest |= $bit;
1536 } else {
1537 $dest &= ~$bit;
1538 }
1539 }
1540 return $temp;
1541}
1542
1549function wfVarDump( $var ) {
1550 global $wgOut;
1551 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1552 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1553 print $s;
1554 } else {
1555 $wgOut->addHTML( $s );
1556 }
1557}
1558
1566function wfHttpError( $code, $label, $desc ) {
1567 global $wgOut;
1568 HttpStatus::header( $code );
1569 if ( $wgOut ) {
1570 $wgOut->disable();
1571 $wgOut->sendCacheControl();
1572 }
1573
1574 MediaWiki\HeaderCallback::warnIfHeadersSent();
1575 header( 'Content-type: text/html; charset=utf-8' );
1576 ob_start();
1577 print '<!DOCTYPE html>' .
1578 '<html><head><title>' .
1579 htmlspecialchars( $label ) .
1580 '</title></head><body><h1>' .
1581 htmlspecialchars( $label ) .
1582 '</h1><p>' .
1583 nl2br( htmlspecialchars( $desc ) ) .
1584 "</p></body></html>\n";
1585 header( 'Content-Length: ' . ob_get_length() );
1586 ob_end_flush();
1587}
1588
1606function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1607 while ( $status = ob_get_status() ) {
1608 if ( isset( $status['flags'] ) ) {
1609 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1610 $deleteable = ( $status['flags'] & $flags ) === $flags;
1611 } elseif ( isset( $status['del'] ) ) {
1612 $deleteable = $status['del'];
1613 } else {
1614 // Guess that any PHP-internal setting can't be removed.
1615 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1616 }
1617 if ( !$deleteable ) {
1618 // Give up, and hope the result doesn't break
1619 // output behavior.
1620 break;
1621 }
1622 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1623 // Unit testing barrier to prevent this function from breaking PHPUnit.
1624 break;
1625 }
1626 if ( !ob_end_clean() ) {
1627 // Could not remove output buffer handler; abort now
1628 // to avoid getting in some kind of infinite loop.
1629 break;
1630 }
1631 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1632 // Reset the 'Content-Encoding' field set by this handler
1633 // so we can start fresh.
1634 header_remove( 'Content-Encoding' );
1635 break;
1636 }
1637 }
1638}
1639
1655 wfDeprecated( __FUNCTION__, '1.36' );
1656 wfResetOutputBuffers( false );
1657}
1658
1667function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1668 $ret = MWTimestamp::convert( $outputtype, $ts );
1669 if ( $ret === false ) {
1670 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1671 }
1672 return $ret;
1673}
1674
1683function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1684 if ( $ts === null ) {
1685 return null;
1686 } else {
1687 return wfTimestamp( $outputtype, $ts );
1688 }
1689}
1690
1696function wfTimestampNow() {
1697 return MWTimestamp::now( TS_MW );
1698}
1699
1705function wfIsWindows() {
1706 return PHP_OS_FAMILY === 'Windows';
1707}
1708
1715function wfIsCLI() {
1716 return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1717}
1718
1730function wfTempDir() {
1731 global $wgTmpDirectory;
1732
1733 if ( $wgTmpDirectory !== false ) {
1734 return $wgTmpDirectory;
1735 }
1736
1737 return TempFSFile::getUsableTempDirectory();
1738}
1739
1749function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1750 global $wgDirectoryMode;
1751
1752 if ( FileBackend::isStoragePath( $dir ) ) {
1753 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1754 }
1755
1756 if ( $caller !== null ) {
1757 wfDebug( "$caller: called wfMkdirParents($dir)" );
1758 }
1759
1760 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1761 return true;
1762 }
1763
1764 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1765
1766 if ( $mode === null ) {
1767 $mode = $wgDirectoryMode;
1768 }
1769
1770 // Turn off the normal warning, we're doing our own below
1771 AtEase::suppressWarnings();
1772 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1773 AtEase::restoreWarnings();
1774
1775 if ( !$ok ) {
1776 // directory may have been created on another request since we last checked
1777 if ( is_dir( $dir ) ) {
1778 return true;
1779 }
1780
1781 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1782 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1783 }
1784 return $ok;
1785}
1786
1792function wfRecursiveRemoveDir( $dir ) {
1793 wfDebug( __FUNCTION__ . "( $dir )" );
1794 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1795 if ( is_dir( $dir ) ) {
1796 $objects = scandir( $dir );
1797 foreach ( $objects as $object ) {
1798 if ( $object != "." && $object != ".." ) {
1799 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1800 wfRecursiveRemoveDir( $dir . '/' . $object );
1801 } else {
1802 unlink( $dir . '/' . $object );
1803 }
1804 }
1805 }
1806 reset( $objects );
1807 rmdir( $dir );
1808 }
1809}
1810
1817function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1818 $accForFormat = $acc >= 0 ? $acc : 0;
1819 $ret = sprintf( "%.{$accForFormat}f", $nr );
1820 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1821}
1822
1846function wfIniGetBool( $setting ) {
1847 return wfStringToBool( ini_get( $setting ) );
1848}
1849
1862function wfStringToBool( $val ) {
1863 $val = strtolower( $val );
1864 // 'on' and 'true' can't have whitespace around them, but '1' can.
1865 return $val == 'on'
1866 || $val == 'true'
1867 || $val == 'yes'
1868 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1869}
1870
1884function wfEscapeShellArg( ...$args ) {
1885 return Shell::escape( ...$args );
1886}
1887
1912function wfShellExec( $cmd, &$retval = null, $environ = [],
1913 $limits = [], $options = []
1914) {
1915 if ( Shell::isDisabled() ) {
1916 $retval = 1;
1917 // Backwards compatibility be upon us...
1918 return 'Unable to run external programs, proc_open() is disabled.';
1919 }
1920
1921 if ( is_array( $cmd ) ) {
1922 $cmd = Shell::escape( $cmd );
1923 }
1924
1925 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1926 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1927
1928 try {
1929 $result = Shell::command( [] )
1930 ->unsafeParams( (array)$cmd )
1931 ->environment( $environ )
1932 ->limits( $limits )
1933 ->includeStderr( $includeStderr )
1934 ->profileMethod( $profileMethod )
1935 // For b/c
1936 ->restrict( Shell::RESTRICT_NONE )
1937 ->execute();
1938 } catch ( ProcOpenError $ex ) {
1939 $retval = -1;
1940 return '';
1941 }
1942
1943 $retval = $result->getExitCode();
1944
1945 return $result->getStdout();
1946}
1947
1965function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1966 return wfShellExec( $cmd, $retval, $environ, $limits,
1967 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1968}
1969
1985function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
1986 global $wgPhpCli;
1987 // Give site config file a chance to run the script in a wrapper.
1988 // The caller may likely want to call wfBasename() on $script.
1989 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
1990 $cmd = [ $options['php'] ?? $wgPhpCli ];
1991 if ( isset( $options['wrapper'] ) ) {
1992 $cmd[] = $options['wrapper'];
1993 }
1994 $cmd[] = $script;
1995 // Escape each parameter for shell
1996 return Shell::escape( array_merge( $cmd, $parameters ) );
1997}
1998
2010function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2011 global $wgDiff3;
2012
2013 # This check may also protect against code injection in
2014 # case of broken installations.
2015 AtEase::suppressWarnings();
2016 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2017 AtEase::restoreWarnings();
2018
2019 if ( !$haveDiff3 ) {
2020 wfDebug( "diff3 not found" );
2021 return false;
2022 }
2023
2024 # Make temporary files
2025 $td = wfTempDir();
2026 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2027 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2028 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2029
2030 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2031 # a newline character. To avoid this, we normalize the trailing whitespace before
2032 # creating the diff.
2033
2034 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2035 fclose( $oldtextFile );
2036 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2037 fclose( $mytextFile );
2038 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2039 fclose( $yourtextFile );
2040
2041 # Check for a conflict
2042 $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2043 $oldtextName, $yourtextName );
2044 $handle = popen( $cmd, 'r' );
2045
2046 $mergeAttemptResult = '';
2047 do {
2048 $data = fread( $handle, 8192 );
2049 if ( strlen( $data ) == 0 ) {
2050 break;
2051 }
2052 $mergeAttemptResult .= $data;
2053 } while ( true );
2054 pclose( $handle );
2055
2056 $conflict = $mergeAttemptResult !== '';
2057
2058 # Merge differences
2059 $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2060 $oldtextName, $yourtextName );
2061 $handle = popen( $cmd, 'r' );
2062 $result = '';
2063 do {
2064 $data = fread( $handle, 8192 );
2065 if ( strlen( $data ) == 0 ) {
2066 break;
2067 }
2068 $result .= $data;
2069 } while ( true );
2070 pclose( $handle );
2071 unlink( $mytextName );
2072 unlink( $oldtextName );
2073 unlink( $yourtextName );
2074
2075 if ( $result === '' && $old !== '' && !$conflict ) {
2076 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2077 $conflict = true;
2078 }
2079 return !$conflict;
2080}
2081
2094function wfBaseName( $path, $suffix = '' ) {
2095 if ( $suffix == '' ) {
2096 $encSuffix = '';
2097 } else {
2098 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2099 }
2100
2101 $matches = [];
2102 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2103 return $matches[1];
2104 } else {
2105 return '';
2106 }
2107}
2108
2118function wfRelativePath( $path, $from ) {
2119 // Normalize mixed input on Windows...
2120 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2121 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2122
2123 // Trim trailing slashes -- fix for drive root
2124 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2125 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2126
2127 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2128 $against = explode( DIRECTORY_SEPARATOR, $from );
2129
2130 if ( $pieces[0] !== $against[0] ) {
2131 // Non-matching Windows drive letters?
2132 // Return a full path.
2133 return $path;
2134 }
2135
2136 // Trim off common prefix
2137 while ( count( $pieces ) && count( $against )
2138 && $pieces[0] == $against[0] ) {
2139 array_shift( $pieces );
2140 array_shift( $against );
2141 }
2142
2143 // relative dots to bump us to the parent
2144 while ( count( $against ) ) {
2145 array_unshift( $pieces, '..' );
2146 array_shift( $against );
2147 }
2148
2149 $pieces[] = wfBaseName( $path );
2150
2151 return implode( DIRECTORY_SEPARATOR, $pieces );
2152}
2153
2162function wfWikiID() {
2163 wfDeprecated( __FUNCTION__, '1.35' );
2164 global $wgDBprefix, $wgDBname;
2165
2166 if ( $wgDBprefix ) {
2167 return "$wgDBname-$wgDBprefix";
2168 } else {
2169 return $wgDBname;
2170 }
2171}
2172
2204function wfGetDB( $db, $groups = [], $wiki = false ) {
2205 if ( $wiki === false ) {
2206 return MediaWikiServices::getInstance()
2207 ->getDBLoadBalancer()
2208 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2209 } else {
2210 return MediaWikiServices::getInstance()
2211 ->getDBLoadBalancerFactory()
2212 ->getMainLB( $wiki )
2213 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2214 }
2215}
2216
2227function wfGetLB( $wiki = false ) {
2228 wfDeprecated( __FUNCTION__, '1.27' );
2229 if ( $wiki === false ) {
2230 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
2231 return MediaWikiServices::getInstance()->getDBLoadBalancer();
2232 } else {
2233 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2234 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
2235 return $factory->getMainLB( $wiki );
2236 }
2237}
2238
2246function wfFindFile( $title, $options = [] ) {
2247 wfDeprecated( __FUNCTION__, '1.34' );
2248 return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2249}
2250
2259function wfLocalFile( $title ) {
2260 wfDeprecated( __FUNCTION__, '1.34' );
2261 return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2262}
2263
2271 global $wgMiserMode;
2272 return $wgMiserMode
2273 || ( SiteStats::pages() > 100000
2274 && SiteStats::edits() > 1000000
2275 && SiteStats::users() > 10000 );
2276}
2277
2286function wfScript( $script = 'index' ) {
2288 if ( $script === 'index' ) {
2289 return $wgScript;
2290 } elseif ( $script === 'load' ) {
2291 return $wgLoadScript;
2292 } else {
2293 return "{$wgScriptPath}/{$script}.php";
2294 }
2295}
2296
2303function wfGetScriptUrl() {
2304 wfDeprecated( __FUNCTION__, '1.35' );
2305 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2306 /* as it was called, minus the query string.
2307 *
2308 * Some sites use Apache rewrite rules to handle subdomains,
2309 * and have PHP set up in a weird way that causes PHP_SELF
2310 * to contain the rewritten URL instead of the one that the
2311 * outside world sees.
2312 *
2313 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2314 * provides containing the "before" URL.
2315 */
2316 return $_SERVER['SCRIPT_NAME'];
2317 } else {
2318 return $_SERVER['URL'];
2319 }
2320}
2321
2329function wfBoolToStr( $value ) {
2330 return $value ? 'true' : 'false';
2331}
2332
2338function wfGetNull() {
2339 return wfIsWindows() ? 'NUL' : '/dev/null';
2340}
2341
2351 global $wgIllegalFileChars;
2352 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2353 $name = preg_replace(
2354 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2355 '-',
2356 $name
2357 );
2358 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2359 $name = wfBaseName( $name );
2360 return $name;
2361}
2362
2369function wfMemoryLimit( $newLimit ) {
2370 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2371 // If the INI config is already unlimited, there is nothing larger
2372 if ( $oldLimit != -1 ) {
2373 $newLimit = wfShorthandToInteger( (string)$newLimit );
2374 if ( $newLimit == -1 ) {
2375 wfDebug( "Removing PHP's memory limit" );
2376 AtEase::suppressWarnings();
2377 ini_set( 'memory_limit', $newLimit );
2378 AtEase::restoreWarnings();
2379 } elseif ( $newLimit > $oldLimit ) {
2380 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2381 AtEase::suppressWarnings();
2382 ini_set( 'memory_limit', $newLimit );
2383 AtEase::restoreWarnings();
2384 }
2385 }
2386}
2387
2396
2397 $timeout = RequestTimeout::singleton();
2398 $timeLimit = $timeout->getWallTimeLimit();
2399 if ( $timeLimit !== INF ) {
2400 // RequestTimeout library is active
2401 if ( $wgTransactionalTimeLimit > $timeLimit ) {
2402 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2403 }
2404 } else {
2405 // Fallback case, likely $wgRequestTimeLimit === null
2406 $timeLimit = (int)ini_get( 'max_execution_time' );
2407 // Note that CLI scripts use 0
2408 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2409 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2410 }
2411 }
2412 ignore_user_abort( true ); // ignore client disconnects
2413
2414 return $timeLimit;
2415}
2416
2424function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2425 $string = trim( $string ?? '' );
2426 if ( $string === '' ) {
2427 return $default;
2428 }
2429 $last = $string[strlen( $string ) - 1];
2430 $val = intval( $string );
2431 switch ( $last ) {
2432 case 'g':
2433 case 'G':
2434 $val *= 1024;
2435 // break intentionally missing
2436 case 'm':
2437 case 'M':
2438 $val *= 1024;
2439 // break intentionally missing
2440 case 'k':
2441 case 'K':
2442 $val *= 1024;
2443 }
2444
2445 return $val;
2446}
2447
2457function wfGetCache( $cacheType ) {
2458 wfDeprecated( __FUNCTION__, '1.32' );
2459 return ObjectCache::getInstance( $cacheType );
2460}
2461
2470function wfGetMainCache() {
2471 wfDeprecated( __FUNCTION__, '1.32' );
2472 return ObjectCache::getLocalClusterInstance();
2473}
2474
2489function wfUnpack( $format, $data, $length = false ) {
2490 if ( $length !== false ) {
2491 $realLen = strlen( $data );
2492 if ( $realLen < $length ) {
2493 throw new MWException( "Tried to use wfUnpack on a "
2494 . "string of length $realLen, but needed one "
2495 . "of at least length $length."
2496 );
2497 }
2498 }
2499
2500 AtEase::suppressWarnings();
2501 $result = unpack( $format, $data );
2502 AtEase::restoreWarnings();
2503
2504 if ( $result === false ) {
2505 // If it cannot extract the packed data.
2506 throw new MWException( "unpack could not unpack binary data" );
2507 }
2508 return $result;
2509}
2510
2520function wfCanIPUseHTTPS( $ip ) {
2521 wfDeprecated( __FUNCTION__, '1.37' );
2522 return true;
2523}
2524
2532function wfIsInfinity( $str ) {
2533 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2534 return in_array( $str, ExpiryDef::INFINITY_VALS );
2535}
2536
2551function wfThumbIsStandard( File $file, array $params ) {
2553
2554 $multipliers = [ 1 ];
2555 if ( $wgResponsiveImages ) {
2556 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2557 // @see Linker::processResponsiveImages
2558 $multipliers[] = 1.5;
2559 $multipliers[] = 2;
2560 }
2561
2562 $handler = $file->getHandler();
2563 if ( !$handler || !isset( $params['width'] ) ) {
2564 return false;
2565 }
2566
2567 $basicParams = [];
2568 if ( isset( $params['page'] ) ) {
2569 $basicParams['page'] = $params['page'];
2570 }
2571
2572 $thumbLimits = [];
2573 $imageLimits = [];
2574 // Expand limits to account for multipliers
2575 foreach ( $multipliers as $multiplier ) {
2576 $thumbLimits = array_merge( $thumbLimits, array_map(
2577 static function ( $width ) use ( $multiplier ) {
2578 return round( $width * $multiplier );
2579 }, $wgThumbLimits )
2580 );
2581 $imageLimits = array_merge( $imageLimits, array_map(
2582 static function ( $pair ) use ( $multiplier ) {
2583 return [
2584 round( $pair[0] * $multiplier ),
2585 round( $pair[1] * $multiplier ),
2586 ];
2587 }, $wgImageLimits )
2588 );
2589 }
2590
2591 // Check if the width matches one of $wgThumbLimits
2592 if ( in_array( $params['width'], $thumbLimits ) ) {
2593 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2594 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2595 $handler->normaliseParams( $file, $normalParams );
2596 } else {
2597 // If not, then check if the width matchs one of $wgImageLimits
2598 $match = false;
2599 foreach ( $imageLimits as $pair ) {
2600 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2601 // Decide whether the thumbnail should be scaled on width or height.
2602 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2603 $handler->normaliseParams( $file, $normalParams );
2604 // Check if this standard thumbnail size maps to the given width
2605 if ( $normalParams['width'] == $params['width'] ) {
2606 $match = true;
2607 break;
2608 }
2609 }
2610 if ( !$match ) {
2611 return false; // not standard for description pages
2612 }
2613 }
2614
2615 // Check that the given values for non-page, non-width, params are just defaults
2616 foreach ( $params as $key => $value ) {
2617 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2618 return false;
2619 }
2620 }
2621
2622 return true;
2623}
2624
2637function wfArrayPlus2d( array $baseArray, array $newValues ) {
2638 // First merge items that are in both arrays
2639 foreach ( $baseArray as $name => &$groupVal ) {
2640 if ( isset( $newValues[$name] ) ) {
2641 $groupVal += $newValues[$name];
2642 }
2643 }
2644 // Now add items that didn't exist yet
2645 $baseArray += $newValues;
2646
2647 return $baseArray;
2648}
$wgLanguageCode
Site language code.
$wgDBprefix
Current wiki database table name prefix.
$wgScript
The URL path to index.php.
$wgInternalServer
Internal server name as known to CDN, if different.
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
$wgDebugLogPrefix
Prefix for debug log lines.
$wgPhpCli
Executable path of the PHP cli binary.
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
$wgTmpDirectory
The local filesystem path to a temporary directory.
$wgStyleDirectory
Filesystem stylesheets directory.
$wgTransactionalTimeLimit
The request time limit for "slow" write requests that should not be interrupted due to the risk of da...
$wgDBname
Current wiki database name.
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
$wgDirectoryMode
Default value for chmoding of new directories.
$wgDiff3
Path to the GNU diff3 utility.
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
$wgDebugRawPage
If true, log debugging data from action=raw and load.php.
$wgEnableMagicLinks
Enable the magic links feature of automatically turning ISBN xxx, PMID xxx, RFC xxx into links.
$wgScriptPath
The path we should point to.
$wgExtensionDirectory
Filesystem extensions directory.
$wgLoadScript
The URL path to load.php.
$wgCanonicalServer
Canonical URL of the server, to use in IRC feeds and notification e-mails.
$wgMiserMode
Disable database-intensive features.
$wgServer
URL of the server.
$wgHttpsPort
For installations where the canonical server is HTTP but HTTPS is optionally supported,...
const PROTO_CANONICAL
Definition Defines.php:195
const PROTO_HTTPS
Definition Defines.php:192
const PROTO_CURRENT
Definition Defines.php:194
const PROTO_INTERNAL
Definition Defines.php:196
const PROTO_HTTP
Definition Defines.php:191
global $wgCommandLineMode
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()
wfLogDBError( $text, array $context=[])
Log for database errors.
wfLoadSkins(array $skins)
Load multiple skins at once.
wfGetLB( $wiki=false)
Get a load balancer object.
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).
wfReadOnly()
Check whether the wiki is in read-only mode.
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...
wfLocalFile( $title)
Get an object referring to a locally registered file.
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.
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.
wfGetMainCache()
Get the main cache object.
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
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)
wfFindFile( $title, $options=[])
Find a file.
wfReportTime( $nonce=null)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
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.
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
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 regular expression of url protocols.
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...
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
wfShowingResults( $offset, $limit)
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.
wfGetScriptUrl()
Get the script URL.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
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:
wfGetCache( $cacheType)
Get a specific cache object.
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 path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfIsWindows()
Check if the operating system is Windows.
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.
wfQueriesMustScale()
Should low-performance queries be disabled?
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.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfLogProfilingData()
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.
wfIsCLI()
Check if we are running from the commandline.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
global $wgRequest
Definition Setup.php:807
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgOut
Definition Setup.php:927
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition Setup.php:927
const MW_ENTRY_POINT
Definition api.php:41
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:67
MediaWiki exception.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Executes shell commands.
Definition Shell.php:45
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition Message.php:456
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition Message.php:422
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
static edits()
Definition SiteStats.php:94
static users()
static pages()
Type definition for expiry timestamps.
Definition ExpiryDef.php:17
while(( $__line=Maintenance::readconsole()) !==false) print
Definition eval.php:69
$line
Definition mcc.php:119
$cache
Definition mcc.php:33
if( $line===false) $args
Definition mcc.php:124
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s
$source
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
if(!is_readable( $file)) $ext
Definition router.php:48