MediaWiki  master
Maintenance.php
Go to the documentation of this file.
1 <?php
31 
55 abstract class Maintenance {
60  public const DB_NONE = 0;
61  public const DB_STD = 1;
62  public const DB_ADMIN = 2;
63 
64  // Const for getStdin()
65  public const STDIN_ALL = 'all';
66 
72  protected $mParams = [];
73 
75  protected $mShortParamsMap = [];
76 
78  protected $mArgList = [];
79 
81  protected $mOptions = [];
82 
84  protected $mArgs = [];
85 
87  protected $mAllowUnregisteredOptions = false;
88 
90  protected $mSelf;
91 
93  protected $mQuiet = false;
94  protected $mDbUser, $mDbPass;
95 
97  protected $mDescription = '';
98 
100  protected $mInputLoaded = false;
101 
108  protected $mBatchSize = null;
109 
115  private $mGenericParameters = [];
121  private $mDependantParameters = [];
122 
127  private $mDb = null;
128 
130  private $lastReplicationWait = 0.0;
131 
136  public $fileHandle;
137 
139  private $hookContainer;
140 
142  private $hookRunner;
143 
149  private $config;
150 
155  private $requiredExtensions = [];
156 
168  public $orderedOptions = [];
169 
176  public function __construct() {
177  $this->addDefaultParams();
178  register_shutdown_function( [ $this, 'outputChanneled' ], false );
179  }
180 
188  public static function shouldExecute() {
189  global $wgCommandLineMode;
190 
191  if ( !function_exists( 'debug_backtrace' ) ) {
192  // If someone has a better idea...
193  return $wgCommandLineMode;
194  }
195 
196  $bt = debug_backtrace();
197  $count = count( $bt );
198  if ( $count < 2 ) {
199  return false; // sanity
200  }
201  if ( $bt[0]['class'] !== self::class || $bt[0]['function'] !== 'shouldExecute' ) {
202  return false; // last call should be to this function
203  }
204  $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
205  for ( $i = 1; $i < $count; $i++ ) {
206  if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
207  return false; // previous calls should all be "requires"
208  }
209  }
210 
211  return true;
212  }
213 
222  abstract public function execute();
223 
230  protected function supportsOption( $name ) {
231  return isset( $this->mParams[$name] );
232  }
233 
245  protected function addOption( $name, $description, $required = false,
246  $withArg = false, $shortName = false, $multiOccurrence = false
247  ) {
248  $this->mParams[$name] = [
249  'desc' => $description,
250  'require' => $required,
251  'withArg' => $withArg,
252  'shortName' => $shortName,
253  'multiOccurrence' => $multiOccurrence
254  ];
255 
256  if ( $shortName !== false ) {
257  $this->mShortParamsMap[$shortName] = $name;
258  }
259  }
260 
266  protected function hasOption( $name ) {
267  return isset( $this->mOptions[$name] );
268  }
269 
281  protected function getOption( $name, $default = null ) {
282  if ( $this->hasOption( $name ) ) {
283  return $this->mOptions[$name];
284  } else {
285  // Set it so we don't have to provide the default again
286  $this->mOptions[$name] = $default;
287 
288  return $this->mOptions[$name];
289  }
290  }
291 
298  protected function addArg( $arg, $description, $required = true ) {
299  $this->mArgList[] = [
300  'name' => $arg,
301  'desc' => $description,
302  'require' => $required
303  ];
304  }
305 
310  protected function deleteOption( $name ) {
311  unset( $this->mParams[$name] );
312  }
313 
319  protected function setAllowUnregisteredOptions( $allow ) {
320  $this->mAllowUnregisteredOptions = $allow;
321  }
322 
327  protected function addDescription( $text ) {
328  $this->mDescription = $text;
329  }
330 
336  protected function hasArg( $argId = 0 ) {
337  if ( func_num_args() === 0 ) {
338  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
339  }
340 
341  return isset( $this->mArgs[$argId] );
342  }
343 
351  protected function getArg( $argId = 0, $default = null ) {
352  if ( func_num_args() === 0 ) {
353  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
354  }
355 
356  return $this->mArgs[$argId] ?? $default;
357  }
358 
366  protected function getBatchSize() {
367  return $this->mBatchSize;
368  }
369 
373  protected function setBatchSize( $s = 0 ) {
374  $this->mBatchSize = $s;
375 
376  // If we support $mBatchSize, show the option.
377  // Used to be in addDefaultParams, but in order for that to
378  // work, subclasses would have to call this function in the constructor
379  // before they called parent::__construct which is just weird
380  // (and really wasn't done).
381  if ( $this->mBatchSize ) {
382  $this->addOption( 'batch-size', 'Run this many operations ' .
383  'per batch, default: ' . $this->mBatchSize, false, true );
384  if ( isset( $this->mParams['batch-size'] ) ) {
385  // This seems a little ugly...
386  $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
387  }
388  }
389  }
390 
395  public function getName() {
396  return $this->mSelf;
397  }
398 
405  protected function getStdin( $len = null ) {
406  if ( $len == self::STDIN_ALL ) {
407  return file_get_contents( 'php://stdin' );
408  }
409  $f = fopen( 'php://stdin', 'rt' );
410  if ( !$len ) {
411  return $f;
412  }
413  $input = fgets( $f, $len );
414  fclose( $f );
415 
416  return rtrim( $input );
417  }
418 
422  public function isQuiet() {
423  return $this->mQuiet;
424  }
425 
433  protected function output( $out, $channel = null ) {
434  // This is sometimes called very early, before Setup.php is included.
435  if ( class_exists( MediaWikiServices::class ) ) {
436  // Try to periodically flush buffered metrics to avoid OOMs
437  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
438  if ( $stats->getDataCount() > 1000 ) {
439  MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
440  }
441  }
442 
443  if ( $this->mQuiet ) {
444  return;
445  }
446  if ( $channel === null ) {
447  $this->cleanupChanneled();
448  print $out;
449  } else {
450  $out = preg_replace( '/\n\z/', '', $out );
451  $this->outputChanneled( $out, $channel );
452  }
453  }
454 
462  protected function error( $err, $die = 0 ) {
463  if ( intval( $die ) !== 0 ) {
464  wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
465  $this->fatalError( $err, intval( $die ) );
466  }
467  $this->outputChanneled( false );
468  if (
469  ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
470  !defined( 'MW_PHPUNIT_TEST' )
471  ) {
472  fwrite( STDERR, $err . "\n" );
473  } else {
474  print $err;
475  }
476  }
477 
486  protected function fatalError( $msg, $exitCode = 1 ) {
487  $this->error( $msg );
488  exit( $exitCode );
489  }
490 
491  private $atLineStart = true;
492  private $lastChannel = null;
493 
497  public function cleanupChanneled() {
498  if ( !$this->atLineStart ) {
499  print "\n";
500  $this->atLineStart = true;
501  }
502  }
503 
512  public function outputChanneled( $msg, $channel = null ) {
513  if ( $msg === false ) {
514  $this->cleanupChanneled();
515 
516  return;
517  }
518 
519  // End the current line if necessary
520  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
521  print "\n";
522  }
523 
524  print $msg;
525 
526  $this->atLineStart = false;
527  if ( $channel === null ) {
528  // For unchanneled messages, output trailing newline immediately
529  print "\n";
530  $this->atLineStart = true;
531  }
532  $this->lastChannel = $channel;
533  }
534 
546  public function getDbType() {
547  return self::DB_STD;
548  }
549 
553  protected function addDefaultParams() {
554  # Generic (non script dependant) options:
555 
556  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
557  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
558  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
559  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
560  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
561  $this->addOption(
562  'memory-limit',
563  'Set a specific memory limit for the script, '
564  . '"max" for no limit or "default" to avoid changing it',
565  false,
566  true
567  );
568  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
569  "http://en.wikipedia.org. This is sometimes necessary because " .
570  "server name detection may fail in command line scripts.", false, true );
571  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
572 
573  # Save generic options to display them separately in help
574  $this->mGenericParameters = $this->mParams;
575 
576  # Script dependant options:
577 
578  // If we support a DB, show the options
579  if ( $this->getDbType() > 0 ) {
580  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
581  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
582  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
583  }
584 
585  # Save additional script dependant options to display
586  # ┬áthem separately in help
587  $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
588  }
589 
595  public function getConfig() {
596  if ( $this->config === null ) {
597  $this->config = MediaWikiServices::getInstance()->getMainConfig();
598  }
599 
600  return $this->config;
601  }
602 
607  public function setConfig( Config $config ) {
608  $this->config = $config;
609  }
610 
620  protected function requireExtension( $name ) {
621  $this->requiredExtensions[] = $name;
622  }
623 
629  public function checkRequiredExtensions() {
630  $registry = ExtensionRegistry::getInstance();
631  $missing = [];
632  foreach ( $this->requiredExtensions as $name ) {
633  if ( !$registry->isLoaded( $name ) ) {
634  $missing[] = $name;
635  }
636  }
637 
638  if ( $missing ) {
639  if ( count( $missing ) === 1 ) {
640  $msg = 'The "' . $missing[ 0 ] . '" extension must be installed for this script to run. '
641  . 'Please enable it and then try again.';
642  } else {
643  $msg = 'The following extensions must be installed for this script to run: "'
644  . implode( '", "', $missing ) . '". Please enable them and then try again.';
645  }
646  $this->fatalError( $msg );
647  }
648  }
649 
654  public function setAgentAndTriggers() {
655  if ( function_exists( 'posix_getpwuid' ) ) {
656  $agent = posix_getpwuid( posix_geteuid() )['name'];
657  } else {
658  $agent = 'sysadmin';
659  }
660  $agent .= '@' . wfHostname();
661 
662  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
663  // Add a comment for easy SHOW PROCESSLIST interpretation
664  $lbFactory->setAgentName(
665  mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
666  );
667  self::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
668  }
669 
675  public static function setLBFactoryTriggers( LBFactory $LBFactory, Config $config ) {
676  $services = MediaWikiServices::getInstance();
677  $stats = $services->getStatsdDataFactory();
678  // Hook into period lag checks which often happen in long-running scripts
679  $lbFactory = $services->getDBLoadBalancerFactory();
680  $lbFactory->setWaitForReplicationListener(
681  __METHOD__,
682  function () use ( $stats, $config ) {
683  // Check config in case of JobRunner and unit tests
684  if ( $config->get( 'CommandLineMode' ) ) {
685  DeferredUpdates::tryOpportunisticExecute( 'run' );
686  }
687  // Try to periodically flush buffered metrics to avoid OOMs
689  }
690  );
691  // Check for other windows to run them. A script may read or do a few writes
692  // to the master but mostly be writing to something else, like a file store.
693  $lbFactory->getMainLB()->setTransactionListener(
694  __METHOD__,
695  function ( $trigger ) use ( $stats, $config ) {
696  // Check config in case of JobRunner and unit tests
697  if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
698  DeferredUpdates::tryOpportunisticExecute( 'run' );
699  }
700  // Try to periodically flush buffered metrics to avoid OOMs
702  }
703  );
704  }
705 
713  public function runChild( $maintClass, $classFile = null ) {
714  // Make sure the class is loaded first
715  if ( !class_exists( $maintClass ) ) {
716  if ( $classFile ) {
717  require_once $classFile;
718  }
719  if ( !class_exists( $maintClass ) ) {
720  $this->error( "Cannot spawn child: $maintClass" );
721  }
722  }
723 
727  $child = new $maintClass();
728  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
729  if ( $this->mDb !== null ) {
730  $child->setDB( $this->mDb );
731  }
732 
733  return $child;
734  }
735 
739  public function setup() {
740  global $IP, $wgCommandLineMode;
741 
742  # Abort if called from a web server
743  # wfIsCLI() is not available yet
744  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
745  $this->fatalError( 'This script must be run from the command line' );
746  }
747 
748  if ( $IP === null ) {
749  $this->fatalError( "\$IP not set, aborting!\n" .
750  '(Did you forget to call parent::__construct() in your maintenance script?)' );
751  }
752 
753  # Make sure we can handle script parameters
754  if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
755  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
756  }
757 
758  // Send PHP warnings and errors to stderr instead of stdout.
759  // This aids in diagnosing problems, while keeping messages
760  // out of redirected output.
761  if ( ini_get( 'display_errors' ) ) {
762  ini_set( 'display_errors', 'stderr' );
763  }
764 
765  $this->loadParamsAndArgs();
766 
767  # Set the memory limit
768  # Note we need to set it again later in cache LocalSettings changed it
769  $this->adjustMemoryLimit();
770 
771  # Set max execution time to 0 (no limit). PHP.net says that
772  # "When running PHP from the command line the default setting is 0."
773  # But sometimes this doesn't seem to be the case.
774  ini_set( 'max_execution_time', 0 );
775 
776  $wgCommandLineMode = true;
777 
778  # Turn off output buffering if it's on
779  while ( ob_get_level() > 0 ) {
780  ob_end_flush();
781  }
782  }
783 
794  public function memoryLimit() {
795  $limit = $this->getOption( 'memory-limit', 'max' );
796  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
797  return $limit;
798  }
799 
803  protected function adjustMemoryLimit() {
804  $limit = $this->memoryLimit();
805  if ( $limit == 'max' ) {
806  $limit = -1; // no memory limit
807  }
808  if ( $limit != 'default' ) {
809  ini_set( 'memory_limit', $limit );
810  }
811  }
812 
816  protected function activateProfiler() {
818 
819  $output = $this->getOption( 'profiler' );
820  if ( !$output ) {
821  return;
822  }
823 
824  if ( isset( $wgProfiler['class'] ) ) {
825  $class = $wgProfiler['class'];
827  $profiler = new $class(
828  [ 'sampling' => 1, 'output' => [ $output ] ]
829  + $wgProfiler
830  + [ 'threshold' => 0.0 ]
831  );
832  $profiler->setAllowOutput();
833  Profiler::replaceStubInstance( $profiler );
834  }
835 
836  $trxProfiler = Profiler::instance()->getTransactionProfiler();
837  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
838  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
839  }
840 
844  public function clearParamsAndArgs() {
845  $this->mOptions = [];
846  $this->mArgs = [];
847  $this->mInputLoaded = false;
848  }
849 
857  public function loadWithArgv( $argv ) {
858  $options = [];
859  $args = [];
860  $this->orderedOptions = [];
861 
862  # Parse arguments
863  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
864  if ( $arg == '--' ) {
865  # End of options, remainder should be considered arguments
866  $arg = next( $argv );
867  while ( $arg !== false ) {
868  $args[] = $arg;
869  $arg = next( $argv );
870  }
871  break;
872  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
873  # Long options
874  $option = substr( $arg, 2 );
875  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
876  $param = next( $argv );
877  if ( $param === false ) {
878  $this->error( "\nERROR: $option parameter needs a value after it\n" );
879  $this->maybeHelp( true );
880  }
881 
882  $this->setParam( $options, $option, $param );
883  } else {
884  $bits = explode( '=', $option, 2 );
885  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
886  }
887  } elseif ( $arg == '-' ) {
888  # Lonely "-", often used to indicate stdin or stdout.
889  $args[] = $arg;
890  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
891  # Short options
892  $argLength = strlen( $arg );
893  for ( $p = 1; $p < $argLength; $p++ ) {
894  $option = $arg[$p];
895  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
896  $option = $this->mShortParamsMap[$option];
897  }
898 
899  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
900  $param = next( $argv );
901  if ( $param === false ) {
902  $this->error( "\nERROR: $option parameter needs a value after it\n" );
903  $this->maybeHelp( true );
904  }
905  $this->setParam( $options, $option, $param );
906  } else {
907  $this->setParam( $options, $option, 1 );
908  }
909  }
910  } else {
911  $args[] = $arg;
912  }
913  }
914 
915  $this->mOptions = $options;
916  $this->mArgs = $args;
917  $this->loadSpecialVars();
918  $this->mInputLoaded = true;
919  }
920 
933  private function setParam( &$options, $option, $value ) {
934  $this->orderedOptions[] = [ $option, $value ];
935 
936  if ( isset( $this->mParams[$option] ) ) {
937  $multi = $this->mParams[$option]['multiOccurrence'];
938  } else {
939  $multi = false;
940  }
941  $exists = array_key_exists( $option, $options );
942  if ( $multi && $exists ) {
943  $options[$option][] = $value;
944  } elseif ( $multi ) {
945  $options[$option] = [ $value ];
946  } elseif ( !$exists ) {
947  $options[$option] = $value;
948  } else {
949  $this->error( "\nERROR: $option parameter given twice\n" );
950  $this->maybeHelp( true );
951  }
952  }
953 
963  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
964  # If we were given opts or args, set those and return early
965  if ( $self ) {
966  $this->mSelf = $self;
967  $this->mInputLoaded = true;
968  }
969  if ( $opts ) {
970  $this->mOptions = $opts;
971  $this->mInputLoaded = true;
972  }
973  if ( $args ) {
974  $this->mArgs = $args;
975  $this->mInputLoaded = true;
976  }
977 
978  # If we've already loaded input (either by user values or from $argv)
979  # skip on loading it again. The array_shift() will corrupt values if
980  # it's run again and again
981  if ( $this->mInputLoaded ) {
982  $this->loadSpecialVars();
983 
984  return;
985  }
986 
987  global $argv;
988  $this->mSelf = $argv[0];
989  $this->loadWithArgv( array_slice( $argv, 1 ) );
990  }
991 
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 
1029  protected function loadSpecialVars() {
1030  if ( $this->hasOption( 'dbuser' ) ) {
1031  $this->mDbUser = $this->getOption( 'dbuser' );
1032  }
1033  if ( $this->hasOption( 'dbpass' ) ) {
1034  $this->mDbPass = $this->getOption( 'dbpass' );
1035  }
1036  if ( $this->hasOption( 'quiet' ) ) {
1037  $this->mQuiet = true;
1038  }
1039  if ( $this->hasOption( 'batch-size' ) ) {
1040  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1041  }
1042  }
1043 
1049  protected function maybeHelp( $force = false ) {
1050  if ( !$force && !$this->hasOption( 'help' ) ) {
1051  return;
1052  }
1053  $this->showHelp();
1054  die( 1 );
1055  }
1056 
1060  protected function showHelp() {
1061  $screenWidth = 80; // TODO: Calculate this!
1062  $tab = " ";
1063  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1064 
1065  ksort( $this->mParams );
1066  $this->mQuiet = false;
1067 
1068  // Description ...
1069  if ( $this->mDescription ) {
1070  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1071  }
1072  $output = "\nUsage: php " . basename( $this->mSelf );
1073 
1074  // ... append parameters ...
1075  if ( $this->mParams ) {
1076  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1077  }
1078 
1079  // ... and append arguments.
1080  if ( $this->mArgList ) {
1081  $output .= ' ';
1082  foreach ( $this->mArgList as $k => $arg ) {
1083  if ( $arg['require'] ) {
1084  $output .= '<' . $arg['name'] . '>';
1085  } else {
1086  $output .= '[' . $arg['name'] . ']';
1087  }
1088  if ( $k < count( $this->mArgList ) - 1 ) {
1089  $output .= ' ';
1090  }
1091  }
1092  }
1093  $this->output( "$output\n\n" );
1094 
1095  # TODO abstract some repetitive code below
1096 
1097  // Generic parameters
1098  $this->output( "Generic maintenance parameters:\n" );
1099  foreach ( $this->mGenericParameters as $par => $info ) {
1100  if ( $info['shortName'] !== false ) {
1101  $par .= " (-{$info['shortName']})";
1102  }
1103  $this->output(
1104  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1105  "\n$tab$tab" ) . "\n"
1106  );
1107  }
1108  $this->output( "\n" );
1109 
1110  $scriptDependantParams = $this->mDependantParameters;
1111  if ( count( $scriptDependantParams ) > 0 ) {
1112  $this->output( "Script dependant parameters:\n" );
1113  // Parameters description
1114  foreach ( $scriptDependantParams as $par => $info ) {
1115  if ( $info['shortName'] !== false ) {
1116  $par .= " (-{$info['shortName']})";
1117  }
1118  $this->output(
1119  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1120  "\n$tab$tab" ) . "\n"
1121  );
1122  }
1123  $this->output( "\n" );
1124  }
1125 
1126  // Script specific parameters not defined on construction by
1127  // Maintenance::addDefaultParams()
1128  $scriptSpecificParams = array_diff_key(
1129  # all script parameters:
1130  $this->mParams,
1131  # remove the Maintenance default parameters:
1132  $this->mGenericParameters,
1133  $this->mDependantParameters
1134  );
1135  '@phan-var array[] $scriptSpecificParams';
1136  if ( count( $scriptSpecificParams ) > 0 ) {
1137  $this->output( "Script specific parameters:\n" );
1138  // Parameters description
1139  foreach ( $scriptSpecificParams as $par => $info ) {
1140  if ( $info['shortName'] !== false ) {
1141  $par .= " (-{$info['shortName']})";
1142  }
1143  $this->output(
1144  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1145  "\n$tab$tab" ) . "\n"
1146  );
1147  }
1148  $this->output( "\n" );
1149  }
1150 
1151  // Print arguments
1152  if ( count( $this->mArgList ) > 0 ) {
1153  $this->output( "Arguments:\n" );
1154  // Arguments description
1155  foreach ( $this->mArgList as $info ) {
1156  $openChar = $info['require'] ? '<' : '[';
1157  $closeChar = $info['require'] ? '>' : ']';
1158  $this->output(
1159  wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1160  $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1161  );
1162  }
1163  $this->output( "\n" );
1164  }
1165  }
1166 
1171  public function finalSetup() {
1175 
1176  # Turn off output buffering again, it might have been turned on in the settings files
1177  if ( ob_get_level() ) {
1178  ob_end_flush();
1179  }
1180  # Same with these
1181  $wgCommandLineMode = true;
1182 
1183  # Override $wgServer
1184  if ( $this->hasOption( 'server' ) ) {
1185  $wgServer = $this->getOption( 'server', $wgServer );
1186  }
1187 
1188  # If these were passed, use them
1189  if ( $this->mDbUser ) {
1191  }
1192  if ( $this->mDbPass ) {
1194  }
1195  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1196  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1197 
1198  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1199  if ( $service ) {
1200  $service->destroy();
1201  }
1202  }
1203 
1204  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1207 
1208  if ( $wgDBservers ) {
1212  foreach ( $wgDBservers as $i => $server ) {
1213  $wgDBservers[$i]['user'] = $wgDBuser;
1214  $wgDBservers[$i]['password'] = $wgDBpassword;
1215  }
1216  }
1217  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1218  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1219  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1220  }
1221  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1222  if ( $service ) {
1223  $service->destroy();
1224  }
1225  }
1226 
1227  // Per-script profiling; useful for debugging
1228  $this->activateProfiler();
1229 
1230  $this->afterFinalSetup();
1231 
1232  $wgShowExceptionDetails = true;
1233  $wgShowHostnames = true;
1234 
1235  Wikimedia\suppressWarnings();
1236  set_time_limit( 0 );
1237  Wikimedia\restoreWarnings();
1238 
1239  $this->adjustMemoryLimit();
1240  }
1241 
1246  protected function afterFinalSetup() {
1247  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1248  // @phan-suppress-next-line PhanUndeclaredConstant
1249  call_user_func( MW_CMDLINE_CALLBACK );
1250  }
1251  }
1252 
1257  public function globals() {
1258  if ( $this->hasOption( 'globals' ) ) {
1259  print_r( $GLOBALS );
1260  }
1261  }
1262 
1267  public function loadSettings() {
1268  global $wgCommandLineMode, $IP;
1269 
1270  if ( isset( $this->mOptions['conf'] ) ) {
1271  $settingsFile = $this->mOptions['conf'];
1272  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1273  $settingsFile = MW_CONFIG_FILE;
1274  } else {
1275  $settingsFile = "$IP/LocalSettings.php";
1276  }
1277  if ( isset( $this->mOptions['wiki'] ) ) {
1278  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1279  define( 'MW_DB', $bits[0] );
1280  define( 'MW_PREFIX', $bits[1] ?? '' );
1281  } elseif ( isset( $this->mOptions['server'] ) ) {
1282  // Provide the option for site admins to detect and configure
1283  // multiple wikis based on server names. This offers --server
1284  // as alternative to --wiki.
1285  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1286  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1287  }
1288 
1289  if ( !is_readable( $settingsFile ) ) {
1290  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1291  "must exist and be readable in the source directory.\n" .
1292  "Use --conf to specify it." );
1293  }
1294  $wgCommandLineMode = true;
1295 
1296  return $settingsFile;
1297  }
1298 
1304  public function purgeRedundantText( $delete = true ) {
1305  # Data should come off the master, wrapped in a transaction
1306  $dbw = $this->getDB( DB_MASTER );
1307  $this->beginTransaction( $dbw, __METHOD__ );
1308 
1309  # Get "active" text records via the content table
1310  $cur = [];
1311  $this->output( 'Searching for active text records via contents table...' );
1312  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1313  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1314  foreach ( $res as $row ) {
1315  // @phan-suppress-next-line PhanUndeclaredMethod
1316  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1317  if ( $textId ) {
1318  $cur[] = $textId;
1319  }
1320  }
1321  $this->output( "done.\n" );
1322 
1323  # Get the IDs of all text records not in these sets
1324  $this->output( 'Searching for inactive text records...' );
1325  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1326  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1327  $old = [];
1328  foreach ( $res as $row ) {
1329  $old[] = $row->old_id;
1330  }
1331  $this->output( "done.\n" );
1332 
1333  # Inform the user of what we're going to do
1334  $count = count( $old );
1335  $this->output( "$count inactive items found.\n" );
1336 
1337  # Delete as appropriate
1338  if ( $delete && $count ) {
1339  $this->output( 'Deleting...' );
1340  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1341  $this->output( "done.\n" );
1342  }
1343 
1344  $this->commitTransaction( $dbw, __METHOD__ );
1345  }
1346 
1351  protected function getDir() {
1352  return __DIR__ . '/../';
1353  }
1354 
1369  protected function getDB( $db, $groups = [], $dbDomain = false ) {
1370  if ( $this->mDb === null ) {
1371  return MediaWikiServices::getInstance()
1372  ->getDBLoadBalancerFactory()
1373  ->getMainLB( $dbDomain )
1374  ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1375  }
1376 
1377  return $this->mDb;
1378  }
1379 
1386  public function setDB( IMaintainableDatabase $db ) {
1387  $this->mDb = $db;
1388  }
1389 
1400  protected function beginTransaction( IDatabase $dbw, $fname ) {
1401  $dbw->begin( $fname );
1402  }
1403 
1415  protected function commitTransaction( IDatabase $dbw, $fname ) {
1416  $dbw->commit( $fname );
1417  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1418  $waitSucceeded = $lbFactory->waitForReplication(
1419  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1420  );
1421  $this->lastReplicationWait = microtime( true );
1422  return $waitSucceeded;
1423  }
1424 
1435  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1436  $dbw->rollback( $fname );
1437  }
1438 
1443  private function lockSearchindex( $db ) {
1444  $write = [ 'searchindex' ];
1445  $read = [
1446  'page',
1447  'revision',
1448  'text',
1449  'interwiki',
1450  'l10n_cache',
1451  'user',
1452  'page_restrictions'
1453  ];
1454  $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1455  }
1456 
1461  private function unlockSearchindex( $db ) {
1462  $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1463  }
1464 
1470  private function relockSearchindex( $db ) {
1471  $this->unlockSearchindex( $db );
1472  $this->lockSearchindex( $db );
1473  }
1474 
1482  public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1483  $lockTime = time();
1484 
1485  # Lock searchindex
1486  if ( $maxLockTime ) {
1487  $this->output( " --- Waiting for lock ---" );
1488  $this->lockSearchindex( $dbw );
1489  $lockTime = time();
1490  $this->output( "\n" );
1491  }
1492 
1493  # Loop through the results and do a search update
1494  foreach ( $results as $row ) {
1495  # Allow reads to be processed
1496  if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1497  $this->output( " --- Relocking ---" );
1498  $this->relockSearchindex( $dbw );
1499  $lockTime = time();
1500  $this->output( "\n" );
1501  }
1502  call_user_func( $callback, $row );
1503  }
1504 
1505  # Unlock searchindex
1506  if ( $maxLockTime ) {
1507  $this->output( " --- Unlocking --" );
1508  $this->unlockSearchindex( $dbw );
1509  $this->output( "\n" );
1510  }
1511  }
1512 
1518  public function updateSearchIndexForPage( int $pageId ) {
1519  // Get current revision
1520  $rev = MediaWikiServices::getInstance()
1521  ->getRevisionLookup()
1522  ->getRevisionByPageId( $pageId, 0, IDBAccessObject::READ_LATEST );
1523  $title = null;
1524  if ( $rev ) {
1525  $titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
1526  $title = $titleObj->getPrefixedDBkey();
1527  $this->output( "$title..." );
1528  # Update searchindex
1529  $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent( SlotRecord::MAIN ) );
1530  $u->doUpdate();
1531  $this->output( "\n" );
1532  }
1533 
1534  return $title;
1535  }
1536 
1547  protected function countDown( $seconds ) {
1548  if ( $this->isQuiet() ) {
1549  return;
1550  }
1551  for ( $i = $seconds; $i >= 0; $i-- ) {
1552  if ( $i != $seconds ) {
1553  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1554  }
1555  $this->output( $i );
1556  if ( $i ) {
1557  sleep( 1 );
1558  }
1559  }
1560  $this->output( "\n" );
1561  }
1562 
1571  public static function posix_isatty( $fd ) {
1572  if ( !function_exists( 'posix_isatty' ) ) {
1573  return !$fd;
1574  } else {
1575  return posix_isatty( $fd );
1576  }
1577  }
1578 
1584  public static function readconsole( $prompt = '> ' ) {
1585  static $isatty = null;
1586  if ( $isatty === null ) {
1587  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1588  }
1589 
1590  if ( $isatty && function_exists( 'readline' ) ) {
1591  return readline( $prompt );
1592  } else {
1593  if ( $isatty ) {
1594  $st = self::readlineEmulation( $prompt );
1595  } else {
1596  if ( feof( STDIN ) ) {
1597  $st = false;
1598  } else {
1599  $st = fgets( STDIN, 1024 );
1600  }
1601  }
1602  if ( $st === false ) {
1603  return false;
1604  }
1605  $resp = trim( $st );
1606 
1607  return $resp;
1608  }
1609  }
1610 
1616  private static function readlineEmulation( $prompt ) {
1617  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1618  if ( !wfIsWindows() && $bash ) {
1619  $encPrompt = Shell::escape( $prompt );
1620  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1621  $result = Shell::command( $bash, '-c', $command )
1622  ->passStdin()
1623  ->forwardStderr()
1624  ->execute();
1625 
1626  if ( $result->getExitCode() == 0 ) {
1627  return $result->getStdout();
1628  } elseif ( $result->getExitCode() == 127 ) {
1629  // Couldn't execute bash even though we thought we saw it.
1630  // Shell probably spit out an error message, sorry :(
1631  // Fall through to fgets()...
1632  } else {
1633  // EOF/ctrl+D
1634  return false;
1635  }
1636  }
1637 
1638  // Fallback... we'll have no editing controls, EWWW
1639  if ( feof( STDIN ) ) {
1640  return false;
1641  }
1642  print $prompt;
1643 
1644  return fgets( STDIN, 1024 );
1645  }
1646 
1654  public static function getTermSize() {
1655  $default = [ 80, 50 ];
1656  if ( wfIsWindows() ) {
1657  return $default;
1658  }
1659  if ( Shell::isDisabled() ) {
1660  return $default;
1661  }
1662  // It's possible to get the screen size with VT-100 terminal escapes,
1663  // but reading the responses is not possible without setting raw mode
1664  // (unless you want to require the user to press enter), and that
1665  // requires an ioctl(), which we can't do. So we have to shell out to
1666  // something that can do the relevant syscalls. There are a few
1667  // options. Linux and Mac OS X both have "stty size" which does the
1668  // job directly.
1669  $result = Shell::command( 'stty', 'size' )
1670  ->passStdin()
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 
1695  protected function getHookContainer() {
1696  if ( !$this->hookContainer ) {
1697  $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1698  }
1699  return $this->hookContainer;
1700  }
1701 
1710  protected function getHookRunner() {
1711  if ( !$this->hookRunner ) {
1712  $this->hookRunner = new HookRunner( $this->getHookContainer() );
1713  }
1714  return $this->hookRunner;
1715  }
1716 
1727  protected function parseIntList( $text ) {
1728  $ids = preg_split( '/[\s,;:|]+/', $text );
1729  $ids = array_map(
1730  function ( $id ) {
1731  return (int)$id;
1732  },
1733  $ids
1734  );
1735  return array_filter( $ids );
1736  }
1737 }
Maintenance\$mArgList
array $mArgList
Desired/allowed args.
Definition: Maintenance.php:78
Maintenance\$mBatchSize
int $mBatchSize
Batch size.
Definition: Maintenance.php:108
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
Maintenance\setParam
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
Definition: Maintenance.php:933
Maintenance\getTermSize
static getTermSize()
Get the terminal size as a two-element array where the first element is the width (number of columns)...
Definition: Maintenance.php:1654
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1138
Maintenance\getStdin
getStdin( $len=null)
Return input from stdin.
Definition: Maintenance.php:405
Profiler\replaceStubInstance
static replaceStubInstance(Profiler $profiler)
Replace the current profiler with $profiler if no non-stub profiler is set.
Definition: Profiler.php:102
Maintenance\$mGenericParameters
array[] $mGenericParameters
Generic options added by addDefaultParams()
Definition: Maintenance.php:115
Wikimedia\Rdbms\IDatabase\rollback
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:165
Maintenance\getDbType
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition: Maintenance.php:546
Maintenance\maybeHelp
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:1049
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:486
Maintenance\$mDbPass
$mDbPass
Definition: Maintenance.php:94
Maintenance\updateSearchIndexForPage
updateSearchIndexForPage(int $pageId)
Update the searchindex table for a given pageid.
Definition: Maintenance.php:1518
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:327
Maintenance\setup
setup()
Do some sanity checking and basic setup.
Definition: Maintenance.php:739
Maintenance\$requiredExtensions
array $requiredExtensions
Definition: Maintenance.php:155
Maintenance\runChild
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
Definition: Maintenance.php:713
Maintenance\setLBFactoryTriggers
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
Definition: Maintenance.php:675
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1584
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6790
SearchUpdate
Database independant search index updater.
Definition: SearchUpdate.php:33
Maintenance\$mDescription
string $mDescription
A description of the script, children should change this via addDescription()
Definition: Maintenance.php:97
Maintenance\loadParamsAndArgs
loadParamsAndArgs( $self=null, $opts=null, $args=null)
Process command line arguments $mOptions becomes an array with keys set to the option names $mArgs be...
Definition: Maintenance.php:963
Maintenance\showHelp
showHelp()
Definitely show the help.
Definition: Maintenance.php:1060
Maintenance\$mParams
array[] $mParams
Array of desired/allowed params.
Definition: Maintenance.php:72
Maintenance\relockSearchindex
relockSearchindex( $db)
Unlock and lock again Since the lock is low-priority, queued reads will be able to complete.
Definition: Maintenance.php:1470
Maintenance\getName
getName()
Get the script's name.
Definition: Maintenance.php:395
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1283
Maintenance\$hookContainer
HookContainer null $hookContainer
Definition: Maintenance.php:139
Maintenance\$hookRunner
HookRunner null $hookRunner
Definition: Maintenance.php:142
$wgLBFactoryConf
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-master wiki farm, set the class here to somethi...
Definition: DefaultSettings.php:2234
$s
$s
Definition: mergeMessageFileList.php:184
Maintenance\hasArg
hasArg( $argId=0)
Does a given argument exist?
Definition: Maintenance.php:336
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:55
Maintenance\setConfig
setConfig(Config $config)
Definition: Maintenance.php:607
$res
$res
Definition: testCompression.php:57
$wgDBpassword
$wgDBpassword
Database user's password.
Definition: DefaultSettings.php:2036
Maintenance\$lastChannel
$lastChannel
Definition: Maintenance.php:492
Maintenance\loadWithArgv
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
Definition: Maintenance.php:857
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
Maintenance\checkRequiredExtensions
checkRequiredExtensions()
Verify that the required extensions are installed.
Definition: Maintenance.php:629
Maintenance\finalSetup
finalSetup()
Handle some last-minute setup here.
Definition: Maintenance.php:1171
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
Definition: Maintenance.php:1435
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1400
Maintenance\afterFinalSetup
afterFinalSetup()
Execute a callback function at the end of initialisation @stable for overriding.
Definition: Maintenance.php:1246
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
$wgDBadminuser
$wgDBadminuser
Separate username for maintenance tasks.
Definition: DefaultSettings.php:2066
Maintenance\unlockSearchindex
unlockSearchindex( $db)
Unlock the tables.
Definition: Maintenance.php:1461
Maintenance\clearParamsAndArgs
clearParamsAndArgs()
Clear all params and arguments.
Definition: Maintenance.php:844
Config
Interface for configuration instances.
Definition: Config.php:30
$wgDBservers
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
Definition: DefaultSettings.php:2222
Maintenance\$mInputLoaded
bool $mInputLoaded
Have we already loaded our user input?
Definition: Maintenance.php:100
$wgDBDefaultGroup
$wgDBDefaultGroup
Default group to use when getting database connections.
Definition: DefaultSettings.php:2118
Maintenance\updateSearchIndex
updateSearchIndex( $maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
Definition: Maintenance.php:1482
$wgProfiler
$wgProfiler
Profiler configuration.
Definition: DefaultSettings.php:6865
Maintenance\loadSpecialVars
loadSpecialVars()
Handle the special variables that are global to all scripts @stable for overriding.
Definition: Maintenance.php:1029
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:595
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
Maintenance\$atLineStart
$atLineStart
Definition: Maintenance.php:491
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
Maintenance\$mArgs
array $mArgs
This is the list of arguments that were actually passed.
Definition: Maintenance.php:84
Maintenance\$lastReplicationWait
float $lastReplicationWait
UNIX timestamp.
Definition: Maintenance.php:130
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:245
Maintenance\$mDbUser
$mDbUser
Definition: Maintenance.php:94
Maintenance\requireExtension
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
Definition: Maintenance.php:620
$args
if( $line===false) $args
Definition: mcc.php:124
Maintenance\$orderedOptions
array $orderedOptions
Used to read the options in the order they were passed.
Definition: Maintenance.php:168
Maintenance\globals
globals()
Potentially debug globals.
Definition: Maintenance.php:1257
$title
$title
Definition: testCompression.php:38
Maintenance\$mAllowUnregisteredOptions
bool $mAllowUnregisteredOptions
Allow arbitrary options to be passed, or only specified ones?
Definition: Maintenance.php:87
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Maintenance\addDefaultParams
addDefaultParams()
Add the default parameters to the scripts.
Definition: Maintenance.php:553
Maintenance\readlineEmulation
static readlineEmulation( $prompt)
Emulate readline()
Definition: Maintenance.php:1616
Maintenance\countDown
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
Definition: Maintenance.php:1547
Maintenance\DB_ADMIN
const DB_ADMIN
Definition: Maintenance.php:62
Maintenance\deleteOption
deleteOption( $name)
Remove an option.
Definition: Maintenance.php:310
Maintenance\shouldExecute
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class?...
Definition: Maintenance.php:188
Maintenance\DB_STD
const DB_STD
Definition: Maintenance.php:61
Maintenance\$mOptions
array $mOptions
This is the list of options that were actually passed.
Definition: Maintenance.php:81
Maintenance\supportsOption
supportsOption( $name)
Checks to see if a particular option in supported.
Definition: Maintenance.php:230
Maintenance\isQuiet
isQuiet()
Definition: Maintenance.php:422
Maintenance\activateProfiler
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
Definition: Maintenance.php:816
Maintenance\getHookContainer
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: Maintenance.php:1695
Maintenance\setAllowUnregisteredOptions
setAllowUnregisteredOptions( $allow)
Sets whether to allow unregistered options, which are options passed to a script that do not match an...
Definition: Maintenance.php:319
Maintenance\$mDependantParameters
array[] $mDependantParameters
Generic options which might or not be supported by the script.
Definition: Maintenance.php:121
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1853
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:111
Maintenance\requireTestsAutoloader
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
Definition: Maintenance.php:1685
Maintenance\posix_isatty
static posix_isatty( $fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
Definition: Maintenance.php:1571
Maintenance\getHookRunner
getHookRunner()
Get a HookRunner for running core hooks.
Definition: Maintenance.php:1710
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1415
Maintenance\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc Stable for overriding.
Definition: Maintenance.php:996
Maintenance\$config
Config $config
Accessible via getConfig()
Definition: Maintenance.php:149
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1369
Maintenance\$mQuiet
bool $mQuiet
Special vars for params that are always used.
Definition: Maintenance.php:93
Maintenance\cleanupChanneled
cleanupChanneled()
Clean up channeled output.
Definition: Maintenance.php:497
Maintenance\DB_NONE
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:60
Maintenance\loadSettings
loadSettings()
Generic setup for most installs.
Definition: Maintenance.php:1267
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:280
Maintenance\adjustMemoryLimit
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
Definition: Maintenance.php:803
Maintenance\purgeRedundantText
purgeRedundantText( $delete=true)
Support function for cleaning up redundant text records.
Definition: Maintenance.php:1304
$self
$self
Definition: doMaintenance.php:63
Maintenance\$fileHandle
resource $fileHandle
Used when creating separate schema files.
Definition: Maintenance.php:136
Maintenance\$mShortParamsMap
array $mShortParamsMap
Mapping short parameters to long ones.
Definition: Maintenance.php:75
$command
$command
Definition: mcc.php:125
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:281
Maintenance\$mSelf
string null $mSelf
Name of the script currently running.
Definition: Maintenance.php:90
Maintenance\STDIN_ALL
const STDIN_ALL
Definition: Maintenance.php:65
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:298
Wikimedia\Rdbms\LBFactory
An interface for generating database load balancers.
Definition: LBFactory.php:41
Maintenance\parseIntList
parseIntList( $text)
Utility function to parse a string (perhaps from a command line option) into a list of integers (perh...
Definition: Maintenance.php:1727
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:366
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
Definition: DefaultSettings.php:6762
Maintenance\setAgentAndTriggers
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
Definition: Maintenance.php:654
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1386
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:462
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:433
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
Maintenance\getDir
getDir()
Get the maintenance directory.
Definition: Maintenance.php:1351
$wgDBuser
$wgDBuser
Database username.
Definition: DefaultSettings.php:2031
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:567
ExecutableFinder\findInDefaultPaths
static findInDefaultPaths( $names, $versionInfo=false)
Same as locateExecutable(), but checks in getPossibleBinPaths() by default.
Definition: ExecutableFinder.php:96
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:266
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:351
$maintClass
string false $maintClass
-var class-string|false
Definition: Maintenance.php:48
$IP
$IP
Definition: WebStart.php:49
$wgDBadminpassword
$wgDBadminpassword
Separate password for maintenance tasks.
Definition: DefaultSettings.php:2071
Maintenance\outputChanneled
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
Definition: Maintenance.php:512
Maintenance\__construct
__construct()
Default constructor.
Definition: Maintenance.php:176
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
$wgTrxProfilerLimits
$wgTrxProfilerLimits
Performance expectations for DB usage.
Definition: DefaultSettings.php:6624
Maintenance\execute
execute()
Do the actual work.
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
Wikimedia\Rdbms\IDatabase\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Wikimedia\Rdbms\IDatabase\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Maintenance\lockSearchindex
lockSearchindex( $db)
Lock the search index.
Definition: Maintenance.php:1443
Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40
Maintenance\setBatchSize
setBatchSize( $s=0)
Definition: Maintenance.php:373
Maintenance\$mDb
IMaintainableDatabase $mDb
Used by getDB() / setDB()
Definition: Maintenance.php:127
Maintenance\memoryLimit
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
Definition: Maintenance.php:794