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  // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
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 
489  protected function fatalError( $msg, $exitCode = 1 ) {
490  $this->error( $msg );
491  exit( $exitCode );
492  }
493 
494  private $atLineStart = true;
495  private $lastChannel = null;
496 
500  public function cleanupChanneled() {
501  if ( !$this->atLineStart ) {
502  print "\n";
503  $this->atLineStart = true;
504  }
505  }
506 
515  public function outputChanneled( $msg, $channel = null ) {
516  if ( $msg === false ) {
517  $this->cleanupChanneled();
518 
519  return;
520  }
521 
522  // End the current line if necessary
523  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
524  print "\n";
525  }
526 
527  print $msg;
528 
529  $this->atLineStart = false;
530  if ( $channel === null ) {
531  // For unchanneled messages, output trailing newline immediately
532  print "\n";
533  $this->atLineStart = true;
534  }
535  $this->lastChannel = $channel;
536  }
537 
549  public function getDbType() {
550  return self::DB_STD;
551  }
552 
556  protected function addDefaultParams() {
557  # Generic (non-script-dependent) options:
558 
559  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
560  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
561  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
562  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
563  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
564  $this->addOption(
565  'memory-limit',
566  'Set a specific memory limit for the script, '
567  . '"max" for no limit or "default" to avoid changing it',
568  false,
569  true
570  );
571  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
572  "http://en.wikipedia.org. This is sometimes necessary because " .
573  "server name detection may fail in command line scripts.", false, true );
574  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
575 
576  # Save generic options to display them separately in help
577  $this->mGenericParameters = $this->mParams;
578 
579  # Script-dependent options:
580 
581  // If we support a DB, show the options
582  if ( $this->getDbType() > 0 ) {
583  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
584  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
585  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
586  }
587 
588  # Save additional script-dependent options to display
589  # ┬áthem separately in help
590  $this->mDependentParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
591  }
592 
598  public function getConfig() {
599  if ( $this->config === null ) {
600  $this->config = MediaWikiServices::getInstance()->getMainConfig();
601  }
602 
603  return $this->config;
604  }
605 
610  public function setConfig( Config $config ) {
611  $this->config = $config;
612  }
613 
623  protected function requireExtension( $name ) {
624  $this->requiredExtensions[] = $name;
625  }
626 
632  public function checkRequiredExtensions() {
633  $registry = ExtensionRegistry::getInstance();
634  $missing = [];
635  foreach ( $this->requiredExtensions as $name ) {
636  if ( !$registry->isLoaded( $name ) ) {
637  $missing[] = $name;
638  }
639  }
640 
641  if ( $missing ) {
642  if ( count( $missing ) === 1 ) {
643  $msg = 'The "' . $missing[ 0 ] . '" extension must be installed for this script to run. '
644  . 'Please enable it and then try again.';
645  } else {
646  $msg = 'The following extensions must be installed for this script to run: "'
647  . implode( '", "', $missing ) . '". Please enable them and then try again.';
648  }
649  $this->fatalError( $msg );
650  }
651  }
652 
662  public function setAgentAndTriggers() {
663  wfDeprecated( __METHOD__, '1.37' );
664  }
665 
673  public function runChild( $maintClass, $classFile = null ) {
674  // Make sure the class is loaded first
675  if ( !class_exists( $maintClass ) ) {
676  if ( $classFile ) {
677  require_once $classFile;
678  }
679  if ( !class_exists( $maintClass ) ) {
680  $this->fatalError( "Cannot spawn child: $maintClass" );
681  }
682  }
683 
687  $child = new $maintClass();
688  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
689  if ( $this->mDb !== null ) {
690  $child->setDB( $this->mDb );
691  }
692 
693  return $child;
694  }
695 
699  public function setup() {
700  global $IP, $wgCommandLineMode;
701 
702  # Abort if called from a web server
703  # wfIsCLI() is not available yet
704  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
705  $this->fatalError( 'This script must be run from the command line' );
706  }
707 
708  if ( $IP === null ) {
709  $this->fatalError( "\$IP not set, aborting!\n" .
710  '(Did you forget to call parent::__construct() in your maintenance script?)' );
711  }
712 
713  # Make sure we can handle script parameters
714  if ( !ini_get( 'register_argc_argv' ) ) {
715  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
716  }
717 
718  // Send PHP warnings and errors to stderr instead of stdout.
719  // This aids in diagnosing problems, while keeping messages
720  // out of redirected output.
721  if ( ini_get( 'display_errors' ) ) {
722  ini_set( 'display_errors', 'stderr' );
723  }
724 
725  $this->loadParamsAndArgs();
726 
727  # Set the memory limit
728  # Note we need to set it again later in cache LocalSettings changed it
729  $this->adjustMemoryLimit();
730 
731  # Set max execution time to 0 (no limit). PHP.net says that
732  # "When running PHP from the command line the default setting is 0."
733  # But sometimes this doesn't seem to be the case.
734  ini_set( 'max_execution_time', 0 );
735 
736  $wgCommandLineMode = true;
737 
738  # Turn off output buffering if it's on
739  while ( ob_get_level() > 0 ) {
740  ob_end_flush();
741  }
742  }
743 
754  public function memoryLimit() {
755  $limit = $this->getOption( 'memory-limit', 'max' );
756  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
757  return $limit;
758  }
759 
763  protected function adjustMemoryLimit() {
764  $limit = $this->memoryLimit();
765  if ( $limit == 'max' ) {
766  $limit = -1; // no memory limit
767  }
768  if ( $limit != 'default' ) {
769  ini_set( 'memory_limit', $limit );
770  }
771  }
772 
776  protected function activateProfiler() {
778 
779  $output = $this->getOption( 'profiler' );
780  if ( !$output ) {
781  return;
782  }
783 
784  if ( isset( $wgProfiler['class'] ) ) {
785  $class = $wgProfiler['class'];
787  $profiler = new $class(
788  [ 'sampling' => 1, 'output' => [ $output ] ]
789  + $wgProfiler
790  + [ 'threshold' => 0.0 ]
791  );
792  $profiler->setAllowOutput();
793  Profiler::replaceStubInstance( $profiler );
794  }
795 
796  $trxProfiler = Profiler::instance()->getTransactionProfiler();
797  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
798  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
799  }
800 
804  public function clearParamsAndArgs() {
805  $this->mOptions = [];
806  $this->mArgs = [];
807  $this->mInputLoaded = false;
808  }
809 
817  public function loadWithArgv( $argv ) {
818  $options = [];
819  $args = [];
820  $this->orderedOptions = [];
821 
822  # Parse arguments
823  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
824  if ( $arg == '--' ) {
825  # End of options, remainder should be considered arguments
826  $arg = next( $argv );
827  while ( $arg !== false ) {
828  $args[] = $arg;
829  $arg = next( $argv );
830  }
831  break;
832  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
833  # Long options
834  $option = substr( $arg, 2 );
835  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
836  $param = next( $argv );
837  if ( $param === false ) {
838  $this->error( "\nERROR: $option parameter needs a value after it\n" );
839  $this->maybeHelp( true );
840  }
841 
842  $this->setParam( $options, $option, $param );
843  } else {
844  $bits = explode( '=', $option, 2 );
845  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
846  }
847  } elseif ( $arg == '-' ) {
848  # Lonely "-", often used to indicate stdin or stdout.
849  $args[] = $arg;
850  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
851  # Short options
852  $argLength = strlen( $arg );
853  for ( $p = 1; $p < $argLength; $p++ ) {
854  $option = $arg[$p];
855  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
856  $option = $this->mShortParamsMap[$option];
857  }
858 
859  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
860  $param = next( $argv );
861  if ( $param === false ) {
862  $this->error( "\nERROR: $option parameter needs a value after it\n" );
863  $this->maybeHelp( true );
864  }
865  $this->setParam( $options, $option, $param );
866  } else {
867  $this->setParam( $options, $option, 1 );
868  }
869  }
870  } else {
871  $args[] = $arg;
872  }
873  }
874 
875  $this->mOptions = $options;
876  $this->mArgs = $args;
877  $this->loadSpecialVars();
878  $this->mInputLoaded = true;
879  }
880 
893  private function setParam( &$options, $option, $value ) {
894  $this->orderedOptions[] = [ $option, $value ];
895 
896  if ( isset( $this->mParams[$option] ) ) {
897  $multi = $this->mParams[$option]['multiOccurrence'];
898  } else {
899  $multi = false;
900  }
901  $exists = array_key_exists( $option, $options );
902  if ( $multi && $exists ) {
903  $options[$option][] = $value;
904  } elseif ( $multi ) {
905  $options[$option] = [ $value ];
906  } elseif ( !$exists ) {
907  $options[$option] = $value;
908  } else {
909  $this->error( "\nERROR: $option parameter given twice\n" );
910  $this->maybeHelp( true );
911  }
912  }
913 
923  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
924  # If we were given opts or args, set those and return early
925  if ( $self ) {
926  $this->mSelf = $self;
927  $this->mInputLoaded = true;
928  }
929  if ( $opts ) {
930  $this->mOptions = $opts;
931  $this->mInputLoaded = true;
932  }
933  if ( $args ) {
934  $this->mArgs = $args;
935  $this->mInputLoaded = true;
936  }
937 
938  # If we've already loaded input (either by user values or from $argv)
939  # skip on loading it again. The array_shift() will corrupt values if
940  # it's run again and again
941  if ( $this->mInputLoaded ) {
942  $this->loadSpecialVars();
943 
944  return;
945  }
946 
947  global $argv;
948  $this->mSelf = $argv[0];
949  $this->loadWithArgv( array_slice( $argv, 1 ) );
950  }
951 
956  public function validateParamsAndArgs() {
957  $die = false;
958  # Check to make sure we've got all the required options
959  foreach ( $this->mParams as $opt => $info ) {
960  if ( $info['require'] && !$this->hasOption( $opt ) ) {
961  $this->error( "Param $opt required!" );
962  $die = true;
963  }
964  }
965  # Check arg list too
966  foreach ( $this->mArgList as $k => $info ) {
967  if ( $info['require'] && !$this->hasArg( $k ) ) {
968  $this->error( 'Argument <' . $info['name'] . '> required!' );
969  $die = true;
970  }
971  }
972  if ( !$this->mAllowUnregisteredOptions ) {
973  # Check for unexpected options
974  foreach ( $this->mOptions as $opt => $val ) {
975  if ( !$this->supportsOption( $opt ) ) {
976  $this->error( "Unexpected option $opt!" );
977  $die = true;
978  }
979  }
980  }
981 
982  $this->maybeHelp( $die );
983  }
984 
989  protected function loadSpecialVars() {
990  if ( $this->hasOption( 'dbuser' ) ) {
991  $this->mDbUser = $this->getOption( 'dbuser' );
992  }
993  if ( $this->hasOption( 'dbpass' ) ) {
994  $this->mDbPass = $this->getOption( 'dbpass' );
995  }
996  if ( $this->hasOption( 'quiet' ) ) {
997  $this->mQuiet = true;
998  }
999  if ( $this->hasOption( 'batch-size' ) ) {
1000  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1001  }
1002  }
1003 
1009  protected function maybeHelp( $force = false ) {
1010  if ( !$force && !$this->hasOption( 'help' ) ) {
1011  return;
1012  }
1013  $this->showHelp();
1014  die( 1 );
1015  }
1016 
1020  protected function showHelp() {
1021  $screenWidth = 80; // TODO: Calculate this!
1022  $tab = " ";
1023  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1024 
1025  ksort( $this->mParams );
1026  $this->mQuiet = false;
1027 
1028  // Description ...
1029  if ( $this->mDescription ) {
1030  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1031  }
1032  $output = "\nUsage: php " . basename( $this->mSelf );
1033 
1034  // ... append parameters ...
1035  if ( $this->mParams ) {
1036  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1037  }
1038 
1039  // ... and append arguments.
1040  if ( $this->mArgList ) {
1041  $output .= ' ';
1042  foreach ( $this->mArgList as $k => $arg ) {
1043  if ( $arg['require'] ) {
1044  $output .= '<' . $arg['name'] . '>';
1045  } else {
1046  $output .= '[' . $arg['name'] . ']';
1047  }
1048  if ( $k < count( $this->mArgList ) - 1 ) {
1049  $output .= ' ';
1050  }
1051  }
1052  }
1053  $this->output( "$output\n\n" );
1054 
1055  $this->formatHelpItems(
1056  $this->mGenericParameters,
1057  'Generic maintenance parameters',
1058  $descWidth, $tab
1059  );
1060 
1061  $this->formatHelpItems(
1062  $this->mDependentParameters,
1063  'Script dependent parameters',
1064  $descWidth, $tab
1065  );
1066 
1067  // Script-specific parameters not defined on construction by
1068  // Maintenance::addDefaultParams()
1069  $scriptSpecificParams = array_diff_key(
1070  # all script parameters:
1071  $this->mParams,
1072  # remove the Maintenance default parameters:
1073  $this->mGenericParameters,
1074  $this->mDependentParameters
1075  );
1076 
1077  $this->formatHelpItems(
1078  $scriptSpecificParams,
1079  'Script specific parameters',
1080  $descWidth, $tab
1081  );
1082 
1083  // Print arguments
1084  if ( count( $this->mArgList ) > 0 ) {
1085  $this->output( "Arguments:\n" );
1086  // Arguments description
1087  foreach ( $this->mArgList as $info ) {
1088  $openChar = $info['require'] ? '<' : '[';
1089  $closeChar = $info['require'] ? '>' : ']';
1090  $this->output(
1091  wordwrap(
1092  "$tab$openChar" . $info['name'] . "$closeChar: " . $info['desc'],
1093  $descWidth,
1094  "\n$tab$tab"
1095  ) . "\n"
1096  );
1097  }
1098  $this->output( "\n" );
1099  }
1100  }
1101 
1102  private function formatHelpItems( array $items, $heading, $descWidth, $tab ) {
1103  if ( $items === [] ) {
1104  return;
1105  }
1106 
1107  $this->output( "$heading:\n" );
1108 
1109  foreach ( $items as $name => $info ) {
1110  if ( $info['shortName'] !== false ) {
1111  $name .= ' (-' . $info['shortName'] . ')';
1112  }
1113  $this->output(
1114  wordwrap(
1115  "$tab--$name: " . strtr( $info['desc'], [ "\n" => "\n$tab$tab" ] ),
1116  $descWidth,
1117  "\n$tab$tab"
1118  ) . "\n"
1119  );
1120  }
1121 
1122  $this->output( "\n" );
1123  }
1124 
1129  public function finalSetup() {
1133 
1134  # Turn off output buffering again, it might have been turned on in the settings files
1135  if ( ob_get_level() ) {
1136  ob_end_flush();
1137  }
1138  # Same with these
1139  $wgCommandLineMode = true;
1140 
1141  # Override $wgServer
1142  if ( $this->hasOption( 'server' ) ) {
1143  $wgServer = $this->getOption( 'server', $wgServer );
1144  }
1145 
1146  # If these were passed, use them
1147  if ( $this->mDbUser ) {
1149  }
1150  if ( $this->mDbPass ) {
1152  }
1153  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1154  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1155  // TODO: once MediaWikiServices::getInstance() starts throwing exceptions
1156  // and not deprecation warnings for premature access to service container,
1157  // we can remove this line. This method is called before Setup.php,
1158  // so it would be guaranteed DBLoadBalancerFactory is not yet initialized.
1159  if ( MediaWikiServices::hasInstance() ) {
1160  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1161  if ( $service ) {
1162  $service->destroy();
1163  }
1164  }
1165  }
1166 
1167  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1170 
1171  if ( $wgDBservers ) {
1175  foreach ( $wgDBservers as $i => $server ) {
1176  $wgDBservers[$i]['user'] = $wgDBuser;
1177  $wgDBservers[$i]['password'] = $wgDBpassword;
1178  }
1179  }
1180  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1181  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1182  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1183  }
1184  // TODO: once MediaWikiServices::getInstance() starts throwing exceptions
1185  // and not deprecation warnings for premature access to service container,
1186  // we can remove this line. This method is called before Setup.php,
1187  // so it would be guaranteed DBLoadBalancerFactory is not yet initialized.
1188  if ( MediaWikiServices::hasInstance() ) {
1189  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1190  if ( $service ) {
1191  $service->destroy();
1192  }
1193  }
1194  }
1195 
1196  // Per-script profiling; useful for debugging
1197  $this->activateProfiler();
1198 
1199  $this->afterFinalSetup();
1200 
1201  $wgShowExceptionDetails = true;
1202  $wgShowHostnames = true;
1203 
1204  Wikimedia\suppressWarnings();
1205  set_time_limit( 0 );
1206  Wikimedia\restoreWarnings();
1207 
1208  $this->adjustMemoryLimit();
1209  }
1210 
1215  protected function afterFinalSetup() {
1216  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1217  call_user_func( MW_CMDLINE_CALLBACK );
1218  }
1219  }
1220 
1225  public function globals() {
1226  if ( $this->hasOption( 'globals' ) ) {
1227  print_r( $GLOBALS );
1228  }
1229  }
1230 
1240  public function shutdown() {
1241  $lbFactory = null;
1242  if (
1243  $this->getDbType() !== self::DB_NONE &&
1244  // Service might be disabled, e.g. when running install.php
1245  !MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancerFactory' )
1246  ) {
1247  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1248  $lbFactory->commitPrimaryChanges( get_class( $this ) );
1249 
1251  }
1252 
1253  // Handle external profiler outputs
1254  // FIXME: Handle embedded outputs as well, such as ProfilerOutputText (T253547)
1255  $profiler = Profiler::instance();
1256  $profiler->logData();
1257 
1259  MediaWikiServices::getInstance()->getStatsdDataFactory(),
1260  $this->getConfig()
1261  );
1262 
1263  if ( $lbFactory ) {
1264  $lbFactory->commitPrimaryChanges( 'doMaintenance' );
1265  $lbFactory->shutdown( $lbFactory::SHUTDOWN_NO_CHRONPROT );
1266  }
1267  }
1268 
1273  public function loadSettings() {
1274  global $wgCommandLineMode, $IP;
1275 
1276  if ( isset( $this->mOptions['conf'] ) ) {
1277  $settingsFile = $this->mOptions['conf'];
1278  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1279  $settingsFile = MW_CONFIG_FILE;
1280  } else {
1281  $settingsFile = "$IP/LocalSettings.php";
1282  }
1283  if ( isset( $this->mOptions['wiki'] ) ) {
1284  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1285  define( 'MW_DB', $bits[0] );
1286  define( 'MW_PREFIX', $bits[1] ?? '' );
1287  } elseif ( isset( $this->mOptions['server'] ) ) {
1288  // Provide the option for site admins to detect and configure
1289  // multiple wikis based on server names. This offers --server
1290  // as alternative to --wiki.
1291  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1292  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1293  }
1294 
1295  if ( !is_readable( $settingsFile ) ) {
1296  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1297  "must exist and be readable in the source directory.\n" .
1298  "Use --conf to specify it." );
1299  }
1300  $wgCommandLineMode = true;
1301 
1302  return $settingsFile;
1303  }
1304 
1310  public function purgeRedundantText( $delete = true ) {
1311  # Data should come off the master, wrapped in a transaction
1312  $dbw = $this->getDB( DB_PRIMARY );
1313  $this->beginTransaction( $dbw, __METHOD__ );
1314 
1315  # Get "active" text records via the content table
1316  $cur = [];
1317  $this->output( 'Searching for active text records via contents table...' );
1318  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1319  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1320  foreach ( $res as $row ) {
1321  // @phan-suppress-next-line PhanUndeclaredMethod
1322  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1323  if ( $textId ) {
1324  $cur[] = $textId;
1325  }
1326  }
1327  $this->output( "done.\n" );
1328 
1329  # Get the IDs of all text records not in these sets
1330  $this->output( 'Searching for inactive text records...' );
1331  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1332  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1333  $old = [];
1334  foreach ( $res as $row ) {
1335  $old[] = $row->old_id;
1336  }
1337  $this->output( "done.\n" );
1338 
1339  # Inform the user of what we're going to do
1340  $count = count( $old );
1341  $this->output( "$count inactive items found.\n" );
1342 
1343  # Delete as appropriate
1344  if ( $delete && $count ) {
1345  $this->output( 'Deleting...' );
1346  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1347  $this->output( "done.\n" );
1348  }
1349 
1350  $this->commitTransaction( $dbw, __METHOD__ );
1351  }
1352 
1357  protected function getDir() {
1358  return __DIR__ . '/../';
1359  }
1360 
1375  protected function getDB( $db, $groups = [], $dbDomain = false ) {
1376  if ( $this->mDb === null ) {
1377  return MediaWikiServices::getInstance()
1378  ->getDBLoadBalancerFactory()
1379  ->getMainLB( $dbDomain )
1380  ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1381  }
1382 
1383  return $this->mDb;
1384  }
1385 
1392  public function setDB( IMaintainableDatabase $db ) {
1393  $this->mDb = $db;
1394  }
1395 
1406  protected function beginTransaction( IDatabase $dbw, $fname ) {
1407  $dbw->begin( $fname );
1408  }
1409 
1421  protected function commitTransaction( IDatabase $dbw, $fname ) {
1422  $dbw->commit( $fname );
1423  return $this->waitForReplication();
1424  }
1425 
1432  protected function waitForReplication() {
1433  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1434  $waitSucceeded = $lbFactory->waitForReplication(
1435  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1436  );
1437  $this->lastReplicationWait = microtime( true );
1438  return $waitSucceeded;
1439  }
1440 
1451  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1452  $dbw->rollback( $fname );
1453  }
1454 
1465  protected function countDown( $seconds ) {
1466  if ( $this->isQuiet() ) {
1467  return;
1468  }
1469  for ( $i = $seconds; $i >= 0; $i-- ) {
1470  if ( $i != $seconds ) {
1471  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1472  }
1473  $this->output( $i );
1474  if ( $i ) {
1475  sleep( 1 );
1476  }
1477  }
1478  $this->output( "\n" );
1479  }
1480 
1489  public static function posix_isatty( $fd ) {
1490  if ( !function_exists( 'posix_isatty' ) ) {
1491  return !$fd;
1492  } else {
1493  return posix_isatty( $fd );
1494  }
1495  }
1496 
1502  public static function readconsole( $prompt = '> ' ) {
1503  static $isatty = null;
1504  if ( $isatty === null ) {
1505  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1506  }
1507 
1508  if ( $isatty && function_exists( 'readline' ) ) {
1509  return readline( $prompt );
1510  } else {
1511  if ( $isatty ) {
1512  $st = self::readlineEmulation( $prompt );
1513  } else {
1514  if ( feof( STDIN ) ) {
1515  $st = false;
1516  } else {
1517  $st = fgets( STDIN, 1024 );
1518  }
1519  }
1520  if ( $st === false ) {
1521  return false;
1522  }
1523  $resp = trim( $st );
1524 
1525  return $resp;
1526  }
1527  }
1528 
1534  private static function readlineEmulation( $prompt ) {
1535  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1536  if ( !wfIsWindows() && $bash ) {
1537  $encPrompt = Shell::escape( $prompt );
1538  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1539  $result = Shell::command( $bash, '-c', $command )
1540  ->passStdin()
1541  ->forwardStderr()
1542  ->execute();
1543 
1544  if ( $result->getExitCode() == 0 ) {
1545  return $result->getStdout();
1546  } elseif ( $result->getExitCode() == 127 ) {
1547  // Couldn't execute bash even though we thought we saw it.
1548  // Shell probably spit out an error message, sorry :(
1549  // Fall through to fgets()...
1550  } else {
1551  // EOF/ctrl+D
1552  return false;
1553  }
1554  }
1555 
1556  // Fallback... we'll have no editing controls, EWWW
1557  if ( feof( STDIN ) ) {
1558  return false;
1559  }
1560  print $prompt;
1561 
1562  return fgets( STDIN, 1024 );
1563  }
1564 
1572  public static function getTermSize() {
1573  static $termSize = null;
1574 
1575  if ( $termSize !== null ) {
1576  return $termSize;
1577  }
1578 
1579  $default = [ 80, 50 ];
1580 
1581  if ( wfIsWindows() || Shell::isDisabled() ) {
1582  $termSize = $default;
1583 
1584  return $termSize;
1585  }
1586 
1587  // It's possible to get the screen size with VT-100 terminal escapes,
1588  // but reading the responses is not possible without setting raw mode
1589  // (unless you want to require the user to press enter), and that
1590  // requires an ioctl(), which we can't do. So we have to shell out to
1591  // something that can do the relevant syscalls. There are a few
1592  // options. Linux and Mac OS X both have "stty size" which does the
1593  // job directly.
1594  $result = Shell::command( 'stty', 'size' )->passStdin()->execute();
1595  if ( $result->getExitCode() !== 0 ||
1596  !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m )
1597  ) {
1598  $termSize = $default;
1599 
1600  return $termSize;
1601  }
1602 
1603  $termSize = [ intval( $m[2] ), intval( $m[1] ) ];
1604 
1605  return $termSize;
1606  }
1607 
1612  public static function requireTestsAutoloader() {
1613  require_once __DIR__ . '/../../tests/common/TestsAutoLoader.php';
1614  }
1615 
1622  protected function getHookContainer() {
1623  if ( !$this->hookContainer ) {
1624  $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1625  }
1626  return $this->hookContainer;
1627  }
1628 
1637  protected function getHookRunner() {
1638  if ( !$this->hookRunner ) {
1639  $this->hookRunner = new HookRunner( $this->getHookContainer() );
1640  }
1641  return $this->hookRunner;
1642  }
1643 
1654  protected function parseIntList( $text ) {
1655  $ids = preg_split( '/[\s,;:|]+/', $text );
1656  $ids = array_map(
1657  static function ( $id ) {
1658  return (int)$id;
1659  },
1660  $ids
1661  );
1662  return array_filter( $ids );
1663  }
1664 
1673  protected function validateUserOption( $errorMsg ) {
1674  $user = null;
1675  if ( $this->hasOption( "user" ) ) {
1676  $user = User::newFromName( $this->getOption( 'user' ) );
1677  } elseif ( $this->hasOption( "userid" ) ) {
1678  $user = User::newFromId( $this->getOption( 'userid' ) );
1679  } else {
1680  $this->fatalError( $errorMsg );
1681  }
1682  if ( !$user || !$user->getId() ) {
1683  if ( $this->hasOption( "user" ) ) {
1684  $this->fatalError( "No such user: " . $this->getOption( 'user' ) );
1685  } elseif ( $this->hasOption( "userid" ) ) {
1686  $this->fatalError( "No such user id: " . $this->getOption( 'userid' ) );
1687  }
1688  }
1689 
1690  return $user;
1691  }
1692 }
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:648
Maintenance\setParam
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
Definition: Maintenance.php:893
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:1572
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1185
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:200
Maintenance\getDbType
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition: Maintenance.php:549
Maintenance\maybeHelp
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:1009
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:489
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:699
Maintenance\$requiredExtensions
array $requiredExtensions
Definition: Maintenance.php:159
Maintenance\runChild
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
Definition: Maintenance.php:673
Maintenance\shutdown
shutdown()
Call before exiting CLI process for the last DB commit, and flush any remaining buffers and other def...
Definition: Maintenance.php:1240
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1502
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:7426
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:923
Maintenance\showHelp
showHelp()
Definitely show the help.
Definition: Maintenance.php:1020
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:607
$wgLBFactoryConf
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-primary wiki farm, set the class here to someth...
Definition: DefaultSettings.php:2298
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:610
$res
$res
Definition: testCompression.php:57
$wgDBpassword
$wgDBpassword
Database user's password.
Definition: DefaultSettings.php:2100
Maintenance\$lastChannel
$lastChannel
Definition: Maintenance.php:495
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:817
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:632
Maintenance\finalSetup
finalSetup()
Handle some last-minute setup here.
Definition: Maintenance.php:1129
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transaction on a DB handle.
Definition: Maintenance.php:1451
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
Definition: Maintenance.php:1406
Maintenance\afterFinalSetup
afterFinalSetup()
Execute a callback function at the end of initialisation @stable to override.
Definition: Maintenance.php:1215
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:134
$wgDBadminuser
$wgDBadminuser
Separate username for maintenance tasks.
Definition: DefaultSettings.php:2130
Maintenance\clearParamsAndArgs
clearParamsAndArgs()
Clear all params and arguments.
Definition: Maintenance.php:804
Config
Interface for configuration instances.
Definition: Config.php:30
Maintenance\formatHelpItems
formatHelpItems(array $items, $heading, $descWidth, $tab)
Definition: Maintenance.php:1102
$wgDBservers
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
Definition: DefaultSettings.php:2286
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:2182
$wgProfiler
$wgProfiler
Profiler configuration.
Definition: DefaultSettings.php:7514
Maintenance\loadSpecialVars
loadSpecialVars()
Handle the special variables that are global to all scripts @stable to override.
Definition: Maintenance.php:989
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:598
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Definition: GlobalFunctions.php:989
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:494
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:623
$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:1225
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:556
Maintenance\readlineEmulation
static readlineEmulation( $prompt)
Emulate readline()
Definition: Maintenance.php:1534
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:1465
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:1432
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:1673
$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:776
Maintenance\getHookContainer
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: Maintenance.php:1622
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:1695
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:110
Maintenance\requireTestsAutoloader
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
Definition: Maintenance.php:1612
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:1489
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:1637
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1421
Maintenance\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc.
Definition: Maintenance.php:956
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1375
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:500
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:1273
Maintenance\adjustMemoryLimit
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
Definition: Maintenance.php:763
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:1310
$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:1654
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:7410
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:662
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1392
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:1357
$wgDBuser
$wgDBuser
Database username.
Definition: DefaultSettings.php:2095
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:554
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:2135
Maintenance\outputChanneled
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
Definition: Maintenance.php:515
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:7282
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
Maintenance\memoryLimit
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
Definition: Maintenance.php:754