MediaWiki REL1_32
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\ScopedCallback;
33use Wikimedia\WrappedString;
34
45function wfLoadExtension( $ext, $path = null ) {
46 if ( !$path ) {
48 $path = "$wgExtensionDirectory/$ext/extension.json";
49 }
51}
52
66function wfLoadExtensions( array $exts ) {
69 foreach ( $exts as $ext ) {
70 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
71 }
72}
73
82function wfLoadSkin( $skin, $path = null ) {
83 if ( !$path ) {
84 global $wgStyleDirectory;
85 $path = "$wgStyleDirectory/$skin/skin.json";
86 }
88}
89
97function wfLoadSkins( array $skins ) {
98 global $wgStyleDirectory;
100 foreach ( $skins as $skin ) {
101 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
102 }
103}
104
111function wfArrayDiff2( $a, $b ) {
112 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
113}
114
120function wfArrayDiff2_cmp( $a, $b ) {
121 if ( is_string( $a ) && is_string( $b ) ) {
122 return strcmp( $a, $b );
123 } elseif ( count( $a ) !== count( $b ) ) {
124 return count( $a ) <=> count( $b );
125 } else {
126 reset( $a );
127 reset( $b );
128 while ( key( $a ) !== null && key( $b ) !== null ) {
129 $valueA = current( $a );
130 $valueB = current( $b );
131 $cmp = strcmp( $valueA, $valueB );
132 if ( $cmp !== 0 ) {
133 return $cmp;
134 }
135 next( $a );
136 next( $b );
137 }
138 return 0;
139 }
140}
141
150function wfArrayFilter( array $arr, callable $callback ) {
151 return array_filter( $arr, $callback, ARRAY_FILTER_USE_BOTH );
152}
153
162function wfArrayFilterByKey( array $arr, callable $callback ) {
163 return array_filter( $arr, $callback, ARRAY_FILTER_USE_KEY );
164}
165
175function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
176 if ( is_null( $changed ) ) {
177 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
178 }
179 if ( $default[$key] !== $value ) {
180 $changed[$key] = $value;
181 }
182}
183
203function wfMergeErrorArrays( ...$args ) {
204 $out = [];
205 foreach ( $args as $errors ) {
206 foreach ( $errors as $params ) {
207 $originalParams = $params;
208 if ( $params[0] instanceof MessageSpecifier ) {
209 $msg = $params[0];
210 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
211 }
212 # @todo FIXME: Sometimes get nested arrays for $params,
213 # which leads to E_NOTICEs
214 $spec = implode( "\t", $params );
215 $out[$spec] = $originalParams;
216 }
217 }
218 return array_values( $out );
219}
220
229function wfArrayInsertAfter( array $array, array $insert, $after ) {
230 // Find the offset of the element to insert after.
231 $keys = array_keys( $array );
232 $offsetByKey = array_flip( $keys );
233
234 $offset = $offsetByKey[$after];
235
236 // Insert at the specified offset
237 $before = array_slice( $array, 0, $offset + 1, true );
238 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
239
240 $output = $before + $insert + $after;
241
242 return $output;
243}
244
252function wfObjectToArray( $objOrArray, $recursive = true ) {
253 $array = [];
254 if ( is_object( $objOrArray ) ) {
255 $objOrArray = get_object_vars( $objOrArray );
256 }
257 foreach ( $objOrArray as $key => $value ) {
258 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
260 }
261
262 $array[$key] = $value;
263 }
264
265 return $array;
266}
267
278function wfRandom() {
279 // The maximum random value is "only" 2^31-1, so get two random
280 // values to reduce the chance of dupes
281 $max = mt_getrandmax() + 1;
282 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
283 return $rand;
284}
285
296function wfRandomString( $length = 32 ) {
297 $str = '';
298 for ( $n = 0; $n < $length; $n += 7 ) {
299 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
300 }
301 return substr( $str, 0, $length );
302}
303
331function wfUrlencode( $s ) {
332 static $needle;
333
334 if ( is_null( $s ) ) {
335 $needle = null;
336 return '';
337 }
338
339 if ( is_null( $needle ) ) {
340 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
341 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
342 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
343 ) {
344 $needle[] = '%3A';
345 }
346 }
347
348 $s = urlencode( $s );
349 $s = str_ireplace(
350 $needle,
351 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
352 $s
353 );
354
355 return $s;
356}
357
368function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
369 if ( !is_null( $array2 ) ) {
370 $array1 = $array1 + $array2;
371 }
372
373 $cgi = '';
374 foreach ( $array1 as $key => $value ) {
375 if ( !is_null( $value ) && $value !== false ) {
376 if ( $cgi != '' ) {
377 $cgi .= '&';
378 }
379 if ( $prefix !== '' ) {
380 $key = $prefix . "[$key]";
381 }
382 if ( is_array( $value ) ) {
383 $firstTime = true;
384 foreach ( $value as $k => $v ) {
385 $cgi .= $firstTime ? '' : '&';
386 if ( is_array( $v ) ) {
387 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
388 } else {
389 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
390 }
391 $firstTime = false;
392 }
393 } else {
394 if ( is_object( $value ) ) {
395 $value = $value->__toString();
396 }
397 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
398 }
399 }
400 }
401 return $cgi;
402}
403
413function wfCgiToArray( $query ) {
414 if ( isset( $query[0] ) && $query[0] == '?' ) {
415 $query = substr( $query, 1 );
416 }
417 $bits = explode( '&', $query );
418 $ret = [];
419 foreach ( $bits as $bit ) {
420 if ( $bit === '' ) {
421 continue;
422 }
423 if ( strpos( $bit, '=' ) === false ) {
424 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
425 $key = $bit;
426 $value = '';
427 } else {
428 list( $key, $value ) = explode( '=', $bit );
429 }
430 $key = urldecode( $key );
431 $value = urldecode( $value );
432 if ( strpos( $key, '[' ) !== false ) {
433 $keys = array_reverse( explode( '[', $key ) );
434 $key = array_pop( $keys );
435 $temp = $value;
436 foreach ( $keys as $k ) {
437 $k = substr( $k, 0, -1 );
438 $temp = [ $k => $temp ];
439 }
440 if ( isset( $ret[$key] ) ) {
441 $ret[$key] = array_merge( $ret[$key], $temp );
442 } else {
443 $ret[$key] = $temp;
444 }
445 } else {
446 $ret[$key] = $value;
447 }
448 }
449 return $ret;
450}
451
460function wfAppendQuery( $url, $query ) {
461 if ( is_array( $query ) ) {
463 }
464 if ( $query != '' ) {
465 // Remove the fragment, if there is one
466 $fragment = false;
467 $hashPos = strpos( $url, '#' );
468 if ( $hashPos !== false ) {
469 $fragment = substr( $url, $hashPos );
470 $url = substr( $url, 0, $hashPos );
471 }
472
473 // Add parameter
474 if ( false === strpos( $url, '?' ) ) {
475 $url .= '?';
476 } else {
477 $url .= '&';
478 }
479 $url .= $query;
480
481 // Put the fragment back
482 if ( $fragment !== false ) {
483 $url .= $fragment;
484 }
485 }
486 return $url;
487}
488
512function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
515 if ( $defaultProto === PROTO_CANONICAL ) {
516 $serverUrl = $wgCanonicalServer;
517 } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
518 // Make $wgInternalServer fall back to $wgServer if not set
519 $serverUrl = $wgInternalServer;
520 } else {
521 $serverUrl = $wgServer;
522 if ( $defaultProto === PROTO_CURRENT ) {
523 $defaultProto = $wgRequest->getProtocol() . '://';
524 }
525 }
526
527 // Analyze $serverUrl to obtain its protocol
528 $bits = wfParseUrl( $serverUrl );
529 $serverHasProto = $bits && $bits['scheme'] != '';
530
531 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
532 if ( $serverHasProto ) {
533 $defaultProto = $bits['scheme'] . '://';
534 } else {
535 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
536 // This really isn't supposed to happen. Fall back to HTTP in this
537 // ridiculous case.
538 $defaultProto = PROTO_HTTP;
539 }
540 }
541
542 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
543
544 if ( substr( $url, 0, 2 ) == '//' ) {
545 $url = $defaultProtoWithoutSlashes . $url;
546 } elseif ( substr( $url, 0, 1 ) == '/' ) {
547 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
548 // otherwise leave it alone.
549 if ( $serverHasProto ) {
550 $url = $serverUrl . $url;
551 } else {
552 // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
553 // user to override the port number (T67184)
554 if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
555 if ( isset( $bits['port'] ) ) {
556 throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
557 }
558 $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
559 } else {
560 $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
561 }
562 }
563 }
564
565 $bits = wfParseUrl( $url );
566
567 if ( $bits && isset( $bits['path'] ) ) {
568 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
569 return wfAssembleUrl( $bits );
570 } elseif ( $bits ) {
571 # No path to expand
572 return $url;
573 } elseif ( substr( $url, 0, 1 ) != '/' ) {
574 # URL is a relative path
575 return wfRemoveDotSegments( $url );
576 }
577
578 # Expanded URL is not valid.
579 return false;
580}
581
590function wfGetServerUrl( $proto ) {
591 $url = wfExpandUrl( '/', $proto );
592 return substr( $url, 0, -1 );
593}
594
608function wfAssembleUrl( $urlParts ) {
609 $result = '';
610
611 if ( isset( $urlParts['delimiter'] ) ) {
612 if ( isset( $urlParts['scheme'] ) ) {
613 $result .= $urlParts['scheme'];
614 }
615
616 $result .= $urlParts['delimiter'];
617 }
618
619 if ( isset( $urlParts['host'] ) ) {
620 if ( isset( $urlParts['user'] ) ) {
621 $result .= $urlParts['user'];
622 if ( isset( $urlParts['pass'] ) ) {
623 $result .= ':' . $urlParts['pass'];
624 }
625 $result .= '@';
626 }
627
628 $result .= $urlParts['host'];
629
630 if ( isset( $urlParts['port'] ) ) {
631 $result .= ':' . $urlParts['port'];
632 }
633 }
634
635 if ( isset( $urlParts['path'] ) ) {
636 $result .= $urlParts['path'];
637 }
638
639 if ( isset( $urlParts['query'] ) ) {
640 $result .= '?' . $urlParts['query'];
641 }
642
643 if ( isset( $urlParts['fragment'] ) ) {
644 $result .= '#' . $urlParts['fragment'];
645 }
646
647 return $result;
648}
649
662function wfRemoveDotSegments( $urlPath ) {
663 $output = '';
664 $inputOffset = 0;
665 $inputLength = strlen( $urlPath );
666
667 while ( $inputOffset < $inputLength ) {
668 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
669 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
670 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
671 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
672 $trimOutput = false;
673
674 if ( $prefixLengthTwo == './' ) {
675 # Step A, remove leading "./"
676 $inputOffset += 2;
677 } elseif ( $prefixLengthThree == '../' ) {
678 # Step A, remove leading "../"
679 $inputOffset += 3;
680 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
681 # Step B, replace leading "/.$" with "/"
682 $inputOffset += 1;
683 $urlPath[$inputOffset] = '/';
684 } elseif ( $prefixLengthThree == '/./' ) {
685 # Step B, replace leading "/./" with "/"
686 $inputOffset += 2;
687 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
688 # Step C, replace leading "/..$" with "/" and
689 # remove last path component in output
690 $inputOffset += 2;
691 $urlPath[$inputOffset] = '/';
692 $trimOutput = true;
693 } elseif ( $prefixLengthFour == '/../' ) {
694 # Step C, replace leading "/../" with "/" and
695 # remove last path component in output
696 $inputOffset += 3;
697 $trimOutput = true;
698 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
699 # Step D, remove "^.$"
700 $inputOffset += 1;
701 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
702 # Step D, remove "^..$"
703 $inputOffset += 2;
704 } else {
705 # Step E, move leading path segment to output
706 if ( $prefixLengthOne == '/' ) {
707 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
708 } else {
709 $slashPos = strpos( $urlPath, '/', $inputOffset );
710 }
711 if ( $slashPos === false ) {
712 $output .= substr( $urlPath, $inputOffset );
713 $inputOffset = $inputLength;
714 } else {
715 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
716 $inputOffset += $slashPos - $inputOffset;
717 }
718 }
719
720 if ( $trimOutput ) {
721 $slashPos = strrpos( $output, '/' );
722 if ( $slashPos === false ) {
723 $output = '';
724 } else {
725 $output = substr( $output, 0, $slashPos );
726 }
727 }
728 }
729
730 return $output;
731}
732
740function wfUrlProtocols( $includeProtocolRelative = true ) {
741 global $wgUrlProtocols;
742
743 // Cache return values separately based on $includeProtocolRelative
744 static $withProtRel = null, $withoutProtRel = null;
745 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
746 if ( !is_null( $cachedValue ) ) {
747 return $cachedValue;
748 }
749
750 // Support old-style $wgUrlProtocols strings, for backwards compatibility
751 // with LocalSettings files from 1.5
752 if ( is_array( $wgUrlProtocols ) ) {
753 $protocols = [];
754 foreach ( $wgUrlProtocols as $protocol ) {
755 // Filter out '//' if !$includeProtocolRelative
756 if ( $includeProtocolRelative || $protocol !== '//' ) {
757 $protocols[] = preg_quote( $protocol, '/' );
758 }
759 }
760
761 $retval = implode( '|', $protocols );
762 } else {
763 // Ignore $includeProtocolRelative in this case
764 // This case exists for pre-1.6 compatibility, and we can safely assume
765 // that '//' won't appear in a pre-1.6 config because protocol-relative
766 // URLs weren't supported until 1.18
768 }
769
770 // Cache return value
771 if ( $includeProtocolRelative ) {
772 $withProtRel = $retval;
773 } else {
774 $withoutProtRel = $retval;
775 }
776 return $retval;
777}
778
786 return wfUrlProtocols( false );
787}
788
814function wfParseUrl( $url ) {
815 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
816
817 // Protocol-relative URLs are handled really badly by parse_url(). It's so
818 // bad that the easiest way to handle them is to just prepend 'http:' and
819 // strip the protocol out later.
820 $wasRelative = substr( $url, 0, 2 ) == '//';
821 if ( $wasRelative ) {
822 $url = "http:$url";
823 }
824 Wikimedia\suppressWarnings();
825 $bits = parse_url( $url );
826 Wikimedia\restoreWarnings();
827
828 // T212067: PHP < 5.6.28, 7.0.0–7.0.12, and HHVM (all relevant versions) screw up parsing
829 // the query part of pathless URLs
830 if ( isset( $bits['host'] ) && strpos( $bits['host'], '?' ) !== false ) {
831 list( $host, $query ) = explode( '?', $bits['host'], 2 );
832 $bits['host'] = $host;
833 $bits['query'] = $query
834 . ( $bits['path'] ?? '' )
835 . ( isset( $bits['query'] ) ? '?' . $bits['query'] : '' );
836 unset( $bits['path'] );
837 }
838
839 // parse_url() returns an array without scheme for some invalid URLs, e.g.
840 // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
841 if ( !$bits || !isset( $bits['scheme'] ) ) {
842 return false;
843 }
844
845 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
846 $bits['scheme'] = strtolower( $bits['scheme'] );
847
848 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
849 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
850 $bits['delimiter'] = '://';
851 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
852 $bits['delimiter'] = ':';
853 // parse_url detects for news: and mailto: the host part of an url as path
854 // We have to correct this wrong detection
855 if ( isset( $bits['path'] ) ) {
856 $bits['host'] = $bits['path'];
857 $bits['path'] = '';
858 }
859 } else {
860 return false;
861 }
862
863 /* Provide an empty host for eg. file:/// urls (see T30627) */
864 if ( !isset( $bits['host'] ) ) {
865 $bits['host'] = '';
866
867 // See T47069
868 if ( isset( $bits['path'] ) ) {
869 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
870 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
871 $bits['path'] = '/' . $bits['path'];
872 }
873 } else {
874 $bits['path'] = '';
875 }
876 }
877
878 // If the URL was protocol-relative, fix scheme and delimiter
879 if ( $wasRelative ) {
880 $bits['scheme'] = '';
881 $bits['delimiter'] = '//';
882 }
883 return $bits;
884}
885
896function wfExpandIRI( $url ) {
897 return preg_replace_callback(
898 '/((?:%[89A-F][0-9A-F])+)/i',
899 function ( array $matches ) {
900 return urldecode( $matches[1] );
901 },
902 wfExpandUrl( $url )
903 );
904}
905
912function wfMakeUrlIndexes( $url ) {
913 $bits = wfParseUrl( $url );
914
915 // Reverse the labels in the hostname, convert to lower case
916 // For emails reverse domainpart only
917 if ( $bits['scheme'] == 'mailto' ) {
918 $mailparts = explode( '@', $bits['host'], 2 );
919 if ( count( $mailparts ) === 2 ) {
920 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
921 } else {
922 // No domain specified, don't mangle it
923 $domainpart = '';
924 }
925 $reversedHost = $domainpart . '@' . $mailparts[0];
926 } else {
927 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
928 }
929 // Add an extra dot to the end
930 // Why? Is it in wrong place in mailto links?
931 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
932 $reversedHost .= '.';
933 }
934 // Reconstruct the pseudo-URL
935 $prot = $bits['scheme'];
936 $index = $prot . $bits['delimiter'] . $reversedHost;
937 // Leave out user and password. Add the port, path, query and fragment
938 if ( isset( $bits['port'] ) ) {
939 $index .= ':' . $bits['port'];
940 }
941 if ( isset( $bits['path'] ) ) {
942 $index .= $bits['path'];
943 } else {
944 $index .= '/';
945 }
946 if ( isset( $bits['query'] ) ) {
947 $index .= '?' . $bits['query'];
948 }
949 if ( isset( $bits['fragment'] ) ) {
950 $index .= '#' . $bits['fragment'];
951 }
952
953 if ( $prot == '' ) {
954 return [ "http:$index", "https:$index" ];
955 } else {
956 return [ $index ];
957 }
958}
959
966function wfMatchesDomainList( $url, $domains ) {
967 $bits = wfParseUrl( $url );
968 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
969 $host = '.' . $bits['host'];
970 foreach ( (array)$domains as $domain ) {
971 $domain = '.' . $domain;
972 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
973 return true;
974 }
975 }
976 }
977 return false;
978}
979
1000function wfDebug( $text, $dest = 'all', array $context = [] ) {
1002 global $wgDebugTimestamps;
1003
1004 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1005 return;
1006 }
1007
1008 $text = trim( $text );
1009
1010 if ( $wgDebugTimestamps ) {
1011 $context['seconds_elapsed'] = sprintf(
1012 '%6.4f',
1013 microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT']
1014 );
1015 $context['memory_used'] = sprintf(
1016 '%5.1fM',
1017 ( memory_get_usage( true ) / ( 1024 * 1024 ) )
1018 );
1019 }
1020
1021 if ( $wgDebugLogPrefix !== '' ) {
1022 $context['prefix'] = $wgDebugLogPrefix;
1023 }
1024 $context['private'] = ( $dest === false || $dest === 'private' );
1025
1026 $logger = LoggerFactory::getInstance( 'wfDebug' );
1027 $logger->debug( $text, $context );
1028}
1029
1035 static $cache;
1036 if ( $cache !== null ) {
1037 return $cache;
1038 }
1039 // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1040 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
1041 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1042 || (
1043 isset( $_SERVER['SCRIPT_NAME'] )
1044 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1045 )
1046 ) {
1047 $cache = true;
1048 } else {
1049 $cache = false;
1050 }
1051 return $cache;
1052}
1053
1059function wfDebugMem( $exact = false ) {
1060 $mem = memory_get_usage();
1061 if ( !$exact ) {
1062 $mem = floor( $mem / 1024 ) . ' KiB';
1063 } else {
1064 $mem .= ' B';
1065 }
1066 wfDebug( "Memory usage: $mem\n" );
1067}
1068
1094function wfDebugLog(
1095 $logGroup, $text, $dest = 'all', array $context = []
1096) {
1097 $text = trim( $text );
1098
1099 $logger = LoggerFactory::getInstance( $logGroup );
1100 $context['private'] = ( $dest === false || $dest === 'private' );
1101 $logger->info( $text, $context );
1102}
1103
1112function wfLogDBError( $text, array $context = [] ) {
1113 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1114 $logger->error( trim( $text ), $context );
1115}
1116
1130function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1131 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1132}
1133
1144function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1145 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1146}
1147
1157function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1158 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1159}
1160
1167
1168 $context = RequestContext::getMain();
1169 $request = $context->getRequest();
1170
1171 $profiler = Profiler::instance();
1172 $profiler->setContext( $context );
1173 $profiler->logData();
1174
1175 // Send out any buffered statsd metrics as needed
1176 MediaWiki::emitBufferedStatsdData(
1177 MediaWikiServices::getInstance()->getStatsdDataFactory(),
1178 $context->getConfig()
1179 );
1180
1181 // Profiling must actually be enabled...
1182 if ( $profiler instanceof ProfilerStub ) {
1183 return;
1184 }
1185
1186 if ( isset( $wgDebugLogGroups['profileoutput'] )
1187 && $wgDebugLogGroups['profileoutput'] === false
1188 ) {
1189 // Explicitly disabled
1190 return;
1191 }
1192 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1193 return;
1194 }
1195
1196 $ctx = [ 'elapsed' => $request->getElapsedTime() ];
1197 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1198 $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
1199 }
1200 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1201 $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP'];
1202 }
1203 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1204 $ctx['from'] = $_SERVER['HTTP_FROM'];
1205 }
1206 if ( isset( $ctx['forwarded_for'] ) ||
1207 isset( $ctx['client_ip'] ) ||
1208 isset( $ctx['from'] ) ) {
1209 $ctx['proxy'] = $_SERVER['REMOTE_ADDR'];
1210 }
1211
1212 // Don't load $wgUser at this late stage just for statistics purposes
1213 // @todo FIXME: We can detect some anons even if it is not loaded.
1214 // See User::getId()
1215 $user = $context->getUser();
1216 $ctx['anon'] = $user->isItemLoaded( 'id' ) && $user->isAnon();
1217
1218 // Command line script uses a FauxRequest object which does not have
1219 // any knowledge about an URL and throw an exception instead.
1220 try {
1221 $ctx['url'] = urldecode( $request->getRequestURL() );
1222 } catch ( Exception $ignored ) {
1223 // no-op
1224 }
1225
1226 $ctx['output'] = $profiler->getOutput();
1227
1228 $log = LoggerFactory::getInstance( 'profileoutput' );
1229 $log->info( "Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx );
1230}
1231
1239function wfIncrStats( $key, $count = 1 ) {
1240 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1241 $stats->updateCount( $key, $count );
1242}
1243
1249function wfReadOnly() {
1250 return MediaWikiServices::getInstance()->getReadOnlyMode()
1251 ->isReadOnly();
1252}
1253
1263 return MediaWikiServices::getInstance()->getReadOnlyMode()
1264 ->getReason();
1265}
1266
1274 return MediaWikiServices::getInstance()->getConfiguredReadOnlyMode()
1275 ->getReason();
1276}
1277
1293function wfGetLangObj( $langcode = false ) {
1294 # Identify which language to get or create a language object for.
1295 # Using is_object here due to Stub objects.
1296 if ( is_object( $langcode ) ) {
1297 # Great, we already have the object (hopefully)!
1298 return $langcode;
1299 }
1300
1301 global $wgLanguageCode;
1302 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1303 # $langcode is the language code of the wikis content language object.
1304 # or it is a boolean and value is true
1305 return MediaWikiServices::getInstance()->getContentLanguage();
1306 }
1307
1308 global $wgLang;
1309 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1310 # $langcode is the language code of user language object.
1311 # or it was a boolean and value is false
1312 return $wgLang;
1313 }
1314
1315 $validCodes = array_keys( Language::fetchLanguageNames() );
1316 if ( in_array( $langcode, $validCodes ) ) {
1317 # $langcode corresponds to a valid language.
1318 return Language::factory( $langcode );
1319 }
1320
1321 # $langcode is a string, but not a valid language code; use content language.
1322 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1323 return MediaWikiServices::getInstance()->getContentLanguage();
1324}
1325
1342function wfMessage( $key, ...$params ) {
1343 $message = new Message( $key );
1344
1345 // We call Message::params() to reduce code duplication
1346 if ( $params ) {
1347 $message->params( ...$params );
1348 }
1349
1350 return $message;
1351}
1352
1365function wfMessageFallback( ...$keys ) {
1366 return Message::newFallbackSequence( ...$keys );
1367}
1368
1377function wfMsgReplaceArgs( $message, $args ) {
1378 # Fix windows line-endings
1379 # Some messages are split with explode("\n", $msg)
1380 $message = str_replace( "\r", '', $message );
1381
1382 // Replace arguments
1383 if ( is_array( $args ) && $args ) {
1384 if ( is_array( $args[0] ) ) {
1385 $args = array_values( $args[0] );
1386 }
1387 $replacementKeys = [];
1388 foreach ( $args as $n => $param ) {
1389 $replacementKeys['$' . ( $n + 1 )] = $param;
1390 }
1391 $message = strtr( $message, $replacementKeys );
1392 }
1393
1394 return $message;
1395}
1396
1404function wfHostname() {
1405 static $host;
1406 if ( is_null( $host ) ) {
1407 # Hostname overriding
1408 global $wgOverrideHostname;
1409 if ( $wgOverrideHostname !== false ) {
1410 # Set static and skip any detection
1411 $host = $wgOverrideHostname;
1412 return $host;
1413 }
1414
1415 if ( function_exists( 'posix_uname' ) ) {
1416 // This function not present on Windows
1417 $uname = posix_uname();
1418 } else {
1419 $uname = false;
1420 }
1421 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1422 $host = $uname['nodename'];
1423 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1424 # Windows computer name
1425 $host = getenv( 'COMPUTERNAME' );
1426 } else {
1427 # This may be a virtual server.
1428 $host = $_SERVER['SERVER_NAME'];
1429 }
1430 }
1431 return $host;
1432}
1433
1444function wfReportTime( $nonce = null ) {
1445 global $wgShowHostnames;
1446
1447 $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1448 // seconds to milliseconds
1449 $responseTime = round( $elapsed * 1000 );
1450 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1451 if ( $wgShowHostnames ) {
1452 $reportVars['wgHostname'] = wfHostname();
1453 }
1454 return Skin::makeVariablesScript( $reportVars, $nonce );
1455}
1456
1467function wfDebugBacktrace( $limit = 0 ) {
1468 static $disabled = null;
1469
1470 if ( is_null( $disabled ) ) {
1471 $disabled = !function_exists( 'debug_backtrace' );
1472 if ( $disabled ) {
1473 wfDebug( "debug_backtrace() is disabled\n" );
1474 }
1475 }
1476 if ( $disabled ) {
1477 return [];
1478 }
1479
1480 if ( $limit ) {
1481 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1482 } else {
1483 return array_slice( debug_backtrace(), 1 );
1484 }
1485}
1486
1495function wfBacktrace( $raw = null ) {
1496 global $wgCommandLineMode;
1497
1498 if ( $raw === null ) {
1499 $raw = $wgCommandLineMode;
1500 }
1501
1502 if ( $raw ) {
1503 $frameFormat = "%s line %s calls %s()\n";
1504 $traceFormat = "%s";
1505 } else {
1506 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1507 $traceFormat = "<ul>\n%s</ul>\n";
1508 }
1509
1510 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1511 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1512 $line = $frame['line'] ?? '-';
1513 $call = $frame['function'];
1514 if ( !empty( $frame['class'] ) ) {
1515 $call = $frame['class'] . $frame['type'] . $call;
1516 }
1517 return sprintf( $frameFormat, $file, $line, $call );
1518 }, wfDebugBacktrace() );
1519
1520 return sprintf( $traceFormat, implode( '', $frames ) );
1521}
1522
1532function wfGetCaller( $level = 2 ) {
1533 $backtrace = wfDebugBacktrace( $level + 1 );
1534 if ( isset( $backtrace[$level] ) ) {
1535 return wfFormatStackFrame( $backtrace[$level] );
1536 } else {
1537 return 'unknown';
1538 }
1539}
1540
1548function wfGetAllCallers( $limit = 3 ) {
1549 $trace = array_reverse( wfDebugBacktrace() );
1550 if ( !$limit || $limit > count( $trace ) - 1 ) {
1551 $limit = count( $trace ) - 1;
1552 }
1553 $trace = array_slice( $trace, -$limit - 1, $limit );
1554 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1555}
1556
1563function wfFormatStackFrame( $frame ) {
1564 if ( !isset( $frame['function'] ) ) {
1565 return 'NO_FUNCTION_GIVEN';
1566 }
1567 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1568 $frame['class'] . $frame['type'] . $frame['function'] :
1569 $frame['function'];
1570}
1571
1572/* Some generic result counters, pulled out of SearchEngine */
1573
1581function wfShowingResults( $offset, $limit ) {
1582 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1583}
1584
1594function wfClientAcceptsGzip( $force = false ) {
1595 static $result = null;
1596 if ( $result === null || $force ) {
1597 $result = false;
1598 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1599 # @todo FIXME: We may want to blacklist some broken browsers
1600 $m = [];
1601 if ( preg_match(
1602 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1603 $_SERVER['HTTP_ACCEPT_ENCODING'],
1604 $m
1605 )
1606 ) {
1607 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1608 $result = false;
1609 return $result;
1610 }
1611 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
1612 $result = true;
1613 }
1614 }
1615 }
1616 return $result;
1617}
1618
1629function wfEscapeWikiText( $text ) {
1630 global $wgEnableMagicLinks;
1631 static $repl = null, $repl2 = null;
1632 if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1633 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1634 // in those situations
1635 $repl = [
1636 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1637 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1638 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1639 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1640 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1641 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1642 "\n " => "\n&#32;", "\r " => "\r&#32;",
1643 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1644 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1645 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1646 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1647 '__' => '_&#95;', '://' => '&#58;//',
1648 ];
1649
1650 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1651 // We have to catch everything "\s" matches in PCRE
1652 foreach ( $magicLinks as $magic ) {
1653 $repl["$magic "] = "$magic&#32;";
1654 $repl["$magic\t"] = "$magic&#9;";
1655 $repl["$magic\r"] = "$magic&#13;";
1656 $repl["$magic\n"] = "$magic&#10;";
1657 $repl["$magic\f"] = "$magic&#12;";
1658 }
1659
1660 // And handle protocols that don't use "://"
1661 global $wgUrlProtocols;
1662 $repl2 = [];
1663 foreach ( $wgUrlProtocols as $prot ) {
1664 if ( substr( $prot, -1 ) === ':' ) {
1665 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1666 }
1667 }
1668 $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1669 }
1670 $text = substr( strtr( "\n$text", $repl ), 1 );
1671 $text = preg_replace( $repl2, '$1&#58;', $text );
1672 return $text;
1673}
1674
1685function wfSetVar( &$dest, $source, $force = false ) {
1686 $temp = $dest;
1687 if ( !is_null( $source ) || $force ) {
1688 $dest = $source;
1689 }
1690 return $temp;
1691}
1692
1702function wfSetBit( &$dest, $bit, $state = true ) {
1703 $temp = (bool)( $dest & $bit );
1704 if ( !is_null( $state ) ) {
1705 if ( $state ) {
1706 $dest |= $bit;
1707 } else {
1708 $dest &= ~$bit;
1709 }
1710 }
1711 return $temp;
1712}
1713
1720function wfVarDump( $var ) {
1721 global $wgOut;
1722 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1723 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1724 print $s;
1725 } else {
1726 $wgOut->addHTML( $s );
1727 }
1728}
1729
1737function wfHttpError( $code, $label, $desc ) {
1738 global $wgOut;
1740 if ( $wgOut ) {
1741 $wgOut->disable();
1742 $wgOut->sendCacheControl();
1743 }
1744
1745 MediaWiki\HeaderCallback::warnIfHeadersSent();
1746 header( 'Content-type: text/html; charset=utf-8' );
1747 print '<!DOCTYPE html>' .
1748 '<html><head><title>' .
1749 htmlspecialchars( $label ) .
1750 '</title></head><body><h1>' .
1751 htmlspecialchars( $label ) .
1752 '</h1><p>' .
1753 nl2br( htmlspecialchars( $desc ) ) .
1754 "</p></body></html>\n";
1755}
1756
1774function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1775 if ( $resetGzipEncoding ) {
1776 // Suppress Content-Encoding and Content-Length
1777 // headers from OutputHandler::handle.
1780 }
1781 while ( $status = ob_get_status() ) {
1782 if ( isset( $status['flags'] ) ) {
1783 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1784 $deleteable = ( $status['flags'] & $flags ) === $flags;
1785 } elseif ( isset( $status['del'] ) ) {
1786 $deleteable = $status['del'];
1787 } else {
1788 // Guess that any PHP-internal setting can't be removed.
1789 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1790 }
1791 if ( !$deleteable ) {
1792 // Give up, and hope the result doesn't break
1793 // output behavior.
1794 break;
1795 }
1796 if ( $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ) {
1797 // Unit testing barrier to prevent this function from breaking PHPUnit.
1798 break;
1799 }
1800 if ( !ob_end_clean() ) {
1801 // Could not remove output buffer handler; abort now
1802 // to avoid getting in some kind of infinite loop.
1803 break;
1804 }
1805 if ( $resetGzipEncoding ) {
1806 if ( $status['name'] == 'ob_gzhandler' ) {
1807 // Reset the 'Content-Encoding' field set by this handler
1808 // so we can start fresh.
1809 header_remove( 'Content-Encoding' );
1810 break;
1811 }
1812 }
1813 }
1814}
1815
1829 wfResetOutputBuffers( false );
1830}
1831
1840function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1841 # No arg means accept anything (per HTTP spec)
1842 if ( !$accept ) {
1843 return [ $def => 1.0 ];
1844 }
1845
1846 $prefs = [];
1847
1848 $parts = explode( ',', $accept );
1849
1850 foreach ( $parts as $part ) {
1851 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1852 $values = explode( ';', trim( $part ) );
1853 $match = [];
1854 if ( count( $values ) == 1 ) {
1855 $prefs[$values[0]] = 1.0;
1856 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1857 $prefs[$values[0]] = floatval( $match[1] );
1858 }
1859 }
1860
1861 return $prefs;
1862}
1863
1876function mimeTypeMatch( $type, $avail ) {
1877 if ( array_key_exists( $type, $avail ) ) {
1878 return $type;
1879 } else {
1880 $mainType = explode( '/', $type )[0];
1881 if ( array_key_exists( "$mainType/*", $avail ) ) {
1882 return "$mainType/*";
1883 } elseif ( array_key_exists( '*/*', $avail ) ) {
1884 return '*/*';
1885 } else {
1886 return null;
1887 }
1888 }
1889}
1890
1904function wfNegotiateType( $cprefs, $sprefs ) {
1905 $combine = [];
1906
1907 foreach ( array_keys( $sprefs ) as $type ) {
1908 $subType = explode( '/', $type )[1];
1909 if ( $subType != '*' ) {
1910 $ckey = mimeTypeMatch( $type, $cprefs );
1911 if ( $ckey ) {
1912 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1913 }
1914 }
1915 }
1916
1917 foreach ( array_keys( $cprefs ) as $type ) {
1918 $subType = explode( '/', $type )[1];
1919 if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
1920 $skey = mimeTypeMatch( $type, $sprefs );
1921 if ( $skey ) {
1922 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1923 }
1924 }
1925 }
1926
1927 $bestq = 0;
1928 $besttype = null;
1929
1930 foreach ( array_keys( $combine ) as $type ) {
1931 if ( $combine[$type] > $bestq ) {
1932 $besttype = $type;
1933 $bestq = $combine[$type];
1934 }
1935 }
1936
1937 return $besttype;
1938}
1939
1946function wfSuppressWarnings( $end = false ) {
1947 Wikimedia\suppressWarnings( $end );
1948}
1949
1955 Wikimedia\restoreWarnings();
1956}
1957
1966function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1967 $ret = MWTimestamp::convert( $outputtype, $ts );
1968 if ( $ret === false ) {
1969 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
1970 }
1971 return $ret;
1972}
1973
1982function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1983 if ( is_null( $ts ) ) {
1984 return null;
1985 } else {
1986 return wfTimestamp( $outputtype, $ts );
1987 }
1988}
1989
1995function wfTimestampNow() {
1996 # return NOW
1997 return MWTimestamp::now( TS_MW );
1998}
1999
2005function wfIsWindows() {
2006 static $isWindows = null;
2007 if ( $isWindows === null ) {
2008 $isWindows = strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN';
2009 }
2010 return $isWindows;
2011}
2012
2018function wfIsHHVM() {
2019 return defined( 'HHVM_VERSION' );
2020}
2021
2028function wfIsCLI() {
2029 return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
2030}
2031
2043function wfTempDir() {
2044 global $wgTmpDirectory;
2045
2046 if ( $wgTmpDirectory !== false ) {
2047 return $wgTmpDirectory;
2048 }
2049
2051}
2052
2062function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2063 global $wgDirectoryMode;
2064
2065 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
2066 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
2067 }
2068
2069 if ( !is_null( $caller ) ) {
2070 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2071 }
2072
2073 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
2074 return true;
2075 }
2076
2077 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
2078
2079 if ( is_null( $mode ) ) {
2080 $mode = $wgDirectoryMode;
2081 }
2082
2083 // Turn off the normal warning, we're doing our own below
2084 Wikimedia\suppressWarnings();
2085 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2086 Wikimedia\restoreWarnings();
2087
2088 if ( !$ok ) {
2089 // directory may have been created on another request since we last checked
2090 if ( is_dir( $dir ) ) {
2091 return true;
2092 }
2093
2094 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2095 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2096 }
2097 return $ok;
2098}
2099
2105function wfRecursiveRemoveDir( $dir ) {
2106 wfDebug( __FUNCTION__ . "( $dir )\n" );
2107 // taken from https://secure.php.net/manual/en/function.rmdir.php#98622
2108 if ( is_dir( $dir ) ) {
2109 $objects = scandir( $dir );
2110 foreach ( $objects as $object ) {
2111 if ( $object != "." && $object != ".." ) {
2112 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2113 wfRecursiveRemoveDir( $dir . '/' . $object );
2114 } else {
2115 unlink( $dir . '/' . $object );
2116 }
2117 }
2118 }
2119 reset( $objects );
2120 rmdir( $dir );
2121 }
2122}
2123
2130function wfPercent( $nr, $acc = 2, $round = true ) {
2131 $ret = sprintf( "%.${acc}f", $nr );
2132 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2133}
2134
2158function wfIniGetBool( $setting ) {
2159 return wfStringToBool( ini_get( $setting ) );
2160}
2161
2174function wfStringToBool( $val ) {
2175 $val = strtolower( $val );
2176 // 'on' and 'true' can't have whitespace around them, but '1' can.
2177 return $val == 'on'
2178 || $val == 'true'
2179 || $val == 'yes'
2180 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2181}
2182
2195function wfEscapeShellArg( ...$args ) {
2196 return Shell::escape( ...$args );
2197}
2198
2222function wfShellExec( $cmd, &$retval = null, $environ = [],
2223 $limits = [], $options = []
2224) {
2225 if ( Shell::isDisabled() ) {
2226 $retval = 1;
2227 // Backwards compatibility be upon us...
2228 return 'Unable to run external programs, proc_open() is disabled.';
2229 }
2230
2231 if ( is_array( $cmd ) ) {
2232 $cmd = Shell::escape( $cmd );
2233 }
2234
2235 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2236 $profileMethod = $options['profileMethod'] ?? wfGetCaller();
2237
2238 try {
2239 $result = Shell::command( [] )
2240 ->unsafeParams( (array)$cmd )
2241 ->environment( $environ )
2242 ->limits( $limits )
2243 ->includeStderr( $includeStderr )
2244 ->profileMethod( $profileMethod )
2245 // For b/c
2246 ->restrict( Shell::RESTRICT_NONE )
2247 ->execute();
2248 } catch ( ProcOpenError $ex ) {
2249 $retval = -1;
2250 return '';
2251 }
2252
2253 $retval = $result->getExitCode();
2254
2255 return $result->getStdout();
2256}
2257
2275function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
2276 return wfShellExec( $cmd, $retval, $environ, $limits,
2277 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
2278}
2279
2294function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2295 global $wgPhpCli;
2296 // Give site config file a chance to run the script in a wrapper.
2297 // The caller may likely want to call wfBasename() on $script.
2298 Hooks::run( 'wfShellWikiCmd', [ &$script, &$parameters, &$options ] );
2299 $cmd = [ $options['php'] ?? $wgPhpCli ];
2300 if ( isset( $options['wrapper'] ) ) {
2301 $cmd[] = $options['wrapper'];
2302 }
2303 $cmd[] = $script;
2304 // Escape each parameter for shell
2305 return Shell::escape( array_merge( $cmd, $parameters ) );
2306}
2307
2319function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2320 global $wgDiff3;
2321
2322 # This check may also protect against code injection in
2323 # case of broken installations.
2324 Wikimedia\suppressWarnings();
2325 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2326 Wikimedia\restoreWarnings();
2327
2328 if ( !$haveDiff3 ) {
2329 wfDebug( "diff3 not found\n" );
2330 return false;
2331 }
2332
2333 # Make temporary files
2334 $td = wfTempDir();
2335 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2336 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2337 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2338
2339 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2340 # a newline character. To avoid this, we normalize the trailing whitespace before
2341 # creating the diff.
2342
2343 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2344 fclose( $oldtextFile );
2345 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2346 fclose( $mytextFile );
2347 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2348 fclose( $yourtextFile );
2349
2350 # Check for a conflict
2351 $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2352 $oldtextName, $yourtextName );
2353 $handle = popen( $cmd, 'r' );
2354
2355 $mergeAttemptResult = '';
2356 do {
2357 $data = fread( $handle, 8192 );
2358 if ( strlen( $data ) == 0 ) {
2359 break;
2360 }
2361 $mergeAttemptResult .= $data;
2362 } while ( true );
2363 pclose( $handle );
2364
2365 $conflict = $mergeAttemptResult !== '';
2366
2367 # Merge differences
2368 $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2369 $oldtextName, $yourtextName );
2370 $handle = popen( $cmd, 'r' );
2371 $result = '';
2372 do {
2373 $data = fread( $handle, 8192 );
2374 if ( strlen( $data ) == 0 ) {
2375 break;
2376 }
2377 $result .= $data;
2378 } while ( true );
2379 pclose( $handle );
2380 unlink( $mytextName );
2381 unlink( $oldtextName );
2382 unlink( $yourtextName );
2383
2384 if ( $result === '' && $old !== '' && !$conflict ) {
2385 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
2386 $conflict = true;
2387 }
2388 return !$conflict;
2389}
2390
2402function wfDiff( $before, $after, $params = '-u' ) {
2403 if ( $before == $after ) {
2404 return '';
2405 }
2406
2407 global $wgDiff;
2408 Wikimedia\suppressWarnings();
2409 $haveDiff = $wgDiff && file_exists( $wgDiff );
2410 Wikimedia\restoreWarnings();
2411
2412 # This check may also protect against code injection in
2413 # case of broken installations.
2414 if ( !$haveDiff ) {
2415 wfDebug( "diff executable not found\n" );
2416 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2417 $format = new UnifiedDiffFormatter();
2418 return $format->format( $diffs );
2419 }
2420
2421 # Make temporary files
2422 $td = wfTempDir();
2423 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2424 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2425
2426 fwrite( $oldtextFile, $before );
2427 fclose( $oldtextFile );
2428 fwrite( $newtextFile, $after );
2429 fclose( $newtextFile );
2430
2431 // Get the diff of the two files
2432 $cmd = "$wgDiff " . $params . ' ' . Shell::escape( $oldtextName, $newtextName );
2433
2434 $h = popen( $cmd, 'r' );
2435 if ( !$h ) {
2436 unlink( $oldtextName );
2437 unlink( $newtextName );
2438 throw new Exception( __METHOD__ . '(): popen() failed' );
2439 }
2440
2441 $diff = '';
2442
2443 do {
2444 $data = fread( $h, 8192 );
2445 if ( strlen( $data ) == 0 ) {
2446 break;
2447 }
2448 $diff .= $data;
2449 } while ( true );
2450
2451 // Clean up
2452 pclose( $h );
2453 unlink( $oldtextName );
2454 unlink( $newtextName );
2455
2456 // Kill the --- and +++ lines. They're not useful.
2457 $diff_lines = explode( "\n", $diff );
2458 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
2459 unset( $diff_lines[0] );
2460 }
2461 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
2462 unset( $diff_lines[1] );
2463 }
2464
2465 $diff = implode( "\n", $diff_lines );
2466
2467 return $diff;
2468}
2469
2482function wfBaseName( $path, $suffix = '' ) {
2483 if ( $suffix == '' ) {
2484 $encSuffix = '';
2485 } else {
2486 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2487 }
2488
2489 $matches = [];
2490 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2491 return $matches[1];
2492 } else {
2493 return '';
2494 }
2495}
2496
2506function wfRelativePath( $path, $from ) {
2507 // Normalize mixed input on Windows...
2508 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2509 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2510
2511 // Trim trailing slashes -- fix for drive root
2512 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2513 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2514
2515 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2516 $against = explode( DIRECTORY_SEPARATOR, $from );
2517
2518 if ( $pieces[0] !== $against[0] ) {
2519 // Non-matching Windows drive letters?
2520 // Return a full path.
2521 return $path;
2522 }
2523
2524 // Trim off common prefix
2525 while ( count( $pieces ) && count( $against )
2526 && $pieces[0] == $against[0] ) {
2527 array_shift( $pieces );
2528 array_shift( $against );
2529 }
2530
2531 // relative dots to bump us to the parent
2532 while ( count( $against ) ) {
2533 array_unshift( $pieces, '..' );
2534 array_shift( $against );
2535 }
2536
2537 array_push( $pieces, wfBaseName( $path ) );
2538
2539 return implode( DIRECTORY_SEPARATOR, $pieces );
2540}
2541
2549 wfDeprecated( __FUNCTION__, '1.27' );
2550 $session = SessionManager::getGlobalSession();
2551 $delay = $session->delaySave();
2552
2553 $session->resetId();
2554
2555 // Make sure a session is started, since that's what the old
2556 // wfResetSessionID() did.
2557 if ( session_id() !== $session->getId() ) {
2558 wfSetupSession( $session->getId() );
2559 }
2560
2561 ScopedCallback::consume( $delay );
2562}
2563
2573function wfSetupSession( $sessionId = false ) {
2574 wfDeprecated( __FUNCTION__, '1.27' );
2575
2576 if ( $sessionId ) {
2577 session_id( $sessionId );
2578 }
2579
2580 $session = SessionManager::getGlobalSession();
2581 $session->persist();
2582
2583 if ( session_id() !== $session->getId() ) {
2584 session_id( $session->getId() );
2585 }
2586 Wikimedia\quietCall( 'session_start' );
2587}
2588
2595function wfGetPrecompiledData( $name ) {
2596 global $IP;
2597
2598 $file = "$IP/serialized/$name";
2599 if ( file_exists( $file ) ) {
2600 $blob = file_get_contents( $file );
2601 if ( $blob ) {
2602 return unserialize( $blob );
2603 }
2604 }
2605 return false;
2606}
2607
2615function wfMemcKey( ...$args ) {
2616 return ObjectCache::getLocalClusterInstance()->makeKey( ...$args );
2617}
2618
2629function wfForeignMemcKey( $db, $prefix, ...$args ) {
2630 $keyspace = $prefix ? "$db-$prefix" : $db;
2631 return ObjectCache::getLocalClusterInstance()->makeKeyInternal( $keyspace, $args );
2632}
2633
2646function wfGlobalCacheKey( ...$args ) {
2647 return ObjectCache::getLocalClusterInstance()->makeGlobalKey( ...$args );
2648}
2649
2656function wfWikiID() {
2657 global $wgDBprefix, $wgDBname;
2658 if ( $wgDBprefix ) {
2659 return "$wgDBname-$wgDBprefix";
2660 } else {
2661 return $wgDBname;
2662 }
2663}
2664
2672function wfSplitWikiID( $wiki ) {
2673 $bits = explode( '-', $wiki, 2 );
2674 if ( count( $bits ) < 2 ) {
2675 $bits[] = '';
2676 }
2677 return $bits;
2678}
2679
2705function wfGetDB( $db, $groups = [], $wiki = false ) {
2706 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2707}
2708
2718function wfGetLB( $wiki = false ) {
2719 if ( $wiki === false ) {
2720 return MediaWikiServices::getInstance()->getDBLoadBalancer();
2721 } else {
2722 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2723 return $factory->getMainLB( $wiki );
2724 }
2725}
2726
2734function wfGetLBFactory() {
2735 return MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2736}
2737
2746function wfFindFile( $title, $options = [] ) {
2747 return RepoGroup::singleton()->findFile( $title, $options );
2748}
2749
2757function wfLocalFile( $title ) {
2758 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2759}
2760
2768 global $wgMiserMode;
2769 return $wgMiserMode
2770 || ( SiteStats::pages() > 100000
2771 && SiteStats::edits() > 1000000
2772 && SiteStats::users() > 10000 );
2773}
2774
2783function wfScript( $script = 'index' ) {
2785 if ( $script === 'index' ) {
2786 return $wgScript;
2787 } elseif ( $script === 'load' ) {
2788 return $wgLoadScript;
2789 } else {
2790 return "{$wgScriptPath}/{$script}.php";
2791 }
2792}
2793
2799function wfGetScriptUrl() {
2800 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2801 /* as it was called, minus the query string.
2802 *
2803 * Some sites use Apache rewrite rules to handle subdomains,
2804 * and have PHP set up in a weird way that causes PHP_SELF
2805 * to contain the rewritten URL instead of the one that the
2806 * outside world sees.
2807 *
2808 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2809 * provides containing the "before" URL.
2810 */
2811 return $_SERVER['SCRIPT_NAME'];
2812 } else {
2813 return $_SERVER['URL'];
2814 }
2815}
2816
2824function wfBoolToStr( $value ) {
2825 return $value ? 'true' : 'false';
2826}
2827
2833function wfGetNull() {
2834 return wfIsWindows() ? 'NUL' : '/dev/null';
2835}
2836
2860 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
2861) {
2862 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2863
2864 if ( $cluster === '*' ) {
2865 $cluster = false;
2866 $domain = false;
2867 } elseif ( $wiki === false ) {
2868 $domain = $lbFactory->getLocalDomainID();
2869 } else {
2870 $domain = $wiki;
2871 }
2872
2873 $opts = [
2874 'domain' => $domain,
2875 'cluster' => $cluster,
2876 // B/C: first argument used to be "max seconds of lag"; ignore such values
2877 'ifWritesSince' => ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null
2878 ];
2879 if ( $timeout !== null ) {
2880 $opts['timeout'] = $timeout;
2881 }
2882
2883 return $lbFactory->waitForReplication( $opts );
2884}
2885
2895function wfCountDown( $seconds ) {
2896 wfDeprecated( __FUNCTION__, '1.31' );
2897 for ( $i = $seconds; $i >= 0; $i-- ) {
2898 if ( $i != $seconds ) {
2899 echo str_repeat( "\x08", strlen( $i + 1 ) );
2900 }
2901 echo $i;
2902 flush();
2903 if ( $i ) {
2904 sleep( 1 );
2905 }
2906 }
2907 echo "\n";
2908}
2909
2919 global $wgIllegalFileChars;
2920 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2921 $name = preg_replace(
2922 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2923 '-',
2924 $name
2925 );
2926 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2927 $name = wfBaseName( $name );
2928 return $name;
2929}
2930
2936function wfMemoryLimit() {
2937 global $wgMemoryLimit;
2938 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2939 if ( $memlimit != -1 ) {
2940 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
2941 if ( $conflimit == -1 ) {
2942 wfDebug( "Removing PHP's memory limit\n" );
2943 Wikimedia\suppressWarnings();
2944 ini_set( 'memory_limit', $conflimit );
2945 Wikimedia\restoreWarnings();
2946 return $conflimit;
2947 } elseif ( $conflimit > $memlimit ) {
2948 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
2949 Wikimedia\suppressWarnings();
2950 ini_set( 'memory_limit', $conflimit );
2951 Wikimedia\restoreWarnings();
2952 return $conflimit;
2953 }
2954 }
2955 return $memlimit;
2956}
2957
2966
2967 $timeLimit = ini_get( 'max_execution_time' );
2968 // Note that CLI scripts use 0
2969 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2970 set_time_limit( $wgTransactionalTimeLimit );
2971 }
2972
2973 ignore_user_abort( true ); // ignore client disconnects
2974
2975 return $timeLimit;
2976}
2977
2985function wfShorthandToInteger( $string = '', $default = -1 ) {
2986 $string = trim( $string );
2987 if ( $string === '' ) {
2988 return $default;
2989 }
2990 $last = $string[strlen( $string ) - 1];
2991 $val = intval( $string );
2992 switch ( $last ) {
2993 case 'g':
2994 case 'G':
2995 $val *= 1024;
2996 // break intentionally missing
2997 case 'm':
2998 case 'M':
2999 $val *= 1024;
3000 // break intentionally missing
3001 case 'k':
3002 case 'K':
3003 $val *= 1024;
3004 }
3005
3006 return $val;
3007}
3008
3019function wfBCP47( $code ) {
3020 wfDeprecated( __METHOD__, '1.31' );
3021 return LanguageCode::bcp47( $code );
3022}
3023
3031function wfGetCache( $cacheType ) {
3032 return ObjectCache::getInstance( $cacheType );
3033}
3034
3041function wfGetMainCache() {
3042 return ObjectCache::getLocalClusterInstance();
3043}
3044
3051 global $wgMessageCacheType;
3052 return ObjectCache::getInstance( $wgMessageCacheType );
3053}
3054
3069function wfUnpack( $format, $data, $length = false ) {
3070 if ( $length !== false ) {
3071 $realLen = strlen( $data );
3072 if ( $realLen < $length ) {
3073 throw new MWException( "Tried to use wfUnpack on a "
3074 . "string of length $realLen, but needed one "
3075 . "of at least length $length."
3076 );
3077 }
3078 }
3079
3080 Wikimedia\suppressWarnings();
3081 $result = unpack( $format, $data );
3082 Wikimedia\restoreWarnings();
3083
3084 if ( $result === false ) {
3085 // If it cannot extract the packed data.
3086 throw new MWException( "unpack could not unpack binary data" );
3087 }
3088 return $result;
3089}
3090
3105function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
3106 # Handle redirects; callers almost always hit wfFindFile() anyway,
3107 # so just use that method because it has a fast process cache.
3108 $file = wfFindFile( $name ); // get the final name
3109 $name = $file ? $file->getTitle()->getDBkey() : $name;
3110
3111 # Run the extension hook
3112 $bad = false;
3113 if ( !Hooks::run( 'BadImage', [ $name, &$bad ] ) ) {
3114 return (bool)$bad;
3115 }
3116
3117 $cache = ObjectCache::getLocalServerInstance( 'hash' );
3118 $key = $cache->makeKey(
3119 'bad-image-list', ( $blacklist === null ) ? 'default' : md5( $blacklist )
3120 );
3121 $badImages = $cache->get( $key );
3122
3123 if ( $badImages === false ) { // cache miss
3124 if ( $blacklist === null ) {
3125 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
3126 }
3127 # Build the list now
3128 $badImages = [];
3129 $lines = explode( "\n", $blacklist );
3130 foreach ( $lines as $line ) {
3131 # List items only
3132 if ( substr( $line, 0, 1 ) !== '*' ) {
3133 continue;
3134 }
3135
3136 # Find all links
3137 $m = [];
3138 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
3139 continue;
3140 }
3141
3142 $exceptions = [];
3143 $imageDBkey = false;
3144 foreach ( $m[1] as $i => $titleText ) {
3145 $title = Title::newFromText( $titleText );
3146 if ( !is_null( $title ) ) {
3147 if ( $i == 0 ) {
3148 $imageDBkey = $title->getDBkey();
3149 } else {
3150 $exceptions[$title->getPrefixedDBkey()] = true;
3151 }
3152 }
3153 }
3154
3155 if ( $imageDBkey !== false ) {
3156 $badImages[$imageDBkey] = $exceptions;
3157 }
3158 }
3159 $cache->set( $key, $badImages, 60 );
3160 }
3161
3162 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
3163 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
3164
3165 return $bad;
3166}
3167
3175function wfCanIPUseHTTPS( $ip ) {
3176 $canDo = true;
3177 Hooks::run( 'CanIPUseHTTPS', [ $ip, &$canDo ] );
3178 return !!$canDo;
3179}
3180
3188function wfIsInfinity( $str ) {
3189 // These are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
3190 $infinityValues = [ 'infinite', 'indefinite', 'infinity', 'never' ];
3191 return in_array( $str, $infinityValues );
3192}
3193
3210
3211 $multipliers = [ 1 ];
3212 if ( $wgResponsiveImages ) {
3213 // These available sizes are hardcoded currently elsewhere in MediaWiki.
3214 // @see Linker::processResponsiveImages
3215 $multipliers[] = 1.5;
3216 $multipliers[] = 2;
3217 }
3218
3219 $handler = $file->getHandler();
3220 if ( !$handler || !isset( $params['width'] ) ) {
3221 return false;
3222 }
3223
3224 $basicParams = [];
3225 if ( isset( $params['page'] ) ) {
3226 $basicParams['page'] = $params['page'];
3227 }
3228
3229 $thumbLimits = [];
3230 $imageLimits = [];
3231 // Expand limits to account for multipliers
3232 foreach ( $multipliers as $multiplier ) {
3233 $thumbLimits = array_merge( $thumbLimits, array_map(
3234 function ( $width ) use ( $multiplier ) {
3235 return round( $width * $multiplier );
3236 }, $wgThumbLimits )
3237 );
3238 $imageLimits = array_merge( $imageLimits, array_map(
3239 function ( $pair ) use ( $multiplier ) {
3240 return [
3241 round( $pair[0] * $multiplier ),
3242 round( $pair[1] * $multiplier ),
3243 ];
3244 }, $wgImageLimits )
3245 );
3246 }
3247
3248 // Check if the width matches one of $wgThumbLimits
3249 if ( in_array( $params['width'], $thumbLimits ) ) {
3250 $normalParams = $basicParams + [ 'width' => $params['width'] ];
3251 // Append any default values to the map (e.g. "lossy", "lossless", ...)
3252 $handler->normaliseParams( $file, $normalParams );
3253 } else {
3254 // If not, then check if the width matchs one of $wgImageLimits
3255 $match = false;
3256 foreach ( $imageLimits as $pair ) {
3257 $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
3258 // Decide whether the thumbnail should be scaled on width or height.
3259 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
3260 $handler->normaliseParams( $file, $normalParams );
3261 // Check if this standard thumbnail size maps to the given width
3262 if ( $normalParams['width'] == $params['width'] ) {
3263 $match = true;
3264 break;
3265 }
3266 }
3267 if ( !$match ) {
3268 return false; // not standard for description pages
3269 }
3270 }
3271
3272 // Check that the given values for non-page, non-width, params are just defaults
3273 foreach ( $params as $key => $value ) {
3274 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
3275 return false;
3276 }
3277 }
3278
3279 return true;
3280}
3281
3294function wfArrayPlus2d( array $baseArray, array $newValues ) {
3295 // First merge items that are in both arrays
3296 foreach ( $baseArray as $name => &$groupVal ) {
3297 if ( isset( $newValues[$name] ) ) {
3298 $groupVal += $newValues[$name];
3299 }
3300 }
3301 // Now add items that didn't exist yet
3302 $baseArray += $newValues;
3303
3304 return $baseArray;
3305}
3306
3315function wfGetRusage() {
3316 if ( !function_exists( 'getrusage' ) ) {
3317 return false;
3318 } elseif ( defined( 'HHVM_VERSION' ) && PHP_OS === 'Linux' ) {
3319 return getrusage( 2 /* RUSAGE_THREAD */ );
3320 } else {
3321 return getrusage( 0 /* RUSAGE_SELF */ );
3322 }
3323}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
unserialize( $serialized)
$wgLanguageCode
Site language code.
$wgMemoryLimit
The minimum amount of memory that MediaWiki "needs"; MediaWiki will try to raise PHP's memory limit i...
$wgDBprefix
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.
$wgDisableOutputCompression
Disable output compression (enabled by default if zlib is available)
$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...
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
$wgDirectoryMode
Default value for chmoding of new directories.
$wgMessageCacheType
The cache type for storing the contents of the MediaWiki namespace.
$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.
$wgDebugTimestamps
Prefix debug messages with relative timestamp.
$wgDebugLogGroups
Map of string log group names to log destinations.
$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 between 0 and 1, in a way not likely to give duplicate values for any real...
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.
wfBCP47( $code)
Get the normalised IETF language tag See unit test for examples.
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.
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.
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 getUserPermissionsErrors, with duplicate removal e.g.
wfPercent( $nr, $acc=2, $round=true)
wfCountDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
wfRestoreWarnings()
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
wfHostname()
Fetch server name for use in error reporting etc.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfSplitWikiID( $wiki)
Split a wiki ID into DB name and table prefix.
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.
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.
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
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.
wfSetupSession( $sessionId=false)
Initialise php session.
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.
wfMakeUrlIndexes( $url)
Make URL indexes, appropriate for the el_index field of externallinks.
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.
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
wfGetLBFactory()
Get the load balancer factory object.
wfGetScriptUrl()
Get the script URL.
wfGlobalCacheKey(... $args)
Make a cache key with database-agnostic prefix.
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.
wfArrayFilterByKey(array $arr, callable $callback)
wfIsBadImage( $name, $contextTitle=false, $blacklist=null)
Determine if an image exists on the 'bad image list'.
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.
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
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.
wfMemoryLimit()
Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit.
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.
wfResetSessionID()
Reset the session id.
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.
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)
Throws 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.
wfIsHHVM()
Check if we are running under HHVM.
wfArrayFilter(array $arr, callable $callback)
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:915
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:747
$wgLang
Definition Setup.php:910
$IP
Definition WebStart.php:41
$line
Definition cdb.php:59
if( $line===false) $args
Definition cdb.php:64
Class representing a 'diff' between two sequences of strings.
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:51
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1383
static header( $code)
Output an HTTP status code header.
MediaWiki exception.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This serves as the entry point to the MediaWiki session handling system.
Executes shell commands.
Definition Shell.php:44
The Message class provides methods which fulfil two basic services:
Definition Message.php:160
Stub profiler that does nothing.
static singleton()
Get a RepoGroup instance.
Definition RepoGroup.php:59
static edits()
Definition SiteStats.php:94
static users()
static pages()
static getUsableTempDirectory()
A formatter that outputs unified diffs.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
while(( $__line=Maintenance::readconsole()) !==false) print
Definition eval.php:64
const PROTO_CANONICAL
Definition Defines.php:223
const PROTO_HTTPS
Definition Defines.php:220
const PROTO_CURRENT
Definition Defines.php:222
const PROTO_INTERNAL
Definition Defines.php:224
const PROTO_HTTP
Definition Defines.php:219
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2880
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:2042
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:266
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1305
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2050
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
Definition hooks.txt:2214
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2885
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:895
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:2054
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:894
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned $skin
Definition hooks.txt:2060
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:933
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1656
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition hooks.txt:2317
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:247
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
$cache
Definition mcc.php:33
controlled by the following MediaWiki still creates a BagOStuff but calls it to it are no ops If the cache daemon can t be it should also disable itself fairly $wgDBname
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$source
$last
$lines
Definition router.php:61
if(!is_readable( $file)) $ext
Definition router.php:55
$params