MediaWiki  master
Maintenance.php
Go to the documentation of this file.
1 <?php
23 // phpcs:disable MediaWiki.Classes.UnsortedUseStatements.UnsortedUse
24 
25 define( 'MW_ENTRY_POINT', 'cli' );
26 
27 // Bail on old versions of PHP, or if composer has not been run yet to install
28 // dependencies.
29 require_once __DIR__ . '/../includes/PHPVersionCheck.php';
30 wfEntryPointCheck( 'text' );
31 
34 
40 // Define this so scripts can easily find doMaintenance.php
41 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' );
42 
46 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
47 
52 $maintClass = false;
53 
54 // Some extensions rely on MW_INSTALL_PATH to find core files to include. Setting it here helps them
55 // if they're included by a core script (like DatabaseUpdater) after Maintenance.php has already
56 // been run.
57 if ( strval( getenv( 'MW_INSTALL_PATH' ) ) === '' ) {
58  putenv( 'MW_INSTALL_PATH=' . realpath( __DIR__ . '/..' ) );
59 }
60 
66 
88 abstract class Maintenance {
93  const DB_NONE = 0;
94  const DB_STD = 1;
95  const DB_ADMIN = 2;
96 
97  // Const for getStdin()
98  const STDIN_ALL = 'all';
99 
105  protected $mParams = [];
106 
107  // Array of mapping short parameters to long ones
108  protected $mShortParamsMap = [];
109 
110  // Array of desired/allowed args
111  protected $mArgList = [];
112 
113  // This is the list of options that were actually passed
114  protected $mOptions = [];
115 
116  // This is the list of arguments that were actually passed
117  protected $mArgs = [];
118 
119  // Allow arbitrary options to be passed, or only specified ones?
120  protected $mAllowUnregisteredOptions = false;
121 
122  // Name of the script currently running
123  protected $mSelf;
124 
125  // Special vars for params that are always used
126  protected $mQuiet = false;
127  protected $mDbUser, $mDbPass;
128 
129  // A description of the script, children should change this via addDescription()
130  protected $mDescription = '';
131 
132  // Have we already loaded our user input?
133  protected $mInputLoaded = false;
134 
141  protected $mBatchSize = null;
142 
148  private $mGenericParameters = [];
154  private $mDependantParameters = [];
155 
160  private $mDb = null;
161 
163  private $lastReplicationWait = 0.0;
164 
169  public $fileHandle;
170 
176  private $config;
177 
182  private $requiredExtensions = [];
183 
195  public $orderedOptions = [];
196 
201  public function __construct() {
202  global $IP;
203  $IP = getenv( 'MW_INSTALL_PATH' );
204 
205  $this->addDefaultParams();
206  register_shutdown_function( [ $this, 'outputChanneled' ], false );
207  }
208 
216  public static function shouldExecute() {
217  global $wgCommandLineMode;
218 
219  if ( !function_exists( 'debug_backtrace' ) ) {
220  // If someone has a better idea...
221  return $wgCommandLineMode;
222  }
223 
224  $bt = debug_backtrace();
225  $count = count( $bt );
226  if ( $count < 2 ) {
227  return false; // sanity
228  }
229  if ( $bt[0]['class'] !== self::class || $bt[0]['function'] !== 'shouldExecute' ) {
230  return false; // last call should be to this function
231  }
232  $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
233  for ( $i = 1; $i < $count; $i++ ) {
234  if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
235  return false; // previous calls should all be "requires"
236  }
237  }
238 
239  return true;
240  }
241 
250  abstract public function execute();
251 
258  protected function supportsOption( $name ) {
259  return isset( $this->mParams[$name] );
260  }
261 
273  protected function addOption( $name, $description, $required = false,
274  $withArg = false, $shortName = false, $multiOccurrence = false
275  ) {
276  $this->mParams[$name] = [
277  'desc' => $description,
278  'require' => $required,
279  'withArg' => $withArg,
280  'shortName' => $shortName,
281  'multiOccurrence' => $multiOccurrence
282  ];
283 
284  if ( $shortName !== false ) {
285  $this->mShortParamsMap[$shortName] = $name;
286  }
287  }
288 
294  protected function hasOption( $name ) {
295  return isset( $this->mOptions[$name] );
296  }
297 
308  protected function getOption( $name, $default = null ) {
309  if ( $this->hasOption( $name ) ) {
310  return $this->mOptions[$name];
311  } else {
312  // Set it so we don't have to provide the default again
313  $this->mOptions[$name] = $default;
314 
315  return $this->mOptions[$name];
316  }
317  }
318 
325  protected function addArg( $arg, $description, $required = true ) {
326  $this->mArgList[] = [
327  'name' => $arg,
328  'desc' => $description,
329  'require' => $required
330  ];
331  }
332 
337  protected function deleteOption( $name ) {
338  unset( $this->mParams[$name] );
339  }
340 
346  protected function setAllowUnregisteredOptions( $allow ) {
347  $this->mAllowUnregisteredOptions = $allow;
348  }
349 
354  protected function addDescription( $text ) {
355  $this->mDescription = $text;
356  }
357 
363  protected function hasArg( $argId = 0 ) {
364  if ( func_num_args() === 0 ) {
365  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
366  }
367 
368  return isset( $this->mArgs[$argId] );
369  }
370 
377  protected function getArg( $argId = 0, $default = null ) {
378  if ( func_num_args() === 0 ) {
379  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
380  }
381 
382  return $this->mArgs[$argId] ?? $default;
383  }
384 
392  protected function getBatchSize() {
393  return $this->mBatchSize;
394  }
395 
400  protected function setBatchSize( $s = 0 ) {
401  $this->mBatchSize = $s;
402 
403  // If we support $mBatchSize, show the option.
404  // Used to be in addDefaultParams, but in order for that to
405  // work, subclasses would have to call this function in the constructor
406  // before they called parent::__construct which is just weird
407  // (and really wasn't done).
408  if ( $this->mBatchSize ) {
409  $this->addOption( 'batch-size', 'Run this many operations ' .
410  'per batch, default: ' . $this->mBatchSize, false, true );
411  if ( isset( $this->mParams['batch-size'] ) ) {
412  // This seems a little ugly...
413  $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
414  }
415  }
416  }
417 
422  public function getName() {
423  return $this->mSelf;
424  }
425 
432  protected function getStdin( $len = null ) {
433  if ( $len == self::STDIN_ALL ) {
434  return file_get_contents( 'php://stdin' );
435  }
436  $f = fopen( 'php://stdin', 'rt' );
437  if ( !$len ) {
438  return $f;
439  }
440  $input = fgets( $f, $len );
441  fclose( $f );
442 
443  return rtrim( $input );
444  }
445 
449  public function isQuiet() {
450  return $this->mQuiet;
451  }
452 
459  protected function output( $out, $channel = null ) {
460  // This is sometimes called very early, before Setup.php is included.
461  if ( class_exists( MediaWikiServices::class ) ) {
462  // Try to periodically flush buffered metrics to avoid OOMs
463  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
464  if ( $stats->getDataCount() > 1000 ) {
465  MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
466  }
467  }
468 
469  if ( $this->mQuiet ) {
470  return;
471  }
472  if ( $channel === null ) {
473  $this->cleanupChanneled();
474  print $out;
475  } else {
476  $out = preg_replace( '/\n\z/', '', $out );
477  $this->outputChanneled( $out, $channel );
478  }
479  }
480 
487  protected function error( $err, $die = 0 ) {
488  if ( intval( $die ) !== 0 ) {
489  wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
490  $this->fatalError( $err, intval( $die ) );
491  }
492  $this->outputChanneled( false );
493  if (
494  ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
495  !defined( 'MW_PHPUNIT_TEST' )
496  ) {
497  fwrite( STDERR, $err . "\n" );
498  } else {
499  print $err;
500  }
501  }
502 
510  protected function fatalError( $msg, $exitCode = 1 ) {
511  $this->error( $msg );
512  exit( $exitCode );
513  }
514 
515  private $atLineStart = true;
516  private $lastChannel = null;
517 
521  public function cleanupChanneled() {
522  if ( !$this->atLineStart ) {
523  print "\n";
524  $this->atLineStart = true;
525  }
526  }
527 
536  public function outputChanneled( $msg, $channel = null ) {
537  if ( $msg === false ) {
538  $this->cleanupChanneled();
539 
540  return;
541  }
542 
543  // End the current line if necessary
544  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
545  print "\n";
546  }
547 
548  print $msg;
549 
550  $this->atLineStart = false;
551  if ( $channel === null ) {
552  // For unchanneled messages, output trailing newline immediately
553  print "\n";
554  $this->atLineStart = true;
555  }
556  $this->lastChannel = $channel;
557  }
558 
569  public function getDbType() {
570  return self::DB_STD;
571  }
572 
576  protected function addDefaultParams() {
577  # Generic (non script dependant) options:
578 
579  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
580  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
581  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
582  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
583  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
584  $this->addOption(
585  'memory-limit',
586  'Set a specific memory limit for the script, '
587  . '"max" for no limit or "default" to avoid changing it',
588  false,
589  true
590  );
591  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
592  "http://en.wikipedia.org. This is sometimes necessary because " .
593  "server name detection may fail in command line scripts.", false, true );
594  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
595  // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
596  $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, false );
597 
598  # Save generic options to display them separately in help
599  $this->mGenericParameters = $this->mParams;
600 
601  # Script dependant options:
602 
603  // If we support a DB, show the options
604  if ( $this->getDbType() > 0 ) {
605  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
606  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
607  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
608  }
609 
610  # Save additional script dependant options to display
611  # ┬áthem separately in help
612  $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
613  }
614 
619  public function getConfig() {
620  if ( $this->config === null ) {
621  $this->config = MediaWikiServices::getInstance()->getMainConfig();
622  }
623 
624  return $this->config;
625  }
626 
631  public function setConfig( Config $config ) {
632  $this->config = $config;
633  }
634 
644  protected function requireExtension( $name ) {
645  $this->requiredExtensions[] = $name;
646  }
647 
653  public function checkRequiredExtensions() {
654  $registry = ExtensionRegistry::getInstance();
655  $missing = [];
656  foreach ( $this->requiredExtensions as $name ) {
657  if ( !$registry->isLoaded( $name ) ) {
658  $missing[] = $name;
659  }
660  }
661 
662  if ( $missing ) {
663  $joined = implode( ', ', $missing );
664  $msg = "The following extensions are required to be installed "
665  . "for this script to run: $joined. Please enable them and then try again.";
666  $this->fatalError( $msg );
667  }
668  }
669 
674  public function setAgentAndTriggers() {
675  if ( function_exists( 'posix_getpwuid' ) ) {
676  $agent = posix_getpwuid( posix_geteuid() )['name'];
677  } else {
678  $agent = 'sysadmin';
679  }
680  $agent .= '@' . wfHostname();
681 
682  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
683  // Add a comment for easy SHOW PROCESSLIST interpretation
684  $lbFactory->setAgentName(
685  mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
686  );
687  self::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
688  }
689 
695  public static function setLBFactoryTriggers( LBFactory $LBFactory, Config $config ) {
696  $services = MediaWikiServices::getInstance();
697  $stats = $services->getStatsdDataFactory();
698  // Hook into period lag checks which often happen in long-running scripts
699  $lbFactory = $services->getDBLoadBalancerFactory();
700  $lbFactory->setWaitForReplicationListener(
701  __METHOD__,
702  function () use ( $stats, $config ) {
703  // Check config in case of JobRunner and unit tests
704  if ( $config->get( 'CommandLineMode' ) ) {
706  }
707  // Try to periodically flush buffered metrics to avoid OOMs
709  }
710  );
711  // Check for other windows to run them. A script may read or do a few writes
712  // to the master but mostly be writing to something else, like a file store.
713  $lbFactory->getMainLB()->setTransactionListener(
714  __METHOD__,
715  function ( $trigger ) use ( $stats, $config ) {
716  // Check config in case of JobRunner and unit tests
717  if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
719  }
720  // Try to periodically flush buffered metrics to avoid OOMs
722  }
723  );
724  }
725 
733  public function runChild( $maintClass, $classFile = null ) {
734  // Make sure the class is loaded first
735  if ( !class_exists( $maintClass ) ) {
736  if ( $classFile ) {
737  require_once $classFile;
738  }
739  if ( !class_exists( $maintClass ) ) {
740  $this->error( "Cannot spawn child: $maintClass" );
741  }
742  }
743 
747  $child = new $maintClass();
748  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
749  if ( $this->mDb !== null ) {
750  $child->setDB( $this->mDb );
751  }
752 
753  return $child;
754  }
755 
759  public function setup() {
760  global $IP, $wgCommandLineMode;
761 
762  # Abort if called from a web server
763  # wfIsCLI() is not available yet
764  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
765  $this->fatalError( 'This script must be run from the command line' );
766  }
767 
768  if ( $IP === null ) {
769  $this->fatalError( "\$IP not set, aborting!\n" .
770  '(Did you forget to call parent::__construct() in your maintenance script?)' );
771  }
772 
773  # Make sure we can handle script parameters
774  if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
775  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
776  }
777 
778  // Send PHP warnings and errors to stderr instead of stdout.
779  // This aids in diagnosing problems, while keeping messages
780  // out of redirected output.
781  if ( ini_get( 'display_errors' ) ) {
782  ini_set( 'display_errors', 'stderr' );
783  }
784 
785  $this->loadParamsAndArgs();
786 
787  # Set the memory limit
788  # Note we need to set it again later in cache LocalSettings changed it
789  $this->adjustMemoryLimit();
790 
791  # Set max execution time to 0 (no limit). PHP.net says that
792  # "When running PHP from the command line the default setting is 0."
793  # But sometimes this doesn't seem to be the case.
794  ini_set( 'max_execution_time', 0 );
795 
796  # Define us as being in MediaWiki
797  define( 'MEDIAWIKI', true );
798 
799  $wgCommandLineMode = true;
800 
801  # Turn off output buffering if it's on
802  while ( ob_get_level() > 0 ) {
803  ob_end_flush();
804  }
805  }
806 
816  public function memoryLimit() {
817  $limit = $this->getOption( 'memory-limit', 'max' );
818  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
819  return $limit;
820  }
821 
825  protected function adjustMemoryLimit() {
826  $limit = $this->memoryLimit();
827  if ( $limit == 'max' ) {
828  $limit = -1; // no memory limit
829  }
830  if ( $limit != 'default' ) {
831  ini_set( 'memory_limit', $limit );
832  }
833  }
834 
838  protected function activateProfiler() {
840 
841  $output = $this->getOption( 'profiler' );
842  if ( !$output ) {
843  return;
844  }
845 
846  if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
847  $class = $wgProfiler['class'];
849  $profiler = new $class(
850  [ 'sampling' => 1, 'output' => [ $output ] ]
851  + $wgProfiler
852  + [ 'threshold' => $wgProfileLimit ]
853  );
854  $profiler->setAllowOutput();
855  Profiler::replaceStubInstance( $profiler );
856  }
857 
858  $trxProfiler = Profiler::instance()->getTransactionProfiler();
859  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
860  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
861  }
862 
866  public function clearParamsAndArgs() {
867  $this->mOptions = [];
868  $this->mArgs = [];
869  $this->mInputLoaded = false;
870  }
871 
879  public function loadWithArgv( $argv ) {
880  $options = [];
881  $args = [];
882  $this->orderedOptions = [];
883 
884  # Parse arguments
885  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
886  if ( $arg == '--' ) {
887  # End of options, remainder should be considered arguments
888  $arg = next( $argv );
889  while ( $arg !== false ) {
890  $args[] = $arg;
891  $arg = next( $argv );
892  }
893  break;
894  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
895  # Long options
896  $option = substr( $arg, 2 );
897  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
898  $param = next( $argv );
899  if ( $param === false ) {
900  $this->error( "\nERROR: $option parameter needs a value after it\n" );
901  $this->maybeHelp( true );
902  }
903 
904  $this->setParam( $options, $option, $param );
905  } else {
906  $bits = explode( '=', $option, 2 );
907  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
908  }
909  } elseif ( $arg == '-' ) {
910  # Lonely "-", often used to indicate stdin or stdout.
911  $args[] = $arg;
912  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
913  # Short options
914  $argLength = strlen( $arg );
915  for ( $p = 1; $p < $argLength; $p++ ) {
916  $option = $arg[$p];
917  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
918  $option = $this->mShortParamsMap[$option];
919  }
920 
921  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
922  $param = next( $argv );
923  if ( $param === false ) {
924  $this->error( "\nERROR: $option parameter needs a value after it\n" );
925  $this->maybeHelp( true );
926  }
927  $this->setParam( $options, $option, $param );
928  } else {
929  $this->setParam( $options, $option, 1 );
930  }
931  }
932  } else {
933  $args[] = $arg;
934  }
935  }
936 
937  $this->mOptions = $options;
938  $this->mArgs = $args;
939  $this->loadSpecialVars();
940  $this->mInputLoaded = true;
941  }
942 
955  private function setParam( &$options, $option, $value ) {
956  $this->orderedOptions[] = [ $option, $value ];
957 
958  if ( isset( $this->mParams[$option] ) ) {
959  $multi = $this->mParams[$option]['multiOccurrence'];
960  } else {
961  $multi = false;
962  }
963  $exists = array_key_exists( $option, $options );
964  if ( $multi && $exists ) {
965  $options[$option][] = $value;
966  } elseif ( $multi ) {
967  $options[$option] = [ $value ];
968  } elseif ( !$exists ) {
969  $options[$option] = $value;
970  } else {
971  $this->error( "\nERROR: $option parameter given twice\n" );
972  $this->maybeHelp( true );
973  }
974  }
975 
985  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
986  # If we were given opts or args, set those and return early
987  if ( $self ) {
988  $this->mSelf = $self;
989  $this->mInputLoaded = true;
990  }
991  if ( $opts ) {
992  $this->mOptions = $opts;
993  $this->mInputLoaded = true;
994  }
995  if ( $args ) {
996  $this->mArgs = $args;
997  $this->mInputLoaded = true;
998  }
999 
1000  # If we've already loaded input (either by user values or from $argv)
1001  # skip on loading it again. The array_shift() will corrupt values if
1002  # it's run again and again
1003  if ( $this->mInputLoaded ) {
1004  $this->loadSpecialVars();
1005 
1006  return;
1007  }
1008 
1009  global $argv;
1010  $this->mSelf = $argv[0];
1011  $this->loadWithArgv( array_slice( $argv, 1 ) );
1012  }
1013 
1017  public function validateParamsAndArgs() {
1018  $die = false;
1019  # Check to make sure we've got all the required options
1020  foreach ( $this->mParams as $opt => $info ) {
1021  if ( $info['require'] && !$this->hasOption( $opt ) ) {
1022  $this->error( "Param $opt required!" );
1023  $die = true;
1024  }
1025  }
1026  # Check arg list too
1027  foreach ( $this->mArgList as $k => $info ) {
1028  if ( $info['require'] && !$this->hasArg( $k ) ) {
1029  $this->error( 'Argument <' . $info['name'] . '> required!' );
1030  $die = true;
1031  }
1032  }
1033  if ( !$this->mAllowUnregisteredOptions ) {
1034  # Check for unexpected options
1035  foreach ( $this->mOptions as $opt => $val ) {
1036  if ( !$this->supportsOption( $opt ) ) {
1037  $this->error( "Unexpected option $opt!" );
1038  $die = true;
1039  }
1040  }
1041  }
1042 
1043  $this->maybeHelp( $die );
1044  }
1045 
1049  protected function loadSpecialVars() {
1050  if ( $this->hasOption( 'dbuser' ) ) {
1051  $this->mDbUser = $this->getOption( 'dbuser' );
1052  }
1053  if ( $this->hasOption( 'dbpass' ) ) {
1054  $this->mDbPass = $this->getOption( 'dbpass' );
1055  }
1056  if ( $this->hasOption( 'quiet' ) ) {
1057  $this->mQuiet = true;
1058  }
1059  if ( $this->hasOption( 'batch-size' ) ) {
1060  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1061  }
1062  }
1063 
1069  protected function maybeHelp( $force = false ) {
1070  if ( !$force && !$this->hasOption( 'help' ) ) {
1071  return;
1072  }
1073  $this->showHelp();
1074  die( 1 );
1075  }
1076 
1080  protected function showHelp() {
1081  $screenWidth = 80; // TODO: Calculate this!
1082  $tab = " ";
1083  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1084 
1085  ksort( $this->mParams );
1086  $this->mQuiet = false;
1087 
1088  // Description ...
1089  if ( $this->mDescription ) {
1090  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1091  }
1092  $output = "\nUsage: php " . basename( $this->mSelf );
1093 
1094  // ... append parameters ...
1095  if ( $this->mParams ) {
1096  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1097  }
1098 
1099  // ... and append arguments.
1100  if ( $this->mArgList ) {
1101  $output .= ' ';
1102  foreach ( $this->mArgList as $k => $arg ) {
1103  if ( $arg['require'] ) {
1104  $output .= '<' . $arg['name'] . '>';
1105  } else {
1106  $output .= '[' . $arg['name'] . ']';
1107  }
1108  if ( $k < count( $this->mArgList ) - 1 ) {
1109  $output .= ' ';
1110  }
1111  }
1112  }
1113  $this->output( "$output\n\n" );
1114 
1115  # TODO abstract some repetitive code below
1116 
1117  // Generic parameters
1118  $this->output( "Generic maintenance parameters:\n" );
1119  foreach ( $this->mGenericParameters as $par => $info ) {
1120  if ( $info['shortName'] !== false ) {
1121  $par .= " (-{$info['shortName']})";
1122  }
1123  $this->output(
1124  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1125  "\n$tab$tab" ) . "\n"
1126  );
1127  }
1128  $this->output( "\n" );
1129 
1130  $scriptDependantParams = $this->mDependantParameters;
1131  if ( count( $scriptDependantParams ) > 0 ) {
1132  $this->output( "Script dependant parameters:\n" );
1133  // Parameters description
1134  foreach ( $scriptDependantParams as $par => $info ) {
1135  if ( $info['shortName'] !== false ) {
1136  $par .= " (-{$info['shortName']})";
1137  }
1138  $this->output(
1139  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1140  "\n$tab$tab" ) . "\n"
1141  );
1142  }
1143  $this->output( "\n" );
1144  }
1145 
1146  // Script specific parameters not defined on construction by
1147  // Maintenance::addDefaultParams()
1148  $scriptSpecificParams = array_diff_key(
1149  # all script parameters:
1150  $this->mParams,
1151  # remove the Maintenance default parameters:
1152  $this->mGenericParameters,
1153  $this->mDependantParameters
1154  );
1155  '@phan-var array[] $scriptSpecificParams';
1156  if ( count( $scriptSpecificParams ) > 0 ) {
1157  $this->output( "Script specific parameters:\n" );
1158  // Parameters description
1159  foreach ( $scriptSpecificParams as $par => $info ) {
1160  if ( $info['shortName'] !== false ) {
1161  $par .= " (-{$info['shortName']})";
1162  }
1163  $this->output(
1164  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1165  "\n$tab$tab" ) . "\n"
1166  );
1167  }
1168  $this->output( "\n" );
1169  }
1170 
1171  // Print arguments
1172  if ( count( $this->mArgList ) > 0 ) {
1173  $this->output( "Arguments:\n" );
1174  // Arguments description
1175  foreach ( $this->mArgList as $info ) {
1176  $openChar = $info['require'] ? '<' : '[';
1177  $closeChar = $info['require'] ? '>' : ']';
1178  $this->output(
1179  wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1180  $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1181  );
1182  }
1183  $this->output( "\n" );
1184  }
1185  }
1186 
1190  public function finalSetup() {
1194 
1195  # Turn off output buffering again, it might have been turned on in the settings files
1196  if ( ob_get_level() ) {
1197  ob_end_flush();
1198  }
1199  # Same with these
1200  $wgCommandLineMode = true;
1201 
1202  # Override $wgServer
1203  if ( $this->hasOption( 'server' ) ) {
1204  $wgServer = $this->getOption( 'server', $wgServer );
1205  }
1206 
1207  # If these were passed, use them
1208  if ( $this->mDbUser ) {
1210  }
1211  if ( $this->mDbPass ) {
1213  }
1214  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1215  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1216 
1217  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1218  }
1219 
1220  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1223 
1224  if ( $wgDBservers ) {
1228  foreach ( $wgDBservers as $i => $server ) {
1229  $wgDBservers[$i]['user'] = $wgDBuser;
1230  $wgDBservers[$i]['password'] = $wgDBpassword;
1231  }
1232  }
1233  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1234  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1235  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1236  }
1237  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1238  }
1239 
1240  # Apply debug settings
1241  if ( $this->hasOption( 'mwdebug' ) ) {
1242  require __DIR__ . '/../includes/DevelopmentSettings.php';
1243  }
1244 
1245  // Per-script profiling; useful for debugging
1246  $this->activateProfiler();
1247 
1248  $this->afterFinalSetup();
1249 
1250  $wgShowExceptionDetails = true;
1251  $wgShowHostnames = true;
1252 
1253  Wikimedia\suppressWarnings();
1254  set_time_limit( 0 );
1255  Wikimedia\restoreWarnings();
1256 
1257  $this->adjustMemoryLimit();
1258  }
1259 
1263  protected function afterFinalSetup() {
1264  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1265  // @phan-suppress-next-line PhanUndeclaredConstant
1266  call_user_func( MW_CMDLINE_CALLBACK );
1267  }
1268  }
1269 
1274  public function globals() {
1275  if ( $this->hasOption( 'globals' ) ) {
1276  print_r( $GLOBALS );
1277  }
1278  }
1279 
1284  public function loadSettings() {
1285  global $wgCommandLineMode, $IP;
1286 
1287  if ( isset( $this->mOptions['conf'] ) ) {
1288  $settingsFile = $this->mOptions['conf'];
1289  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1290  $settingsFile = MW_CONFIG_FILE;
1291  } else {
1292  $settingsFile = "$IP/LocalSettings.php";
1293  }
1294  if ( isset( $this->mOptions['wiki'] ) ) {
1295  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1296  define( 'MW_DB', $bits[0] );
1297  define( 'MW_PREFIX', $bits[1] ?? '' );
1298  } elseif ( isset( $this->mOptions['server'] ) ) {
1299  // Provide the option for site admins to detect and configure
1300  // multiple wikis based on server names. This offers --server
1301  // as alternative to --wiki.
1302  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1303  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1304  }
1305 
1306  if ( !is_readable( $settingsFile ) ) {
1307  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1308  "must exist and be readable in the source directory.\n" .
1309  "Use --conf to specify it." );
1310  }
1311  $wgCommandLineMode = true;
1312 
1313  return $settingsFile;
1314  }
1315 
1321  public function purgeRedundantText( $delete = true ) {
1323 
1324  # Data should come off the master, wrapped in a transaction
1325  $dbw = $this->getDB( DB_MASTER );
1326  $this->beginTransaction( $dbw, __METHOD__ );
1327 
1329  # Get "active" text records from the revisions table
1330  $cur = [];
1331  $this->output( 'Searching for active text records in revisions table...' );
1332  $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1333  foreach ( $res as $row ) {
1334  $cur[] = $row->rev_text_id;
1335  }
1336  $this->output( "done.\n" );
1337 
1338  # Get "active" text records from the archive table
1339  $this->output( 'Searching for active text records in archive table...' );
1340  $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1341  foreach ( $res as $row ) {
1342  # old pre-MW 1.5 records can have null ar_text_id's.
1343  if ( $row->ar_text_id !== null ) {
1344  $cur[] = $row->ar_text_id;
1345  }
1346  }
1347  $this->output( "done.\n" );
1348  } else {
1349  # Get "active" text records via the content table
1350  $cur = [];
1351  $this->output( 'Searching for active text records via contents table...' );
1352  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1353  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1354  foreach ( $res as $row ) {
1355  // @phan-suppress-next-line PhanUndeclaredMethod
1356  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1357  if ( $textId ) {
1358  $cur[] = $textId;
1359  }
1360  }
1361  $this->output( "done.\n" );
1362  }
1363  $this->output( "done.\n" );
1364 
1365  # Get the IDs of all text records not in these sets
1366  $this->output( 'Searching for inactive text records...' );
1367  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1368  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1369  $old = [];
1370  foreach ( $res as $row ) {
1371  $old[] = $row->old_id;
1372  }
1373  $this->output( "done.\n" );
1374 
1375  # Inform the user of what we're going to do
1376  $count = count( $old );
1377  $this->output( "$count inactive items found.\n" );
1378 
1379  # Delete as appropriate
1380  if ( $delete && $count ) {
1381  $this->output( 'Deleting...' );
1382  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1383  $this->output( "done.\n" );
1384  }
1385 
1386  $this->commitTransaction( $dbw, __METHOD__ );
1387  }
1388 
1393  protected function getDir() {
1394  return __DIR__;
1395  }
1396 
1409  protected function getDB( $db, $groups = [], $dbDomain = false ) {
1410  if ( $this->mDb === null ) {
1411  return MediaWikiServices::getInstance()
1412  ->getDBLoadBalancerFactory()
1413  ->getMainLB( $dbDomain )
1414  ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1415  }
1416 
1417  return $this->mDb;
1418  }
1419 
1425  public function setDB( IMaintainableDatabase $db ) {
1426  $this->mDb = $db;
1427  }
1428 
1439  protected function beginTransaction( IDatabase $dbw, $fname ) {
1440  $dbw->begin( $fname );
1441  }
1442 
1454  protected function commitTransaction( IDatabase $dbw, $fname ) {
1455  $dbw->commit( $fname );
1456  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1457  $waitSucceeded = $lbFactory->waitForReplication(
1458  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1459  );
1460  $this->lastReplicationWait = microtime( true );
1461  return $waitSucceeded;
1462  }
1463 
1474  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1475  $dbw->rollback( $fname );
1476  }
1477 
1482  private function lockSearchindex( $db ) {
1483  $write = [ 'searchindex' ];
1484  $read = [
1485  'page',
1486  'revision',
1487  'text',
1488  'interwiki',
1489  'l10n_cache',
1490  'user',
1491  'page_restrictions'
1492  ];
1493  $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1494  }
1495 
1500  private function unlockSearchindex( $db ) {
1501  $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1502  }
1503 
1509  private function relockSearchindex( $db ) {
1510  $this->unlockSearchindex( $db );
1511  $this->lockSearchindex( $db );
1512  }
1513 
1521  public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1522  $lockTime = time();
1523 
1524  # Lock searchindex
1525  if ( $maxLockTime ) {
1526  $this->output( " --- Waiting for lock ---" );
1527  $this->lockSearchindex( $dbw );
1528  $lockTime = time();
1529  $this->output( "\n" );
1530  }
1531 
1532  # Loop through the results and do a search update
1533  foreach ( $results as $row ) {
1534  # Allow reads to be processed
1535  if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1536  $this->output( " --- Relocking ---" );
1537  $this->relockSearchindex( $dbw );
1538  $lockTime = time();
1539  $this->output( "\n" );
1540  }
1541  call_user_func( $callback, $dbw, $row );
1542  }
1543 
1544  # Unlock searchindex
1545  if ( $maxLockTime ) {
1546  $this->output( " --- Unlocking --" );
1547  $this->unlockSearchindex( $dbw );
1548  $this->output( "\n" );
1549  }
1550  }
1551 
1558  public function updateSearchIndexForPage( $dbw, $pageId ) {
1559  // Get current revision
1560  $rev = Revision::loadFromPageId( $dbw, $pageId );
1561  $title = null;
1562  if ( $rev ) {
1563  $titleObj = $rev->getTitle();
1564  $title = $titleObj->getPrefixedDBkey();
1565  $this->output( "$title..." );
1566  # Update searchindex
1567  $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent() );
1568  $u->doUpdate();
1569  $this->output( "\n" );
1570  }
1571 
1572  return $title;
1573  }
1574 
1585  protected function countDown( $seconds ) {
1586  if ( $this->isQuiet() ) {
1587  return;
1588  }
1589  for ( $i = $seconds; $i >= 0; $i-- ) {
1590  if ( $i != $seconds ) {
1591  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1592  }
1593  $this->output( $i );
1594  if ( $i ) {
1595  sleep( 1 );
1596  }
1597  }
1598  $this->output( "\n" );
1599  }
1600 
1609  public static function posix_isatty( $fd ) {
1610  if ( !function_exists( 'posix_isatty' ) ) {
1611  return !$fd;
1612  } else {
1613  return posix_isatty( $fd );
1614  }
1615  }
1616 
1622  public static function readconsole( $prompt = '> ' ) {
1623  static $isatty = null;
1624  if ( $isatty === null ) {
1625  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1626  }
1627 
1628  if ( $isatty && function_exists( 'readline' ) ) {
1629  return readline( $prompt );
1630  } else {
1631  if ( $isatty ) {
1632  $st = self::readlineEmulation( $prompt );
1633  } else {
1634  if ( feof( STDIN ) ) {
1635  $st = false;
1636  } else {
1637  $st = fgets( STDIN, 1024 );
1638  }
1639  }
1640  if ( $st === false ) {
1641  return false;
1642  }
1643  $resp = trim( $st );
1644 
1645  return $resp;
1646  }
1647  }
1648 
1654  private static function readlineEmulation( $prompt ) {
1655  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1656  if ( !wfIsWindows() && $bash ) {
1657  $retval = false;
1658  $encPrompt = Shell::escape( $prompt );
1659  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1660  $encCommand = Shell::escape( $command );
1661  $line = Shell::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1662 
1663  if ( $retval == 0 ) {
1664  return $line;
1665  } elseif ( $retval == 127 ) {
1666  // Couldn't execute bash even though we thought we saw it.
1667  // Shell probably spit out an error message, sorry :(
1668  // Fall through to fgets()...
1669  } else {
1670  // EOF/ctrl+D
1671  return false;
1672  }
1673  }
1674 
1675  // Fallback... we'll have no editing controls, EWWW
1676  if ( feof( STDIN ) ) {
1677  return false;
1678  }
1679  print $prompt;
1680 
1681  return fgets( STDIN, 1024 );
1682  }
1683 
1691  public static function getTermSize() {
1692  $default = [ 80, 50 ];
1693  if ( wfIsWindows() ) {
1694  return $default;
1695  }
1696  if ( Shell::isDisabled() ) {
1697  return $default;
1698  }
1699  // It's possible to get the screen size with VT-100 terminal escapes,
1700  // but reading the responses is not possible without setting raw mode
1701  // (unless you want to require the user to press enter), and that
1702  // requires an ioctl(), which we can't do. So we have to shell out to
1703  // something that can do the relevant syscalls. There are a few
1704  // options. Linux and Mac OS X both have "stty size" which does the
1705  // job directly.
1706  $result = Shell::command( 'stty', 'size' )
1707  ->execute();
1708  if ( $result->getExitCode() !== 0 ) {
1709  return $default;
1710  }
1711  if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1712  return $default;
1713  }
1714  return [ intval( $m[2] ), intval( $m[1] ) ];
1715  }
1716 
1721  public static function requireTestsAutoloader() {
1722  require_once __DIR__ . '/../tests/common/TestsAutoLoader.php';
1723  }
1724 }
1725 
1730  protected $mSelf = "FakeMaintenanceScript";
1731 
1732  public function execute() {
1733  }
1734 }
1735 
1740 abstract class LoggedUpdateMaintenance extends Maintenance {
1741  public function __construct() {
1742  parent::__construct();
1743  $this->addOption( 'force', 'Run the update even if it was completed already' );
1744  $this->setBatchSize( 200 );
1745  }
1746 
1747  public function execute() {
1748  $db = $this->getDB( DB_MASTER );
1749  $key = $this->getUpdateKey();
1750 
1751  if ( !$this->hasOption( 'force' )
1752  && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
1753  ) {
1754  $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1755 
1756  return true;
1757  }
1758 
1759  if ( !$this->doDBUpdates() ) {
1760  return false;
1761  }
1762 
1763  $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, [ 'IGNORE' ] );
1764 
1765  return true;
1766  }
1767 
1772  protected function updateSkippedMessage() {
1773  $key = $this->getUpdateKey();
1774 
1775  return "Update '{$key}' already logged as completed. Use --force to run it again.";
1776  }
1777 
1783  abstract protected function doDBUpdates();
1784 
1789  abstract protected function getUpdateKey();
1790 }
$wgProfileLimit
$wgProfileLimit
Only record profiling info for pages that took longer than this.
Definition: DefaultSettings.php:6419
FakeMaintenance\$mSelf
$mSelf
Definition: Maintenance.php:1730
RUN_MAINTENANCE_IF_MAIN
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:41
Maintenance\$mBatchSize
int $mBatchSize
Batch size.
Definition: Maintenance.php:141
LoggedUpdateMaintenance\__construct
__construct()
Default constructor.
Definition: Maintenance.php:1741
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
Maintenance\setParam
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
Definition: Maintenance.php:955
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:1691
Maintenance\$mShortParamsMap
$mShortParamsMap
Definition: Maintenance.php:108
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1073
Maintenance\getStdin
getStdin( $len=null)
Return input from stdin.
Definition: Maintenance.php:432
Profiler\replaceStubInstance
static replaceStubInstance(Profiler $profiler)
Replace the current profiler with $profiler if no non-stub profiler is set.
Definition: Profiler.php:99
Maintenance\$mGenericParameters
array[] $mGenericParameters
Generic options added by addDefaultParams()
Definition: Maintenance.php:148
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:63
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:130
Maintenance\getDbType
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition: Maintenance.php:569
Maintenance\maybeHelp
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:1069
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:510
Maintenance\$mDbPass
$mDbPass
Definition: Maintenance.php:127
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:354
Maintenance\setup
setup()
Do some sanity checking and basic setup.
Definition: Maintenance.php:759
Maintenance\$requiredExtensions
array $requiredExtensions
Definition: Maintenance.php:182
Maintenance\runChild
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
Definition: Maintenance.php:733
Maintenance\setLBFactoryTriggers
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
Definition: Maintenance.php:695
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1622
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6339
Maintenance\$mAllowUnregisteredOptions
$mAllowUnregisteredOptions
Definition: Maintenance.php:120
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:985
Maintenance\showHelp
showHelp()
Definitely show the help.
Definition: Maintenance.php:1080
Maintenance\$mParams
array[] $mParams
Array of desired/allowed params.
Definition: Maintenance.php:105
Maintenance\relockSearchindex
relockSearchindex( $db)
Unlock and lock again Since the lock is low-priority, queued reads will be able to complete.
Definition: Maintenance.php:1509
Maintenance\getName
getName()
Get the script's name.
Definition: Maintenance.php:422
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1325
$wgMultiContentRevisionSchemaMigrationStage
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables).
Definition: DefaultSettings.php:8970
$wgLBFactoryConf
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-master wiki farm, set the class here to somethi...
Definition: DefaultSettings.php:2120
$s
$s
Definition: mergeMessageFileList.php:185
Maintenance\hasArg
hasArg( $argId=0)
Does a given argument exist?
Definition: Maintenance.php:363
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:88
Maintenance\setConfig
setConfig(Config $config)
Definition: Maintenance.php:631
$res
$res
Definition: testCompression.php:54
$wgDBpassword
$wgDBpassword
Database user's password.
Definition: DefaultSettings.php:1933
Maintenance\$lastChannel
$lastChannel
Definition: Maintenance.php:516
Maintenance\loadWithArgv
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
Definition: Maintenance.php:879
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:653
Maintenance\finalSetup
finalSetup()
Handle some last-minute setup here.
Definition: Maintenance.php:1190
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
Definition: Maintenance.php:1474
Maintenance\$mDescription
$mDescription
Definition: Maintenance.php:130
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1439
Maintenance\afterFinalSetup
afterFinalSetup()
Execute a callback function at the end of initialisation.
Definition: Maintenance.php:1263
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:127
$wgDBadminuser
$wgDBadminuser
Separate username for maintenance tasks.
Definition: DefaultSettings.php:1963
Maintenance\unlockSearchindex
unlockSearchindex( $db)
Unlock the tables.
Definition: Maintenance.php:1500
Maintenance\clearParamsAndArgs
clearParamsAndArgs()
Clear all params and arguments.
Definition: Maintenance.php:866
Config
Interface for configuration instances.
Definition: Config.php:28
$wgDBservers
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
Definition: DefaultSettings.php:2108
Maintenance\$mSelf
$mSelf
Definition: Maintenance.php:123
$wgDBDefaultGroup
$wgDBDefaultGroup
Default group to use when getting database connections.
Definition: DefaultSettings.php:2005
Maintenance\updateSearchIndex
updateSearchIndex( $maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
Definition: Maintenance.php:1521
Maintenance\$mArgs
$mArgs
Definition: Maintenance.php:117
$wgProfiler
$wgProfiler
Profiler configuration.
Definition: DefaultSettings.php:6413
Maintenance\loadSpecialVars
loadSpecialVars()
Handle the special variables that are global to all scripts.
Definition: Maintenance.php:1049
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:619
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1044
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
LoggedUpdateMaintenance
Class for scripts that perform database maintenance and want to log the update in updatelog so we can...
Definition: Maintenance.php:1740
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
Maintenance\$atLineStart
$atLineStart
Definition: Maintenance.php:515
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
Maintenance\$lastReplicationWait
float $lastReplicationWait
UNIX timestamp.
Definition: Maintenance.php:163
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:28
Revision\loadFromPageId
static loadFromPageId( $db, $pageid, $id=0)
Load either the current, or a specified, revision that's attached to a given page.
Definition: Revision.php:261
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:273
Maintenance\$mDbUser
$mDbUser
Definition: Maintenance.php:127
Maintenance\requireExtension
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
Definition: Maintenance.php:644
$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:195
Maintenance\globals
globals()
Potentially debug globals.
Definition: Maintenance.php:1274
$title
$title
Definition: testCompression.php:36
FakeMaintenance
Fake maintenance wrapper, mostly used for the web installer/updater.
Definition: Maintenance.php:1729
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Maintenance\addDefaultParams
addDefaultParams()
Add the default parameters to the scripts.
Definition: Maintenance.php:576
Maintenance\readlineEmulation
static readlineEmulation( $prompt)
Emulate readline()
Definition: Maintenance.php:1654
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:1585
Maintenance\DB_ADMIN
const DB_ADMIN
Definition: Maintenance.php:95
Maintenance\deleteOption
deleteOption( $name)
Remove an option.
Definition: Maintenance.php:337
Maintenance\shouldExecute
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class?...
Definition: Maintenance.php:216
LoggedUpdateMaintenance\execute
execute()
Do the actual work.
Definition: Maintenance.php:1747
Maintenance\DB_STD
const DB_STD
Definition: Maintenance.php:94
Maintenance\updateSearchIndexForPage
updateSearchIndexForPage( $dbw, $pageId)
Update the searchindex table for a given pageid.
Definition: Maintenance.php:1558
Maintenance\supportsOption
supportsOption( $name)
Checks to see if a particular option in supported.
Definition: Maintenance.php:258
Maintenance\$mQuiet
$mQuiet
Definition: Maintenance.php:126
Maintenance\isQuiet
isQuiet()
Definition: Maintenance.php:449
Maintenance\activateProfiler
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
Definition: Maintenance.php:838
DeferredUpdates\tryOpportunisticExecute
static tryOpportunisticExecute( $mode='run')
Run all deferred updates immediately if there are no DB writes active.
Definition: DeferredUpdates.php:436
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:346
Maintenance\$mDependantParameters
array[] $mDependantParameters
Generic options which might or not be supported by the script.
Definition: Maintenance.php:154
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1909
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:105
Maintenance\requireTestsAutoloader
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
Definition: Maintenance.php:1721
$line
$line
Definition: mcc.php:119
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:1609
LoggedUpdateMaintenance\updateSkippedMessage
updateSkippedMessage()
Message to show that the update was done already and was just skipped.
Definition: Maintenance.php:1772
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1454
Maintenance\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc.
Definition: Maintenance.php:1017
Maintenance\$config
Config $config
Accessible via getConfig()
Definition: Maintenance.php:176
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1409
Maintenance\cleanupChanneled
cleanupChanneled()
Clean up channeled output.
Definition: Maintenance.php:521
Maintenance\DB_NONE
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:93
Maintenance\loadSettings
loadSettings()
Generic setup for most installs.
Definition: Maintenance.php:1284
LoggedUpdateMaintenance\doDBUpdates
doDBUpdates()
Do the actual work.
Maintenance\adjustMemoryLimit
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
Definition: Maintenance.php:825
LoggedUpdateMaintenance\getUpdateKey
getUpdateKey()
Get the update key name to go in the update log table.
Maintenance\purgeRedundantText
purgeRedundantText( $delete=true)
Support function for cleaning up redundant text records.
Definition: Maintenance.php:1321
$self
$self
Definition: doMaintenance.php:55
Maintenance\$fileHandle
resource $fileHandle
Used when creating separate schema files.
Definition: Maintenance.php:169
$command
$command
Definition: mcc.php:125
Maintenance\$mInputLoaded
$mInputLoaded
Definition: Maintenance.php:133
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:308
Maintenance\STDIN_ALL
const STDIN_ALL
Definition: Maintenance.php:98
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:325
Wikimedia\Rdbms\LBFactory
An interface for generating database load balancers.
Definition: LBFactory.php:40
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:392
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
Definition: DefaultSettings.php:6311
Maintenance\$mOptions
$mOptions
Definition: Maintenance.php:114
Maintenance\setAgentAndTriggers
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
Definition: Maintenance.php:674
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1425
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:487
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:459
Maintenance\$mArgList
$mArgList
Definition: Maintenance.php:111
Maintenance\getDir
getDir()
Get the maintenance directory.
Definition: Maintenance.php:1393
$wgDBuser
$wgDBuser
Database username.
Definition: DefaultSettings.php:1928
ExecutableFinder\findInDefaultPaths
static findInDefaultPaths( $names, $versionInfo=false)
Same as locateExecutable(), but checks in getPossibleBinPaths() by default.
Definition: ExecutableFinder.php:96
wfEntryPointCheck
wfEntryPointCheck( $format='text', $scriptPath='/')
Check PHP version and that external dependencies are installed, and display an informative error if e...
Definition: PHPVersionCheck.php:225
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:294
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:377
$maintClass
string false $maintClass
@phan-var class-string|false
Definition: Maintenance.php:52
$IP
$IP
Definition: WebStart.php:41
$wgDBadminpassword
$wgDBadminpassword
Separate password for maintenance tasks.
Definition: DefaultSettings.php:1968
Maintenance\outputChanneled
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
Definition: Maintenance.php:536
Maintenance\__construct
__construct()
Default constructor.
Definition: Maintenance.php:201
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
FakeMaintenance\execute
execute()
Do the actual work.
Definition: Maintenance.php:1732
$wgTrxProfilerLimits
$wgTrxProfilerLimits
Performance expectations for DB usage.
Definition: DefaultSettings.php:6167
Maintenance\execute
execute()
Do the actual work.
SCHEMA_COMPAT_READ_OLD
const SCHEMA_COMPAT_READ_OLD
Definition: Defines.php:265
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
Wikimedia\Rdbms\IDatabase\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Wikimedia\Rdbms\IDatabase\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Maintenance\lockSearchindex
lockSearchindex( $db)
Lock the search index.
Definition: Maintenance.php:1482
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:400
Maintenance\$mDb
IMaintainableDatabase $mDb
Used by getDB() / setDB()
Definition: Maintenance.php:160
Maintenance\memoryLimit
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
Definition: Maintenance.php:816