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 
32 use Wikimedia\AtEase\AtEase;
34 use Wikimedia\WrappedString;
35 
46 function wfLoadExtension( $ext, $path = null ) {
47  if ( !$path ) {
48  global $wgExtensionDirectory;
49  $path = "$wgExtensionDirectory/$ext/extension.json";
50  }
52 }
53 
67 function wfLoadExtensions( array $exts ) {
68  global $wgExtensionDirectory;
69  $registry = ExtensionRegistry::getInstance();
70  foreach ( $exts as $ext ) {
71  $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
72  }
73 }
74 
83 function wfLoadSkin( $skin, $path = null ) {
84  if ( !$path ) {
85  global $wgStyleDirectory;
86  $path = "$wgStyleDirectory/$skin/skin.json";
87  }
89 }
90 
98 function wfLoadSkins( array $skins ) {
99  global $wgStyleDirectory;
100  $registry = ExtensionRegistry::getInstance();
101  foreach ( $skins as $skin ) {
102  $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
103  }
104 }
105 
112 function wfArrayDiff2( $a, $b ) {
113  return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
114 }
115 
121 function wfArrayDiff2_cmp( $a, $b ) {
122  if ( is_string( $a ) && is_string( $b ) ) {
123  return strcmp( $a, $b );
124  } elseif ( count( $a ) !== count( $b ) ) {
125  return count( $a ) <=> count( $b );
126  } else {
127  reset( $a );
128  reset( $b );
129  while ( key( $a ) !== null && key( $b ) !== null ) {
130  $valueA = current( $a );
131  $valueB = current( $b );
132  $cmp = strcmp( $valueA, $valueB );
133  if ( $cmp !== 0 ) {
134  return $cmp;
135  }
136  next( $a );
137  next( $b );
138  }
139  return 0;
140  }
141 }
142 
152 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
153  if ( $changed === null ) {
154  throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
155  }
156  if ( $default[$key] !== $value ) {
157  $changed[$key] = $value;
158  }
159 }
160 
180 function wfMergeErrorArrays( ...$args ) {
181  $out = [];
182  foreach ( $args as $errors ) {
183  foreach ( $errors as $params ) {
184  $originalParams = $params;
185  if ( $params[0] instanceof MessageSpecifier ) {
186  $msg = $params[0];
187  $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
188  }
189  # @todo FIXME: Sometimes get nested arrays for $params,
190  # which leads to E_NOTICEs
191  $spec = implode( "\t", $params );
192  $out[$spec] = $originalParams;
193  }
194  }
195  return array_values( $out );
196 }
197 
206 function wfArrayInsertAfter( array $array, array $insert, $after ) {
207  // Find the offset of the element to insert after.
208  $keys = array_keys( $array );
209  $offsetByKey = array_flip( $keys );
210 
211  $offset = $offsetByKey[$after];
212 
213  // Insert at the specified offset
214  $before = array_slice( $array, 0, $offset + 1, true );
215  $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
216 
217  $output = $before + $insert + $after;
218 
219  return $output;
220 }
221 
229 function wfObjectToArray( $objOrArray, $recursive = true ) {
230  $array = [];
231  if ( is_object( $objOrArray ) ) {
232  $objOrArray = get_object_vars( $objOrArray );
233  }
234  foreach ( $objOrArray as $key => $value ) {
235  if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
236  $value = wfObjectToArray( $value );
237  }
238 
239  $array[$key] = $value;
240  }
241 
242  return $array;
243 }
244 
255 function wfRandom() {
256  // The maximum random value is "only" 2^31-1, so get two random
257  // values to reduce the chance of dupes
258  $max = mt_getrandmax() + 1;
259  $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
260  return $rand;
261 }
262 
273 function wfRandomString( $length = 32 ) {
274  $str = '';
275  for ( $n = 0; $n < $length; $n += 7 ) {
276  $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
277  }
278  return substr( $str, 0, $length );
279 }
280 
308 function wfUrlencode( $s ) {
309  static $needle;
310 
311  if ( $s === null ) {
312  // Reset $needle for testing.
313  $needle = null;
314  return '';
315  }
316 
317  if ( $needle === null ) {
318  $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
319  if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
320  ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
321  ) {
322  $needle[] = '%3A';
323  }
324  }
325 
326  $s = urlencode( $s );
327  $s = str_ireplace(
328  $needle,
329  [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
330  $s
331  );
332 
333  return $s;
334 }
335 
346 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
347  if ( $array2 !== null ) {
348  $array1 += $array2;
349  }
350 
351  $cgi = '';
352  foreach ( $array1 as $key => $value ) {
353  if ( $value !== null && $value !== false ) {
354  if ( $cgi != '' ) {
355  $cgi .= '&';
356  }
357  if ( $prefix !== '' ) {
358  $key = $prefix . "[$key]";
359  }
360  if ( is_array( $value ) ) {
361  $firstTime = true;
362  foreach ( $value as $k => $v ) {
363  $cgi .= $firstTime ? '' : '&';
364  if ( is_array( $v ) ) {
365  $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
366  } else {
367  $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
368  }
369  $firstTime = false;
370  }
371  } else {
372  if ( is_object( $value ) ) {
373  $value = $value->__toString();
374  }
375  $cgi .= urlencode( $key ) . '=' . urlencode( $value );
376  }
377  }
378  }
379  return $cgi;
380 }
381 
391 function wfCgiToArray( $query ) {
392  if ( isset( $query[0] ) && $query[0] == '?' ) {
393  $query = substr( $query, 1 );
394  }
395  $bits = explode( '&', $query );
396  $ret = [];
397  foreach ( $bits as $bit ) {
398  if ( $bit === '' ) {
399  continue;
400  }
401  if ( strpos( $bit, '=' ) === false ) {
402  // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
403  $key = $bit;
404  $value = '';
405  } else {
406  list( $key, $value ) = explode( '=', $bit );
407  }
408  $key = urldecode( $key );
409  $value = urldecode( $value );
410  if ( strpos( $key, '[' ) !== false ) {
411  $keys = array_reverse( explode( '[', $key ) );
412  $key = array_pop( $keys );
413  $temp = $value;
414  foreach ( $keys as $k ) {
415  $k = substr( $k, 0, -1 );
416  $temp = [ $k => $temp ];
417  }
418  if ( isset( $ret[$key] ) ) {
419  $ret[$key] = array_merge( $ret[$key], $temp );
420  } else {
421  $ret[$key] = $temp;
422  }
423  } else {
424  $ret[$key] = $value;
425  }
426  }
427  return $ret;
428 }
429 
438 function wfAppendQuery( $url, $query ) {
439  if ( is_array( $query ) ) {
440  $query = wfArrayToCgi( $query );
441  }
442  if ( $query != '' ) {
443  // Remove the fragment, if there is one
444  $fragment = false;
445  $hashPos = strpos( $url, '#' );
446  if ( $hashPos !== false ) {
447  $fragment = substr( $url, $hashPos );
448  $url = substr( $url, 0, $hashPos );
449  }
450 
451  // Add parameter
452  if ( strpos( $url, '?' ) === false ) {
453  $url .= '?';
454  } else {
455  $url .= '&';
456  }
457  $url .= $query;
458 
459  // Put the fragment back
460  if ( $fragment !== false ) {
461  $url .= $fragment;
462  }
463  }
464  return $url;
465 }
466 
490 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
492  $wgHttpsPort;
493  if ( $defaultProto === PROTO_CANONICAL ) {
494  $serverUrl = $wgCanonicalServer;
495  } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
496  // Make $wgInternalServer fall back to $wgServer if not set
497  $serverUrl = $wgInternalServer;
498  } else {
499  $serverUrl = $wgServer;
500  if ( $defaultProto === PROTO_CURRENT ) {
501  $defaultProto = $wgRequest->getProtocol() . '://';
502  }
503  }
504 
505  // Analyze $serverUrl to obtain its protocol
506  $bits = wfParseUrl( $serverUrl );
507  $serverHasProto = $bits && $bits['scheme'] != '';
508 
509  if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
510  if ( $serverHasProto ) {
511  $defaultProto = $bits['scheme'] . '://';
512  } else {
513  // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
514  // This really isn't supposed to happen. Fall back to HTTP in this
515  // ridiculous case.
516  $defaultProto = PROTO_HTTP;
517  }
518  }
519 
520  $defaultProtoWithoutSlashes = $defaultProto !== null ? substr( $defaultProto, 0, -2 ) : '';
521 
522  if ( substr( $url, 0, 2 ) == '//' ) {
523  $url = $defaultProtoWithoutSlashes . $url;
524  } elseif ( substr( $url, 0, 1 ) == '/' ) {
525  // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
526  // otherwise leave it alone.
527  if ( $serverHasProto ) {
528  $url = $serverUrl . $url;
529  } else {
530  // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
531  // user to override the port number (T67184)
532  if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
533  if ( isset( $bits['port'] ) ) {
534  throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
535  }
536  $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
537  } else {
538  $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
539  }
540  }
541  }
542 
543  $bits = wfParseUrl( $url );
544 
545  if ( $bits && isset( $bits['path'] ) ) {
546  $bits['path'] = wfRemoveDotSegments( $bits['path'] );
547  return wfAssembleUrl( $bits );
548  } elseif ( $bits ) {
549  # No path to expand
550  return $url;
551  } elseif ( substr( $url, 0, 1 ) != '/' ) {
552  # URL is a relative path
553  return wfRemoveDotSegments( $url );
554  }
555 
556  # Expanded URL is not valid.
557  return false;
558 }
559 
568 function wfGetServerUrl( $proto ) {
569  $url = wfExpandUrl( '/', $proto );
570  return substr( $url, 0, -1 );
571 }
572 
586 function wfAssembleUrl( $urlParts ) {
587  $result = '';
588 
589  if ( isset( $urlParts['delimiter'] ) ) {
590  if ( isset( $urlParts['scheme'] ) ) {
591  $result .= $urlParts['scheme'];
592  }
593 
594  $result .= $urlParts['delimiter'];
595  }
596 
597  if ( isset( $urlParts['host'] ) ) {
598  if ( isset( $urlParts['user'] ) ) {
599  $result .= $urlParts['user'];
600  if ( isset( $urlParts['pass'] ) ) {
601  $result .= ':' . $urlParts['pass'];
602  }
603  $result .= '@';
604  }
605 
606  $result .= $urlParts['host'];
607 
608  if ( isset( $urlParts['port'] ) ) {
609  $result .= ':' . $urlParts['port'];
610  }
611  }
612 
613  if ( isset( $urlParts['path'] ) ) {
614  $result .= $urlParts['path'];
615  }
616 
617  if ( isset( $urlParts['query'] ) ) {
618  $result .= '?' . $urlParts['query'];
619  }
620 
621  if ( isset( $urlParts['fragment'] ) ) {
622  $result .= '#' . $urlParts['fragment'];
623  }
624 
625  return $result;
626 }
627 
640 function wfRemoveDotSegments( $urlPath ) {
641  $output = '';
642  $inputOffset = 0;
643  $inputLength = strlen( $urlPath );
644 
645  while ( $inputOffset < $inputLength ) {
646  $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
647  $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
648  $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
649  $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
650  $trimOutput = false;
651 
652  if ( $prefixLengthTwo == './' ) {
653  # Step A, remove leading "./"
654  $inputOffset += 2;
655  } elseif ( $prefixLengthThree == '../' ) {
656  # Step A, remove leading "../"
657  $inputOffset += 3;
658  } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
659  # Step B, replace leading "/.$" with "/"
660  $inputOffset += 1;
661  $urlPath[$inputOffset] = '/';
662  } elseif ( $prefixLengthThree == '/./' ) {
663  # Step B, replace leading "/./" with "/"
664  $inputOffset += 2;
665  } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
666  # Step C, replace leading "/..$" with "/" and
667  # remove last path component in output
668  $inputOffset += 2;
669  $urlPath[$inputOffset] = '/';
670  $trimOutput = true;
671  } elseif ( $prefixLengthFour == '/../' ) {
672  # Step C, replace leading "/../" with "/" and
673  # remove last path component in output
674  $inputOffset += 3;
675  $trimOutput = true;
676  } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
677  # Step D, remove "^.$"
678  $inputOffset += 1;
679  } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
680  # Step D, remove "^..$"
681  $inputOffset += 2;
682  } else {
683  # Step E, move leading path segment to output
684  if ( $prefixLengthOne == '/' ) {
685  $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
686  } else {
687  $slashPos = strpos( $urlPath, '/', $inputOffset );
688  }
689  if ( $slashPos === false ) {
690  $output .= substr( $urlPath, $inputOffset );
691  $inputOffset = $inputLength;
692  } else {
693  $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
694  $inputOffset += $slashPos - $inputOffset;
695  }
696  }
697 
698  if ( $trimOutput ) {
699  $slashPos = strrpos( $output, '/' );
700  if ( $slashPos === false ) {
701  $output = '';
702  } else {
703  $output = substr( $output, 0, $slashPos );
704  }
705  }
706  }
707 
708  return $output;
709 }
710 
718 function wfUrlProtocols( $includeProtocolRelative = true ) {
719  global $wgUrlProtocols;
720 
721  // Cache return values separately based on $includeProtocolRelative
722  static $withProtRel = null, $withoutProtRel = null;
723  $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
724  if ( $cachedValue !== null ) {
725  return $cachedValue;
726  }
727 
728  // Support old-style $wgUrlProtocols strings, for backwards compatibility
729  // with LocalSettings files from 1.5
730  if ( is_array( $wgUrlProtocols ) ) {
731  $protocols = [];
732  foreach ( $wgUrlProtocols as $protocol ) {
733  // Filter out '//' if !$includeProtocolRelative
734  if ( $includeProtocolRelative || $protocol !== '//' ) {
735  $protocols[] = preg_quote( $protocol, '/' );
736  }
737  }
738 
739  $retval = implode( '|', $protocols );
740  } else {
741  // Ignore $includeProtocolRelative in this case
742  // This case exists for pre-1.6 compatibility, and we can safely assume
743  // that '//' won't appear in a pre-1.6 config because protocol-relative
744  // URLs weren't supported until 1.18
745  $retval = $wgUrlProtocols;
746  }
747 
748  // Cache return value
749  if ( $includeProtocolRelative ) {
750  $withProtRel = $retval;
751  } else {
752  $withoutProtRel = $retval;
753  }
754  return $retval;
755 }
756 
764  return wfUrlProtocols( false );
765 }
766 
792 function wfParseUrl( $url ) {
793  global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
794 
795  // Protocol-relative URLs are handled really badly by parse_url(). It's so
796  // bad that the easiest way to handle them is to just prepend 'http:' and
797  // strip the protocol out later.
798  $wasRelative = substr( $url, 0, 2 ) == '//';
799  if ( $wasRelative ) {
800  $url = "http:$url";
801  }
802  $bits = parse_url( $url );
803  // parse_url() returns an array without scheme for some invalid URLs, e.g.
804  // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
805  if ( !$bits || !isset( $bits['scheme'] ) ) {
806  return false;
807  }
808 
809  // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
810  $bits['scheme'] = strtolower( $bits['scheme'] );
811 
812  // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
813  if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
814  $bits['delimiter'] = '://';
815  } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
816  $bits['delimiter'] = ':';
817  // parse_url detects for news: and mailto: the host part of an url as path
818  // We have to correct this wrong detection
819  if ( isset( $bits['path'] ) ) {
820  $bits['host'] = $bits['path'];
821  $bits['path'] = '';
822  }
823  } else {
824  return false;
825  }
826 
827  /* Provide an empty host for eg. file:/// urls (see T30627) */
828  if ( !isset( $bits['host'] ) ) {
829  $bits['host'] = '';
830 
831  // See T47069
832  if ( isset( $bits['path'] ) ) {
833  /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
834  if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
835  $bits['path'] = '/' . $bits['path'];
836  }
837  } else {
838  $bits['path'] = '';
839  }
840  }
841 
842  // If the URL was protocol-relative, fix scheme and delimiter
843  if ( $wasRelative ) {
844  $bits['scheme'] = '';
845  $bits['delimiter'] = '//';
846  }
847  return $bits;
848 }
849 
860 function wfExpandIRI( $url ) {
861  return preg_replace_callback(
862  '/((?:%[89A-F][0-9A-F])+)/i',
863  function ( array $matches ) {
864  return urldecode( $matches[1] );
865  },
866  wfExpandUrl( $url )
867  );
868 }
869 
876 function wfMatchesDomainList( $url, $domains ) {
877  $bits = wfParseUrl( $url );
878  if ( is_array( $bits ) && isset( $bits['host'] ) ) {
879  $host = '.' . $bits['host'];
880  foreach ( (array)$domains as $domain ) {
881  $domain = '.' . $domain;
882  if ( substr( $host, -strlen( $domain ) ) === $domain ) {
883  return true;
884  }
885  }
886  }
887  return false;
888 }
889 
910 function wfDebug( $text, $dest = 'all', array $context = [] ) {
912 
913  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
914  return;
915  }
916 
917  $text = trim( $text );
918 
919  if ( $wgDebugLogPrefix !== '' ) {
920  $context['prefix'] = $wgDebugLogPrefix;
921  }
922  $context['private'] = ( $dest === false || $dest === 'private' );
923 
924  $logger = LoggerFactory::getInstance( 'wfDebug' );
925  $logger->debug( $text, $context );
926 }
927 
932 function wfIsDebugRawPage() {
933  static $cache;
934  if ( $cache !== null ) {
935  return $cache;
936  }
937  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
938  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
939  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
940  || MW_ENTRY_POINT === 'load'
941  ) {
942  $cache = true;
943  } else {
944  $cache = false;
945  }
946  return $cache;
947 }
948 
954 function wfDebugMem( $exact = false ) {
955  $mem = memory_get_usage();
956  if ( !$exact ) {
957  $mem = floor( $mem / 1024 ) . ' KiB';
958  } else {
959  $mem .= ' B';
960  }
961  wfDebug( "Memory usage: $mem" );
962 }
963 
989 function wfDebugLog(
990  $logGroup, $text, $dest = 'all', array $context = []
991 ) {
992  $text = trim( $text );
993 
994  $logger = LoggerFactory::getInstance( $logGroup );
995  $context['private'] = ( $dest === false || $dest === 'private' );
996  $logger->info( $text, $context );
997 }
998 
1007 function wfLogDBError( $text, array $context = [] ) {
1008  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1009  $logger->error( trim( $text ), $context );
1010 }
1011 
1027 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1028  if ( is_string( $version ) || $version === false ) {
1029  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1030  } else {
1031  throw new Exception(
1032  "MediaWiki version must either be a string or false. " .
1033  "Example valid version: '1.33'"
1034  );
1035  }
1036 }
1037 
1059 function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
1060  MWDebug::deprecatedMsg( $msg, $version, $component,
1061  $callerOffset === false ? false : $callerOffset + 1 );
1062 }
1063 
1074 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1075  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1076 }
1077 
1087 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1088  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1089 }
1090 
1096  $context = RequestContext::getMain();
1097 
1098  $profiler = Profiler::instance();
1099  $profiler->setContext( $context );
1100  $profiler->logData();
1101 
1102  // Send out any buffered statsd metrics as needed
1104  MediaWikiServices::getInstance()->getStatsdDataFactory(),
1105  $context->getConfig()
1106  );
1107 }
1108 
1116 function wfIncrStats( $key, $count = 1 ) {
1117  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1118  $stats->updateCount( $key, $count );
1119 }
1120 
1126 function wfReadOnly() {
1127  return MediaWikiServices::getInstance()->getReadOnlyMode()
1128  ->isReadOnly();
1129 }
1130 
1139 function wfReadOnlyReason() {
1140  return MediaWikiServices::getInstance()->getReadOnlyMode()
1141  ->getReason();
1142 }
1143 
1151  return MediaWikiServices::getInstance()->getConfiguredReadOnlyMode()
1152  ->getReason();
1153 }
1154 
1170 function wfGetLangObj( $langcode = false ) {
1171  # Identify which language to get or create a language object for.
1172  # Using is_object here due to Stub objects.
1173  if ( is_object( $langcode ) ) {
1174  # Great, we already have the object (hopefully)!
1175  return $langcode;
1176  }
1177 
1178  global $wgLanguageCode;
1179  $services = MediaWikiServices::getInstance();
1180  if ( $langcode === true || $langcode === $wgLanguageCode ) {
1181  # $langcode is the language code of the wikis content language object.
1182  # or it is a boolean and value is true
1183  return $services->getContentLanguage();
1184  }
1185 
1186  global $wgLang;
1187  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1188  # $langcode is the language code of user language object.
1189  # or it was a boolean and value is false
1190  return $wgLang;
1191  }
1192 
1193  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1194  if ( in_array( $langcode, $validCodes ) ) {
1195  # $langcode corresponds to a valid language.
1196  return $services->getLanguageFactory()->getLanguage( $langcode );
1197  }
1198 
1199  # $langcode is a string, but not a valid language code; use content language.
1200  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1201  return $services->getContentLanguage();
1202 }
1203 
1220 function wfMessage( $key, ...$params ) {
1221  $message = new Message( $key );
1222 
1223  // We call Message::params() to reduce code duplication
1224  if ( $params ) {
1225  $message->params( ...$params );
1226  }
1227 
1228  return $message;
1229 }
1230 
1243 function wfMessageFallback( ...$keys ) {
1244  return Message::newFallbackSequence( ...$keys );
1245 }
1246 
1255 function wfMsgReplaceArgs( $message, $args ) {
1256  # Fix windows line-endings
1257  # Some messages are split with explode("\n", $msg)
1258  $message = str_replace( "\r", '', $message );
1259 
1260  // Replace arguments
1261  if ( is_array( $args ) && $args ) {
1262  if ( is_array( $args[0] ) ) {
1263  $args = array_values( $args[0] );
1264  }
1265  $replacementKeys = [];
1266  foreach ( $args as $n => $param ) {
1267  $replacementKeys['$' . ( $n + 1 )] = $param;
1268  }
1269  $message = strtr( $message, $replacementKeys );
1270  }
1271 
1272  return $message;
1273 }
1274 
1283 function wfHostname() {
1284  // Hostname overriding
1285  global $wgOverrideHostname;
1286  if ( $wgOverrideHostname !== false ) {
1287  return $wgOverrideHostname;
1288  }
1289 
1290  return php_uname( 'n' ) ?: 'unknown';
1291 }
1292 
1303 function wfReportTime( $nonce = null ) {
1304  global $wgShowHostnames;
1305 
1306  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1307  // seconds to milliseconds
1308  $responseTime = round( $elapsed * 1000 );
1309  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1310  if ( $wgShowHostnames ) {
1311  $reportVars['wgHostname'] = wfHostname();
1312  }
1313 
1314  return (
1316  ResourceLoader::makeConfigSetScript( $reportVars ),
1317  $nonce
1318  )
1319  );
1320 }
1321 
1332 function wfDebugBacktrace( $limit = 0 ) {
1333  static $disabled = null;
1334 
1335  if ( $disabled === null ) {
1336  $disabled = !function_exists( 'debug_backtrace' );
1337  if ( $disabled ) {
1338  wfDebug( "debug_backtrace() is disabled" );
1339  }
1340  }
1341  if ( $disabled ) {
1342  return [];
1343  }
1344 
1345  if ( $limit ) {
1346  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1347  } else {
1348  return array_slice( debug_backtrace(), 1 );
1349  }
1350 }
1351 
1360 function wfBacktrace( $raw = null ) {
1361  global $wgCommandLineMode;
1362 
1363  if ( $raw === null ) {
1364  $raw = $wgCommandLineMode;
1365  }
1366 
1367  if ( $raw ) {
1368  $frameFormat = "%s line %s calls %s()\n";
1369  $traceFormat = "%s";
1370  } else {
1371  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1372  $traceFormat = "<ul>\n%s</ul>\n";
1373  }
1374 
1375  $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1376  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1377  $line = $frame['line'] ?? '-';
1378  $call = $frame['function'];
1379  if ( !empty( $frame['class'] ) ) {
1380  $call = $frame['class'] . $frame['type'] . $call;
1381  }
1382  return sprintf( $frameFormat, $file, $line, $call );
1383  }, wfDebugBacktrace() );
1384 
1385  return sprintf( $traceFormat, implode( '', $frames ) );
1386 }
1387 
1397 function wfGetCaller( $level = 2 ) {
1398  $backtrace = wfDebugBacktrace( $level + 1 );
1399  if ( isset( $backtrace[$level] ) ) {
1400  return wfFormatStackFrame( $backtrace[$level] );
1401  } else {
1402  return 'unknown';
1403  }
1404 }
1405 
1413 function wfGetAllCallers( $limit = 3 ) {
1414  $trace = array_reverse( wfDebugBacktrace() );
1415  if ( !$limit || $limit > count( $trace ) - 1 ) {
1416  $limit = count( $trace ) - 1;
1417  }
1418  $trace = array_slice( $trace, -$limit - 1, $limit );
1419  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1420 }
1421 
1428 function wfFormatStackFrame( $frame ) {
1429  if ( !isset( $frame['function'] ) ) {
1430  return 'NO_FUNCTION_GIVEN';
1431  }
1432  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1433  $frame['class'] . $frame['type'] . $frame['function'] :
1434  $frame['function'];
1435 }
1436 
1437 /* Some generic result counters, pulled out of SearchEngine */
1438 
1446 function wfShowingResults( $offset, $limit ) {
1447  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1448 }
1449 
1459 function wfClientAcceptsGzip( $force = false ) {
1460  static $result = null;
1461  if ( $result === null || $force ) {
1462  $result = false;
1463  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1464  # @todo FIXME: We may want to blacklist some broken browsers
1465  $m = [];
1466  if ( preg_match(
1467  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1468  $_SERVER['HTTP_ACCEPT_ENCODING'],
1469  $m
1470  )
1471  ) {
1472  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1473  $result = false;
1474  return $result;
1475  }
1476  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1477  $result = true;
1478  }
1479  }
1480  }
1481  return $result;
1482 }
1483 
1494 function wfEscapeWikiText( $text ) {
1495  global $wgEnableMagicLinks;
1496  static $repl = null, $repl2 = null;
1497  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1498  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1499  // in those situations
1500  $repl = [
1501  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1502  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1503  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1504  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1505  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1506  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1507  "\n " => "\n&#32;", "\r " => "\r&#32;",
1508  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1509  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1510  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1511  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1512  '__' => '_&#95;', '://' => '&#58;//',
1513  ];
1514 
1515  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1516  // We have to catch everything "\s" matches in PCRE
1517  foreach ( $magicLinks as $magic ) {
1518  $repl["$magic "] = "$magic&#32;";
1519  $repl["$magic\t"] = "$magic&#9;";
1520  $repl["$magic\r"] = "$magic&#13;";
1521  $repl["$magic\n"] = "$magic&#10;";
1522  $repl["$magic\f"] = "$magic&#12;";
1523  }
1524 
1525  // And handle protocols that don't use "://"
1526  global $wgUrlProtocols;
1527  $repl2 = [];
1528  foreach ( $wgUrlProtocols as $prot ) {
1529  if ( substr( $prot, -1 ) === ':' ) {
1530  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1531  }
1532  }
1533  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1534  }
1535  $text = substr( strtr( "\n$text", $repl ), 1 );
1536  $text = preg_replace( $repl2, '$1&#58;', $text );
1537  return $text;
1538 }
1539 
1550 function wfSetVar( &$dest, $source, $force = false ) {
1551  $temp = $dest;
1552  if ( $source !== null || $force ) {
1553  $dest = $source;
1554  }
1555  return $temp;
1556 }
1557 
1567 function wfSetBit( &$dest, $bit, $state = true ) {
1568  $temp = (bool)( $dest & $bit );
1569  if ( $state !== null ) {
1570  if ( $state ) {
1571  $dest |= $bit;
1572  } else {
1573  $dest &= ~$bit;
1574  }
1575  }
1576  return $temp;
1577 }
1578 
1585 function wfVarDump( $var ) {
1586  global $wgOut;
1587  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1588  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1589  print $s;
1590  } else {
1591  $wgOut->addHTML( $s );
1592  }
1593 }
1594 
1602 function wfHttpError( $code, $label, $desc ) {
1603  global $wgOut;
1604  HttpStatus::header( $code );
1605  if ( $wgOut ) {
1606  $wgOut->disable();
1607  $wgOut->sendCacheControl();
1608  }
1609 
1611  header( 'Content-type: text/html; charset=utf-8' );
1612  ob_start();
1613  print '<!DOCTYPE html>' .
1614  '<html><head><title>' .
1615  htmlspecialchars( $label ) .
1616  '</title></head><body><h1>' .
1617  htmlspecialchars( $label ) .
1618  '</h1><p>' .
1619  nl2br( htmlspecialchars( $desc ) ) .
1620  "</p></body></html>\n";
1621  header( 'Content-Length: ' . ob_get_length() );
1622  ob_end_flush();
1623 }
1624 
1642 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1643  if ( $resetGzipEncoding ) {
1644  // Suppress Content-Encoding and Content-Length
1645  // headers from OutputHandler::handle.
1648  }
1649  while ( $status = ob_get_status() ) {
1650  if ( isset( $status['flags'] ) ) {
1651  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1652  $deleteable = ( $status['flags'] & $flags ) === $flags;
1653  } elseif ( isset( $status['del'] ) ) {
1654  $deleteable = $status['del'];
1655  } else {
1656  // Guess that any PHP-internal setting can't be removed.
1657  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1658  }
1659  if ( !$deleteable ) {
1660  // Give up, and hope the result doesn't break
1661  // output behavior.
1662  break;
1663  }
1664  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1665  // Unit testing barrier to prevent this function from breaking PHPUnit.
1666  break;
1667  }
1668  if ( !ob_end_clean() ) {
1669  // Could not remove output buffer handler; abort now
1670  // to avoid getting in some kind of infinite loop.
1671  break;
1672  }
1673  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1674  // Reset the 'Content-Encoding' field set by this handler
1675  // so we can start fresh.
1676  header_remove( 'Content-Encoding' );
1677  break;
1678  }
1679  }
1680 }
1681 
1695  wfResetOutputBuffers( false );
1696 }
1697 
1706 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1707  # No arg means accept anything (per HTTP spec)
1708  if ( !$accept ) {
1709  return [ $def => 1.0 ];
1710  }
1711 
1712  $prefs = [];
1713 
1714  $parts = explode( ',', $accept );
1715 
1716  foreach ( $parts as $part ) {
1717  # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1718  $values = explode( ';', trim( $part ) );
1719  $match = [];
1720  if ( count( $values ) == 1 ) {
1721  $prefs[$values[0]] = 1.0;
1722  } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1723  $prefs[$values[0]] = floatval( $match[1] );
1724  }
1725  }
1726 
1727  return $prefs;
1728 }
1729 
1742 function mimeTypeMatch( $type, $avail ) {
1743  if ( array_key_exists( $type, $avail ) ) {
1744  return $type;
1745  } else {
1746  $mainType = explode( '/', $type )[0];
1747  if ( array_key_exists( "$mainType/*", $avail ) ) {
1748  return "$mainType/*";
1749  } elseif ( array_key_exists( '*/*', $avail ) ) {
1750  return '*/*';
1751  } else {
1752  return null;
1753  }
1754  }
1755 }
1756 
1771 function wfNegotiateType( $cprefs, $sprefs ) {
1772  $combine = [];
1773 
1774  foreach ( array_keys( $sprefs ) as $type ) {
1775  $subType = explode( '/', $type )[1];
1776  if ( $subType != '*' ) {
1777  $ckey = mimeTypeMatch( $type, $cprefs );
1778  if ( $ckey ) {
1779  $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1780  }
1781  }
1782  }
1783 
1784  foreach ( array_keys( $cprefs ) as $type ) {
1785  $subType = explode( '/', $type )[1];
1786  if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
1787  $skey = mimeTypeMatch( $type, $sprefs );
1788  if ( $skey ) {
1789  $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1790  }
1791  }
1792  }
1793 
1794  $bestq = 0;
1795  $besttype = null;
1796 
1797  foreach ( array_keys( $combine ) as $type ) {
1798  if ( $combine[$type] > $bestq ) {
1799  $besttype = $type;
1800  $bestq = $combine[$type];
1801  }
1802  }
1803 
1804  return $besttype;
1805 }
1806 
1815 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1816  $ret = MWTimestamp::convert( $outputtype, $ts );
1817  if ( $ret === false ) {
1818  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1819  }
1820  return $ret;
1821 }
1822 
1831 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1832  if ( $ts === null ) {
1833  return null;
1834  } else {
1835  return wfTimestamp( $outputtype, $ts );
1836  }
1837 }
1838 
1844 function wfTimestampNow() {
1845  return MWTimestamp::now( TS_MW );
1846 }
1847 
1853 function wfIsWindows() {
1854  return PHP_OS_FAMILY === 'Windows';
1855 }
1856 
1863 function wfIsCLI() {
1864  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1865 }
1866 
1878 function wfTempDir() {
1879  global $wgTmpDirectory;
1880 
1881  if ( $wgTmpDirectory !== false ) {
1882  return $wgTmpDirectory;
1883  }
1884 
1886 }
1887 
1897 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1898  global $wgDirectoryMode;
1899 
1900  if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1901  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1902  }
1903 
1904  if ( $caller !== null ) {
1905  wfDebug( "$caller: called wfMkdirParents($dir)" );
1906  }
1907 
1908  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1909  return true;
1910  }
1911 
1912  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1913 
1914  if ( $mode === null ) {
1915  $mode = $wgDirectoryMode;
1916  }
1917 
1918  // Turn off the normal warning, we're doing our own below
1919  AtEase::suppressWarnings();
1920  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1921  AtEase::restoreWarnings();
1922 
1923  if ( !$ok ) {
1924  // directory may have been created on another request since we last checked
1925  if ( is_dir( $dir ) ) {
1926  return true;
1927  }
1928 
1929  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1930  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1931  }
1932  return $ok;
1933 }
1934 
1940 function wfRecursiveRemoveDir( $dir ) {
1941  wfDebug( __FUNCTION__ . "( $dir )" );
1942  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1943  if ( is_dir( $dir ) ) {
1944  $objects = scandir( $dir );
1945  foreach ( $objects as $object ) {
1946  if ( $object != "." && $object != ".." ) {
1947  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1948  wfRecursiveRemoveDir( $dir . '/' . $object );
1949  } else {
1950  unlink( $dir . '/' . $object );
1951  }
1952  }
1953  }
1954  reset( $objects );
1955  rmdir( $dir );
1956  }
1957 }
1958 
1965 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1966  $accForFormat = $acc >= 0 ? $acc : 0;
1967  $ret = sprintf( "%.${accForFormat}f", $nr );
1968  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1969 }
1970 
1994 function wfIniGetBool( $setting ) {
1995  return wfStringToBool( ini_get( $setting ) );
1996 }
1997 
2010 function wfStringToBool( $val ) {
2011  $val = strtolower( $val );
2012  // 'on' and 'true' can't have whitespace around them, but '1' can.
2013  return $val == 'on'
2014  || $val == 'true'
2015  || $val == 'yes'
2016  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2017 }
2018 
2031 function wfEscapeShellArg( ...$args ) {
2032  return Shell::escape( ...$args );
2033 }
2034 
2059 function wfShellExec( $cmd, &$retval = null, $environ = [],
2060  $limits = [], $options = []
2061 ) {
2062  if ( Shell::isDisabled() ) {
2063  $retval = 1;
2064  // Backwards compatibility be upon us...
2065  return 'Unable to run external programs, proc_open() is disabled.';
2066  }
2067 
2068  if ( is_array( $cmd ) ) {
2069  $cmd = Shell::escape( $cmd );
2070  }
2071 
2072  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2073  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
2074 
2075  try {
2076  $result = Shell::command( [] )
2077  ->unsafeParams( (array)$cmd )
2078  ->environment( $environ )
2079  ->limits( $limits )
2080  ->includeStderr( $includeStderr )
2081  ->profileMethod( $profileMethod )
2082  // For b/c
2083  ->restrict( Shell::RESTRICT_NONE )
2084  ->execute();
2085  } catch ( ProcOpenError $ex ) {
2086  $retval = -1;
2087  return '';
2088  }
2089 
2090  $retval = $result->getExitCode();
2091 
2092  return $result->getStdout();
2093 }
2094 
2112 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
2113  return wfShellExec( $cmd, $retval, $environ, $limits,
2114  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
2115 }
2116 
2132 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2133  global $wgPhpCli;
2134  // Give site config file a chance to run the script in a wrapper.
2135  // The caller may likely want to call wfBasename() on $script.
2136  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
2137  $cmd = [ $options['php'] ?? $wgPhpCli ];
2138  if ( isset( $options['wrapper'] ) ) {
2139  $cmd[] = $options['wrapper'];
2140  }
2141  $cmd[] = $script;
2142  // Escape each parameter for shell
2143  return Shell::escape( array_merge( $cmd, $parameters ) );
2144 }
2145 
2157 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2158  global $wgDiff3;
2159 
2160  # This check may also protect against code injection in
2161  # case of broken installations.
2162  AtEase::suppressWarnings();
2163  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2164  AtEase::restoreWarnings();
2165 
2166  if ( !$haveDiff3 ) {
2167  wfDebug( "diff3 not found" );
2168  return false;
2169  }
2170 
2171  # Make temporary files
2172  $td = wfTempDir();
2173  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2174  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2175  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2176 
2177  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2178  # a newline character. To avoid this, we normalize the trailing whitespace before
2179  # creating the diff.
2180 
2181  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2182  fclose( $oldtextFile );
2183  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2184  fclose( $mytextFile );
2185  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2186  fclose( $yourtextFile );
2187 
2188  # Check for a conflict
2189  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2190  $oldtextName, $yourtextName );
2191  $handle = popen( $cmd, 'r' );
2192 
2193  $mergeAttemptResult = '';
2194  do {
2195  $data = fread( $handle, 8192 );
2196  if ( strlen( $data ) == 0 ) {
2197  break;
2198  }
2199  $mergeAttemptResult .= $data;
2200  } while ( true );
2201  pclose( $handle );
2202 
2203  $conflict = $mergeAttemptResult !== '';
2204 
2205  # Merge differences
2206  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2207  $oldtextName, $yourtextName );
2208  $handle = popen( $cmd, 'r' );
2209  $result = '';
2210  do {
2211  $data = fread( $handle, 8192 );
2212  if ( strlen( $data ) == 0 ) {
2213  break;
2214  }
2215  $result .= $data;
2216  } while ( true );
2217  pclose( $handle );
2218  unlink( $mytextName );
2219  unlink( $oldtextName );
2220  unlink( $yourtextName );
2221 
2222  if ( $result === '' && $old !== '' && !$conflict ) {
2223  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2224  $conflict = true;
2225  }
2226  return !$conflict;
2227 }
2228 
2240 function wfDiff( $before, $after, $params = '-u' ) {
2241  wfDeprecated( __FUNCTION__, '1.25' );
2242  if ( $before == $after ) {
2243  return '';
2244  }
2245 
2246  global $wgDiff;
2247  AtEase::suppressWarnings();
2248  $haveDiff = $wgDiff && file_exists( $wgDiff );
2249  AtEase::restoreWarnings();
2250 
2251  # This check may also protect against code injection in
2252  # case of broken installations.
2253  if ( !$haveDiff ) {
2254  wfDebug( "diff executable not found" );
2255  $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2256  $format = new UnifiedDiffFormatter();
2257  return $format->format( $diffs );
2258  }
2259 
2260  # Make temporary files
2261  $td = wfTempDir();
2262  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2263  $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2264 
2265  fwrite( $oldtextFile, $before );
2266  fclose( $oldtextFile );
2267  fwrite( $newtextFile, $after );
2268  fclose( $newtextFile );
2269 
2270  // Get the diff of the two files
2271  $cmd = "$wgDiff " . $params . ' ' . Shell::escape( $oldtextName, $newtextName );
2272 
2273  $h = popen( $cmd, 'r' );
2274  if ( !$h ) {
2275  unlink( $oldtextName );
2276  unlink( $newtextName );
2277  throw new Exception( __FUNCTION__ . '(): popen() failed' );
2278  }
2279 
2280  $diff = '';
2281 
2282  do {
2283  $data = fread( $h, 8192 );
2284  if ( strlen( $data ) == 0 ) {
2285  break;
2286  }
2287  $diff .= $data;
2288  } while ( true );
2289 
2290  // Clean up
2291  pclose( $h );
2292  unlink( $oldtextName );
2293  unlink( $newtextName );
2294 
2295  // Kill the --- and +++ lines. They're not useful.
2296  $diff_lines = explode( "\n", $diff );
2297  if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
2298  unset( $diff_lines[0] );
2299  }
2300  if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
2301  unset( $diff_lines[1] );
2302  }
2303 
2304  $diff = implode( "\n", $diff_lines );
2305 
2306  return $diff;
2307 }
2308 
2321 function wfBaseName( $path, $suffix = '' ) {
2322  if ( $suffix == '' ) {
2323  $encSuffix = '';
2324  } else {
2325  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2326  }
2327 
2328  $matches = [];
2329  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2330  return $matches[1];
2331  } else {
2332  return '';
2333  }
2334 }
2335 
2345 function wfRelativePath( $path, $from ) {
2346  // Normalize mixed input on Windows...
2347  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2348  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2349 
2350  // Trim trailing slashes -- fix for drive root
2351  $path = rtrim( $path, DIRECTORY_SEPARATOR );
2352  $from = rtrim( $from, DIRECTORY_SEPARATOR );
2353 
2354  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2355  $against = explode( DIRECTORY_SEPARATOR, $from );
2356 
2357  if ( $pieces[0] !== $against[0] ) {
2358  // Non-matching Windows drive letters?
2359  // Return a full path.
2360  return $path;
2361  }
2362 
2363  // Trim off common prefix
2364  while ( count( $pieces ) && count( $against )
2365  && $pieces[0] == $against[0] ) {
2366  array_shift( $pieces );
2367  array_shift( $against );
2368  }
2369 
2370  // relative dots to bump us to the parent
2371  while ( count( $against ) ) {
2372  array_unshift( $pieces, '..' );
2373  array_shift( $against );
2374  }
2375 
2376  array_push( $pieces, wfBaseName( $path ) );
2377 
2378  return implode( DIRECTORY_SEPARATOR, $pieces );
2379 }
2380 
2387 function wfGetPrecompiledData( $name ) {
2388  global $IP;
2389 
2390  $file = "$IP/serialized/$name";
2391  if ( file_exists( $file ) ) {
2392  $blob = file_get_contents( $file );
2393  if ( $blob ) {
2394  return unserialize( $blob );
2395  }
2396  }
2397  return false;
2398 }
2399 
2407 function wfMemcKey( ...$args ) {
2408  return ObjectCache::getLocalClusterInstance()->makeKey( ...$args );
2409 }
2410 
2422 function wfForeignMemcKey( $db, $prefix, ...$args ) {
2423  $keyspace = $prefix ? "$db-$prefix" : $db;
2424  return ObjectCache::getLocalClusterInstance()->makeKeyInternal( $keyspace, $args );
2425 }
2426 
2434 function wfWikiID() {
2435  global $wgDBprefix, $wgDBname;
2436 
2437  if ( $wgDBprefix ) {
2438  return "$wgDBname-$wgDBprefix";
2439  } else {
2440  return $wgDBname;
2441  }
2442 }
2443 
2475 function wfGetDB( $db, $groups = [], $wiki = false ) {
2476  return wfGetLB( $wiki )->getMaintenanceConnectionRef( $db, $groups, $wiki );
2477 }
2478 
2488 function wfGetLB( $wiki = false ) {
2489  if ( $wiki === false ) {
2490  return MediaWikiServices::getInstance()->getDBLoadBalancer();
2491  } else {
2492  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2493  return $factory->getMainLB( $wiki );
2494  }
2495 }
2496 
2504 function wfFindFile( $title, $options = [] ) {
2505  return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2506 }
2507 
2516 function wfLocalFile( $title ) {
2517  return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2518 }
2519 
2527  global $wgMiserMode;
2528  return $wgMiserMode
2529  || ( SiteStats::pages() > 100000
2530  && SiteStats::edits() > 1000000
2531  && SiteStats::users() > 10000 );
2532 }
2533 
2542 function wfScript( $script = 'index' ) {
2544  if ( $script === 'index' ) {
2545  return $wgScript;
2546  } elseif ( $script === 'load' ) {
2547  return $wgLoadScript;
2548  } else {
2549  return "{$wgScriptPath}/{$script}.php";
2550  }
2551 }
2552 
2559 function wfGetScriptUrl() {
2560  wfDeprecated( __FUNCTION__, '1.35' );
2561  if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2562  /* as it was called, minus the query string.
2563  *
2564  * Some sites use Apache rewrite rules to handle subdomains,
2565  * and have PHP set up in a weird way that causes PHP_SELF
2566  * to contain the rewritten URL instead of the one that the
2567  * outside world sees.
2568  *
2569  * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2570  * provides containing the "before" URL.
2571  */
2572  return $_SERVER['SCRIPT_NAME'];
2573  } else {
2574  return $_SERVER['URL'];
2575  }
2576 }
2577 
2585 function wfBoolToStr( $value ) {
2586  return $value ? 'true' : 'false';
2587 }
2588 
2594 function wfGetNull() {
2595  return wfIsWindows() ? 'NUL' : '/dev/null';
2596 }
2597 
2606 function wfStripIllegalFilenameChars( $name ) {
2607  global $wgIllegalFileChars;
2608  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2609  $name = preg_replace(
2610  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2611  '-',
2612  $name
2613  );
2614  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2615  $name = wfBaseName( $name );
2616  return $name;
2617 }
2618 
2625 function wfMemoryLimit( $newLimit ) {
2626  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2627  // If the INI config is already unlimited, there is nothing larger
2628  if ( $oldLimit != -1 ) {
2629  $newLimit = wfShorthandToInteger( $newLimit );
2630  if ( $newLimit == -1 ) {
2631  wfDebug( "Removing PHP's memory limit" );
2632  Wikimedia\suppressWarnings();
2633  ini_set( 'memory_limit', $newLimit );
2634  Wikimedia\restoreWarnings();
2635  } elseif ( $newLimit > $oldLimit ) {
2636  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2637  Wikimedia\suppressWarnings();
2638  ini_set( 'memory_limit', $newLimit );
2639  Wikimedia\restoreWarnings();
2640  }
2641  }
2642 }
2643 
2652 
2653  $timeLimit = (int)ini_get( 'max_execution_time' );
2654  // Note that CLI scripts use 0
2655  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2656  set_time_limit( $wgTransactionalTimeLimit );
2657  }
2658 
2659  ignore_user_abort( true ); // ignore client disconnects
2660 
2661  return $timeLimit;
2662 }
2663 
2671 function wfShorthandToInteger( $string = '', $default = -1 ) {
2672  $string = trim( $string );
2673  if ( $string === '' ) {
2674  return $default;
2675  }
2676  $last = $string[strlen( $string ) - 1];
2677  $val = intval( $string );
2678  switch ( $last ) {
2679  case 'g':
2680  case 'G':
2681  $val *= 1024;
2682  // break intentionally missing
2683  case 'm':
2684  case 'M':
2685  $val *= 1024;
2686  // break intentionally missing
2687  case 'k':
2688  case 'K':
2689  $val *= 1024;
2690  }
2691 
2692  return $val;
2693 }
2694 
2702 function wfGetCache( $cacheType ) {
2703  return ObjectCache::getInstance( $cacheType );
2704 }
2705 
2712 function wfGetMainCache() {
2714 }
2715 
2730 function wfUnpack( $format, $data, $length = false ) {
2731  if ( $length !== false ) {
2732  $realLen = strlen( $data );
2733  if ( $realLen < $length ) {
2734  throw new MWException( "Tried to use wfUnpack on a "
2735  . "string of length $realLen, but needed one "
2736  . "of at least length $length."
2737  );
2738  }
2739  }
2740 
2741  Wikimedia\suppressWarnings();
2742  $result = unpack( $format, $data );
2743  Wikimedia\restoreWarnings();
2744 
2745  if ( $result === false ) {
2746  // If it cannot extract the packed data.
2747  throw new MWException( "unpack could not unpack binary data" );
2748  }
2749  return $result;
2750 }
2751 
2767 function wfIsBadImage( $name, $contextTitle = false ) {
2768  wfDeprecated( __FUNCTION__, '1.34' );
2769  $services = MediaWikiServices::getInstance();
2770  return $services->getBadFileLookup()->isBadFile( $name, $contextTitle ?: null );
2771 }
2772 
2780 function wfCanIPUseHTTPS( $ip ) {
2781  $canDo = true;
2782  Hooks::runner()->onCanIPUseHTTPS( $ip, $canDo );
2783  return (bool)$canDo;
2784 }
2785 
2793 function wfIsInfinity( $str ) {
2794  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2795  return in_array( $str, ExpiryDef::INFINITY_VALS );
2796 }
2797 
2812 function wfThumbIsStandard( File $file, array $params ) {
2814 
2815  $multipliers = [ 1 ];
2816  if ( $wgResponsiveImages ) {
2817  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2818  // @see Linker::processResponsiveImages
2819  $multipliers[] = 1.5;
2820  $multipliers[] = 2;
2821  }
2822 
2823  $handler = $file->getHandler();
2824  if ( !$handler || !isset( $params['width'] ) ) {
2825  return false;
2826  }
2827 
2828  $basicParams = [];
2829  if ( isset( $params['page'] ) ) {
2830  $basicParams['page'] = $params['page'];
2831  }
2832 
2833  $thumbLimits = [];
2834  $imageLimits = [];
2835  // Expand limits to account for multipliers
2836  foreach ( $multipliers as $multiplier ) {
2837  $thumbLimits = array_merge( $thumbLimits, array_map(
2838  function ( $width ) use ( $multiplier ) {
2839  return round( $width * $multiplier );
2840  }, $wgThumbLimits )
2841  );
2842  $imageLimits = array_merge( $imageLimits, array_map(
2843  function ( $pair ) use ( $multiplier ) {
2844  return [
2845  round( $pair[0] * $multiplier ),
2846  round( $pair[1] * $multiplier ),
2847  ];
2848  }, $wgImageLimits )
2849  );
2850  }
2851 
2852  // Check if the width matches one of $wgThumbLimits
2853  if ( in_array( $params['width'], $thumbLimits ) ) {
2854  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2855  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2856  $handler->normaliseParams( $file, $normalParams );
2857  } else {
2858  // If not, then check if the width matchs one of $wgImageLimits
2859  $match = false;
2860  foreach ( $imageLimits as $pair ) {
2861  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2862  // Decide whether the thumbnail should be scaled on width or height.
2863  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2864  $handler->normaliseParams( $file, $normalParams );
2865  // Check if this standard thumbnail size maps to the given width
2866  if ( $normalParams['width'] == $params['width'] ) {
2867  $match = true;
2868  break;
2869  }
2870  }
2871  if ( !$match ) {
2872  return false; // not standard for description pages
2873  }
2874  }
2875 
2876  // Check that the given values for non-page, non-width, params are just defaults
2877  foreach ( $params as $key => $value ) {
2878  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2879  return false;
2880  }
2881  }
2882 
2883  return true;
2884 }
2885 
2898 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2899  // First merge items that are in both arrays
2900  foreach ( $baseArray as $name => &$groupVal ) {
2901  if ( isset( $newValues[$name] ) ) {
2902  $groupVal += $newValues[$name];
2903  }
2904  }
2905  // Now add items that didn't exist yet
2906  $baseArray += $newValues;
2907 
2908  return $baseArray;
2909 }
2910 
2920 function wfGetRusage() {
2921  wfDeprecated( __FUNCTION__, '1.35' );
2922  return getrusage( 0 /* RUSAGE_SELF */ );
2923 }
$wgPhpCli
$wgPhpCli
Executable path of the PHP cli binary.
Definition: DefaultSettings.php:8808
wfArrayInsertAfter
wfArrayInsertAfter(array $array, array $insert, $after)
Insert array into another array after the specified KEY
Definition: GlobalFunctions.php:206
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:180
wfResetOutputBuffers
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
Definition: GlobalFunctions.php:1642
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1243
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1561
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:2780
ResourceLoader\makeConfigSetScript
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
Definition: ResourceLoader.php:1670
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:1136
PROTO_INTERNAL
const PROTO_INTERNAL
Definition: Defines.php:213
MediaWiki\ProcOpenError
@newable
Definition: ProcOpenError.php:28
wfDiff
wfDiff( $before, $after, $params='-u')
Returns unified plain-text diff of two texts.
Definition: GlobalFunctions.php:2240
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1680
$wgDebugRawPage
$wgDebugRawPage
If true, log debugging data from action=raw and load.php.
Definition: DefaultSettings.php:6585
wfThumbIsStandard
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
Definition: GlobalFunctions.php:2812
$wgTmpDirectory
$wgTmpDirectory
The local filesystem path to a temporary directory.
Definition: DefaultSettings.php:414
wfArrayPlus2d
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
Definition: GlobalFunctions.php:2898
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:1989
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:1897
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:163
$wgDiff3
$wgDiff3
Path to the GNU diff3 utility.
Definition: DefaultSettings.php:7083
wfMerge
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
Definition: GlobalFunctions.php:2157
wfDebugBacktrace
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
Definition: GlobalFunctions.php:1332
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:1550
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:2488
wfFormatStackFrame
wfFormatStackFrame( $frame)
Return a string representation of frame.
Definition: GlobalFunctions.php:1428
ResourceLoader\makeInlineScript
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
Definition: ResourceLoader.php:1643
wfRemoveDotSegments
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
Definition: GlobalFunctions.php:640
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:207
wfSetBit
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
Definition: GlobalFunctions.php:1567
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:1771
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1815
SiteStats\pages
static pages()
Definition: SiteStats.php:112
wfUnpack
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
Definition: GlobalFunctions.php:2730
wfConfiguredReadOnlyReason
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: GlobalFunctions.php:1150
MessageSpecifier
Stable for implementing.
Definition: MessageSpecifier.php:24
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6777
wfMemoryLimit
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
Definition: GlobalFunctions.php:2625
wfObjectToArray
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
Definition: GlobalFunctions.php:229
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:308
wfArrayDiff2_cmp
wfArrayDiff2_cmp( $a, $b)
Definition: GlobalFunctions.php:121
wfGetScriptUrl
wfGetScriptUrl()
Get the script URL.
Definition: GlobalFunctions.php:2559
$wgDiff
$wgDiff
Path to the GNU diff utility.
Definition: DefaultSettings.php:7088
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2321
wfQueriesMustScale
wfQueriesMustScale()
Should low-performance queries be disabled?
Definition: GlobalFunctions.php:2526
$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()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1283
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1126
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1255
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
$s
$s
Definition: mergeMessageFileList.php:184
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1087
wfStringToBool
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
Definition: GlobalFunctions.php:2010
$wgTransactionalTimeLimit
$wgTransactionalTimeLimit
The minimum amount of time that MediaWiki needs for "slow" write request, particularly ones with mult...
Definition: DefaultSettings.php:2413
$wgDebugLogPrefix
$wgDebugLogPrefix
Prefix for debug log lines.
Definition: DefaultSettings.php:6571
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:860
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:989
$wgDBprefix
$wgDBprefix
Current wiki database table name prefix.
Definition: DefaultSettings.php:2009
wfShellWikiCmd
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:2132
wfBoolToStr
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
Definition: GlobalFunctions.php:2585
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:438
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
Wikimedia\ParamValidator\TypeDef\ExpiryDef
Type definition for expiry timestamps.
Definition: ExpiryDef.php:17
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:792
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:63
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:1303
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1059
wfGetMainCache
wfGetMainCache()
Get the main cache object.
Definition: GlobalFunctions.php:2712
MWException
MediaWiki exception.
Definition: MWException.php:29
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2606
wfGetRusage
wfGetRusage()
Get system resource usage of current request context.
Definition: GlobalFunctions.php:2920
mimeTypeMatch
mimeTypeMatch( $type, $avail)
Checks if a given MIME type matches any of the keys in the given array.
Definition: GlobalFunctions.php:1742
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
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:2542
wfArrayDiff2
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
Definition: GlobalFunctions.php:112
wfIncrStats
wfIncrStats( $key, $count=1)
Increment a statistics counter.
Definition: GlobalFunctions.php:1116
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1528
$blob
$blob
Definition: testCompression.php:70
wfTransactionalTimeLimit
wfTransactionalTimeLimit()
Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.
Definition: GlobalFunctions.php:2650
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2475
wfUrlProtocolsWithoutProtRel
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
Definition: GlobalFunctions.php:763
wfIsBadImage
wfIsBadImage( $name, $contextTitle=false)
Determine if an image exists on the 'bad image list'.
Definition: GlobalFunctions.php:2767
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
$matches
$matches
Definition: NoLocalSettings.php:24
$wgLang
$wgLang
Definition: Setup.php:776
$wgLoadScript
$wgLoadScript
The URL path to load.php.
Definition: DefaultSettings.php:215
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:1831
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:1170
wfCgiToArray
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Definition: GlobalFunctions.php:391
wfLoadSkins
wfLoadSkins(array $skins)
Load multiple skins at once.
Definition: GlobalFunctions.php:98
$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:2702
$wgEnableMagicLinks
$wgEnableMagicLinks
Enable the magic links feature of automatically turning ISBN xxx, PMID xxx, RFC xxx into links.
Definition: DefaultSettings.php:4745
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1844
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:910
wfPercent
wfPercent( $nr, int $acc=2, bool $round=true)
Definition: GlobalFunctions.php:1965
wfAcceptToPrefs
wfAcceptToPrefs( $accept, $def=' */*')
Converts an Accept-* header into an array mapping string values to quality factors.
Definition: GlobalFunctions.php:1706
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:120
wfIsDebugRawPage
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
Definition: GlobalFunctions.php:932
wfForeignMemcKey
wfForeignMemcKey( $db, $prefix,... $args)
Make a cache key for a foreign DB.
Definition: GlobalFunctions.php:2422
UnifiedDiffFormatter
A formatter that outputs unified diffs @newable.
Definition: UnifiedDiffFormatter.php:32
wfUrlProtocols
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
Definition: GlobalFunctions.php:718
wfLoadExtensions
wfLoadExtensions(array $exts)
Load multiple extensions at once.
Definition: GlobalFunctions.php:67
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2434
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1694
wfClientAcceptsGzip
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
Definition: GlobalFunctions.php:1459
$wgUrlProtocols
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
Definition: DefaultSettings.php:4582
$wgExtensionDirectory
$wgExtensionDirectory
Filesystem extensions directory.
Definition: DefaultSettings.php:251
wfIsCLI
wfIsCLI()
Check if we are running from the commandline.
Definition: GlobalFunctions.php:1863
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1853
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:111
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
$line
$line
Definition: mcc.php:119
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:3103
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2793
wfDebugMem
wfDebugMem( $exact=false)
Send a line giving PHP memory usage.
Definition: GlobalFunctions.php:954
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:208
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1672
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1494
wfAppendToArrayIfNotDefault
wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed)
Appends to second array if $value differs from that in $default.
Definition: GlobalFunctions.php:152
$wgDisableOutputCompression
$wgDisableOutputCompression
Disable output compression (enabled by default if zlib is available)
Definition: DefaultSettings.php:3549
wfVarDump
wfVarDump( $var)
A wrapper around the PHP function var_export().
Definition: GlobalFunctions.php:1585
$wgIllegalFileChars
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
Definition: DefaultSettings.php:488
wfGetNull
wfGetNull()
Get a platform-independent path to the null file, e.g.
Definition: GlobalFunctions.php:2594
TempFSFile\getUsableTempDirectory
static getUsableTempDirectory()
Definition: TempFSFile.php:80
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:454
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1994
$wgOverrideHostname
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
Definition: DefaultSettings.php:6784
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:2504
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1413
wfLoadExtension
wfLoadExtension( $ext, $path=null)
Load an extension.
Definition: GlobalFunctions.php:46
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
wfLoadSkin
wfLoadSkin( $skin, $path=null)
Load a skin.
Definition: GlobalFunctions.php:83
wfShorthandToInteger
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
Definition: GlobalFunctions.php:2671
$wgImageLimits
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
Definition: DefaultSettings.php:1548
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:255
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1878
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2369
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1602
wfReadOnlyReason
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
Definition: GlobalFunctions.php:1139
wfMatchesDomainList
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
Definition: GlobalFunctions.php:876
$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:2387
wfRecursiveRemoveDir
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:1940
$wgHttpsPort
$wgHttpsPort
For installations where the canonical server is HTTP but HTTPS is optionally supported,...
Definition: DefaultSettings.php:148
$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:161
$keys
$keys
Definition: testCompression.php:72
wfBacktrace
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
Definition: GlobalFunctions.php:1360
wfEscapeShellArg
wfEscapeShellArg(... $args)
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2031
$source
$source
Definition: mwdoc-filter.php:34
wfAssembleUrl
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
Definition: GlobalFunctions.php:586
$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:2345
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:1074
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:702
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:644
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:2407
$wgOut
$wgOut
Definition: Setup.php:781
wfGetServerUrl
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
Definition: GlobalFunctions.php:568
$wgScriptPath
$wgScriptPath
The path we should point to.
Definition: DefaultSettings.php:179
$IP
$IP
Definition: WebStart.php:49
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:2516
Message\newFallbackSequence
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:456
wfShowingResults
wfShowingResults( $offset, $limit)
Definition: GlobalFunctions.php:1446
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:1397
$wgStyleDirectory
$wgStyleDirectory
Filesystem stylesheets directory.
Definition: DefaultSettings.php:258
wfLogDBError
wfLogDBError( $text, array $context=[])
Log for database errors.
Definition: GlobalFunctions.php:1007
SiteStats\edits
static edits()
Definition: SiteStats.php:94
MWDebug\deprecatedMsg
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: MWDebug.php:257
MW_ENTRY_POINT
const MW_ENTRY_POINT
Definition: api.php:41
$wgInternalServer
$wgInternalServer
Internal server name as known to CDN, if different.
Definition: DefaultSettings.php:2909
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:490
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:2112
MediaWiki\HeaderCallback\warnIfHeadersSent
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
Definition: HeaderCallback.php:83
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1095
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:2059
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:346
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:273
$type
$type
Definition: testCompression.php:52