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