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 
153 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
154  wfDeprecated( __FUNCTION__, '1.36' );
155 
156  if ( $changed === null ) {
157  throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
158  }
159  if ( $default[$key] !== $value ) {
160  $changed[$key] = $value;
161  }
162 }
163 
183 function wfMergeErrorArrays( ...$args ) {
184  $out = [];
185  foreach ( $args as $errors ) {
186  foreach ( $errors as $params ) {
187  $originalParams = $params;
188  if ( $params[0] instanceof MessageSpecifier ) {
189  $msg = $params[0];
190  $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
191  }
192  # @todo FIXME: Sometimes get nested arrays for $params,
193  # which leads to E_NOTICEs
194  $spec = implode( "\t", $params );
195  $out[$spec] = $originalParams;
196  }
197  }
198  return array_values( $out );
199 }
200 
209 function wfArrayInsertAfter( array $array, array $insert, $after ) {
210  // Find the offset of the element to insert after.
211  $keys = array_keys( $array );
212  $offsetByKey = array_flip( $keys );
213 
214  $offset = $offsetByKey[$after];
215 
216  // Insert at the specified offset
217  $before = array_slice( $array, 0, $offset + 1, true );
218  $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
219 
220  $output = $before + $insert + $after;
221 
222  return $output;
223 }
224 
233 function wfObjectToArray( $objOrArray, $recursive = true ) {
234  $array = [];
235  if ( is_object( $objOrArray ) ) {
236  $objOrArray = get_object_vars( $objOrArray );
237  }
238  foreach ( $objOrArray as $key => $value ) {
239  if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
240  $value = wfObjectToArray( $value );
241  }
242 
243  $array[$key] = $value;
244  }
245 
246  return $array;
247 }
248 
259 function wfRandom() {
260  // The maximum random value is "only" 2^31-1, so get two random
261  // values to reduce the chance of dupes
262  $max = mt_getrandmax() + 1;
263  $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
264  return $rand;
265 }
266 
277 function wfRandomString( $length = 32 ) {
278  $str = '';
279  for ( $n = 0; $n < $length; $n += 7 ) {
280  $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
281  }
282  return substr( $str, 0, $length );
283 }
284 
312 function wfUrlencode( $s ) {
313  static $needle;
314 
315  if ( $s === null ) {
316  // Reset $needle for testing.
317  $needle = null;
318  return '';
319  }
320 
321  if ( $needle === null ) {
322  $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
323  if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
324  ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
325  ) {
326  $needle[] = '%3A';
327  }
328  }
329 
330  $s = urlencode( $s );
331  $s = str_ireplace(
332  $needle,
333  [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
334  $s
335  );
336 
337  return $s;
338 }
339 
350 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
351  if ( $array2 !== null ) {
352  $array1 += $array2;
353  }
354 
355  $cgi = '';
356  foreach ( $array1 as $key => $value ) {
357  if ( $value !== null && $value !== false ) {
358  if ( $cgi != '' ) {
359  $cgi .= '&';
360  }
361  if ( $prefix !== '' ) {
362  $key = $prefix . "[$key]";
363  }
364  if ( is_array( $value ) ) {
365  $firstTime = true;
366  foreach ( $value as $k => $v ) {
367  $cgi .= $firstTime ? '' : '&';
368  if ( is_array( $v ) ) {
369  $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
370  } else {
371  $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
372  }
373  $firstTime = false;
374  }
375  } else {
376  if ( is_object( $value ) ) {
377  $value = $value->__toString();
378  }
379  $cgi .= urlencode( $key ) . '=' . urlencode( $value );
380  }
381  }
382  }
383  return $cgi;
384 }
385 
395 function wfCgiToArray( $query ) {
396  if ( isset( $query[0] ) && $query[0] == '?' ) {
397  $query = substr( $query, 1 );
398  }
399  $bits = explode( '&', $query );
400  $ret = [];
401  foreach ( $bits as $bit ) {
402  if ( $bit === '' ) {
403  continue;
404  }
405  if ( strpos( $bit, '=' ) === false ) {
406  // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
407  $key = $bit;
408  $value = '';
409  } else {
410  list( $key, $value ) = explode( '=', $bit );
411  }
412  $key = urldecode( $key );
413  $value = urldecode( $value );
414  if ( strpos( $key, '[' ) !== false ) {
415  $keys = array_reverse( explode( '[', $key ) );
416  $key = array_pop( $keys );
417  $temp = $value;
418  foreach ( $keys as $k ) {
419  $k = substr( $k, 0, -1 );
420  $temp = [ $k => $temp ];
421  }
422  if ( isset( $ret[$key] ) ) {
423  $ret[$key] = array_merge( $ret[$key], $temp );
424  } else {
425  $ret[$key] = $temp;
426  }
427  } else {
428  $ret[$key] = $value;
429  }
430  }
431  return $ret;
432 }
433 
442 function wfAppendQuery( $url, $query ) {
443  if ( is_array( $query ) ) {
444  $query = wfArrayToCgi( $query );
445  }
446  if ( $query != '' ) {
447  // Remove the fragment, if there is one
448  $fragment = false;
449  $hashPos = strpos( $url, '#' );
450  if ( $hashPos !== false ) {
451  $fragment = substr( $url, $hashPos );
452  $url = substr( $url, 0, $hashPos );
453  }
454 
455  // Add parameter
456  if ( strpos( $url, '?' ) === false ) {
457  $url .= '?';
458  } else {
459  $url .= '&';
460  }
461  $url .= $query;
462 
463  // Put the fragment back
464  if ( $fragment !== false ) {
465  $url .= $fragment;
466  }
467  }
468  return $url;
469 }
470 
494 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
496  $wgHttpsPort;
497  if ( $defaultProto === PROTO_CANONICAL ) {
498  $serverUrl = $wgCanonicalServer;
499  } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
500  // Make $wgInternalServer fall back to $wgServer if not set
501  $serverUrl = $wgInternalServer;
502  } else {
503  $serverUrl = $wgServer;
504  if ( $defaultProto === PROTO_CURRENT ) {
505  $defaultProto = $wgRequest->getProtocol() . '://';
506  }
507  }
508 
509  // Analyze $serverUrl to obtain its protocol
510  $bits = wfParseUrl( $serverUrl );
511  $serverHasProto = $bits && $bits['scheme'] != '';
512 
513  if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
514  if ( $serverHasProto ) {
515  $defaultProto = $bits['scheme'] . '://';
516  } else {
517  // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
518  // This really isn't supposed to happen. Fall back to HTTP in this
519  // ridiculous case.
520  $defaultProto = PROTO_HTTP;
521  }
522  }
523 
524  $defaultProtoWithoutSlashes = $defaultProto !== null ? substr( $defaultProto, 0, -2 ) : '';
525 
526  if ( substr( $url, 0, 2 ) == '//' ) {
527  $url = $defaultProtoWithoutSlashes . $url;
528  } elseif ( substr( $url, 0, 1 ) == '/' ) {
529  // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
530  // otherwise leave it alone.
531  if ( $serverHasProto ) {
532  $url = $serverUrl . $url;
533  } else {
534  // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the
535  // user to override the port number (T67184)
536  if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
537  if ( isset( $bits['port'] ) ) {
538  throw new Exception( 'A protocol-relative $wgServer may not contain a port number' );
539  }
540  $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url;
541  } else {
542  $url = $defaultProtoWithoutSlashes . $serverUrl . $url;
543  }
544  }
545  }
546 
547  $bits = wfParseUrl( $url );
548 
549  if ( $bits && isset( $bits['path'] ) ) {
550  $bits['path'] = wfRemoveDotSegments( $bits['path'] );
551  return wfAssembleUrl( $bits );
552  } elseif ( $bits ) {
553  # No path to expand
554  return $url;
555  } elseif ( substr( $url, 0, 1 ) != '/' ) {
556  # URL is a relative path
557  return wfRemoveDotSegments( $url );
558  }
559 
560  # Expanded URL is not valid.
561  return false;
562 }
563 
572 function wfGetServerUrl( $proto ) {
573  $url = wfExpandUrl( '/', $proto );
574  return substr( $url, 0, -1 );
575 }
576 
590 function wfAssembleUrl( $urlParts ) {
591  $result = '';
592 
593  if ( isset( $urlParts['delimiter'] ) ) {
594  if ( isset( $urlParts['scheme'] ) ) {
595  $result .= $urlParts['scheme'];
596  }
597 
598  $result .= $urlParts['delimiter'];
599  }
600 
601  if ( isset( $urlParts['host'] ) ) {
602  if ( isset( $urlParts['user'] ) ) {
603  $result .= $urlParts['user'];
604  if ( isset( $urlParts['pass'] ) ) {
605  $result .= ':' . $urlParts['pass'];
606  }
607  $result .= '@';
608  }
609 
610  $result .= $urlParts['host'];
611 
612  if ( isset( $urlParts['port'] ) ) {
613  $result .= ':' . $urlParts['port'];
614  }
615  }
616 
617  if ( isset( $urlParts['path'] ) ) {
618  $result .= $urlParts['path'];
619  }
620 
621  if ( isset( $urlParts['query'] ) && $urlParts['query'] !== '' ) {
622  $result .= '?' . $urlParts['query'];
623  }
624 
625  if ( isset( $urlParts['fragment'] ) ) {
626  $result .= '#' . $urlParts['fragment'];
627  }
628 
629  return $result;
630 }
631 
644 function wfRemoveDotSegments( $urlPath ) {
645  $output = '';
646  $inputOffset = 0;
647  $inputLength = strlen( $urlPath );
648 
649  while ( $inputOffset < $inputLength ) {
650  $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
651  $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
652  $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
653  $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
654  $trimOutput = false;
655 
656  if ( $prefixLengthTwo == './' ) {
657  # Step A, remove leading "./"
658  $inputOffset += 2;
659  } elseif ( $prefixLengthThree == '../' ) {
660  # Step A, remove leading "../"
661  $inputOffset += 3;
662  } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
663  # Step B, replace leading "/.$" with "/"
664  $inputOffset += 1;
665  $urlPath[$inputOffset] = '/';
666  } elseif ( $prefixLengthThree == '/./' ) {
667  # Step B, replace leading "/./" with "/"
668  $inputOffset += 2;
669  } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
670  # Step C, replace leading "/..$" with "/" and
671  # remove last path component in output
672  $inputOffset += 2;
673  $urlPath[$inputOffset] = '/';
674  $trimOutput = true;
675  } elseif ( $prefixLengthFour == '/../' ) {
676  # Step C, replace leading "/../" with "/" and
677  # remove last path component in output
678  $inputOffset += 3;
679  $trimOutput = true;
680  } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
681  # Step D, remove "^.$"
682  $inputOffset += 1;
683  } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
684  # Step D, remove "^..$"
685  $inputOffset += 2;
686  } else {
687  # Step E, move leading path segment to output
688  if ( $prefixLengthOne == '/' ) {
689  $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
690  } else {
691  $slashPos = strpos( $urlPath, '/', $inputOffset );
692  }
693  if ( $slashPos === false ) {
694  $output .= substr( $urlPath, $inputOffset );
695  $inputOffset = $inputLength;
696  } else {
697  $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
698  $inputOffset += $slashPos - $inputOffset;
699  }
700  }
701 
702  if ( $trimOutput ) {
703  $slashPos = strrpos( $output, '/' );
704  if ( $slashPos === false ) {
705  $output = '';
706  } else {
707  $output = substr( $output, 0, $slashPos );
708  }
709  }
710  }
711 
712  return $output;
713 }
714 
722 function wfUrlProtocols( $includeProtocolRelative = true ) {
723  global $wgUrlProtocols;
724 
725  // Cache return values separately based on $includeProtocolRelative
726  static $withProtRel = null, $withoutProtRel = null;
727  $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
728  if ( $cachedValue !== null ) {
729  return $cachedValue;
730  }
731 
732  // Support old-style $wgUrlProtocols strings, for backwards compatibility
733  // with LocalSettings files from 1.5
734  if ( is_array( $wgUrlProtocols ) ) {
735  $protocols = [];
736  foreach ( $wgUrlProtocols as $protocol ) {
737  // Filter out '//' if !$includeProtocolRelative
738  if ( $includeProtocolRelative || $protocol !== '//' ) {
739  $protocols[] = preg_quote( $protocol, '/' );
740  }
741  }
742 
743  $retval = implode( '|', $protocols );
744  } else {
745  // Ignore $includeProtocolRelative in this case
746  // This case exists for pre-1.6 compatibility, and we can safely assume
747  // that '//' won't appear in a pre-1.6 config because protocol-relative
748  // URLs weren't supported until 1.18
749  $retval = $wgUrlProtocols;
750  }
751 
752  // Cache return value
753  if ( $includeProtocolRelative ) {
754  $withProtRel = $retval;
755  } else {
756  $withoutProtRel = $retval;
757  }
758  return $retval;
759 }
760 
768  return wfUrlProtocols( false );
769 }
770 
796 function wfParseUrl( $url ) {
797  global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
798 
799  // Protocol-relative URLs are handled really badly by parse_url(). It's so
800  // bad that the easiest way to handle them is to just prepend 'http:' and
801  // strip the protocol out later.
802  $wasRelative = substr( $url, 0, 2 ) == '//';
803  if ( $wasRelative ) {
804  $url = "http:$url";
805  }
806  $bits = parse_url( $url );
807  // parse_url() returns an array without scheme for some invalid URLs, e.g.
808  // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
809  if ( !$bits || !isset( $bits['scheme'] ) ) {
810  return false;
811  }
812 
813  // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
814  $bits['scheme'] = strtolower( $bits['scheme'] );
815 
816  // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
817  if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
818  $bits['delimiter'] = '://';
819  } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
820  $bits['delimiter'] = ':';
821  // parse_url detects for news: and mailto: the host part of an url as path
822  // We have to correct this wrong detection
823  if ( isset( $bits['path'] ) ) {
824  $bits['host'] = $bits['path'];
825  $bits['path'] = '';
826  }
827  } else {
828  return false;
829  }
830 
831  /* Provide an empty host for eg. file:/// urls (see T30627) */
832  if ( !isset( $bits['host'] ) ) {
833  $bits['host'] = '';
834 
835  // See T47069
836  if ( isset( $bits['path'] ) ) {
837  /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
838  if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
839  $bits['path'] = '/' . $bits['path'];
840  }
841  } else {
842  $bits['path'] = '';
843  }
844  }
845 
846  // If the URL was protocol-relative, fix scheme and delimiter
847  if ( $wasRelative ) {
848  $bits['scheme'] = '';
849  $bits['delimiter'] = '//';
850  }
851  return $bits;
852 }
853 
864 function wfExpandIRI( $url ) {
865  return preg_replace_callback(
866  '/((?:%[89A-F][0-9A-F])+)/i',
867  function ( array $matches ) {
868  return urldecode( $matches[1] );
869  },
870  wfExpandUrl( $url )
871  );
872 }
873 
880 function wfMatchesDomainList( $url, $domains ) {
881  $bits = wfParseUrl( $url );
882  if ( is_array( $bits ) && isset( $bits['host'] ) ) {
883  $host = '.' . $bits['host'];
884  foreach ( (array)$domains as $domain ) {
885  $domain = '.' . $domain;
886  if ( substr( $host, -strlen( $domain ) ) === $domain ) {
887  return true;
888  }
889  }
890  }
891  return false;
892 }
893 
914 function wfDebug( $text, $dest = 'all', array $context = [] ) {
916 
917  if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
918  return;
919  }
920 
921  $text = trim( $text );
922 
923  if ( $wgDebugLogPrefix !== '' ) {
924  $context['prefix'] = $wgDebugLogPrefix;
925  }
926  $context['private'] = ( $dest === false || $dest === 'private' );
927 
928  $logger = LoggerFactory::getInstance( 'wfDebug' );
929  $logger->debug( $text, $context );
930 }
931 
936 function wfIsDebugRawPage() {
937  static $cache;
938  if ( $cache !== null ) {
939  return $cache;
940  }
941  // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
942  // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
943  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
944  || MW_ENTRY_POINT === 'load'
945  ) {
946  $cache = true;
947  } else {
948  $cache = false;
949  }
950  return $cache;
951 }
952 
959 function wfDebugMem( $exact = false ) {
960  wfDeprecated( __FUNCTION__, '1.36' );
961  $mem = memory_get_usage();
962  if ( !$exact ) {
963  $mem = floor( $mem / 1024 ) . ' KiB';
964  } else {
965  $mem .= ' B';
966  }
967  wfDebug( "Memory usage: $mem" );
968 }
969 
995 function wfDebugLog(
996  $logGroup, $text, $dest = 'all', array $context = []
997 ) {
998  $text = trim( $text );
999 
1000  $logger = LoggerFactory::getInstance( $logGroup );
1001  $context['private'] = ( $dest === false || $dest === 'private' );
1002  $logger->info( $text, $context );
1003 }
1004 
1013 function wfLogDBError( $text, array $context = [] ) {
1014  $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1015  $logger->error( trim( $text ), $context );
1016 }
1017 
1033 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1034  if ( is_string( $version ) || $version === false ) {
1035  MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1036  } else {
1037  throw new Exception(
1038  "MediaWiki version must either be a string or false. " .
1039  "Example valid version: '1.33'"
1040  );
1041  }
1042 }
1043 
1065 function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
1066  MWDebug::deprecatedMsg( $msg, $version, $component,
1067  $callerOffset === false ? false : $callerOffset + 1 );
1068 }
1069 
1080 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1081  MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1082 }
1083 
1093 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1094  MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1095 }
1096 
1102  $context = RequestContext::getMain();
1103 
1104  $profiler = Profiler::instance();
1105  $profiler->setContext( $context );
1106  $profiler->logData();
1107 
1108  // Send out any buffered statsd metrics as needed
1110  MediaWikiServices::getInstance()->getStatsdDataFactory(),
1111  $context->getConfig()
1112  );
1113 }
1114 
1124 function wfIncrStats( $key, $count = 1 ) {
1125  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1126  $stats->updateCount( $key, $count );
1127 }
1128 
1134 function wfReadOnly() {
1135  return MediaWikiServices::getInstance()->getReadOnlyMode()
1136  ->isReadOnly();
1137 }
1138 
1147 function wfReadOnlyReason() {
1148  return MediaWikiServices::getInstance()->getReadOnlyMode()
1149  ->getReason();
1150 }
1151 
1160  wfDeprecated( __FUNCTION__, '1.36' );
1161  return MediaWikiServices::getInstance()->getConfiguredReadOnlyMode()
1162  ->getReason();
1163 }
1164 
1180 function wfGetLangObj( $langcode = false ) {
1181  # Identify which language to get or create a language object for.
1182  # Using is_object here due to Stub objects.
1183  if ( is_object( $langcode ) ) {
1184  # Great, we already have the object (hopefully)!
1185  return $langcode;
1186  }
1187 
1188  global $wgLanguageCode;
1189  $services = MediaWikiServices::getInstance();
1190  if ( $langcode === true || $langcode === $wgLanguageCode ) {
1191  # $langcode is the language code of the wikis content language object.
1192  # or it is a boolean and value is true
1193  return $services->getContentLanguage();
1194  }
1195 
1196  global $wgLang;
1197  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1198  # $langcode is the language code of user language object.
1199  # or it was a boolean and value is false
1200  return $wgLang;
1201  }
1202 
1203  $validCodes = array_keys( $services->getLanguageNameUtils()->getLanguageNames() );
1204  if ( in_array( $langcode, $validCodes ) ) {
1205  # $langcode corresponds to a valid language.
1206  return $services->getLanguageFactory()->getLanguage( $langcode );
1207  }
1208 
1209  # $langcode is a string, but not a valid language code; use content language.
1210  wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language." );
1211  return $services->getContentLanguage();
1212 }
1213 
1230 function wfMessage( $key, ...$params ) {
1231  $message = new Message( $key );
1232 
1233  // We call Message::params() to reduce code duplication
1234  if ( $params ) {
1235  $message->params( ...$params );
1236  }
1237 
1238  return $message;
1239 }
1240 
1253 function wfMessageFallback( ...$keys ) {
1254  return Message::newFallbackSequence( ...$keys );
1255 }
1256 
1265 function wfMsgReplaceArgs( $message, $args ) {
1266  # Fix windows line-endings
1267  # Some messages are split with explode("\n", $msg)
1268  $message = str_replace( "\r", '', $message );
1269 
1270  // Replace arguments
1271  if ( is_array( $args ) && $args ) {
1272  if ( is_array( $args[0] ) ) {
1273  $args = array_values( $args[0] );
1274  }
1275  $replacementKeys = [];
1276  foreach ( $args as $n => $param ) {
1277  $replacementKeys['$' . ( $n + 1 )] = $param;
1278  }
1279  $message = strtr( $message, $replacementKeys );
1280  }
1281 
1282  return $message;
1283 }
1284 
1293 function wfHostname() {
1294  // Hostname overriding
1295  global $wgOverrideHostname;
1296  if ( $wgOverrideHostname !== false ) {
1297  return $wgOverrideHostname;
1298  }
1299 
1300  return php_uname( 'n' ) ?: 'unknown';
1301 }
1302 
1313 function wfReportTime( $nonce = null ) {
1314  global $wgShowHostnames;
1315 
1316  $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
1317  // seconds to milliseconds
1318  $responseTime = round( $elapsed * 1000 );
1319  $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1320  if ( $wgShowHostnames ) {
1321  $reportVars['wgHostname'] = wfHostname();
1322  }
1323 
1324  return (
1326  ResourceLoader::makeConfigSetScript( $reportVars ),
1327  $nonce
1328  )
1329  );
1330 }
1331 
1342 function wfDebugBacktrace( $limit = 0 ) {
1343  static $disabled = null;
1344 
1345  if ( $disabled === null ) {
1346  $disabled = !function_exists( 'debug_backtrace' );
1347  if ( $disabled ) {
1348  wfDebug( "debug_backtrace() is disabled" );
1349  }
1350  }
1351  if ( $disabled ) {
1352  return [];
1353  }
1354 
1355  if ( $limit ) {
1356  return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1357  } else {
1358  return array_slice( debug_backtrace(), 1 );
1359  }
1360 }
1361 
1370 function wfBacktrace( $raw = null ) {
1371  global $wgCommandLineMode;
1372 
1373  if ( $raw === null ) {
1374  $raw = $wgCommandLineMode;
1375  }
1376 
1377  if ( $raw ) {
1378  $frameFormat = "%s line %s calls %s()\n";
1379  $traceFormat = "%s";
1380  } else {
1381  $frameFormat = "<li>%s line %s calls %s()</li>\n";
1382  $traceFormat = "<ul>\n%s</ul>\n";
1383  }
1384 
1385  $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1386  $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1387  $line = $frame['line'] ?? '-';
1388  $call = $frame['function'];
1389  if ( !empty( $frame['class'] ) ) {
1390  $call = $frame['class'] . $frame['type'] . $call;
1391  }
1392  return sprintf( $frameFormat, $file, $line, $call );
1393  }, wfDebugBacktrace() );
1394 
1395  return sprintf( $traceFormat, implode( '', $frames ) );
1396 }
1397 
1407 function wfGetCaller( $level = 2 ) {
1408  $backtrace = wfDebugBacktrace( $level + 1 );
1409  if ( isset( $backtrace[$level] ) ) {
1410  return wfFormatStackFrame( $backtrace[$level] );
1411  } else {
1412  return 'unknown';
1413  }
1414 }
1415 
1423 function wfGetAllCallers( $limit = 3 ) {
1424  $trace = array_reverse( wfDebugBacktrace() );
1425  if ( !$limit || $limit > count( $trace ) - 1 ) {
1426  $limit = count( $trace ) - 1;
1427  }
1428  $trace = array_slice( $trace, -$limit - 1, $limit );
1429  return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1430 }
1431 
1438 function wfFormatStackFrame( $frame ) {
1439  if ( !isset( $frame['function'] ) ) {
1440  return 'NO_FUNCTION_GIVEN';
1441  }
1442  return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1443  $frame['class'] . $frame['type'] . $frame['function'] :
1444  $frame['function'];
1445 }
1446 
1447 /* Some generic result counters, pulled out of SearchEngine */
1448 
1456 function wfShowingResults( $offset, $limit ) {
1457  return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1458 }
1459 
1469 function wfClientAcceptsGzip( $force = false ) {
1470  static $result = null;
1471  if ( $result === null || $force ) {
1472  $result = false;
1473  if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1474  # @todo FIXME: We may want to blacklist some broken browsers
1475  $m = [];
1476  if ( preg_match(
1477  '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1478  $_SERVER['HTTP_ACCEPT_ENCODING'],
1479  $m
1480  )
1481  ) {
1482  if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1483  $result = false;
1484  return $result;
1485  }
1486  wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
1487  $result = true;
1488  }
1489  }
1490  }
1491  return $result;
1492 }
1493 
1504 function wfEscapeWikiText( $text ) {
1505  global $wgEnableMagicLinks;
1506  static $repl = null, $repl2 = null;
1507  if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) {
1508  // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1509  // in those situations
1510  $repl = [
1511  '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1512  '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1513  '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
1514  "\n#" => "\n&#35;", "\r#" => "\r&#35;",
1515  "\n*" => "\n&#42;", "\r*" => "\r&#42;",
1516  "\n:" => "\n&#58;", "\r:" => "\r&#58;",
1517  "\n " => "\n&#32;", "\r " => "\r&#32;",
1518  "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
1519  "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
1520  "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
1521  "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
1522  '__' => '_&#95;', '://' => '&#58;//',
1523  ];
1524 
1525  $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1526  // We have to catch everything "\s" matches in PCRE
1527  foreach ( $magicLinks as $magic ) {
1528  $repl["$magic "] = "$magic&#32;";
1529  $repl["$magic\t"] = "$magic&#9;";
1530  $repl["$magic\r"] = "$magic&#13;";
1531  $repl["$magic\n"] = "$magic&#10;";
1532  $repl["$magic\f"] = "$magic&#12;";
1533  }
1534 
1535  // And handle protocols that don't use "://"
1536  global $wgUrlProtocols;
1537  $repl2 = [];
1538  foreach ( $wgUrlProtocols as $prot ) {
1539  if ( substr( $prot, -1 ) === ':' ) {
1540  $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1541  }
1542  }
1543  $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1544  }
1545  $text = substr( strtr( "\n$text", $repl ), 1 );
1546  $text = preg_replace( $repl2, '$1&#58;', $text );
1547  return $text;
1548 }
1549 
1560 function wfSetVar( &$dest, $source, $force = false ) {
1561  $temp = $dest;
1562  if ( $source !== null || $force ) {
1563  $dest = $source;
1564  }
1565  return $temp;
1566 }
1567 
1577 function wfSetBit( &$dest, $bit, $state = true ) {
1578  $temp = (bool)( $dest & $bit );
1579  if ( $state !== null ) {
1580  if ( $state ) {
1581  $dest |= $bit;
1582  } else {
1583  $dest &= ~$bit;
1584  }
1585  }
1586  return $temp;
1587 }
1588 
1595 function wfVarDump( $var ) {
1596  global $wgOut;
1597  $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1598  if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1599  print $s;
1600  } else {
1601  $wgOut->addHTML( $s );
1602  }
1603 }
1604 
1612 function wfHttpError( $code, $label, $desc ) {
1613  global $wgOut;
1614  HttpStatus::header( $code );
1615  if ( $wgOut ) {
1616  $wgOut->disable();
1617  $wgOut->sendCacheControl();
1618  }
1619 
1621  header( 'Content-type: text/html; charset=utf-8' );
1622  ob_start();
1623  print '<!DOCTYPE html>' .
1624  '<html><head><title>' .
1625  htmlspecialchars( $label ) .
1626  '</title></head><body><h1>' .
1627  htmlspecialchars( $label ) .
1628  '</h1><p>' .
1629  nl2br( htmlspecialchars( $desc ) ) .
1630  "</p></body></html>\n";
1631  header( 'Content-Length: ' . ob_get_length() );
1632  ob_end_flush();
1633 }
1634 
1652 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1653  if ( $resetGzipEncoding ) {
1654  // Suppress Content-Encoding and Content-Length
1655  // headers from OutputHandler::handle.
1658  }
1659  while ( $status = ob_get_status() ) {
1660  if ( isset( $status['flags'] ) ) {
1661  $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
1662  $deleteable = ( $status['flags'] & $flags ) === $flags;
1663  } elseif ( isset( $status['del'] ) ) {
1664  $deleteable = $status['del'];
1665  } else {
1666  // Guess that any PHP-internal setting can't be removed.
1667  $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1668  }
1669  if ( !$deleteable ) {
1670  // Give up, and hope the result doesn't break
1671  // output behavior.
1672  break;
1673  }
1674  if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) {
1675  // Unit testing barrier to prevent this function from breaking PHPUnit.
1676  break;
1677  }
1678  if ( !ob_end_clean() ) {
1679  // Could not remove output buffer handler; abort now
1680  // to avoid getting in some kind of infinite loop.
1681  break;
1682  }
1683  if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
1684  // Reset the 'Content-Encoding' field set by this handler
1685  // so we can start fresh.
1686  header_remove( 'Content-Encoding' );
1687  break;
1688  }
1689  }
1690 }
1691 
1707  wfDeprecated( __FUNCTION__, '1.36' );
1708  wfResetOutputBuffers( false );
1709 }
1710 
1720 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1721  wfDeprecated( __FUNCTION__, '1.36' );
1722  # No arg means accept anything (per HTTP spec)
1723  if ( !$accept ) {
1724  return [ $def => 1.0 ];
1725  }
1726 
1727  $prefs = [];
1728 
1729  $parts = explode( ',', $accept );
1730 
1731  foreach ( $parts as $part ) {
1732  # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1733  $values = explode( ';', trim( $part ) );
1734  $match = [];
1735  if ( count( $values ) == 1 ) {
1736  $prefs[$values[0]] = 1.0;
1737  } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1738  $prefs[$values[0]] = floatval( $match[1] );
1739  }
1740  }
1741 
1742  return $prefs;
1743 }
1744 
1757 function mimeTypeMatch( $type, $avail ) {
1758  if ( array_key_exists( $type, $avail ) ) {
1759  return $type;
1760  } else {
1761  $mainType = explode( '/', $type )[0];
1762  if ( array_key_exists( "$mainType/*", $avail ) ) {
1763  return "$mainType/*";
1764  } elseif ( array_key_exists( '*/*', $avail ) ) {
1765  return '*/*';
1766  } else {
1767  return null;
1768  }
1769  }
1770 }
1771 
1786 function wfNegotiateType( $cprefs, $sprefs ) {
1787  wfDeprecated( __FUNCTION__, '1.36' );
1788  $combine = [];
1789 
1790  foreach ( array_keys( $sprefs ) as $type ) {
1791  $subType = explode( '/', $type )[1];
1792  if ( $subType != '*' ) {
1793  $ckey = mimeTypeMatch( $type, $cprefs );
1794  if ( $ckey ) {
1795  $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1796  }
1797  }
1798  }
1799 
1800  foreach ( array_keys( $cprefs ) as $type ) {
1801  $subType = explode( '/', $type )[1];
1802  if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
1803  $skey = mimeTypeMatch( $type, $sprefs );
1804  if ( $skey ) {
1805  $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1806  }
1807  }
1808  }
1809 
1810  $bestq = 0;
1811  $besttype = null;
1812 
1813  foreach ( array_keys( $combine ) as $type ) {
1814  if ( $combine[$type] > $bestq ) {
1815  $besttype = $type;
1816  $bestq = $combine[$type];
1817  }
1818  }
1819 
1820  return $besttype;
1821 }
1822 
1831 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
1832  $ret = MWTimestamp::convert( $outputtype, $ts );
1833  if ( $ret === false ) {
1834  wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" );
1835  }
1836  return $ret;
1837 }
1838 
1847 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1848  if ( $ts === null ) {
1849  return null;
1850  } else {
1851  return wfTimestamp( $outputtype, $ts );
1852  }
1853 }
1854 
1860 function wfTimestampNow() {
1861  return MWTimestamp::now( TS_MW );
1862 }
1863 
1869 function wfIsWindows() {
1870  return PHP_OS_FAMILY === 'Windows';
1871 }
1872 
1879 function wfIsCLI() {
1880  return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
1881 }
1882 
1894 function wfTempDir() {
1895  global $wgTmpDirectory;
1896 
1897  if ( $wgTmpDirectory !== false ) {
1898  return $wgTmpDirectory;
1899  }
1900 
1902 }
1903 
1913 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
1914  global $wgDirectoryMode;
1915 
1916  if ( FileBackend::isStoragePath( $dir ) ) { // sanity
1917  throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
1918  }
1919 
1920  if ( $caller !== null ) {
1921  wfDebug( "$caller: called wfMkdirParents($dir)" );
1922  }
1923 
1924  if ( strval( $dir ) === '' || is_dir( $dir ) ) {
1925  return true;
1926  }
1927 
1928  $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir );
1929 
1930  if ( $mode === null ) {
1931  $mode = $wgDirectoryMode;
1932  }
1933 
1934  // Turn off the normal warning, we're doing our own below
1935  AtEase::suppressWarnings();
1936  $ok = mkdir( $dir, $mode, true ); // PHP5 <3
1937  AtEase::restoreWarnings();
1938 
1939  if ( !$ok ) {
1940  // directory may have been created on another request since we last checked
1941  if ( is_dir( $dir ) ) {
1942  return true;
1943  }
1944 
1945  // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
1946  wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
1947  }
1948  return $ok;
1949 }
1950 
1956 function wfRecursiveRemoveDir( $dir ) {
1957  wfDebug( __FUNCTION__ . "( $dir )" );
1958  // taken from https://www.php.net/manual/en/function.rmdir.php#98622
1959  if ( is_dir( $dir ) ) {
1960  $objects = scandir( $dir );
1961  foreach ( $objects as $object ) {
1962  if ( $object != "." && $object != ".." ) {
1963  if ( filetype( $dir . '/' . $object ) == "dir" ) {
1964  wfRecursiveRemoveDir( $dir . '/' . $object );
1965  } else {
1966  unlink( $dir . '/' . $object );
1967  }
1968  }
1969  }
1970  reset( $objects );
1971  rmdir( $dir );
1972  }
1973 }
1974 
1981 function wfPercent( $nr, int $acc = 2, bool $round = true ) {
1982  $accForFormat = $acc >= 0 ? $acc : 0;
1983  $ret = sprintf( "%.${accForFormat}f", $nr );
1984  return $round ? round( (float)$ret, $acc ) . '%' : "$ret%";
1985 }
1986 
2010 function wfIniGetBool( $setting ) {
2011  return wfStringToBool( ini_get( $setting ) );
2012 }
2013 
2026 function wfStringToBool( $val ) {
2027  $val = strtolower( $val );
2028  // 'on' and 'true' can't have whitespace around them, but '1' can.
2029  return $val == 'on'
2030  || $val == 'true'
2031  || $val == 'yes'
2032  || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2033 }
2034 
2047 function wfEscapeShellArg( ...$args ) {
2048  return Shell::escape( ...$args );
2049 }
2050 
2075 function wfShellExec( $cmd, &$retval = null, $environ = [],
2076  $limits = [], $options = []
2077 ) {
2078  if ( Shell::isDisabled() ) {
2079  $retval = 1;
2080  // Backwards compatibility be upon us...
2081  return 'Unable to run external programs, proc_open() is disabled.';
2082  }
2083 
2084  if ( is_array( $cmd ) ) {
2085  $cmd = Shell::escape( $cmd );
2086  }
2087 
2088  $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2089  $profileMethod = $options['profileMethod'] ?? wfGetCaller();
2090 
2091  try {
2092  $result = Shell::command( [] )
2093  ->unsafeParams( (array)$cmd )
2094  ->environment( $environ )
2095  ->limits( $limits )
2096  ->includeStderr( $includeStderr )
2097  ->profileMethod( $profileMethod )
2098  // For b/c
2099  ->restrict( Shell::RESTRICT_NONE )
2100  ->execute();
2101  } catch ( ProcOpenError $ex ) {
2102  $retval = -1;
2103  return '';
2104  }
2105 
2106  $retval = $result->getExitCode();
2107 
2108  return $result->getStdout();
2109 }
2110 
2128 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
2129  return wfShellExec( $cmd, $retval, $environ, $limits,
2130  [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
2131 }
2132 
2148 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2149  global $wgPhpCli;
2150  // Give site config file a chance to run the script in a wrapper.
2151  // The caller may likely want to call wfBasename() on $script.
2152  Hooks::runner()->onWfShellWikiCmd( $script, $parameters, $options );
2153  $cmd = [ $options['php'] ?? $wgPhpCli ];
2154  if ( isset( $options['wrapper'] ) ) {
2155  $cmd[] = $options['wrapper'];
2156  }
2157  $cmd[] = $script;
2158  // Escape each parameter for shell
2159  return Shell::escape( array_merge( $cmd, $parameters ) );
2160 }
2161 
2173 function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
2174  global $wgDiff3;
2175 
2176  # This check may also protect against code injection in
2177  # case of broken installations.
2178  AtEase::suppressWarnings();
2179  $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2180  AtEase::restoreWarnings();
2181 
2182  if ( !$haveDiff3 ) {
2183  wfDebug( "diff3 not found" );
2184  return false;
2185  }
2186 
2187  # Make temporary files
2188  $td = wfTempDir();
2189  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2190  $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2191  $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2192 
2193  # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2194  # a newline character. To avoid this, we normalize the trailing whitespace before
2195  # creating the diff.
2196 
2197  fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2198  fclose( $oldtextFile );
2199  fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2200  fclose( $mytextFile );
2201  fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2202  fclose( $yourtextFile );
2203 
2204  # Check for a conflict
2205  $cmd = Shell::escape( $wgDiff3, '-a', '--overlap-only', $mytextName,
2206  $oldtextName, $yourtextName );
2207  $handle = popen( $cmd, 'r' );
2208 
2209  $mergeAttemptResult = '';
2210  do {
2211  $data = fread( $handle, 8192 );
2212  if ( strlen( $data ) == 0 ) {
2213  break;
2214  }
2215  $mergeAttemptResult .= $data;
2216  } while ( true );
2217  pclose( $handle );
2218 
2219  $conflict = $mergeAttemptResult !== '';
2220 
2221  # Merge differences
2222  $cmd = Shell::escape( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2223  $oldtextName, $yourtextName );
2224  $handle = popen( $cmd, 'r' );
2225  $result = '';
2226  do {
2227  $data = fread( $handle, 8192 );
2228  if ( strlen( $data ) == 0 ) {
2229  break;
2230  }
2231  $result .= $data;
2232  } while ( true );
2233  pclose( $handle );
2234  unlink( $mytextName );
2235  unlink( $oldtextName );
2236  unlink( $yourtextName );
2237 
2238  if ( $result === '' && $old !== '' && !$conflict ) {
2239  wfDebug( "Unexpected null result from diff3. Command: $cmd" );
2240  $conflict = true;
2241  }
2242  return !$conflict;
2243 }
2244 
2256 function wfDiff( $before, $after, $params = '-u' ) {
2257  wfDeprecated( __FUNCTION__, '1.25' );
2258  if ( $before == $after ) {
2259  return '';
2260  }
2261 
2262  global $wgDiff;
2263  AtEase::suppressWarnings();
2264  $haveDiff = $wgDiff && file_exists( $wgDiff );
2265  AtEase::restoreWarnings();
2266 
2267  # This check may also protect against code injection in
2268  # case of broken installations.
2269  if ( !$haveDiff ) {
2270  wfDebug( "diff executable not found" );
2271  $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2272  $format = new UnifiedDiffFormatter();
2273  return $format->format( $diffs );
2274  }
2275 
2276  # Make temporary files
2277  $td = wfTempDir();
2278  $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2279  $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2280 
2281  fwrite( $oldtextFile, $before );
2282  fclose( $oldtextFile );
2283  fwrite( $newtextFile, $after );
2284  fclose( $newtextFile );
2285 
2286  // Get the diff of the two files
2287  $cmd = "$wgDiff " . $params . ' ' . Shell::escape( $oldtextName, $newtextName );
2288 
2289  $h = popen( $cmd, 'r' );
2290  if ( !$h ) {
2291  unlink( $oldtextName );
2292  unlink( $newtextName );
2293  throw new Exception( __FUNCTION__ . '(): popen() failed' );
2294  }
2295 
2296  $diff = '';
2297 
2298  do {
2299  $data = fread( $h, 8192 );
2300  if ( strlen( $data ) == 0 ) {
2301  break;
2302  }
2303  $diff .= $data;
2304  } while ( true );
2305 
2306  // Clean up
2307  pclose( $h );
2308  unlink( $oldtextName );
2309  unlink( $newtextName );
2310 
2311  // Kill the --- and +++ lines. They're not useful.
2312  $diff_lines = explode( "\n", $diff );
2313  if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
2314  unset( $diff_lines[0] );
2315  }
2316  if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
2317  unset( $diff_lines[1] );
2318  }
2319 
2320  $diff = implode( "\n", $diff_lines );
2321 
2322  return $diff;
2323 }
2324 
2337 function wfBaseName( $path, $suffix = '' ) {
2338  if ( $suffix == '' ) {
2339  $encSuffix = '';
2340  } else {
2341  $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2342  }
2343 
2344  $matches = [];
2345  if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2346  return $matches[1];
2347  } else {
2348  return '';
2349  }
2350 }
2351 
2361 function wfRelativePath( $path, $from ) {
2362  // Normalize mixed input on Windows...
2363  $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2364  $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2365 
2366  // Trim trailing slashes -- fix for drive root
2367  $path = rtrim( $path, DIRECTORY_SEPARATOR );
2368  $from = rtrim( $from, DIRECTORY_SEPARATOR );
2369 
2370  $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2371  $against = explode( DIRECTORY_SEPARATOR, $from );
2372 
2373  if ( $pieces[0] !== $against[0] ) {
2374  // Non-matching Windows drive letters?
2375  // Return a full path.
2376  return $path;
2377  }
2378 
2379  // Trim off common prefix
2380  while ( count( $pieces ) && count( $against )
2381  && $pieces[0] == $against[0] ) {
2382  array_shift( $pieces );
2383  array_shift( $against );
2384  }
2385 
2386  // relative dots to bump us to the parent
2387  while ( count( $against ) ) {
2388  array_unshift( $pieces, '..' );
2389  array_shift( $against );
2390  }
2391 
2392  $pieces[] = wfBaseName( $path );
2393 
2394  return implode( DIRECTORY_SEPARATOR, $pieces );
2395 }
2396 
2404 function wfGetPrecompiledData( $name ) {
2405  wfDeprecated( __FUNCTION__, '1.36' );
2406  global $IP;
2407 
2408  $file = "$IP/serialized/$name";
2409  if ( file_exists( $file ) ) {
2410  $blob = file_get_contents( $file );
2411  if ( $blob ) {
2412  return unserialize( $blob );
2413  }
2414  }
2415  return false;
2416 }
2417 
2425 function wfWikiID() {
2426  global $wgDBprefix, $wgDBname;
2427 
2428  if ( $wgDBprefix ) {
2429  return "$wgDBname-$wgDBprefix";
2430  } else {
2431  return $wgDBname;
2432  }
2433 }
2434 
2466 function wfGetDB( $db, $groups = [], $wiki = false ) {
2467  return wfGetLB( $wiki )->getMaintenanceConnectionRef( $db, $groups, $wiki );
2468 }
2469 
2479 function wfGetLB( $wiki = false ) {
2480  if ( $wiki === false ) {
2481  return MediaWikiServices::getInstance()->getDBLoadBalancer();
2482  } else {
2483  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
2484  return $factory->getMainLB( $wiki );
2485  }
2486 }
2487 
2495 function wfFindFile( $title, $options = [] ) {
2496  return MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title, $options );
2497 }
2498 
2507 function wfLocalFile( $title ) {
2508  return MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $title );
2509 }
2510 
2518  global $wgMiserMode;
2519  return $wgMiserMode
2520  || ( SiteStats::pages() > 100000
2521  && SiteStats::edits() > 1000000
2522  && SiteStats::users() > 10000 );
2523 }
2524 
2533 function wfScript( $script = 'index' ) {
2535  if ( $script === 'index' ) {
2536  return $wgScript;
2537  } elseif ( $script === 'load' ) {
2538  return $wgLoadScript;
2539  } else {
2540  return "{$wgScriptPath}/{$script}.php";
2541  }
2542 }
2543 
2550 function wfGetScriptUrl() {
2551  wfDeprecated( __FUNCTION__, '1.35' );
2552  if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
2553  /* as it was called, minus the query string.
2554  *
2555  * Some sites use Apache rewrite rules to handle subdomains,
2556  * and have PHP set up in a weird way that causes PHP_SELF
2557  * to contain the rewritten URL instead of the one that the
2558  * outside world sees.
2559  *
2560  * If in this mode, use SCRIPT_URL instead, which mod_rewrite
2561  * provides containing the "before" URL.
2562  */
2563  return $_SERVER['SCRIPT_NAME'];
2564  } else {
2565  return $_SERVER['URL'];
2566  }
2567 }
2568 
2576 function wfBoolToStr( $value ) {
2577  return $value ? 'true' : 'false';
2578 }
2579 
2585 function wfGetNull() {
2586  return wfIsWindows() ? 'NUL' : '/dev/null';
2587 }
2588 
2597 function wfStripIllegalFilenameChars( $name ) {
2598  global $wgIllegalFileChars;
2599  $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
2600  $name = preg_replace(
2601  "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
2602  '-',
2603  $name
2604  );
2605  // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
2606  $name = wfBaseName( $name );
2607  return $name;
2608 }
2609 
2616 function wfMemoryLimit( $newLimit ) {
2617  $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
2618  // If the INI config is already unlimited, there is nothing larger
2619  if ( $oldLimit != -1 ) {
2620  $newLimit = wfShorthandToInteger( $newLimit );
2621  if ( $newLimit == -1 ) {
2622  wfDebug( "Removing PHP's memory limit" );
2623  Wikimedia\suppressWarnings();
2624  ini_set( 'memory_limit', $newLimit );
2625  Wikimedia\restoreWarnings();
2626  } elseif ( $newLimit > $oldLimit ) {
2627  wfDebug( "Raising PHP's memory limit to $newLimit bytes" );
2628  Wikimedia\suppressWarnings();
2629  ini_set( 'memory_limit', $newLimit );
2630  Wikimedia\restoreWarnings();
2631  }
2632  }
2633 }
2634 
2643 
2644  $timeLimit = (int)ini_get( 'max_execution_time' );
2645  // Note that CLI scripts use 0
2646  if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
2647  set_time_limit( $wgTransactionalTimeLimit );
2648  }
2649 
2650  ignore_user_abort( true ); // ignore client disconnects
2651 
2652  return $timeLimit;
2653 }
2654 
2662 function wfShorthandToInteger( $string = '', $default = -1 ) {
2663  $string = trim( $string );
2664  if ( $string === '' ) {
2665  return $default;
2666  }
2667  $last = $string[strlen( $string ) - 1];
2668  $val = intval( $string );
2669  switch ( $last ) {
2670  case 'g':
2671  case 'G':
2672  $val *= 1024;
2673  // break intentionally missing
2674  case 'm':
2675  case 'M':
2676  $val *= 1024;
2677  // break intentionally missing
2678  case 'k':
2679  case 'K':
2680  $val *= 1024;
2681  }
2682 
2683  return $val;
2684 }
2685 
2693 function wfGetCache( $cacheType ) {
2694  return ObjectCache::getInstance( $cacheType );
2695 }
2696 
2703 function wfGetMainCache() {
2705 }
2706 
2721 function wfUnpack( $format, $data, $length = false ) {
2722  if ( $length !== false ) {
2723  $realLen = strlen( $data );
2724  if ( $realLen < $length ) {
2725  throw new MWException( "Tried to use wfUnpack on a "
2726  . "string of length $realLen, but needed one "
2727  . "of at least length $length."
2728  );
2729  }
2730  }
2731 
2732  Wikimedia\suppressWarnings();
2733  $result = unpack( $format, $data );
2734  Wikimedia\restoreWarnings();
2735 
2736  if ( $result === false ) {
2737  // If it cannot extract the packed data.
2738  throw new MWException( "unpack could not unpack binary data" );
2739  }
2740  return $result;
2741 }
2742 
2750 function wfCanIPUseHTTPS( $ip ) {
2751  $canDo = true;
2752  Hooks::runner()->onCanIPUseHTTPS( $ip, $canDo );
2753  return (bool)$canDo;
2754 }
2755 
2763 function wfIsInfinity( $str ) {
2764  // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js).
2765  return in_array( $str, ExpiryDef::INFINITY_VALS );
2766 }
2767 
2782 function wfThumbIsStandard( File $file, array $params ) {
2784 
2785  $multipliers = [ 1 ];
2786  if ( $wgResponsiveImages ) {
2787  // These available sizes are hardcoded currently elsewhere in MediaWiki.
2788  // @see Linker::processResponsiveImages
2789  $multipliers[] = 1.5;
2790  $multipliers[] = 2;
2791  }
2792 
2793  $handler = $file->getHandler();
2794  if ( !$handler || !isset( $params['width'] ) ) {
2795  return false;
2796  }
2797 
2798  $basicParams = [];
2799  if ( isset( $params['page'] ) ) {
2800  $basicParams['page'] = $params['page'];
2801  }
2802 
2803  $thumbLimits = [];
2804  $imageLimits = [];
2805  // Expand limits to account for multipliers
2806  foreach ( $multipliers as $multiplier ) {
2807  $thumbLimits = array_merge( $thumbLimits, array_map(
2808  function ( $width ) use ( $multiplier ) {
2809  return round( $width * $multiplier );
2810  }, $wgThumbLimits )
2811  );
2812  $imageLimits = array_merge( $imageLimits, array_map(
2813  function ( $pair ) use ( $multiplier ) {
2814  return [
2815  round( $pair[0] * $multiplier ),
2816  round( $pair[1] * $multiplier ),
2817  ];
2818  }, $wgImageLimits )
2819  );
2820  }
2821 
2822  // Check if the width matches one of $wgThumbLimits
2823  if ( in_array( $params['width'], $thumbLimits ) ) {
2824  $normalParams = $basicParams + [ 'width' => $params['width'] ];
2825  // Append any default values to the map (e.g. "lossy", "lossless", ...)
2826  $handler->normaliseParams( $file, $normalParams );
2827  } else {
2828  // If not, then check if the width matchs one of $wgImageLimits
2829  $match = false;
2830  foreach ( $imageLimits as $pair ) {
2831  $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ];
2832  // Decide whether the thumbnail should be scaled on width or height.
2833  // Also append any default values to the map (e.g. "lossy", "lossless", ...)
2834  $handler->normaliseParams( $file, $normalParams );
2835  // Check if this standard thumbnail size maps to the given width
2836  if ( $normalParams['width'] == $params['width'] ) {
2837  $match = true;
2838  break;
2839  }
2840  }
2841  if ( !$match ) {
2842  return false; // not standard for description pages
2843  }
2844  }
2845 
2846  // Check that the given values for non-page, non-width, params are just defaults
2847  foreach ( $params as $key => $value ) {
2848  if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
2849  return false;
2850  }
2851  }
2852 
2853  return true;
2854 }
2855 
2868 function wfArrayPlus2d( array $baseArray, array $newValues ) {
2869  // First merge items that are in both arrays
2870  foreach ( $baseArray as $name => &$groupVal ) {
2871  if ( isset( $newValues[$name] ) ) {
2872  $groupVal += $newValues[$name];
2873  }
2874  }
2875  // Now add items that didn't exist yet
2876  $baseArray += $newValues;
2877 
2878  return $baseArray;
2879 }
2880 
2890 function wfGetRusage() {
2891  wfDeprecated( __FUNCTION__, '1.35' );
2892  return getrusage( 0 /* RUSAGE_SELF */ );
2893 }
$wgPhpCli
$wgPhpCli
Executable path of the PHP cli binary.
Definition: DefaultSettings.php:8804
wfArrayInsertAfter
wfArrayInsertAfter(array $array, array $insert, $after)
Insert array into another array after the specified KEY
Definition: GlobalFunctions.php:209
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:183
wfResetOutputBuffers
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
Definition: GlobalFunctions.php:1652
wfMessageFallback
wfMessageFallback(... $keys)
This function accepts multiple message keys and returns a message instance for the first message whic...
Definition: GlobalFunctions.php:1253
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1566
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:2750
ResourceLoader\makeConfigSetScript
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
Definition: ResourceLoader.php:1669
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:1137
MediaWiki\ProcOpenError
@newable
Definition: ProcOpenError.php:28
wfDiff
wfDiff( $before, $after, $params='-u')
Returns unified plain-text diff of two texts.
Definition: GlobalFunctions.php:2256
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1684
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:203
$wgDebugRawPage
$wgDebugRawPage
If true, log debugging data from action=raw and load.php.
Definition: DefaultSettings.php:6591
wfThumbIsStandard
wfThumbIsStandard(File $file, array $params)
Returns true if these thumbnail parameters match one that MediaWiki requests from file description pa...
Definition: GlobalFunctions.php:2782
$wgTmpDirectory
$wgTmpDirectory
The local filesystem path to a temporary directory.
Definition: DefaultSettings.php:419
wfArrayPlus2d
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
Definition: GlobalFunctions.php:2868
$wgDBname
$wgDBname
Current wiki database name.
Definition: DefaultSettings.php:1990
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:1913
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
$wgDiff3
$wgDiff3
Path to the GNU diff3 utility.
Definition: DefaultSettings.php:7087
wfMerge
wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
wfMerge attempts to merge differences between three texts.
Definition: GlobalFunctions.php:2173
wfDebugBacktrace
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
Definition: GlobalFunctions.php:1342
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:1560
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:2479
wfFormatStackFrame
wfFormatStackFrame( $frame)
Return a string representation of frame.
Definition: GlobalFunctions.php:1438
ResourceLoader\makeInlineScript
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
Definition: ResourceLoader.php:1642
wfRemoveDotSegments
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
Definition: GlobalFunctions.php:644
$wgScript
$wgScript
The URL path to index.php.
Definition: DefaultSettings.php:204
wfSetBit
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
Definition: GlobalFunctions.php:1577
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:1786
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1831
SiteStats\pages
static pages()
Definition: SiteStats.php:112
wfUnpack
wfUnpack( $format, $data, $length=false)
Wrapper around php's unpack.
Definition: GlobalFunctions.php:2721
wfConfiguredReadOnlyReason
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: GlobalFunctions.php:1159
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:6783
wfMemoryLimit
wfMemoryLimit( $newLimit)
Raise PHP's memory limit (if needed).
Definition: GlobalFunctions.php:2616
wfObjectToArray
wfObjectToArray( $objOrArray, $recursive=true)
Recursively converts the parameter (an object) to an array with the same data.
Definition: GlobalFunctions.php:233
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:312
wfArrayDiff2_cmp
wfArrayDiff2_cmp( $a, $b)
Definition: GlobalFunctions.php:121
wfGetScriptUrl
wfGetScriptUrl()
Get the script URL.
Definition: GlobalFunctions.php:2550
$wgDiff
$wgDiff
Path to the GNU diff utility.
Definition: DefaultSettings.php:7092
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2337
wfQueriesMustScale
wfQueriesMustScale()
Should low-performance queries be disabled?
Definition: GlobalFunctions.php:2517
$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:1293
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1134
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1265
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1230
$s
$s
Definition: mergeMessageFileList.php:186
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1093
wfStringToBool
wfStringToBool( $val)
Convert string value to boolean, when the following are interpreted as true:
Definition: GlobalFunctions.php:2026
$wgTransactionalTimeLimit
$wgTransactionalTimeLimit
The minimum amount of time that MediaWiki needs for "slow" write request, particularly ones with mult...
Definition: DefaultSettings.php:2412
$wgDebugLogPrefix
$wgDebugLogPrefix
Prefix for debug log lines.
Definition: DefaultSettings.php:6577
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:864
$wgLang
$wgLang
Definition: Setup.php:777
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:995
$wgDBprefix
$wgDBprefix
Current wiki database table name prefix.
Definition: DefaultSettings.php:2010
wfShellWikiCmd
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:2148
wfBoolToStr
wfBoolToStr( $value)
Convenience function converts boolean values into "true" or "false" (string) values.
Definition: GlobalFunctions.php:2576
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:442
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:796
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:1313
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1065
wfGetMainCache
wfGetMainCache()
Get the main cache object.
Definition: GlobalFunctions.php:2703
MWException
MediaWiki exception.
Definition: MWException.php:29
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2597
wfGetRusage
wfGetRusage()
Get system resource usage of current request context.
Definition: GlobalFunctions.php:2890
mimeTypeMatch
mimeTypeMatch( $type, $avail)
Checks if a given MIME type matches any of the keys in the given array.
Definition: GlobalFunctions.php:1757
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1033
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:2533
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:1124
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:2641
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2466
wfUrlProtocolsWithoutProtRel
wfUrlProtocolsWithoutProtRel()
Like wfUrlProtocols(), but excludes '//' from the protocol list.
Definition: GlobalFunctions.php:767
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
$matches
$matches
Definition: NoLocalSettings.php:24
$wgLoadScript
$wgLoadScript
The URL path to load.php.
Definition: DefaultSettings.php:212
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:1847
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:1180
wfCgiToArray
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Definition: GlobalFunctions.php:395
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:221
wfGetCache
wfGetCache( $cacheType)
Get a specific cache object.
Definition: GlobalFunctions.php:2693
$wgEnableMagicLinks
$wgEnableMagicLinks
Enable the magic links feature of automatically turning ISBN xxx, PMID xxx, RFC xxx into links.
Definition: DefaultSettings.php:4759
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1860
PROTO_CANONICAL
const PROTO_CANONICAL
Definition: Defines.php:206
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:914
wfPercent
wfPercent( $nr, int $acc=2, bool $round=true)
Definition: GlobalFunctions.php:1981
wfAcceptToPrefs
wfAcceptToPrefs( $accept, $def=' */*')
Converts an Accept-* header into an array mapping string values to quality factors.
Definition: GlobalFunctions.php:1720
$wgCanonicalServer
$wgCanonicalServer
Canonical URL of the server, to use in IRC feeds and notification e-mails.
Definition: DefaultSettings.php:117
wfIsDebugRawPage
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
Definition: GlobalFunctions.php:936
UnifiedDiffFormatter
A formatter that outputs unified diffs @newable.
Definition: UnifiedDiffFormatter.php:32
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:205
wfUrlProtocols
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
Definition: GlobalFunctions.php:722
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:2425
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1706
wfClientAcceptsGzip
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
Definition: GlobalFunctions.php:1469
$wgUrlProtocols
$wgUrlProtocols
URL schemes that should be recognized as valid by wfParseUrl().
Definition: DefaultSettings.php:4589
$wgExtensionDirectory
$wgExtensionDirectory
Filesystem extensions directory.
Definition: DefaultSettings.php:248
wfIsCLI
wfIsCLI()
Check if we are running from the commandline.
Definition: GlobalFunctions.php:1879
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1869
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:108
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:3105
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2763
wfDebugMem
wfDebugMem( $exact=false)
Send a line giving PHP memory usage.
Definition: GlobalFunctions.php:959
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1676
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1504
wfAppendToArrayIfNotDefault
wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed)
Appends to second array if $value differs from that in $default.
Definition: GlobalFunctions.php:153
$wgDisableOutputCompression
$wgDisableOutputCompression
Disable output compression (enabled by default if zlib is available)
Definition: DefaultSettings.php:3550
wfVarDump
wfVarDump( $var)
A wrapper around the PHP function var_export().
Definition: GlobalFunctions.php:1595
$wgIllegalFileChars
$wgIllegalFileChars
Additional characters that are not allowed in filenames.
Definition: DefaultSettings.php:492
wfGetNull
wfGetNull()
Get a platform-independent path to the null file, e.g.
Definition: GlobalFunctions.php:2585
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:2010
$wgOverrideHostname
$wgOverrideHostname
Override server hostname detection with a hardcoded value.
Definition: DefaultSettings.php:6790
PROTO_INTERNAL
const PROTO_INTERNAL
Definition: Defines.php:207
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:2495
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1423
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:2662
$wgImageLimits
$wgImageLimits
Limit images on image description pages to a user-selectable limit.
Definition: DefaultSettings.php:1553
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:259
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1894
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2368
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1612
wfReadOnlyReason
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
Definition: GlobalFunctions.php:1147
wfMatchesDomainList
wfMatchesDomainList( $url, $domains)
Check whether a given URL has a domain that occurs in a given set of domains.
Definition: GlobalFunctions.php:880
$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:2404
wfRecursiveRemoveDir
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:1956
$wgHttpsPort
$wgHttpsPort
For installations where the canonical server is HTTP but HTTPS is optionally supported,...
Definition: DefaultSettings.php:145
$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:1370
wfEscapeShellArg
wfEscapeShellArg(... $args)
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2047
$source
$source
Definition: mwdoc-filter.php:34
wfAssembleUrl
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
Definition: GlobalFunctions.php:590
$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:2361
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:1080
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:735
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:645
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
$wgOut
$wgOut
Definition: Setup.php:782
wfGetServerUrl
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
Definition: GlobalFunctions.php:572
$wgScriptPath
$wgScriptPath
The path we should point to.
Definition: DefaultSettings.php:176
$IP
$IP
Definition: WebStart.php:49
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:2507
Message\newFallbackSequence
static newFallbackSequence(... $keys)
Factory function accepting multiple message keys and returning a message instance for the first messa...
Definition: Message.php:458
wfShowingResults
wfShowingResults( $offset, $limit)
Definition: GlobalFunctions.php:1456
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:1407
$wgStyleDirectory
$wgStyleDirectory
Filesystem stylesheets directory.
Definition: DefaultSettings.php:255
wfLogDBError
wfLogDBError( $text, array $context=[])
Log for database errors.
Definition: GlobalFunctions.php:1013
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:304
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:2912
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:202
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:494
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:2128
MediaWiki\HeaderCallback\warnIfHeadersSent
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
Definition: HeaderCallback.php:85
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1101
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:2075
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:350
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:277
$type
$type
Definition: testCompression.php:52