MediaWiki  master
Maintenance.php
Go to the documentation of this file.
1 <?php
28 
59 abstract class Maintenance {
64  public const DB_NONE = 0;
65  public const DB_STD = 1;
66  public const DB_ADMIN = 2;
67 
68  // Const for getStdin()
69  public const STDIN_ALL = -1;
70 
76  protected $mParams = [];
77 
79  protected $mShortParamsMap = [];
80 
82  protected $mArgList = [];
83 
85  protected $mOptions = [];
86 
88  protected $mArgs = [];
89 
91  protected $mAllowUnregisteredOptions = false;
92 
94  protected $mSelf;
95 
97  protected $mQuiet = false;
98  protected $mDbUser, $mDbPass;
99 
101  protected $mDescription = '';
102 
104  protected $mInputLoaded = false;
105 
112  protected $mBatchSize = null;
113 
119  private $mGenericParameters = [];
125  private $mDependentParameters = [];
126 
131  private $mDb = null;
132 
134  private $lastReplicationWait = 0.0;
135 
140  public $fileHandle;
141 
143  private $hookContainer;
144 
146  private $hookRunner;
147 
153  private $config;
154 
159  private $requiredExtensions = [];
160 
172  public $orderedOptions = [];
173 
180  public function __construct() {
181  $this->addDefaultParams();
182  register_shutdown_function( [ $this, 'outputChanneled' ], false );
183  }
184 
192  public static function shouldExecute() {
193  global $wgCommandLineMode;
194 
195  if ( !function_exists( 'debug_backtrace' ) ) {
196  // If someone has a better idea...
197  return $wgCommandLineMode;
198  }
199 
200  $bt = debug_backtrace();
201  $count = count( $bt );
202  if ( $count < 2 ) {
203  return false; // sanity
204  }
205  if ( $bt[0]['class'] !== self::class || $bt[0]['function'] !== 'shouldExecute' ) {
206  return false; // last call should be to this function
207  }
208  $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
209  for ( $i = 1; $i < $count; $i++ ) {
210  if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
211  return false; // previous calls should all be "requires"
212  }
213  }
214 
215  return true;
216  }
217 
226  abstract public function execute();
227 
234  protected function supportsOption( $name ) {
235  return isset( $this->mParams[$name] );
236  }
237 
249  protected function addOption( $name, $description, $required = false,
250  $withArg = false, $shortName = false, $multiOccurrence = false
251  ) {
252  $this->mParams[$name] = [
253  'desc' => $description,
254  'require' => $required,
255  'withArg' => $withArg,
256  'shortName' => $shortName,
257  'multiOccurrence' => $multiOccurrence
258  ];
259 
260  if ( $shortName !== false ) {
261  $this->mShortParamsMap[$shortName] = $name;
262  }
263  }
264 
271  protected function hasOption( $name ) {
272  return isset( $this->mOptions[$name] );
273  }
274 
286  protected function getOption( $name, $default = null ) {
287  if ( $this->hasOption( $name ) ) {
288  return $this->mOptions[$name];
289  } else {
290  return $default;
291  }
292  }
293 
300  protected function addArg( $arg, $description, $required = true ) {
301  $this->mArgList[] = [
302  'name' => $arg,
303  'desc' => $description,
304  'require' => $required
305  ];
306  }
307 
312  protected function deleteOption( $name ) {
313  unset( $this->mParams[$name] );
314  }
315 
321  protected function setAllowUnregisteredOptions( $allow ) {
322  $this->mAllowUnregisteredOptions = $allow;
323  }
324 
329  protected function addDescription( $text ) {
330  $this->mDescription = $text;
331  }
332 
338  protected function hasArg( $argId = 0 ) {
339  if ( func_num_args() === 0 ) {
340  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
341  }
342 
343  return isset( $this->mArgs[$argId] );
344  }
345 
353  protected function getArg( $argId = 0, $default = null ) {
354  if ( func_num_args() === 0 ) {
355  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
356  }
357 
358  return $this->mArgs[$argId] ?? $default;
359  }
360 
368  protected function getBatchSize() {
369  return $this->mBatchSize;
370  }
371 
375  protected function setBatchSize( $s = 0 ) {
376  $this->mBatchSize = $s;
377 
378  // If we support $mBatchSize, show the option.
379  // Used to be in addDefaultParams, but in order for that to
380  // work, subclasses would have to call this function in the constructor
381  // before they called parent::__construct which is just weird
382  // (and really wasn't done).
383  if ( $this->mBatchSize ) {
384  $this->addOption( 'batch-size', 'Run this many operations ' .
385  'per batch, default: ' . $this->mBatchSize, false, true );
386  if ( isset( $this->mParams['batch-size'] ) ) {
387  // This seems a little ugly...
388  $this->mDependentParameters['batch-size'] = $this->mParams['batch-size'];
389  }
390  }
391  }
392 
397  public function getName() {
398  return $this->mSelf;
399  }
400 
407  protected function getStdin( $len = null ) {
408  if ( $len == self::STDIN_ALL ) {
409  return file_get_contents( 'php://stdin' );
410  }
411  $f = fopen( 'php://stdin', 'rt' );
412  if ( !$len ) {
413  return $f;
414  }
415  $input = fgets( $f, $len );
416  fclose( $f );
417 
418  return rtrim( $input );
419  }
420 
424  public function isQuiet() {
425  return $this->mQuiet;
426  }
427 
435  protected function output( $out, $channel = null ) {
436  // This is sometimes called very early, before Setup.php is included.
437  if ( class_exists( MediaWikiServices::class ) ) {
438  // Try to periodically flush buffered metrics to avoid OOMs
439  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
440  if ( $stats->getDataCount() > 1000 ) {
441  MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
442  }
443  }
444 
445  if ( $this->mQuiet ) {
446  return;
447  }
448  if ( $channel === null ) {
449  $this->cleanupChanneled();
450  print $out;
451  } else {
452  $out = preg_replace( '/\n\z/', '', $out );
453  $this->outputChanneled( $out, $channel );
454  }
455  }
456 
464  protected function error( $err, $die = 0 ) {
465  if ( intval( $die ) !== 0 ) {
466  wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
467  $this->fatalError( $err, intval( $die ) );
468  }
469  $this->outputChanneled( false );
470  if (
471  ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
472  !defined( 'MW_PHPUNIT_TEST' )
473  ) {
474  fwrite( STDERR, $err . "\n" );
475  } else {
476  print $err;
477  }
478  }
479 
488  protected function fatalError( $msg, $exitCode = 1 ) {
489  $this->error( $msg );
490  exit( $exitCode );
491  }
492 
493  private $atLineStart = true;
494  private $lastChannel = null;
495 
499  public function cleanupChanneled() {
500  if ( !$this->atLineStart ) {
501  print "\n";
502  $this->atLineStart = true;
503  }
504  }
505 
514  public function outputChanneled( $msg, $channel = null ) {
515  if ( $msg === false ) {
516  $this->cleanupChanneled();
517 
518  return;
519  }
520 
521  // End the current line if necessary
522  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
523  print "\n";
524  }
525 
526  print $msg;
527 
528  $this->atLineStart = false;
529  if ( $channel === null ) {
530  // For unchanneled messages, output trailing newline immediately
531  print "\n";
532  $this->atLineStart = true;
533  }
534  $this->lastChannel = $channel;
535  }
536 
548  public function getDbType() {
549  return self::DB_STD;
550  }
551 
555  protected function addDefaultParams() {
556  # Generic (non-script-dependent) options:
557 
558  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
559  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
560  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
561  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
562  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
563  $this->addOption(
564  'memory-limit',
565  'Set a specific memory limit for the script, '
566  . '"max" for no limit or "default" to avoid changing it',
567  false,
568  true
569  );
570  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
571  "http://en.wikipedia.org. This is sometimes necessary because " .
572  "server name detection may fail in command line scripts.", false, true );
573  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
574 
575  # Save generic options to display them separately in help
576  $this->mGenericParameters = $this->mParams;
577 
578  # Script-dependent options:
579 
580  // If we support a DB, show the options
581  if ( $this->getDbType() > 0 ) {
582  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
583  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
584  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
585  }
586 
587  # Save additional script-dependent options to display
588  # ┬áthem separately in help
589  $this->mDependentParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
590  }
591 
597  public function getConfig() {
598  if ( $this->config === null ) {
599  $this->config = MediaWikiServices::getInstance()->getMainConfig();
600  }
601 
602  return $this->config;
603  }
604 
609  public function setConfig( Config $config ) {
610  $this->config = $config;
611  }
612 
622  protected function requireExtension( $name ) {
623  $this->requiredExtensions[] = $name;
624  }
625 
631  public function checkRequiredExtensions() {
632  $registry = ExtensionRegistry::getInstance();
633  $missing = [];
634  foreach ( $this->requiredExtensions as $name ) {
635  if ( !$registry->isLoaded( $name ) ) {
636  $missing[] = $name;
637  }
638  }
639 
640  if ( $missing ) {
641  if ( count( $missing ) === 1 ) {
642  $msg = 'The "' . $missing[ 0 ] . '" extension must be installed for this script to run. '
643  . 'Please enable it and then try again.';
644  } else {
645  $msg = 'The following extensions must be installed for this script to run: "'
646  . implode( '", "', $missing ) . '". Please enable them and then try again.';
647  }
648  $this->fatalError( $msg );
649  }
650  }
651 
661  public function setAgentAndTriggers() {
662  wfDeprecated( __METHOD__, '1.37' );
663  }
664 
672  public function runChild( $maintClass, $classFile = null ) {
673  // Make sure the class is loaded first
674  if ( !class_exists( $maintClass ) ) {
675  if ( $classFile ) {
676  require_once $classFile;
677  }
678  if ( !class_exists( $maintClass ) ) {
679  $this->fatalError( "Cannot spawn child: $maintClass" );
680  }
681  }
682 
686  $child = new $maintClass();
687  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
688  if ( $this->mDb !== null ) {
689  $child->setDB( $this->mDb );
690  }
691 
692  return $child;
693  }
694 
698  public function setup() {
699  global $IP, $wgCommandLineMode;
700 
701  # Abort if called from a web server
702  # wfIsCLI() is not available yet
703  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
704  $this->fatalError( 'This script must be run from the command line' );
705  }
706 
707  if ( $IP === null ) {
708  $this->fatalError( "\$IP not set, aborting!\n" .
709  '(Did you forget to call parent::__construct() in your maintenance script?)' );
710  }
711 
712  # Make sure we can handle script parameters
713  if ( !ini_get( 'register_argc_argv' ) ) {
714  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
715  }
716 
717  // Send PHP warnings and errors to stderr instead of stdout.
718  // This aids in diagnosing problems, while keeping messages
719  // out of redirected output.
720  if ( ini_get( 'display_errors' ) ) {
721  ini_set( 'display_errors', 'stderr' );
722  }
723 
724  $this->loadParamsAndArgs();
725 
726  # Set the memory limit
727  # Note we need to set it again later in cache LocalSettings changed it
728  $this->adjustMemoryLimit();
729 
730  # Set max execution time to 0 (no limit). PHP.net says that
731  # "When running PHP from the command line the default setting is 0."
732  # But sometimes this doesn't seem to be the case.
733  ini_set( 'max_execution_time', 0 );
734 
735  $wgCommandLineMode = true;
736 
737  # Turn off output buffering if it's on
738  while ( ob_get_level() > 0 ) {
739  ob_end_flush();
740  }
741  }
742 
753  public function memoryLimit() {
754  $limit = $this->getOption( 'memory-limit', 'max' );
755  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
756  return $limit;
757  }
758 
762  protected function adjustMemoryLimit() {
763  $limit = $this->memoryLimit();
764  if ( $limit == 'max' ) {
765  $limit = -1; // no memory limit
766  }
767  if ( $limit != 'default' ) {
768  ini_set( 'memory_limit', $limit );
769  }
770  }
771 
775  protected function activateProfiler() {
777 
778  $output = $this->getOption( 'profiler' );
779  if ( !$output ) {
780  return;
781  }
782 
783  if ( isset( $wgProfiler['class'] ) ) {
784  $class = $wgProfiler['class'];
786  $profiler = new $class(
787  [ 'sampling' => 1, 'output' => [ $output ] ]
788  + $wgProfiler
789  + [ 'threshold' => 0.0 ]
790  );
791  $profiler->setAllowOutput();
792  Profiler::replaceStubInstance( $profiler );
793  }
794 
795  $trxProfiler = Profiler::instance()->getTransactionProfiler();
796  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
797  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
798  }
799 
803  public function clearParamsAndArgs() {
804  $this->mOptions = [];
805  $this->mArgs = [];
806  $this->mInputLoaded = false;
807  }
808 
816  public function loadWithArgv( $argv ) {
817  $options = [];
818  $args = [];
819  $this->orderedOptions = [];
820 
821  # Parse arguments
822  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
823  if ( $arg == '--' ) {
824  # End of options, remainder should be considered arguments
825  $arg = next( $argv );
826  while ( $arg !== false ) {
827  $args[] = $arg;
828  $arg = next( $argv );
829  }
830  break;
831  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
832  # Long options
833  $option = substr( $arg, 2 );
834  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
835  $param = next( $argv );
836  if ( $param === false ) {
837  $this->error( "\nERROR: $option parameter needs a value after it\n" );
838  $this->maybeHelp( true );
839  }
840 
841  $this->setParam( $options, $option, $param );
842  } else {
843  $bits = explode( '=', $option, 2 );
844  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
845  }
846  } elseif ( $arg == '-' ) {
847  # Lonely "-", often used to indicate stdin or stdout.
848  $args[] = $arg;
849  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
850  # Short options
851  $argLength = strlen( $arg );
852  for ( $p = 1; $p < $argLength; $p++ ) {
853  $option = $arg[$p];
854  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
855  $option = $this->mShortParamsMap[$option];
856  }
857 
858  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
859  $param = next( $argv );
860  if ( $param === false ) {
861  $this->error( "\nERROR: $option parameter needs a value after it\n" );
862  $this->maybeHelp( true );
863  }
864  $this->setParam( $options, $option, $param );
865  } else {
866  $this->setParam( $options, $option, 1 );
867  }
868  }
869  } else {
870  $args[] = $arg;
871  }
872  }
873 
874  $this->mOptions = $options;
875  $this->mArgs = $args;
876  $this->loadSpecialVars();
877  $this->mInputLoaded = true;
878  }
879 
892  private function setParam( &$options, $option, $value ) {
893  $this->orderedOptions[] = [ $option, $value ];
894 
895  if ( isset( $this->mParams[$option] ) ) {
896  $multi = $this->mParams[$option]['multiOccurrence'];
897  } else {
898  $multi = false;
899  }
900  $exists = array_key_exists( $option, $options );
901  if ( $multi && $exists ) {
902  $options[$option][] = $value;
903  } elseif ( $multi ) {
904  $options[$option] = [ $value ];
905  } elseif ( !$exists ) {
906  $options[$option] = $value;
907  } else {
908  $this->error( "\nERROR: $option parameter given twice\n" );
909  $this->maybeHelp( true );
910  }
911  }
912 
922  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
923  # If we were given opts or args, set those and return early
924  if ( $self ) {
925  $this->mSelf = $self;
926  $this->mInputLoaded = true;
927  }
928  if ( $opts ) {
929  $this->mOptions = $opts;
930  $this->mInputLoaded = true;
931  }
932  if ( $args ) {
933  $this->mArgs = $args;
934  $this->mInputLoaded = true;
935  }
936 
937  # If we've already loaded input (either by user values or from $argv)
938  # skip on loading it again. The array_shift() will corrupt values if
939  # it's run again and again
940  if ( $this->mInputLoaded ) {
941  $this->loadSpecialVars();
942 
943  return;
944  }
945 
946  global $argv;
947  $this->mSelf = $argv[0];
948  $this->loadWithArgv( array_slice( $argv, 1 ) );
949  }
950 
955  public function validateParamsAndArgs() {
956  $die = false;
957  # Check to make sure we've got all the required options
958  foreach ( $this->mParams as $opt => $info ) {
959  if ( $info['require'] && !$this->hasOption( $opt ) ) {
960  $this->error( "Param $opt required!" );
961  $die = true;
962  }
963  }
964  # Check arg list too
965  foreach ( $this->mArgList as $k => $info ) {
966  if ( $info['require'] && !$this->hasArg( $k ) ) {
967  $this->error( 'Argument <' . $info['name'] . '> required!' );
968  $die = true;
969  }
970  }
971  if ( !$this->mAllowUnregisteredOptions ) {
972  # Check for unexpected options
973  foreach ( $this->mOptions as $opt => $val ) {
974  if ( !$this->supportsOption( $opt ) ) {
975  $this->error( "Unexpected option $opt!" );
976  $die = true;
977  }
978  }
979  }
980 
981  $this->maybeHelp( $die );
982  }
983 
988  protected function loadSpecialVars() {
989  if ( $this->hasOption( 'dbuser' ) ) {
990  $this->mDbUser = $this->getOption( 'dbuser' );
991  }
992  if ( $this->hasOption( 'dbpass' ) ) {
993  $this->mDbPass = $this->getOption( 'dbpass' );
994  }
995  if ( $this->hasOption( 'quiet' ) ) {
996  $this->mQuiet = true;
997  }
998  if ( $this->hasOption( 'batch-size' ) ) {
999  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1000  }
1001  }
1002 
1008  protected function maybeHelp( $force = false ) {
1009  if ( !$force && !$this->hasOption( 'help' ) ) {
1010  return;
1011  }
1012  $this->showHelp();
1013  die( 1 );
1014  }
1015 
1019  protected function showHelp() {
1020  $screenWidth = 80; // TODO: Calculate this!
1021  $tab = " ";
1022  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1023 
1024  ksort( $this->mParams );
1025  $this->mQuiet = false;
1026 
1027  // Description ...
1028  if ( $this->mDescription ) {
1029  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1030  }
1031  $output = "\nUsage: php " . basename( $this->mSelf );
1032 
1033  // ... append parameters ...
1034  if ( $this->mParams ) {
1035  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1036  }
1037 
1038  // ... and append arguments.
1039  if ( $this->mArgList ) {
1040  $output .= ' ';
1041  foreach ( $this->mArgList as $k => $arg ) {
1042  if ( $arg['require'] ) {
1043  $output .= '<' . $arg['name'] . '>';
1044  } else {
1045  $output .= '[' . $arg['name'] . ']';
1046  }
1047  if ( $k < count( $this->mArgList ) - 1 ) {
1048  $output .= ' ';
1049  }
1050  }
1051  }
1052  $this->output( "$output\n\n" );
1053 
1054  $this->formatHelpItems(
1055  $this->mGenericParameters,
1056  'Generic maintenance parameters',
1057  $descWidth, $tab
1058  );
1059 
1060  $this->formatHelpItems(
1061  $this->mDependentParameters,
1062  'Script dependent parameters',
1063  $descWidth, $tab
1064  );
1065 
1066  // Script-specific parameters not defined on construction by
1067  // Maintenance::addDefaultParams()
1068  $scriptSpecificParams = array_diff_key(
1069  # all script parameters:
1070  $this->mParams,
1071  # remove the Maintenance default parameters:
1072  $this->mGenericParameters,
1073  $this->mDependentParameters
1074  );
1075 
1076  $this->formatHelpItems(
1077  $scriptSpecificParams,
1078  'Script specific parameters',
1079  $descWidth, $tab
1080  );
1081 
1082  // Print arguments
1083  if ( count( $this->mArgList ) > 0 ) {
1084  $this->output( "Arguments:\n" );
1085  // Arguments description
1086  foreach ( $this->mArgList as $info ) {
1087  $openChar = $info['require'] ? '<' : '[';
1088  $closeChar = $info['require'] ? '>' : ']';
1089  $this->output(
1090  wordwrap(
1091  "$tab$openChar" . $info['name'] . "$closeChar: " . $info['desc'],
1092  $descWidth,
1093  "\n$tab$tab"
1094  ) . "\n"
1095  );
1096  }
1097  $this->output( "\n" );
1098  }
1099  }
1100 
1101  private function formatHelpItems( array $items, $heading, $descWidth, $tab ) {
1102  if ( $items === [] ) {
1103  return;
1104  }
1105 
1106  $this->output( "$heading:\n" );
1107 
1108  foreach ( $items as $name => $info ) {
1109  if ( $info['shortName'] !== false ) {
1110  $name .= ' (-' . $info['shortName'] . ')';
1111  }
1112  $this->output(
1113  wordwrap(
1114  "$tab--$name: " . strtr( $info['desc'], [ "\n" => "\n$tab$tab" ] ),
1115  $descWidth,
1116  "\n$tab$tab"
1117  ) . "\n"
1118  );
1119  }
1120 
1121  $this->output( "\n" );
1122  }
1123 
1128  public function finalSetup() {
1132 
1133  # Turn off output buffering again, it might have been turned on in the settings files
1134  if ( ob_get_level() ) {
1135  ob_end_flush();
1136  }
1137  # Same with these
1138  $wgCommandLineMode = true;
1139 
1140  # Override $wgServer
1141  if ( $this->hasOption( 'server' ) ) {
1142  $wgServer = $this->getOption( 'server', $wgServer );
1143  }
1144 
1145  # If these were passed, use them
1146  if ( $this->mDbUser ) {
1148  }
1149  if ( $this->mDbPass ) {
1151  }
1152  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1153  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1154  // TODO: once MediaWikiServices::getInstance() starts throwing exceptions
1155  // and not deprecation warnings for premature access to service container,
1156  // we can remove this line. This method is called before Setup.php,
1157  // so it would be guaranteed DBLoadBalancerFactory is not yet initialized.
1158  if ( MediaWikiServices::hasInstance() ) {
1159  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1160  if ( $service ) {
1161  $service->destroy();
1162  }
1163  }
1164  }
1165 
1166  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1169 
1170  if ( $wgDBservers ) {
1174  foreach ( $wgDBservers as $i => $server ) {
1175  $wgDBservers[$i]['user'] = $wgDBuser;
1176  $wgDBservers[$i]['password'] = $wgDBpassword;
1177  }
1178  }
1179  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1180  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1181  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1182  }
1183  // TODO: once MediaWikiServices::getInstance() starts throwing exceptions
1184  // and not deprecation warnings for premature access to service container,
1185  // we can remove this line. This method is called before Setup.php,
1186  // so it would be guaranteed DBLoadBalancerFactory is not yet initialized.
1187  if ( MediaWikiServices::hasInstance() ) {
1188  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1189  if ( $service ) {
1190  $service->destroy();
1191  }
1192  }
1193  }
1194 
1195  // Per-script profiling; useful for debugging
1196  $this->activateProfiler();
1197 
1198  $this->afterFinalSetup();
1199 
1200  $wgShowExceptionDetails = true;
1201  $wgShowHostnames = true;
1202 
1203  Wikimedia\suppressWarnings();
1204  set_time_limit( 0 );
1205  Wikimedia\restoreWarnings();
1206 
1207  $this->adjustMemoryLimit();
1208  }
1209 
1214  protected function afterFinalSetup() {
1215  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1216  call_user_func( MW_CMDLINE_CALLBACK );
1217  }
1218  }
1219 
1224  public function globals() {
1225  if ( $this->hasOption( 'globals' ) ) {
1226  print_r( $GLOBALS );
1227  }
1228  }
1229 
1234  public function shutdown() {
1235  $lbFactory = null;
1236  if (
1237  $this->getDbType() !== self::DB_NONE &&
1238  // Service might be disabled, e.g. when running install.php
1239  !MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancerFactory' )
1240  ) {
1241  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1242  $lbFactory->commitMasterChanges( get_class( $this ) );
1243  // @TODO: make less assumptions about deferred updates being coupled to the DB
1245  }
1246 
1248 
1249  if ( $lbFactory ) {
1250  $lbFactory->commitMasterChanges( 'doMaintenance' );
1251  $lbFactory->shutdown( $lbFactory::SHUTDOWN_NO_CHRONPROT );
1252  }
1253  }
1254 
1259  public function loadSettings() {
1260  global $wgCommandLineMode, $IP;
1261 
1262  if ( isset( $this->mOptions['conf'] ) ) {
1263  $settingsFile = $this->mOptions['conf'];
1264  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1265  $settingsFile = MW_CONFIG_FILE;
1266  } else {
1267  $settingsFile = "$IP/LocalSettings.php";
1268  }
1269  if ( isset( $this->mOptions['wiki'] ) ) {
1270  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1271  define( 'MW_DB', $bits[0] );
1272  define( 'MW_PREFIX', $bits[1] ?? '' );
1273  } elseif ( isset( $this->mOptions['server'] ) ) {
1274  // Provide the option for site admins to detect and configure
1275  // multiple wikis based on server names. This offers --server
1276  // as alternative to --wiki.
1277  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1278  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1279  }
1280 
1281  if ( !is_readable( $settingsFile ) ) {
1282  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1283  "must exist and be readable in the source directory.\n" .
1284  "Use --conf to specify it." );
1285  }
1286  $wgCommandLineMode = true;
1287 
1288  return $settingsFile;
1289  }
1290 
1296  public function purgeRedundantText( $delete = true ) {
1297  # Data should come off the master, wrapped in a transaction
1298  $dbw = $this->getDB( DB_PRIMARY );
1299  $this->beginTransaction( $dbw, __METHOD__ );
1300 
1301  # Get "active" text records via the content table
1302  $cur = [];
1303  $this->output( 'Searching for active text records via contents table...' );
1304  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1305  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1306  foreach ( $res as $row ) {
1307  // @phan-suppress-next-line PhanUndeclaredMethod
1308  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1309  if ( $textId ) {
1310  $cur[] = $textId;
1311  }
1312  }
1313  $this->output( "done.\n" );
1314 
1315  # Get the IDs of all text records not in these sets
1316  $this->output( 'Searching for inactive text records...' );
1317  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1318  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1319  $old = [];
1320  foreach ( $res as $row ) {
1321  $old[] = $row->old_id;
1322  }
1323  $this->output( "done.\n" );
1324 
1325  # Inform the user of what we're going to do
1326  $count = count( $old );
1327  $this->output( "$count inactive items found.\n" );
1328 
1329  # Delete as appropriate
1330  if ( $delete && $count ) {
1331  $this->output( 'Deleting...' );
1332  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1333  $this->output( "done.\n" );
1334  }
1335 
1336  $this->commitTransaction( $dbw, __METHOD__ );
1337  }
1338 
1343  protected function getDir() {
1344  return __DIR__ . '/../';
1345  }
1346 
1361  protected function getDB( $db, $groups = [], $dbDomain = false ) {
1362  if ( $this->mDb === null ) {
1363  return MediaWikiServices::getInstance()
1364  ->getDBLoadBalancerFactory()
1365  ->getMainLB( $dbDomain )
1366  ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1367  }
1368 
1369  return $this->mDb;
1370  }
1371 
1378  public function setDB( IMaintainableDatabase $db ) {
1379  $this->mDb = $db;
1380  }
1381 
1392  protected function beginTransaction( IDatabase $dbw, $fname ) {
1393  $dbw->begin( $fname );
1394  }
1395 
1407  protected function commitTransaction( IDatabase $dbw, $fname ) {
1408  $dbw->commit( $fname );
1409  return $this->waitForReplication();
1410  }
1411 
1418  protected function waitForReplication() {
1419  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1420  $waitSucceeded = $lbFactory->waitForReplication(
1421  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1422  );
1423  $this->lastReplicationWait = microtime( true );
1424  return $waitSucceeded;
1425  }
1426 
1437  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1438  $dbw->rollback( $fname );
1439  }
1440 
1451  protected function countDown( $seconds ) {
1452  if ( $this->isQuiet() ) {
1453  return;
1454  }
1455  for ( $i = $seconds; $i >= 0; $i-- ) {
1456  if ( $i != $seconds ) {
1457  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1458  }
1459  $this->output( $i );
1460  if ( $i ) {
1461  sleep( 1 );
1462  }
1463  }
1464  $this->output( "\n" );
1465  }
1466 
1475  public static function posix_isatty( $fd ) {
1476  if ( !function_exists( 'posix_isatty' ) ) {
1477  return !$fd;
1478  } else {
1479  return posix_isatty( $fd );
1480  }
1481  }
1482 
1488  public static function readconsole( $prompt = '> ' ) {
1489  static $isatty = null;
1490  if ( $isatty === null ) {
1491  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1492  }
1493 
1494  if ( $isatty && function_exists( 'readline' ) ) {
1495  return readline( $prompt );
1496  } else {
1497  if ( $isatty ) {
1498  $st = self::readlineEmulation( $prompt );
1499  } else {
1500  if ( feof( STDIN ) ) {
1501  $st = false;
1502  } else {
1503  $st = fgets( STDIN, 1024 );
1504  }
1505  }
1506  if ( $st === false ) {
1507  return false;
1508  }
1509  $resp = trim( $st );
1510 
1511  return $resp;
1512  }
1513  }
1514 
1520  private static function readlineEmulation( $prompt ) {
1521  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1522  if ( !wfIsWindows() && $bash ) {
1523  $encPrompt = Shell::escape( $prompt );
1524  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1525  $result = Shell::command( $bash, '-c', $command )
1526  ->passStdin()
1527  ->forwardStderr()
1528  ->execute();
1529 
1530  if ( $result->getExitCode() == 0 ) {
1531  return $result->getStdout();
1532  } elseif ( $result->getExitCode() == 127 ) {
1533  // Couldn't execute bash even though we thought we saw it.
1534  // Shell probably spit out an error message, sorry :(
1535  // Fall through to fgets()...
1536  } else {
1537  // EOF/ctrl+D
1538  return false;
1539  }
1540  }
1541 
1542  // Fallback... we'll have no editing controls, EWWW
1543  if ( feof( STDIN ) ) {
1544  return false;
1545  }
1546  print $prompt;
1547 
1548  return fgets( STDIN, 1024 );
1549  }
1550 
1558  public static function getTermSize() {
1559  static $termSize = null;
1560 
1561  if ( $termSize !== null ) {
1562  return $termSize;
1563  }
1564 
1565  $default = [ 80, 50 ];
1566 
1567  if ( wfIsWindows() || Shell::isDisabled() ) {
1568  $termSize = $default;
1569 
1570  return $termSize;
1571  }
1572 
1573  // It's possible to get the screen size with VT-100 terminal escapes,
1574  // but reading the responses is not possible without setting raw mode
1575  // (unless you want to require the user to press enter), and that
1576  // requires an ioctl(), which we can't do. So we have to shell out to
1577  // something that can do the relevant syscalls. There are a few
1578  // options. Linux and Mac OS X both have "stty size" which does the
1579  // job directly.
1580  $result = Shell::command( 'stty', 'size' )->passStdin()->execute();
1581  if ( $result->getExitCode() !== 0 ||
1582  !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m )
1583  ) {
1584  $termSize = $default;
1585 
1586  return $termSize;
1587  }
1588 
1589  $termSize = [ intval( $m[2] ), intval( $m[1] ) ];
1590 
1591  return $termSize;
1592  }
1593 
1598  public static function requireTestsAutoloader() {
1599  require_once __DIR__ . '/../../tests/common/TestsAutoLoader.php';
1600  }
1601 
1608  protected function getHookContainer() {
1609  if ( !$this->hookContainer ) {
1610  $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1611  }
1612  return $this->hookContainer;
1613  }
1614 
1623  protected function getHookRunner() {
1624  if ( !$this->hookRunner ) {
1625  $this->hookRunner = new HookRunner( $this->getHookContainer() );
1626  }
1627  return $this->hookRunner;
1628  }
1629 
1640  protected function parseIntList( $text ) {
1641  $ids = preg_split( '/[\s,;:|]+/', $text );
1642  $ids = array_map(
1643  static function ( $id ) {
1644  return (int)$id;
1645  },
1646  $ids
1647  );
1648  return array_filter( $ids );
1649  }
1650 
1659  protected function validateUserOption( $errorMsg ) {
1660  $user = null;
1661  if ( $this->hasOption( "user" ) ) {
1662  $user = User::newFromName( $this->getOption( 'user' ) );
1663  } elseif ( $this->hasOption( "userid" ) ) {
1664  $user = User::newFromId( $this->getOption( 'userid' ) );
1665  } else {
1666  $this->fatalError( $errorMsg );
1667  }
1668  if ( !$user || !$user->getId() ) {
1669  if ( $this->hasOption( "user" ) ) {
1670  $this->fatalError( "No such user: " . $this->getOption( 'user' ) );
1671  } elseif ( $this->hasOption( "userid" ) ) {
1672  $this->fatalError( "No such user id: " . $this->getOption( 'userid' ) );
1673  }
1674  }
1675 
1676  return $user;
1677  }
1678 }
Maintenance\$mArgList
array $mArgList
Desired/allowed args.
Definition: Maintenance.php:82
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:45
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:643
Maintenance\setParam
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
Definition: Maintenance.php:892
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:1558
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1156
Maintenance\getStdin
getStdin( $len=null)
Return input from stdin.
Definition: Maintenance.php:407
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:119
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:184
Maintenance\getDbType
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition: Maintenance.php:548
Maintenance\maybeHelp
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:1008
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:488
Maintenance\$mDbPass
$mDbPass
Definition: Maintenance.php:98
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:329
Maintenance\setup
setup()
Do some sanity checking and basic setup.
Definition: Maintenance.php:698
Maintenance\$requiredExtensions
array $requiredExtensions
Definition: Maintenance.php:159
Maintenance\runChild
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
Definition: Maintenance.php:672
Maintenance\shutdown
shutdown()
Call before shutdown to run any deferred updates.
Definition: Maintenance.php:1234
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1488
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:7449
Maintenance\$mDescription
string $mDescription
A description of the script, children should change this via addDescription()
Definition: Maintenance.php:101
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:922
Maintenance\showHelp
showHelp()
Definitely show the help.
Definition: Maintenance.php:1019
Maintenance\$mParams
array[] $mParams
Array of desired/allowed params.
Definition: Maintenance.php:76
Maintenance\getName
getName()
Get the script's name.
Definition: Maintenance.php:397
Maintenance\$hookContainer
HookContainer null $hookContainer
Definition: Maintenance.php:143
Maintenance\$hookRunner
HookRunner null $hookRunner
Definition: Maintenance.php:146
User\newFromName
static newFromName( $name, $validate='valid')
Definition: User.php:602
$wgLBFactoryConf
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-primary wiki farm, set the class here to someth...
Definition: DefaultSettings.php:2300
Maintenance\hasArg
hasArg( $argId=0)
Does a given argument exist?
Definition: Maintenance.php:338
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:59
Maintenance\setConfig
setConfig(Config $config)
Definition: Maintenance.php:609
$res
$res
Definition: testCompression.php:57
$wgDBpassword
$wgDBpassword
Database user's password.
Definition: DefaultSettings.php:2102
Maintenance\$lastChannel
$lastChannel
Definition: Maintenance.php:494
Maintenance\$mBatchSize
int null $mBatchSize
Batch size.
Definition: Maintenance.php:112
Maintenance\loadWithArgv
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
Definition: Maintenance.php:816
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:631
Maintenance\finalSetup
finalSetup()
Handle some last-minute setup here.
Definition: Maintenance.php:1128
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transaction on a DB handle.
Definition: Maintenance.php:1437
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
Definition: Maintenance.php:1392
Maintenance\afterFinalSetup
afterFinalSetup()
Execute a callback function at the end of initialisation @stable to override.
Definition: Maintenance.php:1214
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
$wgDBadminuser
$wgDBadminuser
Separate username for maintenance tasks.
Definition: DefaultSettings.php:2132
Maintenance\clearParamsAndArgs
clearParamsAndArgs()
Clear all params and arguments.
Definition: Maintenance.php:803
Config
Interface for configuration instances.
Definition: Config.php:30
Maintenance\formatHelpItems
formatHelpItems(array $items, $heading, $descWidth, $tab)
Definition: Maintenance.php:1101
$wgDBservers
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
Definition: DefaultSettings.php:2288
Maintenance\$mInputLoaded
bool $mInputLoaded
Have we already loaded our user input?
Definition: Maintenance.php:104
$wgDBDefaultGroup
$wgDBDefaultGroup
Default group to use when getting database connections.
Definition: DefaultSettings.php:2184
$wgProfiler
$wgProfiler
Profiler configuration.
Definition: DefaultSettings.php:7524
Maintenance\loadSpecialVars
loadSpecialVars()
Handle the special variables that are global to all scripts @stable to override.
Definition: Maintenance.php:988
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:597
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:996
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:140
Maintenance\$atLineStart
$atLineStart
Definition: Maintenance.php:493
Maintenance\$mArgs
array $mArgs
This is the list of arguments that were actually passed.
Definition: Maintenance.php:88
Maintenance\$lastReplicationWait
float $lastReplicationWait
UNIX timestamp.
Definition: Maintenance.php:134
$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:249
Maintenance\$mDbUser
$mDbUser
Definition: Maintenance.php:98
Maintenance\requireExtension
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
Definition: Maintenance.php:622
$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:172
Maintenance\$config
Config null $config
Accessible via getConfig()
Definition: Maintenance.php:153
Maintenance\globals
globals()
Potentially debug globals.
Definition: Maintenance.php:1224
Maintenance\$mAllowUnregisteredOptions
bool $mAllowUnregisteredOptions
Allow arbitrary options to be passed, or only specified ones?
Definition: Maintenance.php:91
Maintenance\addDefaultParams
addDefaultParams()
Add the default parameters to the scripts.
Definition: Maintenance.php:555
Maintenance\readlineEmulation
static readlineEmulation( $prompt)
Emulate readline()
Definition: Maintenance.php:1520
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:1451
Maintenance\DB_ADMIN
const DB_ADMIN
Definition: Maintenance.php:66
Maintenance\$mDb
IMaintainableDatabase null $mDb
Used by getDB() / setDB()
Definition: Maintenance.php:131
Maintenance\deleteOption
deleteOption( $name)
Remove an option.
Definition: Maintenance.php:312
Maintenance\shouldExecute
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class?...
Definition: Maintenance.php:192
Maintenance\waitForReplication
waitForReplication()
Wait for replica DBs to catch up.
Definition: Maintenance.php:1418
Maintenance\DB_STD
const DB_STD
Definition: Maintenance.php:65
Maintenance\$mOptions
array $mOptions
This is the list of options that were actually passed.
Definition: Maintenance.php:85
Maintenance\validateUserOption
validateUserOption( $errorMsg)
Definition: Maintenance.php:1659
$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:234
Maintenance\isQuiet
isQuiet()
Definition: Maintenance.php:424
Maintenance\activateProfiler
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
Definition: Maintenance.php:775
Maintenance\getHookContainer
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: Maintenance.php:1608
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:321
DB_PRIMARY
const DB_PRIMARY
Definition: defines.php:27
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1730
$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:1598
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:1475
Maintenance\$mDependentParameters
array[] $mDependentParameters
Generic options which might or not be supported by the script.
Definition: Maintenance.php:125
Maintenance\getHookRunner
getHookRunner()
Get a HookRunner for running core hooks.
Definition: Maintenance.php:1623
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1407
Maintenance\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc.
Definition: Maintenance.php:955
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1361
Maintenance\$mQuiet
bool $mQuiet
Special vars for params that are always used.
Definition: Maintenance.php:97
Maintenance\cleanupChanneled
cleanupChanneled()
Clean up channeled output.
Definition: Maintenance.php:499
Maintenance\DB_NONE
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:64
Maintenance\loadSettings
loadSettings()
Generic setup for most installs.
Definition: Maintenance.php:1259
Maintenance\adjustMemoryLimit
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
Definition: Maintenance.php:762
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:1296
$self
$self
Definition: doMaintenance.php:63
Maintenance\$mShortParamsMap
array $mShortParamsMap
Mapping short parameters to long ones.
Definition: Maintenance.php:79
$command
$command
Definition: mcc.php:125
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:286
Maintenance\$mSelf
string null $mSelf
Name of the script currently running.
Definition: Maintenance.php:94
Maintenance\STDIN_ALL
const STDIN_ALL
Definition: Maintenance.php:69
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:300
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:1640
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:368
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
Definition: DefaultSettings.php:7433
Maintenance\setAgentAndTriggers
setAgentAndTriggers()
This method used to be for internal use by doMaintenance.php to apply some optional global state to L...
Definition: Maintenance.php:661
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1378
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:464
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:435
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
Maintenance\getDir
getDir()
Get the maintenance directory.
Definition: Maintenance.php:1343
$wgDBuser
$wgDBuser
Database username.
Definition: DefaultSettings.php:2097
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:555
ExecutableFinder\findInDefaultPaths
static findInDefaultPaths( $names, $versionInfo=false)
Same as locateExecutable(), but checks in getPossibleBinPaths() by default.
Definition: ExecutableFinder.php:96
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option was set.
Definition: Maintenance.php:271
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:353
$maintClass
string false $maintClass
Definition: Maintenance.php:56
$IP
$IP
Definition: WebStart.php:49
$wgDBadminpassword
$wgDBadminpassword
Separate password for maintenance tasks.
Definition: DefaultSettings.php:2137
Maintenance\outputChanneled
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
Definition: Maintenance.php:514
Maintenance\__construct
__construct()
Default constructor.
Definition: Maintenance.php:180
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:7305
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\setBatchSize
setBatchSize( $s=0)
Definition: Maintenance.php:375
wfLogProfilingData
wfLogProfilingData()
Definition: GlobalFunctions.php:1064
Maintenance\memoryLimit
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
Definition: Maintenance.php:753