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 
791 function wfParseUrl( $url ) {
792  global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
793 
794  // Protocol-relative URLs are handled really badly by parse_url(). It's so
795  // bad that the easiest way to handle them is to just prepend 'http:' and
796  // strip the protocol out later.
797  $wasRelative = substr( $url, 0, 2 ) == '//';
798  if ( $wasRelative ) {
799  $url = "http:$url";
800  }
801  $bits = parse_url( $url );
802  // parse_url() returns an array without scheme for some invalid URLs, e.g.
803  // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
804  if ( !$bits || !isset( $bits['scheme'] ) ) {
805  return false;
806  }
807 
808  // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
809  $bits['scheme'] = strtolower( $bits['scheme'] );
810 
811  // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
812  if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
813  $bits['delimiter'] = '://';
814  } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
815  $bits['delimiter'] = ':';
816  // parse_url detects for news: and mailto: the host part of an url as path
817  // We have to correct this wrong detection
818  if ( isset( $bits['path'] ) ) {
819  $bits['host'] = $bits['path'];
820  $bits['path'] = '';
821  }
822  } else {
823  return false;
824  }
825 
826  /* Provide an empty host for eg. file:/// urls (see T30627) */
827  if ( !isset( $bits['host'] ) ) {
828  $bits['host'] = '';
829 
830  // See T47069
831  if ( isset( $bits['path'] ) ) {
832  /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
833  if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
834  $bits['path'] = '/' . $bits['path'];
835  }
836  } else {
837  $bits['path'] = '';
838  }
839  }
840 
841  // If the URL was protocol-relative, fix scheme and delimiter
842  if ( $wasRelative ) {
843  $bits['scheme'] = '';
844  $bits['delimiter'] = '//';
845  }
846  return $bits;
847 }
848 
859 function wfExpandIRI( $url ) {
860  return preg_replace_callback(
861  '/((?:%[89A-F][0-9A-F])+)/i',
862  function ( array $matches ) {
863  return urldecode( $matches[1] );
864  },
865  wfExpandUrl( $url )
866  );
867 }
868 
875 function wfMatchesDomainList( $url, $domains ) {
876  $bits = wfParseUrl( $url );
877  if ( is_array( $bits ) && isset( $bits['host'] ) ) {
878  $host = '.' . $bits['host'];
879  foreach ( (array)$domains as $domain ) {
880  $domain = '.' . $domain;
881  if ( substr( $host, -strlen( $domain ) ) === $domain ) {
882  return true;
883  }
884  }
885  }
886  return false;
887 }
888 
909 function wfDebug( $text, $dest = 'all', array $context = [] ) {
911 
912  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
913  return;
914  }
915 
916  $text = trim( $text );
917 
918  if ( $wgDebugLogPrefix !== '' ) {
919  $context['prefix'] = $wgDebugLogPrefix;
920  }
921  $context['private'] = ( $dest === false || $dest === 'private' );
922 
923  $logger = LoggerFactory::getInstance( 'wfDebug' );
924  $logger->debug( $text, $context );
925 }
926 
931 function wfIsDebugRawPage() {
932  static $cache;
933  if ( $cache !== null ) {
934  return $cache;
935  }
936  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
937  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
938  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
939  || MW_ENTRY_POINT === 'load'
940  ) {
941  $cache = true;
942  } else {
943  $cache = false;
944  }
945  return $cache;
946 }
947 
953 function wfDebugMem( $exact = false ) {
954  $mem = memory_get_usage();
955  if ( !$exact ) {
956  $mem = floor( $mem / 1024 ) . ' KiB';
957  } else {
958  $mem .= ' B';
959  }
960  wfDebug( "Memory usage: $mem" );
961 }
962 
988 function wfDebugLog(
989  $logGroup, $text, $dest = 'all', array $context = []
990 ) {
991  $text = trim( $text );
992 
993  $logger = LoggerFactory::getInstance( $logGroup );
994  $context['private'] = ( $dest === false || $dest === 'private' );
995  $logger->info( $text, $context );
996 }
997 
1006 function wfLogDBError( $text, array $context = [] ) {
1007  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1008  $logger->error( trim( $text ), $context );
1009 }
1010 
1026 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1027  if ( is_string( $version ) || $version === false ) {
1028  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1029  } else {
1030  throw new Exception(
1031  "MediaWiki version must either be a string or false. " .
1032  "Example valid version: '1.33'"
1033  );
1034  }
1035 }
1036 
1058 function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
1059  MWDebug::deprecatedMsg( $msg, $version, $component,
1060  $callerOffset === false ? false : $callerOffset + 1 );
1061 }
1062 
1073 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1074  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1075 }
1076 
1086 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1087  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1088 }
1089 
1095  $context = RequestContext::getMain();
1096 
1097  $profiler = Profiler::instance();
1098  $profiler->setContext( $context );
1099  $profiler->logData();
1100 
1101  // Send out any buffered statsd metrics as needed
1103  MediaWikiServices::getInstance()->getStatsdDataFactory(),
1104  $context->getConfig()
1105  );
1106 }
1107 
1115 function wfIncrStats( $key, $count = 1 ) {
1116  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1117  $stats->updateCount( $key, $count );
1118 }
1119 
1125 function wfReadOnly() {
1126  return MediaWikiServices::getInstance()->getReadOnlyMode()
1127  ->isReadOnly();
1128 }
1129 
1138 function wfReadOnlyReason() {
1139  return MediaWikiServices::getInstance()->getReadOnlyMode()
1140  ->getReason();
1141 }
1142 
1150  return MediaWikiServices::getInstance()->getConfiguredReadOnlyMode()
1151  ->getReason();
1152 }
1153 
1169 function wfGetLangObj( $langcode = false ) {
1170  # Identify which language to get or create a language object for.
1171  # Using is_object here due to Stub objects.
1172  if ( is_object( $langcode ) ) {
1173  # Great, we already have the object (hopefully)!
1174  return $langcode;
1175  }
1176 
1177  global $wgLanguageCode;
1178  $services = MediaWikiServices::getInstance();
1179  if ( $langcode === true || $langcode === $wgLanguageCode ) {
1180  # $langcode is the language code of the wikis content language object.
1181  # or it is a boolean and value is true
1182  return $services->getContentLanguage();
1183  }
1184 
1185  global $wgLang;
1186  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1187  # $langcode is the language code of user language object.
1188  # or it was a boolean and value is false
1189  return $wgLang;
1190  }
1191 
1192  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1193  if ( in_array( $langcode, $validCodes ) ) {
1194  # $langcode corresponds to a valid language.
1195  return $services->getLanguageFactory()->getLanguage( $langcode );
1196  }
1197 
1198  # $langcode is a string, but not a valid language code; use content language.
1199  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1200  return $services->getContentLanguage();
1201 }
1202 
1219 function wfMessage( $key, ...$params ) {
1220  $message = new Message( $key );
1221 
1222  // We call Message::params() to reduce code duplication
1223  if ( $params ) {
1224  $message->params( ...$params );
1225  }
1226 
1227  return $message;
1228 }
1229 
1242 function wfMessageFallback( ...$keys ) {
1243  return Message::newFallbackSequence( ...$keys );
1244 }
1245 
1254 function wfMsgReplaceArgs( $message, $args ) {
1255  # Fix windows line-endings
1256  # Some messages are split with explode("\n", $msg)
1257  $message = str_replace( "\r", '', $message );
1258 
1259  // Replace arguments
1260  if ( is_array( $args ) && $args ) {
1261  if ( is_array( $args[0] ) ) {
1262  $args = array_values( $args[0] );
1263  }
1264  $replacementKeys = [];
1265  foreach ( $args as $n => $param ) {
1266  $replacementKeys['$' . ( $n + 1 )] = $param;
1267  }
1268  $message = strtr( $message, $replacementKeys );
1269  }
1270 
1271  return $message;
1272 }
1273 
1282 function wfHostname() {
1283  // Hostname overriding
1284  global $wgOverrideHostname;
1285  if ( $wgOverrideHostname !== false ) {
1286  return $wgOverrideHostname;
1287  }
1288 
1289  return php_uname( 'n' ) ?: 'unknown';
1290 }
1291 
1302 function wfReportTime( $nonce = null ) {
1303  global $wgShowHostnames;
1304 
1305  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1306  // seconds to milliseconds
1307  $responseTime = round( $elapsed * 1000 );
1308  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1309  if ( $wgShowHostnames ) {
1310  $reportVars['wgHostname'] = wfHostname();
1311  }
1312  return Skin::makeVariablesScript( $reportVars, $nonce );
1313 }
1314 
1325 function wfDebugBacktrace( $limit = 0 ) {
1326  static $disabled = null;
1327 
1328  if ( $disabled === null ) {
1329  $disabled = !function_exists( 'debug_backtrace' );
1330  if ( $disabled ) {
1331  wfDebug( "debug_backtrace() is disabled" );
1332  }
1333  }
1334  if ( $disabled ) {
1335  return [];
1336  }
1337 
1338  if ( $limit ) {
1339  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1340  } else {
1341  return array_slice( debug_backtrace(), 1 );
1342  }
1343 }
1344 
1353 function wfBacktrace( $raw = null ) {
1354  global $wgCommandLineMode;
1355 
1356  if ( $raw === null ) {
1357  $raw = $wgCommandLineMode;
1358  }
1359 
1360  if ( $raw ) {
1361  $frameFormat = "%s line %s calls %s()\n";
1362  $traceFormat = "%s";
1363  } else {
1364  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1365  $traceFormat = "<ul>\n%s</ul>\n";
1366  }
1367 
1368  $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1369  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1370  $line = $frame['line'] ?? '-';
1371  $call = $frame['function'];
1372  if ( !empty( $frame['class'] ) ) {
1373  $call = $frame['class'] . $frame['type'] . $call;
1374  }
1375  return sprintf( $frameFormat, $file, $line, $call );
1376  }, wfDebugBacktrace() );
1377 
1378  return sprintf( $traceFormat, implode( '', $frames ) );
1379 }
1380 
1390 function wfGetCaller( $level = 2 ) {
1391  $backtrace = wfDebugBacktrace( $level + 1 );
1392  if ( isset( $backtrace[$level] ) ) {
1393  return wfFormatStackFrame( $backtrace[$level] );
1394  } else {
1395  return 'unknown';
1396  }
1397 }
1398 
1406 function wfGetAllCallers( $limit = 3 ) {
1407  $trace = array_reverse( wfDebugBacktrace() );
1408  if ( !$limit || $limit > count( $trace ) - 1 ) {
1409  $limit = count( $trace ) - 1;
1410  }
1411  $trace = array_slice( $trace, -$limit - 1, $limit );
1412  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1413 }
1414 
1421 function wfFormatStackFrame( $frame ) {
1422  if ( !isset( $frame['function'] ) ) {
1423  return 'NO_FUNCTION_GIVEN';
1424  }
1425  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1426  $frame['class'] . $frame['type'] . $frame['function'] :
1427  $frame['function'];
1428 }
1429 
1430 /* Some generic result counters, pulled out of SearchEngine */
1431 
1439 function wfShowingResults( $offset, $limit ) {
1440  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1441 }
1442 
1452 function wfClientAcceptsGzip( $force = false ) {
1453  static $result = null;
1454  if ( $result === null || $force ) {
1455  $result = false;
1456  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1457  # @todo FIXME: We may want to blacklist some broken browsers
1458  $m = [];
1459  if ( preg_match(
1460  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1461  $_SERVER['HTTP_ACCEPT_ENCODING'],
1462  $m
1463  )
1464  ) {
1465  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1466  $result = false;
1467  return $result;
1468  }
1469  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1470  $result = true;
1471  }
1472  }
1473  }
1474  return $result;
1475 }
1476 
1487 function wfEscapeWikiText( $text ) {
1488  global $wgEnableMagicLinks;
1489  static $repl = null, $repl2 = null;
1490  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1491  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1492  // in those situations
1493  $repl = [
1494  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1495  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1496  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1497  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1498  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1499  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1500  "\n " => "\n&#32;", "\r " => "\r&#32;",
1501  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1502  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1503  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1504  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1505  '__' => '_&#95;', '://' => '&#58;//',
1506  ];
1507 
1508  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1509  // We have to catch everything "\s" matches in PCRE
1510  foreach ( $magicLinks as $magic ) {
1511  $repl["$magic "] = "$magic&#32;";
1512  $repl["$magic\t"] = "$magic&#9;";
1513  $repl["$magic\r"] = "$magic&#13;";
1514  $repl["$magic\n"] = "$magic&#10;";
1515  $repl["$magic\f"] = "$magic&#12;";
1516  }
1517 
1518  // And handle protocols that don't use "://"
1519  global $wgUrlProtocols;
1520  $repl2 = [];
1521  foreach ( $wgUrlProtocols as $prot ) {
1522  if ( substr( $prot, -1 ) === ':' ) {
1523  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1524  }
1525  }
1526  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1527  }
1528  $text = substr( strtr( "\n$text", $repl ), 1 );
1529  $text = preg_replace( $repl2, '$1&#58;', $text );
1530  return $text;
1531 }
1532 
1543 function wfSetVar( &$dest, $source, $force = false ) {
1544  $temp = $dest;
1545  if ( $source !== null || $force ) {
1546  $dest = $source;
1547  }
1548  return $temp;
1549 }
1550 
1560 function wfSetBit( &$dest, $bit, $state = true ) {
1561  $temp = (bool)( $dest & $bit );
1562  if ( $state !== null ) {
1563  if ( $state ) {
1564  $dest |= $bit;
1565  } else {
1566  $dest &= ~$bit;
1567  }
1568  }
1569  return $temp;
1570 }
1571 
1578 function wfVarDump( $var ) {
1579  global $wgOut;
1580  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1581  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1582  print $s;
1583  } else {
1584  $wgOut->addHTML( $s );
1585  }
1586 }
1587 
1595 function wfHttpError( $code, $label, $desc ) {
1596  global $wgOut;
1597  HttpStatus::header( $code );
1598  if ( $wgOut ) {
1599  $wgOut->disable();
1600  $wgOut->sendCacheControl();
1601  }
1602 
1604  header( 'Content-type: text/html; charset=utf-8' );
1605  ob_start();
1606  print '<!DOCTYPE html>' .
1607  '<html><head><title>' .
1608  htmlspecialchars( $label ) .
1609  '</title></head><body><h1>' .
1610  htmlspecialchars( $label ) .
1611  '</h1><p>' .
1612  nl2br( htmlspecialchars( $desc ) ) .
1613  "</p></body></html>\n";
1614  header( 'Content-Length: ' . ob_get_length() );
1615  ob_end_flush();
1616 }
1617 
1635 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1636  if ( $resetGzipEncoding ) {
1637  // Suppress Content-Encoding and Content-Length
1638  // headers from OutputHandler::handle.
1641  }
1642  while ( $status = ob_get_status() ) {
1643  if ( isset( $status['flags'] ) ) {
1644  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1645  $deleteable = ( $status['flags'] & $flags ) === $flags;
1646  } elseif ( isset( $status['del'] ) ) {
1647  $deleteable = $status['del'];
1648  } else {
1649  // Guess that any PHP-internal setting can't be removed.
1650  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1651  }
1652  if ( !$deleteable ) {
1653  // Give up, and hope the result doesn't break
1654  // output behavior.
1655  break;
1656  }
1657  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1658  // Unit testing barrier to prevent this function from breaking PHPUnit.
1659  break;
1660  }
1661  if ( !ob_end_clean() ) {
1662  // Could not remove output buffer handler; abort now
1663  // to avoid getting in some kind of infinite loop.
1664  break;
1665  }
1666  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1667  // Reset the 'Content-Encoding' field set by this handler
1668  // so we can start fresh.
1669  header_remove( 'Content-Encoding' );
1670  break;
1671  }
1672  }
1673 }
1674 
1688  wfResetOutputBuffers( false );
1689 }
1690 
1699 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1700  # No arg means accept anything (per HTTP spec)
1701  if ( !$accept ) {
1702  return [ $def => 1.0 ];
1703  }
1704 
1705  $prefs = [];
1706 
1707  $parts = explode( ',', $accept );
1708 
1709  foreach ( $parts as $part ) {
1710  # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1711  $values = explode( ';', trim( $part ) );
1712  $match = [];
1713  if ( count( $values ) == 1 ) {
1714  $prefs[$values[0]] = 1.0;
1715  } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1716  $prefs[$values[0]] = floatval( $match[1] );
1717  }
1718  }
1719 
1720  return $prefs;
1721 }
1722 
1735 function mimeTypeMatch( $type, $avail ) {
1736  if ( array_key_exists( $type, $avail ) ) {
1737  return $type;
1738  } else {
1739  $mainType = explode( '/', $type )[0];
1740  if ( array_key_exists( "$mainType/*", $avail ) ) {
1741  return "$mainType/*";
1742  } elseif ( array_key_exists( '*/*', $avail ) ) {
1743  return '*/*';
1744  } else {
1745  return null;
1746  }
1747  }
1748 }
1749 
1764 function wfNegotiateType( $cprefs, $sprefs ) {
1765  $combine = [];
1766 
1767  foreach ( array_keys( $sprefs ) as $type ) {
1768  $subType = explode( '/', $type )[1];
1769  if ( $subType != '*' ) {
1770  $ckey = mimeTypeMatch( $type, $cprefs );
1771  if ( $ckey ) {
1772  $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1773  }
1774  }
1775  }
1776 
1777  foreach ( array_keys( $cprefs ) as $type ) {
1778  $subType = explode( '/', $type )[1];
1779  if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
1780  $skey = mimeTypeMatch( $type, $sprefs );
1781  if ( $skey ) {
1782  $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1783  }
1784  }
1785  }
1786 
1787  $bestq = 0;
1788  $besttype = null;
1789 
1790  foreach ( array_keys( $combine ) as $type ) {
1791  if ( $combine[$type] > $bestq ) {
1792  $besttype = $type;
1793  $bestq = $combine[$type];
1794  }
1795  }
1796 
1797  return $besttype;
1798 }
1799 
1808 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1809  $ret = MWTimestamp::convert( $outputtype, $ts );
1810  if ( $ret === false ) {
1811  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1812  }
1813  return $ret;
1814 }
1815 
1824 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1825  if ( $ts === null ) {
1826  return null;
1827  } else {
1828  return wfTimestamp( $outputtype, $ts );
1829  }
1830 }
1831 
1837 function wfTimestampNow() {
1838  return MWTimestamp::now( TS_MW );
1839 }
1840 
1846 function wfIsWindows() {
1847  return PHP_OS_FAMILY === 'Windows';
1848 }
1849 
1856 function wfIsCLI() {
1857  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1858 }
1859 
1871 function wfTempDir() {
1872  global $wgTmpDirectory;
1873 
1874  if ( $wgTmpDirectory !== false ) {
1875  return $wgTmpDirectory;
1876  }
1877 
1879 }
1880 
1890 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1891  global $wgDirectoryMode;
1892 
1893  if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1894  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1895  }
1896 
1897  if ( $caller !== null ) {
1898  wfDebug( "$caller: called wfMkdirParents($dir)" );
1899  }
1900 
1901  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1902  return true;
1903  }
1904 
1905  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1906 
1907  if ( $mode === null ) {
1908  $mode = $wgDirectoryMode;
1909  }
1910 
1911  // Turn off the normal warning, we're doing our own below
1912  AtEase::suppressWarnings();
1913  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1914  AtEase::restoreWarnings();
1915 
1916  if ( !$ok ) {
1917  // directory may have been created on another request since we last checked
1918  if ( is_dir( $dir ) ) {
1919  return true;
1920  }
1921 
1922  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1923  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1924  }
1925  return $ok;
1926 }
1927 
1933 function wfRecursiveRemoveDir( $dir ) {
1934  wfDebug( __FUNCTION__ . "( $dir )" );
1935  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1936  if ( is_dir( $dir ) ) {
1937  $objects = scandir( $dir );
1938  foreach ( $objects as $object ) {
1939  if ( $object != "." && $object != ".." ) {
1940  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1941  wfRecursiveRemoveDir( $dir . '/' . $object );
1942  } else {
1943  unlink( $dir . '/' . $object );
1944  }
1945  }
1946  }
1947  reset( $objects );
1948  rmdir( $dir );
1949  }
1950 }
1951 
1958 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1959  $accForFormat = $acc >= 0 ? $acc : 0;
1960  $ret = sprintf( "%.${accForFormat}f", $nr );
1961  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1962 }
1963 
1987 function wfIniGetBool( $setting ) {
1988  return wfStringToBool( ini_get( $setting ) );
1989 }
1990 
2003 function wfStringToBool( $val ) {
2004  $val = strtolower( $val );
2005  // 'on' and 'true' can't have whitespace around them, but '1' can.
2006  return $val == 'on'
2007  || $val == 'true'
2008  || $val == 'yes'
2009  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2010 }
2011 
2024 function wfEscapeShellArg( ...$args ) {
2025  return Shell::escape( ...$args );
2026 }
2027 
2052 function wfShellExec( $cmd, &$retval = null, $environ = [],
2053  $limits = [], $options = []
2054 ) {
2055  if ( Shell::isDisabled() ) {
2056  $retval = 1;
2057  // Backwards compatibility be upon us...
2058  return 'Unable to run external programs, proc_open() is disabled.';
2059  }
2060 
2061  if ( is_array( $cmd ) ) {
2062  $cmd = Shell::escape( $cmd );
2063  }
2064 
2065  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2066  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
2067 
2068  try {
2069  $result = Shell::command( [] )
2070  ->unsafeParams( (array)$cmd )
2071  ->environment( $environ )
2072  ->limits( $limits )
2073  ->includeStderr( $includeStderr )
2074  ->profileMethod( $profileMethod )
2075  // For b/c
2076  ->restrict( Shell::RESTRICT_NONE )
2077  ->execute();
2078  } catch ( ProcOpenError $ex ) {
2079  $retval = -1;
2080  return '';
2081  }
2082 
2083  $retval = $result->getExitCode();
2084 
2085  return $result->getStdout();
2086 }
2087 
2105 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
2106  return wfShellExec( $cmd, $retval, $environ, $limits,
2107  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
2108 }
2109 
2125 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2126  global $wgPhpCli;
2127  // Give site config file a chance to run the script in a wrapper.
2128  // The caller may likely want to call wfBasename() on $script.
2129  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
2130  $cmd = [ $options['php'] ?? $wgPhpCli ];
2131  if ( isset( $options['wrapper'] ) ) {
2132  $cmd[] = $options['wrapper'];
2133  }
2134  $cmd[] = $script;
2135  // Escape each parameter for shell
2136  return Shell::escape( array_merge( $cmd, $parameters ) );
2137 }
2138 
2150 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2151  global $wgDiff3;
2152 
2153  # This check may also protect against code injection in
2154  # case of broken installations.
2155  AtEase::suppressWarnings();
2156  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2157  AtEase::restoreWarnings();
2158 
2159  if ( !$haveDiff3 ) {
2160  wfDebug( "diff3 not found" );
2161  return false;
2162  }
2163 
2164  # Make temporary files
2165  $td = wfTempDir();
2166  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2167  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2168  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2169 
2170  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2171  # a newline character. To avoid this, we normalize the trailing whitespace before
2172  # creating the diff.
2173 
2174  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2175  fclose( $oldtextFile );
2176  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2177  fclose( $mytextFile );
2178  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2179  fclose( $yourtextFile );
2180 
2181  # Check for a conflict
2182  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2183  $oldtextName, $yourtextName );
2184  $handle = popen( $cmd, 'r' );
2185 
2186  $mergeAttemptResult = '';
2187  do {
2188  $data = fread( $handle, 8192 );
2189  if ( strlen( $data ) == 0 ) {
2190  break;
2191  }
2192  $mergeAttemptResult .= $data;
2193  } while ( true );
2194  pclose( $handle );
2195 
2196  $conflict = $mergeAttemptResult !== '';
2197 
2198  # Merge differences
2199  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2200  $oldtextName, $yourtextName );
2201  $handle = popen( $cmd, 'r' );
2202  $result = '';
2203  do {
2204  $data = fread( $handle, 8192 );
2205  if ( strlen( $data ) == 0 ) {
2206  break;
2207  }
2208  $result .= $data;
2209  } while ( true );
2210  pclose( $handle );
2211  unlink( $mytextName );
2212  unlink( $oldtextName );
2213  unlink( $yourtextName );
2214 
2215  if ( $result === '' && $old !== '' && !$conflict ) {
2216  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2217  $conflict = true;
2218  }
2219  return !$conflict;
2220 }
2221 
2233 function wfDiff( $before, $after, $params = '-u' ) {
2234  if ( $before == $after ) {
2235  return '';
2236  }
2237 
2238  global $wgDiff;
2239  AtEase::suppressWarnings();
2240  $haveDiff = $wgDiff && file_exists( $wgDiff );
2241  AtEase::restoreWarnings();
2242 
2243  # This check may also protect against code injection in
2244  # case of broken installations.
2245  if ( !$haveDiff ) {
2246  wfDebug( "diff executable not found" );
2247  $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2248  $format = new UnifiedDiffFormatter();
2249  return $format->format( $diffs );
2250  }
2251 
2252  # Make temporary files
2253  $td = wfTempDir();
2254  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2255  $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2256 
2257  fwrite( $oldtextFile, $before );
2258  fclose( $oldtextFile );
2259  fwrite( $newtextFile, $after );
2260  fclose( $newtextFile );
2261 
2262  // Get the diff of the two files
2263  $cmd = "$wgDiff " . $params . ' ' . Shell::escape( $oldtextName, $newtextName );
2264 
2265  $h = popen( $cmd, 'r' );
2266  if ( !$h ) {
2267  unlink( $oldtextName );
2268  unlink( $newtextName );
2269  throw new Exception( __FUNCTION__ . '(): popen() failed' );
2270  }
2271 
2272  $diff = '';
2273 
2274  do {
2275  $data = fread( $h, 8192 );
2276  if ( strlen( $data ) == 0 ) {
2277  break;
2278  }
2279  $diff .= $data;
2280  } while ( true );
2281 
2282  // Clean up
2283  pclose( $h );
2284  unlink( $oldtextName );
2285  unlink( $newtextName );
2286 
2287  // Kill the --- and +++ lines. They're not useful.
2288  $diff_lines = explode( "\n", $diff );
2289  if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
2290  unset( $diff_lines[0] );
2291  }
2292  if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
2293  unset( $diff_lines[1] );
2294  }
2295 
2296  $diff = implode( "\n", $diff_lines );
2297 
2298  return $diff;
2299 }
2300 
2313 function wfBaseName( $path, $suffix = '' ) {
2314  if ( $suffix == '' ) {
2315  $encSuffix = '';
2316  } else {
2317  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2318  }
2319 
2320  $matches = [];
2321  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2322  return $matches[1];
2323  } else {
2324  return '';
2325  }
2326 }
2327 
2337 function wfRelativePath( $path, $from ) {
2338  // Normalize mixed input on Windows...
2339  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2340  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2341 
2342  // Trim trailing slashes -- fix for drive root
2343  $path = rtrim( $path, DIRECTORY_SEPARATOR );
2344  $from = rtrim( $from, DIRECTORY_SEPARATOR );
2345 
2346  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2347  $against = explode( DIRECTORY_SEPARATOR, $from );
2348 
2349  if ( $pieces[0] !== $against[0] ) {
2350  // Non-matching Windows drive letters?
2351  // Return a full path.
2352  return $path;
2353  }
2354 
2355  // Trim off common prefix
2356  while ( count( $pieces ) && count( $against )
2357  && $pieces[0] == $against[0] ) {
2358  array_shift( $pieces );
2359  array_shift( $against );
2360  }
2361 
2362  // relative dots to bump us to the parent
2363  while ( count( $against ) ) {
2364  array_unshift( $pieces, '..' );
2365  array_shift( $against );
2366  }
2367 
2368  array_push( $pieces, wfBaseName( $path ) );
2369 
2370  return implode( DIRECTORY_SEPARATOR, $pieces );
2371 }
2372 
2379 function wfGetPrecompiledData( $name ) {
2380  global $IP;
2381 
2382  $file = "$IP/serialized/$name";
2383  if ( file_exists( $file ) ) {
2384  $blob = file_get_contents( $file );
2385  if ( $blob ) {
2386  return unserialize( $blob );
2387  }
2388  }
2389  return false;
2390 }
2391 
2399 function wfMemcKey( ...$args ) {
2400  return ObjectCache::getLocalClusterInstance()->makeKey( ...$args );
2401 }
2402 
2414 function wfForeignMemcKey( $db, $prefix, ...$args ) {
2415  $keyspace = $prefix ? "$db-$prefix" : $db;
2416  return ObjectCache::getLocalClusterInstance()->makeKeyInternal( $keyspace, $args );
2417 }
2418 
2426 function wfWikiID() {
2427  global $wgDBprefix, $wgDBname;
2428 
2429  if ( $wgDBprefix ) {
2430  return "$wgDBname-$wgDBprefix";
2431  } else {
2432  return $wgDBname;
2433  }
2434 }
2435 
2467 function wfGetDB( $db, $groups = [], $wiki = false ) {
2468  return wfGetLB( $wiki )->getMaintenanceConnectionRef( $db, $groups, $wiki );
2469 }
2470 
2480 function wfGetLB( $wiki = false ) {
2481  if ( $wiki === false ) {
2482  return MediaWikiServices::getInstance()->getDBLoadBalancer();
2483  } else {
2484  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2485  return $factory->getMainLB( $wiki );
2486  }
2487 }
2488 
2496 function wfFindFile( $title, $options = [] ) {
2497  return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2498 }
2499 
2508 function wfLocalFile( $title ) {
2509  return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2510 }
2511 
2519  global $wgMiserMode;
2520  return $wgMiserMode
2521  || ( SiteStats::pages() > 100000
2522  && SiteStats::edits() > 1000000
2523  && SiteStats::users() > 10000 );
2524 }
2525 
2534 function wfScript( $script = 'index' ) {
2536  if ( $script === 'index' ) {
2537  return $wgScript;
2538  } elseif ( $script === 'load' ) {
2539  return $wgLoadScript;
2540  } else {
2541  return "{$wgScriptPath}/{$script}.php";
2542  }
2543 }
2544 
2551 function wfGetScriptUrl() {
2552  wfDeprecated( __FUNCTION__, '1.35' );
2553  if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2554  /* as it was called, minus the query string.
2555  *
2556  * Some sites use Apache rewrite rules to handle subdomains,
2557  * and have PHP set up in a weird way that causes PHP_SELF
2558  * to contain the rewritten URL instead of the one that the
2559  * outside world sees.
2560  *
2561  * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2562  * provides containing the "before" URL.
2563  */
2564  return $_SERVER['SCRIPT_NAME'];
2565  } else {
2566  return $_SERVER['URL'];
2567  }
2568 }
2569 
2577 function wfBoolToStr( $value ) {
2578  return $value ? 'true' : 'false';
2579 }
2580 
2586 function wfGetNull() {
2587  return wfIsWindows() ? 'NUL' : '/dev/null';
2588 }
2589 
2598 function wfStripIllegalFilenameChars( $name ) {
2599  global $wgIllegalFileChars;
2600  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2601  $name = preg_replace(
2602  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2603  '-',
2604  $name
2605  );
2606  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2607  $name = wfBaseName( $name );
2608  return $name;
2609 }
2610 
2617 function wfMemoryLimit( $newLimit ) {
2618  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2619  // If the INI config is already unlimited, there is nothing larger
2620  if ( $oldLimit != -1 ) {
2621  $newLimit = wfShorthandToInteger( $newLimit );
2622  if ( $newLimit == -1 ) {
2623  wfDebug( "Removing PHP's memory limit" );
2624  Wikimedia\suppressWarnings();
2625  ini_set( 'memory_limit', $newLimit );
2626  Wikimedia\restoreWarnings();
2627  } elseif ( $newLimit > $oldLimit ) {
2628  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2629  Wikimedia\suppressWarnings();
2630  ini_set( 'memory_limit', $newLimit );
2631  Wikimedia\restoreWarnings();
2632  }
2633  }
2634 }
2635 
2644 
2645  $timeLimit = (int)ini_get( 'max_execution_time' );
2646  // Note that CLI scripts use 0
2647  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2648  set_time_limit( $wgTransactionalTimeLimit );
2649  }
2650 
2651  ignore_user_abort( true ); // ignore client disconnects
2652 
2653  return $timeLimit;
2654 }
2655 
2663 function wfShorthandToInteger( $string = '', $default = -1 ) {
2664  $string = trim( $string );
2665  if ( $string === '' ) {
2666  return $default;
2667  }
2668  $last = $string[strlen( $string ) - 1];
2669  $val = intval( $string );
2670  switch ( $last ) {
2671  case 'g':
2672  case 'G':
2673  $val *= 1024;
2674  // break intentionally missing
2675  case 'm':
2676  case 'M':
2677  $val *= 1024;
2678  // break intentionally missing
2679  case 'k':
2680  case 'K':
2681  $val *= 1024;
2682  }
2683 
2684  return $val;
2685 }
2686 
2694 function wfGetCache( $cacheType ) {
2695  return ObjectCache::getInstance( $cacheType );
2696 }
2697 
2704 function wfGetMainCache() {
2706 }
2707 
2722 function wfUnpack( $format, $data, $length = false ) {
2723  if ( $length !== false ) {
2724  $realLen = strlen( $data );
2725  if ( $realLen < $length ) {
2726  throw new MWException( "Tried to use wfUnpack on a "
2727  . "string of length $realLen, but needed one "
2728  . "of at least length $length."
2729  );
2730  }
2731  }
2732 
2733  Wikimedia\suppressWarnings();
2734  $result = unpack( $format, $data );
2735  Wikimedia\restoreWarnings();
2736 
2737  if ( $result === false ) {
2738  // If it cannot extract the packed data.
2739  throw new MWException( "unpack could not unpack binary data" );
2740  }
2741  return $result;
2742 }
2743 
2759 function wfIsBadImage( $name, $contextTitle = false ) {
2760  wfDeprecated( __FUNCTION__, '1.34' );
2761  $services = MediaWikiServices::getInstance();
2762  return $services->getBadFileLookup()->isBadFile( $name, $contextTitle ?: null );
2763 }
2764 
2772 function wfCanIPUseHTTPS( $ip ) {
2773  $canDo = true;
2774  Hooks::runner()->onCanIPUseHTTPS( $ip, $canDo );
2775  return (bool)$canDo;
2776 }
2777 
2785 function wfIsInfinity( $str ) {
2786  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2787  return in_array( $str, ExpiryDef::INFINITY_VALS );
2788 }
2789 
2804 function wfThumbIsStandard( File $file, array $params ) {
2806 
2807  $multipliers = [ 1 ];
2808  if ( $wgResponsiveImages ) {
2809  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2810  // @see Linker::processResponsiveImages
2811  $multipliers[] = 1.5;
2812  $multipliers[] = 2;
2813  }
2814 
2815  $handler = $file->getHandler();
2816  if ( !$handler || !isset( $params['width'] ) ) {
2817  return false;
2818  }
2819 
2820  $basicParams = [];
2821  if ( isset( $params['page'] ) ) {
2822  $basicParams['page'] = $params['page'];
2823  }
2824 
2825  $thumbLimits = [];
2826  $imageLimits = [];
2827  // Expand limits to account for multipliers
2828  foreach ( $multipliers as $multiplier ) {
2829  $thumbLimits = array_merge( $thumbLimits, array_map(
2830  function ( $width ) use ( $multiplier ) {
2831  return round( $width * $multiplier );
2832  }, $wgThumbLimits )
2833  );
2834  $imageLimits = array_merge( $imageLimits, array_map(
2835  function ( $pair ) use ( $multiplier ) {
2836  return [
2837  round( $pair[0] * $multiplier ),
2838  round( $pair[1] * $multiplier ),
2839  ];
2840  }, $wgImageLimits )
2841  );
2842  }
2843 
2844  // Check if the width matches one of $wgThumbLimits
2845  if ( in_array( $params['width'], $thumbLimits ) ) {
2846  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2847  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2848  $handler->normaliseParams( $file, $normalParams );
2849  } else {
2850  // If not, then check if the width matchs one of $wgImageLimits
2851  $match = false;
2852  foreach ( $imageLimits as $pair ) {
2853  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2854  // Decide whether the thumbnail should be scaled on width or height.
2855  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2856  $handler->normaliseParams( $file, $normalParams );
2857  // Check if this standard thumbnail size maps to the given width
2858  if ( $normalParams['width'] == $params['width'] ) {
2859  $match = true;
2860  break;
2861  }
2862  }
2863  if ( !$match ) {
2864  return false; // not standard for description pages
2865  }
2866  }
2867 
2868  // Check that the given values for non-page, non-width, params are just defaults
2869  foreach ( $params as $key => $value ) {
2870  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2871  return false;
2872  }
2873  }
2874 
2875  return true;
2876 }
2877 
2890 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2891  // First merge items that are in both arrays
2892  foreach ( $baseArray as $name => &$groupVal ) {
2893  if ( isset( $newValues[$name] ) ) {
2894  $groupVal += $newValues[$name];
2895  }
2896  }
2897  // Now add items that didn't exist yet
2898  $baseArray += $newValues;
2899 
2900  return $baseArray;
2901 }
2902 
2912 function wfGetRusage() {
2913  wfDeprecated( __FUNCTION__, '1.35' );
2914  return getrusage( 0 /* RUSAGE_SELF */ );
2915 }
$wgPhpCli
$wgPhpCli
Executable path of the PHP cli binary.
Definition: DefaultSettings.php:8796
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:1635
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1242
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1570
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:2772
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:1133
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:2233
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1689
$wgDebugRawPage
$wgDebugRawPage
If true, log debugging data from action=raw and load.php.
Definition: DefaultSettings.php:6577
wfThumbIsStandard
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
Definition: GlobalFunctions.php:2804
$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:2890
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:1998
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:1890
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:155
$wgDiff3
$wgDiff3
Path to the GNU diff3 utility.
Definition: DefaultSettings.php:7075
wfMerge
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
Definition: GlobalFunctions.php:2150
wfDebugBacktrace
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
Definition: GlobalFunctions.php:1325
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:1543
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:2480
wfFormatStackFrame
wfFormatStackFrame( $frame)
Return a string representation of frame.
Definition: GlobalFunctions.php:1421
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:1560
Skin\makeVariablesScript
static makeVariablesScript( $data, $nonce=null)
Definition: Skin.php:439
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:1764
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1808
SiteStats\pages
static pages()
Definition: SiteStats.php:112
wfUnpack
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
Definition: GlobalFunctions.php:2722
wfConfiguredReadOnlyReason
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: GlobalFunctions.php:1149
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:6769
wfMemoryLimit
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
Definition: GlobalFunctions.php:2617
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:2551
$wgDiff
$wgDiff
Path to the GNU diff utility.
Definition: DefaultSettings.php:7080
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2313
wfQueriesMustScale
wfQueriesMustScale()
Should low-performance queries be disabled?
Definition: GlobalFunctions.php:2518
$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:1282
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1125
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1254
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1219
$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:1086
wfStringToBool
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
Definition: GlobalFunctions.php:2003
$wgTransactionalTimeLimit
$wgTransactionalTimeLimit
The minimum amount of time that MediaWiki needs for "slow" write request, particularly ones with mult...
Definition: DefaultSettings.php:2421
$wgDebugLogPrefix
$wgDebugLogPrefix
Prefix for debug log lines.
Definition: DefaultSettings.php:6563
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:859
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:988
$wgDBprefix
$wgDBprefix
Current wiki database table name prefix.
Definition: DefaultSettings.php:2018
wfShellWikiCmd
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:2125
wfBoolToStr
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
Definition: GlobalFunctions.php:2577
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:16
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:791
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:1302
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1058
wfGetMainCache
wfGetMainCache()
Get the main cache object.
Definition: GlobalFunctions.php:2704
MWException
MediaWiki exception.
Definition: MWException.php:29
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2598
wfGetRusage
wfGetRusage()
Get system resource usage of current request context.
Definition: GlobalFunctions.php:2912
mimeTypeMatch
mimeTypeMatch( $type, $avail)
Checks if a given MIME type matches any of the keys in the given array.
Definition: GlobalFunctions.php:1735
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1026
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:2534
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:1115
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:2642
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2467
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:2759
$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:1824
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:1169
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:2694
$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:1837
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:909
wfPercent
wfPercent( $nr, int $acc=2, bool $round=true)
Definition: GlobalFunctions.php:1958
wfAcceptToPrefs
wfAcceptToPrefs( $accept, $def=' */*')
Converts an Accept-* header into an array mapping string values to quality factors.
Definition: GlobalFunctions.php:1699
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:931
wfForeignMemcKey
wfForeignMemcKey( $db, $prefix,... $args)
Make a cache key for a foreign DB.
Definition: GlobalFunctions.php:2414
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:2426
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1687
wfClientAcceptsGzip
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
Definition: GlobalFunctions.php:1452
$wgUrlProtocols
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
Definition: DefaultSettings.php:4581
$wgExtensionDirectory
$wgExtensionDirectory
Filesystem extensions directory.
Definition: DefaultSettings.php:251
wfIsCLI
wfIsCLI()
Check if we are running from the commandline.
Definition: GlobalFunctions.php:1856
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1846
$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:3102
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2785
wfDebugMem
wfDebugMem( $exact=false)
Send a line giving PHP memory usage.
Definition: GlobalFunctions.php:953
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:208
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1681
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1487
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:3548
wfVarDump
wfVarDump( $var)
A wrapper around the PHP function var_export().
Definition: GlobalFunctions.php:1578
$wgIllegalFileChars
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
Definition: DefaultSettings.php:497
wfGetNull
wfGetNull()
Get a platform-independent path to the null file, e.g.
Definition: GlobalFunctions.php:2586
TempFSFile\getUsableTempDirectory
static getUsableTempDirectory()
Definition: TempFSFile.php:80
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:453
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1987
$wgOverrideHostname
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
Definition: DefaultSettings.php:6776
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:2496
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1406
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:2663
$wgImageLimits
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
Definition: DefaultSettings.php:1557
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:1871
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2377
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1595
wfReadOnlyReason
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
Definition: GlobalFunctions.php:1138
wfMatchesDomainList
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
Definition: GlobalFunctions.php:875
$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:2379
wfRecursiveRemoveDir
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:1933
$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:1353
wfEscapeShellArg
wfEscapeShellArg(... $args)
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2024
$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:2337
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:1073
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:700
$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:2399
$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:2508
Message\newFallbackSequence
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:469
wfShowingResults
wfShowingResults( $offset, $limit)
Definition: GlobalFunctions.php:1439
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:1390
$wgStyleDirectory
$wgStyleDirectory
Filesystem stylesheets directory.
Definition: DefaultSettings.php:258
wfLogDBError
wfLogDBError( $text, array $context=[])
Log for database errors.
Definition: GlobalFunctions.php:1006
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:2908
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:2105
MediaWiki\HeaderCallback\warnIfHeadersSent
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
Definition: HeaderCallback.php:76
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1094
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:2052
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