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 // Some extensions rely on MW_INSTALL_PATH to find core files to include. Setting it here helps them
46 // if they're included by a core script (like DatabaseUpdater) after Maintenance.php has already
48 if ( strval( getenv( 'MW_INSTALL_PATH' ) ) === '' ) {
49 putenv( 'MW_INSTALL_PATH=' . realpath( __DIR__
. '/..' ) );
52 use Wikimedia\Rdbms\IDatabase
;
53 use MediaWiki\Logger\LoggerFactory
;
54 use MediaWiki\MediaWikiServices
;
55 use Wikimedia\Rdbms\LBFactory
;
56 use Wikimedia\Rdbms\IMaintainableDatabase
;
59 * Abstract maintenance class for quickly writing and churning out
60 * maintenance scripts with minimal effort. All that _must_ be defined
61 * is the execute() method. See docs/maintenance.txt for more info
62 * and a quick demo of how to use it.
65 * params: registry of named values that may be passed to the script
66 * arg list: registry of positional values that may be passed to the script
67 * options: passed param values
68 * args: passed positional values
71 * mwscript somescript.php --foo=bar baz
73 * bar is the option value of the option for param foo
74 * baz is the arg value at index 0 in the arg list
77 * @ingroup Maintenance
79 abstract class Maintenance
{
81 * Constants for DB access type
82 * @see Maintenance::getDbType()
88 // Const for getStdin()
89 const STDIN_ALL
= 'all';
91 // Array of desired/allowed params
92 protected $mParams = [];
94 // Array of mapping short parameters to long ones
95 protected $mShortParamsMap = [];
97 // Array of desired/allowed args
98 protected $mArgList = [];
100 // This is the list of options that were actually passed
101 protected $mOptions = [];
103 // This is the list of arguments that were actually passed
104 protected $mArgs = [];
106 // Allow arbitrary options to be passed, or only specified ones?
107 protected $mAllowUnregisteredOptions = false;
109 // Name of the script currently running
112 // Special vars for params that are always used
113 protected $mQuiet = false;
114 protected $mDbUser, $mDbPass;
116 // A description of the script, children should change this via addDescription()
117 protected $mDescription = '';
119 // Have we already loaded our user input?
120 protected $mInputLoaded = false;
123 * Batch size. If a script supports this, they should set
124 * a default with setBatchSize()
128 protected $mBatchSize = null;
130 // Generic options added by addDefaultParams()
131 private $mGenericParameters = [];
132 // Generic options which might or not be supported by the script
133 private $mDependantParameters = [];
136 * Used by getDB() / setDB()
137 * @var IMaintainableDatabase
141 /** @var float UNIX timestamp */
142 private $lastReplicationWait = 0.0;
145 * Used when creating separate schema files.
151 * Accessible via getConfig()
158 * @see Maintenance::requireExtension
161 private $requiredExtensions = [];
164 * Used to read the options in the order they were passed.
165 * Useful for option chaining (Ex. dumpBackup.php). It will
166 * be an empty array if the options are passed in through
167 * loadParamsAndArgs( $self, $opts, $args ).
169 * This is an array of arrays where
170 * 0 => the option and 1 => parameter value.
174 public $orderedOptions = [];
177 * Default constructor. Children should call this *first* if implementing
178 * their own constructors
180 public function __construct() {
182 $IP = getenv( 'MW_INSTALL_PATH' );
184 $this->addDefaultParams();
185 register_shutdown_function( [ $this, 'outputChanneled' ], false );
189 * Should we execute the maintenance script, or just allow it to be included
190 * as a standalone class? It checks that the call stack only includes this
191 * function and "requires" (meaning was called from the file scope)
195 public static function shouldExecute() {
196 global $wgCommandLineMode;
198 if ( !function_exists( 'debug_backtrace' ) ) {
199 // If someone has a better idea...
200 return $wgCommandLineMode;
203 $bt = debug_backtrace();
204 $count = count( $bt );
206 return false; // sanity
208 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
209 return false; // last call should be to this function
211 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
212 for ( $i = 1; $i < $count; $i++
) {
213 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
214 return false; // previous calls should all be "requires"
222 * Do the actual work. All child classes will need to implement this
224 * @return bool|null|void True for success, false for failure. Not returning
225 * a value, or returning null, is also interpreted as success. Returning
226 * false for failure will cause doMaintenance.php to exit the process
227 * with a non-zero exit status.
229 abstract public function execute();
232 * Checks to see if a particular option in supported. Normally this means it
233 * has been registered by the script via addOption.
234 * @param string $name The name of the option
235 * @return bool true if the option exists, false otherwise
237 protected function supportsOption( $name ) {
238 return isset( $this->mParams
[$name] );
242 * Add a parameter to the script. Will be displayed on --help
243 * with the associated description
245 * @param string $name The name of the param (help, version, etc)
246 * @param string $description The description of the param to show on --help
247 * @param bool $required Is the param required?
248 * @param bool $withArg Is an argument required with this option?
249 * @param string|bool $shortName Character to use as short name
250 * @param bool $multiOccurrence Can this option be passed multiple times?
252 protected function addOption( $name, $description, $required = false,
253 $withArg = false, $shortName = false, $multiOccurrence = false
255 $this->mParams
[$name] = [
256 'desc' => $description,
257 'require' => $required,
258 'withArg' => $withArg,
259 'shortName' => $shortName,
260 'multiOccurrence' => $multiOccurrence
263 if ( $shortName !== false ) {
264 $this->mShortParamsMap
[$shortName] = $name;
269 * Checks to see if a particular option exists.
270 * @param string $name The name of the option
273 protected function hasOption( $name ) {
274 return isset( $this->mOptions
[$name] );
278 * Get an option, or return the default.
280 * If the option was added to support multiple occurrences,
281 * this will return an array.
283 * @param string $name The name of the param
284 * @param mixed|null $default Anything you want, default null
287 protected function getOption( $name, $default = null ) {
288 if ( $this->hasOption( $name ) ) {
289 return $this->mOptions
[$name];
291 // Set it so we don't have to provide the default again
292 $this->mOptions
[$name] = $default;
294 return $this->mOptions
[$name];
299 * Add some args that are needed
300 * @param string $arg Name of the arg, like 'start'
301 * @param string $description Short description of the arg
302 * @param bool $required Is this required?
304 protected function addArg( $arg, $description, $required = true ) {
305 $this->mArgList
[] = [
307 'desc' => $description,
308 'require' => $required
313 * Remove an option. Useful for removing options that won't be used in your script.
314 * @param string $name The option to remove.
316 protected function deleteOption( $name ) {
317 unset( $this->mParams
[$name] );
321 * Sets whether to allow unregistered options, which are options passed to
322 * a script that do not match an expected parameter.
323 * @param bool $allow Should we allow?
325 protected function setAllowUnregisteredOptions( $allow ) {
326 $this->mAllowUnregisteredOptions
= $allow;
330 * Set the description text.
331 * @param string $text The text of the description
333 protected function addDescription( $text ) {
334 $this->mDescription
= $text;
338 * Does a given argument exist?
339 * @param int $argId The integer value (from zero) for the arg
342 protected function hasArg( $argId = 0 ) {
343 if ( func_num_args() === 0 ) {
344 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
347 return isset( $this->mArgs
[$argId] );
352 * @param int $argId The integer value (from zero) for the arg
353 * @param mixed|null $default The default if it doesn't exist
356 protected function getArg( $argId = 0, $default = null ) {
357 if ( func_num_args() === 0 ) {
358 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
361 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
371 protected function getBatchSize() {
372 return $this->mBatchSize
;
376 * Set the batch size.
377 * @param int $s The number of operations to do in a batch
379 protected function setBatchSize( $s = 0 ) {
380 $this->mBatchSize
= $s;
382 // If we support $mBatchSize, show the option.
383 // Used to be in addDefaultParams, but in order for that to
384 // work, subclasses would have to call this function in the constructor
385 // before they called parent::__construct which is just weird
386 // (and really wasn't done).
387 if ( $this->mBatchSize
) {
388 $this->addOption( 'batch-size', 'Run this many operations ' .
389 'per batch, default: ' . $this->mBatchSize
, false, true );
390 if ( isset( $this->mParams
['batch-size'] ) ) {
391 // This seems a little ugly...
392 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
398 * Get the script's name
401 public function getName() {
406 * Return input from stdin.
407 * @param int|null $len The number of bytes to read. If null, just return the handle.
408 * Maintenance::STDIN_ALL returns the full length
411 protected function getStdin( $len = null ) {
412 if ( $len == self
::STDIN_ALL
) {
413 return file_get_contents( 'php://stdin' );
415 $f = fopen( 'php://stdin', 'rt' );
419 $input = fgets( $f, $len );
422 return rtrim( $input );
428 public function isQuiet() {
429 return $this->mQuiet
;
433 * Throw some output to the user. Scripts can call this with no fears,
434 * as we handle all --quiet stuff here
435 * @param string $out The text to show to the user
436 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
438 protected function output( $out, $channel = null ) {
439 // This is sometimes called very early, before Setup.php is included.
440 if ( class_exists( MediaWikiServices
::class ) ) {
441 // Try to periodically flush buffered metrics to avoid OOMs
442 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
443 if ( $stats->getDataCount() > 1000 ) {
444 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
448 if ( $this->mQuiet
) {
451 if ( $channel === null ) {
452 $this->cleanupChanneled();
455 $out = preg_replace( '/\n\z/', '', $out );
456 $this->outputChanneled( $out, $channel );
461 * Throw an error to the user. Doesn't respect --quiet, so don't use
462 * this for non-error output
463 * @param string $err The error to display
464 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
466 protected function error( $err, $die = 0 ) {
467 if ( intval( $die ) !== 0 ) {
468 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
469 $this->fatalError( $err, intval( $die ) );
471 $this->outputChanneled( false );
473 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
474 !defined( 'MW_PHPUNIT_TEST' )
476 fwrite( STDERR
, $err . "\n" );
483 * Output a message and terminate the current script.
485 * @param string $msg Error message
486 * @param int $exitCode PHP exit status. Should be in range 1-254.
489 protected function fatalError( $msg, $exitCode = 1 ) {
490 $this->error( $msg );
494 private $atLineStart = true;
495 private $lastChannel = null;
498 * Clean up channeled output. Output a newline if necessary.
500 public function cleanupChanneled() {
501 if ( !$this->atLineStart
) {
503 $this->atLineStart
= true;
508 * Message outputter with channeled message support. Messages on the
509 * same channel are concatenated, but any intervening messages in another
510 * channel start a new line.
511 * @param string $msg The message without trailing newline
512 * @param string|null $channel Channel identifier or null for no
513 * channel. Channel comparison uses ===.
515 public function outputChanneled( $msg, $channel = null ) {
516 if ( $msg === false ) {
517 $this->cleanupChanneled();
522 // End the current line if necessary
523 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
529 $this->atLineStart
= false;
530 if ( $channel === null ) {
531 // For unchanneled messages, output trailing newline immediately
533 $this->atLineStart
= true;
535 $this->lastChannel
= $channel;
539 * Does the script need different DB access? By default, we give Maintenance
540 * scripts normal rights to the DB. Sometimes, a script needs admin rights
541 * access for a reason and sometimes they want no access. Subclasses should
542 * override and return one of the following values, as needed:
543 * Maintenance::DB_NONE - For no DB access at all
544 * Maintenance::DB_STD - For normal DB access, default
545 * Maintenance::DB_ADMIN - For admin DB access
548 public function getDbType() {
553 * Add the default parameters to the scripts
555 protected function addDefaultParams() {
556 # Generic (non script dependant) options:
558 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
559 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
560 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
561 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
562 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
565 'Set a specific memory limit for the script, '
566 . '"max" for no limit or "default" to avoid changing it',
570 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
571 "http://en.wikipedia.org. This is sometimes necessary because " .
572 "server name detection may fail in command line scripts.", false, true );
573 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
574 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
575 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
577 # Save generic options to display them separately in help
578 $this->mGenericParameters
= $this->mParams
;
580 # Script dependant options:
582 // If we support a DB, show the options
583 if ( $this->getDbType() > 0 ) {
584 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
585 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
586 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
589 # Save additional script dependant options to display
590 # Â them separately in help
591 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
598 public function getConfig() {
599 if ( $this->config
=== null ) {
600 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
603 return $this->config
;
608 * @param Config $config
610 public function setConfig( Config
$config ) {
611 $this->config
= $config;
615 * Indicate that the specified extension must be
616 * loaded before the script can run.
618 * This *must* be called in the constructor.
621 * @param string $name
623 protected function requireExtension( $name ) {
624 $this->requiredExtensions
[] = $name;
628 * Verify that the required extensions are installed
632 public function checkRequiredExtensions() {
633 $registry = ExtensionRegistry
::getInstance();
635 foreach ( $this->requiredExtensions
as $name ) {
636 if ( !$registry->isLoaded( $name ) ) {
642 $joined = implode( ', ', $missing );
643 $msg = "The following extensions are required to be installed "
644 . "for this script to run: $joined. Please enable them and then try again.";
645 $this->fatalError( $msg );
650 * Set triggers like when to try to run deferred updates
653 public function setAgentAndTriggers() {
654 if ( function_exists( 'posix_getpwuid' ) ) {
655 $agent = posix_getpwuid( posix_geteuid() )['name'];
659 $agent .= '@' . wfHostname();
661 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
662 // Add a comment for easy SHOW PROCESSLIST interpretation
663 $lbFactory->setAgentName(
664 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
666 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
670 * @param LBFactory $LBFactory
671 * @param Config $config
674 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
675 $services = MediaWikiServices
::getInstance();
676 $stats = $services->getStatsdDataFactory();
677 // Hook into period lag checks which often happen in long-running scripts
678 $lbFactory = $services->getDBLoadBalancerFactory();
679 $lbFactory->setWaitForReplicationListener(
681 function () use ( $stats, $config ) {
682 // Check config in case of JobRunner and unit tests
683 if ( $config->get( 'CommandLineMode' ) ) {
684 DeferredUpdates
::tryOpportunisticExecute( 'run' );
686 // Try to periodically flush buffered metrics to avoid OOMs
687 MediaWiki
::emitBufferedStatsdData( $stats, $config );
690 // Check for other windows to run them. A script may read or do a few writes
691 // to the master but mostly be writing to something else, like a file store.
692 $lbFactory->getMainLB()->setTransactionListener(
694 function ( $trigger ) use ( $stats, $config ) {
695 // Check config in case of JobRunner and unit tests
696 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
697 DeferredUpdates
::tryOpportunisticExecute( 'run' );
699 // Try to periodically flush buffered metrics to avoid OOMs
700 MediaWiki
::emitBufferedStatsdData( $stats, $config );
706 * Run a child maintenance script. Pass all of the current arguments
708 * @param string $maintClass A name of a child maintenance class
709 * @param string|null $classFile Full path of where the child is
710 * @return Maintenance
712 public function runChild( $maintClass, $classFile = null ) {
713 // Make sure the class is loaded first
714 if ( !class_exists( $maintClass ) ) {
716 require_once $classFile;
718 if ( !class_exists( $maintClass ) ) {
719 $this->error( "Cannot spawn child: $maintClass" );
724 * @var Maintenance $child
726 $child = new $maintClass();
727 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
728 if ( !is_null( $this->mDb
) ) {
729 $child->setDB( $this->mDb
);
736 * Do some sanity checking and basic setup
738 public function setup() {
739 global $IP, $wgCommandLineMode;
741 # Abort if called from a web server
742 # wfIsCLI() is not available yet
743 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
744 $this->fatalError( 'This script must be run from the command line' );
747 if ( $IP === null ) {
748 $this->fatalError( "\$IP not set, aborting!\n" .
749 '(Did you forget to call parent::__construct() in your maintenance script?)' );
752 # Make sure we can handle script parameters
753 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
754 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
757 // Send PHP warnings and errors to stderr instead of stdout.
758 // This aids in diagnosing problems, while keeping messages
759 // out of redirected output.
760 if ( ini_get( 'display_errors' ) ) {
761 ini_set( 'display_errors', 'stderr' );
764 $this->loadParamsAndArgs();
766 # Set the memory limit
767 # Note we need to set it again later in cache LocalSettings changed it
768 $this->adjustMemoryLimit();
770 # Set max execution time to 0 (no limit). PHP.net says that
771 # "When running PHP from the command line the default setting is 0."
772 # But sometimes this doesn't seem to be the case.
773 ini_set( 'max_execution_time', 0 );
775 # Define us as being in MediaWiki
776 define( 'MEDIAWIKI', true );
778 $wgCommandLineMode = true;
780 # Turn off output buffering if it's on
781 while ( ob_get_level() > 0 ) {
787 * Normally we disable the memory_limit when running admin scripts.
788 * Some scripts may wish to actually set a limit, however, to avoid
789 * blowing up unexpectedly. We also support a --memory-limit option,
790 * to allow sysadmins to explicitly set one if they'd prefer to override
791 * defaults (or for people using Suhosin which yells at you for trying
792 * to disable the limits)
795 public function memoryLimit() {
796 $limit = $this->getOption( 'memory-limit', 'max' );
797 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
802 * Adjusts PHP's memory limit to better suit our needs, if needed.
804 protected function adjustMemoryLimit() {
805 $limit = $this->memoryLimit();
806 if ( $limit == 'max' ) {
807 $limit = -1; // no memory limit
809 if ( $limit != 'default' ) {
810 ini_set( 'memory_limit', $limit );
815 * Activate the profiler (assuming $wgProfiler is set)
817 protected function activateProfiler() {
818 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
820 $output = $this->getOption( 'profiler' );
825 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
826 $class = $wgProfiler['class'];
827 /** @var Profiler $profiler */
828 $profiler = new $class(
829 [ 'sampling' => 1, 'output' => [ $output ] ]
831 +
[ 'threshold' => $wgProfileLimit ]
833 $profiler->setTemplated( true );
834 Profiler
::replaceStubInstance( $profiler );
837 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
838 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
839 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
843 * Clear all params and arguments.
845 public function clearParamsAndArgs() {
846 $this->mOptions
= [];
848 $this->mInputLoaded
= false;
852 * Load params and arguments from a given array
853 * of command-line arguments
858 public function loadWithArgv( $argv ) {
861 $this->orderedOptions
= [];
864 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
865 if ( $arg == '--' ) {
866 # End of options, remainder should be considered arguments
867 $arg = next( $argv );
868 while ( $arg !== false ) {
870 $arg = next( $argv );
873 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
875 $option = substr( $arg, 2 );
876 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
877 $param = next( $argv );
878 if ( $param === false ) {
879 $this->error( "\nERROR: $option parameter needs a value after it\n" );
880 $this->maybeHelp( true );
883 $this->setParam( $options, $option, $param );
885 $bits = explode( '=', $option, 2 );
886 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
888 } elseif ( $arg == '-' ) {
889 # Lonely "-", often used to indicate stdin or stdout.
891 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
893 $argLength = strlen( $arg );
894 for ( $p = 1; $p < $argLength; $p++
) {
896 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
897 $option = $this->mShortParamsMap
[$option];
900 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
901 $param = next( $argv );
902 if ( $param === false ) {
903 $this->error( "\nERROR: $option parameter needs a value after it\n" );
904 $this->maybeHelp( true );
906 $this->setParam( $options, $option, $param );
908 $this->setParam( $options, $option, 1 );
916 $this->mOptions
= $options;
917 $this->mArgs
= $args;
918 $this->loadSpecialVars();
919 $this->mInputLoaded
= true;
923 * Helper function used solely by loadParamsAndArgs
924 * to prevent code duplication
926 * This sets the param in the options array based on
927 * whether or not it can be specified multiple times.
930 * @param array $options
931 * @param string $option
932 * @param mixed $value
934 private function setParam( &$options, $option, $value ) {
935 $this->orderedOptions
[] = [ $option, $value ];
937 if ( isset( $this->mParams
[$option] ) ) {
938 $multi = $this->mParams
[$option]['multiOccurrence'];
942 $exists = array_key_exists( $option, $options );
943 if ( $multi && $exists ) {
944 $options[$option][] = $value;
945 } elseif ( $multi ) {
946 $options[$option] = [ $value ];
947 } elseif ( !$exists ) {
948 $options[$option] = $value;
950 $this->error( "\nERROR: $option parameter given twice\n" );
951 $this->maybeHelp( true );
956 * Process command line arguments
957 * $mOptions becomes an array with keys set to the option names
958 * $mArgs becomes a zero-based array containing the non-option arguments
960 * @param string|null $self The name of the script, if any
961 * @param array|null $opts An array of options, in form of key=>value
962 * @param array|null $args An array of command line arguments
964 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
965 # If we were given opts or args, set those and return early
967 $this->mSelf
= $self;
968 $this->mInputLoaded
= true;
971 $this->mOptions
= $opts;
972 $this->mInputLoaded
= true;
975 $this->mArgs
= $args;
976 $this->mInputLoaded
= true;
979 # If we've already loaded input (either by user values or from $argv)
980 # skip on loading it again. The array_shift() will corrupt values if
981 # it's run again and again
982 if ( $this->mInputLoaded
) {
983 $this->loadSpecialVars();
989 $this->mSelf
= $argv[0];
990 $this->loadWithArgv( array_slice( $argv, 1 ) );
994 * Run some validation checks on the params, etc
996 public function validateParamsAndArgs() {
998 # Check to make sure we've got all the required options
999 foreach ( $this->mParams
as $opt => $info ) {
1000 if ( $info['require'] && !$this->hasOption( $opt ) ) {
1001 $this->error( "Param $opt required!" );
1005 # Check arg list too
1006 foreach ( $this->mArgList
as $k => $info ) {
1007 if ( $info['require'] && !$this->hasArg( $k ) ) {
1008 $this->error( 'Argument <' . $info['name'] . '> required!' );
1012 if ( !$this->mAllowUnregisteredOptions
) {
1013 # Check for unexpected options
1014 foreach ( $this->mOptions
as $opt => $val ) {
1015 if ( !$this->supportsOption( $opt ) ) {
1016 $this->error( "Unexpected option $opt!" );
1022 $this->maybeHelp( $die );
1026 * Handle the special variables that are global to all scripts
1028 protected function loadSpecialVars() {
1029 if ( $this->hasOption( 'dbuser' ) ) {
1030 $this->mDbUser
= $this->getOption( 'dbuser' );
1032 if ( $this->hasOption( 'dbpass' ) ) {
1033 $this->mDbPass
= $this->getOption( 'dbpass' );
1035 if ( $this->hasOption( 'quiet' ) ) {
1036 $this->mQuiet
= true;
1038 if ( $this->hasOption( 'batch-size' ) ) {
1039 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1044 * Maybe show the help.
1045 * @param bool $force Whether to force the help to show, default false
1047 protected function maybeHelp( $force = false ) {
1048 if ( !$force && !$this->hasOption( 'help' ) ) {
1052 $screenWidth = 80; // TODO: Calculate this!
1054 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1056 ksort( $this->mParams
);
1057 $this->mQuiet
= false;
1060 if ( $this->mDescription
) {
1061 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1063 $output = "\nUsage: php " . basename( $this->mSelf
);
1065 // ... append parameters ...
1066 if ( $this->mParams
) {
1067 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1070 // ... and append arguments.
1071 if ( $this->mArgList
) {
1073 foreach ( $this->mArgList
as $k => $arg ) {
1074 if ( $arg['require'] ) {
1075 $output .= '<' . $arg['name'] . '>';
1077 $output .= '[' . $arg['name'] . ']';
1079 if ( $k < count( $this->mArgList
) - 1 ) {
1084 $this->output( "$output\n\n" );
1086 # TODO abstract some repetitive code below
1088 // Generic parameters
1089 $this->output( "Generic maintenance parameters:\n" );
1090 foreach ( $this->mGenericParameters
as $par => $info ) {
1091 if ( $info['shortName'] !== false ) {
1092 $par .= " (-{$info['shortName']})";
1095 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1096 "\n$tab$tab" ) . "\n"
1099 $this->output( "\n" );
1101 $scriptDependantParams = $this->mDependantParameters
;
1102 if ( count( $scriptDependantParams ) > 0 ) {
1103 $this->output( "Script dependant parameters:\n" );
1104 // Parameters description
1105 foreach ( $scriptDependantParams as $par => $info ) {
1106 if ( $info['shortName'] !== false ) {
1107 $par .= " (-{$info['shortName']})";
1110 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1111 "\n$tab$tab" ) . "\n"
1114 $this->output( "\n" );
1117 // Script specific parameters not defined on construction by
1118 // Maintenance::addDefaultParams()
1119 $scriptSpecificParams = array_diff_key(
1120 # all script parameters:
1122 # remove the Maintenance default parameters:
1123 $this->mGenericParameters
,
1124 $this->mDependantParameters
1126 if ( count( $scriptSpecificParams ) > 0 ) {
1127 $this->output( "Script specific parameters:\n" );
1128 // Parameters description
1129 foreach ( $scriptSpecificParams as $par => $info ) {
1130 if ( $info['shortName'] !== false ) {
1131 $par .= " (-{$info['shortName']})";
1134 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1135 "\n$tab$tab" ) . "\n"
1138 $this->output( "\n" );
1142 if ( count( $this->mArgList
) > 0 ) {
1143 $this->output( "Arguments:\n" );
1144 // Arguments description
1145 foreach ( $this->mArgList
as $info ) {
1146 $openChar = $info['require'] ?
'<' : '[';
1147 $closeChar = $info['require'] ?
'>' : ']';
1149 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1150 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1153 $this->output( "\n" );
1160 * Handle some last-minute setup here.
1162 public function finalSetup() {
1163 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1164 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1165 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1167 # Turn off output buffering again, it might have been turned on in the settings files
1168 if ( ob_get_level() ) {
1172 $wgCommandLineMode = true;
1174 # Override $wgServer
1175 if ( $this->hasOption( 'server' ) ) {
1176 $wgServer = $this->getOption( 'server', $wgServer );
1179 # If these were passed, use them
1180 if ( $this->mDbUser
) {
1181 $wgDBadminuser = $this->mDbUser
;
1183 if ( $this->mDbPass
) {
1184 $wgDBadminpassword = $this->mDbPass
;
1186 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1187 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1189 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1192 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1193 $wgDBuser = $wgDBadminuser;
1194 $wgDBpassword = $wgDBadminpassword;
1196 if ( $wgDBservers ) {
1198 * @var array $wgDBservers
1200 foreach ( $wgDBservers as $i => $server ) {
1201 $wgDBservers[$i]['user'] = $wgDBuser;
1202 $wgDBservers[$i]['password'] = $wgDBpassword;
1205 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1206 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1207 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1209 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1212 # Apply debug settings
1213 if ( $this->hasOption( 'mwdebug' ) ) {
1214 require __DIR__
. '/../includes/DevelopmentSettings.php';
1217 // Per-script profiling; useful for debugging
1218 $this->activateProfiler();
1220 $this->afterFinalSetup();
1222 $wgShowExceptionDetails = true;
1223 $wgShowHostnames = true;
1225 Wikimedia\
suppressWarnings();
1226 set_time_limit( 0 );
1227 Wikimedia\restoreWarnings
();
1229 $this->adjustMemoryLimit();
1233 * Execute a callback function at the end of initialisation
1235 protected function afterFinalSetup() {
1236 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1237 call_user_func( MW_CMDLINE_CALLBACK
);
1242 * Potentially debug globals. Originally a feature only
1245 public function globals() {
1246 if ( $this->hasOption( 'globals' ) ) {
1247 print_r( $GLOBALS );
1252 * Generic setup for most installs. Returns the location of LocalSettings
1255 public function loadSettings() {
1256 global $wgCommandLineMode, $IP;
1258 if ( isset( $this->mOptions
['conf'] ) ) {
1259 $settingsFile = $this->mOptions
['conf'];
1260 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1261 $settingsFile = MW_CONFIG_FILE
;
1263 $settingsFile = "$IP/LocalSettings.php";
1265 if ( isset( $this->mOptions
['wiki'] ) ) {
1266 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1267 define( 'MW_DB', $bits[0] );
1268 define( 'MW_PREFIX', $bits[1] ??
'' );
1269 } elseif ( isset( $this->mOptions
['server'] ) ) {
1270 // Provide the option for site admins to detect and configure
1271 // multiple wikis based on server names. This offers --server
1272 // as alternative to --wiki.
1273 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1274 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1277 if ( !is_readable( $settingsFile ) ) {
1278 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1279 "must exist and be readable in the source directory.\n" .
1280 "Use --conf to specify it." );
1282 $wgCommandLineMode = true;
1284 return $settingsFile;
1288 * Support function for cleaning up redundant text records
1289 * @param bool $delete Whether or not to actually delete the records
1290 * @author Rob Church <robchur@gmail.com>
1292 public function purgeRedundantText( $delete = true ) {
1293 global $wgMultiContentRevisionSchemaMigrationStage;
1295 # Data should come off the master, wrapped in a transaction
1296 $dbw = $this->getDB( DB_MASTER
);
1297 $this->beginTransaction( $dbw, __METHOD__
);
1299 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1300 # Get "active" text records from the revisions table
1302 $this->output( 'Searching for active text records in revisions table...' );
1303 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1304 foreach ( $res as $row ) {
1305 $cur[] = $row->rev_text_id
;
1307 $this->output( "done.\n" );
1309 # Get "active" text records from the archive table
1310 $this->output( 'Searching for active text records in archive table...' );
1311 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1312 foreach ( $res as $row ) {
1313 # old pre-MW 1.5 records can have null ar_text_id's.
1314 if ( $row->ar_text_id
!== null ) {
1315 $cur[] = $row->ar_text_id
;
1318 $this->output( "done.\n" );
1320 # Get "active" text records via the content table
1322 $this->output( 'Searching for active text records via contents table...' );
1323 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1324 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1325 foreach ( $res as $row ) {
1326 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1331 $this->output( "done.\n" );
1333 $this->output( "done.\n" );
1335 # Get the IDs of all text records not in these sets
1336 $this->output( 'Searching for inactive text records...' );
1337 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1338 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1340 foreach ( $res as $row ) {
1341 $old[] = $row->old_id
;
1343 $this->output( "done.\n" );
1345 # Inform the user of what we're going to do
1346 $count = count( $old );
1347 $this->output( "$count inactive items found.\n" );
1349 # Delete as appropriate
1350 if ( $delete && $count ) {
1351 $this->output( 'Deleting...' );
1352 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1353 $this->output( "done.\n" );
1356 $this->commitTransaction( $dbw, __METHOD__
);
1360 * Get the maintenance directory.
1363 protected function getDir() {
1368 * Returns a database to be used by current maintenance script. It can be set by setDB().
1369 * If not set, wfGetDB() will be used.
1370 * This function has the same parameters as wfGetDB()
1372 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1373 * @param string|string[] $groups default: empty array
1374 * @param string|bool $wiki default: current wiki
1375 * @return IMaintainableDatabase
1377 protected function getDB( $db, $groups = [], $wiki = false ) {
1378 if ( $this->mDb
=== null ) {
1379 return wfGetDB( $db, $groups, $wiki );
1385 * Sets database object to be returned by getDB().
1387 * @param IDatabase $db
1389 public function setDB( IDatabase
$db ) {
1394 * Begin a transcation on a DB
1396 * This method makes it clear that begin() is called from a maintenance script,
1397 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1399 * @param IDatabase $dbw
1400 * @param string $fname Caller name
1403 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1404 $dbw->begin( $fname );
1408 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1410 * This method makes it clear that commit() is called from a maintenance script,
1411 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1413 * @param IDatabase $dbw
1414 * @param string $fname Caller name
1415 * @return bool Whether the replica DB wait succeeded
1418 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1419 $dbw->commit( $fname );
1420 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1421 $waitSucceeded = $lbFactory->waitForReplication(
1422 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1424 $this->lastReplicationWait
= microtime( true );
1425 return $waitSucceeded;
1429 * Rollback the transcation on a DB handle
1431 * This method makes it clear that rollback() is called from a maintenance script,
1432 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1434 * @param IDatabase $dbw
1435 * @param string $fname Caller name
1438 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1439 $dbw->rollback( $fname );
1443 * Lock the search index
1444 * @param IMaintainableDatabase &$db
1446 private function lockSearchindex( $db ) {
1447 $write = [ 'searchindex' ];
1457 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1462 * @param IMaintainableDatabase &$db
1464 private function unlockSearchindex( $db ) {
1465 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1469 * Unlock and lock again
1470 * Since the lock is low-priority, queued reads will be able to complete
1471 * @param IMaintainableDatabase &$db
1473 private function relockSearchindex( $db ) {
1474 $this->unlockSearchindex( $db );
1475 $this->lockSearchindex( $db );
1479 * Perform a search index update with locking
1480 * @param int $maxLockTime The maximum time to keep the search index locked.
1481 * @param string $callback The function that will update the function.
1482 * @param IMaintainableDatabase $dbw
1483 * @param array $results
1485 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1489 if ( $maxLockTime ) {
1490 $this->output( " --- Waiting for lock ---" );
1491 $this->lockSearchindex( $dbw );
1493 $this->output( "\n" );
1496 # Loop through the results and do a search update
1497 foreach ( $results as $row ) {
1498 # Allow reads to be processed
1499 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1500 $this->output( " --- Relocking ---" );
1501 $this->relockSearchindex( $dbw );
1503 $this->output( "\n" );
1505 call_user_func( $callback, $dbw, $row );
1508 # Unlock searchindex
1509 if ( $maxLockTime ) {
1510 $this->output( " --- Unlocking --" );
1511 $this->unlockSearchindex( $dbw );
1512 $this->output( "\n" );
1517 * Update the searchindex table for a given pageid
1518 * @param IDatabase $dbw A database write handle
1519 * @param int $pageId The page ID to update.
1520 * @return null|string
1522 public function updateSearchIndexForPage( $dbw, $pageId ) {
1523 // Get current revision
1524 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1527 $titleObj = $rev->getTitle();
1528 $title = $titleObj->getPrefixedDBkey();
1529 $this->output( "$title..." );
1530 # Update searchindex
1531 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1533 $this->output( "\n" );
1540 * Count down from $seconds to zero on the terminal, with a one-second pause
1541 * between showing each number. If the maintenance script is in quiet mode,
1542 * this function does nothing.
1546 * @codeCoverageIgnore
1547 * @param int $seconds
1549 protected function countDown( $seconds ) {
1550 if ( $this->isQuiet() ) {
1553 for ( $i = $seconds; $i >= 0; $i-- ) {
1554 if ( $i != $seconds ) {
1555 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1557 $this->output( $i );
1562 $this->output( "\n" );
1566 * Wrapper for posix_isatty()
1567 * We default as considering stdin a tty (for nice readline methods)
1568 * but treating stout as not a tty to avoid color codes
1570 * @param mixed $fd File descriptor
1573 public static function posix_isatty( $fd ) {
1574 if ( !function_exists( 'posix_isatty' ) ) {
1577 return posix_isatty( $fd );
1582 * Prompt the console for input
1583 * @param string $prompt What to begin the line with, like '> '
1584 * @return string Response
1586 public static function readconsole( $prompt = '> ' ) {
1587 static $isatty = null;
1588 if ( is_null( $isatty ) ) {
1589 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1592 if ( $isatty && function_exists( 'readline' ) ) {
1593 return readline( $prompt );
1596 $st = self
::readlineEmulation( $prompt );
1598 if ( feof( STDIN
) ) {
1601 $st = fgets( STDIN
, 1024 );
1604 if ( $st === false ) {
1607 $resp = trim( $st );
1614 * Emulate readline()
1615 * @param string $prompt What to begin the line with, like '> '
1618 private static function readlineEmulation( $prompt ) {
1619 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1620 if ( !wfIsWindows() && $bash ) {
1622 $encPrompt = Shell
::escape( $prompt );
1623 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1624 $encCommand = Shell
::escape( $command );
1625 $line = Shell
::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1627 if ( $retval == 0 ) {
1629 } elseif ( $retval == 127 ) {
1630 // Couldn't execute bash even though we thought we saw it.
1631 // Shell probably spit out an error message, sorry :(
1632 // Fall through to fgets()...
1639 // Fallback... we'll have no editing controls, EWWW
1640 if ( feof( STDIN
) ) {
1645 return fgets( STDIN
, 1024 );
1649 * Get the terminal size as a two-element array where the first element
1650 * is the width (number of columns) and the second element is the height
1655 public static function getTermSize() {
1656 $default = [ 80, 50 ];
1657 if ( wfIsWindows() ) {
1660 if ( Shell
::isDisabled() ) {
1663 // It's possible to get the screen size with VT-100 terminal escapes,
1664 // but reading the responses is not possible without setting raw mode
1665 // (unless you want to require the user to press enter), and that
1666 // requires an ioctl(), which we can't do. So we have to shell out to
1667 // something that can do the relevant syscalls. There are a few
1668 // options. Linux and Mac OS X both have "stty size" which does the
1670 $result = Shell
::command( 'stty', 'size' )
1672 if ( $result->getExitCode() !== 0 ) {
1675 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1678 return [ intval( $m[2] ), intval( $m[1] ) ];
1682 * Call this to set up the autoloader to allow classes to be used from the
1685 public static function requireTestsAutoloader() {
1686 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1691 * Fake maintenance wrapper, mostly used for the web installer/updater
1693 class FakeMaintenance
extends Maintenance
{
1694 protected $mSelf = "FakeMaintenanceScript";
1696 public function execute() {
1701 * Class for scripts that perform database maintenance and want to log the
1702 * update in `updatelog` so we can later skip it
1704 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1705 public function __construct() {
1706 parent
::__construct();
1707 $this->addOption( 'force', 'Run the update even if it was completed already' );
1708 $this->setBatchSize( 200 );
1711 public function execute() {
1712 $db = $this->getDB( DB_MASTER
);
1713 $key = $this->getUpdateKey();
1715 if ( !$this->hasOption( 'force' )
1716 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1718 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1723 if ( !$this->doDBUpdates() ) {
1727 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' );
1733 * Message to show that the update was done already and was just skipped
1736 protected function updateSkippedMessage() {
1737 $key = $this->getUpdateKey();
1739 return "Update '{$key}' already logged as completed.";
1743 * Do the actual work. All child classes will need to implement this.
1744 * Return true to log the update as done or false (usually on failure).
1747 abstract protected function doDBUpdates();
1750 * Get the update key name to go in the update log table
1753 abstract protected function getUpdateKey();