MediaWiki  master
Maintenance.php
Go to the documentation of this file.
1 <?php
23 // Bail on old versions of PHP, or if composer has not been run yet to install
24 // dependencies.
25 require_once __DIR__ . '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'text' );
27 
29 
35 // Define this so scripts can easily find doMaintenance.php
36 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' );
37 
41 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
42 
43 $maintClass = false;
44 
45 // Some extensions rely on MW_INSTALL_PATH to find core files to include. Setting it here helps them
46 // if they're included by a core script (like DatabaseUpdater) after Maintenance.php has already
47 // been run.
48 if ( strval( getenv( 'MW_INSTALL_PATH' ) ) === '' ) {
49  putenv( 'MW_INSTALL_PATH=' . realpath( __DIR__ . '/..' ) );
50 }
51 
57 
79 abstract class Maintenance {
84  const DB_NONE = 0;
85  const DB_STD = 1;
86  const DB_ADMIN = 2;
87 
88  // Const for getStdin()
89  const STDIN_ALL = 'all';
90 
91  // Array of desired/allowed params
92  protected $mParams = [];
93 
94  // Array of mapping short parameters to long ones
95  protected $mShortParamsMap = [];
96 
97  // Array of desired/allowed args
98  protected $mArgList = [];
99 
100  // This is the list of options that were actually passed
101  protected $mOptions = [];
102 
103  // This is the list of arguments that were actually passed
104  protected $mArgs = [];
105 
106  // Allow arbitrary options to be passed, or only specified ones?
107  protected $mAllowUnregisteredOptions = false;
108 
109  // Name of the script currently running
110  protected $mSelf;
111 
112  // Special vars for params that are always used
113  protected $mQuiet = false;
114  protected $mDbUser, $mDbPass;
115 
116  // A description of the script, children should change this via addDescription()
117  protected $mDescription = '';
118 
119  // Have we already loaded our user input?
120  protected $mInputLoaded = false;
121 
128  protected $mBatchSize = null;
129 
130  // Generic options added by addDefaultParams()
131  private $mGenericParameters = [];
132  // Generic options which might or not be supported by the script
133  private $mDependantParameters = [];
134 
139  private $mDb = null;
140 
142  private $lastReplicationWait = 0.0;
143 
148  public $fileHandle;
149 
155  private $config;
156 
161  private $requiredExtensions = [];
162 
174  public $orderedOptions = [];
175 
180  public function __construct() {
181  global $IP;
182  $IP = getenv( 'MW_INSTALL_PATH' );
183 
184  $this->addDefaultParams();
185  register_shutdown_function( [ $this, 'outputChanneled' ], false );
186  }
187 
195  public static function shouldExecute() {
196  global $wgCommandLineMode;
197 
198  if ( !function_exists( 'debug_backtrace' ) ) {
199  // If someone has a better idea...
200  return $wgCommandLineMode;
201  }
202 
203  $bt = debug_backtrace();
204  $count = count( $bt );
205  if ( $count < 2 ) {
206  return false; // sanity
207  }
208  if ( $bt[0]['class'] !== self::class || $bt[0]['function'] !== 'shouldExecute' ) {
209  return false; // last call should be to this function
210  }
211  $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
212  for ( $i = 1; $i < $count; $i++ ) {
213  if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
214  return false; // previous calls should all be "requires"
215  }
216  }
217 
218  return true;
219  }
220 
229  abstract public function execute();
230 
237  protected function supportsOption( $name ) {
238  return isset( $this->mParams[$name] );
239  }
240 
252  protected function addOption( $name, $description, $required = false,
253  $withArg = false, $shortName = false, $multiOccurrence = false
254  ) {
255  $this->mParams[$name] = [
256  'desc' => $description,
257  'require' => $required,
258  'withArg' => $withArg,
259  'shortName' => $shortName,
260  'multiOccurrence' => $multiOccurrence
261  ];
262 
263  if ( $shortName !== false ) {
264  $this->mShortParamsMap[$shortName] = $name;
265  }
266  }
267 
273  protected function hasOption( $name ) {
274  return isset( $this->mOptions[$name] );
275  }
276 
287  protected function getOption( $name, $default = null ) {
288  if ( $this->hasOption( $name ) ) {
289  return $this->mOptions[$name];
290  } else {
291  // Set it so we don't have to provide the default again
292  $this->mOptions[$name] = $default;
293 
294  return $this->mOptions[$name];
295  }
296  }
297 
304  protected function addArg( $arg, $description, $required = true ) {
305  $this->mArgList[] = [
306  'name' => $arg,
307  'desc' => $description,
308  'require' => $required
309  ];
310  }
311 
316  protected function deleteOption( $name ) {
317  unset( $this->mParams[$name] );
318  }
319 
325  protected function setAllowUnregisteredOptions( $allow ) {
326  $this->mAllowUnregisteredOptions = $allow;
327  }
328 
333  protected function addDescription( $text ) {
334  $this->mDescription = $text;
335  }
336 
342  protected function hasArg( $argId = 0 ) {
343  if ( func_num_args() === 0 ) {
344  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
345  }
346 
347  return isset( $this->mArgs[$argId] );
348  }
349 
356  protected function getArg( $argId = 0, $default = null ) {
357  if ( func_num_args() === 0 ) {
358  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
359  }
360 
361  return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
362  }
363 
371  protected function getBatchSize() {
372  return $this->mBatchSize;
373  }
374 
379  protected function setBatchSize( $s = 0 ) {
380  $this->mBatchSize = $s;
381 
382  // If we support $mBatchSize, show the option.
383  // Used to be in addDefaultParams, but in order for that to
384  // work, subclasses would have to call this function in the constructor
385  // before they called parent::__construct which is just weird
386  // (and really wasn't done).
387  if ( $this->mBatchSize ) {
388  $this->addOption( 'batch-size', 'Run this many operations ' .
389  'per batch, default: ' . $this->mBatchSize, false, true );
390  if ( isset( $this->mParams['batch-size'] ) ) {
391  // This seems a little ugly...
392  $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
393  }
394  }
395  }
396 
401  public function getName() {
402  return $this->mSelf;
403  }
404 
411  protected function getStdin( $len = null ) {
412  if ( $len == self::STDIN_ALL ) {
413  return file_get_contents( 'php://stdin' );
414  }
415  $f = fopen( 'php://stdin', 'rt' );
416  if ( !$len ) {
417  return $f;
418  }
419  $input = fgets( $f, $len );
420  fclose( $f );
421 
422  return rtrim( $input );
423  }
424 
428  public function isQuiet() {
429  return $this->mQuiet;
430  }
431 
438  protected function output( $out, $channel = null ) {
439  // This is sometimes called very early, before Setup.php is included.
440  if ( class_exists( MediaWikiServices::class ) ) {
441  // Try to periodically flush buffered metrics to avoid OOMs
442  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
443  if ( $stats->getDataCount() > 1000 ) {
444  MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
445  }
446  }
447 
448  if ( $this->mQuiet ) {
449  return;
450  }
451  if ( $channel === null ) {
452  $this->cleanupChanneled();
453  print $out;
454  } else {
455  $out = preg_replace( '/\n\z/', '', $out );
456  $this->outputChanneled( $out, $channel );
457  }
458  }
459 
466  protected function error( $err, $die = 0 ) {
467  if ( intval( $die ) !== 0 ) {
468  wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
469  $this->fatalError( $err, intval( $die ) );
470  }
471  $this->outputChanneled( false );
472  if (
473  ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
474  !defined( 'MW_PHPUNIT_TEST' )
475  ) {
476  fwrite( STDERR, $err . "\n" );
477  } else {
478  print $err;
479  }
480  }
481 
489  protected function fatalError( $msg, $exitCode = 1 ) {
490  $this->error( $msg );
491  exit( $exitCode );
492  }
493 
494  private $atLineStart = true;
495  private $lastChannel = null;
496 
500  public function cleanupChanneled() {
501  if ( !$this->atLineStart ) {
502  print "\n";
503  $this->atLineStart = true;
504  }
505  }
506 
515  public function outputChanneled( $msg, $channel = null ) {
516  if ( $msg === false ) {
517  $this->cleanupChanneled();
518 
519  return;
520  }
521 
522  // End the current line if necessary
523  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
524  print "\n";
525  }
526 
527  print $msg;
528 
529  $this->atLineStart = false;
530  if ( $channel === null ) {
531  // For unchanneled messages, output trailing newline immediately
532  print "\n";
533  $this->atLineStart = true;
534  }
535  $this->lastChannel = $channel;
536  }
537 
548  public function getDbType() {
549  return self::DB_STD;
550  }
551 
555  protected function addDefaultParams() {
556  # Generic (non script dependant) options:
557 
558  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
559  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
560  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
561  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
562  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
563  $this->addOption(
564  'memory-limit',
565  'Set a specific memory limit for the script, '
566  . '"max" for no limit or "default" to avoid changing it',
567  false,
568  true
569  );
570  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
571  "http://en.wikipedia.org. This is sometimes necessary because " .
572  "server name detection may fail in command line scripts.", false, true );
573  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
574  // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
575  $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
576 
577  # Save generic options to display them separately in help
578  $this->mGenericParameters = $this->mParams;
579 
580  # Script dependant options:
581 
582  // If we support a DB, show the options
583  if ( $this->getDbType() > 0 ) {
584  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
585  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
586  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
587  }
588 
589  # Save additional script dependant options to display
590  # ┬áthem separately in help
591  $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
592  }
593 
598  public function getConfig() {
599  if ( $this->config === null ) {
600  $this->config = MediaWikiServices::getInstance()->getMainConfig();
601  }
602 
603  return $this->config;
604  }
605 
610  public function setConfig( Config $config ) {
611  $this->config = $config;
612  }
613 
623  protected function requireExtension( $name ) {
624  $this->requiredExtensions[] = $name;
625  }
626 
632  public function checkRequiredExtensions() {
633  $registry = ExtensionRegistry::getInstance();
634  $missing = [];
635  foreach ( $this->requiredExtensions as $name ) {
636  if ( !$registry->isLoaded( $name ) ) {
637  $missing[] = $name;
638  }
639  }
640 
641  if ( $missing ) {
642  $joined = implode( ', ', $missing );
643  $msg = "The following extensions are required to be installed "
644  . "for this script to run: $joined. Please enable them and then try again.";
645  $this->fatalError( $msg );
646  }
647  }
648 
653  public function setAgentAndTriggers() {
654  if ( function_exists( 'posix_getpwuid' ) ) {
655  $agent = posix_getpwuid( posix_geteuid() )['name'];
656  } else {
657  $agent = 'sysadmin';
658  }
659  $agent .= '@' . wfHostname();
660 
661  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
662  // Add a comment for easy SHOW PROCESSLIST interpretation
663  $lbFactory->setAgentName(
664  mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
665  );
666  self::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
667  }
668 
674  public static function setLBFactoryTriggers( LBFactory $LBFactory, Config $config ) {
675  $services = MediaWikiServices::getInstance();
676  $stats = $services->getStatsdDataFactory();
677  // Hook into period lag checks which often happen in long-running scripts
678  $lbFactory = $services->getDBLoadBalancerFactory();
679  $lbFactory->setWaitForReplicationListener(
680  __METHOD__,
681  function () use ( $stats, $config ) {
682  // Check config in case of JobRunner and unit tests
683  if ( $config->get( 'CommandLineMode' ) ) {
685  }
686  // Try to periodically flush buffered metrics to avoid OOMs
687  MediaWiki::emitBufferedStatsdData( $stats, $config );
688  }
689  );
690  // Check for other windows to run them. A script may read or do a few writes
691  // to the master but mostly be writing to something else, like a file store.
692  $lbFactory->getMainLB()->setTransactionListener(
693  __METHOD__,
694  function ( $trigger ) use ( $stats, $config ) {
695  // Check config in case of JobRunner and unit tests
696  if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
698  }
699  // Try to periodically flush buffered metrics to avoid OOMs
700  MediaWiki::emitBufferedStatsdData( $stats, $config );
701  }
702  );
703  }
704 
712  public function runChild( $maintClass, $classFile = null ) {
713  // Make sure the class is loaded first
714  if ( !class_exists( $maintClass ) ) {
715  if ( $classFile ) {
716  require_once $classFile;
717  }
718  if ( !class_exists( $maintClass ) ) {
719  $this->error( "Cannot spawn child: $maintClass" );
720  }
721  }
722 
726  $child = new $maintClass();
727  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
728  if ( !is_null( $this->mDb ) ) {
729  $child->setDB( $this->mDb );
730  }
731 
732  return $child;
733  }
734 
738  public function setup() {
739  global $IP, $wgCommandLineMode;
740 
741  # Abort if called from a web server
742  # wfIsCLI() is not available yet
743  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
744  $this->fatalError( 'This script must be run from the command line' );
745  }
746 
747  if ( $IP === null ) {
748  $this->fatalError( "\$IP not set, aborting!\n" .
749  '(Did you forget to call parent::__construct() in your maintenance script?)' );
750  }
751 
752  # Make sure we can handle script parameters
753  if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
754  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
755  }
756 
757  // Send PHP warnings and errors to stderr instead of stdout.
758  // This aids in diagnosing problems, while keeping messages
759  // out of redirected output.
760  if ( ini_get( 'display_errors' ) ) {
761  ini_set( 'display_errors', 'stderr' );
762  }
763 
764  $this->loadParamsAndArgs();
765 
766  # Set the memory limit
767  # Note we need to set it again later in cache LocalSettings changed it
768  $this->adjustMemoryLimit();
769 
770  # Set max execution time to 0 (no limit). PHP.net says that
771  # "When running PHP from the command line the default setting is 0."
772  # But sometimes this doesn't seem to be the case.
773  ini_set( 'max_execution_time', 0 );
774 
775  # Define us as being in MediaWiki
776  define( 'MEDIAWIKI', true );
777 
778  $wgCommandLineMode = true;
779 
780  # Turn off output buffering if it's on
781  while ( ob_get_level() > 0 ) {
782  ob_end_flush();
783  }
784  }
785 
795  public function memoryLimit() {
796  $limit = $this->getOption( 'memory-limit', 'max' );
797  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
798  return $limit;
799  }
800 
804  protected function adjustMemoryLimit() {
805  $limit = $this->memoryLimit();
806  if ( $limit == 'max' ) {
807  $limit = -1; // no memory limit
808  }
809  if ( $limit != 'default' ) {
810  ini_set( 'memory_limit', $limit );
811  }
812  }
813 
817  protected function activateProfiler() {
819 
820  $output = $this->getOption( 'profiler' );
821  if ( !$output ) {
822  return;
823  }
824 
825  if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
826  $class = $wgProfiler['class'];
828  $profiler = new $class(
829  [ 'sampling' => 1, 'output' => [ $output ] ]
830  + $wgProfiler
831  + [ 'threshold' => $wgProfileLimit ]
832  );
833  $profiler->setTemplated( true );
834  Profiler::replaceStubInstance( $profiler );
835  }
836 
837  $trxProfiler = Profiler::instance()->getTransactionProfiler();
838  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
839  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
840  }
841 
845  public function clearParamsAndArgs() {
846  $this->mOptions = [];
847  $this->mArgs = [];
848  $this->mInputLoaded = false;
849  }
850 
858  public function loadWithArgv( $argv ) {
859  $options = [];
860  $args = [];
861  $this->orderedOptions = [];
862 
863  # Parse arguments
864  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
865  if ( $arg == '--' ) {
866  # End of options, remainder should be considered arguments
867  $arg = next( $argv );
868  while ( $arg !== false ) {
869  $args[] = $arg;
870  $arg = next( $argv );
871  }
872  break;
873  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
874  # Long options
875  $option = substr( $arg, 2 );
876  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
877  $param = next( $argv );
878  if ( $param === false ) {
879  $this->error( "\nERROR: $option parameter needs a value after it\n" );
880  $this->maybeHelp( true );
881  }
882 
883  $this->setParam( $options, $option, $param );
884  } else {
885  $bits = explode( '=', $option, 2 );
886  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
887  }
888  } elseif ( $arg == '-' ) {
889  # Lonely "-", often used to indicate stdin or stdout.
890  $args[] = $arg;
891  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
892  # Short options
893  $argLength = strlen( $arg );
894  for ( $p = 1; $p < $argLength; $p++ ) {
895  $option = $arg[$p];
896  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
897  $option = $this->mShortParamsMap[$option];
898  }
899 
900  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
901  $param = next( $argv );
902  if ( $param === false ) {
903  $this->error( "\nERROR: $option parameter needs a value after it\n" );
904  $this->maybeHelp( true );
905  }
906  $this->setParam( $options, $option, $param );
907  } else {
908  $this->setParam( $options, $option, 1 );
909  }
910  }
911  } else {
912  $args[] = $arg;
913  }
914  }
915 
916  $this->mOptions = $options;
917  $this->mArgs = $args;
918  $this->loadSpecialVars();
919  $this->mInputLoaded = true;
920  }
921 
934  private function setParam( &$options, $option, $value ) {
935  $this->orderedOptions[] = [ $option, $value ];
936 
937  if ( isset( $this->mParams[$option] ) ) {
938  $multi = $this->mParams[$option]['multiOccurrence'];
939  } else {
940  $multi = false;
941  }
942  $exists = array_key_exists( $option, $options );
943  if ( $multi && $exists ) {
944  $options[$option][] = $value;
945  } elseif ( $multi ) {
946  $options[$option] = [ $value ];
947  } elseif ( !$exists ) {
948  $options[$option] = $value;
949  } else {
950  $this->error( "\nERROR: $option parameter given twice\n" );
951  $this->maybeHelp( true );
952  }
953  }
954 
964  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
965  # If we were given opts or args, set those and return early
966  if ( $self ) {
967  $this->mSelf = $self;
968  $this->mInputLoaded = true;
969  }
970  if ( $opts ) {
971  $this->mOptions = $opts;
972  $this->mInputLoaded = true;
973  }
974  if ( $args ) {
975  $this->mArgs = $args;
976  $this->mInputLoaded = true;
977  }
978 
979  # If we've already loaded input (either by user values or from $argv)
980  # skip on loading it again. The array_shift() will corrupt values if
981  # it's run again and again
982  if ( $this->mInputLoaded ) {
983  $this->loadSpecialVars();
984 
985  return;
986  }
987 
988  global $argv;
989  $this->mSelf = $argv[0];
990  $this->loadWithArgv( array_slice( $argv, 1 ) );
991  }
992 
996  public function validateParamsAndArgs() {
997  $die = false;
998  # Check to make sure we've got all the required options
999  foreach ( $this->mParams as $opt => $info ) {
1000  if ( $info['require'] && !$this->hasOption( $opt ) ) {
1001  $this->error( "Param $opt required!" );
1002  $die = true;
1003  }
1004  }
1005  # Check arg list too
1006  foreach ( $this->mArgList as $k => $info ) {
1007  if ( $info['require'] && !$this->hasArg( $k ) ) {
1008  $this->error( 'Argument <' . $info['name'] . '> required!' );
1009  $die = true;
1010  }
1011  }
1012  if ( !$this->mAllowUnregisteredOptions ) {
1013  # Check for unexpected options
1014  foreach ( $this->mOptions as $opt => $val ) {
1015  if ( !$this->supportsOption( $opt ) ) {
1016  $this->error( "Unexpected option $opt!" );
1017  $die = true;
1018  }
1019  }
1020  }
1021 
1022  $this->maybeHelp( $die );
1023  }
1024 
1028  protected function loadSpecialVars() {
1029  if ( $this->hasOption( 'dbuser' ) ) {
1030  $this->mDbUser = $this->getOption( 'dbuser' );
1031  }
1032  if ( $this->hasOption( 'dbpass' ) ) {
1033  $this->mDbPass = $this->getOption( 'dbpass' );
1034  }
1035  if ( $this->hasOption( 'quiet' ) ) {
1036  $this->mQuiet = true;
1037  }
1038  if ( $this->hasOption( 'batch-size' ) ) {
1039  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1040  }
1041  }
1042 
1047  protected function maybeHelp( $force = false ) {
1048  if ( !$force && !$this->hasOption( 'help' ) ) {
1049  return;
1050  }
1051 
1052  $screenWidth = 80; // TODO: Calculate this!
1053  $tab = " ";
1054  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1055 
1056  ksort( $this->mParams );
1057  $this->mQuiet = false;
1058 
1059  // Description ...
1060  if ( $this->mDescription ) {
1061  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1062  }
1063  $output = "\nUsage: php " . basename( $this->mSelf );
1064 
1065  // ... append parameters ...
1066  if ( $this->mParams ) {
1067  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1068  }
1069 
1070  // ... and append arguments.
1071  if ( $this->mArgList ) {
1072  $output .= ' ';
1073  foreach ( $this->mArgList as $k => $arg ) {
1074  if ( $arg['require'] ) {
1075  $output .= '<' . $arg['name'] . '>';
1076  } else {
1077  $output .= '[' . $arg['name'] . ']';
1078  }
1079  if ( $k < count( $this->mArgList ) - 1 ) {
1080  $output .= ' ';
1081  }
1082  }
1083  }
1084  $this->output( "$output\n\n" );
1085 
1086  # TODO abstract some repetitive code below
1087 
1088  // Generic parameters
1089  $this->output( "Generic maintenance parameters:\n" );
1090  foreach ( $this->mGenericParameters as $par => $info ) {
1091  if ( $info['shortName'] !== false ) {
1092  $par .= " (-{$info['shortName']})";
1093  }
1094  $this->output(
1095  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1096  "\n$tab$tab" ) . "\n"
1097  );
1098  }
1099  $this->output( "\n" );
1100 
1101  $scriptDependantParams = $this->mDependantParameters;
1102  if ( count( $scriptDependantParams ) > 0 ) {
1103  $this->output( "Script dependant parameters:\n" );
1104  // Parameters description
1105  foreach ( $scriptDependantParams as $par => $info ) {
1106  if ( $info['shortName'] !== false ) {
1107  $par .= " (-{$info['shortName']})";
1108  }
1109  $this->output(
1110  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1111  "\n$tab$tab" ) . "\n"
1112  );
1113  }
1114  $this->output( "\n" );
1115  }
1116 
1117  // Script specific parameters not defined on construction by
1118  // Maintenance::addDefaultParams()
1119  $scriptSpecificParams = array_diff_key(
1120  # all script parameters:
1121  $this->mParams,
1122  # remove the Maintenance default parameters:
1123  $this->mGenericParameters,
1124  $this->mDependantParameters
1125  );
1126  if ( count( $scriptSpecificParams ) > 0 ) {
1127  $this->output( "Script specific parameters:\n" );
1128  // Parameters description
1129  foreach ( $scriptSpecificParams as $par => $info ) {
1130  if ( $info['shortName'] !== false ) {
1131  $par .= " (-{$info['shortName']})";
1132  }
1133  $this->output(
1134  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1135  "\n$tab$tab" ) . "\n"
1136  );
1137  }
1138  $this->output( "\n" );
1139  }
1140 
1141  // Print arguments
1142  if ( count( $this->mArgList ) > 0 ) {
1143  $this->output( "Arguments:\n" );
1144  // Arguments description
1145  foreach ( $this->mArgList as $info ) {
1146  $openChar = $info['require'] ? '<' : '[';
1147  $closeChar = $info['require'] ? '>' : ']';
1148  $this->output(
1149  wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1150  $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1151  );
1152  }
1153  $this->output( "\n" );
1154  }
1155 
1156  die( 1 );
1157  }
1158 
1162  public function finalSetup() {
1166 
1167  # Turn off output buffering again, it might have been turned on in the settings files
1168  if ( ob_get_level() ) {
1169  ob_end_flush();
1170  }
1171  # Same with these
1172  $wgCommandLineMode = true;
1173 
1174  # Override $wgServer
1175  if ( $this->hasOption( 'server' ) ) {
1176  $wgServer = $this->getOption( 'server', $wgServer );
1177  }
1178 
1179  # If these were passed, use them
1180  if ( $this->mDbUser ) {
1181  $wgDBadminuser = $this->mDbUser;
1182  }
1183  if ( $this->mDbPass ) {
1184  $wgDBadminpassword = $this->mDbPass;
1185  }
1186  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1187  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1188 
1189  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1190  }
1191 
1192  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1193  $wgDBuser = $wgDBadminuser;
1194  $wgDBpassword = $wgDBadminpassword;
1195 
1196  if ( $wgDBservers ) {
1200  foreach ( $wgDBservers as $i => $server ) {
1201  $wgDBservers[$i]['user'] = $wgDBuser;
1202  $wgDBservers[$i]['password'] = $wgDBpassword;
1203  }
1204  }
1205  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1206  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1207  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1208  }
1209  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1210  }
1211 
1212  # Apply debug settings
1213  if ( $this->hasOption( 'mwdebug' ) ) {
1214  require __DIR__ . '/../includes/DevelopmentSettings.php';
1215  }
1216 
1217  // Per-script profiling; useful for debugging
1218  $this->activateProfiler();
1219 
1220  $this->afterFinalSetup();
1221 
1222  $wgShowExceptionDetails = true;
1223  $wgShowHostnames = true;
1224 
1225  Wikimedia\suppressWarnings();
1226  set_time_limit( 0 );
1227  Wikimedia\restoreWarnings();
1228 
1229  $this->adjustMemoryLimit();
1230  }
1231 
1235  protected function afterFinalSetup() {
1236  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1237  call_user_func( MW_CMDLINE_CALLBACK );
1238  }
1239  }
1240 
1245  public function globals() {
1246  if ( $this->hasOption( 'globals' ) ) {
1247  print_r( $GLOBALS );
1248  }
1249  }
1250 
1255  public function loadSettings() {
1256  global $wgCommandLineMode, $IP;
1257 
1258  if ( isset( $this->mOptions['conf'] ) ) {
1259  $settingsFile = $this->mOptions['conf'];
1260  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1261  $settingsFile = MW_CONFIG_FILE;
1262  } else {
1263  $settingsFile = "$IP/LocalSettings.php";
1264  }
1265  if ( isset( $this->mOptions['wiki'] ) ) {
1266  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1267  define( 'MW_DB', $bits[0] );
1268  define( 'MW_PREFIX', $bits[1] ?? '' );
1269  } elseif ( isset( $this->mOptions['server'] ) ) {
1270  // Provide the option for site admins to detect and configure
1271  // multiple wikis based on server names. This offers --server
1272  // as alternative to --wiki.
1273  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1274  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1275  }
1276 
1277  if ( !is_readable( $settingsFile ) ) {
1278  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1279  "must exist and be readable in the source directory.\n" .
1280  "Use --conf to specify it." );
1281  }
1282  $wgCommandLineMode = true;
1283 
1284  return $settingsFile;
1285  }
1286 
1292  public function purgeRedundantText( $delete = true ) {
1294 
1295  # Data should come off the master, wrapped in a transaction
1296  $dbw = $this->getDB( DB_MASTER );
1297  $this->beginTransaction( $dbw, __METHOD__ );
1298 
1299  if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD ) {
1300  # Get "active" text records from the revisions table
1301  $cur = [];
1302  $this->output( 'Searching for active text records in revisions table...' );
1303  $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1304  foreach ( $res as $row ) {
1305  $cur[] = $row->rev_text_id;
1306  }
1307  $this->output( "done.\n" );
1308 
1309  # Get "active" text records from the archive table
1310  $this->output( 'Searching for active text records in archive table...' );
1311  $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1312  foreach ( $res as $row ) {
1313  # old pre-MW 1.5 records can have null ar_text_id's.
1314  if ( $row->ar_text_id !== null ) {
1315  $cur[] = $row->ar_text_id;
1316  }
1317  }
1318  $this->output( "done.\n" );
1319  } else {
1320  # Get "active" text records via the content table
1321  $cur = [];
1322  $this->output( 'Searching for active text records via contents table...' );
1323  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1324  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1325  foreach ( $res as $row ) {
1326  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1327  if ( $textId ) {
1328  $cur[] = $textId;
1329  }
1330  }
1331  $this->output( "done.\n" );
1332  }
1333  $this->output( "done.\n" );
1334 
1335  # Get the IDs of all text records not in these sets
1336  $this->output( 'Searching for inactive text records...' );
1337  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1338  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1339  $old = [];
1340  foreach ( $res as $row ) {
1341  $old[] = $row->old_id;
1342  }
1343  $this->output( "done.\n" );
1344 
1345  # Inform the user of what we're going to do
1346  $count = count( $old );
1347  $this->output( "$count inactive items found.\n" );
1348 
1349  # Delete as appropriate
1350  if ( $delete && $count ) {
1351  $this->output( 'Deleting...' );
1352  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1353  $this->output( "done.\n" );
1354  }
1355 
1356  $this->commitTransaction( $dbw, __METHOD__ );
1357  }
1358 
1363  protected function getDir() {
1364  return __DIR__;
1365  }
1366 
1377  protected function getDB( $db, $groups = [], $wiki = false ) {
1378  if ( $this->mDb === null ) {
1379  return wfGetDB( $db, $groups, $wiki );
1380  }
1381  return $this->mDb;
1382  }
1383 
1389  public function setDB( IDatabase $db ) {
1390  $this->mDb = $db;
1391  }
1392 
1403  protected function beginTransaction( IDatabase $dbw, $fname ) {
1404  $dbw->begin( $fname );
1405  }
1406 
1418  protected function commitTransaction( IDatabase $dbw, $fname ) {
1419  $dbw->commit( $fname );
1420  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1421  $waitSucceeded = $lbFactory->waitForReplication(
1422  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1423  );
1424  $this->lastReplicationWait = microtime( true );
1425  return $waitSucceeded;
1426  }
1427 
1438  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1439  $dbw->rollback( $fname );
1440  }
1441 
1446  private function lockSearchindex( $db ) {
1447  $write = [ 'searchindex' ];
1448  $read = [
1449  'page',
1450  'revision',
1451  'text',
1452  'interwiki',
1453  'l10n_cache',
1454  'user',
1455  'page_restrictions'
1456  ];
1457  $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1458  }
1459 
1464  private function unlockSearchindex( $db ) {
1465  $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1466  }
1467 
1473  private function relockSearchindex( $db ) {
1474  $this->unlockSearchindex( $db );
1475  $this->lockSearchindex( $db );
1476  }
1477 
1485  public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1486  $lockTime = time();
1487 
1488  # Lock searchindex
1489  if ( $maxLockTime ) {
1490  $this->output( " --- Waiting for lock ---" );
1491  $this->lockSearchindex( $dbw );
1492  $lockTime = time();
1493  $this->output( "\n" );
1494  }
1495 
1496  # Loop through the results and do a search update
1497  foreach ( $results as $row ) {
1498  # Allow reads to be processed
1499  if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1500  $this->output( " --- Relocking ---" );
1501  $this->relockSearchindex( $dbw );
1502  $lockTime = time();
1503  $this->output( "\n" );
1504  }
1505  call_user_func( $callback, $dbw, $row );
1506  }
1507 
1508  # Unlock searchindex
1509  if ( $maxLockTime ) {
1510  $this->output( " --- Unlocking --" );
1511  $this->unlockSearchindex( $dbw );
1512  $this->output( "\n" );
1513  }
1514  }
1515 
1522  public function updateSearchIndexForPage( $dbw, $pageId ) {
1523  // Get current revision
1524  $rev = Revision::loadFromPageId( $dbw, $pageId );
1525  $title = null;
1526  if ( $rev ) {
1527  $titleObj = $rev->getTitle();
1528  $title = $titleObj->getPrefixedDBkey();
1529  $this->output( "$title..." );
1530  # Update searchindex
1531  $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1532  $u->doUpdate();
1533  $this->output( "\n" );
1534  }
1535 
1536  return $title;
1537  }
1538 
1549  protected function countDown( $seconds ) {
1550  if ( $this->isQuiet() ) {
1551  return;
1552  }
1553  for ( $i = $seconds; $i >= 0; $i-- ) {
1554  if ( $i != $seconds ) {
1555  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1556  }
1557  $this->output( $i );
1558  if ( $i ) {
1559  sleep( 1 );
1560  }
1561  }
1562  $this->output( "\n" );
1563  }
1564 
1573  public static function posix_isatty( $fd ) {
1574  if ( !function_exists( 'posix_isatty' ) ) {
1575  return !$fd;
1576  } else {
1577  return posix_isatty( $fd );
1578  }
1579  }
1580 
1586  public static function readconsole( $prompt = '> ' ) {
1587  static $isatty = null;
1588  if ( is_null( $isatty ) ) {
1589  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1590  }
1591 
1592  if ( $isatty && function_exists( 'readline' ) ) {
1593  return readline( $prompt );
1594  } else {
1595  if ( $isatty ) {
1596  $st = self::readlineEmulation( $prompt );
1597  } else {
1598  if ( feof( STDIN ) ) {
1599  $st = false;
1600  } else {
1601  $st = fgets( STDIN, 1024 );
1602  }
1603  }
1604  if ( $st === false ) {
1605  return false;
1606  }
1607  $resp = trim( $st );
1608 
1609  return $resp;
1610  }
1611  }
1612 
1618  private static function readlineEmulation( $prompt ) {
1619  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1620  if ( !wfIsWindows() && $bash ) {
1621  $retval = false;
1622  $encPrompt = Shell::escape( $prompt );
1623  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1624  $encCommand = Shell::escape( $command );
1625  $line = Shell::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1626 
1627  if ( $retval == 0 ) {
1628  return $line;
1629  } elseif ( $retval == 127 ) {
1630  // Couldn't execute bash even though we thought we saw it.
1631  // Shell probably spit out an error message, sorry :(
1632  // Fall through to fgets()...
1633  } else {
1634  // EOF/ctrl+D
1635  return false;
1636  }
1637  }
1638 
1639  // Fallback... we'll have no editing controls, EWWW
1640  if ( feof( STDIN ) ) {
1641  return false;
1642  }
1643  print $prompt;
1644 
1645  return fgets( STDIN, 1024 );
1646  }
1647 
1655  public static function getTermSize() {
1656  $default = [ 80, 50 ];
1657  if ( wfIsWindows() ) {
1658  return $default;
1659  }
1660  if ( Shell::isDisabled() ) {
1661  return $default;
1662  }
1663  // It's possible to get the screen size with VT-100 terminal escapes,
1664  // but reading the responses is not possible without setting raw mode
1665  // (unless you want to require the user to press enter), and that
1666  // requires an ioctl(), which we can't do. So we have to shell out to
1667  // something that can do the relevant syscalls. There are a few
1668  // options. Linux and Mac OS X both have "stty size" which does the
1669  // job directly.
1670  $result = Shell::command( 'stty', 'size' )
1671  ->execute();
1672  if ( $result->getExitCode() !== 0 ) {
1673  return $default;
1674  }
1675  if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1676  return $default;
1677  }
1678  return [ intval( $m[2] ), intval( $m[1] ) ];
1679  }
1680 
1685  public static function requireTestsAutoloader() {
1686  require_once __DIR__ . '/../tests/common/TestsAutoLoader.php';
1687  }
1688 }
1689 
1694  protected $mSelf = "FakeMaintenanceScript";
1695 
1696  public function execute() {
1697  }
1698 }
1699 
1704 abstract class LoggedUpdateMaintenance extends Maintenance {
1705  public function __construct() {
1706  parent::__construct();
1707  $this->addOption( 'force', 'Run the update even if it was completed already' );
1708  $this->setBatchSize( 200 );
1709  }
1710 
1711  public function execute() {
1712  $db = $this->getDB( DB_MASTER );
1713  $key = $this->getUpdateKey();
1714 
1715  if ( !$this->hasOption( 'force' )
1716  && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
1717  ) {
1718  $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1719 
1720  return true;
1721  }
1722 
1723  if ( !$this->doDBUpdates() ) {
1724  return false;
1725  }
1726 
1727  $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, 'IGNORE' );
1728 
1729  return true;
1730  }
1731 
1736  protected function updateSkippedMessage() {
1737  $key = $this->getUpdateKey();
1738 
1739  return "Update '{$key}' already logged as completed.";
1740  }
1741 
1747  abstract protected function doDBUpdates();
1748 
1753  abstract protected function getUpdateKey();
1754 }
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
const STDIN_ALL
Definition: Maintenance.php:89
getArg( $argId=0, $default=null)
Get an argument.
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:84
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:36
maybeHelp( $force=false)
Maybe show the help.
checkRequiredExtensions()
Verify that the required extensions are installed.
if(is_array( $mode)) switch( $mode) $input
$wgDBDefaultGroup
Default group to use when getting database connections.
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
error( $err, $die=0)
Throw an error to the user.
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
$IP
Definition: WebStart.php:41
An interface for generating database load balancers.
Definition: LBFactory.php:39
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables)...
$wgDBadminpassword
Separate password for maintenance tasks.
lockSearchindex( $db)
Lock the search index.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getOption( $name, $default=null)
Get an option, or return the default.
getDir()
Get the maintenance directory.
array $orderedOptions
Used to read the options in the order they were passed.
$command
Definition: cdb.php:65
static instance()
Singleton.
Definition: Profiler.php:62
$wgDBpassword
Database user&#39;s password.
wfHostname()
Fetch server name for use in error reporting etc.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
getName()
Get the script&#39;s name.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
addDefaultParams()
Add the default parameters to the scripts.
finalSetup()
Handle some last-minute setup here.
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
afterFinalSetup()
Execute a callback function at the end of initialisation.
$value
static readconsole( $prompt='> ')
Prompt the console for input.
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
setConfig(Config $config)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
updateSearchIndex( $maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
static loadFromPageId( $db, $pageid, $id=0)
Load either the current, or a specified, revision that&#39;s attached to a given page.
Definition: Revision.php:260
setBatchSize( $s=0)
Set the batch size.
$wgDBuser
Database username.
loadSpecialVars()
Handle the special variables that are global to all scripts.
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
wfEntryPointCheck( $format='text', $scriptPath='/')
Check PHP version and that external dependencies are installed, and display an informative error if e...
updateSearchIndexForPage( $dbw, $pageId)
Update the searchindex table for a given pageid.
hasOption( $name)
Checks to see if a particular option exists.
relockSearchindex( $db)
Unlock and lock again Since the lock is low-priority, queued reads will be able to complete...
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
wfIsWindows()
Check if the operating system is Windows.
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
const DB_MASTER
Definition: defines.php:26
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
array $requiredExtensions
rollback( $fname=__METHOD__, $flush='')
Rollback a transaction previously started using begin().
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
$maintClass
Definition: Maintenance.php:43
if( $line===false) $args
Definition: cdb.php:64
cleanupChanneled()
Clean up channeled output.
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
static replaceStubInstance(Profiler $profiler)
Replace the current profiler with $profiler if no non-stub profiler is set.
Definition: Profiler.php:98
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:780
supportsOption( $name)
Checks to see if a particular option in supported.
Fake maintenance wrapper, mostly used for the web installer/updater.
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
hasArg( $argId=0)
Does a given argument exist?
$wgTrxProfilerLimits
Performance expectations for DB usage.
Interface for configuration instances.
Definition: Config.php:28
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2217
$mAllowUnregisteredOptions
$self
$res
Definition: database.txt:21
float $lastReplicationWait
UNIX timestamp.
addDescription( $text)
Set the description text.
const DB_ADMIN
Definition: Maintenance.php:86
setup()
Do some sanity checking and basic setup.
setDB(IDatabase $db)
Sets database object to be returned by getDB().
clearParamsAndArgs()
Clear all params and arguments.
deleteOption( $name)
Remove an option.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
addArg( $arg, $description, $required=true)
Add some args that are needed.
globals()
Potentially debug globals.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
adjustMemoryLimit()
Adjusts PHP&#39;s memory limit to better suit our needs, if needed.
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
$GLOBALS['IP']
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
output( $out, $channel=null)
Throw some output to the user.
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1766
resource $fileHandle
Used when creating separate schema files.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
unlockSearchindex( $db)
Unlock the tables.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
static findInDefaultPaths( $names, $versionInfo=false)
Same as locateExecutable(), but checks in getPossibleBinPaths() by default.
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class...
static tryOpportunisticExecute( $mode='run')
Run all deferred updates immediately if there are no DB writes active.
const DB_STD
Definition: Maintenance.php:85
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static getTermSize()
Get the terminal size as a two-element array where the first element is the width (number of columns)...
static readlineEmulation( $prompt)
Emulate readline()
static posix_isatty( $fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
Class for scripts that perform database maintenance and want to log the update in updatelog so we can...
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
$wgDBadminuser
Separate username for maintenance tasks.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
$wgProfileLimit
Only record profiling info for pages that took longer than this.
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:933
int $mBatchSize
Batch size.
getBatchSize()
Returns batch size.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$line
Definition: cdb.php:59
global $wgCommandLineMode
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
$f
Definition: router.php:79
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
updateSkippedMessage()
Message to show that the update was done already and was just skipped.
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getStdin( $len=null)
Return input from stdin.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
$wgServer
URL of the server.
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-master wiki farm, set the class here to somethi...
loadSettings()
Generic setup for most installs.
const SCHEMA_COMPAT_READ_OLD
Definition: Defines.php:285
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
purgeRedundantText( $delete=true)
Support function for cleaning up redundant text records.
$wgProfiler
Profiler configuration.
validateParamsAndArgs()
Run some validation checks on the params, etc.
Config $config
Accessible via getConfig()
IMaintainableDatabase $mDb
Used by getDB() / setDB()
loadParamsAndArgs( $self=null, $opts=null, $args=null)
Process command line arguments $mOptions becomes an array with keys set to the option names $mArgs be...
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
public function execute()
Definition: maintenance.txt:45
__construct()
Default constructor.
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
setAllowUnregisteredOptions( $allow)
Sets whether to allow unregistered options, which are options passed to a script that do not match an...
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.