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 = -1;
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 $mDependentParameters = [];
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 
267  protected function hasOption( $name ) {
268  return isset( $this->mOptions[$name] );
269  }
270 
282  protected function getOption( $name, $default = null ) {
283  if ( $this->hasOption( $name ) ) {
284  return $this->mOptions[$name];
285  } else {
286  return $default;
287  }
288  }
289 
296  protected function addArg( $arg, $description, $required = true ) {
297  $this->mArgList[] = [
298  'name' => $arg,
299  'desc' => $description,
300  'require' => $required
301  ];
302  }
303 
308  protected function deleteOption( $name ) {
309  unset( $this->mParams[$name] );
310  }
311 
317  protected function setAllowUnregisteredOptions( $allow ) {
318  $this->mAllowUnregisteredOptions = $allow;
319  }
320 
325  protected function addDescription( $text ) {
326  $this->mDescription = $text;
327  }
328 
334  protected function hasArg( $argId = 0 ) {
335  if ( func_num_args() === 0 ) {
336  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
337  }
338 
339  return isset( $this->mArgs[$argId] );
340  }
341 
349  protected function getArg( $argId = 0, $default = null ) {
350  if ( func_num_args() === 0 ) {
351  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
352  }
353 
354  return $this->mArgs[$argId] ?? $default;
355  }
356 
364  protected function getBatchSize() {
365  return $this->mBatchSize;
366  }
367 
371  protected function setBatchSize( $s = 0 ) {
372  $this->mBatchSize = $s;
373 
374  // If we support $mBatchSize, show the option.
375  // Used to be in addDefaultParams, but in order for that to
376  // work, subclasses would have to call this function in the constructor
377  // before they called parent::__construct which is just weird
378  // (and really wasn't done).
379  if ( $this->mBatchSize ) {
380  $this->addOption( 'batch-size', 'Run this many operations ' .
381  'per batch, default: ' . $this->mBatchSize, false, true );
382  if ( isset( $this->mParams['batch-size'] ) ) {
383  // This seems a little ugly...
384  $this->mDependentParameters['batch-size'] = $this->mParams['batch-size'];
385  }
386  }
387  }
388 
393  public function getName() {
394  return $this->mSelf;
395  }
396 
403  protected function getStdin( $len = null ) {
404  if ( $len == self::STDIN_ALL ) {
405  return file_get_contents( 'php://stdin' );
406  }
407  $f = fopen( 'php://stdin', 'rt' );
408  if ( !$len ) {
409  return $f;
410  }
411  $input = fgets( $f, $len );
412  fclose( $f );
413 
414  return rtrim( $input );
415  }
416 
420  public function isQuiet() {
421  return $this->mQuiet;
422  }
423 
431  protected function output( $out, $channel = null ) {
432  // This is sometimes called very early, before Setup.php is included.
433  if ( class_exists( MediaWikiServices::class ) ) {
434  // Try to periodically flush buffered metrics to avoid OOMs
435  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
436  if ( $stats->getDataCount() > 1000 ) {
437  MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
438  }
439  }
440 
441  if ( $this->mQuiet ) {
442  return;
443  }
444  if ( $channel === null ) {
445  $this->cleanupChanneled();
446  print $out;
447  } else {
448  $out = preg_replace( '/\n\z/', '', $out );
449  $this->outputChanneled( $out, $channel );
450  }
451  }
452 
460  protected function error( $err, $die = 0 ) {
461  if ( intval( $die ) !== 0 ) {
462  wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
463  $this->fatalError( $err, intval( $die ) );
464  }
465  $this->outputChanneled( false );
466  if (
467  ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
468  !defined( 'MW_PHPUNIT_TEST' )
469  ) {
470  fwrite( STDERR, $err . "\n" );
471  } else {
472  print $err;
473  }
474  }
475 
484  protected function fatalError( $msg, $exitCode = 1 ) {
485  $this->error( $msg );
486  exit( $exitCode );
487  }
488 
489  private $atLineStart = true;
490  private $lastChannel = null;
491 
495  public function cleanupChanneled() {
496  if ( !$this->atLineStart ) {
497  print "\n";
498  $this->atLineStart = true;
499  }
500  }
501 
510  public function outputChanneled( $msg, $channel = null ) {
511  if ( $msg === false ) {
512  $this->cleanupChanneled();
513 
514  return;
515  }
516 
517  // End the current line if necessary
518  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
519  print "\n";
520  }
521 
522  print $msg;
523 
524  $this->atLineStart = false;
525  if ( $channel === null ) {
526  // For unchanneled messages, output trailing newline immediately
527  print "\n";
528  $this->atLineStart = true;
529  }
530  $this->lastChannel = $channel;
531  }
532 
544  public function getDbType() {
545  return self::DB_STD;
546  }
547 
551  protected function addDefaultParams() {
552  # Generic (non-script-dependent) options:
553 
554  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
555  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
556  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
557  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
558  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
559  $this->addOption(
560  'memory-limit',
561  'Set a specific memory limit for the script, '
562  . '"max" for no limit or "default" to avoid changing it',
563  false,
564  true
565  );
566  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
567  "http://en.wikipedia.org. This is sometimes necessary because " .
568  "server name detection may fail in command line scripts.", false, true );
569  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
570 
571  # Save generic options to display them separately in help
572  $this->mGenericParameters = $this->mParams;
573 
574  # Script-dependent options:
575 
576  // If we support a DB, show the options
577  if ( $this->getDbType() > 0 ) {
578  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
579  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
580  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
581  }
582 
583  # Save additional script-dependent options to display
584  # ┬áthem separately in help
585  $this->mDependentParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
586  }
587 
593  public function getConfig() {
594  if ( $this->config === null ) {
595  $this->config = MediaWikiServices::getInstance()->getMainConfig();
596  }
597 
598  return $this->config;
599  }
600 
605  public function setConfig( Config $config ) {
606  $this->config = $config;
607  }
608 
618  protected function requireExtension( $name ) {
619  $this->requiredExtensions[] = $name;
620  }
621 
627  public function checkRequiredExtensions() {
628  $registry = ExtensionRegistry::getInstance();
629  $missing = [];
630  foreach ( $this->requiredExtensions as $name ) {
631  if ( !$registry->isLoaded( $name ) ) {
632  $missing[] = $name;
633  }
634  }
635 
636  if ( $missing ) {
637  if ( count( $missing ) === 1 ) {
638  $msg = 'The "' . $missing[ 0 ] . '" extension must be installed for this script to run. '
639  . 'Please enable it and then try again.';
640  } else {
641  $msg = 'The following extensions must be installed for this script to run: "'
642  . implode( '", "', $missing ) . '". Please enable them and then try again.';
643  }
644  $this->fatalError( $msg );
645  }
646  }
647 
652  public function setAgentAndTriggers() {
653  if ( function_exists( 'posix_getpwuid' ) ) {
654  $agent = posix_getpwuid( posix_geteuid() )['name'];
655  } else {
656  $agent = 'sysadmin';
657  }
658  $agent .= '@' . wfHostname();
659 
660  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
661  // Add a comment for easy SHOW PROCESSLIST interpretation
662  $lbFactory->setAgentName(
663  mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
664  );
665  self::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
666  }
667 
673  public static function setLBFactoryTriggers( LBFactory $LBFactory, Config $config ) {
674  $services = MediaWikiServices::getInstance();
675  $stats = $services->getStatsdDataFactory();
676  // Hook into period lag checks which often happen in long-running scripts
677  $lbFactory = $services->getDBLoadBalancerFactory();
678  $lbFactory->setWaitForReplicationListener(
679  __METHOD__,
680  static function () use ( $stats, $config ) {
681  // Check config in case of JobRunner and unit tests
682  if ( $config->get( 'CommandLineMode' ) ) {
683  DeferredUpdates::tryOpportunisticExecute( 'run' );
684  }
685  // Try to periodically flush buffered metrics to avoid OOMs
687  }
688  );
689  // Check for other windows to run them. A script may read or do a few writes
690  // to the master but mostly be writing to something else, like a file store.
691  $lbFactory->getMainLB()->setTransactionListener(
692  __METHOD__,
693  static function ( $trigger ) use ( $stats, $config ) {
694  // Check config in case of JobRunner and unit tests
695  if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
696  DeferredUpdates::tryOpportunisticExecute( 'run' );
697  }
698  // Try to periodically flush buffered metrics to avoid OOMs
700  }
701  );
702  }
703 
711  public function runChild( $maintClass, $classFile = null ) {
712  // Make sure the class is loaded first
713  if ( !class_exists( $maintClass ) ) {
714  if ( $classFile ) {
715  require_once $classFile;
716  }
717  if ( !class_exists( $maintClass ) ) {
718  $this->fatalError( "Cannot spawn child: $maintClass" );
719  }
720  }
721 
725  $child = new $maintClass();
726  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
727  if ( $this->mDb !== null ) {
728  $child->setDB( $this->mDb );
729  }
730 
731  return $child;
732  }
733 
737  public function setup() {
738  global $IP, $wgCommandLineMode;
739 
740  # Abort if called from a web server
741  # wfIsCLI() is not available yet
742  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
743  $this->fatalError( 'This script must be run from the command line' );
744  }
745 
746  if ( $IP === null ) {
747  $this->fatalError( "\$IP not set, aborting!\n" .
748  '(Did you forget to call parent::__construct() in your maintenance script?)' );
749  }
750 
751  # Make sure we can handle script parameters
752  if ( !ini_get( 'register_argc_argv' ) ) {
753  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
754  }
755 
756  // Send PHP warnings and errors to stderr instead of stdout.
757  // This aids in diagnosing problems, while keeping messages
758  // out of redirected output.
759  if ( ini_get( 'display_errors' ) ) {
760  ini_set( 'display_errors', 'stderr' );
761  }
762 
763  $this->loadParamsAndArgs();
764 
765  # Set the memory limit
766  # Note we need to set it again later in cache LocalSettings changed it
767  $this->adjustMemoryLimit();
768 
769  # Set max execution time to 0 (no limit). PHP.net says that
770  # "When running PHP from the command line the default setting is 0."
771  # But sometimes this doesn't seem to be the case.
772  ini_set( 'max_execution_time', 0 );
773 
774  $wgCommandLineMode = true;
775 
776  # Turn off output buffering if it's on
777  while ( ob_get_level() > 0 ) {
778  ob_end_flush();
779  }
780  }
781 
792  public function memoryLimit() {
793  $limit = $this->getOption( 'memory-limit', 'max' );
794  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
795  return $limit;
796  }
797 
801  protected function adjustMemoryLimit() {
802  $limit = $this->memoryLimit();
803  if ( $limit == 'max' ) {
804  $limit = -1; // no memory limit
805  }
806  if ( $limit != 'default' ) {
807  ini_set( 'memory_limit', $limit );
808  }
809  }
810 
814  protected function activateProfiler() {
816 
817  $output = $this->getOption( 'profiler' );
818  if ( !$output ) {
819  return;
820  }
821 
822  if ( isset( $wgProfiler['class'] ) ) {
823  $class = $wgProfiler['class'];
825  $profiler = new $class(
826  [ 'sampling' => 1, 'output' => [ $output ] ]
827  + $wgProfiler
828  + [ 'threshold' => 0.0 ]
829  );
830  $profiler->setAllowOutput();
831  Profiler::replaceStubInstance( $profiler );
832  }
833 
834  $trxProfiler = Profiler::instance()->getTransactionProfiler();
835  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
836  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
837  }
838 
842  public function clearParamsAndArgs() {
843  $this->mOptions = [];
844  $this->mArgs = [];
845  $this->mInputLoaded = false;
846  }
847 
855  public function loadWithArgv( $argv ) {
856  $options = [];
857  $args = [];
858  $this->orderedOptions = [];
859 
860  # Parse arguments
861  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
862  if ( $arg == '--' ) {
863  # End of options, remainder should be considered arguments
864  $arg = next( $argv );
865  while ( $arg !== false ) {
866  $args[] = $arg;
867  $arg = next( $argv );
868  }
869  break;
870  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
871  # Long options
872  $option = substr( $arg, 2 );
873  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
874  $param = next( $argv );
875  if ( $param === false ) {
876  $this->error( "\nERROR: $option parameter needs a value after it\n" );
877  $this->maybeHelp( true );
878  }
879 
880  $this->setParam( $options, $option, $param );
881  } else {
882  $bits = explode( '=', $option, 2 );
883  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
884  }
885  } elseif ( $arg == '-' ) {
886  # Lonely "-", often used to indicate stdin or stdout.
887  $args[] = $arg;
888  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
889  # Short options
890  $argLength = strlen( $arg );
891  for ( $p = 1; $p < $argLength; $p++ ) {
892  $option = $arg[$p];
893  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
894  $option = $this->mShortParamsMap[$option];
895  }
896 
897  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
898  $param = next( $argv );
899  if ( $param === false ) {
900  $this->error( "\nERROR: $option parameter needs a value after it\n" );
901  $this->maybeHelp( true );
902  }
903  $this->setParam( $options, $option, $param );
904  } else {
905  $this->setParam( $options, $option, 1 );
906  }
907  }
908  } else {
909  $args[] = $arg;
910  }
911  }
912 
913  $this->mOptions = $options;
914  $this->mArgs = $args;
915  $this->loadSpecialVars();
916  $this->mInputLoaded = true;
917  }
918 
931  private function setParam( &$options, $option, $value ) {
932  $this->orderedOptions[] = [ $option, $value ];
933 
934  if ( isset( $this->mParams[$option] ) ) {
935  $multi = $this->mParams[$option]['multiOccurrence'];
936  } else {
937  $multi = false;
938  }
939  $exists = array_key_exists( $option, $options );
940  if ( $multi && $exists ) {
941  $options[$option][] = $value;
942  } elseif ( $multi ) {
943  $options[$option] = [ $value ];
944  } elseif ( !$exists ) {
945  $options[$option] = $value;
946  } else {
947  $this->error( "\nERROR: $option parameter given twice\n" );
948  $this->maybeHelp( true );
949  }
950  }
951 
961  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
962  # If we were given opts or args, set those and return early
963  if ( $self ) {
964  $this->mSelf = $self;
965  $this->mInputLoaded = true;
966  }
967  if ( $opts ) {
968  $this->mOptions = $opts;
969  $this->mInputLoaded = true;
970  }
971  if ( $args ) {
972  $this->mArgs = $args;
973  $this->mInputLoaded = true;
974  }
975 
976  # If we've already loaded input (either by user values or from $argv)
977  # skip on loading it again. The array_shift() will corrupt values if
978  # it's run again and again
979  if ( $this->mInputLoaded ) {
980  $this->loadSpecialVars();
981 
982  return;
983  }
984 
985  global $argv;
986  $this->mSelf = $argv[0];
987  $this->loadWithArgv( array_slice( $argv, 1 ) );
988  }
989 
994  public function validateParamsAndArgs() {
995  $die = false;
996  # Check to make sure we've got all the required options
997  foreach ( $this->mParams as $opt => $info ) {
998  if ( $info['require'] && !$this->hasOption( $opt ) ) {
999  $this->error( "Param $opt required!" );
1000  $die = true;
1001  }
1002  }
1003  # Check arg list too
1004  foreach ( $this->mArgList as $k => $info ) {
1005  if ( $info['require'] && !$this->hasArg( $k ) ) {
1006  $this->error( 'Argument <' . $info['name'] . '> required!' );
1007  $die = true;
1008  }
1009  }
1010  if ( !$this->mAllowUnregisteredOptions ) {
1011  # Check for unexpected options
1012  foreach ( $this->mOptions as $opt => $val ) {
1013  if ( !$this->supportsOption( $opt ) ) {
1014  $this->error( "Unexpected option $opt!" );
1015  $die = true;
1016  }
1017  }
1018  }
1019 
1020  $this->maybeHelp( $die );
1021  }
1022 
1027  protected function loadSpecialVars() {
1028  if ( $this->hasOption( 'dbuser' ) ) {
1029  $this->mDbUser = $this->getOption( 'dbuser' );
1030  }
1031  if ( $this->hasOption( 'dbpass' ) ) {
1032  $this->mDbPass = $this->getOption( 'dbpass' );
1033  }
1034  if ( $this->hasOption( 'quiet' ) ) {
1035  $this->mQuiet = true;
1036  }
1037  if ( $this->hasOption( 'batch-size' ) ) {
1038  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1039  }
1040  }
1041 
1047  protected function maybeHelp( $force = false ) {
1048  if ( !$force && !$this->hasOption( 'help' ) ) {
1049  return;
1050  }
1051  $this->showHelp();
1052  die( 1 );
1053  }
1054 
1058  protected function showHelp() {
1059  $screenWidth = self::getTermSize()[0];
1060  $tab = " ";
1061  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1062 
1063  ksort( $this->mParams );
1064  $this->mQuiet = false;
1065 
1066  // Description ...
1067  if ( $this->mDescription ) {
1068  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1069  }
1070  $output = "\nUsage: php " . basename( $this->mSelf );
1071 
1072  // ... append parameters ...
1073  if ( $this->mParams ) {
1074  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1075  }
1076 
1077  // ... and append arguments.
1078  if ( $this->mArgList ) {
1079  $output .= ' ';
1080  foreach ( $this->mArgList as $k => $arg ) {
1081  if ( $arg['require'] ) {
1082  $output .= '<' . $arg['name'] . '>';
1083  } else {
1084  $output .= '[' . $arg['name'] . ']';
1085  }
1086  if ( $k < count( $this->mArgList ) - 1 ) {
1087  $output .= ' ';
1088  }
1089  }
1090  }
1091  $this->output( "$output\n\n" );
1092 
1093  $this->formatHelpItems(
1094  $this->mGenericParameters,
1095  'Generic maintenance parameters',
1096  $descWidth, $tab
1097  );
1098 
1099  $this->formatHelpItems(
1100  $this->mDependentParameters,
1101  'Script dependent parameters',
1102  $descWidth, $tab
1103  );
1104 
1105  // Script-specific parameters not defined on construction by
1106  // Maintenance::addDefaultParams()
1107  $scriptSpecificParams = array_diff_key(
1108  # all script parameters:
1109  $this->mParams,
1110  # remove the Maintenance default parameters:
1111  $this->mGenericParameters,
1112  $this->mDependentParameters
1113  );
1114 
1115  $this->formatHelpItems(
1116  $scriptSpecificParams,
1117  'Script specific parameters',
1118  $descWidth, $tab
1119  );
1120 
1121  // Print arguments
1122  if ( count( $this->mArgList ) > 0 ) {
1123  $this->output( "Arguments:\n" );
1124  // Arguments description
1125  foreach ( $this->mArgList as $info ) {
1126  $openChar = $info['require'] ? '<' : '[';
1127  $closeChar = $info['require'] ? '>' : ']';
1128  $this->output(
1129  wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1130  $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1131  );
1132  }
1133  $this->output( "\n" );
1134  }
1135  }
1136 
1137  private function formatHelpItems( array $items, $heading, $descWidth, $tab ) {
1138  if ( $items === [] ) {
1139  return;
1140  }
1141 
1142  $this->output( "$heading:\n" );
1143 
1144  foreach ( $items as $name => $info ) {
1145  if ( $info['shortName'] !== false ) {
1146  $name .= ' (-' . $info['shortName'] . ')';
1147  }
1148  $this->output(
1149  wordwrap(
1150  "$tab--$name: " . $info['desc'],
1151  $descWidth,
1152  "\n$tab$tab"
1153  ) . "\n"
1154  );
1155  }
1156 
1157  $this->output( "\n" );
1158  }
1159 
1164  public function finalSetup() {
1168 
1169  # Turn off output buffering again, it might have been turned on in the settings files
1170  if ( ob_get_level() ) {
1171  ob_end_flush();
1172  }
1173  # Same with these
1174  $wgCommandLineMode = true;
1175 
1176  # Override $wgServer
1177  if ( $this->hasOption( 'server' ) ) {
1178  $wgServer = $this->getOption( 'server', $wgServer );
1179  }
1180 
1181  # If these were passed, use them
1182  if ( $this->mDbUser ) {
1184  }
1185  if ( $this->mDbPass ) {
1187  }
1188  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1189  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1190 
1191  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1192  if ( $service ) {
1193  $service->destroy();
1194  }
1195  }
1196 
1197  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1200 
1201  if ( $wgDBservers ) {
1205  foreach ( $wgDBservers as $i => $server ) {
1206  $wgDBservers[$i]['user'] = $wgDBuser;
1207  $wgDBservers[$i]['password'] = $wgDBpassword;
1208  }
1209  }
1210  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1211  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1212  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1213  }
1214  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1215  if ( $service ) {
1216  $service->destroy();
1217  }
1218  }
1219 
1220  // Per-script profiling; useful for debugging
1221  $this->activateProfiler();
1222 
1223  $this->afterFinalSetup();
1224 
1225  $wgShowExceptionDetails = true;
1226  $wgShowHostnames = true;
1227 
1228  Wikimedia\suppressWarnings();
1229  set_time_limit( 0 );
1230  Wikimedia\restoreWarnings();
1231 
1232  $this->adjustMemoryLimit();
1233  }
1234 
1239  protected function afterFinalSetup() {
1240  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1241  call_user_func( MW_CMDLINE_CALLBACK );
1242  }
1243  }
1244 
1249  public function globals() {
1250  if ( $this->hasOption( 'globals' ) ) {
1251  print_r( $GLOBALS );
1252  }
1253  }
1254 
1259  public function shutdown() {
1260  $lbFactory = null;
1261  if (
1262  $this->getDbType() !== self::DB_NONE &&
1263  // Service might be disabled, e.g. when running install.php
1264  !MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancerFactory' )
1265  ) {
1266  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1267  $lbFactory->commitMasterChanges( get_class( $this ) );
1268  // @TODO: make less assumptions about deferred updates being coupled to the DB
1270  }
1271 
1273 
1274  if ( $lbFactory ) {
1275  $lbFactory->commitMasterChanges( 'doMaintenance' );
1276  $lbFactory->shutdown( $lbFactory::SHUTDOWN_NO_CHRONPROT );
1277  }
1278  }
1279 
1284  public function loadSettings() {
1285  global $wgCommandLineMode, $IP;
1286 
1287  if ( isset( $this->mOptions['conf'] ) ) {
1288  $settingsFile = $this->mOptions['conf'];
1289  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1290  $settingsFile = MW_CONFIG_FILE;
1291  } else {
1292  $settingsFile = "$IP/LocalSettings.php";
1293  }
1294  if ( isset( $this->mOptions['wiki'] ) ) {
1295  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1296  define( 'MW_DB', $bits[0] );
1297  define( 'MW_PREFIX', $bits[1] ?? '' );
1298  } elseif ( isset( $this->mOptions['server'] ) ) {
1299  // Provide the option for site admins to detect and configure
1300  // multiple wikis based on server names. This offers --server
1301  // as alternative to --wiki.
1302  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1303  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1304  }
1305 
1306  if ( !is_readable( $settingsFile ) ) {
1307  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1308  "must exist and be readable in the source directory.\n" .
1309  "Use --conf to specify it." );
1310  }
1311  $wgCommandLineMode = true;
1312 
1313  return $settingsFile;
1314  }
1315 
1321  public function purgeRedundantText( $delete = true ) {
1322  # Data should come off the master, wrapped in a transaction
1323  $dbw = $this->getDB( DB_MASTER );
1324  $this->beginTransaction( $dbw, __METHOD__ );
1325 
1326  # Get "active" text records via the content table
1327  $cur = [];
1328  $this->output( 'Searching for active text records via contents table...' );
1329  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1330  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1331  foreach ( $res as $row ) {
1332  // @phan-suppress-next-line PhanUndeclaredMethod
1333  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1334  if ( $textId ) {
1335  $cur[] = $textId;
1336  }
1337  }
1338  $this->output( "done.\n" );
1339 
1340  # Get the IDs of all text records not in these sets
1341  $this->output( 'Searching for inactive text records...' );
1342  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1343  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1344  $old = [];
1345  foreach ( $res as $row ) {
1346  $old[] = $row->old_id;
1347  }
1348  $this->output( "done.\n" );
1349 
1350  # Inform the user of what we're going to do
1351  $count = count( $old );
1352  $this->output( "$count inactive items found.\n" );
1353 
1354  # Delete as appropriate
1355  if ( $delete && $count ) {
1356  $this->output( 'Deleting...' );
1357  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1358  $this->output( "done.\n" );
1359  }
1360 
1361  $this->commitTransaction( $dbw, __METHOD__ );
1362  }
1363 
1368  protected function getDir() {
1369  return __DIR__ . '/../';
1370  }
1371 
1386  protected function getDB( $db, $groups = [], $dbDomain = false ) {
1387  if ( $this->mDb === null ) {
1388  return MediaWikiServices::getInstance()
1389  ->getDBLoadBalancerFactory()
1390  ->getMainLB( $dbDomain )
1391  ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1392  }
1393 
1394  return $this->mDb;
1395  }
1396 
1403  public function setDB( IMaintainableDatabase $db ) {
1404  $this->mDb = $db;
1405  }
1406 
1417  protected function beginTransaction( IDatabase $dbw, $fname ) {
1418  $dbw->begin( $fname );
1419  }
1420 
1432  protected function commitTransaction( IDatabase $dbw, $fname ) {
1433  $dbw->commit( $fname );
1434  return $this->waitForReplication();
1435  }
1436 
1443  protected function waitForReplication() {
1444  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1445  $waitSucceeded = $lbFactory->waitForReplication(
1446  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1447  );
1448  $this->lastReplicationWait = microtime( true );
1449  return $waitSucceeded;
1450  }
1451 
1462  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1463  $dbw->rollback( $fname );
1464  }
1465 
1470  private function lockSearchindex( $db ) {
1471  $write = [ 'searchindex' ];
1472  $read = [
1473  'page',
1474  'revision',
1475  'text',
1476  'interwiki',
1477  'l10n_cache',
1478  'user',
1479  'page_restrictions'
1480  ];
1481  $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1482  }
1483 
1488  private function unlockSearchindex( $db ) {
1489  $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1490  }
1491 
1497  private function relockSearchindex( $db ) {
1498  $this->unlockSearchindex( $db );
1499  $this->lockSearchindex( $db );
1500  }
1501 
1509  public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1510  $lockTime = time();
1511 
1512  # Lock searchindex
1513  if ( $maxLockTime ) {
1514  $this->output( " --- Waiting for lock ---" );
1515  $this->lockSearchindex( $dbw );
1516  $lockTime = time();
1517  $this->output( "\n" );
1518  }
1519 
1520  # Loop through the results and do a search update
1521  foreach ( $results as $row ) {
1522  # Allow reads to be processed
1523  if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1524  $this->output( " --- Relocking ---" );
1525  $this->relockSearchindex( $dbw );
1526  $lockTime = time();
1527  $this->output( "\n" );
1528  }
1529  call_user_func( $callback, $row );
1530  }
1531 
1532  # Unlock searchindex
1533  if ( $maxLockTime ) {
1534  $this->output( " --- Unlocking --" );
1535  $this->unlockSearchindex( $dbw );
1536  $this->output( "\n" );
1537  }
1538  }
1539 
1545  public function updateSearchIndexForPage( int $pageId ) {
1546  // Get current revision
1547  $rev = MediaWikiServices::getInstance()
1548  ->getRevisionLookup()
1549  ->getRevisionByPageId( $pageId, 0, IDBAccessObject::READ_LATEST );
1550  $title = null;
1551  if ( $rev ) {
1552  $titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
1553  $title = $titleObj->getPrefixedDBkey();
1554  $this->output( "$title..." );
1555  # Update searchindex
1556  $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent( SlotRecord::MAIN ) );
1557  $u->doUpdate();
1558  $this->output( "\n" );
1559  }
1560 
1561  return $title;
1562  }
1563 
1574  protected function countDown( $seconds ) {
1575  if ( $this->isQuiet() ) {
1576  return;
1577  }
1578  for ( $i = $seconds; $i >= 0; $i-- ) {
1579  if ( $i != $seconds ) {
1580  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1581  }
1582  $this->output( $i );
1583  if ( $i ) {
1584  sleep( 1 );
1585  }
1586  }
1587  $this->output( "\n" );
1588  }
1589 
1598  public static function posix_isatty( $fd ) {
1599  if ( !function_exists( 'posix_isatty' ) ) {
1600  return !$fd;
1601  } else {
1602  return posix_isatty( $fd );
1603  }
1604  }
1605 
1611  public static function readconsole( $prompt = '> ' ) {
1612  static $isatty = null;
1613  if ( $isatty === null ) {
1614  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1615  }
1616 
1617  if ( $isatty && function_exists( 'readline' ) ) {
1618  return readline( $prompt );
1619  } else {
1620  if ( $isatty ) {
1621  $st = self::readlineEmulation( $prompt );
1622  } else {
1623  if ( feof( STDIN ) ) {
1624  $st = false;
1625  } else {
1626  $st = fgets( STDIN, 1024 );
1627  }
1628  }
1629  if ( $st === false ) {
1630  return false;
1631  }
1632  $resp = trim( $st );
1633 
1634  return $resp;
1635  }
1636  }
1637 
1643  private static function readlineEmulation( $prompt ) {
1644  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1645  if ( !wfIsWindows() && $bash ) {
1646  $encPrompt = Shell::escape( $prompt );
1647  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1648  $result = Shell::command( $bash, '-c', $command )
1649  ->passStdin()
1650  ->forwardStderr()
1651  ->execute();
1652 
1653  if ( $result->getExitCode() == 0 ) {
1654  return $result->getStdout();
1655  } elseif ( $result->getExitCode() == 127 ) {
1656  // Couldn't execute bash even though we thought we saw it.
1657  // Shell probably spit out an error message, sorry :(
1658  // Fall through to fgets()...
1659  } else {
1660  // EOF/ctrl+D
1661  return false;
1662  }
1663  }
1664 
1665  // Fallback... we'll have no editing controls, EWWW
1666  if ( feof( STDIN ) ) {
1667  return false;
1668  }
1669  print $prompt;
1670 
1671  return fgets( STDIN, 1024 );
1672  }
1673 
1681  public static function getTermSize() {
1682  static $termSize = null;
1683 
1684  if ( $termSize !== null ) {
1685  return $termSize;
1686  }
1687 
1688  $default = [ 80, 50 ];
1689 
1690  if ( wfIsWindows() || Shell::isDisabled() ) {
1691  $termSize = $default;
1692 
1693  return $termSize;
1694  }
1695 
1696  // It's possible to get the screen size with VT-100 terminal escapes,
1697  // but reading the responses is not possible without setting raw mode
1698  // (unless you want to require the user to press enter), and that
1699  // requires an ioctl(), which we can't do. So we have to shell out to
1700  // something that can do the relevant syscalls. There are a few
1701  // options. Linux and Mac OS X both have "stty size" which does the
1702  // job directly.
1703  $result = Shell::command( 'stty', 'size' )->passStdin()->execute();
1704  if ( $result->getExitCode() !== 0 ||
1705  !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m )
1706  ) {
1707  $termSize = $default;
1708 
1709  return $termSize;
1710  }
1711 
1712  $termSize = [ intval( $m[2] ), intval( $m[1] ) ];
1713 
1714  return $termSize;
1715  }
1716 
1721  public static function requireTestsAutoloader() {
1722  require_once __DIR__ . '/../../tests/common/TestsAutoLoader.php';
1723  }
1724 
1731  protected function getHookContainer() {
1732  if ( !$this->hookContainer ) {
1733  $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1734  }
1735  return $this->hookContainer;
1736  }
1737 
1746  protected function getHookRunner() {
1747  if ( !$this->hookRunner ) {
1748  $this->hookRunner = new HookRunner( $this->getHookContainer() );
1749  }
1750  return $this->hookRunner;
1751  }
1752 
1763  protected function parseIntList( $text ) {
1764  $ids = preg_split( '/[\s,;:|]+/', $text );
1765  $ids = array_map(
1766  static function ( $id ) {
1767  return (int)$id;
1768  },
1769  $ids
1770  );
1771  return array_filter( $ids );
1772  }
1773 }
Maintenance\$mArgList
array $mArgList
Desired/allowed args.
Definition: Maintenance.php:78
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:45
Maintenance\setParam
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
Definition: Maintenance.php:931
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:1681
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1117
Maintenance\getStdin
getStdin( $len=null)
Return input from stdin.
Definition: Maintenance.php:403
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:173
Maintenance\getDbType
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition: Maintenance.php:544
Maintenance\maybeHelp
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:1047
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:484
Maintenance\$mDbPass
$mDbPass
Definition: Maintenance.php:94
Maintenance\updateSearchIndexForPage
updateSearchIndexForPage(int $pageId)
Update the searchindex table for a given pageid.
Definition: Maintenance.php:1545
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:325
Maintenance\setup
setup()
Do some sanity checking and basic setup.
Definition: Maintenance.php:737
Maintenance\$requiredExtensions
array $requiredExtensions
Definition: Maintenance.php:155
Maintenance\runChild
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
Definition: Maintenance.php:711
Maintenance\setLBFactoryTriggers
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
Definition: Maintenance.php:673
Maintenance\shutdown
shutdown()
Call before shutdown to run any deferred updates.
Definition: Maintenance.php:1259
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1611
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6868
SearchUpdate
Database independent 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:961
Maintenance\showHelp
showHelp()
Definitely show the help.
Definition: Maintenance.php:1058
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:1497
Maintenance\getName
getName()
Get the script's name.
Definition: Maintenance.php:393
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1294
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:2274
Maintenance\hasArg
hasArg( $argId=0)
Does a given argument exist?
Definition: Maintenance.php:334
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:605
$res
$res
Definition: testCompression.php:57
$wgDBpassword
$wgDBpassword
Database user's password.
Definition: DefaultSettings.php:2076
Maintenance\$lastChannel
$lastChannel
Definition: Maintenance.php:490
Maintenance\$mBatchSize
int null $mBatchSize
Batch size.
Definition: Maintenance.php:108
Maintenance\loadWithArgv
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
Definition: Maintenance.php:855
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:627
Maintenance\finalSetup
finalSetup()
Handle some last-minute setup here.
Definition: Maintenance.php:1164
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transaction on a DB handle.
Definition: Maintenance.php:1462
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
Definition: Maintenance.php:1417
Maintenance\afterFinalSetup
afterFinalSetup()
Execute a callback function at the end of initialisation @stable for overriding.
Definition: Maintenance.php:1239
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
$wgDBadminuser
$wgDBadminuser
Separate username for maintenance tasks.
Definition: DefaultSettings.php:2106
Maintenance\unlockSearchindex
unlockSearchindex( $db)
Unlock the tables.
Definition: Maintenance.php:1488
Maintenance\clearParamsAndArgs
clearParamsAndArgs()
Clear all params and arguments.
Definition: Maintenance.php:842
Config
Interface for configuration instances.
Definition: Config.php:30
Maintenance\formatHelpItems
formatHelpItems(array $items, $heading, $descWidth, $tab)
Definition: Maintenance.php:1137
$wgDBservers
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
Definition: DefaultSettings.php:2262
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:2158
Maintenance\updateSearchIndex
updateSearchIndex( $maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
Definition: Maintenance.php:1509
$wgProfiler
$wgProfiler
Profiler configuration.
Definition: DefaultSettings.php:6943
Maintenance\loadSpecialVars
loadSpecialVars()
Handle the special variables that are global to all scripts @stable for overriding.
Definition: Maintenance.php:1027
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:593
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1034
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
Maintenance\$fileHandle
resource null $fileHandle
Used when creating separate schema files.
Definition: Maintenance.php:136
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
Maintenance\$atLineStart
$atLineStart
Definition: Maintenance.php:489
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:618
$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\$config
Config null $config
Accessible via getConfig()
Definition: Maintenance.php:149
Maintenance\globals
globals()
Potentially debug globals.
Definition: Maintenance.php:1249
$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:551
Maintenance\readlineEmulation
static readlineEmulation( $prompt)
Emulate readline()
Definition: Maintenance.php:1643
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:1574
Maintenance\DB_ADMIN
const DB_ADMIN
Definition: Maintenance.php:62
Maintenance\$mDb
IMaintainableDatabase null $mDb
Used by getDB() / setDB()
Definition: Maintenance.php:127
Maintenance\deleteOption
deleteOption( $name)
Remove an option.
Definition: Maintenance.php:308
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\waitForReplication
waitForReplication()
Wait for replica DBs to catch up.
Definition: Maintenance.php:1443
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
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
Maintenance\supportsOption
supportsOption( $name)
Checks to see if a particular option in supported.
Definition: Maintenance.php:230
Maintenance\isQuiet
isQuiet()
Definition: Maintenance.php:420
Maintenance\activateProfiler
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
Definition: Maintenance.php:814
Maintenance\getHookContainer
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: Maintenance.php:1731
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:317
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1870
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:108
Maintenance\requireTestsAutoloader
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
Definition: Maintenance.php:1721
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:1598
Maintenance\$mDependentParameters
array[] $mDependentParameters
Generic options which might or not be supported by the script.
Definition: Maintenance.php:121
Maintenance\getHookRunner
getHookRunner()
Get a HookRunner for running core hooks.
Definition: Maintenance.php:1746
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1432
Maintenance\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc.
Definition: Maintenance.php:994
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1386
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:495
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:1284
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:291
Maintenance\adjustMemoryLimit
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
Definition: Maintenance.php:801
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Consume and execute all pending updates.
Definition: DeferredUpdates.php:173
Maintenance\purgeRedundantText
purgeRedundantText( $delete=true)
Support function for cleaning up redundant text records.
Definition: Maintenance.php:1321
$self
$self
Definition: doMaintenance.php:63
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:282
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:296
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:1763
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:364
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
Definition: DefaultSettings.php:6840
Maintenance\setAgentAndTriggers
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
Definition: Maintenance.php:652
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1403
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:460
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:431
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
Maintenance\getDir
getDir()
Get the maintenance directory.
Definition: Maintenance.php:1368
$wgDBuser
$wgDBuser
Database username.
Definition: DefaultSettings.php:2071
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:576
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 was set.
Definition: Maintenance.php:267
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:349
$maintClass
string false $maintClass
Definition: Maintenance.php:56
$IP
$IP
Definition: WebStart.php:49
$wgDBadminpassword
$wgDBadminpassword
Separate password for maintenance tasks.
Definition: DefaultSettings.php:2111
Maintenance\outputChanneled
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
Definition: Maintenance.php:510
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:6702
Maintenance\execute
execute()
Do the actual work.
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:1470
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:371
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1102
Maintenance\memoryLimit
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
Definition: Maintenance.php:792