MediaWiki REL1_37
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( $a, $b ) {
114 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
115}
116
122function wfArrayDiff2_cmp( $a, $b ) {
123 if ( is_string( $a ) && is_string( $b ) ) {
124 return strcmp( $a, $b );
125 } elseif ( count( $a ) !== count( $b ) ) {
126 return count( $a ) <=> count( $b );
127 } else {
128 reset( $a );
129 reset( $b );
130 while ( key( $a ) !== null && key( $b ) !== null ) {
131 $valueA = current( $a );
132 $valueB = current( $b );
133 $cmp = strcmp( $valueA, $valueB );
134 if ( $cmp !== 0 ) {
135 return $cmp;
136 }
137 next( $a );
138 next( $b );
139 }
140 return 0;
141 }
142}
143
163function wfMergeErrorArrays( ...$args ) {
164 $out = [];
165 foreach ( $args as $errors ) {
166 foreach ( $errors as $params ) {
167 $originalParams = $params;
168 if ( $params[0] instanceof MessageSpecifier ) {
169 $msg = $params[0];
170 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
171 }
172 # @todo FIXME: Sometimes get nested arrays for $params,
173 # which leads to E_NOTICEs
174 $spec = implode( "\t", $params );
175 $out[$spec] = $originalParams;
176 }
177 }
178 return array_values( $out );
179}
180
189function wfArrayInsertAfter( array $array, array $insert, $after ) {
190 // Find the offset of the element to insert after.
191 $keys = array_keys( $array );
192 $offsetByKey = array_flip( $keys );
193
194 $offset = $offsetByKey[$after];
195
196 // Insert at the specified offset
197 $before = array_slice( $array, 0, $offset + 1, true );
198 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
199
200 $output = $before + $insert + $after;
201
202 return $output;
203}
204
213function wfObjectToArray( $objOrArray, $recursive = true ) {
214 $array = [];
215 if ( is_object( $objOrArray ) ) {
216 $objOrArray = get_object_vars( $objOrArray );
217 }
218 foreach ( $objOrArray as $key => $value ) {
219 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
220 $value = wfObjectToArray( $value );
221 }
222
223 $array[$key] = $value;
224 }
225
226 return $array;
227}
228
239function wfRandom() {
240 // The maximum random value is "only" 2^31-1, so get two random
241 // values to reduce the chance of dupes
242 $max = mt_getrandmax() + 1;
243 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
244 return $rand;
245}
246
257function wfRandomString( $length = 32 ) {
258 $str = '';
259 for ( $n = 0; $n < $length; $n += 7 ) {
260 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
261 }
262 return substr( $str, 0, $length );
263}
264
292function wfUrlencode( $s ) {
293 static $needle;
294
295 if ( $s === null ) {
296 // Reset $needle for testing.
297 $needle = null;
298 return '';
299 }
300
301 if ( $needle === null ) {
302 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
303 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
304 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
305 ) {
306 $needle[] = '%3A';
307 }
308 }
309
310 $s = urlencode( $s );
311 $s = str_ireplace(
312 $needle,
313 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
314 $s
315 );
316
317 return $s;
318}
319
330function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
331 if ( $array2 !== null ) {
332 $array1 += $array2;
333 }
334
335 $cgi = '';
336 foreach ( $array1 as $key => $value ) {
337 if ( $value !== null && $value !== false ) {
338 if ( $cgi != '' ) {
339 $cgi .= '&';
340 }
341 if ( $prefix !== '' ) {
342 $key = $prefix . "[$key]";
343 }
344 if ( is_array( $value ) ) {
345 $firstTime = true;
346 foreach ( $value as $k => $v ) {
347 $cgi .= $firstTime ? '' : '&';
348 if ( is_array( $v ) ) {
349 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
350 } else {
351 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
352 }
353 $firstTime = false;
354 }
355 } else {
356 if ( is_object( $value ) ) {
357 $value = $value->__toString();
358 }
359 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
360 }
361 }
362 }
363 return $cgi;
364}
365
375function wfCgiToArray( $query ) {
376 if ( isset( $query[0] ) && $query[0] == '?' ) {
377 $query = substr( $query, 1 );
378 }
379 $bits = explode( '&', $query );
380 $ret = [];
381 foreach ( $bits as $bit ) {
382 if ( $bit === '' ) {
383 continue;
384 }
385 if ( strpos( $bit, '=' ) === false ) {
386 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
387 $key = $bit;
388 $value = '';
389 } else {
390 list( $key, $value ) = explode( '=', $bit );
391 }
392 $key = urldecode( $key );
393 $value = urldecode( $value );
394 if ( strpos( $key, '[' ) !== false ) {
395 $keys = array_reverse( explode( '[', $key ) );
396 $key = array_pop( $keys );
397 $temp = $value;
398 foreach ( $keys as $k ) {
399 $k = substr( $k, 0, -1 );
400 $temp = [ $k => $temp ];
401 }
402 if ( isset( $ret[$key] ) ) {
403 $ret[$key] = array_merge( $ret[$key], $temp );
404 } else {
405 $ret[$key] = $temp;
406 }
407 } else {
408 $ret[$key] = $value;
409 }
410 }
411 return $ret;
412}
413
422function wfAppendQuery( $url, $query ) {
423 if ( is_array( $query ) ) {
424 $query = wfArrayToCgi( $query );
425 }
426 if ( $query != '' ) {
427 // Remove the fragment, if there is one
428 $fragment = false;
429 $hashPos = strpos( $url, '#' );
430 if ( $hashPos !== false ) {
431 $fragment = substr( $url, $hashPos );
432 $url = substr( $url, 0, $hashPos );
433 }
434
435 // Add parameter
436 if ( strpos( $url, '?' ) === false ) {
437 $url .= '?';
438 } else {
439 $url .= '&';
440 }
441 $url .= $query;
442
443 // Put the fragment back
444 if ( $fragment !== false ) {
445 $url .= $fragment;
446 }
447 }
448 return $url;
449}
450
474function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
477 if ( $defaultProto === PROTO_CANONICAL ) {
478 $serverUrl = $wgCanonicalServer;
479 } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
480 // Make $wgInternalServer fall back to $wgServer if not set
481 $serverUrl = $wgInternalServer;
482 } else {
483 $serverUrl = $wgServer;
484 if ( $defaultProto === PROTO_CURRENT ) {
485 $defaultProto = $wgRequest->getProtocol() . '://';
486 }
487 }
488
489 // Analyze $serverUrl to obtain its protocol
490 $bits = wfParseUrl( $serverUrl );
491 $serverHasProto = $bits && $bits['scheme'] != '';
492
493 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
494 if ( $serverHasProto ) {
495 $defaultProto = $bits['scheme'] . '://';
496 } else {
497 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
498 // This really isn't supposed to happen. Fall back to HTTP in this
499 // ridiculous case.
500 $defaultProto = PROTO_HTTP;
501 }
502 }
503
504 $defaultProtoWithoutSlashes = $defaultProto !== null ? substr( $defaultProto, 0, -2 ) : '';
505
506 if ( substr( $url, 0, 2 ) == '//' ) {
507 $url = $defaultProtoWithoutSlashes . $url;
508 } elseif ( substr( $url, 0, 1 ) == '/' ) {
509 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
510 // otherwise leave it alone.
511 if ( $serverHasProto ) {
512 $url = $serverUrl . $url;
513 } else {
514 // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
515 // user to override the port number (T67184)
516 if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
517 if ( isset( $bits['port'] ) ) {
518 throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
519 }
520 $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
521 } else {
522 $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
523 }
524 }
525 }
526
527 $bits = wfParseUrl( $url );
528
529 if ( $bits && isset( $bits['path'] ) ) {
530 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
531 return wfAssembleUrl( $bits );
532 } elseif ( $bits ) {
533 # No path to expand
534 return $url;
535 } elseif ( substr( $url, 0, 1 ) != '/' ) {
536 # URL is a relative path
537 return wfRemoveDotSegments( $url );
538 }
539
540 # Expanded URL is not valid.
541 return false;
542}
543
552function wfGetServerUrl( $proto ) {
553 $url = wfExpandUrl( '/', $proto );
554 return substr( $url, 0, -1 );
555}
556
570function wfAssembleUrl( $urlParts ) {
571 $result = '';
572
573 if ( isset( $urlParts['delimiter'] ) ) {
574 if ( isset( $urlParts['scheme'] ) ) {
575 $result .= $urlParts['scheme'];
576 }
577
578 $result .= $urlParts['delimiter'];
579 }
580
581 if ( isset( $urlParts['host'] ) ) {
582 if ( isset( $urlParts['user'] ) ) {
583 $result .= $urlParts['user'];
584 if ( isset( $urlParts['pass'] ) ) {
585 $result .= ':' . $urlParts['pass'];
586 }
587 $result .= '@';
588 }
589
590 $result .= $urlParts['host'];
591
592 if ( isset( $urlParts['port'] ) ) {
593 $result .= ':' . $urlParts['port'];
594 }
595 }
596
597 if ( isset( $urlParts['path'] ) ) {
598 $result .= $urlParts['path'];
599 }
600
601 if ( isset( $urlParts['query'] ) && $urlParts['query'] !== '' ) {
602 $result .= '?' . $urlParts['query'];
603 }
604
605 if ( isset( $urlParts['fragment'] ) ) {
606 $result .= '#' . $urlParts['fragment'];
607 }
608
609 return $result;
610}
611
624function wfRemoveDotSegments( $urlPath ) {
625 $output = '';
626 $inputOffset = 0;
627 $inputLength = strlen( $urlPath );
628
629 while ( $inputOffset < $inputLength ) {
630 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
631 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
632 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
633 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
634 $trimOutput = false;
635
636 if ( $prefixLengthTwo == './' ) {
637 # Step A, remove leading "./"
638 $inputOffset += 2;
639 } elseif ( $prefixLengthThree == '../' ) {
640 # Step A, remove leading "../"
641 $inputOffset += 3;
642 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
643 # Step B, replace leading "/.$" with "/"
644 $inputOffset += 1;
645 $urlPath[$inputOffset] = '/';
646 } elseif ( $prefixLengthThree == '/./' ) {
647 # Step B, replace leading "/./" with "/"
648 $inputOffset += 2;
649 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
650 # Step C, replace leading "/..$" with "/" and
651 # remove last path component in output
652 $inputOffset += 2;
653 $urlPath[$inputOffset] = '/';
654 $trimOutput = true;
655 } elseif ( $prefixLengthFour == '/../' ) {
656 # Step C, replace leading "/../" with "/" and
657 # remove last path component in output
658 $inputOffset += 3;
659 $trimOutput = true;
660 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
661 # Step D, remove "^.$"
662 $inputOffset += 1;
663 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
664 # Step D, remove "^..$"
665 $inputOffset += 2;
666 } else {
667 # Step E, move leading path segment to output
668 if ( $prefixLengthOne == '/' ) {
669 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
670 } else {
671 $slashPos = strpos( $urlPath, '/', $inputOffset );
672 }
673 if ( $slashPos === false ) {
674 $output .= substr( $urlPath, $inputOffset );
675 $inputOffset = $inputLength;
676 } else {
677 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
678 $inputOffset += $slashPos - $inputOffset;
679 }
680 }
681
682 if ( $trimOutput ) {
683 $slashPos = strrpos( $output, '/' );
684 if ( $slashPos === false ) {
685 $output = '';
686 } else {
687 $output = substr( $output, 0, $slashPos );
688 }
689 }
690 }
691
692 return $output;
693}
694
702function wfUrlProtocols( $includeProtocolRelative = true ) {
703 global $wgUrlProtocols;
704
705 // Cache return values separately based on $includeProtocolRelative
706 static $withProtRel = null, $withoutProtRel = null;
707 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
708 if ( $cachedValue !== null ) {
709 return $cachedValue;
710 }
711
712 // Support old-style $wgUrlProtocols strings, for backwards compatibility
713 // with LocalSettings files from 1.5
714 if ( is_array( $wgUrlProtocols ) ) {
715 $protocols = [];
716 foreach ( $wgUrlProtocols as $protocol ) {
717 // Filter out '//' if !$includeProtocolRelative
718 if ( $includeProtocolRelative || $protocol !== '//' ) {
719 $protocols[] = preg_quote( $protocol, '/' );
720 }
721 }
722
723 $retval = implode( '|', $protocols );
724 } else {
725 // Ignore $includeProtocolRelative in this case
726 // This case exists for pre-1.6 compatibility, and we can safely assume
727 // that '//' won't appear in a pre-1.6 config because protocol-relative
728 // URLs weren't supported until 1.18
729 $retval = $wgUrlProtocols;
730 }
731
732 // Cache return value
733 if ( $includeProtocolRelative ) {
734 $withProtRel = $retval;
735 } else {
736 $withoutProtRel = $retval;
737 }
738 return $retval;
739}
740
748 return wfUrlProtocols( false );
749}
750
776function wfParseUrl( $url ) {
777 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
778
779 // Protocol-relative URLs are handled really badly by parse_url(). It's so
780 // bad that the easiest way to handle them is to just prepend 'http:' and
781 // strip the protocol out later.
782 $wasRelative = substr( $url, 0, 2 ) == '//';
783 if ( $wasRelative ) {
784 $url = "http:$url";
785 }
786 $bits = parse_url( $url );
787 // parse_url() returns an array without scheme for some invalid URLs, e.g.
788 // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
789 if ( !$bits || !isset( $bits['scheme'] ) ) {
790 return false;
791 }
792
793 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
794 $bits['scheme'] = strtolower( $bits['scheme'] );
795
796 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
797 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
798 $bits['delimiter'] = '://';
799 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
800 $bits['delimiter'] = ':';
801 // parse_url detects for news: and mailto: the host part of an url as path
802 // We have to correct this wrong detection
803 if ( isset( $bits['path'] ) ) {
804 $bits['host'] = $bits['path'];
805 $bits['path'] = '';
806 }
807 } else {
808 return false;
809 }
810
811 /* Provide an empty host for eg. file:/// urls (see T30627) */
812 if ( !isset( $bits['host'] ) ) {
813 $bits['host'] = '';
814
815 // See T47069
816 if ( isset( $bits['path'] ) ) {
817 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
818 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
819 $bits['path'] = '/' . $bits['path'];
820 }
821 } else {
822 $bits['path'] = '';
823 }
824 }
825
826 // If the URL was protocol-relative, fix scheme and delimiter
827 if ( $wasRelative ) {
828 $bits['scheme'] = '';
829 $bits['delimiter'] = '//';
830 }
831 return $bits;
832}
833
844function wfExpandIRI( $url ) {
845 return preg_replace_callback(
846 '/((?:%[89A-F][0-9A-F])+)/i',
847 static function ( array $matches ) {
848 return urldecode( $matches[1] );
849 },
850 wfExpandUrl( $url )
851 );
852}
853
860function wfMatchesDomainList( $url, $domains ) {
861 $bits = wfParseUrl( $url );
862 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
863 $host = '.' . $bits['host'];
864 foreach ( (array)$domains as $domain ) {
865 $domain = '.' . $domain;
866 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
867 return true;
868 }
869 }
870 }
871 return false;
872}
873
894function wfDebug( $text, $dest = 'all', array $context = [] ) {
896
897 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
898 return;
899 }
900
901 $text = trim( $text );
902
903 if ( $wgDebugLogPrefix !== '' ) {
904 $context['prefix'] = $wgDebugLogPrefix;
905 }
906 $context['private'] = ( $dest === false || $dest === 'private' );
907
908 $logger = LoggerFactory::getInstance( 'wfDebug' );
909 $logger->debug( $text, $context );
910}
911
917 static $cache;
918 if ( $cache !== null ) {
919 return $cache;
920 }
921 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
922 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
923 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
924 || MW_ENTRY_POINT === 'load'
925 ) {
926 $cache = true;
927 } else {
928 $cache = false;
929 }
930 return $cache;
931}
932
958function wfDebugLog(
959 $logGroup, $text, $dest = 'all', array $context = []
960) {
961 $text = trim( $text );
962
963 $logger = LoggerFactory::getInstance( $logGroup );
964 $context['private'] = ( $dest === false || $dest === 'private' );
965 $logger->info( $text, $context );
966}
967
976function wfLogDBError( $text, array $context = [] ) {
977 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
978 $logger->error( trim( $text ), $context );
979}
980
997function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
998 if ( !is_string( $version ) && $version !== false ) {
999 throw new InvalidArgumentException(
1000 "MediaWiki version must either be a string or false. " .
1001 "Example valid version: '1.33'"
1002 );
1003 }
1004
1005 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1006}
1007
1028function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
1029 MWDebug::deprecatedMsg( $msg, $version, $component,
1030 $callerOffset === false ? false : $callerOffset + 1 );
1031}
1032
1043function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1044 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1045}
1046
1056function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1057 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1058}
1059
1065 $context = RequestContext::getMain();
1066
1067 $profiler = Profiler::instance();
1068 $profiler->setContext( $context );
1069 $profiler->logData();
1070
1071 // Send out any buffered statsd metrics as needed
1072 MediaWiki::emitBufferedStatsdData(
1073 MediaWikiServices::getInstance()->getStatsdDataFactory(),
1074 $context->getConfig()
1075 );
1076}
1077
1088function wfIncrStats( $key, $count = 1 ) {
1089 wfDeprecated( __FUNCTION__, '1.36' );
1090 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1091 $stats->updateCount( $key, $count );
1092}
1093
1099function wfReadOnly() {
1100 return MediaWikiServices::getInstance()->getReadOnlyMode()
1101 ->isReadOnly();
1102}
1103
1113 return MediaWikiServices::getInstance()->getReadOnlyMode()
1114 ->getReason();
1115}
1116
1132function wfGetLangObj( $langcode = false ) {
1133 # Identify which language to get or create a language object for.
1134 # Using is_object here due to Stub objects.
1135 if ( is_object( $langcode ) ) {
1136 # Great, we already have the object (hopefully)!
1137 return $langcode;
1138 }
1139
1140 global $wgLanguageCode;
1141 $services = MediaWikiServices::getInstance();
1142 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1143 # $langcode is the language code of the wikis content language object.
1144 # or it is a boolean and value is true
1145 return $services->getContentLanguage();
1146 }
1147
1148 global $wgLang;
1149 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1150 # $langcode is the language code of user language object.
1151 # or it was a boolean and value is false
1152 return $wgLang;
1153 }
1154
1155 $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1156 if ( in_array( $langcode, $validCodes ) ) {
1157 # $langcode corresponds to a valid language.
1158 return $services->getLanguageFactory()->getLanguage( $langcode );
1159 }
1160
1161 # $langcode is a string, but not a valid language code; use content language.
1162 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1163 return $services->getContentLanguage();
1164}
1165
1182function wfMessage( $key, ...$params ) {
1183 $message = new Message( $key );
1184
1185 // We call Message::params() to reduce code duplication
1186 if ( $params ) {
1187 $message->params( ...$params );
1188 }
1189
1190 return $message;
1191}
1192
1205function wfMessageFallback( ...$keys ) {
1207}
1208
1217function wfMsgReplaceArgs( $message, $args ) {
1218 # Fix windows line-endings
1219 # Some messages are split with explode("\n", $msg)
1220 $message = str_replace( "\r", '', $message );
1221
1222 // Replace arguments
1223 if ( is_array( $args ) && $args ) {
1224 if ( is_array( $args[0] ) ) {
1225 $args = array_values( $args[0] );
1226 }
1227 $replacementKeys = [];
1228 foreach ( $args as $n => $param ) {
1229 $replacementKeys['$' . ( $n + 1 )] = $param;
1230 }
1231 $message = strtr( $message, $replacementKeys );
1232 }
1233
1234 return $message;
1235}
1236
1245function wfHostname() {
1246 // Hostname overriding
1247 global $wgOverrideHostname;
1248 if ( $wgOverrideHostname !== false ) {
1249 return $wgOverrideHostname;
1250 }
1251
1252 return php_uname( 'n' ) ?: 'unknown';
1253}
1254
1265function wfReportTime( $nonce = null ) {
1266 global $wgShowHostnames;
1267
1268 $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1269 // seconds to milliseconds
1270 $responseTime = round( $elapsed * 1000 );
1271 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1272 if ( $wgShowHostnames ) {
1273 $reportVars['wgHostname'] = wfHostname();
1274 }
1275
1276 return (
1279 $nonce
1280 )
1281 );
1282}
1283
1294function wfDebugBacktrace( $limit = 0 ) {
1295 static $disabled = null;
1296
1297 if ( $disabled === null ) {
1298 $disabled = !function_exists( 'debug_backtrace' );
1299 if ( $disabled ) {
1300 wfDebug( "debug_backtrace() is disabled" );
1301 }
1302 }
1303 if ( $disabled ) {
1304 return [];
1305 }
1306
1307 if ( $limit ) {
1308 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1309 } else {
1310 return array_slice( debug_backtrace(), 1 );
1311 }
1312}
1313
1322function wfBacktrace( $raw = null ) {
1323 global $wgCommandLineMode;
1324
1325 if ( $raw === null ) {
1326 $raw = $wgCommandLineMode;
1327 }
1328
1329 if ( $raw ) {
1330 $frameFormat = "%s line %s calls %s()\n";
1331 $traceFormat = "%s";
1332 } else {
1333 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1334 $traceFormat = "<ul>\n%s</ul>\n";
1335 }
1336
1337 $frames = array_map( static function ( $frame ) use ( $frameFormat ) {
1338 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1339 $line = $frame['line'] ?? '-';
1340 $call = $frame['function'];
1341 if ( !empty( $frame['class'] ) ) {
1342 $call = $frame['class'] . $frame['type'] . $call;
1343 }
1344 return sprintf( $frameFormat, $file, $line, $call );
1345 }, wfDebugBacktrace() );
1346
1347 return sprintf( $traceFormat, implode( '', $frames ) );
1348}
1349
1359function wfGetCaller( $level = 2 ) {
1360 $backtrace = wfDebugBacktrace( $level + 1 );
1361 if ( isset( $backtrace[$level] ) ) {
1362 return wfFormatStackFrame( $backtrace[$level] );
1363 } else {
1364 return 'unknown';
1365 }
1366}
1367
1375function wfGetAllCallers( $limit = 3 ) {
1376 $trace = array_reverse( wfDebugBacktrace() );
1377 if ( !$limit || $limit > count( $trace ) - 1 ) {
1378 $limit = count( $trace ) - 1;
1379 }
1380 $trace = array_slice( $trace, -$limit - 1, $limit );
1381 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1382}
1383
1390function wfFormatStackFrame( $frame ) {
1391 if ( !isset( $frame['function'] ) ) {
1392 return 'NO_FUNCTION_GIVEN';
1393 }
1394 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1395 $frame['class'] . $frame['type'] . $frame['function'] :
1396 $frame['function'];
1397}
1398
1399/* Some generic result counters, pulled out of SearchEngine */
1400
1408function wfShowingResults( $offset, $limit ) {
1409 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1410}
1411
1421function wfClientAcceptsGzip( $force = false ) {
1422 static $result = null;
1423 if ( $result === null || $force ) {
1424 $result = false;
1425 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1426 # @todo FIXME: We may want to disallow some broken browsers
1427 $m = [];
1428 if ( preg_match(
1429 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1430 $_SERVER['HTTP_ACCEPT_ENCODING'],
1431 $m
1432 )
1433 ) {
1434 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1435 return $result;
1436 }
1437 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1438 $result = true;
1439 }
1440 }
1441 }
1442 return $result;
1443}
1444
1455function wfEscapeWikiText( $text ) {
1456 global $wgEnableMagicLinks;
1457 static $repl = null, $repl2 = null;
1458 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1459 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1460 // in those situations
1461 $repl = [
1462 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1463 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1464 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1465 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1466 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1467 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1468 "\n " => "\n&#32;", "\r " => "\r&#32;",
1469 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1470 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1471 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1472 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1473 '__' => '_&#95;', '://' => '&#58;//',
1474 ];
1475
1476 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1477 // We have to catch everything "\s" matches in PCRE
1478 foreach ( $magicLinks as $magic ) {
1479 $repl["$magic "] = "$magic&#32;";
1480 $repl["$magic\t"] = "$magic&#9;";
1481 $repl["$magic\r"] = "$magic&#13;";
1482 $repl["$magic\n"] = "$magic&#10;";
1483 $repl["$magic\f"] = "$magic&#12;";
1484 }
1485
1486 // And handle protocols that don't use "://"
1487 global $wgUrlProtocols;
1488 $repl2 = [];
1489 foreach ( $wgUrlProtocols as $prot ) {
1490 if ( substr( $prot, -1 ) === ':' ) {
1491 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1492 }
1493 }
1494 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1495 }
1496 $text = substr( strtr( "\n$text", $repl ), 1 );
1497 $text = preg_replace( $repl2, '$1&#58;', $text );
1498 return $text;
1499}
1500
1511function wfSetVar( &$dest, $source, $force = false ) {
1512 $temp = $dest;
1513 if ( $source !== null || $force ) {
1514 $dest = $source;
1515 }
1516 return $temp;
1517}
1518
1528function wfSetBit( &$dest, $bit, $state = true ) {
1529 $temp = (bool)( $dest & $bit );
1530 if ( $state !== null ) {
1531 if ( $state ) {
1532 $dest |= $bit;
1533 } else {
1534 $dest &= ~$bit;
1535 }
1536 }
1537 return $temp;
1538}
1539
1546function wfVarDump( $var ) {
1547 global $wgOut;
1548 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1549 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1550 print $s;
1551 } else {
1552 $wgOut->addHTML( $s );
1553 }
1554}
1555
1563function wfHttpError( $code, $label, $desc ) {
1564 global $wgOut;
1565 HttpStatus::header( $code );
1566 if ( $wgOut ) {
1567 $wgOut->disable();
1568 $wgOut->sendCacheControl();
1569 }
1570
1571 MediaWiki\HeaderCallback::warnIfHeadersSent();
1572 header( 'Content-type: text/html; charset=utf-8' );
1573 ob_start();
1574 print '<!DOCTYPE html>' .
1575 '<html><head><title>' .
1576 htmlspecialchars( $label ) .
1577 '</title></head><body><h1>' .
1578 htmlspecialchars( $label ) .
1579 '</h1><p>' .
1580 nl2br( htmlspecialchars( $desc ) ) .
1581 "</p></body></html>\n";
1582 header( 'Content-Length: ' . ob_get_length() );
1583 ob_end_flush();
1584}
1585
1603function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1604 while ( $status = ob_get_status() ) {
1605 if ( isset( $status['flags'] ) ) {
1606 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1607 $deleteable = ( $status['flags'] & $flags ) === $flags;
1608 } elseif ( isset( $status['del'] ) ) {
1609 $deleteable = $status['del'];
1610 } else {
1611 // Guess that any PHP-internal setting can't be removed.
1612 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1613 }
1614 if ( !$deleteable ) {
1615 // Give up, and hope the result doesn't break
1616 // output behavior.
1617 break;
1618 }
1619 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1620 // Unit testing barrier to prevent this function from breaking PHPUnit.
1621 break;
1622 }
1623 if ( !ob_end_clean() ) {
1624 // Could not remove output buffer handler; abort now
1625 // to avoid getting in some kind of infinite loop.
1626 break;
1627 }
1628 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1629 // Reset the 'Content-Encoding' field set by this handler
1630 // so we can start fresh.
1631 header_remove( 'Content-Encoding' );
1632 break;
1633 }
1634 }
1635}
1636
1652 wfDeprecated( __FUNCTION__, '1.36' );
1653 wfResetOutputBuffers( false );
1654}
1655
1668function mimeTypeMatch( $type, $avail ) {
1669 if ( array_key_exists( $type, $avail ) ) {
1670 return $type;
1671 } else {
1672 $mainType = explode( '/', $type )[0];
1673 if ( array_key_exists( "$mainType/*", $avail ) ) {
1674 return "$mainType/*";
1675 } elseif ( array_key_exists( '*/*', $avail ) ) {
1676 return '*/*';
1677 } else {
1678 return null;
1679 }
1680 }
1681}
1682
1691function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1692 $ret = MWTimestamp::convert( $outputtype, $ts );
1693 if ( $ret === false ) {
1694 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1695 }
1696 return $ret;
1697}
1698
1707function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1708 if ( $ts === null ) {
1709 return null;
1710 } else {
1711 return wfTimestamp( $outputtype, $ts );
1712 }
1713}
1714
1720function wfTimestampNow() {
1721 return MWTimestamp::now( TS_MW );
1722}
1723
1729function wfIsWindows() {
1730 return PHP_OS_FAMILY === 'Windows';
1731}
1732
1739function wfIsCLI() {
1740 return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1741}
1742
1754function wfTempDir() {
1755 global $wgTmpDirectory;
1756
1757 if ( $wgTmpDirectory !== false ) {
1758 return $wgTmpDirectory;
1759 }
1760
1761 return TempFSFile::getUsableTempDirectory();
1762}
1763
1773function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1774 global $wgDirectoryMode;
1775
1776 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1777 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1778 }
1779
1780 if ( $caller !== null ) {
1781 wfDebug( "$caller: called wfMkdirParents($dir)" );
1782 }
1783
1784 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1785 return true;
1786 }
1787
1788 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1789
1790 if ( $mode === null ) {
1791 $mode = $wgDirectoryMode;
1792 }
1793
1794 // Turn off the normal warning, we're doing our own below
1795 AtEase::suppressWarnings();
1796 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1797 AtEase::restoreWarnings();
1798
1799 if ( !$ok ) {
1800 // directory may have been created on another request since we last checked
1801 if ( is_dir( $dir ) ) {
1802 return true;
1803 }
1804
1805 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1806 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1807 }
1808 return $ok;
1809}
1810
1816function wfRecursiveRemoveDir( $dir ) {
1817 wfDebug( __FUNCTION__ . "( $dir )" );
1818 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1819 if ( is_dir( $dir ) ) {
1820 $objects = scandir( $dir );
1821 foreach ( $objects as $object ) {
1822 if ( $object != "." && $object != ".." ) {
1823 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1824 wfRecursiveRemoveDir( $dir . '/' . $object );
1825 } else {
1826 unlink( $dir . '/' . $object );
1827 }
1828 }
1829 }
1830 reset( $objects );
1831 rmdir( $dir );
1832 }
1833}
1834
1841function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1842 $accForFormat = $acc >= 0 ? $acc : 0;
1843 $ret = sprintf( "%.{$accForFormat}f", $nr );
1844 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1845}
1846
1870function wfIniGetBool( $setting ) {
1871 return wfStringToBool( ini_get( $setting ) );
1872}
1873
1886function wfStringToBool( $val ) {
1887 $val = strtolower( $val );
1888 // 'on' and 'true' can't have whitespace around them, but '1' can.
1889 return $val == 'on'
1890 || $val == 'true'
1891 || $val == 'yes'
1892 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1893}
1894
1907function wfEscapeShellArg( ...$args ) {
1908 return Shell::escape( ...$args );
1909}
1910
1935function wfShellExec( $cmd, &$retval = null, $environ = [],
1936 $limits = [], $options = []
1937) {
1938 if ( Shell::isDisabled() ) {
1939 $retval = 1;
1940 // Backwards compatibility be upon us...
1941 return 'Unable to run external programs, proc_open() is disabled.';
1942 }
1943
1944 if ( is_array( $cmd ) ) {
1945 $cmd = Shell::escape( $cmd );
1946 }
1947
1948 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
1949 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
1950
1951 try {
1952 $result = Shell::command( [] )
1953 ->unsafeParams( (array)$cmd )
1954 ->environment( $environ )
1955 ->limits( $limits )
1956 ->includeStderr( $includeStderr )
1957 ->profileMethod( $profileMethod )
1958 // For b/c
1959 ->restrict( Shell::RESTRICT_NONE )
1960 ->execute();
1961 } catch ( ProcOpenError $ex ) {
1962 $retval = -1;
1963 return '';
1964 }
1965
1966 $retval = $result->getExitCode();
1967
1968 return $result->getStdout();
1969}
1970
1988function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
1989 return wfShellExec( $cmd, $retval, $environ, $limits,
1990 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
1991}
1992
2008function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2009 global $wgPhpCli;
2010 // Give site config file a chance to run the script in a wrapper.
2011 // The caller may likely want to call wfBasename() on $script.
2012 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
2013 $cmd = [ $options['php'] ?? $wgPhpCli ];
2014 if ( isset( $options['wrapper'] ) ) {
2015 $cmd[] = $options['wrapper'];
2016 }
2017 $cmd[] = $script;
2018 // Escape each parameter for shell
2019 return Shell::escape( array_merge( $cmd, $parameters ) );
2020}
2021
2033function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2034 global $wgDiff3;
2035
2036 # This check may also protect against code injection in
2037 # case of broken installations.
2038 AtEase::suppressWarnings();
2039 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2040 AtEase::restoreWarnings();
2041
2042 if ( !$haveDiff3 ) {
2043 wfDebug( "diff3 not found" );
2044 return false;
2045 }
2046
2047 # Make temporary files
2048 $td = wfTempDir();
2049 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2050 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2051 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2052
2053 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2054 # a newline character. To avoid this, we normalize the trailing whitespace before
2055 # creating the diff.
2056
2057 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2058 fclose( $oldtextFile );
2059 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2060 fclose( $mytextFile );
2061 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2062 fclose( $yourtextFile );
2063
2064 # Check for a conflict
2065 $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2066 $oldtextName, $yourtextName );
2067 $handle = popen( $cmd, 'r' );
2068
2069 $mergeAttemptResult = '';
2070 do {
2071 $data = fread( $handle, 8192 );
2072 if ( strlen( $data ) == 0 ) {
2073 break;
2074 }
2075 $mergeAttemptResult .= $data;
2076 } while ( true );
2077 pclose( $handle );
2078
2079 $conflict = $mergeAttemptResult !== '';
2080
2081 # Merge differences
2082 $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2083 $oldtextName, $yourtextName );
2084 $handle = popen( $cmd, 'r' );
2085 $result = '';
2086 do {
2087 $data = fread( $handle, 8192 );
2088 if ( strlen( $data ) == 0 ) {
2089 break;
2090 }
2091 $result .= $data;
2092 } while ( true );
2093 pclose( $handle );
2094 unlink( $mytextName );
2095 unlink( $oldtextName );
2096 unlink( $yourtextName );
2097
2098 if ( $result === '' && $old !== '' && !$conflict ) {
2099 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2100 $conflict = true;
2101 }
2102 return !$conflict;
2103}
2104
2117function wfBaseName( $path, $suffix = '' ) {
2118 if ( $suffix == '' ) {
2119 $encSuffix = '';
2120 } else {
2121 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2122 }
2123
2124 $matches = [];
2125 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2126 return $matches[1];
2127 } else {
2128 return '';
2129 }
2130}
2131
2141function wfRelativePath( $path, $from ) {
2142 // Normalize mixed input on Windows...
2143 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2144 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2145
2146 // Trim trailing slashes -- fix for drive root
2147 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2148 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2149
2150 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2151 $against = explode( DIRECTORY_SEPARATOR, $from );
2152
2153 if ( $pieces[0] !== $against[0] ) {
2154 // Non-matching Windows drive letters?
2155 // Return a full path.
2156 return $path;
2157 }
2158
2159 // Trim off common prefix
2160 while ( count( $pieces ) && count( $against )
2161 && $pieces[0] == $against[0] ) {
2162 array_shift( $pieces );
2163 array_shift( $against );
2164 }
2165
2166 // relative dots to bump us to the parent
2167 while ( count( $against ) ) {
2168 array_unshift( $pieces, '..' );
2169 array_shift( $against );
2170 }
2171
2172 $pieces[] = wfBaseName( $path );
2173
2174 return implode( DIRECTORY_SEPARATOR, $pieces );
2175}
2176
2184function wfWikiID() {
2185 global $wgDBprefix, $wgDBname;
2186
2187 if ( $wgDBprefix ) {
2188 return "$wgDBname-$wgDBprefix";
2189 } else {
2190 return $wgDBname;
2191 }
2192}
2193
2225function wfGetDB( $db, $groups = [], $wiki = false ) {
2226 if ( $wiki === false ) {
2227 return MediaWikiServices::getInstance()
2228 ->getDBLoadBalancer()
2229 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2230 } else {
2231 return MediaWikiServices::getInstance()
2232 ->getDBLoadBalancerFactory()
2233 ->getMainLB( $wiki )
2234 ->getMaintenanceConnectionRef( $db, $groups, $wiki );
2235 }
2236}
2237
2248function wfGetLB( $wiki = false ) {
2249 wfDeprecated( __FUNCTION__, '1.27' );
2250 if ( $wiki === false ) {
2251 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
2252 return MediaWikiServices::getInstance()->getDBLoadBalancer();
2253 } else {
2254 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2255 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
2256 return $factory->getMainLB( $wiki );
2257 }
2258}
2259
2267function wfFindFile( $title, $options = [] ) {
2268 wfDeprecated( __FUNCTION__, '1.34' );
2269 return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2270}
2271
2280function wfLocalFile( $title ) {
2281 wfDeprecated( __FUNCTION__, '1.34' );
2282 return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2283}
2284
2292 global $wgMiserMode;
2293 return $wgMiserMode
2294 || ( SiteStats::pages() > 100000
2295 && SiteStats::edits() > 1000000
2296 && SiteStats::users() > 10000 );
2297}
2298
2307function wfScript( $script = 'index' ) {
2309 if ( $script === 'index' ) {
2310 return $wgScript;
2311 } elseif ( $script === 'load' ) {
2312 return $wgLoadScript;
2313 } else {
2314 return "{$wgScriptPath}/{$script}.php";
2315 }
2316}
2317
2324function wfGetScriptUrl() {
2325 wfDeprecated( __FUNCTION__, '1.35' );
2326 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2327 /* as it was called, minus the query string.
2328 *
2329 * Some sites use Apache rewrite rules to handle subdomains,
2330 * and have PHP set up in a weird way that causes PHP_SELF
2331 * to contain the rewritten URL instead of the one that the
2332 * outside world sees.
2333 *
2334 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2335 * provides containing the "before" URL.
2336 */
2337 return $_SERVER['SCRIPT_NAME'];
2338 } else {
2339 return $_SERVER['URL'];
2340 }
2341}
2342
2350function wfBoolToStr( $value ) {
2351 return $value ? 'true' : 'false';
2352}
2353
2359function wfGetNull() {
2360 return wfIsWindows() ? 'NUL' : '/dev/null';
2361}
2362
2372 global $wgIllegalFileChars;
2373 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2374 $name = preg_replace(
2375 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2376 '-',
2377 $name
2378 );
2379 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2380 $name = wfBaseName( $name );
2381 return $name;
2382}
2383
2390function wfMemoryLimit( $newLimit ) {
2391 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2392 // If the INI config is already unlimited, there is nothing larger
2393 if ( $oldLimit != -1 ) {
2394 $newLimit = wfShorthandToInteger( $newLimit );
2395 if ( $newLimit == -1 ) {
2396 wfDebug( "Removing PHP's memory limit" );
2397 Wikimedia\suppressWarnings();
2398 ini_set( 'memory_limit', $newLimit );
2399 Wikimedia\restoreWarnings();
2400 } elseif ( $newLimit > $oldLimit ) {
2401 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2402 Wikimedia\suppressWarnings();
2403 ini_set( 'memory_limit', $newLimit );
2404 Wikimedia\restoreWarnings();
2405 }
2406 }
2407}
2408
2417
2418 $timeout = RequestTimeout::singleton();
2419 $timeLimit = $timeout->getWallTimeLimit();
2420 if ( $timeLimit !== INF ) {
2421 // RequestTimeout library is active
2422 if ( $wgTransactionalTimeLimit > $timeLimit ) {
2423 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2424 }
2425 } else {
2426 // Fallback case, likely $wgRequestTimeLimit === null
2427 $timeLimit = (int)ini_get( 'max_execution_time' );
2428 // Note that CLI scripts use 0
2429 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2430 $timeout->setWallTimeLimit( $wgTransactionalTimeLimit );
2431 }
2432 }
2433 ignore_user_abort( true ); // ignore client disconnects
2434
2435 return $timeLimit;
2436}
2437
2445function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2446 $string = trim( $string ?? '' );
2447 if ( $string === '' ) {
2448 return $default;
2449 }
2450 $last = $string[strlen( $string ) - 1];
2451 $val = intval( $string );
2452 switch ( $last ) {
2453 case 'g':
2454 case 'G':
2455 $val *= 1024;
2456 // break intentionally missing
2457 case 'm':
2458 case 'M':
2459 $val *= 1024;
2460 // break intentionally missing
2461 case 'k':
2462 case 'K':
2463 $val *= 1024;
2464 }
2465
2466 return $val;
2467}
2468
2476function wfGetCache( $cacheType ) {
2477 return ObjectCache::getInstance( $cacheType );
2478}
2479
2486function wfGetMainCache() {
2487 return ObjectCache::getLocalClusterInstance();
2488}
2489
2504function wfUnpack( $format, $data, $length = false ) {
2505 if ( $length !== false ) {
2506 $realLen = strlen( $data );
2507 if ( $realLen < $length ) {
2508 throw new MWException( "Tried to use wfUnpack on a "
2509 . "string of length $realLen, but needed one "
2510 . "of at least length $length."
2511 );
2512 }
2513 }
2514
2515 Wikimedia\suppressWarnings();
2516 $result = unpack( $format, $data );
2517 Wikimedia\restoreWarnings();
2518
2519 if ( $result === false ) {
2520 // If it cannot extract the packed data.
2521 throw new MWException( "unpack could not unpack binary data" );
2522 }
2523 return $result;
2524}
2525
2535function wfCanIPUseHTTPS( $ip ) {
2536 wfDeprecated( __FUNCTION__, '1.37' );
2537 return true;
2538}
2539
2547function wfIsInfinity( $str ) {
2548 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2549 return in_array( $str, ExpiryDef::INFINITY_VALS );
2550}
2551
2566function wfThumbIsStandard( File $file, array $params ) {
2568
2569 $multipliers = [ 1 ];
2570 if ( $wgResponsiveImages ) {
2571 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2572 // @see Linker::processResponsiveImages
2573 $multipliers[] = 1.5;
2574 $multipliers[] = 2;
2575 }
2576
2577 $handler = $file->getHandler();
2578 if ( !$handler || !isset( $params['width'] ) ) {
2579 return false;
2580 }
2581
2582 $basicParams = [];
2583 if ( isset( $params['page'] ) ) {
2584 $basicParams['page'] = $params['page'];
2585 }
2586
2587 $thumbLimits = [];
2588 $imageLimits = [];
2589 // Expand limits to account for multipliers
2590 foreach ( $multipliers as $multiplier ) {
2591 $thumbLimits = array_merge( $thumbLimits, array_map(
2592 static function ( $width ) use ( $multiplier ) {
2593 return round( $width * $multiplier );
2594 }, $wgThumbLimits )
2595 );
2596 $imageLimits = array_merge( $imageLimits, array_map(
2597 static function ( $pair ) use ( $multiplier ) {
2598 return [
2599 round( $pair[0] * $multiplier ),
2600 round( $pair[1] * $multiplier ),
2601 ];
2602 }, $wgImageLimits )
2603 );
2604 }
2605
2606 // Check if the width matches one of $wgThumbLimits
2607 if ( in_array( $params['width'], $thumbLimits ) ) {
2608 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2609 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2610 $handler->normaliseParams( $file, $normalParams );
2611 } else {
2612 // If not, then check if the width matchs one of $wgImageLimits
2613 $match = false;
2614 foreach ( $imageLimits as $pair ) {
2615 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2616 // Decide whether the thumbnail should be scaled on width or height.
2617 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2618 $handler->normaliseParams( $file, $normalParams );
2619 // Check if this standard thumbnail size maps to the given width
2620 if ( $normalParams['width'] == $params['width'] ) {
2621 $match = true;
2622 break;
2623 }
2624 }
2625 if ( !$match ) {
2626 return false; // not standard for description pages
2627 }
2628 }
2629
2630 // Check that the given values for non-page, non-width, params are just defaults
2631 foreach ( $params as $key => $value ) {
2632 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2633 return false;
2634 }
2635 }
2636
2637 return true;
2638}
2639
2652function wfArrayPlus2d( array $baseArray, array $newValues ) {
2653 // First merge items that are in both arrays
2654 foreach ( $baseArray as $name => &$groupVal ) {
2655 if ( isset( $newValues[$name] ) ) {
2656 $groupVal += $newValues[$name];
2657 }
2658 }
2659 // Now add items that didn't exist yet
2660 $baseArray += $newValues;
2661
2662 return $baseArray;
2663}
$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:196
const PROTO_HTTPS
Definition Defines.php:193
const PROTO_CURRENT
Definition Defines.php:195
const PROTO_INTERNAL
Definition Defines.php:197
const PROTO_HTTP
Definition Defines.php:192
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)
Version of escapeshellarg() that works better on Windows.
wfIncrStats( $key, $count=1)
Increment a statistics counter.
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.
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...
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
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...
wfArrayDiff2_cmp( $a, $b)
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?
mimeTypeMatch( $type, $avail)
Checks if a given MIME type matches any of the keys in the given array.
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 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.
$wgRequest
Definition Setup.php:702
$wgOut
Definition Setup.php:836
$wgLang
Definition Setup.php:831
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:66
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
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:138
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition Message.php:448
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