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 
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->mDependentParameters['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-dependent) 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-dependent 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-dependent options to display
586  # ┬áthem separately in help
587  $this->mDependentParameters = 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  static 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  static 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->fatalError( "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 ( !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 = self::getTermSize()[0];
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  $this->formatHelpItems(
1096  $this->mGenericParameters,
1097  'Generic maintenance parameters',
1098  $descWidth, $tab
1099  );
1100 
1101  $this->formatHelpItems(
1102  $this->mDependentParameters,
1103  'Script dependent parameters',
1104  $descWidth, $tab
1105  );
1106 
1107  // Script-specific parameters not defined on construction by
1108  // Maintenance::addDefaultParams()
1109  $scriptSpecificParams = array_diff_key(
1110  # all script parameters:
1111  $this->mParams,
1112  # remove the Maintenance default parameters:
1113  $this->mGenericParameters,
1114  $this->mDependentParameters
1115  );
1116 
1117  $this->formatHelpItems(
1118  $scriptSpecificParams,
1119  'Script specific parameters',
1120  $descWidth, $tab
1121  );
1122 
1123  // Print arguments
1124  if ( count( $this->mArgList ) > 0 ) {
1125  $this->output( "Arguments:\n" );
1126  // Arguments description
1127  foreach ( $this->mArgList as $info ) {
1128  $openChar = $info['require'] ? '<' : '[';
1129  $closeChar = $info['require'] ? '>' : ']';
1130  $this->output(
1131  wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1132  $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1133  );
1134  }
1135  $this->output( "\n" );
1136  }
1137  }
1138 
1139  private function formatHelpItems( array $items, $heading, $descWidth, $tab ) {
1140  if ( $items === [] ) {
1141  return;
1142  }
1143 
1144  $this->output( "$heading:\n" );
1145 
1146  foreach ( $items as $name => $info ) {
1147  if ( $info['shortName'] !== false ) {
1148  $name .= ' (-' . $info['shortName'] . ')';
1149  }
1150  $this->output(
1151  wordwrap(
1152  "$tab--$name: " . $info['desc'],
1153  $descWidth,
1154  "\n$tab$tab"
1155  ) . "\n"
1156  );
1157  }
1158 
1159  $this->output( "\n" );
1160  }
1161 
1166  public function finalSetup() {
1170 
1171  # Turn off output buffering again, it might have been turned on in the settings files
1172  if ( ob_get_level() ) {
1173  ob_end_flush();
1174  }
1175  # Same with these
1176  $wgCommandLineMode = true;
1177 
1178  # Override $wgServer
1179  if ( $this->hasOption( 'server' ) ) {
1180  $wgServer = $this->getOption( 'server', $wgServer );
1181  }
1182 
1183  # If these were passed, use them
1184  if ( $this->mDbUser ) {
1186  }
1187  if ( $this->mDbPass ) {
1189  }
1190  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1191  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1192 
1193  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1194  if ( $service ) {
1195  $service->destroy();
1196  }
1197  }
1198 
1199  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1202 
1203  if ( $wgDBservers ) {
1207  foreach ( $wgDBservers as $i => $server ) {
1208  $wgDBservers[$i]['user'] = $wgDBuser;
1209  $wgDBservers[$i]['password'] = $wgDBpassword;
1210  }
1211  }
1212  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1213  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1214  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1215  }
1216  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1217  if ( $service ) {
1218  $service->destroy();
1219  }
1220  }
1221 
1222  // Per-script profiling; useful for debugging
1223  $this->activateProfiler();
1224 
1225  $this->afterFinalSetup();
1226 
1227  $wgShowExceptionDetails = true;
1228  $wgShowHostnames = true;
1229 
1230  Wikimedia\suppressWarnings();
1231  set_time_limit( 0 );
1232  Wikimedia\restoreWarnings();
1233 
1234  $this->adjustMemoryLimit();
1235  }
1236 
1241  protected function afterFinalSetup() {
1242  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1243  call_user_func( MW_CMDLINE_CALLBACK );
1244  }
1245  }
1246 
1251  public function globals() {
1252  if ( $this->hasOption( 'globals' ) ) {
1253  print_r( $GLOBALS );
1254  }
1255  }
1256 
1261  public function shutdown() {
1262  $lbFactory = null;
1263  if (
1264  $this->getDbType() !== self::DB_NONE &&
1265  // Service might be disabled, e.g. when running install.php
1266  !MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancerFactory' )
1267  ) {
1268  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1269  $lbFactory->commitMasterChanges( get_class( $this ) );
1270  // @TODO: make less assumptions about deferred updates being coupled to the DB
1272  }
1273 
1275 
1276  if ( $lbFactory ) {
1277  $lbFactory->commitMasterChanges( 'doMaintenance' );
1278  $lbFactory->shutdown( $lbFactory::SHUTDOWN_NO_CHRONPROT );
1279  }
1280  }
1281 
1286  public function loadSettings() {
1287  global $wgCommandLineMode, $IP;
1288 
1289  if ( isset( $this->mOptions['conf'] ) ) {
1290  $settingsFile = $this->mOptions['conf'];
1291  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1292  $settingsFile = MW_CONFIG_FILE;
1293  } else {
1294  $settingsFile = "$IP/LocalSettings.php";
1295  }
1296  if ( isset( $this->mOptions['wiki'] ) ) {
1297  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1298  define( 'MW_DB', $bits[0] );
1299  define( 'MW_PREFIX', $bits[1] ?? '' );
1300  } elseif ( isset( $this->mOptions['server'] ) ) {
1301  // Provide the option for site admins to detect and configure
1302  // multiple wikis based on server names. This offers --server
1303  // as alternative to --wiki.
1304  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1305  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1306  }
1307 
1308  if ( !is_readable( $settingsFile ) ) {
1309  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1310  "must exist and be readable in the source directory.\n" .
1311  "Use --conf to specify it." );
1312  }
1313  $wgCommandLineMode = true;
1314 
1315  return $settingsFile;
1316  }
1317 
1323  public function purgeRedundantText( $delete = true ) {
1324  # Data should come off the master, wrapped in a transaction
1325  $dbw = $this->getDB( DB_MASTER );
1326  $this->beginTransaction( $dbw, __METHOD__ );
1327 
1328  # Get "active" text records via the content table
1329  $cur = [];
1330  $this->output( 'Searching for active text records via contents table...' );
1331  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1332  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1333  foreach ( $res as $row ) {
1334  // @phan-suppress-next-line PhanUndeclaredMethod
1335  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1336  if ( $textId ) {
1337  $cur[] = $textId;
1338  }
1339  }
1340  $this->output( "done.\n" );
1341 
1342  # Get the IDs of all text records not in these sets
1343  $this->output( 'Searching for inactive text records...' );
1344  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1345  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1346  $old = [];
1347  foreach ( $res as $row ) {
1348  $old[] = $row->old_id;
1349  }
1350  $this->output( "done.\n" );
1351 
1352  # Inform the user of what we're going to do
1353  $count = count( $old );
1354  $this->output( "$count inactive items found.\n" );
1355 
1356  # Delete as appropriate
1357  if ( $delete && $count ) {
1358  $this->output( 'Deleting...' );
1359  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1360  $this->output( "done.\n" );
1361  }
1362 
1363  $this->commitTransaction( $dbw, __METHOD__ );
1364  }
1365 
1370  protected function getDir() {
1371  return __DIR__ . '/../';
1372  }
1373 
1388  protected function getDB( $db, $groups = [], $dbDomain = false ) {
1389  if ( $this->mDb === null ) {
1390  return MediaWikiServices::getInstance()
1391  ->getDBLoadBalancerFactory()
1392  ->getMainLB( $dbDomain )
1393  ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1394  }
1395 
1396  return $this->mDb;
1397  }
1398 
1405  public function setDB( IMaintainableDatabase $db ) {
1406  $this->mDb = $db;
1407  }
1408 
1419  protected function beginTransaction( IDatabase $dbw, $fname ) {
1420  $dbw->begin( $fname );
1421  }
1422 
1434  protected function commitTransaction( IDatabase $dbw, $fname ) {
1435  $dbw->commit( $fname );
1436  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1437  $waitSucceeded = $lbFactory->waitForReplication(
1438  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1439  );
1440  $this->lastReplicationWait = microtime( true );
1441  return $waitSucceeded;
1442  }
1443 
1454  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1455  $dbw->rollback( $fname );
1456  }
1457 
1462  private function lockSearchindex( $db ) {
1463  $write = [ 'searchindex' ];
1464  $read = [
1465  'page',
1466  'revision',
1467  'text',
1468  'interwiki',
1469  'l10n_cache',
1470  'user',
1471  'page_restrictions'
1472  ];
1473  $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1474  }
1475 
1480  private function unlockSearchindex( $db ) {
1481  $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1482  }
1483 
1489  private function relockSearchindex( $db ) {
1490  $this->unlockSearchindex( $db );
1491  $this->lockSearchindex( $db );
1492  }
1493 
1501  public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1502  $lockTime = time();
1503 
1504  # Lock searchindex
1505  if ( $maxLockTime ) {
1506  $this->output( " --- Waiting for lock ---" );
1507  $this->lockSearchindex( $dbw );
1508  $lockTime = time();
1509  $this->output( "\n" );
1510  }
1511 
1512  # Loop through the results and do a search update
1513  foreach ( $results as $row ) {
1514  # Allow reads to be processed
1515  if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1516  $this->output( " --- Relocking ---" );
1517  $this->relockSearchindex( $dbw );
1518  $lockTime = time();
1519  $this->output( "\n" );
1520  }
1521  call_user_func( $callback, $row );
1522  }
1523 
1524  # Unlock searchindex
1525  if ( $maxLockTime ) {
1526  $this->output( " --- Unlocking --" );
1527  $this->unlockSearchindex( $dbw );
1528  $this->output( "\n" );
1529  }
1530  }
1531 
1537  public function updateSearchIndexForPage( int $pageId ) {
1538  // Get current revision
1539  $rev = MediaWikiServices::getInstance()
1540  ->getRevisionLookup()
1541  ->getRevisionByPageId( $pageId, 0, IDBAccessObject::READ_LATEST );
1542  $title = null;
1543  if ( $rev ) {
1544  $titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
1545  $title = $titleObj->getPrefixedDBkey();
1546  $this->output( "$title..." );
1547  # Update searchindex
1548  $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent( SlotRecord::MAIN ) );
1549  $u->doUpdate();
1550  $this->output( "\n" );
1551  }
1552 
1553  return $title;
1554  }
1555 
1566  protected function countDown( $seconds ) {
1567  if ( $this->isQuiet() ) {
1568  return;
1569  }
1570  for ( $i = $seconds; $i >= 0; $i-- ) {
1571  if ( $i != $seconds ) {
1572  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1573  }
1574  $this->output( $i );
1575  if ( $i ) {
1576  sleep( 1 );
1577  }
1578  }
1579  $this->output( "\n" );
1580  }
1581 
1590  public static function posix_isatty( $fd ) {
1591  if ( !function_exists( 'posix_isatty' ) ) {
1592  return !$fd;
1593  } else {
1594  return posix_isatty( $fd );
1595  }
1596  }
1597 
1603  public static function readconsole( $prompt = '> ' ) {
1604  static $isatty = null;
1605  if ( $isatty === null ) {
1606  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1607  }
1608 
1609  if ( $isatty && function_exists( 'readline' ) ) {
1610  return readline( $prompt );
1611  } else {
1612  if ( $isatty ) {
1613  $st = self::readlineEmulation( $prompt );
1614  } else {
1615  if ( feof( STDIN ) ) {
1616  $st = false;
1617  } else {
1618  $st = fgets( STDIN, 1024 );
1619  }
1620  }
1621  if ( $st === false ) {
1622  return false;
1623  }
1624  $resp = trim( $st );
1625 
1626  return $resp;
1627  }
1628  }
1629 
1635  private static function readlineEmulation( $prompt ) {
1636  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1637  if ( !wfIsWindows() && $bash ) {
1638  $encPrompt = Shell::escape( $prompt );
1639  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1640  $result = Shell::command( $bash, '-c', $command )
1641  ->passStdin()
1642  ->forwardStderr()
1643  ->execute();
1644 
1645  if ( $result->getExitCode() == 0 ) {
1646  return $result->getStdout();
1647  } elseif ( $result->getExitCode() == 127 ) {
1648  // Couldn't execute bash even though we thought we saw it.
1649  // Shell probably spit out an error message, sorry :(
1650  // Fall through to fgets()...
1651  } else {
1652  // EOF/ctrl+D
1653  return false;
1654  }
1655  }
1656 
1657  // Fallback... we'll have no editing controls, EWWW
1658  if ( feof( STDIN ) ) {
1659  return false;
1660  }
1661  print $prompt;
1662 
1663  return fgets( STDIN, 1024 );
1664  }
1665 
1673  public static function getTermSize() {
1674  static $termSize = null;
1675 
1676  if ( $termSize !== null ) {
1677  return $termSize;
1678  }
1679 
1680  $default = [ 80, 50 ];
1681 
1682  if ( wfIsWindows() || Shell::isDisabled() ) {
1683  $termSize = $default;
1684 
1685  return $termSize;
1686  }
1687 
1688  // It's possible to get the screen size with VT-100 terminal escapes,
1689  // but reading the responses is not possible without setting raw mode
1690  // (unless you want to require the user to press enter), and that
1691  // requires an ioctl(), which we can't do. So we have to shell out to
1692  // something that can do the relevant syscalls. There are a few
1693  // options. Linux and Mac OS X both have "stty size" which does the
1694  // job directly.
1695  $result = Shell::command( 'stty', 'size' )->passStdin()->execute();
1696  if ( $result->getExitCode() !== 0 ||
1697  !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m )
1698  ) {
1699  $termSize = $default;
1700 
1701  return $termSize;
1702  }
1703 
1704  $termSize = [ intval( $m[2] ), intval( $m[1] ) ];
1705 
1706  return $termSize;
1707  }
1708 
1713  public static function requireTestsAutoloader() {
1714  require_once __DIR__ . '/../../tests/common/TestsAutoLoader.php';
1715  }
1716 
1723  protected function getHookContainer() {
1724  if ( !$this->hookContainer ) {
1725  $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1726  }
1727  return $this->hookContainer;
1728  }
1729 
1738  protected function getHookRunner() {
1739  if ( !$this->hookRunner ) {
1740  $this->hookRunner = new HookRunner( $this->getHookContainer() );
1741  }
1742  return $this->hookRunner;
1743  }
1744 
1755  protected function parseIntList( $text ) {
1756  $ids = preg_split( '/[\s,;:|]+/', $text );
1757  $ids = array_map(
1758  static function ( $id ) {
1759  return (int)$id;
1760  },
1761  $ids
1762  );
1763  return array_filter( $ids );
1764  }
1765 }
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: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:1673
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: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:172
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:1537
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\shutdown
shutdown()
Call before shutdown to run any deferred updates.
Definition: Maintenance.php:1261
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1603
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6874
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: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:1489
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: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: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:2076
Maintenance\$lastChannel
$lastChannel
Definition: Maintenance.php:492
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: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:1166
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
Definition: Maintenance.php:1454
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1419
Maintenance\afterFinalSetup
afterFinalSetup()
Execute a callback function at the end of initialisation @stable for overriding.
Definition: Maintenance.php:1241
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:1480
Maintenance\clearParamsAndArgs
clearParamsAndArgs()
Clear all params and arguments.
Definition: Maintenance.php:844
Config
Interface for configuration instances.
Definition: Config.php:30
Maintenance\formatHelpItems
formatHelpItems(array $items, $heading, $descWidth, $tab)
Definition: Maintenance.php:1139
$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:1501
$wgProfiler
$wgProfiler
Profiler configuration.
Definition: DefaultSettings.php:6949
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: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: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\$config
Config null $config
Accessible via getConfig()
Definition: Maintenance.php:149
Maintenance\globals
globals()
Potentially debug globals.
Definition: Maintenance.php:1251
$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:1635
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:1566
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: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
$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: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:1723
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
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:1713
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:1590
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:1738
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1434
Maintenance\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc Stable for overriding.
Definition: Maintenance.php:996
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1388
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:1286
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:803
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:1323
$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: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:1755
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:6846
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:1405
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:1370
$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:575
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: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: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:6708
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:1462
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
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1102
Maintenance\memoryLimit
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
Definition: Maintenance.php:794