MediaWiki  master
Maintenance.php
Go to the documentation of this file.
1 <?php
31 
53 abstract class Maintenance {
58  public const DB_NONE = 0;
59  public const DB_STD = 1;
60  public const DB_ADMIN = 2;
61 
62  // Const for getStdin()
63  public const STDIN_ALL = 'all';
64 
70  protected $mParams = [];
71 
72  // Array of mapping short parameters to long ones
73  protected $mShortParamsMap = [];
74 
75  // Array of desired/allowed args
76  protected $mArgList = [];
77 
78  // This is the list of options that were actually passed
79  protected $mOptions = [];
80 
81  // This is the list of arguments that were actually passed
82  protected $mArgs = [];
83 
84  // Allow arbitrary options to be passed, or only specified ones?
85  protected $mAllowUnregisteredOptions = false;
86 
87  // Name of the script currently running
88  protected $mSelf;
89 
90  // Special vars for params that are always used
91  protected $mQuiet = false;
92  protected $mDbUser, $mDbPass;
93 
94  // A description of the script, children should change this via addDescription()
95  protected $mDescription = '';
96 
97  // Have we already loaded our user input?
98  protected $mInputLoaded = false;
99 
106  protected $mBatchSize = null;
107 
113  private $mGenericParameters = [];
119  private $mDependantParameters = [];
120 
125  private $mDb = null;
126 
128  private $lastReplicationWait = 0.0;
129 
134  public $fileHandle;
135 
137  private $hookContainer;
138 
140  private $hookRunner;
141 
147  private $config;
148 
153  private $requiredExtensions = [];
154 
166  public $orderedOptions = [];
167 
172  public function __construct() {
173  $this->addDefaultParams();
174  register_shutdown_function( [ $this, 'outputChanneled' ], false );
175  }
176 
184  public static function shouldExecute() {
185  global $wgCommandLineMode;
186 
187  if ( !function_exists( 'debug_backtrace' ) ) {
188  // If someone has a better idea...
189  return $wgCommandLineMode;
190  }
191 
192  $bt = debug_backtrace();
193  $count = count( $bt );
194  if ( $count < 2 ) {
195  return false; // sanity
196  }
197  if ( $bt[0]['class'] !== self::class || $bt[0]['function'] !== 'shouldExecute' ) {
198  return false; // last call should be to this function
199  }
200  $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
201  for ( $i = 1; $i < $count; $i++ ) {
202  if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
203  return false; // previous calls should all be "requires"
204  }
205  }
206 
207  return true;
208  }
209 
218  abstract public function execute();
219 
226  protected function supportsOption( $name ) {
227  return isset( $this->mParams[$name] );
228  }
229 
241  protected function addOption( $name, $description, $required = false,
242  $withArg = false, $shortName = false, $multiOccurrence = false
243  ) {
244  $this->mParams[$name] = [
245  'desc' => $description,
246  'require' => $required,
247  'withArg' => $withArg,
248  'shortName' => $shortName,
249  'multiOccurrence' => $multiOccurrence
250  ];
251 
252  if ( $shortName !== false ) {
253  $this->mShortParamsMap[$shortName] = $name;
254  }
255  }
256 
262  protected function hasOption( $name ) {
263  return isset( $this->mOptions[$name] );
264  }
265 
277  protected function getOption( $name, $default = null ) {
278  if ( $this->hasOption( $name ) ) {
279  return $this->mOptions[$name];
280  } else {
281  // Set it so we don't have to provide the default again
282  $this->mOptions[$name] = $default;
283 
284  return $this->mOptions[$name];
285  }
286  }
287 
294  protected function addArg( $arg, $description, $required = true ) {
295  $this->mArgList[] = [
296  'name' => $arg,
297  'desc' => $description,
298  'require' => $required
299  ];
300  }
301 
306  protected function deleteOption( $name ) {
307  unset( $this->mParams[$name] );
308  }
309 
315  protected function setAllowUnregisteredOptions( $allow ) {
316  $this->mAllowUnregisteredOptions = $allow;
317  }
318 
323  protected function addDescription( $text ) {
324  $this->mDescription = $text;
325  }
326 
332  protected function hasArg( $argId = 0 ) {
333  if ( func_num_args() === 0 ) {
334  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
335  }
336 
337  return isset( $this->mArgs[$argId] );
338  }
339 
347  protected function getArg( $argId = 0, $default = null ) {
348  if ( func_num_args() === 0 ) {
349  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
350  }
351 
352  return $this->mArgs[$argId] ?? $default;
353  }
354 
362  protected function getBatchSize() {
363  return $this->mBatchSize;
364  }
365 
370  protected function setBatchSize( $s = 0 ) {
371  $this->mBatchSize = $s;
372 
373  // If we support $mBatchSize, show the option.
374  // Used to be in addDefaultParams, but in order for that to
375  // work, subclasses would have to call this function in the constructor
376  // before they called parent::__construct which is just weird
377  // (and really wasn't done).
378  if ( $this->mBatchSize ) {
379  $this->addOption( 'batch-size', 'Run this many operations ' .
380  'per batch, default: ' . $this->mBatchSize, false, true );
381  if ( isset( $this->mParams['batch-size'] ) ) {
382  // This seems a little ugly...
383  $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
384  }
385  }
386  }
387 
392  public function getName() {
393  return $this->mSelf;
394  }
395 
402  protected function getStdin( $len = null ) {
403  if ( $len == self::STDIN_ALL ) {
404  return file_get_contents( 'php://stdin' );
405  }
406  $f = fopen( 'php://stdin', 'rt' );
407  if ( !$len ) {
408  return $f;
409  }
410  $input = fgets( $f, $len );
411  fclose( $f );
412 
413  return rtrim( $input );
414  }
415 
419  public function isQuiet() {
420  return $this->mQuiet;
421  }
422 
429  protected function output( $out, $channel = null ) {
430  // This is sometimes called very early, before Setup.php is included.
431  if ( class_exists( MediaWikiServices::class ) ) {
432  // Try to periodically flush buffered metrics to avoid OOMs
433  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
434  if ( $stats->getDataCount() > 1000 ) {
435  MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
436  }
437  }
438 
439  if ( $this->mQuiet ) {
440  return;
441  }
442  if ( $channel === null ) {
443  $this->cleanupChanneled();
444  print $out;
445  } else {
446  $out = preg_replace( '/\n\z/', '', $out );
447  $this->outputChanneled( $out, $channel );
448  }
449  }
450 
457  protected function error( $err, $die = 0 ) {
458  if ( intval( $die ) !== 0 ) {
459  wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
460  $this->fatalError( $err, intval( $die ) );
461  }
462  $this->outputChanneled( false );
463  if (
464  ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
465  !defined( 'MW_PHPUNIT_TEST' )
466  ) {
467  fwrite( STDERR, $err . "\n" );
468  } else {
469  print $err;
470  }
471  }
472 
480  protected function fatalError( $msg, $exitCode = 1 ) {
481  $this->error( $msg );
482  exit( $exitCode );
483  }
484 
485  private $atLineStart = true;
486  private $lastChannel = null;
487 
491  public function cleanupChanneled() {
492  if ( !$this->atLineStart ) {
493  print "\n";
494  $this->atLineStart = true;
495  }
496  }
497 
506  public function outputChanneled( $msg, $channel = null ) {
507  if ( $msg === false ) {
508  $this->cleanupChanneled();
509 
510  return;
511  }
512 
513  // End the current line if necessary
514  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
515  print "\n";
516  }
517 
518  print $msg;
519 
520  $this->atLineStart = false;
521  if ( $channel === null ) {
522  // For unchanneled messages, output trailing newline immediately
523  print "\n";
524  $this->atLineStart = true;
525  }
526  $this->lastChannel = $channel;
527  }
528 
539  public function getDbType() {
540  return self::DB_STD;
541  }
542 
546  protected function addDefaultParams() {
547  # Generic (non script dependant) options:
548 
549  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
550  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
551  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
552  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
553  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
554  $this->addOption(
555  'memory-limit',
556  'Set a specific memory limit for the script, '
557  . '"max" for no limit or "default" to avoid changing it',
558  false,
559  true
560  );
561  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
562  "http://en.wikipedia.org. This is sometimes necessary because " .
563  "server name detection may fail in command line scripts.", false, true );
564  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
565 
566  # Save generic options to display them separately in help
567  $this->mGenericParameters = $this->mParams;
568 
569  # Script dependant options:
570 
571  // If we support a DB, show the options
572  if ( $this->getDbType() > 0 ) {
573  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
574  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
575  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
576  }
577 
578  # Save additional script dependant options to display
579  # ┬áthem separately in help
580  $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
581  }
582 
587  public function getConfig() {
588  if ( $this->config === null ) {
589  $this->config = MediaWikiServices::getInstance()->getMainConfig();
590  }
591 
592  return $this->config;
593  }
594 
599  public function setConfig( Config $config ) {
600  $this->config = $config;
601  }
602 
612  protected function requireExtension( $name ) {
613  $this->requiredExtensions[] = $name;
614  }
615 
621  public function checkRequiredExtensions() {
622  $registry = ExtensionRegistry::getInstance();
623  $missing = [];
624  foreach ( $this->requiredExtensions as $name ) {
625  if ( !$registry->isLoaded( $name ) ) {
626  $missing[] = $name;
627  }
628  }
629 
630  if ( $missing ) {
631  $joined = implode( ', ', $missing );
632  $msg = "The following extensions are required to be installed "
633  . "for this script to run: $joined. Please enable them and then try again.";
634  $this->fatalError( $msg );
635  }
636  }
637 
642  public function setAgentAndTriggers() {
643  if ( function_exists( 'posix_getpwuid' ) ) {
644  $agent = posix_getpwuid( posix_geteuid() )['name'];
645  } else {
646  $agent = 'sysadmin';
647  }
648  $agent .= '@' . wfHostname();
649 
650  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
651  // Add a comment for easy SHOW PROCESSLIST interpretation
652  $lbFactory->setAgentName(
653  mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
654  );
655  self::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
656  }
657 
663  public static function setLBFactoryTriggers( LBFactory $LBFactory, Config $config ) {
664  $services = MediaWikiServices::getInstance();
665  $stats = $services->getStatsdDataFactory();
666  // Hook into period lag checks which often happen in long-running scripts
667  $lbFactory = $services->getDBLoadBalancerFactory();
668  $lbFactory->setWaitForReplicationListener(
669  __METHOD__,
670  function () use ( $stats, $config ) {
671  // Check config in case of JobRunner and unit tests
672  if ( $config->get( 'CommandLineMode' ) ) {
673  DeferredUpdates::tryOpportunisticExecute( 'run' );
674  }
675  // Try to periodically flush buffered metrics to avoid OOMs
677  }
678  );
679  // Check for other windows to run them. A script may read or do a few writes
680  // to the master but mostly be writing to something else, like a file store.
681  $lbFactory->getMainLB()->setTransactionListener(
682  __METHOD__,
683  function ( $trigger ) use ( $stats, $config ) {
684  // Check config in case of JobRunner and unit tests
685  if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
686  DeferredUpdates::tryOpportunisticExecute( 'run' );
687  }
688  // Try to periodically flush buffered metrics to avoid OOMs
690  }
691  );
692  }
693 
701  public function runChild( $maintClass, $classFile = null ) {
702  // Make sure the class is loaded first
703  if ( !class_exists( $maintClass ) ) {
704  if ( $classFile ) {
705  require_once $classFile;
706  }
707  if ( !class_exists( $maintClass ) ) {
708  $this->error( "Cannot spawn child: $maintClass" );
709  }
710  }
711 
715  $child = new $maintClass();
716  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
717  if ( $this->mDb !== null ) {
718  $child->setDB( $this->mDb );
719  }
720 
721  return $child;
722  }
723 
727  public function setup() {
728  global $IP, $wgCommandLineMode;
729 
730  # Abort if called from a web server
731  # wfIsCLI() is not available yet
732  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
733  $this->fatalError( 'This script must be run from the command line' );
734  }
735 
736  if ( $IP === null ) {
737  $this->fatalError( "\$IP not set, aborting!\n" .
738  '(Did you forget to call parent::__construct() in your maintenance script?)' );
739  }
740 
741  # Make sure we can handle script parameters
742  if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
743  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
744  }
745 
746  // Send PHP warnings and errors to stderr instead of stdout.
747  // This aids in diagnosing problems, while keeping messages
748  // out of redirected output.
749  if ( ini_get( 'display_errors' ) ) {
750  ini_set( 'display_errors', 'stderr' );
751  }
752 
753  $this->loadParamsAndArgs();
754 
755  # Set the memory limit
756  # Note we need to set it again later in cache LocalSettings changed it
757  $this->adjustMemoryLimit();
758 
759  # Set max execution time to 0 (no limit). PHP.net says that
760  # "When running PHP from the command line the default setting is 0."
761  # But sometimes this doesn't seem to be the case.
762  ini_set( 'max_execution_time', 0 );
763 
764  $wgCommandLineMode = true;
765 
766  # Turn off output buffering if it's on
767  while ( ob_get_level() > 0 ) {
768  ob_end_flush();
769  }
770  }
771 
781  public function memoryLimit() {
782  $limit = $this->getOption( 'memory-limit', 'max' );
783  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
784  return $limit;
785  }
786 
790  protected function adjustMemoryLimit() {
791  $limit = $this->memoryLimit();
792  if ( $limit == 'max' ) {
793  $limit = -1; // no memory limit
794  }
795  if ( $limit != 'default' ) {
796  ini_set( 'memory_limit', $limit );
797  }
798  }
799 
803  protected function activateProfiler() {
805 
806  $output = $this->getOption( 'profiler' );
807  if ( !$output ) {
808  return;
809  }
810 
811  if ( isset( $wgProfiler['class'] ) ) {
812  $class = $wgProfiler['class'];
814  $profiler = new $class(
815  [ 'sampling' => 1, 'output' => [ $output ] ]
816  + $wgProfiler
817  + [ 'threshold' => 0.0 ]
818  );
819  $profiler->setAllowOutput();
820  Profiler::replaceStubInstance( $profiler );
821  }
822 
823  $trxProfiler = Profiler::instance()->getTransactionProfiler();
824  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
825  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
826  }
827 
831  public function clearParamsAndArgs() {
832  $this->mOptions = [];
833  $this->mArgs = [];
834  $this->mInputLoaded = false;
835  }
836 
844  public function loadWithArgv( $argv ) {
845  $options = [];
846  $args = [];
847  $this->orderedOptions = [];
848 
849  # Parse arguments
850  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
851  if ( $arg == '--' ) {
852  # End of options, remainder should be considered arguments
853  $arg = next( $argv );
854  while ( $arg !== false ) {
855  $args[] = $arg;
856  $arg = next( $argv );
857  }
858  break;
859  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
860  # Long options
861  $option = substr( $arg, 2 );
862  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
863  $param = next( $argv );
864  if ( $param === false ) {
865  $this->error( "\nERROR: $option parameter needs a value after it\n" );
866  $this->maybeHelp( true );
867  }
868 
869  $this->setParam( $options, $option, $param );
870  } else {
871  $bits = explode( '=', $option, 2 );
872  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
873  }
874  } elseif ( $arg == '-' ) {
875  # Lonely "-", often used to indicate stdin or stdout.
876  $args[] = $arg;
877  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
878  # Short options
879  $argLength = strlen( $arg );
880  for ( $p = 1; $p < $argLength; $p++ ) {
881  $option = $arg[$p];
882  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
883  $option = $this->mShortParamsMap[$option];
884  }
885 
886  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
887  $param = next( $argv );
888  if ( $param === false ) {
889  $this->error( "\nERROR: $option parameter needs a value after it\n" );
890  $this->maybeHelp( true );
891  }
892  $this->setParam( $options, $option, $param );
893  } else {
894  $this->setParam( $options, $option, 1 );
895  }
896  }
897  } else {
898  $args[] = $arg;
899  }
900  }
901 
902  $this->mOptions = $options;
903  $this->mArgs = $args;
904  $this->loadSpecialVars();
905  $this->mInputLoaded = true;
906  }
907 
920  private function setParam( &$options, $option, $value ) {
921  $this->orderedOptions[] = [ $option, $value ];
922 
923  if ( isset( $this->mParams[$option] ) ) {
924  $multi = $this->mParams[$option]['multiOccurrence'];
925  } else {
926  $multi = false;
927  }
928  $exists = array_key_exists( $option, $options );
929  if ( $multi && $exists ) {
930  $options[$option][] = $value;
931  } elseif ( $multi ) {
932  $options[$option] = [ $value ];
933  } elseif ( !$exists ) {
934  $options[$option] = $value;
935  } else {
936  $this->error( "\nERROR: $option parameter given twice\n" );
937  $this->maybeHelp( true );
938  }
939  }
940 
950  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
951  # If we were given opts or args, set those and return early
952  if ( $self ) {
953  $this->mSelf = $self;
954  $this->mInputLoaded = true;
955  }
956  if ( $opts ) {
957  $this->mOptions = $opts;
958  $this->mInputLoaded = true;
959  }
960  if ( $args ) {
961  $this->mArgs = $args;
962  $this->mInputLoaded = true;
963  }
964 
965  # If we've already loaded input (either by user values or from $argv)
966  # skip on loading it again. The array_shift() will corrupt values if
967  # it's run again and again
968  if ( $this->mInputLoaded ) {
969  $this->loadSpecialVars();
970 
971  return;
972  }
973 
974  global $argv;
975  $this->mSelf = $argv[0];
976  $this->loadWithArgv( array_slice( $argv, 1 ) );
977  }
978 
982  public function validateParamsAndArgs() {
983  $die = false;
984  # Check to make sure we've got all the required options
985  foreach ( $this->mParams as $opt => $info ) {
986  if ( $info['require'] && !$this->hasOption( $opt ) ) {
987  $this->error( "Param $opt required!" );
988  $die = true;
989  }
990  }
991  # Check arg list too
992  foreach ( $this->mArgList as $k => $info ) {
993  if ( $info['require'] && !$this->hasArg( $k ) ) {
994  $this->error( 'Argument <' . $info['name'] . '> required!' );
995  $die = true;
996  }
997  }
998  if ( !$this->mAllowUnregisteredOptions ) {
999  # Check for unexpected options
1000  foreach ( $this->mOptions as $opt => $val ) {
1001  if ( !$this->supportsOption( $opt ) ) {
1002  $this->error( "Unexpected option $opt!" );
1003  $die = true;
1004  }
1005  }
1006  }
1007 
1008  $this->maybeHelp( $die );
1009  }
1010 
1014  protected function loadSpecialVars() {
1015  if ( $this->hasOption( 'dbuser' ) ) {
1016  $this->mDbUser = $this->getOption( 'dbuser' );
1017  }
1018  if ( $this->hasOption( 'dbpass' ) ) {
1019  $this->mDbPass = $this->getOption( 'dbpass' );
1020  }
1021  if ( $this->hasOption( 'quiet' ) ) {
1022  $this->mQuiet = true;
1023  }
1024  if ( $this->hasOption( 'batch-size' ) ) {
1025  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1026  }
1027  }
1028 
1034  protected function maybeHelp( $force = false ) {
1035  if ( !$force && !$this->hasOption( 'help' ) ) {
1036  return;
1037  }
1038  $this->showHelp();
1039  die( 1 );
1040  }
1041 
1045  protected function showHelp() {
1046  $screenWidth = 80; // TODO: Calculate this!
1047  $tab = " ";
1048  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1049 
1050  ksort( $this->mParams );
1051  $this->mQuiet = false;
1052 
1053  // Description ...
1054  if ( $this->mDescription ) {
1055  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1056  }
1057  $output = "\nUsage: php " . basename( $this->mSelf );
1058 
1059  // ... append parameters ...
1060  if ( $this->mParams ) {
1061  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1062  }
1063 
1064  // ... and append arguments.
1065  if ( $this->mArgList ) {
1066  $output .= ' ';
1067  foreach ( $this->mArgList as $k => $arg ) {
1068  if ( $arg['require'] ) {
1069  $output .= '<' . $arg['name'] . '>';
1070  } else {
1071  $output .= '[' . $arg['name'] . ']';
1072  }
1073  if ( $k < count( $this->mArgList ) - 1 ) {
1074  $output .= ' ';
1075  }
1076  }
1077  }
1078  $this->output( "$output\n\n" );
1079 
1080  # TODO abstract some repetitive code below
1081 
1082  // Generic parameters
1083  $this->output( "Generic maintenance parameters:\n" );
1084  foreach ( $this->mGenericParameters as $par => $info ) {
1085  if ( $info['shortName'] !== false ) {
1086  $par .= " (-{$info['shortName']})";
1087  }
1088  $this->output(
1089  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1090  "\n$tab$tab" ) . "\n"
1091  );
1092  }
1093  $this->output( "\n" );
1094 
1095  $scriptDependantParams = $this->mDependantParameters;
1096  if ( count( $scriptDependantParams ) > 0 ) {
1097  $this->output( "Script dependant parameters:\n" );
1098  // Parameters description
1099  foreach ( $scriptDependantParams as $par => $info ) {
1100  if ( $info['shortName'] !== false ) {
1101  $par .= " (-{$info['shortName']})";
1102  }
1103  $this->output(
1104  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1105  "\n$tab$tab" ) . "\n"
1106  );
1107  }
1108  $this->output( "\n" );
1109  }
1110 
1111  // Script specific parameters not defined on construction by
1112  // Maintenance::addDefaultParams()
1113  $scriptSpecificParams = array_diff_key(
1114  # all script parameters:
1115  $this->mParams,
1116  # remove the Maintenance default parameters:
1117  $this->mGenericParameters,
1118  $this->mDependantParameters
1119  );
1120  '@phan-var array[] $scriptSpecificParams';
1121  if ( count( $scriptSpecificParams ) > 0 ) {
1122  $this->output( "Script specific parameters:\n" );
1123  // Parameters description
1124  foreach ( $scriptSpecificParams as $par => $info ) {
1125  if ( $info['shortName'] !== false ) {
1126  $par .= " (-{$info['shortName']})";
1127  }
1128  $this->output(
1129  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1130  "\n$tab$tab" ) . "\n"
1131  );
1132  }
1133  $this->output( "\n" );
1134  }
1135 
1136  // Print arguments
1137  if ( count( $this->mArgList ) > 0 ) {
1138  $this->output( "Arguments:\n" );
1139  // Arguments description
1140  foreach ( $this->mArgList as $info ) {
1141  $openChar = $info['require'] ? '<' : '[';
1142  $closeChar = $info['require'] ? '>' : ']';
1143  $this->output(
1144  wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1145  $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1146  );
1147  }
1148  $this->output( "\n" );
1149  }
1150  }
1151 
1155  public function finalSetup() {
1159 
1160  # Turn off output buffering again, it might have been turned on in the settings files
1161  if ( ob_get_level() ) {
1162  ob_end_flush();
1163  }
1164  # Same with these
1165  $wgCommandLineMode = true;
1166 
1167  # Override $wgServer
1168  if ( $this->hasOption( 'server' ) ) {
1169  $wgServer = $this->getOption( 'server', $wgServer );
1170  }
1171 
1172  # If these were passed, use them
1173  if ( $this->mDbUser ) {
1175  }
1176  if ( $this->mDbPass ) {
1178  }
1179  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1180  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1181 
1182  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1183  if ( $service ) {
1184  $service->destroy();
1185  }
1186  }
1187 
1188  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1191 
1192  if ( $wgDBservers ) {
1196  foreach ( $wgDBservers as $i => $server ) {
1197  $wgDBservers[$i]['user'] = $wgDBuser;
1198  $wgDBservers[$i]['password'] = $wgDBpassword;
1199  }
1200  }
1201  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1202  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1203  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1204  }
1205  $service = MediaWikiServices::getInstance()->peekService( 'DBLoadBalancerFactory' );
1206  if ( $service ) {
1207  $service->destroy();
1208  }
1209  }
1210 
1211  // Per-script profiling; useful for debugging
1212  $this->activateProfiler();
1213 
1214  $this->afterFinalSetup();
1215 
1216  $wgShowExceptionDetails = true;
1217  $wgShowHostnames = true;
1218 
1219  Wikimedia\suppressWarnings();
1220  set_time_limit( 0 );
1221  Wikimedia\restoreWarnings();
1222 
1223  $this->adjustMemoryLimit();
1224  }
1225 
1229  protected function afterFinalSetup() {
1230  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1231  // @phan-suppress-next-line PhanUndeclaredConstant
1232  call_user_func( MW_CMDLINE_CALLBACK );
1233  }
1234  }
1235 
1240  public function globals() {
1241  if ( $this->hasOption( 'globals' ) ) {
1242  print_r( $GLOBALS );
1243  }
1244  }
1245 
1250  public function loadSettings() {
1251  global $wgCommandLineMode, $IP;
1252 
1253  if ( isset( $this->mOptions['conf'] ) ) {
1254  $settingsFile = $this->mOptions['conf'];
1255  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1256  $settingsFile = MW_CONFIG_FILE;
1257  } else {
1258  $settingsFile = "$IP/LocalSettings.php";
1259  }
1260  if ( isset( $this->mOptions['wiki'] ) ) {
1261  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1262  define( 'MW_DB', $bits[0] );
1263  define( 'MW_PREFIX', $bits[1] ?? '' );
1264  } elseif ( isset( $this->mOptions['server'] ) ) {
1265  // Provide the option for site admins to detect and configure
1266  // multiple wikis based on server names. This offers --server
1267  // as alternative to --wiki.
1268  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1269  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1270  }
1271 
1272  if ( !is_readable( $settingsFile ) ) {
1273  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1274  "must exist and be readable in the source directory.\n" .
1275  "Use --conf to specify it." );
1276  }
1277  $wgCommandLineMode = true;
1278 
1279  return $settingsFile;
1280  }
1281 
1287  public function purgeRedundantText( $delete = true ) {
1288  # Data should come off the master, wrapped in a transaction
1289  $dbw = $this->getDB( DB_MASTER );
1290  $this->beginTransaction( $dbw, __METHOD__ );
1291 
1292  # Get "active" text records via the content table
1293  $cur = [];
1294  $this->output( 'Searching for active text records via contents table...' );
1295  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1296  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1297  foreach ( $res as $row ) {
1298  // @phan-suppress-next-line PhanUndeclaredMethod
1299  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1300  if ( $textId ) {
1301  $cur[] = $textId;
1302  }
1303  }
1304  $this->output( "done.\n" );
1305 
1306  # Get the IDs of all text records not in these sets
1307  $this->output( 'Searching for inactive text records...' );
1308  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1309  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1310  $old = [];
1311  foreach ( $res as $row ) {
1312  $old[] = $row->old_id;
1313  }
1314  $this->output( "done.\n" );
1315 
1316  # Inform the user of what we're going to do
1317  $count = count( $old );
1318  $this->output( "$count inactive items found.\n" );
1319 
1320  # Delete as appropriate
1321  if ( $delete && $count ) {
1322  $this->output( 'Deleting...' );
1323  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1324  $this->output( "done.\n" );
1325  }
1326 
1327  $this->commitTransaction( $dbw, __METHOD__ );
1328  }
1329 
1334  protected function getDir() {
1335  return __DIR__ . '/../';
1336  }
1337 
1350  protected function getDB( $db, $groups = [], $dbDomain = false ) {
1351  if ( $this->mDb === null ) {
1352  return MediaWikiServices::getInstance()
1353  ->getDBLoadBalancerFactory()
1354  ->getMainLB( $dbDomain )
1355  ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1356  }
1357 
1358  return $this->mDb;
1359  }
1360 
1366  public function setDB( IMaintainableDatabase $db ) {
1367  $this->mDb = $db;
1368  }
1369 
1380  protected function beginTransaction( IDatabase $dbw, $fname ) {
1381  $dbw->begin( $fname );
1382  }
1383 
1395  protected function commitTransaction( IDatabase $dbw, $fname ) {
1396  $dbw->commit( $fname );
1397  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1398  $waitSucceeded = $lbFactory->waitForReplication(
1399  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1400  );
1401  $this->lastReplicationWait = microtime( true );
1402  return $waitSucceeded;
1403  }
1404 
1415  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1416  $dbw->rollback( $fname );
1417  }
1418 
1423  private function lockSearchindex( $db ) {
1424  $write = [ 'searchindex' ];
1425  $read = [
1426  'page',
1427  'revision',
1428  'text',
1429  'interwiki',
1430  'l10n_cache',
1431  'user',
1432  'page_restrictions'
1433  ];
1434  $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1435  }
1436 
1441  private function unlockSearchindex( $db ) {
1442  $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1443  }
1444 
1450  private function relockSearchindex( $db ) {
1451  $this->unlockSearchindex( $db );
1452  $this->lockSearchindex( $db );
1453  }
1454 
1462  public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1463  $lockTime = time();
1464 
1465  # Lock searchindex
1466  if ( $maxLockTime ) {
1467  $this->output( " --- Waiting for lock ---" );
1468  $this->lockSearchindex( $dbw );
1469  $lockTime = time();
1470  $this->output( "\n" );
1471  }
1472 
1473  # Loop through the results and do a search update
1474  foreach ( $results as $row ) {
1475  # Allow reads to be processed
1476  if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1477  $this->output( " --- Relocking ---" );
1478  $this->relockSearchindex( $dbw );
1479  $lockTime = time();
1480  $this->output( "\n" );
1481  }
1482  call_user_func( $callback, $row );
1483  }
1484 
1485  # Unlock searchindex
1486  if ( $maxLockTime ) {
1487  $this->output( " --- Unlocking --" );
1488  $this->unlockSearchindex( $dbw );
1489  $this->output( "\n" );
1490  }
1491  }
1492 
1498  public function updateSearchIndexForPage( int $pageId ) {
1499  // Get current revision
1500  $rev = MediaWikiServices::getInstance()
1501  ->getRevisionLookup()
1502  ->getRevisionByPageId( $pageId, 0, IDBAccessObject::READ_LATEST );
1503  $title = null;
1504  if ( $rev ) {
1505  $titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
1506  $title = $titleObj->getPrefixedDBkey();
1507  $this->output( "$title..." );
1508  # Update searchindex
1509  $u = new SearchUpdate( $pageId, $titleObj, $rev->getContent( SlotRecord::MAIN ) );
1510  $u->doUpdate();
1511  $this->output( "\n" );
1512  }
1513 
1514  return $title;
1515  }
1516 
1527  protected function countDown( $seconds ) {
1528  if ( $this->isQuiet() ) {
1529  return;
1530  }
1531  for ( $i = $seconds; $i >= 0; $i-- ) {
1532  if ( $i != $seconds ) {
1533  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1534  }
1535  $this->output( $i );
1536  if ( $i ) {
1537  sleep( 1 );
1538  }
1539  }
1540  $this->output( "\n" );
1541  }
1542 
1551  public static function posix_isatty( $fd ) {
1552  if ( !function_exists( 'posix_isatty' ) ) {
1553  return !$fd;
1554  } else {
1555  return posix_isatty( $fd );
1556  }
1557  }
1558 
1564  public static function readconsole( $prompt = '> ' ) {
1565  static $isatty = null;
1566  if ( $isatty === null ) {
1567  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1568  }
1569 
1570  if ( $isatty && function_exists( 'readline' ) ) {
1571  return readline( $prompt );
1572  } else {
1573  if ( $isatty ) {
1574  $st = self::readlineEmulation( $prompt );
1575  } else {
1576  if ( feof( STDIN ) ) {
1577  $st = false;
1578  } else {
1579  $st = fgets( STDIN, 1024 );
1580  }
1581  }
1582  if ( $st === false ) {
1583  return false;
1584  }
1585  $resp = trim( $st );
1586 
1587  return $resp;
1588  }
1589  }
1590 
1596  private static function readlineEmulation( $prompt ) {
1597  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1598  if ( !wfIsWindows() && $bash ) {
1599  $retval = false;
1600  $encPrompt = Shell::escape( $prompt );
1601  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1602  $encCommand = Shell::escape( $command );
1603  $line = Shell::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1604 
1605  if ( $retval == 0 ) {
1606  return $line;
1607  } elseif ( $retval == 127 ) {
1608  // Couldn't execute bash even though we thought we saw it.
1609  // Shell probably spit out an error message, sorry :(
1610  // Fall through to fgets()...
1611  } else {
1612  // EOF/ctrl+D
1613  return false;
1614  }
1615  }
1616 
1617  // Fallback... we'll have no editing controls, EWWW
1618  if ( feof( STDIN ) ) {
1619  return false;
1620  }
1621  print $prompt;
1622 
1623  return fgets( STDIN, 1024 );
1624  }
1625 
1633  public static function getTermSize() {
1634  $default = [ 80, 50 ];
1635  if ( wfIsWindows() ) {
1636  return $default;
1637  }
1638  if ( Shell::isDisabled() ) {
1639  return $default;
1640  }
1641  // It's possible to get the screen size with VT-100 terminal escapes,
1642  // but reading the responses is not possible without setting raw mode
1643  // (unless you want to require the user to press enter), and that
1644  // requires an ioctl(), which we can't do. So we have to shell out to
1645  // something that can do the relevant syscalls. There are a few
1646  // options. Linux and Mac OS X both have "stty size" which does the
1647  // job directly.
1648  $result = Shell::command( 'stty', 'size' )
1649  ->execute();
1650  if ( $result->getExitCode() !== 0 ) {
1651  return $default;
1652  }
1653  if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1654  return $default;
1655  }
1656  return [ intval( $m[2] ), intval( $m[1] ) ];
1657  }
1658 
1663  public static function requireTestsAutoloader() {
1664  require_once __DIR__ . '/../../tests/common/TestsAutoLoader.php';
1665  }
1666 
1673  protected function getHookContainer() {
1674  if ( !$this->hookContainer ) {
1675  $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
1676  }
1677  return $this->hookContainer;
1678  }
1679 
1688  protected function getHookRunner() {
1689  if ( !$this->hookRunner ) {
1690  $this->hookRunner = new HookRunner( $this->getHookContainer() );
1691  }
1692  return $this->hookRunner;
1693  }
1694 }
Maintenance\$mBatchSize
int $mBatchSize
Batch size.
Definition: Maintenance.php:106
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:920
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:1633
Maintenance\$mShortParamsMap
$mShortParamsMap
Definition: Maintenance.php:73
MediaWiki\emitBufferedStatsdData
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:1092
Maintenance\getStdin
getStdin( $len=null)
Return input from stdin.
Definition: Maintenance.php:402
Profiler\replaceStubInstance
static replaceStubInstance(Profiler $profiler)
Replace the current profiler with $profiler if no non-stub profiler is set.
Definition: Profiler.php:96
Maintenance\$mGenericParameters
array[] $mGenericParameters
Generic options added by addDefaultParams()
Definition: Maintenance.php:113
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:149
Maintenance\getDbType
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition: Maintenance.php:539
Maintenance\maybeHelp
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:1034
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:480
Maintenance\$mDbPass
$mDbPass
Definition: Maintenance.php:92
Maintenance\updateSearchIndexForPage
updateSearchIndexForPage(int $pageId)
Update the searchindex table for a given pageid.
Definition: Maintenance.php:1498
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:323
Maintenance\setup
setup()
Do some sanity checking and basic setup.
Definition: Maintenance.php:727
Maintenance\$requiredExtensions
array $requiredExtensions
Definition: Maintenance.php:153
Maintenance\runChild
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
Definition: Maintenance.php:701
Maintenance\setLBFactoryTriggers
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
Definition: Maintenance.php:663
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1564
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6692
SearchUpdate
Database independant search index updater.
Definition: SearchUpdate.php:33
Maintenance\$mAllowUnregisteredOptions
$mAllowUnregisteredOptions
Definition: Maintenance.php:85
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:950
Maintenance\showHelp
showHelp()
Definitely show the help.
Definition: Maintenance.php:1045
Maintenance\$mParams
array[] $mParams
Array of desired/allowed params.
Definition: Maintenance.php:70
Maintenance\relockSearchindex
relockSearchindex( $db)
Unlock and lock again Since the lock is low-priority, queued reads will be able to complete.
Definition: Maintenance.php:1450
Maintenance\getName
getName()
Get the script's name.
Definition: Maintenance.php:392
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1260
Maintenance\$hookContainer
HookContainer null $hookContainer
Definition: Maintenance.php:137
Maintenance\$hookRunner
HookRunner null $hookRunner
Definition: Maintenance.php:140
$wgLBFactoryConf
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-master wiki farm, set the class here to somethi...
Definition: DefaultSettings.php:2207
$s
$s
Definition: mergeMessageFileList.php:185
Maintenance\hasArg
hasArg( $argId=0)
Does a given argument exist?
Definition: Maintenance.php:332
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:53
Maintenance\setConfig
setConfig(Config $config)
Definition: Maintenance.php:599
$res
$res
Definition: testCompression.php:57
$wgDBpassword
$wgDBpassword
Database user's password.
Definition: DefaultSettings.php:2010
Maintenance\$lastChannel
$lastChannel
Definition: Maintenance.php:486
Maintenance\loadWithArgv
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
Definition: Maintenance.php:844
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:621
Maintenance\finalSetup
finalSetup()
Handle some last-minute setup here.
Definition: Maintenance.php:1155
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
Definition: Maintenance.php:1415
Maintenance\$mDescription
$mDescription
Definition: Maintenance.php:95
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1380
Maintenance\afterFinalSetup
afterFinalSetup()
Execute a callback function at the end of initialisation.
Definition: Maintenance.php:1229
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
$wgDBadminuser
$wgDBadminuser
Separate username for maintenance tasks.
Definition: DefaultSettings.php:2040
Maintenance\unlockSearchindex
unlockSearchindex( $db)
Unlock the tables.
Definition: Maintenance.php:1441
Maintenance\clearParamsAndArgs
clearParamsAndArgs()
Clear all params and arguments.
Definition: Maintenance.php:831
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:2195
Maintenance\$mSelf
$mSelf
Definition: Maintenance.php:88
$wgDBDefaultGroup
$wgDBDefaultGroup
Default group to use when getting database connections.
Definition: DefaultSettings.php:2092
Maintenance\updateSearchIndex
updateSearchIndex( $maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
Definition: Maintenance.php:1462
Maintenance\$mArgs
$mArgs
Definition: Maintenance.php:82
$wgProfiler
$wgProfiler
Profiler configuration.
Definition: DefaultSettings.php:6767
Maintenance\loadSpecialVars
loadSpecialVars()
Handle the special variables that are global to all scripts.
Definition: Maintenance.php:1014
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:587
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1030
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
Maintenance\$atLineStart
$atLineStart
Definition: Maintenance.php:485
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
Maintenance\$lastReplicationWait
float $lastReplicationWait
UNIX timestamp.
Definition: Maintenance.php:128
$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:241
Maintenance\$mDbUser
$mDbUser
Definition: Maintenance.php:92
Maintenance\requireExtension
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
Definition: Maintenance.php:612
$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:166
Maintenance\globals
globals()
Potentially debug globals.
Definition: Maintenance.php:1240
$title
$title
Definition: testCompression.php:38
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Maintenance\addDefaultParams
addDefaultParams()
Add the default parameters to the scripts.
Definition: Maintenance.php:546
Maintenance\readlineEmulation
static readlineEmulation( $prompt)
Emulate readline()
Definition: Maintenance.php:1596
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:1527
Maintenance\DB_ADMIN
const DB_ADMIN
Definition: Maintenance.php:60
Maintenance\deleteOption
deleteOption( $name)
Remove an option.
Definition: Maintenance.php:306
Maintenance\shouldExecute
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class?...
Definition: Maintenance.php:184
Maintenance\DB_STD
const DB_STD
Definition: Maintenance.php:59
Maintenance\supportsOption
supportsOption( $name)
Checks to see if a particular option in supported.
Definition: Maintenance.php:226
Maintenance\$mQuiet
$mQuiet
Definition: Maintenance.php:91
Maintenance\isQuiet
isQuiet()
Definition: Maintenance.php:419
Maintenance\activateProfiler
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
Definition: Maintenance.php:803
Maintenance\getHookContainer
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
Definition: Maintenance.php:1673
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:315
Maintenance\$mDependantParameters
array[] $mDependantParameters
Generic options which might or not be supported by the script.
Definition: Maintenance.php:119
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:1844
$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:1663
$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:1551
Maintenance\getHookRunner
getHookRunner()
Get a HookRunner for running core hooks.
Definition: Maintenance.php:1688
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1395
Maintenance\validateParamsAndArgs
validateParamsAndArgs()
Run some validation checks on the params, etc.
Definition: Maintenance.php:982
Maintenance\$config
Config $config
Accessible via getConfig()
Definition: Maintenance.php:147
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1350
Maintenance\cleanupChanneled
cleanupChanneled()
Clean up channeled output.
Definition: Maintenance.php:491
Maintenance\DB_NONE
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:58
Maintenance\loadSettings
loadSettings()
Generic setup for most installs.
Definition: Maintenance.php:1250
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:281
Maintenance\adjustMemoryLimit
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
Definition: Maintenance.php:790
Maintenance\purgeRedundantText
purgeRedundantText( $delete=true)
Support function for cleaning up redundant text records.
Definition: Maintenance.php:1287
$self
$self
Definition: doMaintenance.php:61
Maintenance\$fileHandle
resource $fileHandle
Used when creating separate schema files.
Definition: Maintenance.php:134
print
print
Definition: opensearch_desc.php:53
$command
$command
Definition: mcc.php:125
Maintenance\$mInputLoaded
$mInputLoaded
Definition: Maintenance.php:98
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:277
Maintenance\STDIN_ALL
const STDIN_ALL
Definition: Maintenance.php:63
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:294
Wikimedia\Rdbms\LBFactory
An interface for generating database load balancers.
Definition: LBFactory.php:41
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:362
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
Definition: DefaultSettings.php:6664
Maintenance\$mOptions
$mOptions
Definition: Maintenance.php:79
Maintenance\setAgentAndTriggers
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
Definition: Maintenance.php:642
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1366
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:457
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:429
Maintenance\$mArgList
$mArgList
Definition: Maintenance.php:76
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:44
Maintenance\getDir
getDir()
Get the maintenance directory.
Definition: Maintenance.php:1334
$wgDBuser
$wgDBuser
Database username.
Definition: DefaultSettings.php:2005
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:563
ExecutableFinder\findInDefaultPaths
static findInDefaultPaths( $names, $versionInfo=false)
Same as locateExecutable(), but checks in getPossibleBinPaths() by default.
Definition: ExecutableFinder.php:96
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:262
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:347
$maintClass
string false $maintClass
-var class-string|false
Definition: Maintenance.php:48
$IP
$IP
Definition: WebStart.php:49
$wgDBadminpassword
$wgDBadminpassword
Separate password for maintenance tasks.
Definition: DefaultSettings.php:2045
Maintenance\outputChanneled
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
Definition: Maintenance.php:506
Maintenance\__construct
__construct()
Default constructor.
Definition: Maintenance.php:172
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:6526
Maintenance\execute
execute()
Do the actual work.
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
Wikimedia\Rdbms\IDatabase\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Wikimedia\Rdbms\IDatabase\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Maintenance\lockSearchindex
lockSearchindex( $db)
Lock the search index.
Definition: Maintenance.php:1423
Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:39
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:370
Maintenance\$mDb
IMaintainableDatabase $mDb
Used by getDB() / setDB()
Definition: Maintenance.php:125
Maintenance\memoryLimit
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
Definition: Maintenance.php:781