MediaWiki  master
GlobalFunctions.php
Go to the documentation of this file.
1 <?php
23 if ( !defined( 'MEDIAWIKI' ) ) {
24  die( "This file is part of MediaWiki, it is not a valid entry point" );
25 }
26 
33 use Wikimedia\AtEase\AtEase;
35 use Wikimedia\WrappedString;
36 
47 function wfLoadExtension( $ext, $path = null ) {
48  if ( !$path ) {
49  global $wgExtensionDirectory;
50  $path = "$wgExtensionDirectory/$ext/extension.json";
51  }
53 }
54 
68 function wfLoadExtensions( array $exts ) {
69  global $wgExtensionDirectory;
70  $registry = ExtensionRegistry::getInstance();
71  foreach ( $exts as $ext ) {
72  $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
73  }
74 }
75 
84 function wfLoadSkin( $skin, $path = null ) {
85  if ( !$path ) {
86  global $wgStyleDirectory;
87  $path = "$wgStyleDirectory/$skin/skin.json";
88  }
90 }
91 
99 function wfLoadSkins( array $skins ) {
100  global $wgStyleDirectory;
101  $registry = ExtensionRegistry::getInstance();
102  foreach ( $skins as $skin ) {
103  $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
104  }
105 }
106 
113 function wfArrayDiff2( $a, $b ) {
114  return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
115 }
116 
122 function wfArrayDiff2_cmp( $a, $b ) {
123  if ( is_string( $a ) && is_string( $b ) ) {
124  return strcmp( $a, $b );
125  } elseif ( count( $a ) !== count( $b ) ) {
126  return count( $a ) <=> count( $b );
127  } else {
128  reset( $a );
129  reset( $b );
130  while ( key( $a ) !== null && key( $b ) !== null ) {
131  $valueA = current( $a );
132  $valueB = current( $b );
133  $cmp = strcmp( $valueA, $valueB );
134  if ( $cmp !== 0 ) {
135  return $cmp;
136  }
137  next( $a );
138  next( $b );
139  }
140  return 0;
141  }
142 }
143 
153 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
154  if ( $changed === null ) {
155  throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
156  }
157  if ( $default[$key] !== $value ) {
158  $changed[$key] = $value;
159  }
160 }
161 
181 function wfMergeErrorArrays( ...$args ) {
182  $out = [];
183  foreach ( $args as $errors ) {
184  foreach ( $errors as $params ) {
185  $originalParams = $params;
186  if ( $params[0] instanceof MessageSpecifier ) {
187  $msg = $params[0];
188  $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
189  }
190  # @todo FIXME: Sometimes get nested arrays for $params,
191  # which leads to E_NOTICEs
192  $spec = implode( "\t", $params );
193  $out[$spec] = $originalParams;
194  }
195  }
196  return array_values( $out );
197 }
198 
207 function wfArrayInsertAfter( array $array, array $insert, $after ) {
208  // Find the offset of the element to insert after.
209  $keys = array_keys( $array );
210  $offsetByKey = array_flip( $keys );
211 
212  $offset = $offsetByKey[$after];
213 
214  // Insert at the specified offset
215  $before = array_slice( $array, 0, $offset + 1, true );
216  $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
217 
218  $output = $before + $insert + $after;
219 
220  return $output;
221 }
222 
230 function wfObjectToArray( $objOrArray, $recursive = true ) {
231  $array = [];
232  if ( is_object( $objOrArray ) ) {
233  $objOrArray = get_object_vars( $objOrArray );
234  }
235  foreach ( $objOrArray as $key => $value ) {
236  if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
237  $value = wfObjectToArray( $value );
238  }
239 
240  $array[$key] = $value;
241  }
242 
243  return $array;
244 }
245 
256 function wfRandom() {
257  // The maximum random value is "only" 2^31-1, so get two random
258  // values to reduce the chance of dupes
259  $max = mt_getrandmax() + 1;
260  $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
261  return $rand;
262 }
263 
274 function wfRandomString( $length = 32 ) {
275  $str = '';
276  for ( $n = 0; $n < $length; $n += 7 ) {
277  $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
278  }
279  return substr( $str, 0, $length );
280 }
281 
309 function wfUrlencode( $s ) {
310  static $needle;
311 
312  if ( $s === null ) {
313  // Reset $needle for testing.
314  $needle = null;
315  return '';
316  }
317 
318  if ( $needle === null ) {
319  $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
320  if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
321  ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
322  ) {
323  $needle[] = '%3A';
324  }
325  }
326 
327  $s = urlencode( $s );
328  $s = str_ireplace(
329  $needle,
330  [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
331  $s
332  );
333 
334  return $s;
335 }
336 
347 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
348  if ( $array2 !== null ) {
349  $array1 = $array1 + $array2;
350  }
351 
352  $cgi = '';
353  foreach ( $array1 as $key => $value ) {
354  if ( $value !== null && $value !== false ) {
355  if ( $cgi != '' ) {
356  $cgi .= '&';
357  }
358  if ( $prefix !== '' ) {
359  $key = $prefix . "[$key]";
360  }
361  if ( is_array( $value ) ) {
362  $firstTime = true;
363  foreach ( $value as $k => $v ) {
364  $cgi .= $firstTime ? '' : '&';
365  if ( is_array( $v ) ) {
366  $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
367  } else {
368  $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
369  }
370  $firstTime = false;
371  }
372  } else {
373  if ( is_object( $value ) ) {
374  $value = $value->__toString();
375  }
376  $cgi .= urlencode( $key ) . '=' . urlencode( $value );
377  }
378  }
379  }
380  return $cgi;
381 }
382 
392 function wfCgiToArray( $query ) {
393  if ( isset( $query[0] ) && $query[0] == '?' ) {
394  $query = substr( $query, 1 );
395  }
396  $bits = explode( '&', $query );
397  $ret = [];
398  foreach ( $bits as $bit ) {
399  if ( $bit === '' ) {
400  continue;
401  }
402  if ( strpos( $bit, '=' ) === false ) {
403  // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
404  $key = $bit;
405  $value = '';
406  } else {
407  list( $key, $value ) = explode( '=', $bit );
408  }
409  $key = urldecode( $key );
410  $value = urldecode( $value );
411  if ( strpos( $key, '[' ) !== false ) {
412  $keys = array_reverse( explode( '[', $key ) );
413  $key = array_pop( $keys );
414  $temp = $value;
415  foreach ( $keys as $k ) {
416  $k = substr( $k, 0, -1 );
417  $temp = [ $k => $temp ];
418  }
419  if ( isset( $ret[$key] ) ) {
420  $ret[$key] = array_merge( $ret[$key], $temp );
421  } else {
422  $ret[$key] = $temp;
423  }
424  } else {
425  $ret[$key] = $value;
426  }
427  }
428  return $ret;
429 }
430 
439 function wfAppendQuery( $url, $query ) {
440  if ( is_array( $query ) ) {
441  $query = wfArrayToCgi( $query );
442  }
443  if ( $query != '' ) {
444  // Remove the fragment, if there is one
445  $fragment = false;
446  $hashPos = strpos( $url, '#' );
447  if ( $hashPos !== false ) {
448  $fragment = substr( $url, $hashPos );
449  $url = substr( $url, 0, $hashPos );
450  }
451 
452  // Add parameter
453  if ( strpos( $url, '?' ) === false ) {
454  $url .= '?';
455  } else {
456  $url .= '&';
457  }
458  $url .= $query;
459 
460  // Put the fragment back
461  if ( $fragment !== false ) {
462  $url .= $fragment;
463  }
464  }
465  return $url;
466 }
467 
491 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
493  $wgHttpsPort;
494  if ( $defaultProto === PROTO_CANONICAL ) {
495  $serverUrl = $wgCanonicalServer;
496  } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
497  // Make $wgInternalServer fall back to $wgServer if not set
498  $serverUrl = $wgInternalServer;
499  } else {
500  $serverUrl = $wgServer;
501  if ( $defaultProto === PROTO_CURRENT ) {
502  $defaultProto = $wgRequest->getProtocol() . '://';
503  }
504  }
505 
506  // Analyze $serverUrl to obtain its protocol
507  $bits = wfParseUrl( $serverUrl );
508  $serverHasProto = $bits && $bits['scheme'] != '';
509 
510  if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
511  if ( $serverHasProto ) {
512  $defaultProto = $bits['scheme'] . '://';
513  } else {
514  // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
515  // This really isn't supposed to happen. Fall back to HTTP in this
516  // ridiculous case.
517  $defaultProto = PROTO_HTTP;
518  }
519  }
520 
521  $defaultProtoWithoutSlashes = $defaultProto !== null ? substr( $defaultProto, 0, -2 ) : '';
522 
523  if ( substr( $url, 0, 2 ) == '//' ) {
524  $url = $defaultProtoWithoutSlashes . $url;
525  } elseif ( substr( $url, 0, 1 ) == '/' ) {
526  // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
527  // otherwise leave it alone.
528  if ( $serverHasProto ) {
529  $url = $serverUrl . $url;
530  } else {
531  // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
532  // user to override the port number (T67184)
533  if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
534  if ( isset( $bits['port'] ) ) {
535  throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
536  }
537  $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
538  } else {
539  $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
540  }
541  }
542  }
543 
544  $bits = wfParseUrl( $url );
545 
546  if ( $bits && isset( $bits['path'] ) ) {
547  $bits['path'] = wfRemoveDotSegments( $bits['path'] );
548  return wfAssembleUrl( $bits );
549  } elseif ( $bits ) {
550  # No path to expand
551  return $url;
552  } elseif ( substr( $url, 0, 1 ) != '/' ) {
553  # URL is a relative path
554  return wfRemoveDotSegments( $url );
555  }
556 
557  # Expanded URL is not valid.
558  return false;
559 }
560 
569 function wfGetServerUrl( $proto ) {
570  $url = wfExpandUrl( '/', $proto );
571  return substr( $url, 0, -1 );
572 }
573 
587 function wfAssembleUrl( $urlParts ) {
588  $result = '';
589 
590  if ( isset( $urlParts['delimiter'] ) ) {
591  if ( isset( $urlParts['scheme'] ) ) {
592  $result .= $urlParts['scheme'];
593  }
594 
595  $result .= $urlParts['delimiter'];
596  }
597 
598  if ( isset( $urlParts['host'] ) ) {
599  if ( isset( $urlParts['user'] ) ) {
600  $result .= $urlParts['user'];
601  if ( isset( $urlParts['pass'] ) ) {
602  $result .= ':' . $urlParts['pass'];
603  }
604  $result .= '@';
605  }
606 
607  $result .= $urlParts['host'];
608 
609  if ( isset( $urlParts['port'] ) ) {
610  $result .= ':' . $urlParts['port'];
611  }
612  }
613 
614  if ( isset( $urlParts['path'] ) ) {
615  $result .= $urlParts['path'];
616  }
617 
618  if ( isset( $urlParts['query'] ) ) {
619  $result .= '?' . $urlParts['query'];
620  }
621 
622  if ( isset( $urlParts['fragment'] ) ) {
623  $result .= '#' . $urlParts['fragment'];
624  }
625 
626  return $result;
627 }
628 
641 function wfRemoveDotSegments( $urlPath ) {
642  $output = '';
643  $inputOffset = 0;
644  $inputLength = strlen( $urlPath );
645 
646  while ( $inputOffset < $inputLength ) {
647  $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
648  $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
649  $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
650  $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
651  $trimOutput = false;
652 
653  if ( $prefixLengthTwo == './' ) {
654  # Step A, remove leading "./"
655  $inputOffset += 2;
656  } elseif ( $prefixLengthThree == '../' ) {
657  # Step A, remove leading "../"
658  $inputOffset += 3;
659  } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
660  # Step B, replace leading "/.$" with "/"
661  $inputOffset += 1;
662  $urlPath[$inputOffset] = '/';
663  } elseif ( $prefixLengthThree == '/./' ) {
664  # Step B, replace leading "/./" with "/"
665  $inputOffset += 2;
666  } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
667  # Step C, replace leading "/..$" with "/" and
668  # remove last path component in output
669  $inputOffset += 2;
670  $urlPath[$inputOffset] = '/';
671  $trimOutput = true;
672  } elseif ( $prefixLengthFour == '/../' ) {
673  # Step C, replace leading "/../" with "/" and
674  # remove last path component in output
675  $inputOffset += 3;
676  $trimOutput = true;
677  } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
678  # Step D, remove "^.$"
679  $inputOffset += 1;
680  } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
681  # Step D, remove "^..$"
682  $inputOffset += 2;
683  } else {
684  # Step E, move leading path segment to output
685  if ( $prefixLengthOne == '/' ) {
686  $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
687  } else {
688  $slashPos = strpos( $urlPath, '/', $inputOffset );
689  }
690  if ( $slashPos === false ) {
691  $output .= substr( $urlPath, $inputOffset );
692  $inputOffset = $inputLength;
693  } else {
694  $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
695  $inputOffset += $slashPos - $inputOffset;
696  }
697  }
698 
699  if ( $trimOutput ) {
700  $slashPos = strrpos( $output, '/' );
701  if ( $slashPos === false ) {
702  $output = '';
703  } else {
704  $output = substr( $output, 0, $slashPos );
705  }
706  }
707  }
708 
709  return $output;
710 }
711 
719 function wfUrlProtocols( $includeProtocolRelative = true ) {
720  global $wgUrlProtocols;
721 
722  // Cache return values separately based on $includeProtocolRelative
723  static $withProtRel = null, $withoutProtRel = null;
724  $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
725  if ( $cachedValue !== null ) {
726  return $cachedValue;
727  }
728 
729  // Support old-style $wgUrlProtocols strings, for backwards compatibility
730  // with LocalSettings files from 1.5
731  if ( is_array( $wgUrlProtocols ) ) {
732  $protocols = [];
733  foreach ( $wgUrlProtocols as $protocol ) {
734  // Filter out '//' if !$includeProtocolRelative
735  if ( $includeProtocolRelative || $protocol !== '//' ) {
736  $protocols[] = preg_quote( $protocol, '/' );
737  }
738  }
739 
740  $retval = implode( '|', $protocols );
741  } else {
742  // Ignore $includeProtocolRelative in this case
743  // This case exists for pre-1.6 compatibility, and we can safely assume
744  // that '//' won't appear in a pre-1.6 config because protocol-relative
745  // URLs weren't supported until 1.18
746  $retval = $wgUrlProtocols;
747  }
748 
749  // Cache return value
750  if ( $includeProtocolRelative ) {
751  $withProtRel = $retval;
752  } else {
753  $withoutProtRel = $retval;
754  }
755  return $retval;
756 }
757 
765  return wfUrlProtocols( false );
766 }
767 
793 function wfParseUrl( $url ) {
794  global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
795 
796  // Protocol-relative URLs are handled really badly by parse_url(). It's so
797  // bad that the easiest way to handle them is to just prepend 'http:' and
798  // strip the protocol out later.
799  $wasRelative = substr( $url, 0, 2 ) == '//';
800  if ( $wasRelative ) {
801  $url = "http:$url";
802  }
803  AtEase::suppressWarnings();
804  $bits = parse_url( $url );
805  AtEase::restoreWarnings();
806  // parse_url() returns an array without scheme for some invalid URLs, e.g.
807  // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
808  if ( !$bits || !isset( $bits['scheme'] ) ) {
809  return false;
810  }
811 
812  // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
813  $bits['scheme'] = strtolower( $bits['scheme'] );
814 
815  // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
816  if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
817  $bits['delimiter'] = '://';
818  } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
819  $bits['delimiter'] = ':';
820  // parse_url detects for news: and mailto: the host part of an url as path
821  // We have to correct this wrong detection
822  if ( isset( $bits['path'] ) ) {
823  $bits['host'] = $bits['path'];
824  $bits['path'] = '';
825  }
826  } else {
827  return false;
828  }
829 
830  /* Provide an empty host for eg. file:/// urls (see T30627) */
831  if ( !isset( $bits['host'] ) ) {
832  $bits['host'] = '';
833 
834  // See T47069
835  if ( isset( $bits['path'] ) ) {
836  /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
837  if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
838  $bits['path'] = '/' . $bits['path'];
839  }
840  } else {
841  $bits['path'] = '';
842  }
843  }
844 
845  // If the URL was protocol-relative, fix scheme and delimiter
846  if ( $wasRelative ) {
847  $bits['scheme'] = '';
848  $bits['delimiter'] = '//';
849  }
850  return $bits;
851 }
852 
863 function wfExpandIRI( $url ) {
864  return preg_replace_callback(
865  '/((?:%[89A-F][0-9A-F])+)/i',
866  function ( array $matches ) {
867  return urldecode( $matches[1] );
868  },
869  wfExpandUrl( $url )
870  );
871 }
872 
879 function wfMatchesDomainList( $url, $domains ) {
880  $bits = wfParseUrl( $url );
881  if ( is_array( $bits ) && isset( $bits['host'] ) ) {
882  $host = '.' . $bits['host'];
883  foreach ( (array)$domains as $domain ) {
884  $domain = '.' . $domain;
885  if ( substr( $host, -strlen( $domain ) ) === $domain ) {
886  return true;
887  }
888  }
889  }
890  return false;
891 }
892 
913 function wfDebug( $text, $dest = 'all', array $context = [] ) {
915 
916  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
917  return;
918  }
919 
920  $text = trim( $text );
921 
922  if ( $wgDebugLogPrefix !== '' ) {
923  $context['prefix'] = $wgDebugLogPrefix;
924  }
925  $context['private'] = ( $dest === false || $dest === 'private' );
926 
927  $logger = LoggerFactory::getInstance( 'wfDebug' );
928  $logger->debug( $text, $context );
929 }
930 
935 function wfIsDebugRawPage() {
936  static $cache;
937  if ( $cache !== null ) {
938  return $cache;
939  }
940  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
941  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
942  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
943  || MW_ENTRY_POINT === 'load'
944  ) {
945  $cache = true;
946  } else {
947  $cache = false;
948  }
949  return $cache;
950 }
951 
957 function wfDebugMem( $exact = false ) {
958  $mem = memory_get_usage();
959  if ( !$exact ) {
960  $mem = floor( $mem / 1024 ) . ' KiB';
961  } else {
962  $mem .= ' B';
963  }
964  wfDebug( "Memory usage: $mem\n" );
965 }
966 
992 function wfDebugLog(
993  $logGroup, $text, $dest = 'all', array $context = []
994 ) {
995  $text = trim( $text );
996 
997  $logger = LoggerFactory::getInstance( $logGroup );
998  $context['private'] = ( $dest === false || $dest === 'private' );
999  $logger->info( $text, $context );
1000 }
1001 
1010 function wfLogDBError( $text, array $context = [] ) {
1011  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1012  $logger->error( trim( $text ), $context );
1013 }
1014 
1030 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1031  if ( is_string( $version ) || $version === false ) {
1032  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1033  } else {
1034  throw new Exception(
1035  "MediaWiki version must either be a string or false. " .
1036  "Example valid version: '1.33'"
1037  );
1038  }
1039 }
1040 
1051 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1052  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1053 }
1054 
1064 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1065  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1066 }
1067 
1074  $request = $context->getRequest();
1075 
1076  $profiler = Profiler::instance();
1077  $profiler->setContext( $context );
1078  $profiler->logData();
1079 
1080  // Send out any buffered statsd metrics as needed
1082  MediaWikiServices::getInstance()->getStatsdDataFactory(),
1083  $context->getConfig()
1084  );
1085 }
1086 
1094 function wfIncrStats( $key, $count = 1 ) {
1095  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1096  $stats->updateCount( $key, $count );
1097 }
1098 
1104 function wfReadOnly() {
1105  return MediaWikiServices::getInstance()->getReadOnlyMode()
1106  ->isReadOnly();
1107 }
1108 
1117 function wfReadOnlyReason() {
1118  return MediaWikiServices::getInstance()->getReadOnlyMode()
1119  ->getReason();
1120 }
1121 
1129  return MediaWikiServices::getInstance()->getConfiguredReadOnlyMode()
1130  ->getReason();
1131 }
1132 
1148 function wfGetLangObj( $langcode = false ) {
1149  # Identify which language to get or create a language object for.
1150  # Using is_object here due to Stub objects.
1151  if ( is_object( $langcode ) ) {
1152  # Great, we already have the object (hopefully)!
1153  return $langcode;
1154  }
1155 
1156  global $wgLanguageCode;
1157  $services = MediaWikiServices::getInstance();
1158  if ( $langcode === true || $langcode === $wgLanguageCode ) {
1159  # $langcode is the language code of the wikis content language object.
1160  # or it is a boolean and value is true
1161  return $services->getContentLanguage();
1162  }
1163 
1164  global $wgLang;
1165  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1166  # $langcode is the language code of user language object.
1167  # or it was a boolean and value is false
1168  return $wgLang;
1169  }
1170 
1171  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1172  if ( in_array( $langcode, $validCodes ) ) {
1173  # $langcode corresponds to a valid language.
1174  return $services->getLanguageFactory()->getLanguage( $langcode );
1175  }
1176 
1177  # $langcode is a string, but not a valid language code; use content language.
1178  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1179  return $services->getContentLanguage();
1180 }
1181 
1198 function wfMessage( $key, ...$params ) {
1199  $message = new Message( $key );
1200 
1201  // We call Message::params() to reduce code duplication
1202  if ( $params ) {
1203  $message->params( ...$params );
1204  }
1205 
1206  return $message;
1207 }
1208 
1221 function wfMessageFallback( ...$keys ) {
1222  return Message::newFallbackSequence( ...$keys );
1223 }
1224 
1233 function wfMsgReplaceArgs( $message, $args ) {
1234  # Fix windows line-endings
1235  # Some messages are split with explode("\n", $msg)
1236  $message = str_replace( "\r", '', $message );
1237 
1238  // Replace arguments
1239  if ( is_array( $args ) && $args ) {
1240  if ( is_array( $args[0] ) ) {
1241  $args = array_values( $args[0] );
1242  }
1243  $replacementKeys = [];
1244  foreach ( $args as $n => $param ) {
1245  $replacementKeys['$' . ( $n + 1 )] = $param;
1246  }
1247  $message = strtr( $message, $replacementKeys );
1248  }
1249 
1250  return $message;
1251 }
1252 
1260 function wfHostname() {
1261  static $host;
1262  if ( $host === null ) {
1263  # Hostname overriding
1264  global $wgOverrideHostname;
1265  if ( $wgOverrideHostname !== false ) {
1266  # Set static and skip any detection
1267  $host = $wgOverrideHostname;
1268  return $host;
1269  }
1270 
1271  if ( function_exists( 'posix_uname' ) ) {
1272  // This function not present on Windows
1273  $uname = posix_uname();
1274  } else {
1275  $uname = false;
1276  }
1277  if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1278  $host = $uname['nodename'];
1279  } elseif ( getenv( 'COMPUTERNAME' ) ) {
1280  # Windows computer name
1281  $host = getenv( 'COMPUTERNAME' );
1282  } else {
1283  # This may be a virtual server.
1284  $host = $_SERVER['SERVER_NAME'];
1285  }
1286  }
1287  return $host;
1288 }
1289 
1300 function wfReportTime( $nonce = null ) {
1301  global $wgShowHostnames;
1302 
1303  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1304  // seconds to milliseconds
1305  $responseTime = round( $elapsed * 1000 );
1306  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1307  if ( $wgShowHostnames ) {
1308  $reportVars['wgHostname'] = wfHostname();
1309  }
1310  return Skin::makeVariablesScript( $reportVars, $nonce );
1311 }
1312 
1323 function wfDebugBacktrace( $limit = 0 ) {
1324  static $disabled = null;
1325 
1326  if ( $disabled === null ) {
1327  $disabled = !function_exists( 'debug_backtrace' );
1328  if ( $disabled ) {
1329  wfDebug( "debug_backtrace() is disabled\n" );
1330  }
1331  }
1332  if ( $disabled ) {
1333  return [];
1334  }
1335 
1336  if ( $limit ) {
1337  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1338  } else {
1339  return array_slice( debug_backtrace(), 1 );
1340  }
1341 }
1342 
1351 function wfBacktrace( $raw = null ) {
1352  global $wgCommandLineMode;
1353 
1354  if ( $raw === null ) {
1355  $raw = $wgCommandLineMode;
1356  }
1357 
1358  if ( $raw ) {
1359  $frameFormat = "%s line %s calls %s()\n";
1360  $traceFormat = "%s";
1361  } else {
1362  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1363  $traceFormat = "<ul>\n%s</ul>\n";
1364  }
1365 
1366  $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1367  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1368  $line = $frame['line'] ?? '-';
1369  $call = $frame['function'];
1370  if ( !empty( $frame['class'] ) ) {
1371  $call = $frame['class'] . $frame['type'] . $call;
1372  }
1373  return sprintf( $frameFormat, $file, $line, $call );
1374  }, wfDebugBacktrace() );
1375 
1376  return sprintf( $traceFormat, implode( '', $frames ) );
1377 }
1378 
1388 function wfGetCaller( $level = 2 ) {
1389  $backtrace = wfDebugBacktrace( $level + 1 );
1390  if ( isset( $backtrace[$level] ) ) {
1391  return wfFormatStackFrame( $backtrace[$level] );
1392  } else {
1393  return 'unknown';
1394  }
1395 }
1396 
1404 function wfGetAllCallers( $limit = 3 ) {
1405  $trace = array_reverse( wfDebugBacktrace() );
1406  if ( !$limit || $limit > count( $trace ) - 1 ) {
1407  $limit = count( $trace ) - 1;
1408  }
1409  $trace = array_slice( $trace, -$limit - 1, $limit );
1410  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1411 }
1412 
1419 function wfFormatStackFrame( $frame ) {
1420  if ( !isset( $frame['function'] ) ) {
1421  return 'NO_FUNCTION_GIVEN';
1422  }
1423  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1424  $frame['class'] . $frame['type'] . $frame['function'] :
1425  $frame['function'];
1426 }
1427 
1428 /* Some generic result counters, pulled out of SearchEngine */
1429 
1437 function wfShowingResults( $offset, $limit ) {
1438  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1439 }
1440 
1450 function wfClientAcceptsGzip( $force = false ) {
1451  static $result = null;
1452  if ( $result === null || $force ) {
1453  $result = false;
1454  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1455  # @todo FIXME: We may want to blacklist some broken browsers
1456  $m = [];
1457  if ( preg_match(
1458  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1459  $_SERVER['HTTP_ACCEPT_ENCODING'],
1460  $m
1461  )
1462  ) {
1463  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1464  $result = false;
1465  return $result;
1466  }
1467  wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
1468  $result = true;
1469  }
1470  }
1471  }
1472  return $result;
1473 }
1474 
1485 function wfEscapeWikiText( $text ) {
1486  global $wgEnableMagicLinks;
1487  static $repl = null, $repl2 = null;
1488  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1489  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1490  // in those situations
1491  $repl = [
1492  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1493  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1494  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1495  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1496  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1497  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1498  "\n " => "\n&#32;", "\r " => "\r&#32;",
1499  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1500  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1501  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1502  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1503  '__' => '_&#95;', '://' => '&#58;//',
1504  ];
1505 
1506  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1507  // We have to catch everything "\s" matches in PCRE
1508  foreach ( $magicLinks as $magic ) {
1509  $repl["$magic "] = "$magic&#32;";
1510  $repl["$magic\t"] = "$magic&#9;";
1511  $repl["$magic\r"] = "$magic&#13;";
1512  $repl["$magic\n"] = "$magic&#10;";
1513  $repl["$magic\f"] = "$magic&#12;";
1514  }
1515 
1516  // And handle protocols that don't use "://"
1517  global $wgUrlProtocols;
1518  $repl2 = [];
1519  foreach ( $wgUrlProtocols as $prot ) {
1520  if ( substr( $prot, -1 ) === ':' ) {
1521  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1522  }
1523  }
1524  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1525  }
1526  $text = substr( strtr( "\n$text", $repl ), 1 );
1527  $text = preg_replace( $repl2, '$1&#58;', $text );
1528  return $text;
1529 }
1530 
1541 function wfSetVar( &$dest, $source, $force = false ) {
1542  $temp = $dest;
1543  if ( $source !== null || $force ) {
1544  $dest = $source;
1545  }
1546  return $temp;
1547 }
1548 
1558 function wfSetBit( &$dest, $bit, $state = true ) {
1559  $temp = (bool)( $dest & $bit );
1560  if ( $state !== null ) {
1561  if ( $state ) {
1562  $dest |= $bit;
1563  } else {
1564  $dest &= ~$bit;
1565  }
1566  }
1567  return $temp;
1568 }
1569 
1576 function wfVarDump( $var ) {
1577  global $wgOut;
1578  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1579  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1580  print $s;
1581  } else {
1582  $wgOut->addHTML( $s );
1583  }
1584 }
1585 
1593 function wfHttpError( $code, $label, $desc ) {
1594  global $wgOut;
1595  HttpStatus::header( $code );
1596  if ( $wgOut ) {
1597  $wgOut->disable();
1598  $wgOut->sendCacheControl();
1599  }
1600 
1602  header( 'Content-type: text/html; charset=utf-8' );
1603  ob_start();
1604  print '<!DOCTYPE html>' .
1605  '<html><head><title>' .
1606  htmlspecialchars( $label ) .
1607  '</title></head><body><h1>' .
1608  htmlspecialchars( $label ) .
1609  '</h1><p>' .
1610  nl2br( htmlspecialchars( $desc ) ) .
1611  "</p></body></html>\n";
1612  header( 'Content-Length: ' . ob_get_length() );
1613  ob_end_flush();
1614 }
1615 
1633 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1634  if ( $resetGzipEncoding ) {
1635  // Suppress Content-Encoding and Content-Length
1636  // headers from OutputHandler::handle.
1639  }
1640  while ( $status = ob_get_status() ) {
1641  if ( isset( $status['flags'] ) ) {
1642  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1643  $deleteable = ( $status['flags'] & $flags ) === $flags;
1644  } elseif ( isset( $status['del'] ) ) {
1645  $deleteable = $status['del'];
1646  } else {
1647  // Guess that any PHP-internal setting can't be removed.
1648  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1649  }
1650  if ( !$deleteable ) {
1651  // Give up, and hope the result doesn't break
1652  // output behavior.
1653  break;
1654  }
1655  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1656  // Unit testing barrier to prevent this function from breaking PHPUnit.
1657  break;
1658  }
1659  if ( !ob_end_clean() ) {
1660  // Could not remove output buffer handler; abort now
1661  // to avoid getting in some kind of infinite loop.
1662  break;
1663  }
1664  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1665  // Reset the 'Content-Encoding' field set by this handler
1666  // so we can start fresh.
1667  header_remove( 'Content-Encoding' );
1668  break;
1669  }
1670  }
1671 }
1672 
1686  wfResetOutputBuffers( false );
1687 }
1688 
1697 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1698  # No arg means accept anything (per HTTP spec)
1699  if ( !$accept ) {
1700  return [ $def => 1.0 ];
1701  }
1702 
1703  $prefs = [];
1704 
1705  $parts = explode( ',', $accept );
1706 
1707  foreach ( $parts as $part ) {
1708  # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1709  $values = explode( ';', trim( $part ) );
1710  $match = [];
1711  if ( count( $values ) == 1 ) {
1712  $prefs[$values[0]] = 1.0;
1713  } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1714  $prefs[$values[0]] = floatval( $match[1] );
1715  }
1716  }
1717 
1718  return $prefs;
1719 }
1720 
1733 function mimeTypeMatch( $type, $avail ) {
1734  if ( array_key_exists( $type, $avail ) ) {
1735  return $type;
1736  } else {
1737  $mainType = explode( '/', $type )[0];
1738  if ( array_key_exists( "$mainType/*", $avail ) ) {
1739  return "$mainType/*";
1740  } elseif ( array_key_exists( '*/*', $avail ) ) {
1741  return '*/*';
1742  } else {
1743  return null;
1744  }
1745  }
1746 }
1747 
1762 function wfNegotiateType( $cprefs, $sprefs ) {
1763  $combine = [];
1764 
1765  foreach ( array_keys( $sprefs ) as $type ) {
1766  $subType = explode( '/', $type )[1];
1767  if ( $subType != '*' ) {
1768  $ckey = mimeTypeMatch( $type, $cprefs );
1769  if ( $ckey ) {
1770  $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1771  }
1772  }
1773  }
1774 
1775  foreach ( array_keys( $cprefs ) as $type ) {
1776  $subType = explode( '/', $type )[1];
1777  if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
1778  $skey = mimeTypeMatch( $type, $sprefs );
1779  if ( $skey ) {
1780  $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1781  }
1782  }
1783  }
1784 
1785  $bestq = 0;
1786  $besttype = null;
1787 
1788  foreach ( array_keys( $combine ) as $type ) {
1789  if ( $combine[$type] > $bestq ) {
1790  $besttype = $type;
1791  $bestq = $combine[$type];
1792  }
1793  }
1794 
1795  return $besttype;
1796 }
1797 
1806 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1807  $ret = MWTimestamp::convert( $outputtype, $ts );
1808  if ( $ret === false ) {
1809  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
1810  }
1811  return $ret;
1812 }
1813 
1822 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1823  if ( $ts === null ) {
1824  return null;
1825  } else {
1826  return wfTimestamp( $outputtype, $ts );
1827  }
1828 }
1829 
1835 function wfTimestampNow() {
1836  return MWTimestamp::now( TS_MW );
1837 }
1838 
1844 function wfIsWindows() {
1845  static $isWindows = null;
1846  if ( $isWindows === null ) {
1847  $isWindows = strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN';
1848  }
1849  return $isWindows;
1850 }
1851 
1858 function wfIsCLI() {
1859  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1860 }
1861 
1873 function wfTempDir() {
1874  global $wgTmpDirectory;
1875 
1876  if ( $wgTmpDirectory !== false ) {
1877  return $wgTmpDirectory;
1878  }
1879 
1881 }
1882 
1892 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1893  global $wgDirectoryMode;
1894 
1895  if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1896  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1897  }
1898 
1899  if ( $caller !== null ) {
1900  wfDebug( "$caller: called wfMkdirParents($dir)\n" );
1901  }
1902 
1903  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1904  return true;
1905  }
1906 
1907  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1908 
1909  if ( $mode === null ) {
1910  $mode = $wgDirectoryMode;
1911  }
1912 
1913  // Turn off the normal warning, we're doing our own below
1914  AtEase::suppressWarnings();
1915  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1916  AtEase::restoreWarnings();
1917 
1918  if ( !$ok ) {
1919  // directory may have been created on another request since we last checked
1920  if ( is_dir( $dir ) ) {
1921  return true;
1922  }
1923 
1924  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1925  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1926  }
1927  return $ok;
1928 }
1929 
1935 function wfRecursiveRemoveDir( $dir ) {
1936  wfDebug( __FUNCTION__ . "( $dir )\n" );
1937  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1938  if ( is_dir( $dir ) ) {
1939  $objects = scandir( $dir );
1940  foreach ( $objects as $object ) {
1941  if ( $object != "." && $object != ".." ) {
1942  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1943  wfRecursiveRemoveDir( $dir . '/' . $object );
1944  } else {
1945  unlink( $dir . '/' . $object );
1946  }
1947  }
1948  }
1949  reset( $objects );
1950  rmdir( $dir );
1951  }
1952 }
1953 
1960 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1961  $accForFormat = $acc >= 0 ? $acc : 0;
1962  $ret = sprintf( "%.${accForFormat}f", $nr );
1963  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1964 }
1965 
1989 function wfIniGetBool( $setting ) {
1990  return wfStringToBool( ini_get( $setting ) );
1991 }
1992 
2005 function wfStringToBool( $val ) {
2006  $val = strtolower( $val );
2007  // 'on' and 'true' can't have whitespace around them, but '1' can.
2008  return $val == 'on'
2009  || $val == 'true'
2010  || $val == 'yes'
2011  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2012 }
2013 
2026 function wfEscapeShellArg( ...$args ) {
2027  return Shell::escape( ...$args );
2028 }
2029 
2054 function wfShellExec( $cmd, &$retval = null, $environ = [],
2055  $limits = [], $options = []
2056 ) {
2057  if ( Shell::isDisabled() ) {
2058  $retval = 1;
2059  // Backwards compatibility be upon us...
2060  return 'Unable to run external programs, proc_open() is disabled.';
2061  }
2062 
2063  if ( is_array( $cmd ) ) {
2064  $cmd = Shell::escape( $cmd );
2065  }
2066 
2067  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2068  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
2069 
2070  try {
2071  $result = Shell::command( [] )
2072  ->unsafeParams( (array)$cmd )
2073  ->environment( $environ )
2074  ->limits( $limits )
2075  ->includeStderr( $includeStderr )
2076  ->profileMethod( $profileMethod )
2077  // For b/c
2078  ->restrict( Shell::RESTRICT_NONE )
2079  ->execute();
2080  } catch ( ProcOpenError $ex ) {
2081  $retval = -1;
2082  return '';
2083  }
2084 
2085  $retval = $result->getExitCode();
2086 
2087  return $result->getStdout();
2088 }
2089 
2107 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
2108  return wfShellExec( $cmd, $retval, $environ, $limits,
2109  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
2110 }
2111 
2127 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2128  global $wgPhpCli;
2129  // Give site config file a chance to run the script in a wrapper.
2130  // The caller may likely want to call wfBasename() on $script.
2131  Hooks::run( 'wfShellWikiCmd', [ &$script, &$parameters, &$options ] );
2132  $cmd = [ $options['php'] ?? $wgPhpCli ];
2133  if ( isset( $options['wrapper'] ) ) {
2134  $cmd[] = $options['wrapper'];
2135  }
2136  $cmd[] = $script;
2137  // Escape each parameter for shell
2138  return Shell::escape( array_merge( $cmd, $parameters ) );
2139 }
2140 
2152 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2153  global $wgDiff3;
2154 
2155  # This check may also protect against code injection in
2156  # case of broken installations.
2157  AtEase::suppressWarnings();
2158  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2159  AtEase::restoreWarnings();
2160 
2161  if ( !$haveDiff3 ) {
2162  wfDebug( "diff3 not found\n" );
2163  return false;
2164  }
2165 
2166  # Make temporary files
2167  $td = wfTempDir();
2168  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2169  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2170  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2171 
2172  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2173  # a newline character. To avoid this, we normalize the trailing whitespace before
2174  # creating the diff.
2175 
2176  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2177  fclose( $oldtextFile );
2178  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2179  fclose( $mytextFile );
2180  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2181  fclose( $yourtextFile );
2182 
2183  # Check for a conflict
2184  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2185  $oldtextName, $yourtextName );
2186  $handle = popen( $cmd, 'r' );
2187 
2188  $mergeAttemptResult = '';
2189  do {
2190  $data = fread( $handle, 8192 );
2191  if ( strlen( $data ) == 0 ) {
2192  break;
2193  }
2194  $mergeAttemptResult .= $data;
2195  } while ( true );
2196  pclose( $handle );
2197 
2198  $conflict = $mergeAttemptResult !== '';
2199 
2200  # Merge differences
2201  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2202  $oldtextName, $yourtextName );
2203  $handle = popen( $cmd, 'r' );
2204  $result = '';
2205  do {
2206  $data = fread( $handle, 8192 );
2207  if ( strlen( $data ) == 0 ) {
2208  break;
2209  }
2210  $result .= $data;
2211  } while ( true );
2212  pclose( $handle );
2213  unlink( $mytextName );
2214  unlink( $oldtextName );
2215  unlink( $yourtextName );
2216 
2217  if ( $result === '' && $old !== '' && !$conflict ) {
2218  wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
2219  $conflict = true;
2220  }
2221  return !$conflict;
2222 }
2223 
2235 function wfDiff( $before, $after, $params = '-u' ) {
2236  if ( $before == $after ) {
2237  return '';
2238  }
2239 
2240  global $wgDiff;
2241  AtEase::suppressWarnings();
2242  $haveDiff = $wgDiff && file_exists( $wgDiff );
2243  AtEase::restoreWarnings();
2244 
2245  # This check may also protect against code injection in
2246  # case of broken installations.
2247  if ( !$haveDiff ) {
2248  wfDebug( "diff executable not found\n" );
2249  $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2250  $format = new UnifiedDiffFormatter();
2251  return $format->format( $diffs );
2252  }
2253 
2254  # Make temporary files
2255  $td = wfTempDir();
2256  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2257  $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2258 
2259  fwrite( $oldtextFile, $before );
2260  fclose( $oldtextFile );
2261  fwrite( $newtextFile, $after );
2262  fclose( $newtextFile );
2263 
2264  // Get the diff of the two files
2265  $cmd = "$wgDiff " . $params . ' ' . Shell::escape( $oldtextName, $newtextName );
2266 
2267  $h = popen( $cmd, 'r' );
2268  if ( !$h ) {
2269  unlink( $oldtextName );
2270  unlink( $newtextName );
2271  throw new Exception( __FUNCTION__ . '(): popen() failed' );
2272  }
2273 
2274  $diff = '';
2275 
2276  do {
2277  $data = fread( $h, 8192 );
2278  if ( strlen( $data ) == 0 ) {
2279  break;
2280  }
2281  $diff .= $data;
2282  } while ( true );
2283 
2284  // Clean up
2285  pclose( $h );
2286  unlink( $oldtextName );
2287  unlink( $newtextName );
2288 
2289  // Kill the --- and +++ lines. They're not useful.
2290  $diff_lines = explode( "\n", $diff );
2291  if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
2292  unset( $diff_lines[0] );
2293  }
2294  if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
2295  unset( $diff_lines[1] );
2296  }
2297 
2298  $diff = implode( "\n", $diff_lines );
2299 
2300  return $diff;
2301 }
2302 
2315 function wfBaseName( $path, $suffix = '' ) {
2316  if ( $suffix == '' ) {
2317  $encSuffix = '';
2318  } else {
2319  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2320  }
2321 
2322  $matches = [];
2323  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2324  return $matches[1];
2325  } else {
2326  return '';
2327  }
2328 }
2329 
2339 function wfRelativePath( $path, $from ) {
2340  // Normalize mixed input on Windows...
2341  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2342  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2343 
2344  // Trim trailing slashes -- fix for drive root
2345  $path = rtrim( $path, DIRECTORY_SEPARATOR );
2346  $from = rtrim( $from, DIRECTORY_SEPARATOR );
2347 
2348  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2349  $against = explode( DIRECTORY_SEPARATOR, $from );
2350 
2351  if ( $pieces[0] !== $against[0] ) {
2352  // Non-matching Windows drive letters?
2353  // Return a full path.
2354  return $path;
2355  }
2356 
2357  // Trim off common prefix
2358  while ( count( $pieces ) && count( $against )
2359  && $pieces[0] == $against[0] ) {
2360  array_shift( $pieces );
2361  array_shift( $against );
2362  }
2363 
2364  // relative dots to bump us to the parent
2365  while ( count( $against ) ) {
2366  array_unshift( $pieces, '..' );
2367  array_shift( $against );
2368  }
2369 
2370  array_push( $pieces, wfBaseName( $path ) );
2371 
2372  return implode( DIRECTORY_SEPARATOR, $pieces );
2373 }
2374 
2381 function wfGetPrecompiledData( $name ) {
2382  global $IP;
2383 
2384  $file = "$IP/serialized/$name";
2385  if ( file_exists( $file ) ) {
2386  $blob = file_get_contents( $file );
2387  if ( $blob ) {
2388  return unserialize( $blob );
2389  }
2390  }
2391  return false;
2392 }
2393 
2401 function wfMemcKey( ...$args ) {
2402  return ObjectCache::getLocalClusterInstance()->makeKey( ...$args );
2403 }
2404 
2416 function wfForeignMemcKey( $db, $prefix, ...$args ) {
2417  $keyspace = $prefix ? "$db-$prefix" : $db;
2418  return ObjectCache::getLocalClusterInstance()->makeKeyInternal( $keyspace, $args );
2419 }
2420 
2428 function wfWikiID() {
2429  global $wgDBprefix, $wgDBname;
2430 
2431  if ( $wgDBprefix ) {
2432  return "$wgDBname-$wgDBprefix";
2433  } else {
2434  return $wgDBname;
2435  }
2436 }
2437 
2463 function wfGetDB( $db, $groups = [], $wiki = false ) {
2464  return wfGetLB( $wiki )->getMaintenanceConnectionRef( $db, $groups, $wiki );
2465 }
2466 
2476 function wfGetLB( $wiki = false ) {
2477  if ( $wiki === false ) {
2478  return MediaWikiServices::getInstance()->getDBLoadBalancer();
2479  } else {
2480  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2481  return $factory->getMainLB( $wiki );
2482  }
2483 }
2484 
2492 function wfFindFile( $title, $options = [] ) {
2493  return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2494 }
2495 
2504 function wfLocalFile( $title ) {
2505  return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2506 }
2507 
2515  global $wgMiserMode;
2516  return $wgMiserMode
2517  || ( SiteStats::pages() > 100000
2518  && SiteStats::edits() > 1000000
2519  && SiteStats::users() > 10000 );
2520 }
2521 
2530 function wfScript( $script = 'index' ) {
2532  if ( $script === 'index' ) {
2533  return $wgScript;
2534  } elseif ( $script === 'load' ) {
2535  return $wgLoadScript;
2536  } else {
2537  return "{$wgScriptPath}/{$script}.php";
2538  }
2539 }
2540 
2547 function wfGetScriptUrl() {
2548  wfDeprecated( __FUNCTION__, '1.35' );
2549  if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2550  /* as it was called, minus the query string.
2551  *
2552  * Some sites use Apache rewrite rules to handle subdomains,
2553  * and have PHP set up in a weird way that causes PHP_SELF
2554  * to contain the rewritten URL instead of the one that the
2555  * outside world sees.
2556  *
2557  * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2558  * provides containing the "before" URL.
2559  */
2560  return $_SERVER['SCRIPT_NAME'];
2561  } else {
2562  return $_SERVER['URL'];
2563  }
2564 }
2565 
2573 function wfBoolToStr( $value ) {
2574  return $value ? 'true' : 'false';
2575 }
2576 
2582 function wfGetNull() {
2583  return wfIsWindows() ? 'NUL' : '/dev/null';
2584 }
2585 
2609  $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
2610 ) {
2611  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2612 
2613  if ( $cluster === '*' ) {
2614  $cluster = false;
2615  $domain = false;
2616  } elseif ( $wiki === false ) {
2617  $domain = $lbFactory->getLocalDomainID();
2618  } else {
2619  $domain = $wiki;
2620  }
2621 
2622  $opts = [
2623  'domain' => $domain,
2624  'cluster' => $cluster,
2625  // B/C: first argument used to be "max seconds of lag"; ignore such values
2626  'ifWritesSince' => ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null
2627  ];
2628  if ( $timeout !== null ) {
2629  $opts['timeout'] = $timeout;
2630  }
2631 
2632  return $lbFactory->waitForReplication( $opts );
2633 }
2634 
2643 function wfStripIllegalFilenameChars( $name ) {
2644  global $wgIllegalFileChars;
2645  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2646  $name = preg_replace(
2647  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2648  '-',
2649  $name
2650  );
2651  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2652  $name = wfBaseName( $name );
2653  return $name;
2654 }
2655 
2662 function wfMemoryLimit( $newLimit ) {
2663  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2664  // If the INI config is already unlimited, there is nothing larger
2665  if ( $oldLimit != -1 ) {
2666  $newLimit = wfShorthandToInteger( $newLimit );
2667  if ( $newLimit == -1 ) {
2668  wfDebug( "Removing PHP's memory limit\n" );
2669  Wikimedia\suppressWarnings();
2670  ini_set( 'memory_limit', $newLimit );
2671  Wikimedia\restoreWarnings();
2672  } elseif ( $newLimit > $oldLimit ) {
2673  wfDebug( "Raising PHP's memory limit to $newLimit bytes\n" );
2674  Wikimedia\suppressWarnings();
2675  ini_set( 'memory_limit', $newLimit );
2676  Wikimedia\restoreWarnings();
2677  }
2678  }
2679 }
2680 
2689 
2690  $timeLimit = (int)ini_get( 'max_execution_time' );
2691  // Note that CLI scripts use 0
2692  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2693  set_time_limit( $wgTransactionalTimeLimit );
2694  }
2695 
2696  ignore_user_abort( true ); // ignore client disconnects
2697 
2698  return $timeLimit;
2699 }
2700 
2708 function wfShorthandToInteger( $string = '', $default = -1 ) {
2709  $string = trim( $string );
2710  if ( $string === '' ) {
2711  return $default;
2712  }
2713  $last = $string[strlen( $string ) - 1];
2714  $val = intval( $string );
2715  switch ( $last ) {
2716  case 'g':
2717  case 'G':
2718  $val *= 1024;
2719  // break intentionally missing
2720  case 'm':
2721  case 'M':
2722  $val *= 1024;
2723  // break intentionally missing
2724  case 'k':
2725  case 'K':
2726  $val *= 1024;
2727  }
2728 
2729  return $val;
2730 }
2731 
2739 function wfGetCache( $cacheType ) {
2740  return ObjectCache::getInstance( $cacheType );
2741 }
2742 
2749 function wfGetMainCache() {
2751 }
2752 
2767 function wfUnpack( $format, $data, $length = false ) {
2768  if ( $length !== false ) {
2769  $realLen = strlen( $data );
2770  if ( $realLen < $length ) {
2771  throw new MWException( "Tried to use wfUnpack on a "
2772  . "string of length $realLen, but needed one "
2773  . "of at least length $length."
2774  );
2775  }
2776  }
2777 
2778  Wikimedia\suppressWarnings();
2779  $result = unpack( $format, $data );
2780  Wikimedia\restoreWarnings();
2781 
2782  if ( $result === false ) {
2783  // If it cannot extract the packed data.
2784  throw new MWException( "unpack could not unpack binary data" );
2785  }
2786  return $result;
2787 }
2788 
2805 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
2806  $services = MediaWikiServices::getInstance();
2807  if ( $blacklist !== null ) {
2808  wfDeprecated( __FUNCTION__ . ' with $blacklist parameter', '1.34' );
2809  return ( new BadFileLookup(
2810  function () use ( $blacklist ) {
2811  return $blacklist;
2812  },
2813  $services->getLocalServerObjectCache(),
2814  $services->getRepoGroup(),
2815  $services->getTitleParser()
2816  ) )->isBadFile( $name, $contextTitle ?: null );
2817  }
2818  return $services->getBadFileLookup()->isBadFile( $name, $contextTitle ?: null );
2819 }
2820 
2828 function wfCanIPUseHTTPS( $ip ) {
2829  $canDo = true;
2830  Hooks::run( 'CanIPUseHTTPS', [ $ip, &$canDo ] );
2831  return (bool)$canDo;
2832 }
2833 
2841 function wfIsInfinity( $str ) {
2842  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2843  return in_array( $str, ExpiryDef::INFINITY_VALS );
2844 }
2845 
2860 function wfThumbIsStandard( File $file, array $params ) {
2862 
2863  $multipliers = [ 1 ];
2864  if ( $wgResponsiveImages ) {
2865  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2866  // @see Linker::processResponsiveImages
2867  $multipliers[] = 1.5;
2868  $multipliers[] = 2;
2869  }
2870 
2871  $handler = $file->getHandler();
2872  if ( !$handler || !isset( $params['width'] ) ) {
2873  return false;
2874  }
2875 
2876  $basicParams = [];
2877  if ( isset( $params['page'] ) ) {
2878  $basicParams['page'] = $params['page'];
2879  }
2880 
2881  $thumbLimits = [];
2882  $imageLimits = [];
2883  // Expand limits to account for multipliers
2884  foreach ( $multipliers as $multiplier ) {
2885  $thumbLimits = array_merge( $thumbLimits, array_map(
2886  function ( $width ) use ( $multiplier ) {
2887  return round( $width * $multiplier );
2888  }, $wgThumbLimits )
2889  );
2890  $imageLimits = array_merge( $imageLimits, array_map(
2891  function ( $pair ) use ( $multiplier ) {
2892  return [
2893  round( $pair[0] * $multiplier ),
2894  round( $pair[1] * $multiplier ),
2895  ];
2896  }, $wgImageLimits )
2897  );
2898  }
2899 
2900  // Check if the width matches one of $wgThumbLimits
2901  if ( in_array( $params['width'], $thumbLimits ) ) {
2902  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2903  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2904  $handler->normaliseParams( $file, $normalParams );
2905  } else {
2906  // If not, then check if the width matchs one of $wgImageLimits
2907  $match = false;
2908  foreach ( $imageLimits as $pair ) {
2909  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2910  // Decide whether the thumbnail should be scaled on width or height.
2911  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2912  $handler->normaliseParams( $file, $normalParams );
2913  // Check if this standard thumbnail size maps to the given width
2914  if ( $normalParams['width'] == $params['width'] ) {
2915  $match = true;
2916  break;
2917  }
2918  }
2919  if ( !$match ) {
2920  return false; // not standard for description pages
2921  }
2922  }
2923 
2924  // Check that the given values for non-page, non-width, params are just defaults
2925  foreach ( $params as $key => $value ) {
2926  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2927  return false;
2928  }
2929  }
2930 
2931  return true;
2932 }
2933 
2946 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2947  // First merge items that are in both arrays
2948  foreach ( $baseArray as $name => &$groupVal ) {
2949  if ( isset( $newValues[$name] ) ) {
2950  $groupVal += $newValues[$name];
2951  }
2952  }
2953  // Now add items that didn't exist yet
2954  $baseArray += $newValues;
2955 
2956  return $baseArray;
2957 }
2958 
2968 function wfGetRusage() {
2969  wfDeprecated( __FUNCTION__, '1.35' );
2970  return getrusage( 0 /* RUSAGE_SELF */ );
2971 }
$wgPhpCli
$wgPhpCli
Executable path of the PHP cli binary.
Definition: DefaultSettings.php:8721
wfArrayInsertAfter
wfArrayInsertAfter(array $array, array $insert, $after)
Insert array into another array after the specified KEY
Definition: GlobalFunctions.php:207
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
wfMergeErrorArrays
wfMergeErrorArrays(... $args)
Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e....
Definition: GlobalFunctions.php:181
wfResetOutputBuffers
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
Definition: GlobalFunctions.php:1633
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1221
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1542
PROTO_CANONICAL
const PROTO_CANONICAL
Definition: Defines.php:212
wfCanIPUseHTTPS
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
Definition: GlobalFunctions.php:2828
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:272
SiteStats\users
static users()
Definition: SiteStats.php:121
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1084
PROTO_INTERNAL
const PROTO_INTERNAL
Definition: Defines.php:213
MediaWiki\ProcOpenError
Definition: ProcOpenError.php:25
wfDiff
wfDiff( $before, $after, $params='-u')
Returns unified plain-text diff of two texts.
Definition: GlobalFunctions.php:2235
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1661
$wgDebugRawPage
$wgDebugRawPage
If true, log debugging data from action=raw and load.php.
Definition: DefaultSettings.php:6500
wfThumbIsStandard
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
Definition: GlobalFunctions.php:2860
$wgTmpDirectory
$wgTmpDirectory
The local filesystem path to a temporary directory.
Definition: DefaultSettings.php:392
wfArrayPlus2d
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
Definition: GlobalFunctions.php:2946
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:1970
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:63
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:1892
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:144
MediaWiki\BadFileLookup
Definition: BadFileLookup.php:12
$wgDiff3
$wgDiff3
Path to the GNU diff3 utility.
Definition: DefaultSettings.php:7005
wfMerge
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
Definition: GlobalFunctions.php:2152
wfDebugBacktrace
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
Definition: GlobalFunctions.php:1323
wfSetVar
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...
Definition: GlobalFunctions.php:1541
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:2476
wfFormatStackFrame
wfFormatStackFrame( $frame)
Return a string representation of frame.
Definition: GlobalFunctions.php:1419
wfRemoveDotSegments
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
Definition: GlobalFunctions.php:641
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:185
wfSetBit
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
Definition: GlobalFunctions.php:1558
Skin\makeVariablesScript
static makeVariablesScript( $data, $nonce=null)
Definition: Skin.php:388
wfNegotiateType
wfNegotiateType( $cprefs, $sprefs)
Returns the 'best' match between a client's requested internet media types and the server's list of a...
Definition: GlobalFunctions.php:1762
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1806
SiteStats\pages
static pages()
Definition: SiteStats.php:112
wfUnpack
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
Definition: GlobalFunctions.php:2767
wfConfiguredReadOnlyReason
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: GlobalFunctions.php:1128
MessageSpecifier
Definition: MessageSpecifier.php:21
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6692
wfMemoryLimit
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
Definition: GlobalFunctions.php:2662
wfObjectToArray
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
Definition: GlobalFunctions.php:230
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:309
wfArrayDiff2_cmp
wfArrayDiff2_cmp( $a, $b)
Definition: GlobalFunctions.php:122
wfGetScriptUrl
wfGetScriptUrl()
Get the script URL.
Definition: GlobalFunctions.php:2547
$wgDiff
$wgDiff
Path to the GNU diff utility.
Definition: DefaultSettings.php:7010
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2315
wfQueriesMustScale
wfQueriesMustScale()
Should low-performance queries be disabled?
Definition: GlobalFunctions.php:2514
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1260
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1104
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1233
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1198
$s
$s
Definition: mergeMessageFileList.php:185
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1064
wfStringToBool
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
Definition: GlobalFunctions.php:2005
$wgTransactionalTimeLimit
$wgTransactionalTimeLimit
The minimum amount of time that MediaWiki needs for "slow" write request, particularly ones with mult...
Definition: DefaultSettings.php:2391
$wgDebugLogPrefix
$wgDebugLogPrefix
Prefix for debug log lines.
Definition: DefaultSettings.php:6486
wfExpandIRI
wfExpandIRI( $url)
Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode cha...
Definition: GlobalFunctions.php:863
wfWaitForSlaves
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
Definition: GlobalFunctions.php:2608
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:992
$wgDBprefix
$wgDBprefix
Current wiki database table name prefix.
Definition: DefaultSettings.php:1990
wfShellWikiCmd
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:2127
wfBoolToStr
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
Definition: GlobalFunctions.php:2573
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:439
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
Wikimedia\ParamValidator\TypeDef\ExpiryDef
Type definition for expiry timestamps.
Definition: ExpiryDef.php:16
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:793
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:61
wfReportTime
wfReportTime( $nonce=null)
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
Definition: GlobalFunctions.php:1300
wfGetMainCache
wfGetMainCache()
Get the main cache object.
Definition: GlobalFunctions.php:2749
MWException
MediaWiki exception.
Definition: MWException.php:26
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2643
wfGetRusage
wfGetRusage()
Get system resource usage of current request context.
Definition: GlobalFunctions.php:2968
mimeTypeMatch
mimeTypeMatch( $type, $avail)
Checks if a given MIME type matches any of the keys in the given array.
Definition: GlobalFunctions.php:1733
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1030
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2530
wfArrayDiff2
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
Definition: GlobalFunctions.php:113
wfIncrStats
wfIncrStats( $key, $count=1)
Increment a statistics counter.
Definition: GlobalFunctions.php:1094
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1524
$blob
$blob
Definition: testCompression.php:70
wfTransactionalTimeLimit
wfTransactionalTimeLimit()
Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.
Definition: GlobalFunctions.php:2687
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2463
wfUrlProtocolsWithoutProtRel
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
Definition: GlobalFunctions.php:764
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
$matches
$matches
Definition: NoLocalSettings.php:24
$wgLang
$wgLang
Definition: Setup.php:774
$wgLoadScript
$wgLoadScript
The URL path to load.php.
Definition: DefaultSettings.php:193
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:1822
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:211
ObjectCache\getInstance
static getInstance( $id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:78
$args
if( $line===false) $args
Definition: mcc.php:124
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1148
wfCgiToArray
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Definition: GlobalFunctions.php:392
wfLoadSkins
wfLoadSkins(array $skins)
Load multiple skins at once.
Definition: GlobalFunctions.php:99
$title
$title
Definition: testCompression.php:38
MWDebug\deprecated
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition: MWDebug.php:225
wfGetCache
wfGetCache( $cacheType)
Get a specific cache object.
Definition: GlobalFunctions.php:2739
$wgEnableMagicLinks
$wgEnableMagicLinks
Enable the magic links feature of automatically turning ISBN xxx, PMID xxx, RFC xxx into links.
Definition: DefaultSettings.php:4706
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1835
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:913
wfPercent
wfPercent( $nr, int $acc=2, bool $round=true)
Definition: GlobalFunctions.php:1960
wfAcceptToPrefs
wfAcceptToPrefs( $accept, $def=' */*')
Converts an Accept-* header into an array mapping string values to quality factors.
Definition: GlobalFunctions.php:1697
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:209
$wgCanonicalServer
$wgCanonicalServer
Canonical URL of the server, to use in IRC feeds and notification e-mails.
Definition: DefaultSettings.php:114
wfIsDebugRawPage
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
Definition: GlobalFunctions.php:935
wfForeignMemcKey
wfForeignMemcKey( $db, $prefix,... $args)
Make a cache key for a foreign DB.
Definition: GlobalFunctions.php:2416
UnifiedDiffFormatter
A formatter that outputs unified diffs.
Definition: UnifiedDiffFormatter.php:31
wfUrlProtocols
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
Definition: GlobalFunctions.php:719
wfIsBadImage
wfIsBadImage( $name, $contextTitle=false, $blacklist=null)
Determine if an image exists on the 'bad image list'.
Definition: GlobalFunctions.php:2805
wfLoadExtensions
wfLoadExtensions(array $exts)
Load multiple extensions at once.
Definition: GlobalFunctions.php:68
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2428
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1685
wfClientAcceptsGzip
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
Definition: GlobalFunctions.php:1450
$wgUrlProtocols
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
Definition: DefaultSettings.php:4543
$wgExtensionDirectory
$wgExtensionDirectory
Filesystem extensions directory.
Definition: DefaultSettings.php:229
wfIsCLI
wfIsCLI()
Check if we are running from the commandline.
Definition: GlobalFunctions.php:1858
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1844
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:105
$line
$line
Definition: mcc.php:119
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:3064
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2841
wfDebugMem
wfDebugMem( $exact=false)
Send a line giving PHP memory usage.
Definition: GlobalFunctions.php:957
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:208
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1653
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1485
wfAppendToArrayIfNotDefault
wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed)
Appends to second array if $value differs from that in $default.
Definition: GlobalFunctions.php:153
$wgDisableOutputCompression
$wgDisableOutputCompression
Disable output compression (enabled by default if zlib is available)
Definition: DefaultSettings.php:3510
wfVarDump
wfVarDump( $var)
A wrapper around the PHP function var_export().
Definition: GlobalFunctions.php:1576
$wgIllegalFileChars
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
Definition: DefaultSettings.php:471
wfGetNull
wfGetNull()
Get a platform-independent path to the null file, e.g.
Definition: GlobalFunctions.php:2582
TempFSFile\getUsableTempDirectory
static getUsableTempDirectory()
Definition: TempFSFile.php:80
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:451
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1989
$wgOverrideHostname
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
Definition: DefaultSettings.php:6699
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:2492
$context
$context
Definition: load.php:43
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1404
wfLoadExtension
wfLoadExtension( $ext, $path=null)
Load an extension.
Definition: GlobalFunctions.php:47
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
wfLoadSkin
wfLoadSkin( $skin, $path=null)
Load a skin.
Definition: GlobalFunctions.php:84
wfShorthandToInteger
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
Definition: GlobalFunctions.php:2708
$wgImageLimits
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
Definition: DefaultSettings.php:1529
print
print
Definition: opensearch_desc.php:53
wfRandom
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
Definition: GlobalFunctions.php:256
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1873
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2347
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1593
wfReadOnlyReason
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
Definition: GlobalFunctions.php:1117
wfMatchesDomainList
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
Definition: GlobalFunctions.php:879
$cache
$cache
Definition: mcc.php:33
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
wfGetPrecompiledData
wfGetPrecompiledData( $name)
Get an object from the precompiled serialized directory.
Definition: GlobalFunctions.php:2381
wfRecursiveRemoveDir
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:1935
$wgHttpsPort
$wgHttpsPort
For installations where the canonical server is HTTP but HTTPS is optionally supported,...
Definition: DefaultSettings.php:9064
$path
$path
Definition: NoLocalSettings.php:25
Message
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:160
$keys
$keys
Definition: testCompression.php:72
wfBacktrace
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
Definition: GlobalFunctions.php:1351
wfEscapeShellArg
wfEscapeShellArg(... $args)
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2026
$source
$source
Definition: mwdoc-filter.php:34
wfAssembleUrl
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
Definition: GlobalFunctions.php:587
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
wfRelativePath
wfRelativePath( $path, $from)
Generate a relative path name to the given file.
Definition: GlobalFunctions.php:2339
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1051
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:703
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:641
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
MWDebug\warning
static warning( $msg, $callerOffset=1, $level=E_USER_NOTICE, $log='auto')
Adds a warning entry to the log.
Definition: MWDebug.php:180
wfMemcKey
wfMemcKey(... $args)
Make a cache key for the local wiki.
Definition: GlobalFunctions.php:2401
$wgOut
$wgOut
Definition: Setup.php:779
wfGetServerUrl
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
Definition: GlobalFunctions.php:569
$wgScriptPath
$wgScriptPath
The path we should point to.
Definition: DefaultSettings.php:137
$IP
$IP
Definition: WebStart.php:49
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:2504
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:133
Message\newFallbackSequence
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:467
wfShowingResults
wfShowingResults( $offset, $limit)
Definition: GlobalFunctions.php:1437
wfGetCaller
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Definition: GlobalFunctions.php:1388
$wgStyleDirectory
$wgStyleDirectory
Filesystem stylesheets directory.
Definition: DefaultSettings.php:236
wfLogDBError
wfLogDBError( $text, array $context=[])
Log for database errors.
Definition: GlobalFunctions.php:1010
SiteStats\edits
static edits()
Definition: SiteStats.php:94
MW_ENTRY_POINT
const MW_ENTRY_POINT
Definition: api.php:40
$wgInternalServer
$wgInternalServer
Internal server name as known to CDN, if different.
Definition: DefaultSettings.php:2878
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:491
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:2107
MediaWiki\HeaderCallback\warnIfHeadersSent
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
Definition: HeaderCallback.php:70
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1072
Diff
Class representing a 'diff' between two sequences of strings.
Definition: Diff.php:32
wfShellExec
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
Definition: GlobalFunctions.php:2054
wfArrayToCgi
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
Definition: GlobalFunctions.php:347
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:274
$type
$type
Definition: testCompression.php:52