MediaWiki REL1_35
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\WrappedString;
35
46function wfLoadExtension( $ext, $path = null ) {
47 if ( !$path ) {
49 $path = "$wgExtensionDirectory/$ext/extension.json";
50 }
51 ExtensionRegistry::getInstance()->queue( $path );
52}
53
67function wfLoadExtensions( array $exts ) {
69 $registry = ExtensionRegistry::getInstance();
70 foreach ( $exts as $ext ) {
71 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
72 }
73}
74
83function wfLoadSkin( $skin, $path = null ) {
84 if ( !$path ) {
85 global $wgStyleDirectory;
86 $path = "$wgStyleDirectory/$skin/skin.json";
87 }
88 ExtensionRegistry::getInstance()->queue( $path );
89}
90
98function wfLoadSkins( array $skins ) {
99 global $wgStyleDirectory;
100 $registry = ExtensionRegistry::getInstance();
101 foreach ( $skins as $skin ) {
102 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
103 }
104}
105
112function wfArrayDiff2( $a, $b ) {
113 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
114}
115
121function wfArrayDiff2_cmp( $a, $b ) {
122 if ( is_string( $a ) && is_string( $b ) ) {
123 return strcmp( $a, $b );
124 } elseif ( count( $a ) !== count( $b ) ) {
125 return count( $a ) <=> count( $b );
126 } else {
127 reset( $a );
128 reset( $b );
129 while ( key( $a ) !== null && key( $b ) !== null ) {
130 $valueA = current( $a );
131 $valueB = current( $b );
132 $cmp = strcmp( $valueA, $valueB );
133 if ( $cmp !== 0 ) {
134 return $cmp;
135 }
136 next( $a );
137 next( $b );
138 }
139 return 0;
140 }
141}
142
152function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
153 if ( $changed === null ) {
154 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
155 }
156 if ( $default[$key] !== $value ) {
157 $changed[$key] = $value;
158 }
159}
160
180function wfMergeErrorArrays( ...$args ) {
181 $out = [];
182 foreach ( $args as $errors ) {
183 foreach ( $errors as $params ) {
184 $originalParams = $params;
185 if ( $params[0] instanceof MessageSpecifier ) {
186 $msg = $params[0];
187 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
188 }
189 # @todo FIXME: Sometimes get nested arrays for $params,
190 # which leads to E_NOTICEs
191 $spec = implode( "\t", $params );
192 $out[$spec] = $originalParams;
193 }
194 }
195 return array_values( $out );
196}
197
206function wfArrayInsertAfter( array $array, array $insert, $after ) {
207 // Find the offset of the element to insert after.
208 $keys = array_keys( $array );
209 $offsetByKey = array_flip( $keys );
210
211 $offset = $offsetByKey[$after];
212
213 // Insert at the specified offset
214 $before = array_slice( $array, 0, $offset + 1, true );
215 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
216
217 $output = $before + $insert + $after;
218
219 return $output;
220}
221
229function wfObjectToArray( $objOrArray, $recursive = true ) {
230 $array = [];
231 if ( is_object( $objOrArray ) ) {
232 $objOrArray = get_object_vars( $objOrArray );
233 }
234 foreach ( $objOrArray as $key => $value ) {
235 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
236 $value = wfObjectToArray( $value );
237 }
238
239 $array[$key] = $value;
240 }
241
242 return $array;
243}
244
255function wfRandom() {
256 // The maximum random value is "only" 2^31-1, so get two random
257 // values to reduce the chance of dupes
258 $max = mt_getrandmax() + 1;
259 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
260 return $rand;
261}
262
273function wfRandomString( $length = 32 ) {
274 $str = '';
275 for ( $n = 0; $n < $length; $n += 7 ) {
276 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
277 }
278 return substr( $str, 0, $length );
279}
280
308function wfUrlencode( $s ) {
309 static $needle;
310
311 if ( $s === null ) {
312 // Reset $needle for testing.
313 $needle = null;
314 return '';
315 }
316
317 if ( $needle === null ) {
318 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
319 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
320 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
321 ) {
322 $needle[] = '%3A';
323 }
324 }
325
326 $s = urlencode( $s );
327 $s = str_ireplace(
328 $needle,
329 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
330 $s
331 );
332
333 return $s;
334}
335
346function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
347 if ( $array2 !== null ) {
348 $array1 += $array2;
349 }
350
351 $cgi = '';
352 foreach ( $array1 as $key => $value ) {
353 if ( $value !== null && $value !== false ) {
354 if ( $cgi != '' ) {
355 $cgi .= '&';
356 }
357 if ( $prefix !== '' ) {
358 $key = $prefix . "[$key]";
359 }
360 if ( is_array( $value ) ) {
361 $firstTime = true;
362 foreach ( $value as $k => $v ) {
363 $cgi .= $firstTime ? '' : '&';
364 if ( is_array( $v ) ) {
365 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
366 } else {
367 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
368 }
369 $firstTime = false;
370 }
371 } else {
372 if ( is_object( $value ) ) {
373 $value = $value->__toString();
374 }
375 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
376 }
377 }
378 }
379 return $cgi;
380}
381
391function wfCgiToArray( $query ) {
392 if ( isset( $query[0] ) && $query[0] == '?' ) {
393 $query = substr( $query, 1 );
394 }
395 $bits = explode( '&', $query );
396 $ret = [];
397 foreach ( $bits as $bit ) {
398 if ( $bit === '' ) {
399 continue;
400 }
401 if ( strpos( $bit, '=' ) === false ) {
402 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
403 $key = $bit;
404 $value = '';
405 } else {
406 list( $key, $value ) = explode( '=', $bit );
407 }
408 $key = urldecode( $key );
409 $value = urldecode( $value );
410 if ( strpos( $key, '[' ) !== false ) {
411 $keys = array_reverse( explode( '[', $key ) );
412 $key = array_pop( $keys );
413 $temp = $value;
414 foreach ( $keys as $k ) {
415 $k = substr( $k, 0, -1 );
416 $temp = [ $k => $temp ];
417 }
418 if ( isset( $ret[$key] ) ) {
419 $ret[$key] = array_merge( $ret[$key], $temp );
420 } else {
421 $ret[$key] = $temp;
422 }
423 } else {
424 $ret[$key] = $value;
425 }
426 }
427 return $ret;
428}
429
438function wfAppendQuery( $url, $query ) {
439 if ( is_array( $query ) ) {
440 $query = wfArrayToCgi( $query );
441 }
442 if ( $query != '' ) {
443 // Remove the fragment, if there is one
444 $fragment = false;
445 $hashPos = strpos( $url, '#' );
446 if ( $hashPos !== false ) {
447 $fragment = substr( $url, $hashPos );
448 $url = substr( $url, 0, $hashPos );
449 }
450
451 // Add parameter
452 if ( strpos( $url, '?' ) === false ) {
453 $url .= '?';
454 } else {
455 $url .= '&';
456 }
457 $url .= $query;
458
459 // Put the fragment back
460 if ( $fragment !== false ) {
461 $url .= $fragment;
462 }
463 }
464 return $url;
465}
466
490function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
493 if ( $defaultProto === PROTO_CANONICAL ) {
494 $serverUrl = $wgCanonicalServer;
495 } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
496 // Make $wgInternalServer fall back to $wgServer if not set
497 $serverUrl = $wgInternalServer;
498 } else {
499 $serverUrl = $wgServer;
500 if ( $defaultProto === PROTO_CURRENT ) {
501 $defaultProto = $wgRequest->getProtocol() . '://';
502 }
503 }
504
505 // Analyze $serverUrl to obtain its protocol
506 $bits = wfParseUrl( $serverUrl );
507 $serverHasProto = $bits && $bits['scheme'] != '';
508
509 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
510 if ( $serverHasProto ) {
511 $defaultProto = $bits['scheme'] . '://';
512 } else {
513 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
514 // This really isn't supposed to happen. Fall back to HTTP in this
515 // ridiculous case.
516 $defaultProto = PROTO_HTTP;
517 }
518 }
519
520 $defaultProtoWithoutSlashes = $defaultProto !== null ? substr( $defaultProto, 0, -2 ) : '';
521
522 if ( substr( $url, 0, 2 ) == '//' ) {
523 $url = $defaultProtoWithoutSlashes . $url;
524 } elseif ( substr( $url, 0, 1 ) == '/' ) {
525 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
526 // otherwise leave it alone.
527 if ( $serverHasProto ) {
528 $url = $serverUrl . $url;
529 } else {
530 // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
531 // user to override the port number (T67184)
532 if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
533 if ( isset( $bits['port'] ) ) {
534 throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
535 }
536 $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
537 } else {
538 $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
539 }
540 }
541 }
542
543 $bits = wfParseUrl( $url );
544
545 if ( $bits && isset( $bits['path'] ) ) {
546 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
547 return wfAssembleUrl( $bits );
548 } elseif ( $bits ) {
549 # No path to expand
550 return $url;
551 } elseif ( substr( $url, 0, 1 ) != '/' ) {
552 # URL is a relative path
553 return wfRemoveDotSegments( $url );
554 }
555
556 # Expanded URL is not valid.
557 return false;
558}
559
568function wfGetServerUrl( $proto ) {
569 $url = wfExpandUrl( '/', $proto );
570 return substr( $url, 0, -1 );
571}
572
586function wfAssembleUrl( $urlParts ) {
587 $result = '';
588
589 if ( isset( $urlParts['delimiter'] ) ) {
590 if ( isset( $urlParts['scheme'] ) ) {
591 $result .= $urlParts['scheme'];
592 }
593
594 $result .= $urlParts['delimiter'];
595 }
596
597 if ( isset( $urlParts['host'] ) ) {
598 if ( isset( $urlParts['user'] ) ) {
599 $result .= $urlParts['user'];
600 if ( isset( $urlParts['pass'] ) ) {
601 $result .= ':' . $urlParts['pass'];
602 }
603 $result .= '@';
604 }
605
606 $result .= $urlParts['host'];
607
608 if ( isset( $urlParts['port'] ) ) {
609 $result .= ':' . $urlParts['port'];
610 }
611 }
612
613 if ( isset( $urlParts['path'] ) ) {
614 $result .= $urlParts['path'];
615 }
616
617 if ( isset( $urlParts['query'] ) && $urlParts['query'] !== '' ) {
618 $result .= '?' . $urlParts['query'];
619 }
620
621 if ( isset( $urlParts['fragment'] ) ) {
622 $result .= '#' . $urlParts['fragment'];
623 }
624
625 return $result;
626}
627
640function wfRemoveDotSegments( $urlPath ) {
641 $output = '';
642 $inputOffset = 0;
643 $inputLength = strlen( $urlPath );
644
645 while ( $inputOffset < $inputLength ) {
646 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
647 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
648 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
649 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
650 $trimOutput = false;
651
652 if ( $prefixLengthTwo == './' ) {
653 # Step A, remove leading "./"
654 $inputOffset += 2;
655 } elseif ( $prefixLengthThree == '../' ) {
656 # Step A, remove leading "../"
657 $inputOffset += 3;
658 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
659 # Step B, replace leading "/.$" with "/"
660 $inputOffset += 1;
661 $urlPath[$inputOffset] = '/';
662 } elseif ( $prefixLengthThree == '/./' ) {
663 # Step B, replace leading "/./" with "/"
664 $inputOffset += 2;
665 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
666 # Step C, replace leading "/..$" with "/" and
667 # remove last path component in output
668 $inputOffset += 2;
669 $urlPath[$inputOffset] = '/';
670 $trimOutput = true;
671 } elseif ( $prefixLengthFour == '/../' ) {
672 # Step C, replace leading "/../" with "/" and
673 # remove last path component in output
674 $inputOffset += 3;
675 $trimOutput = true;
676 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
677 # Step D, remove "^.$"
678 $inputOffset += 1;
679 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
680 # Step D, remove "^..$"
681 $inputOffset += 2;
682 } else {
683 # Step E, move leading path segment to output
684 if ( $prefixLengthOne == '/' ) {
685 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
686 } else {
687 $slashPos = strpos( $urlPath, '/', $inputOffset );
688 }
689 if ( $slashPos === false ) {
690 $output .= substr( $urlPath, $inputOffset );
691 $inputOffset = $inputLength;
692 } else {
693 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
694 $inputOffset += $slashPos - $inputOffset;
695 }
696 }
697
698 if ( $trimOutput ) {
699 $slashPos = strrpos( $output, '/' );
700 if ( $slashPos === false ) {
701 $output = '';
702 } else {
703 $output = substr( $output, 0, $slashPos );
704 }
705 }
706 }
707
708 return $output;
709}
710
718function wfUrlProtocols( $includeProtocolRelative = true ) {
719 global $wgUrlProtocols;
720
721 // Cache return values separately based on $includeProtocolRelative
722 static $withProtRel = null, $withoutProtRel = null;
723 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
724 if ( $cachedValue !== null ) {
725 return $cachedValue;
726 }
727
728 // Support old-style $wgUrlProtocols strings, for backwards compatibility
729 // with LocalSettings files from 1.5
730 if ( is_array( $wgUrlProtocols ) ) {
731 $protocols = [];
732 foreach ( $wgUrlProtocols as $protocol ) {
733 // Filter out '//' if !$includeProtocolRelative
734 if ( $includeProtocolRelative || $protocol !== '//' ) {
735 $protocols[] = preg_quote( $protocol, '/' );
736 }
737 }
738
739 $retval = implode( '|', $protocols );
740 } else {
741 // Ignore $includeProtocolRelative in this case
742 // This case exists for pre-1.6 compatibility, and we can safely assume
743 // that '//' won't appear in a pre-1.6 config because protocol-relative
744 // URLs weren't supported until 1.18
745 $retval = $wgUrlProtocols;
746 }
747
748 // Cache return value
749 if ( $includeProtocolRelative ) {
750 $withProtRel = $retval;
751 } else {
752 $withoutProtRel = $retval;
753 }
754 return $retval;
755}
756
764 return wfUrlProtocols( false );
765}
766
792function wfParseUrl( $url ) {
793 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
794
795 // Protocol-relative URLs are handled really badly by parse_url(). It's so
796 // bad that the easiest way to handle them is to just prepend 'http:' and
797 // strip the protocol out later.
798 $wasRelative = substr( $url, 0, 2 ) == '//';
799 if ( $wasRelative ) {
800 $url = "http:$url";
801 }
802 $bits = parse_url( $url );
803 // parse_url() returns an array without scheme for some invalid URLs, e.g.
804 // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
805 if ( !$bits || !isset( $bits['scheme'] ) ) {
806 return false;
807 }
808
809 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
810 $bits['scheme'] = strtolower( $bits['scheme'] );
811
812 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
813 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
814 $bits['delimiter'] = '://';
815 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
816 $bits['delimiter'] = ':';
817 // parse_url detects for news: and mailto: the host part of an url as path
818 // We have to correct this wrong detection
819 if ( isset( $bits['path'] ) ) {
820 $bits['host'] = $bits['path'];
821 $bits['path'] = '';
822 }
823 } else {
824 return false;
825 }
826
827 /* Provide an empty host for eg. file:/// urls (see T30627) */
828 if ( !isset( $bits['host'] ) ) {
829 $bits['host'] = '';
830
831 // See T47069
832 if ( isset( $bits['path'] ) ) {
833 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
834 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
835 $bits['path'] = '/' . $bits['path'];
836 }
837 } else {
838 $bits['path'] = '';
839 }
840 }
841
842 // If the URL was protocol-relative, fix scheme and delimiter
843 if ( $wasRelative ) {
844 $bits['scheme'] = '';
845 $bits['delimiter'] = '//';
846 }
847 return $bits;
848}
849
860function wfExpandIRI( $url ) {
861 return preg_replace_callback(
862 '/((?:%[89A-F][0-9A-F])+)/i',
863 function ( array $matches ) {
864 return urldecode( $matches[1] );
865 },
866 wfExpandUrl( $url )
867 );
868}
869
876function wfMatchesDomainList( $url, $domains ) {
877 $bits = wfParseUrl( $url );
878 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
879 $host = '.' . $bits['host'];
880 foreach ( (array)$domains as $domain ) {
881 $domain = '.' . $domain;
882 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
883 return true;
884 }
885 }
886 }
887 return false;
888}
889
910function wfDebug( $text, $dest = 'all', array $context = [] ) {
912
913 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
914 return;
915 }
916
917 $text = trim( $text );
918
919 if ( $wgDebugLogPrefix !== '' ) {
920 $context['prefix'] = $wgDebugLogPrefix;
921 }
922 $context['private'] = ( $dest === false || $dest === 'private' );
923
924 $logger = LoggerFactory::getInstance( 'wfDebug' );
925 $logger->debug( $text, $context );
926}
927
933 static $cache;
934 if ( $cache !== null ) {
935 return $cache;
936 }
937 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
938 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
939 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
940 || MW_ENTRY_POINT === 'load'
941 ) {
942 $cache = true;
943 } else {
944 $cache = false;
945 }
946 return $cache;
947}
948
954function wfDebugMem( $exact = false ) {
955 $mem = memory_get_usage();
956 if ( !$exact ) {
957 $mem = floor( $mem / 1024 ) . ' KiB';
958 } else {
959 $mem .= ' B';
960 }
961 wfDebug( "Memory usage: $mem" );
962}
963
989function wfDebugLog(
990 $logGroup, $text, $dest = 'all', array $context = []
991) {
992 $text = trim( $text );
993
994 $logger = LoggerFactory::getInstance( $logGroup );
995 $context['private'] = ( $dest === false || $dest === 'private' );
996 $logger->info( $text, $context );
997}
998
1007function wfLogDBError( $text, array $context = [] ) {
1008 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1009 $logger->error( trim( $text ), $context );
1010}
1011
1027function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1028 if ( is_string( $version ) || $version === false ) {
1029 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1030 } else {
1031 throw new Exception(
1032 "MediaWiki version must either be a string or false. " .
1033 "Example valid version: '1.33'"
1034 );
1035 }
1036}
1037
1059function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
1060 MWDebug::deprecatedMsg( $msg, $version, $component,
1061 $callerOffset === false ? false : $callerOffset + 1 );
1062}
1063
1074function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1075 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1076}
1077
1087function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1088 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1089}
1090
1096 $context = RequestContext::getMain();
1097
1098 $profiler = Profiler::instance();
1099 $profiler->setContext( $context );
1100 $profiler->logData();
1101
1102 // Send out any buffered statsd metrics as needed
1103 MediaWiki::emitBufferedStatsdData(
1104 MediaWikiServices::getInstance()->getStatsdDataFactory(),
1105 $context->getConfig()
1106 );
1107}
1108
1116function wfIncrStats( $key, $count = 1 ) {
1117 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1118 $stats->updateCount( $key, $count );
1119}
1120
1126function wfReadOnly() {
1127 return MediaWikiServices::getInstance()->getReadOnlyMode()
1128 ->isReadOnly();
1129}
1130
1140 return MediaWikiServices::getInstance()->getReadOnlyMode()
1141 ->getReason();
1142}
1143
1151 return MediaWikiServices::getInstance()->getConfiguredReadOnlyMode()
1152 ->getReason();
1153}
1154
1170function wfGetLangObj( $langcode = false ) {
1171 # Identify which language to get or create a language object for.
1172 # Using is_object here due to Stub objects.
1173 if ( is_object( $langcode ) ) {
1174 # Great, we already have the object (hopefully)!
1175 return $langcode;
1176 }
1177
1178 global $wgLanguageCode;
1179 $services = MediaWikiServices::getInstance();
1180 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1181 # $langcode is the language code of the wikis content language object.
1182 # or it is a boolean and value is true
1183 return $services->getContentLanguage();
1184 }
1185
1186 global $wgLang;
1187 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1188 # $langcode is the language code of user language object.
1189 # or it was a boolean and value is false
1190 return $wgLang;
1191 }
1192
1193 $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1194 if ( in_array( $langcode, $validCodes ) ) {
1195 # $langcode corresponds to a valid language.
1196 return $services->getLanguageFactory()->getLanguage( $langcode );
1197 }
1198
1199 # $langcode is a string, but not a valid language code; use content language.
1200 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1201 return $services->getContentLanguage();
1202}
1203
1220function wfMessage( $key, ...$params ) {
1221 $message = new Message( $key );
1222
1223 // We call Message::params() to reduce code duplication
1224 if ( $params ) {
1225 $message->params( ...$params );
1226 }
1227
1228 return $message;
1229}
1230
1243function wfMessageFallback( ...$keys ) {
1245}
1246
1255function wfMsgReplaceArgs( $message, $args ) {
1256 # Fix windows line-endings
1257 # Some messages are split with explode("\n", $msg)
1258 $message = str_replace( "\r", '', $message );
1259
1260 // Replace arguments
1261 if ( is_array( $args ) && $args ) {
1262 if ( is_array( $args[0] ) ) {
1263 $args = array_values( $args[0] );
1264 }
1265 $replacementKeys = [];
1266 foreach ( $args as $n => $param ) {
1267 $replacementKeys['$' . ( $n + 1 )] = $param;
1268 }
1269 $message = strtr( $message, $replacementKeys );
1270 }
1271
1272 return $message;
1273}
1274
1283function wfHostname() {
1284 // Hostname overriding
1285 global $wgOverrideHostname;
1286 if ( $wgOverrideHostname !== false ) {
1287 return $wgOverrideHostname;
1288 }
1289
1290 return php_uname( 'n' ) ?: 'unknown';
1291}
1292
1303function wfReportTime( $nonce = null ) {
1304 global $wgShowHostnames;
1305
1306 $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1307 // seconds to milliseconds
1308 $responseTime = round( $elapsed * 1000 );
1309 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1310 if ( $wgShowHostnames ) {
1311 $reportVars['wgHostname'] = wfHostname();
1312 }
1313 return Skin::makeVariablesScript( $reportVars, $nonce );
1314}
1315
1326function wfDebugBacktrace( $limit = 0 ) {
1327 static $disabled = null;
1328
1329 if ( $disabled === null ) {
1330 $disabled = !function_exists( 'debug_backtrace' );
1331 if ( $disabled ) {
1332 wfDebug( "debug_backtrace() is disabled" );
1333 }
1334 }
1335 if ( $disabled ) {
1336 return [];
1337 }
1338
1339 if ( $limit ) {
1340 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1341 } else {
1342 return array_slice( debug_backtrace(), 1 );
1343 }
1344}
1345
1354function wfBacktrace( $raw = null ) {
1355 global $wgCommandLineMode;
1356
1357 if ( $raw === null ) {
1358 $raw = $wgCommandLineMode;
1359 }
1360
1361 if ( $raw ) {
1362 $frameFormat = "%s line %s calls %s()\n";
1363 $traceFormat = "%s";
1364 } else {
1365 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1366 $traceFormat = "<ul>\n%s</ul>\n";
1367 }
1368
1369 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1370 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1371 $line = $frame['line'] ?? '-';
1372 $call = $frame['function'];
1373 if ( !empty( $frame['class'] ) ) {
1374 $call = $frame['class'] . $frame['type'] . $call;
1375 }
1376 return sprintf( $frameFormat, $file, $line, $call );
1377 }, wfDebugBacktrace() );
1378
1379 return sprintf( $traceFormat, implode( '', $frames ) );
1380}
1381
1391function wfGetCaller( $level = 2 ) {
1392 $backtrace = wfDebugBacktrace( $level + 1 );
1393 if ( isset( $backtrace[$level] ) ) {
1394 return wfFormatStackFrame( $backtrace[$level] );
1395 } else {
1396 return 'unknown';
1397 }
1398}
1399
1407function wfGetAllCallers( $limit = 3 ) {
1408 $trace = array_reverse( wfDebugBacktrace() );
1409 if ( !$limit || $limit > count( $trace ) - 1 ) {
1410 $limit = count( $trace ) - 1;
1411 }
1412 $trace = array_slice( $trace, -$limit - 1, $limit );
1413 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1414}
1415
1422function wfFormatStackFrame( $frame ) {
1423 if ( !isset( $frame['function'] ) ) {
1424 return 'NO_FUNCTION_GIVEN';
1425 }
1426 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1427 $frame['class'] . $frame['type'] . $frame['function'] :
1428 $frame['function'];
1429}
1430
1431/* Some generic result counters, pulled out of SearchEngine */
1432
1440function wfShowingResults( $offset, $limit ) {
1441 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1442}
1443
1453function wfClientAcceptsGzip( $force = false ) {
1454 static $result = null;
1455 if ( $result === null || $force ) {
1456 $result = false;
1457 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1458 # @todo FIXME: We may want to blacklist some broken browsers
1459 $m = [];
1460 if ( preg_match(
1461 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1462 $_SERVER['HTTP_ACCEPT_ENCODING'],
1463 $m
1464 )
1465 ) {
1466 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1467 $result = false;
1468 return $result;
1469 }
1470 wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1471 $result = true;
1472 }
1473 }
1474 }
1475 return $result;
1476}
1477
1488function wfEscapeWikiText( $text ) {
1489 global $wgEnableMagicLinks;
1490 static $repl = null, $repl2 = null;
1491 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1492 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1493 // in those situations
1494 $repl = [
1495 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1496 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1497 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1498 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1499 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1500 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1501 "\n " => "\n&#32;", "\r " => "\r&#32;",
1502 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1503 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1504 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1505 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1506 '__' => '_&#95;', '://' => '&#58;//',
1507 ];
1508
1509 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1510 // We have to catch everything "\s" matches in PCRE
1511 foreach ( $magicLinks as $magic ) {
1512 $repl["$magic "] = "$magic&#32;";
1513 $repl["$magic\t"] = "$magic&#9;";
1514 $repl["$magic\r"] = "$magic&#13;";
1515 $repl["$magic\n"] = "$magic&#10;";
1516 $repl["$magic\f"] = "$magic&#12;";
1517 }
1518
1519 // And handle protocols that don't use "://"
1520 global $wgUrlProtocols;
1521 $repl2 = [];
1522 foreach ( $wgUrlProtocols as $prot ) {
1523 if ( substr( $prot, -1 ) === ':' ) {
1524 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1525 }
1526 }
1527 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1528 }
1529 $text = substr( strtr( "\n$text", $repl ), 1 );
1530 $text = preg_replace( $repl2, '$1&#58;', $text );
1531 return $text;
1532}
1533
1544function wfSetVar( &$dest, $source, $force = false ) {
1545 $temp = $dest;
1546 if ( $source !== null || $force ) {
1547 $dest = $source;
1548 }
1549 return $temp;
1550}
1551
1561function wfSetBit( &$dest, $bit, $state = true ) {
1562 $temp = (bool)( $dest & $bit );
1563 if ( $state !== null ) {
1564 if ( $state ) {
1565 $dest |= $bit;
1566 } else {
1567 $dest &= ~$bit;
1568 }
1569 }
1570 return $temp;
1571}
1572
1579function wfVarDump( $var ) {
1580 global $wgOut;
1581 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1582 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1583 print $s;
1584 } else {
1585 $wgOut->addHTML( $s );
1586 }
1587}
1588
1596function wfHttpError( $code, $label, $desc ) {
1597 global $wgOut;
1598 HttpStatus::header( $code );
1599 if ( $wgOut ) {
1600 $wgOut->disable();
1601 $wgOut->sendCacheControl();
1602 }
1603
1604 MediaWiki\HeaderCallback::warnIfHeadersSent();
1605 header( 'Content-type: text/html; charset=utf-8' );
1606 ob_start();
1607 print '<!DOCTYPE html>' .
1608 '<html><head><title>' .
1609 htmlspecialchars( $label ) .
1610 '</title></head><body><h1>' .
1611 htmlspecialchars( $label ) .
1612 '</h1><p>' .
1613 nl2br( htmlspecialchars( $desc ) ) .
1614 "</p></body></html>\n";
1615 header( 'Content-Length: ' . ob_get_length() );
1616 ob_end_flush();
1617}
1618
1636function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1637 while ( $status = ob_get_status() ) {
1638 if ( isset( $status['flags'] ) ) {
1639 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1640 $deleteable = ( $status['flags'] & $flags ) === $flags;
1641 } elseif ( isset( $status['del'] ) ) {
1642 $deleteable = $status['del'];
1643 } else {
1644 // Guess that any PHP-internal setting can't be removed.
1645 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1646 }
1647 if ( !$deleteable ) {
1648 // Give up, and hope the result doesn't break
1649 // output behavior.
1650 break;
1651 }
1652 if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1653 // Unit testing barrier to prevent this function from breaking PHPUnit.
1654 break;
1655 }
1656 if ( !ob_end_clean() ) {
1657 // Could not remove output buffer handler; abort now
1658 // to avoid getting in some kind of infinite loop.
1659 break;
1660 }
1661 if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1662 // Reset the 'Content-Encoding' field set by this handler
1663 // so we can start fresh.
1664 header_remove( 'Content-Encoding' );
1665 break;
1666 }
1667 }
1668}
1669
1683 wfResetOutputBuffers( false );
1684}
1685
1694function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1695 # No arg means accept anything (per HTTP spec)
1696 if ( !$accept ) {
1697 return [ $def => 1.0 ];
1698 }
1699
1700 $prefs = [];
1701
1702 $parts = explode( ',', $accept );
1703
1704 foreach ( $parts as $part ) {
1705 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1706 $values = explode( ';', trim( $part ) );
1707 $match = [];
1708 if ( count( $values ) == 1 ) {
1709 $prefs[$values[0]] = 1.0;
1710 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1711 $prefs[$values[0]] = floatval( $match[1] );
1712 }
1713 }
1714
1715 return $prefs;
1716}
1717
1730function mimeTypeMatch( $type, $avail ) {
1731 if ( array_key_exists( $type, $avail ) ) {
1732 return $type;
1733 } else {
1734 $mainType = explode( '/', $type )[0];
1735 if ( array_key_exists( "$mainType/*", $avail ) ) {
1736 return "$mainType/*";
1737 } elseif ( array_key_exists( '*/*', $avail ) ) {
1738 return '*/*';
1739 } else {
1740 return null;
1741 }
1742 }
1743}
1744
1759function wfNegotiateType( $cprefs, $sprefs ) {
1760 $combine = [];
1761
1762 foreach ( array_keys( $sprefs ) as $type ) {
1763 $subType = explode( '/', $type )[1];
1764 if ( $subType != '*' ) {
1765 $ckey = mimeTypeMatch( $type, $cprefs );
1766 if ( $ckey ) {
1767 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1768 }
1769 }
1770 }
1771
1772 foreach ( array_keys( $cprefs ) as $type ) {
1773 $subType = explode( '/', $type )[1];
1774 if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
1775 $skey = mimeTypeMatch( $type, $sprefs );
1776 if ( $skey ) {
1777 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1778 }
1779 }
1780 }
1781
1782 $bestq = 0;
1783 $besttype = null;
1784
1785 foreach ( array_keys( $combine ) as $type ) {
1786 if ( $combine[$type] > $bestq ) {
1787 $besttype = $type;
1788 $bestq = $combine[$type];
1789 }
1790 }
1791
1792 return $besttype;
1793}
1794
1803function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1804 $ret = MWTimestamp::convert( $outputtype, $ts );
1805 if ( $ret === false ) {
1806 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1807 }
1808 return $ret;
1809}
1810
1819function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1820 if ( $ts === null ) {
1821 return null;
1822 } else {
1823 return wfTimestamp( $outputtype, $ts );
1824 }
1825}
1826
1832function wfTimestampNow() {
1833 return MWTimestamp::now( TS_MW );
1834}
1835
1841function wfIsWindows() {
1842 return PHP_OS_FAMILY === 'Windows';
1843}
1844
1851function wfIsCLI() {
1852 return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1853}
1854
1866function wfTempDir() {
1867 global $wgTmpDirectory;
1868
1869 if ( $wgTmpDirectory !== false ) {
1870 return $wgTmpDirectory;
1871 }
1872
1873 return TempFSFile::getUsableTempDirectory();
1874}
1875
1885function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1886 global $wgDirectoryMode;
1887
1888 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1889 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1890 }
1891
1892 if ( $caller !== null ) {
1893 wfDebug( "$caller: called wfMkdirParents($dir)" );
1894 }
1895
1896 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1897 return true;
1898 }
1899
1900 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1901
1902 if ( $mode === null ) {
1903 $mode = $wgDirectoryMode;
1904 }
1905
1906 // Turn off the normal warning, we're doing our own below
1907 AtEase::suppressWarnings();
1908 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1909 AtEase::restoreWarnings();
1910
1911 if ( !$ok ) {
1912 // directory may have been created on another request since we last checked
1913 if ( is_dir( $dir ) ) {
1914 return true;
1915 }
1916
1917 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1918 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1919 }
1920 return $ok;
1921}
1922
1928function wfRecursiveRemoveDir( $dir ) {
1929 wfDebug( __FUNCTION__ . "( $dir )" );
1930 // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1931 if ( is_dir( $dir ) ) {
1932 $objects = scandir( $dir );
1933 foreach ( $objects as $object ) {
1934 if ( $object != "." && $object != ".." ) {
1935 if ( filetype( $dir . '/' . $object ) == "dir" ) {
1936 wfRecursiveRemoveDir( $dir . '/' . $object );
1937 } else {
1938 unlink( $dir . '/' . $object );
1939 }
1940 }
1941 }
1942 reset( $objects );
1943 rmdir( $dir );
1944 }
1945}
1946
1953function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1954 $accForFormat = $acc >= 0 ? $acc : 0;
1955 $ret = sprintf( "%.{$accForFormat}f", $nr );
1956 return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1957}
1958
1982function wfIniGetBool( $setting ) {
1983 return wfStringToBool( ini_get( $setting ) );
1984}
1985
1998function wfStringToBool( $val ) {
1999 $val = strtolower( $val );
2000 // 'on' and 'true' can't have whitespace around them, but '1' can.
2001 return $val == 'on'
2002 || $val == 'true'
2003 || $val == 'yes'
2004 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2005}
2006
2019function wfEscapeShellArg( ...$args ) {
2020 return Shell::escape( ...$args );
2021}
2022
2047function wfShellExec( $cmd, &$retval = null, $environ = [],
2048 $limits = [], $options = []
2049) {
2050 if ( Shell::isDisabled() ) {
2051 $retval = 1;
2052 // Backwards compatibility be upon us...
2053 return 'Unable to run external programs, proc_open() is disabled.';
2054 }
2055
2056 if ( is_array( $cmd ) ) {
2057 $cmd = Shell::escape( $cmd );
2058 }
2059
2060 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2061 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
2062
2063 try {
2064 $result = Shell::command( [] )
2065 ->unsafeParams( (array)$cmd )
2066 ->environment( $environ )
2067 ->limits( $limits )
2068 ->includeStderr( $includeStderr )
2069 ->profileMethod( $profileMethod )
2070 // For b/c
2071 ->restrict( Shell::RESTRICT_NONE )
2072 ->execute();
2073 } catch ( ProcOpenError $ex ) {
2074 $retval = -1;
2075 return '';
2076 }
2077
2078 $retval = $result->getExitCode();
2079
2080 return $result->getStdout();
2081}
2082
2100function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
2101 return wfShellExec( $cmd, $retval, $environ, $limits,
2102 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
2103}
2104
2120function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2121 global $wgPhpCli;
2122 // Give site config file a chance to run the script in a wrapper.
2123 // The caller may likely want to call wfBasename() on $script.
2124 Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
2125 $cmd = [ $options['php'] ?? $wgPhpCli ];
2126 if ( isset( $options['wrapper'] ) ) {
2127 $cmd[] = $options['wrapper'];
2128 }
2129 $cmd[] = $script;
2130 // Escape each parameter for shell
2131 return Shell::escape( array_merge( $cmd, $parameters ) );
2132}
2133
2145function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2146 global $wgDiff3;
2147
2148 # This check may also protect against code injection in
2149 # case of broken installations.
2150 AtEase::suppressWarnings();
2151 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2152 AtEase::restoreWarnings();
2153
2154 if ( !$haveDiff3 ) {
2155 wfDebug( "diff3 not found" );
2156 return false;
2157 }
2158
2159 # Make temporary files
2160 $td = wfTempDir();
2161 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2162 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2163 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2164
2165 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2166 # a newline character. To avoid this, we normalize the trailing whitespace before
2167 # creating the diff.
2168
2169 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2170 fclose( $oldtextFile );
2171 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2172 fclose( $mytextFile );
2173 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2174 fclose( $yourtextFile );
2175
2176 # Check for a conflict
2177 $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2178 $oldtextName, $yourtextName );
2179 $handle = popen( $cmd, 'r' );
2180
2181 $mergeAttemptResult = '';
2182 do {
2183 $data = fread( $handle, 8192 );
2184 if ( strlen( $data ) == 0 ) {
2185 break;
2186 }
2187 $mergeAttemptResult .= $data;
2188 } while ( true );
2189 pclose( $handle );
2190
2191 $conflict = $mergeAttemptResult !== '';
2192
2193 # Merge differences
2194 $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2195 $oldtextName, $yourtextName );
2196 $handle = popen( $cmd, 'r' );
2197 $result = '';
2198 do {
2199 $data = fread( $handle, 8192 );
2200 if ( strlen( $data ) == 0 ) {
2201 break;
2202 }
2203 $result .= $data;
2204 } while ( true );
2205 pclose( $handle );
2206 unlink( $mytextName );
2207 unlink( $oldtextName );
2208 unlink( $yourtextName );
2209
2210 if ( $result === '' && $old !== '' && !$conflict ) {
2211 wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2212 $conflict = true;
2213 }
2214 return !$conflict;
2215}
2216
2228function wfDiff( $before, $after, $params = '-u' ) {
2229 if ( $before == $after ) {
2230 return '';
2231 }
2232
2233 global $wgDiff;
2234 AtEase::suppressWarnings();
2235 $haveDiff = $wgDiff && file_exists( $wgDiff );
2236 AtEase::restoreWarnings();
2237
2238 # This check may also protect against code injection in
2239 # case of broken installations.
2240 if ( !$haveDiff ) {
2241 wfDebug( "diff executable not found" );
2242 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2243 $format = new UnifiedDiffFormatter();
2244 return $format->format( $diffs );
2245 }
2246
2247 # Make temporary files
2248 $td = wfTempDir();
2249 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2250 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2251
2252 fwrite( $oldtextFile, $before );
2253 fclose( $oldtextFile );
2254 fwrite( $newtextFile, $after );
2255 fclose( $newtextFile );
2256
2257 // Get the diff of the two files
2258 $cmd = "$wgDiff " . $params . ' ' . Shell::escape( $oldtextName, $newtextName );
2259
2260 $h = popen( $cmd, 'r' );
2261 if ( !$h ) {
2262 unlink( $oldtextName );
2263 unlink( $newtextName );
2264 throw new Exception( __FUNCTION__ . '(): popen() failed' );
2265 }
2266
2267 $diff = '';
2268
2269 do {
2270 $data = fread( $h, 8192 );
2271 if ( strlen( $data ) == 0 ) {
2272 break;
2273 }
2274 $diff .= $data;
2275 } while ( true );
2276
2277 // Clean up
2278 pclose( $h );
2279 unlink( $oldtextName );
2280 unlink( $newtextName );
2281
2282 // Kill the --- and +++ lines. They're not useful.
2283 $diff_lines = explode( "\n", $diff );
2284 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
2285 unset( $diff_lines[0] );
2286 }
2287 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
2288 unset( $diff_lines[1] );
2289 }
2290
2291 $diff = implode( "\n", $diff_lines );
2292
2293 return $diff;
2294}
2295
2308function wfBaseName( $path, $suffix = '' ) {
2309 if ( $suffix == '' ) {
2310 $encSuffix = '';
2311 } else {
2312 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2313 }
2314
2315 $matches = [];
2316 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2317 return $matches[1];
2318 } else {
2319 return '';
2320 }
2321}
2322
2332function wfRelativePath( $path, $from ) {
2333 // Normalize mixed input on Windows...
2334 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2335 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2336
2337 // Trim trailing slashes -- fix for drive root
2338 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2339 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2340
2341 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2342 $against = explode( DIRECTORY_SEPARATOR, $from );
2343
2344 if ( $pieces[0] !== $against[0] ) {
2345 // Non-matching Windows drive letters?
2346 // Return a full path.
2347 return $path;
2348 }
2349
2350 // Trim off common prefix
2351 while ( count( $pieces ) && count( $against )
2352 && $pieces[0] == $against[0] ) {
2353 array_shift( $pieces );
2354 array_shift( $against );
2355 }
2356
2357 // relative dots to bump us to the parent
2358 while ( count( $against ) ) {
2359 array_unshift( $pieces, '..' );
2360 array_shift( $against );
2361 }
2362
2363 array_push( $pieces, wfBaseName( $path ) );
2364
2365 return implode( DIRECTORY_SEPARATOR, $pieces );
2366}
2367
2374function wfGetPrecompiledData( $name ) {
2375 global $IP;
2376
2377 $file = "$IP/serialized/$name";
2378 if ( file_exists( $file ) ) {
2379 $blob = file_get_contents( $file );
2380 if ( $blob ) {
2381 return unserialize( $blob );
2382 }
2383 }
2384 return false;
2385}
2386
2394function wfMemcKey( ...$args ) {
2395 return ObjectCache::getLocalClusterInstance()->makeKey( ...$args );
2396}
2397
2409function wfForeignMemcKey( $db, $prefix, ...$args ) {
2410 $keyspace = $prefix ? "$db-$prefix" : $db;
2411 return ObjectCache::getLocalClusterInstance()->makeKeyInternal( $keyspace, $args );
2412}
2413
2421function wfWikiID() {
2422 global $wgDBprefix, $wgDBname;
2423
2424 if ( $wgDBprefix ) {
2425 return "$wgDBname-$wgDBprefix";
2426 } else {
2427 return $wgDBname;
2428 }
2429}
2430
2462function wfGetDB( $db, $groups = [], $wiki = false ) {
2463 return wfGetLB( $wiki )->getMaintenanceConnectionRef( $db, $groups, $wiki );
2464}
2465
2475function wfGetLB( $wiki = false ) {
2476 if ( $wiki === false ) {
2477 return MediaWikiServices::getInstance()->getDBLoadBalancer();
2478 } else {
2479 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2480 return $factory->getMainLB( $wiki );
2481 }
2482}
2483
2491function wfFindFile( $title, $options = [] ) {
2492 return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2493}
2494
2503function wfLocalFile( $title ) {
2504 return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2505}
2506
2514 global $wgMiserMode;
2515 return $wgMiserMode
2516 || ( SiteStats::pages() > 100000
2517 && SiteStats::edits() > 1000000
2518 && SiteStats::users() > 10000 );
2519}
2520
2529function wfScript( $script = 'index' ) {
2531 if ( $script === 'index' ) {
2532 return $wgScript;
2533 } elseif ( $script === 'load' ) {
2534 return $wgLoadScript;
2535 } else {
2536 return "{$wgScriptPath}/{$script}.php";
2537 }
2538}
2539
2546function wfGetScriptUrl() {
2547 wfDeprecated( __FUNCTION__, '1.35' );
2548 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2549 /* as it was called, minus the query string.
2550 *
2551 * Some sites use Apache rewrite rules to handle subdomains,
2552 * and have PHP set up in a weird way that causes PHP_SELF
2553 * to contain the rewritten URL instead of the one that the
2554 * outside world sees.
2555 *
2556 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2557 * provides containing the "before" URL.
2558 */
2559 return $_SERVER['SCRIPT_NAME'];
2560 } else {
2561 return $_SERVER['URL'];
2562 }
2563}
2564
2572function wfBoolToStr( $value ) {
2573 return $value ? 'true' : 'false';
2574}
2575
2581function wfGetNull() {
2582 return wfIsWindows() ? 'NUL' : '/dev/null';
2583}
2584
2608 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
2609) {
2610 wfDeprecated( __FUNCTION__, '1.27' );
2611 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2612
2613 if ( $cluster === '*' ) {
2614 $cluster = false;
2615 $domain = false;
2616 } elseif ( $wiki === false ) {
2617 $domain = $lbFactory->getLocalDomainID();
2618 } else {
2619 $domain = $wiki;
2620 }
2621
2622 $opts = [
2623 'domain' => $domain,
2624 'cluster' => $cluster,
2625 // B/C: first argument used to be "max seconds of lag"; ignore such values
2626 'ifWritesSince' => ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null
2627 ];
2628 if ( $timeout !== null ) {
2629 $opts['timeout'] = $timeout;
2630 }
2631
2632 return $lbFactory->waitForReplication( $opts );
2633}
2634
2644 global $wgIllegalFileChars;
2645 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2646 $name = preg_replace(
2647 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2648 '-',
2649 $name
2650 );
2651 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2652 $name = wfBaseName( $name );
2653 return $name;
2654}
2655
2662function wfMemoryLimit( $newLimit ) {
2663 $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2664 // If the INI config is already unlimited, there is nothing larger
2665 if ( $oldLimit != -1 ) {
2666 $newLimit = wfShorthandToInteger( $newLimit );
2667 if ( $newLimit == -1 ) {
2668 wfDebug( "Removing PHP's memory limit" );
2669 Wikimedia\suppressWarnings();
2670 ini_set( 'memory_limit', $newLimit );
2671 Wikimedia\restoreWarnings();
2672 } elseif ( $newLimit > $oldLimit ) {
2673 wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2674 Wikimedia\suppressWarnings();
2675 ini_set( 'memory_limit', $newLimit );
2676 Wikimedia\restoreWarnings();
2677 }
2678 }
2679}
2680
2689
2690 $timeLimit = (int)ini_get( 'max_execution_time' );
2691 // Note that CLI scripts use 0
2692 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2693 set_time_limit( $wgTransactionalTimeLimit );
2694 }
2695
2696 ignore_user_abort( true ); // ignore client disconnects
2697
2698 return $timeLimit;
2699}
2700
2708function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int {
2709 $string = trim( $string ?? '' );
2710 if ( $string === '' ) {
2711 return $default;
2712 }
2713 $last = $string[strlen( $string ) - 1];
2714 $val = intval( $string );
2715 switch ( $last ) {
2716 case 'g':
2717 case 'G':
2718 $val *= 1024;
2719 // break intentionally missing
2720 case 'm':
2721 case 'M':
2722 $val *= 1024;
2723 // break intentionally missing
2724 case 'k':
2725 case 'K':
2726 $val *= 1024;
2727 }
2728
2729 return $val;
2730}
2731
2739function wfGetCache( $cacheType ) {
2740 return ObjectCache::getInstance( $cacheType );
2741}
2742
2749function wfGetMainCache() {
2750 return ObjectCache::getLocalClusterInstance();
2751}
2752
2767function wfUnpack( $format, $data, $length = false ) {
2768 if ( $length !== false ) {
2769 $realLen = strlen( $data );
2770 if ( $realLen < $length ) {
2771 throw new MWException( "Tried to use wfUnpack on a "
2772 . "string of length $realLen, but needed one "
2773 . "of at least length $length."
2774 );
2775 }
2776 }
2777
2778 Wikimedia\suppressWarnings();
2779 $result = unpack( $format, $data );
2780 Wikimedia\restoreWarnings();
2781
2782 if ( $result === false ) {
2783 // If it cannot extract the packed data.
2784 throw new MWException( "unpack could not unpack binary data" );
2785 }
2786 return $result;
2787}
2788
2804function wfIsBadImage( $name, $contextTitle = false ) {
2805 wfDeprecated( __FUNCTION__, '1.34' );
2806 $services = MediaWikiServices::getInstance();
2807 return $services->getBadFileLookup()->isBadFile( $name, $contextTitle ?: null );
2808}
2809
2817function wfCanIPUseHTTPS( $ip ) {
2818 $canDo = true;
2819 Hooks::runner()->onCanIPUseHTTPS( $ip, $canDo );
2820 return (bool)$canDo;
2821}
2822
2830function wfIsInfinity( $str ) {
2831 // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2832 return in_array( $str, ExpiryDef::INFINITY_VALS );
2833}
2834
2849function wfThumbIsStandard( File $file, array $params ) {
2851
2852 $multipliers = [ 1 ];
2853 if ( $wgResponsiveImages ) {
2854 // These available sizes are hardcoded currently elsewhere in MediaWiki.
2855 // @see Linker::processResponsiveImages
2856 $multipliers[] = 1.5;
2857 $multipliers[] = 2;
2858 }
2859
2860 $handler = $file->getHandler();
2861 if ( !$handler || !isset( $params['width'] ) ) {
2862 return false;
2863 }
2864
2865 $basicParams = [];
2866 if ( isset( $params['page'] ) ) {
2867 $basicParams['page'] = $params['page'];
2868 }
2869
2870 $thumbLimits = [];
2871 $imageLimits = [];
2872 // Expand limits to account for multipliers
2873 foreach ( $multipliers as $multiplier ) {
2874 $thumbLimits = array_merge( $thumbLimits, array_map(
2875 function ( $width ) use ( $multiplier ) {
2876 return round( $width * $multiplier );
2877 }, $wgThumbLimits )
2878 );
2879 $imageLimits = array_merge( $imageLimits, array_map(
2880 function ( $pair ) use ( $multiplier ) {
2881 return [
2882 round( $pair[0] * $multiplier ),
2883 round( $pair[1] * $multiplier ),
2884 ];
2885 }, $wgImageLimits )
2886 );
2887 }
2888
2889 // Check if the width matches one of $wgThumbLimits
2890 if ( in_array( $params['width'], $thumbLimits ) ) {
2891 $normalParams = $basicParams + [ 'width' => $params['width'] ];
2892 // Append any default values to the map (e.g. "lossy", "lossless", ...)
2893 $handler->normaliseParams( $file, $normalParams );
2894 } else {
2895 // If not, then check if the width matchs one of $wgImageLimits
2896 $match = false;
2897 foreach ( $imageLimits as $pair ) {
2898 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2899 // Decide whether the thumbnail should be scaled on width or height.
2900 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2901 $handler->normaliseParams( $file, $normalParams );
2902 // Check if this standard thumbnail size maps to the given width
2903 if ( $normalParams['width'] == $params['width'] ) {
2904 $match = true;
2905 break;
2906 }
2907 }
2908 if ( !$match ) {
2909 return false; // not standard for description pages
2910 }
2911 }
2912
2913 // Check that the given values for non-page, non-width, params are just defaults
2914 foreach ( $params as $key => $value ) {
2915 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2916 return false;
2917 }
2918 }
2919
2920 return true;
2921}
2922
2935function wfArrayPlus2d( array $baseArray, array $newValues ) {
2936 // First merge items that are in both arrays
2937 foreach ( $baseArray as $name => &$groupVal ) {
2938 if ( isset( $newValues[$name] ) ) {
2939 $groupVal += $newValues[$name];
2940 }
2941 }
2942 // Now add items that didn't exist yet
2943 $baseArray += $newValues;
2944
2945 return $baseArray;
2946}
2947
2957function wfGetRusage() {
2958 wfDeprecated( __FUNCTION__, '1.35' );
2959 return getrusage( 0 /* RUSAGE_SELF */ );
2960}
unserialize( $serialized)
$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 minimum amount of time that MediaWiki needs for "slow" write request, particularly ones with mult...
$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,...
$wgDiff
Path to the GNU diff utility.
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...
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
wfVarDump( $var)
A wrapper around the PHP function var_export().
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfNegotiateType( $cprefs, $sprefs)
Returns the 'best' match between a client's requested internet media types and the server's list of a...
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.
wfGetRusage()
Get system resource usage of current request context.
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.
wfGetPrecompiledData( $name)
Get an object from the precompiled serialized directory.
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.
wfAcceptToPrefs( $accept, $def=' */*')
Converts an Accept-* header into an array mapping string values to quality factors.
wfDiff( $before, $after, $params='-u')
Returns unified plain-text diff of two texts.
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()
Set PHP's time limit to the larger of php.ini or $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.
wfIsBadImage( $name, $contextTitle=false)
Determine if an image exists on the 'bad image list'.
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():
wfDebugMem( $exact=false)
Send a line giving PHP memory usage.
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.
wfMemcKey(... $args)
Make a cache key for the local wiki.
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.
wfForeignMemcKey( $db, $prefix,... $args)
Make a cache key for a foreign DB.
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.
wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed)
Appends to second array if $value differs from that in $default.
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 $function is deprecated.
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.
$wgOut
Definition Setup.php:786
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:643
$wgLang
Definition Setup.php:781
$IP
Definition WebStart.php:49
const MW_ENTRY_POINT
Definition api.php:41
Class representing a 'diff' between two sequences of strings.
Definition Diff.php:32
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:63
MediaWiki exception.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Executes shell commands.
Definition Shell.php:44
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:161
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition Message.php:485
static edits()
Definition SiteStats.php:94
static users()
static pages()
A formatter that outputs unified diffs @newable.
Type definition for expiry timestamps.
Definition ExpiryDef.php:17
while(( $__line=Maintenance::readconsole()) !==false) print
Definition eval.php:64
const PROTO_CANONICAL
Definition Defines.php:213
const PROTO_HTTPS
Definition Defines.php:210
const PROTO_CURRENT
Definition Defines.php:212
const PROTO_INTERNAL
Definition Defines.php:214
const PROTO_HTTP
Definition Defines.php:209
Stable for implementing.
$line
Definition mcc.php:119
$cache
Definition mcc.php:33
if( $line===false) $args
Definition mcc.php:124
$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