3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Bail on old versions of PHP, or if composer has not been run yet to install
25 require_once __DIR__
. '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'text' );
28 use MediaWiki\Shell\Shell
;
31 * @defgroup MaintenanceArchive Maintenance archives
32 * @ingroup Maintenance
35 // Define this so scripts can easily find doMaintenance.php
36 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
39 * @deprecated since 1.31
41 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
45 use Wikimedia\Rdbms\IDatabase
;
46 use MediaWiki\Logger\LoggerFactory
;
47 use MediaWiki\MediaWikiServices
;
48 use Wikimedia\Rdbms\LBFactory
;
49 use Wikimedia\Rdbms\IMaintainableDatabase
;
52 * Abstract maintenance class for quickly writing and churning out
53 * maintenance scripts with minimal effort. All that _must_ be defined
54 * is the execute() method. See docs/maintenance.txt for more info
55 * and a quick demo of how to use it.
58 * @ingroup Maintenance
60 abstract class Maintenance
{
62 * Constants for DB access type
63 * @see Maintenance::getDbType()
69 // Const for getStdin()
70 const STDIN_ALL
= 'all';
72 // This is the desired params
73 protected $mParams = [];
75 // Array of mapping short parameters to long ones
76 protected $mShortParamsMap = [];
78 // Array of desired args
79 protected $mArgList = [];
81 // This is the list of options that were actually passed
82 protected $mOptions = [];
84 // This is the list of arguments that were actually passed
85 protected $mArgs = [];
87 // Allow arbitrary options to be passed, or only specified ones?
88 protected $mAllowUnregisteredOptions = false;
90 // Name of the script currently running
93 // Special vars for params that are always used
94 protected $mQuiet = false;
95 protected $mDbUser, $mDbPass;
97 // A description of the script, children should change this via addDescription()
98 protected $mDescription = '';
100 // Have we already loaded our user input?
101 protected $mInputLoaded = false;
104 * Batch size. If a script supports this, they should set
105 * a default with setBatchSize()
109 protected $mBatchSize = null;
111 // Generic options added by addDefaultParams()
112 private $mGenericParameters = [];
113 // Generic options which might or not be supported by the script
114 private $mDependantParameters = [];
117 * Used by getDB() / setDB()
118 * @var IMaintainableDatabase
122 /** @var float UNIX timestamp */
123 private $lastReplicationWait = 0.0;
126 * Used when creating separate schema files.
132 * Accessible via getConfig()
139 * @see Maintenance::requireExtension
142 private $requiredExtensions = [];
145 * Used to read the options in the order they were passed.
146 * Useful for option chaining (Ex. dumpBackup.php). It will
147 * be an empty array if the options are passed in through
148 * loadParamsAndArgs( $self, $opts, $args ).
150 * This is an array of arrays where
151 * 0 => the option and 1 => parameter value.
155 public $orderedOptions = [];
158 * Default constructor. Children should call this *first* if implementing
159 * their own constructors
161 public function __construct() {
162 // Setup $IP, using MW_INSTALL_PATH if it exists
164 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
165 ?
getenv( 'MW_INSTALL_PATH' )
166 : realpath( __DIR__
. '/..' );
168 $this->addDefaultParams();
169 register_shutdown_function( [ $this, 'outputChanneled' ], false );
173 * Should we execute the maintenance script, or just allow it to be included
174 * as a standalone class? It checks that the call stack only includes this
175 * function and "requires" (meaning was called from the file scope)
179 public static function shouldExecute() {
180 global $wgCommandLineMode;
182 if ( !function_exists( 'debug_backtrace' ) ) {
183 // If someone has a better idea...
184 return $wgCommandLineMode;
187 $bt = debug_backtrace();
188 $count = count( $bt );
190 return false; // sanity
192 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
193 return false; // last call should be to this function
195 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
196 for ( $i = 1; $i < $count; $i++
) {
197 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
198 return false; // previous calls should all be "requires"
206 * Do the actual work. All child classes will need to implement this
208 * @return bool|null|void True for success, false for failure. Not returning
209 * a value, or returning null, is also interpreted as success. Returning
210 * false for failure will cause doMaintenance.php to exit the process
211 * with a non-zero exit status.
213 abstract public function execute();
216 * Checks to see if a particular option in supported. Normally this means it
217 * has been registered by the script via addOption.
218 * @param string $name The name of the option
219 * @return bool true if the option exists, false otherwise
221 protected function supportsOption( $name ) {
222 return isset( $this->mParams
[$name] );
226 * Add a parameter to the script. Will be displayed on --help
227 * with the associated description
229 * @param string $name The name of the param (help, version, etc)
230 * @param string $description The description of the param to show on --help
231 * @param bool $required Is the param required?
232 * @param bool $withArg Is an argument required with this option?
233 * @param string|bool $shortName Character to use as short name
234 * @param bool $multiOccurrence Can this option be passed multiple times?
236 protected function addOption( $name, $description, $required = false,
237 $withArg = false, $shortName = false, $multiOccurrence = false
239 $this->mParams
[$name] = [
240 'desc' => $description,
241 'require' => $required,
242 'withArg' => $withArg,
243 'shortName' => $shortName,
244 'multiOccurrence' => $multiOccurrence
247 if ( $shortName !== false ) {
248 $this->mShortParamsMap
[$shortName] = $name;
253 * Checks to see if a particular option exists.
254 * @param string $name The name of the option
257 protected function hasOption( $name ) {
258 return isset( $this->mOptions
[$name] );
262 * Get an option, or return the default.
264 * If the option was added to support multiple occurrences,
265 * this will return an array.
267 * @param string $name The name of the param
268 * @param mixed|null $default Anything you want, default null
271 protected function getOption( $name, $default = null ) {
272 if ( $this->hasOption( $name ) ) {
273 return $this->mOptions
[$name];
275 // Set it so we don't have to provide the default again
276 $this->mOptions
[$name] = $default;
278 return $this->mOptions
[$name];
283 * Add some args that are needed
284 * @param string $arg Name of the arg, like 'start'
285 * @param string $description Short description of the arg
286 * @param bool $required Is this required?
288 protected function addArg( $arg, $description, $required = true ) {
289 $this->mArgList
[] = [
291 'desc' => $description,
292 'require' => $required
297 * Remove an option. Useful for removing options that won't be used in your script.
298 * @param string $name The option to remove.
300 protected function deleteOption( $name ) {
301 unset( $this->mParams
[$name] );
305 * Sets whether to allow unregistered options, which are options passed to
306 * a script that do not match an expected parameter.
307 * @param bool $allow Should we allow?
309 protected function setAllowUnregisteredOptions( $allow ) {
310 $this->mAllowUnregisteredOptions
= $allow;
314 * Set the description text.
315 * @param string $text The text of the description
317 protected function addDescription( $text ) {
318 $this->mDescription
= $text;
322 * Does a given argument exist?
323 * @param int $argId The integer value (from zero) for the arg
326 protected function hasArg( $argId = 0 ) {
327 return isset( $this->mArgs
[$argId] );
332 * @param int $argId The integer value (from zero) for the arg
333 * @param mixed|null $default The default if it doesn't exist
336 protected function getArg( $argId = 0, $default = null ) {
337 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
347 protected function getBatchSize() {
348 return $this->mBatchSize
;
352 * Set the batch size.
353 * @param int $s The number of operations to do in a batch
355 protected function setBatchSize( $s = 0 ) {
356 $this->mBatchSize
= $s;
358 // If we support $mBatchSize, show the option.
359 // Used to be in addDefaultParams, but in order for that to
360 // work, subclasses would have to call this function in the constructor
361 // before they called parent::__construct which is just weird
362 // (and really wasn't done).
363 if ( $this->mBatchSize
) {
364 $this->addOption( 'batch-size', 'Run this many operations ' .
365 'per batch, default: ' . $this->mBatchSize
, false, true );
366 if ( isset( $this->mParams
['batch-size'] ) ) {
367 // This seems a little ugly...
368 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
374 * Get the script's name
377 public function getName() {
382 * Return input from stdin.
383 * @param int|null $len The number of bytes to read. If null, just return the handle.
384 * Maintenance::STDIN_ALL returns the full length
387 protected function getStdin( $len = null ) {
388 if ( $len == self
::STDIN_ALL
) {
389 return file_get_contents( 'php://stdin' );
391 $f = fopen( 'php://stdin', 'rt' );
395 $input = fgets( $f, $len );
398 return rtrim( $input );
404 public function isQuiet() {
405 return $this->mQuiet
;
409 * Throw some output to the user. Scripts can call this with no fears,
410 * as we handle all --quiet stuff here
411 * @param string $out The text to show to the user
412 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
414 protected function output( $out, $channel = null ) {
415 // This is sometimes called very early, before Setup.php is included.
416 if ( class_exists( MediaWikiServices
::class ) ) {
417 // Try to periodically flush buffered metrics to avoid OOMs
418 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
419 if ( $stats->getDataCount() > 1000 ) {
420 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
424 if ( $this->mQuiet
) {
427 if ( $channel === null ) {
428 $this->cleanupChanneled();
431 $out = preg_replace( '/\n\z/', '', $out );
432 $this->outputChanneled( $out, $channel );
437 * Throw an error to the user. Doesn't respect --quiet, so don't use
438 * this for non-error output
439 * @param string $err The error to display
440 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
442 protected function error( $err, $die = 0 ) {
443 if ( intval( $die ) !== 0 ) {
444 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
445 $this->fatalError( $err, intval( $die ) );
447 $this->outputChanneled( false );
449 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
450 !defined( 'MW_PHPUNIT_TEST' )
452 fwrite( STDERR
, $err . "\n" );
459 * Output a message and terminate the current script.
461 * @param string $msg Error message
462 * @param int $exitCode PHP exit status. Should be in range 1-254.
465 protected function fatalError( $msg, $exitCode = 1 ) {
466 $this->error( $msg );
470 private $atLineStart = true;
471 private $lastChannel = null;
474 * Clean up channeled output. Output a newline if necessary.
476 public function cleanupChanneled() {
477 if ( !$this->atLineStart
) {
479 $this->atLineStart
= true;
484 * Message outputter with channeled message support. Messages on the
485 * same channel are concatenated, but any intervening messages in another
486 * channel start a new line.
487 * @param string $msg The message without trailing newline
488 * @param string|null $channel Channel identifier or null for no
489 * channel. Channel comparison uses ===.
491 public function outputChanneled( $msg, $channel = null ) {
492 if ( $msg === false ) {
493 $this->cleanupChanneled();
498 // End the current line if necessary
499 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
505 $this->atLineStart
= false;
506 if ( $channel === null ) {
507 // For unchanneled messages, output trailing newline immediately
509 $this->atLineStart
= true;
511 $this->lastChannel
= $channel;
515 * Does the script need different DB access? By default, we give Maintenance
516 * scripts normal rights to the DB. Sometimes, a script needs admin rights
517 * access for a reason and sometimes they want no access. Subclasses should
518 * override and return one of the following values, as needed:
519 * Maintenance::DB_NONE - For no DB access at all
520 * Maintenance::DB_STD - For normal DB access, default
521 * Maintenance::DB_ADMIN - For admin DB access
524 public function getDbType() {
529 * Add the default parameters to the scripts
531 protected function addDefaultParams() {
532 # Generic (non script dependant) options:
534 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
535 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
536 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
537 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
538 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
541 'Set a specific memory limit for the script, '
542 . '"max" for no limit or "default" to avoid changing it',
546 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
547 "http://en.wikipedia.org. This is sometimes necessary because " .
548 "server name detection may fail in command line scripts.", false, true );
549 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
550 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
551 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
553 # Save generic options to display them separately in help
554 $this->mGenericParameters
= $this->mParams
;
556 # Script dependant options:
558 // If we support a DB, show the options
559 if ( $this->getDbType() > 0 ) {
560 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
561 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
562 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
565 # Save additional script dependant options to display
566 # Â them separately in help
567 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
574 public function getConfig() {
575 if ( $this->config
=== null ) {
576 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
579 return $this->config
;
584 * @param Config $config
586 public function setConfig( Config
$config ) {
587 $this->config
= $config;
591 * Indicate that the specified extension must be
592 * loaded before the script can run.
594 * This *must* be called in the constructor.
597 * @param string $name
599 protected function requireExtension( $name ) {
600 $this->requiredExtensions
[] = $name;
604 * Verify that the required extensions are installed
608 public function checkRequiredExtensions() {
609 $registry = ExtensionRegistry
::getInstance();
611 foreach ( $this->requiredExtensions
as $name ) {
612 if ( !$registry->isLoaded( $name ) ) {
618 $joined = implode( ', ', $missing );
619 $msg = "The following extensions are required to be installed "
620 . "for this script to run: $joined. Please enable them and then try again.";
621 $this->fatalError( $msg );
626 * Set triggers like when to try to run deferred updates
629 public function setAgentAndTriggers() {
630 if ( function_exists( 'posix_getpwuid' ) ) {
631 $agent = posix_getpwuid( posix_geteuid() )['name'];
635 $agent .= '@' . wfHostname();
637 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
638 // Add a comment for easy SHOW PROCESSLIST interpretation
639 $lbFactory->setAgentName(
640 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
642 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
646 * @param LBFactory $LBFactory
647 * @param Config $config
650 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
651 $services = MediaWikiServices
::getInstance();
652 $stats = $services->getStatsdDataFactory();
653 // Hook into period lag checks which often happen in long-running scripts
654 $lbFactory = $services->getDBLoadBalancerFactory();
655 $lbFactory->setWaitForReplicationListener(
657 function () use ( $stats, $config ) {
658 // Check config in case of JobRunner and unit tests
659 if ( $config->get( 'CommandLineMode' ) ) {
660 DeferredUpdates
::tryOpportunisticExecute( 'run' );
662 // Try to periodically flush buffered metrics to avoid OOMs
663 MediaWiki
::emitBufferedStatsdData( $stats, $config );
666 // Check for other windows to run them. A script may read or do a few writes
667 // to the master but mostly be writing to something else, like a file store.
668 $lbFactory->getMainLB()->setTransactionListener(
670 function ( $trigger ) use ( $stats, $config ) {
671 // Check config in case of JobRunner and unit tests
672 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
673 DeferredUpdates
::tryOpportunisticExecute( 'run' );
675 // Try to periodically flush buffered metrics to avoid OOMs
676 MediaWiki
::emitBufferedStatsdData( $stats, $config );
682 * Run a child maintenance script. Pass all of the current arguments
684 * @param string $maintClass A name of a child maintenance class
685 * @param string|null $classFile Full path of where the child is
686 * @return Maintenance
688 public function runChild( $maintClass, $classFile = null ) {
689 // Make sure the class is loaded first
690 if ( !class_exists( $maintClass ) ) {
692 require_once $classFile;
694 if ( !class_exists( $maintClass ) ) {
695 $this->error( "Cannot spawn child: $maintClass" );
700 * @var $child Maintenance
702 $child = new $maintClass();
703 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
704 if ( !is_null( $this->mDb
) ) {
705 $child->setDB( $this->mDb
);
712 * Do some sanity checking and basic setup
714 public function setup() {
715 global $IP, $wgCommandLineMode;
717 # Abort if called from a web server
718 # wfIsCLI() is not available yet
719 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
720 $this->fatalError( 'This script must be run from the command line' );
723 if ( $IP === null ) {
724 $this->fatalError( "\$IP not set, aborting!\n" .
725 '(Did you forget to call parent::__construct() in your maintenance script?)' );
728 # Make sure we can handle script parameters
729 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
730 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
733 // Send PHP warnings and errors to stderr instead of stdout.
734 // This aids in diagnosing problems, while keeping messages
735 // out of redirected output.
736 if ( ini_get( 'display_errors' ) ) {
737 ini_set( 'display_errors', 'stderr' );
740 $this->loadParamsAndArgs();
743 # Set the memory limit
744 # Note we need to set it again later in cache LocalSettings changed it
745 $this->adjustMemoryLimit();
747 # Set max execution time to 0 (no limit). PHP.net says that
748 # "When running PHP from the command line the default setting is 0."
749 # But sometimes this doesn't seem to be the case.
750 ini_set( 'max_execution_time', 0 );
752 # Define us as being in MediaWiki
753 define( 'MEDIAWIKI', true );
755 $wgCommandLineMode = true;
757 # Turn off output buffering if it's on
758 while ( ob_get_level() > 0 ) {
762 $this->validateParamsAndArgs();
766 * Normally we disable the memory_limit when running admin scripts.
767 * Some scripts may wish to actually set a limit, however, to avoid
768 * blowing up unexpectedly. We also support a --memory-limit option,
769 * to allow sysadmins to explicitly set one if they'd prefer to override
770 * defaults (or for people using Suhosin which yells at you for trying
771 * to disable the limits)
774 public function memoryLimit() {
775 $limit = $this->getOption( 'memory-limit', 'max' );
776 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
781 * Adjusts PHP's memory limit to better suit our needs, if needed.
783 protected function adjustMemoryLimit() {
784 $limit = $this->memoryLimit();
785 if ( $limit == 'max' ) {
786 $limit = -1; // no memory limit
788 if ( $limit != 'default' ) {
789 ini_set( 'memory_limit', $limit );
794 * Activate the profiler (assuming $wgProfiler is set)
796 protected function activateProfiler() {
797 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
799 $output = $this->getOption( 'profiler' );
804 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
805 $class = $wgProfiler['class'];
806 /** @var Profiler $profiler */
807 $profiler = new $class(
808 [ 'sampling' => 1, 'output' => [ $output ] ]
810 +
[ 'threshold' => $wgProfileLimit ]
812 $profiler->setTemplated( true );
813 Profiler
::replaceStubInstance( $profiler );
816 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
817 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
818 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
822 * Clear all params and arguments.
824 public function clearParamsAndArgs() {
825 $this->mOptions
= [];
827 $this->mInputLoaded
= false;
831 * Load params and arguments from a given array
832 * of command-line arguments
837 public function loadWithArgv( $argv ) {
840 $this->orderedOptions
= [];
843 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
844 if ( $arg == '--' ) {
845 # End of options, remainder should be considered arguments
846 $arg = next( $argv );
847 while ( $arg !== false ) {
849 $arg = next( $argv );
852 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
854 $option = substr( $arg, 2 );
855 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
856 $param = next( $argv );
857 if ( $param === false ) {
858 $this->error( "\nERROR: $option parameter needs a value after it\n" );
859 $this->maybeHelp( true );
862 $this->setParam( $options, $option, $param );
864 $bits = explode( '=', $option, 2 );
865 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
867 } elseif ( $arg == '-' ) {
868 # Lonely "-", often used to indicate stdin or stdout.
870 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
872 $argLength = strlen( $arg );
873 for ( $p = 1; $p < $argLength; $p++
) {
875 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
876 $option = $this->mShortParamsMap
[$option];
879 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
880 $param = next( $argv );
881 if ( $param === false ) {
882 $this->error( "\nERROR: $option parameter needs a value after it\n" );
883 $this->maybeHelp( true );
885 $this->setParam( $options, $option, $param );
887 $this->setParam( $options, $option, 1 );
895 $this->mOptions
= $options;
896 $this->mArgs
= $args;
897 $this->loadSpecialVars();
898 $this->mInputLoaded
= true;
902 * Helper function used solely by loadParamsAndArgs
903 * to prevent code duplication
905 * This sets the param in the options array based on
906 * whether or not it can be specified multiple times.
909 * @param array $options
910 * @param string $option
911 * @param mixed $value
913 private function setParam( &$options, $option, $value ) {
914 $this->orderedOptions
[] = [ $option, $value ];
916 if ( isset( $this->mParams
[$option] ) ) {
917 $multi = $this->mParams
[$option]['multiOccurrence'];
921 $exists = array_key_exists( $option, $options );
922 if ( $multi && $exists ) {
923 $options[$option][] = $value;
924 } elseif ( $multi ) {
925 $options[$option] = [ $value ];
926 } elseif ( !$exists ) {
927 $options[$option] = $value;
929 $this->error( "\nERROR: $option parameter given twice\n" );
930 $this->maybeHelp( true );
935 * Process command line arguments
936 * $mOptions becomes an array with keys set to the option names
937 * $mArgs becomes a zero-based array containing the non-option arguments
939 * @param string|null $self The name of the script, if any
940 * @param array|null $opts An array of options, in form of key=>value
941 * @param array|null $args An array of command line arguments
943 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
944 # If we were given opts or args, set those and return early
946 $this->mSelf
= $self;
947 $this->mInputLoaded
= true;
950 $this->mOptions
= $opts;
951 $this->mInputLoaded
= true;
954 $this->mArgs
= $args;
955 $this->mInputLoaded
= true;
958 # If we've already loaded input (either by user values or from $argv)
959 # skip on loading it again. The array_shift() will corrupt values if
960 # it's run again and again
961 if ( $this->mInputLoaded
) {
962 $this->loadSpecialVars();
968 $this->mSelf
= $argv[0];
969 $this->loadWithArgv( array_slice( $argv, 1 ) );
973 * Run some validation checks on the params, etc
975 protected function validateParamsAndArgs() {
977 # Check to make sure we've got all the required options
978 foreach ( $this->mParams
as $opt => $info ) {
979 if ( $info['require'] && !$this->hasOption( $opt ) ) {
980 $this->error( "Param $opt required!" );
985 foreach ( $this->mArgList
as $k => $info ) {
986 if ( $info['require'] && !$this->hasArg( $k ) ) {
987 $this->error( 'Argument <' . $info['name'] . '> required!' );
991 if ( !$this->mAllowUnregisteredOptions
) {
992 # Check for unexpected options
993 foreach ( $this->mOptions
as $opt => $val ) {
994 if ( !$this->supportsOption( $opt ) ) {
995 $this->error( "Unexpected option $opt!" );
1002 $this->maybeHelp( true );
1007 * Handle the special variables that are global to all scripts
1009 protected function loadSpecialVars() {
1010 if ( $this->hasOption( 'dbuser' ) ) {
1011 $this->mDbUser
= $this->getOption( 'dbuser' );
1013 if ( $this->hasOption( 'dbpass' ) ) {
1014 $this->mDbPass
= $this->getOption( 'dbpass' );
1016 if ( $this->hasOption( 'quiet' ) ) {
1017 $this->mQuiet
= true;
1019 if ( $this->hasOption( 'batch-size' ) ) {
1020 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1025 * Maybe show the help.
1026 * @param bool $force Whether to force the help to show, default false
1028 protected function maybeHelp( $force = false ) {
1029 if ( !$force && !$this->hasOption( 'help' ) ) {
1033 $screenWidth = 80; // TODO: Calculate this!
1035 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1037 ksort( $this->mParams
);
1038 $this->mQuiet
= false;
1041 if ( $this->mDescription
) {
1042 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1044 $output = "\nUsage: php " . basename( $this->mSelf
);
1046 // ... append parameters ...
1047 if ( $this->mParams
) {
1048 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1051 // ... and append arguments.
1052 if ( $this->mArgList
) {
1054 foreach ( $this->mArgList
as $k => $arg ) {
1055 if ( $arg['require'] ) {
1056 $output .= '<' . $arg['name'] . '>';
1058 $output .= '[' . $arg['name'] . ']';
1060 if ( $k < count( $this->mArgList
) - 1 ) {
1065 $this->output( "$output\n\n" );
1067 # TODO abstract some repetitive code below
1069 // Generic parameters
1070 $this->output( "Generic maintenance parameters:\n" );
1071 foreach ( $this->mGenericParameters
as $par => $info ) {
1072 if ( $info['shortName'] !== false ) {
1073 $par .= " (-{$info['shortName']})";
1076 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1077 "\n$tab$tab" ) . "\n"
1080 $this->output( "\n" );
1082 $scriptDependantParams = $this->mDependantParameters
;
1083 if ( count( $scriptDependantParams ) > 0 ) {
1084 $this->output( "Script dependant parameters:\n" );
1085 // Parameters description
1086 foreach ( $scriptDependantParams as $par => $info ) {
1087 if ( $info['shortName'] !== false ) {
1088 $par .= " (-{$info['shortName']})";
1091 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1092 "\n$tab$tab" ) . "\n"
1095 $this->output( "\n" );
1098 // Script specific parameters not defined on construction by
1099 // Maintenance::addDefaultParams()
1100 $scriptSpecificParams = array_diff_key(
1101 # all script parameters:
1103 # remove the Maintenance default parameters:
1104 $this->mGenericParameters
,
1105 $this->mDependantParameters
1107 if ( count( $scriptSpecificParams ) > 0 ) {
1108 $this->output( "Script specific parameters:\n" );
1109 // Parameters description
1110 foreach ( $scriptSpecificParams as $par => $info ) {
1111 if ( $info['shortName'] !== false ) {
1112 $par .= " (-{$info['shortName']})";
1115 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1116 "\n$tab$tab" ) . "\n"
1119 $this->output( "\n" );
1123 if ( count( $this->mArgList
) > 0 ) {
1124 $this->output( "Arguments:\n" );
1125 // Arguments description
1126 foreach ( $this->mArgList
as $info ) {
1127 $openChar = $info['require'] ?
'<' : '[';
1128 $closeChar = $info['require'] ?
'>' : ']';
1130 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1131 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1134 $this->output( "\n" );
1141 * Handle some last-minute setup here.
1143 public function finalSetup() {
1144 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1145 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1146 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1148 # Turn off output buffering again, it might have been turned on in the settings files
1149 if ( ob_get_level() ) {
1153 $wgCommandLineMode = true;
1155 # Override $wgServer
1156 if ( $this->hasOption( 'server' ) ) {
1157 $wgServer = $this->getOption( 'server', $wgServer );
1160 # If these were passed, use them
1161 if ( $this->mDbUser
) {
1162 $wgDBadminuser = $this->mDbUser
;
1164 if ( $this->mDbPass
) {
1165 $wgDBadminpassword = $this->mDbPass
;
1167 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1168 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1170 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1173 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1174 $wgDBuser = $wgDBadminuser;
1175 $wgDBpassword = $wgDBadminpassword;
1177 if ( $wgDBservers ) {
1179 * @var $wgDBservers array
1181 foreach ( $wgDBservers as $i => $server ) {
1182 $wgDBservers[$i]['user'] = $wgDBuser;
1183 $wgDBservers[$i]['password'] = $wgDBpassword;
1186 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1187 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1188 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1190 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1193 # Apply debug settings
1194 if ( $this->hasOption( 'mwdebug' ) ) {
1195 require __DIR__
. '/../includes/DevelopmentSettings.php';
1198 // Per-script profiling; useful for debugging
1199 $this->activateProfiler();
1201 $this->afterFinalSetup();
1203 $wgShowExceptionDetails = true;
1204 $wgShowHostnames = true;
1206 Wikimedia\
suppressWarnings();
1207 set_time_limit( 0 );
1208 Wikimedia\restoreWarnings
();
1210 $this->adjustMemoryLimit();
1214 * Execute a callback function at the end of initialisation
1216 protected function afterFinalSetup() {
1217 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1218 call_user_func( MW_CMDLINE_CALLBACK
);
1223 * Potentially debug globals. Originally a feature only
1226 public function globals() {
1227 if ( $this->hasOption( 'globals' ) ) {
1228 print_r( $GLOBALS );
1233 * Generic setup for most installs. Returns the location of LocalSettings
1236 public function loadSettings() {
1237 global $wgCommandLineMode, $IP;
1239 if ( isset( $this->mOptions
['conf'] ) ) {
1240 $settingsFile = $this->mOptions
['conf'];
1241 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1242 $settingsFile = MW_CONFIG_FILE
;
1244 $settingsFile = "$IP/LocalSettings.php";
1246 if ( isset( $this->mOptions
['wiki'] ) ) {
1247 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1248 define( 'MW_DB', $bits[0] );
1249 define( 'MW_PREFIX', $bits[1] ??
'' );
1250 } elseif ( isset( $this->mOptions
['server'] ) ) {
1251 // Provide the option for site admins to detect and configure
1252 // multiple wikis based on server names. This offers --server
1253 // as alternative to --wiki.
1254 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1255 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1258 if ( !is_readable( $settingsFile ) ) {
1259 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1260 "must exist and be readable in the source directory.\n" .
1261 "Use --conf to specify it." );
1263 $wgCommandLineMode = true;
1265 return $settingsFile;
1269 * Support function for cleaning up redundant text records
1270 * @param bool $delete Whether or not to actually delete the records
1271 * @author Rob Church <robchur@gmail.com>
1273 public function purgeRedundantText( $delete = true ) {
1274 global $wgMultiContentRevisionSchemaMigrationStage;
1276 # Data should come off the master, wrapped in a transaction
1277 $dbw = $this->getDB( DB_MASTER
);
1278 $this->beginTransaction( $dbw, __METHOD__
);
1280 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1281 # Get "active" text records from the revisions table
1283 $this->output( 'Searching for active text records in revisions table...' );
1284 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1285 foreach ( $res as $row ) {
1286 $cur[] = $row->rev_text_id
;
1288 $this->output( "done.\n" );
1290 # Get "active" text records from the archive table
1291 $this->output( 'Searching for active text records in archive table...' );
1292 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1293 foreach ( $res as $row ) {
1294 # old pre-MW 1.5 records can have null ar_text_id's.
1295 if ( $row->ar_text_id
!== null ) {
1296 $cur[] = $row->ar_text_id
;
1299 $this->output( "done.\n" );
1301 # Get "active" text records via the content table
1303 $this->output( 'Searching for active text records via contents table...' );
1304 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1305 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1306 foreach ( $res as $row ) {
1307 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1312 $this->output( "done.\n" );
1314 $this->output( "done.\n" );
1316 # Get the IDs of all text records not in these sets
1317 $this->output( 'Searching for inactive text records...' );
1318 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1319 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1321 foreach ( $res as $row ) {
1322 $old[] = $row->old_id
;
1324 $this->output( "done.\n" );
1326 # Inform the user of what we're going to do
1327 $count = count( $old );
1328 $this->output( "$count inactive items found.\n" );
1330 # Delete as appropriate
1331 if ( $delete && $count ) {
1332 $this->output( 'Deleting...' );
1333 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1334 $this->output( "done.\n" );
1337 $this->commitTransaction( $dbw, __METHOD__
);
1341 * Get the maintenance directory.
1344 protected function getDir() {
1349 * Returns a database to be used by current maintenance script. It can be set by setDB().
1350 * If not set, wfGetDB() will be used.
1351 * This function has the same parameters as wfGetDB()
1353 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1354 * @param string|string[] $groups default: empty array
1355 * @param string|bool $wiki default: current wiki
1356 * @return IMaintainableDatabase
1358 protected function getDB( $db, $groups = [], $wiki = false ) {
1359 if ( $this->mDb
=== null ) {
1360 return wfGetDB( $db, $groups, $wiki );
1366 * Sets database object to be returned by getDB().
1368 * @param IDatabase $db
1370 public function setDB( IDatabase
$db ) {
1375 * Begin a transcation on a DB
1377 * This method makes it clear that begin() is called from a maintenance script,
1378 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1380 * @param IDatabase $dbw
1381 * @param string $fname Caller name
1384 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1385 $dbw->begin( $fname );
1389 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1391 * This method makes it clear that commit() is called from a maintenance script,
1392 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1394 * @param IDatabase $dbw
1395 * @param string $fname Caller name
1396 * @return bool Whether the replica DB wait succeeded
1399 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1400 $dbw->commit( $fname );
1401 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1402 $waitSucceeded = $lbFactory->waitForReplication(
1403 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1405 $this->lastReplicationWait
= microtime( true );
1406 return $waitSucceeded;
1410 * Rollback the transcation on a DB handle
1412 * This method makes it clear that rollback() is called from a maintenance script,
1413 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1415 * @param IDatabase $dbw
1416 * @param string $fname Caller name
1419 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1420 $dbw->rollback( $fname );
1424 * Lock the search index
1425 * @param IMaintainableDatabase &$db
1427 private function lockSearchindex( $db ) {
1428 $write = [ 'searchindex' ];
1438 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1443 * @param IMaintainableDatabase &$db
1445 private function unlockSearchindex( $db ) {
1446 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1450 * Unlock and lock again
1451 * Since the lock is low-priority, queued reads will be able to complete
1452 * @param IMaintainableDatabase &$db
1454 private function relockSearchindex( $db ) {
1455 $this->unlockSearchindex( $db );
1456 $this->lockSearchindex( $db );
1460 * Perform a search index update with locking
1461 * @param int $maxLockTime The maximum time to keep the search index locked.
1462 * @param string $callback The function that will update the function.
1463 * @param IMaintainableDatabase $dbw
1464 * @param array $results
1466 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1470 if ( $maxLockTime ) {
1471 $this->output( " --- Waiting for lock ---" );
1472 $this->lockSearchindex( $dbw );
1474 $this->output( "\n" );
1477 # Loop through the results and do a search update
1478 foreach ( $results as $row ) {
1479 # Allow reads to be processed
1480 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1481 $this->output( " --- Relocking ---" );
1482 $this->relockSearchindex( $dbw );
1484 $this->output( "\n" );
1486 call_user_func( $callback, $dbw, $row );
1489 # Unlock searchindex
1490 if ( $maxLockTime ) {
1491 $this->output( " --- Unlocking --" );
1492 $this->unlockSearchindex( $dbw );
1493 $this->output( "\n" );
1498 * Update the searchindex table for a given pageid
1499 * @param IDatabase $dbw A database write handle
1500 * @param int $pageId The page ID to update.
1501 * @return null|string
1503 public function updateSearchIndexForPage( $dbw, $pageId ) {
1504 // Get current revision
1505 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1508 $titleObj = $rev->getTitle();
1509 $title = $titleObj->getPrefixedDBkey();
1510 $this->output( "$title..." );
1511 # Update searchindex
1512 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1514 $this->output( "\n" );
1521 * Count down from $seconds to zero on the terminal, with a one-second pause
1522 * between showing each number. If the maintenance script is in quiet mode,
1523 * this function does nothing.
1527 * @codeCoverageIgnore
1528 * @param int $seconds
1530 protected function countDown( $seconds ) {
1531 if ( $this->isQuiet() ) {
1534 for ( $i = $seconds; $i >= 0; $i-- ) {
1535 if ( $i != $seconds ) {
1536 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1538 $this->output( $i );
1543 $this->output( "\n" );
1547 * Wrapper for posix_isatty()
1548 * We default as considering stdin a tty (for nice readline methods)
1549 * but treating stout as not a tty to avoid color codes
1551 * @param mixed $fd File descriptor
1554 public static function posix_isatty( $fd ) {
1555 if ( !function_exists( 'posix_isatty' ) ) {
1558 return posix_isatty( $fd );
1563 * Prompt the console for input
1564 * @param string $prompt What to begin the line with, like '> '
1565 * @return string Response
1567 public static function readconsole( $prompt = '> ' ) {
1568 static $isatty = null;
1569 if ( is_null( $isatty ) ) {
1570 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1573 if ( $isatty && function_exists( 'readline' ) ) {
1574 return readline( $prompt );
1577 $st = self
::readlineEmulation( $prompt );
1579 if ( feof( STDIN
) ) {
1582 $st = fgets( STDIN
, 1024 );
1585 if ( $st === false ) {
1588 $resp = trim( $st );
1595 * Emulate readline()
1596 * @param string $prompt What to begin the line with, like '> '
1599 private static function readlineEmulation( $prompt ) {
1600 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1601 if ( !wfIsWindows() && $bash ) {
1603 $encPrompt = wfEscapeShellArg( $prompt );
1604 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1605 $encCommand = wfEscapeShellArg( $command );
1606 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1608 if ( $retval == 0 ) {
1610 } elseif ( $retval == 127 ) {
1611 // Couldn't execute bash even though we thought we saw it.
1612 // Shell probably spit out an error message, sorry :(
1613 // Fall through to fgets()...
1620 // Fallback... we'll have no editing controls, EWWW
1621 if ( feof( STDIN
) ) {
1626 return fgets( STDIN
, 1024 );
1630 * Get the terminal size as a two-element array where the first element
1631 * is the width (number of columns) and the second element is the height
1636 public static function getTermSize() {
1637 $default = [ 80, 50 ];
1638 if ( wfIsWindows() ) {
1641 if ( Shell
::isDisabled() ) {
1644 // It's possible to get the screen size with VT-100 terminal escapes,
1645 // but reading the responses is not possible without setting raw mode
1646 // (unless you want to require the user to press enter), and that
1647 // requires an ioctl(), which we can't do. So we have to shell out to
1648 // something that can do the relevant syscalls. There are a few
1649 // options. Linux and Mac OS X both have "stty size" which does the
1651 $result = Shell
::command( 'stty', 'size' )
1653 if ( $result->getExitCode() !== 0 ) {
1656 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1659 return [ intval( $m[2] ), intval( $m[1] ) ];
1663 * Call this to set up the autoloader to allow classes to be used from the
1666 public static function requireTestsAutoloader() {
1667 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1672 * Fake maintenance wrapper, mostly used for the web installer/updater
1674 class FakeMaintenance
extends Maintenance
{
1675 protected $mSelf = "FakeMaintenanceScript";
1677 public function execute() {
1682 * Class for scripts that perform database maintenance and want to log the
1683 * update in `updatelog` so we can later skip it
1685 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1686 public function __construct() {
1687 parent
::__construct();
1688 $this->addOption( 'force', 'Run the update even if it was completed already' );
1689 $this->setBatchSize( 200 );
1692 public function execute() {
1693 $db = $this->getDB( DB_MASTER
);
1694 $key = $this->getUpdateKey();
1696 if ( !$this->hasOption( 'force' )
1697 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1699 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1704 if ( !$this->doDBUpdates() ) {
1708 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' );
1714 * Message to show that the update was done already and was just skipped
1717 protected function updateSkippedMessage() {
1718 $key = $this->getUpdateKey();
1720 return "Update '{$key}' already logged as completed.";
1724 * Do the actual work. All child classes will need to implement this.
1725 * Return true to log the update as done or false (usually on failure).
1728 abstract protected function doDBUpdates();
1731 * Get the update key name to go in the update log table
1734 abstract protected function getUpdateKey();