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
;
29 use Wikimedia\Rdbms\IResultWrapper
;
32 * @defgroup MaintenanceArchive Maintenance archives
33 * @ingroup Maintenance
36 // Define this so scripts can easily find doMaintenance.php
37 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
40 * @deprecated since 1.31
42 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
46 // Some extensions rely on MW_INSTALL_PATH to find core files to include. Setting it here helps them
47 // if they're included by a core script (like DatabaseUpdater) after Maintenance.php has already
49 if ( strval( getenv( 'MW_INSTALL_PATH' ) ) === '' ) {
50 putenv( 'MW_INSTALL_PATH=' . realpath( __DIR__
. '/..' ) );
53 use Wikimedia\Rdbms\IDatabase
;
54 use MediaWiki\Logger\LoggerFactory
;
55 use MediaWiki\MediaWikiServices
;
56 use Wikimedia\Rdbms\LBFactory
;
57 use Wikimedia\Rdbms\IMaintainableDatabase
;
60 * Abstract maintenance class for quickly writing and churning out
61 * maintenance scripts with minimal effort. All that _must_ be defined
62 * is the execute() method. See docs/maintenance.txt for more info
63 * and a quick demo of how to use it.
66 * params: registry of named values that may be passed to the script
67 * arg list: registry of positional values that may be passed to the script
68 * options: passed param values
69 * args: passed positional values
72 * mwscript somescript.php --foo=bar baz
74 * bar is the option value of the option for param foo
75 * baz is the arg value at index 0 in the arg list
78 * @ingroup Maintenance
80 abstract class Maintenance
{
82 * Constants for DB access type
83 * @see Maintenance::getDbType()
89 // Const for getStdin()
90 const STDIN_ALL
= 'all';
92 // Array of desired/allowed params
93 protected $mParams = [];
95 // Array of mapping short parameters to long ones
96 protected $mShortParamsMap = [];
98 // Array of desired/allowed args
99 protected $mArgList = [];
101 // This is the list of options that were actually passed
102 protected $mOptions = [];
104 // This is the list of arguments that were actually passed
105 protected $mArgs = [];
107 // Allow arbitrary options to be passed, or only specified ones?
108 protected $mAllowUnregisteredOptions = false;
110 // Name of the script currently running
113 // Special vars for params that are always used
114 protected $mQuiet = false;
115 protected $mDbUser, $mDbPass;
117 // A description of the script, children should change this via addDescription()
118 protected $mDescription = '';
120 // Have we already loaded our user input?
121 protected $mInputLoaded = false;
124 * Batch size. If a script supports this, they should set
125 * a default with setBatchSize()
129 protected $mBatchSize = null;
131 // Generic options added by addDefaultParams()
132 private $mGenericParameters = [];
133 // Generic options which might or not be supported by the script
134 private $mDependantParameters = [];
137 * Used by getDB() / setDB()
138 * @var IMaintainableDatabase
142 /** @var float UNIX timestamp */
143 private $lastReplicationWait = 0.0;
146 * Used when creating separate schema files.
152 * Accessible via getConfig()
159 * @see Maintenance::requireExtension
162 private $requiredExtensions = [];
165 * Used to read the options in the order they were passed.
166 * Useful for option chaining (Ex. dumpBackup.php). It will
167 * be an empty array if the options are passed in through
168 * loadParamsAndArgs( $self, $opts, $args ).
170 * This is an array of arrays where
171 * 0 => the option and 1 => parameter value.
175 public $orderedOptions = [];
178 * Default constructor. Children should call this *first* if implementing
179 * their own constructors
181 public function __construct() {
183 $IP = getenv( 'MW_INSTALL_PATH' );
185 $this->addDefaultParams();
186 register_shutdown_function( [ $this, 'outputChanneled' ], false );
190 * Should we execute the maintenance script, or just allow it to be included
191 * as a standalone class? It checks that the call stack only includes this
192 * function and "requires" (meaning was called from the file scope)
196 public static function shouldExecute() {
197 global $wgCommandLineMode;
199 if ( !function_exists( 'debug_backtrace' ) ) {
200 // If someone has a better idea...
201 return $wgCommandLineMode;
204 $bt = debug_backtrace();
205 $count = count( $bt );
207 return false; // sanity
209 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
210 return false; // last call should be to this function
212 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
213 for ( $i = 1; $i < $count; $i++
) {
214 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
215 return false; // previous calls should all be "requires"
223 * Do the actual work. All child classes will need to implement this
225 * @return bool|null|void True for success, false for failure. Not returning
226 * a value, or returning null, is also interpreted as success. Returning
227 * false for failure will cause doMaintenance.php to exit the process
228 * with a non-zero exit status.
230 abstract public function execute();
233 * Checks to see if a particular option in supported. Normally this means it
234 * has been registered by the script via addOption.
235 * @param string $name The name of the option
236 * @return bool true if the option exists, false otherwise
238 protected function supportsOption( $name ) {
239 return isset( $this->mParams
[$name] );
243 * Add a parameter to the script. Will be displayed on --help
244 * with the associated description
246 * @param string $name The name of the param (help, version, etc)
247 * @param string $description The description of the param to show on --help
248 * @param bool $required Is the param required?
249 * @param bool $withArg Is an argument required with this option?
250 * @param string|bool $shortName Character to use as short name
251 * @param bool $multiOccurrence Can this option be passed multiple times?
253 protected function addOption( $name, $description, $required = false,
254 $withArg = false, $shortName = false, $multiOccurrence = false
256 $this->mParams
[$name] = [
257 'desc' => $description,
258 'require' => $required,
259 'withArg' => $withArg,
260 'shortName' => $shortName,
261 'multiOccurrence' => $multiOccurrence
264 if ( $shortName !== false ) {
265 $this->mShortParamsMap
[$shortName] = $name;
270 * Checks to see if a particular option exists.
271 * @param string $name The name of the option
274 protected function hasOption( $name ) {
275 return isset( $this->mOptions
[$name] );
279 * Get an option, or return the default.
281 * If the option was added to support multiple occurrences,
282 * this will return an array.
284 * @param string $name The name of the param
285 * @param mixed|null $default Anything you want, default null
288 protected function getOption( $name, $default = null ) {
289 if ( $this->hasOption( $name ) ) {
290 return $this->mOptions
[$name];
292 // Set it so we don't have to provide the default again
293 $this->mOptions
[$name] = $default;
295 return $this->mOptions
[$name];
300 * Add some args that are needed
301 * @param string $arg Name of the arg, like 'start'
302 * @param string $description Short description of the arg
303 * @param bool $required Is this required?
305 protected function addArg( $arg, $description, $required = true ) {
306 $this->mArgList
[] = [
308 'desc' => $description,
309 'require' => $required
314 * Remove an option. Useful for removing options that won't be used in your script.
315 * @param string $name The option to remove.
317 protected function deleteOption( $name ) {
318 unset( $this->mParams
[$name] );
322 * Sets whether to allow unregistered options, which are options passed to
323 * a script that do not match an expected parameter.
324 * @param bool $allow Should we allow?
326 protected function setAllowUnregisteredOptions( $allow ) {
327 $this->mAllowUnregisteredOptions
= $allow;
331 * Set the description text.
332 * @param string $text The text of the description
334 protected function addDescription( $text ) {
335 $this->mDescription
= $text;
339 * Does a given argument exist?
340 * @param int $argId The integer value (from zero) for the arg
343 protected function hasArg( $argId = 0 ) {
344 if ( func_num_args() === 0 ) {
345 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
348 return isset( $this->mArgs
[$argId] );
353 * @param int $argId The integer value (from zero) for the arg
354 * @param mixed|null $default The default if it doesn't exist
357 protected function getArg( $argId = 0, $default = null ) {
358 if ( func_num_args() === 0 ) {
359 wfDeprecated( __METHOD__
. ' without an $argId', '1.33' );
362 return $this->mArgs
[$argId] ??
$default;
372 protected function getBatchSize() {
373 return $this->mBatchSize
;
377 * Set the batch size.
378 * @param int $s The number of operations to do in a batch
380 protected function setBatchSize( $s = 0 ) {
381 $this->mBatchSize
= $s;
383 // If we support $mBatchSize, show the option.
384 // Used to be in addDefaultParams, but in order for that to
385 // work, subclasses would have to call this function in the constructor
386 // before they called parent::__construct which is just weird
387 // (and really wasn't done).
388 if ( $this->mBatchSize
) {
389 $this->addOption( 'batch-size', 'Run this many operations ' .
390 'per batch, default: ' . $this->mBatchSize
, false, true );
391 if ( isset( $this->mParams
['batch-size'] ) ) {
392 // This seems a little ugly...
393 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
399 * Get the script's name
402 public function getName() {
407 * Return input from stdin.
408 * @param int|null $len The number of bytes to read. If null, just return the handle.
409 * Maintenance::STDIN_ALL returns the full length
412 protected function getStdin( $len = null ) {
413 if ( $len == self
::STDIN_ALL
) {
414 return file_get_contents( 'php://stdin' );
416 $f = fopen( 'php://stdin', 'rt' );
420 $input = fgets( $f, $len );
423 return rtrim( $input );
429 public function isQuiet() {
430 return $this->mQuiet
;
434 * Throw some output to the user. Scripts can call this with no fears,
435 * as we handle all --quiet stuff here
436 * @param string $out The text to show to the user
437 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
439 protected function output( $out, $channel = null ) {
440 // This is sometimes called very early, before Setup.php is included.
441 if ( class_exists( MediaWikiServices
::class ) ) {
442 // Try to periodically flush buffered metrics to avoid OOMs
443 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
444 if ( $stats->getDataCount() > 1000 ) {
445 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
449 if ( $this->mQuiet
) {
452 if ( $channel === null ) {
453 $this->cleanupChanneled();
456 $out = preg_replace( '/\n\z/', '', $out );
457 $this->outputChanneled( $out, $channel );
462 * Throw an error to the user. Doesn't respect --quiet, so don't use
463 * this for non-error output
464 * @param string $err The error to display
465 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
467 protected function error( $err, $die = 0 ) {
468 if ( intval( $die ) !== 0 ) {
469 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
470 $this->fatalError( $err, intval( $die ) );
472 $this->outputChanneled( false );
474 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
475 !defined( 'MW_PHPUNIT_TEST' )
477 fwrite( STDERR
, $err . "\n" );
484 * Output a message and terminate the current script.
486 * @param string $msg Error message
487 * @param int $exitCode PHP exit status. Should be in range 1-254.
490 protected function fatalError( $msg, $exitCode = 1 ) {
491 $this->error( $msg );
495 private $atLineStart = true;
496 private $lastChannel = null;
499 * Clean up channeled output. Output a newline if necessary.
501 public function cleanupChanneled() {
502 if ( !$this->atLineStart
) {
504 $this->atLineStart
= true;
509 * Message outputter with channeled message support. Messages on the
510 * same channel are concatenated, but any intervening messages in another
511 * channel start a new line.
512 * @param string $msg The message without trailing newline
513 * @param string|null $channel Channel identifier or null for no
514 * channel. Channel comparison uses ===.
516 public function outputChanneled( $msg, $channel = null ) {
517 if ( $msg === false ) {
518 $this->cleanupChanneled();
523 // End the current line if necessary
524 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
530 $this->atLineStart
= false;
531 if ( $channel === null ) {
532 // For unchanneled messages, output trailing newline immediately
534 $this->atLineStart
= true;
536 $this->lastChannel
= $channel;
540 * Does the script need different DB access? By default, we give Maintenance
541 * scripts normal rights to the DB. Sometimes, a script needs admin rights
542 * access for a reason and sometimes they want no access. Subclasses should
543 * override and return one of the following values, as needed:
544 * Maintenance::DB_NONE - For no DB access at all
545 * Maintenance::DB_STD - For normal DB access, default
546 * Maintenance::DB_ADMIN - For admin DB access
549 public function getDbType() {
554 * Add the default parameters to the scripts
556 protected function addDefaultParams() {
557 # Generic (non script dependant) options:
559 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
560 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
561 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
562 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
563 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
566 'Set a specific memory limit for the script, '
567 . '"max" for no limit or "default" to avoid changing it',
571 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
572 "http://en.wikipedia.org. This is sometimes necessary because " .
573 "server name detection may fail in command line scripts.", false, true );
574 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
575 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
576 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
578 # Save generic options to display them separately in help
579 $this->mGenericParameters
= $this->mParams
;
581 # Script dependant options:
583 // If we support a DB, show the options
584 if ( $this->getDbType() > 0 ) {
585 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
586 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
587 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
590 # Save additional script dependant options to display
591 # Â them separately in help
592 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
599 public function getConfig() {
600 if ( $this->config
=== null ) {
601 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
604 return $this->config
;
609 * @param Config $config
611 public function setConfig( Config
$config ) {
612 $this->config
= $config;
616 * Indicate that the specified extension must be
617 * loaded before the script can run.
619 * This *must* be called in the constructor.
622 * @param string $name
624 protected function requireExtension( $name ) {
625 $this->requiredExtensions
[] = $name;
629 * Verify that the required extensions are installed
633 public function checkRequiredExtensions() {
634 $registry = ExtensionRegistry
::getInstance();
636 foreach ( $this->requiredExtensions
as $name ) {
637 if ( !$registry->isLoaded( $name ) ) {
643 $joined = implode( ', ', $missing );
644 $msg = "The following extensions are required to be installed "
645 . "for this script to run: $joined. Please enable them and then try again.";
646 $this->fatalError( $msg );
651 * Set triggers like when to try to run deferred updates
654 public function setAgentAndTriggers() {
655 if ( function_exists( 'posix_getpwuid' ) ) {
656 $agent = posix_getpwuid( posix_geteuid() )['name'];
660 $agent .= '@' . wfHostname();
662 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
663 // Add a comment for easy SHOW PROCESSLIST interpretation
664 $lbFactory->setAgentName(
665 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
667 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
671 * @param LBFactory $LBFactory
672 * @param Config $config
675 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
676 $services = MediaWikiServices
::getInstance();
677 $stats = $services->getStatsdDataFactory();
678 // Hook into period lag checks which often happen in long-running scripts
679 $lbFactory = $services->getDBLoadBalancerFactory();
680 $lbFactory->setWaitForReplicationListener(
682 function () use ( $stats, $config ) {
683 // Check config in case of JobRunner and unit tests
684 if ( $config->get( 'CommandLineMode' ) ) {
685 DeferredUpdates
::tryOpportunisticExecute( 'run' );
687 // Try to periodically flush buffered metrics to avoid OOMs
688 MediaWiki
::emitBufferedStatsdData( $stats, $config );
691 // Check for other windows to run them. A script may read or do a few writes
692 // to the master but mostly be writing to something else, like a file store.
693 $lbFactory->getMainLB()->setTransactionListener(
695 function ( $trigger ) use ( $stats, $config ) {
696 // Check config in case of JobRunner and unit tests
697 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
698 DeferredUpdates
::tryOpportunisticExecute( 'run' );
700 // Try to periodically flush buffered metrics to avoid OOMs
701 MediaWiki
::emitBufferedStatsdData( $stats, $config );
707 * Run a child maintenance script. Pass all of the current arguments
709 * @param string $maintClass A name of a child maintenance class
710 * @param string|null $classFile Full path of where the child is
711 * @return Maintenance
713 public function runChild( $maintClass, $classFile = null ) {
714 // Make sure the class is loaded first
715 if ( !class_exists( $maintClass ) ) {
717 require_once $classFile;
719 if ( !class_exists( $maintClass ) ) {
720 $this->error( "Cannot spawn child: $maintClass" );
725 * @var Maintenance $child
727 $child = new $maintClass();
728 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
729 if ( !is_null( $this->mDb
) ) {
730 $child->setDB( $this->mDb
);
737 * Do some sanity checking and basic setup
739 public function setup() {
740 global $IP, $wgCommandLineMode;
742 # Abort if called from a web server
743 # wfIsCLI() is not available yet
744 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
745 $this->fatalError( 'This script must be run from the command line' );
748 if ( $IP === null ) {
749 $this->fatalError( "\$IP not set, aborting!\n" .
750 '(Did you forget to call parent::__construct() in your maintenance script?)' );
753 # Make sure we can handle script parameters
754 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
755 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
758 // Send PHP warnings and errors to stderr instead of stdout.
759 // This aids in diagnosing problems, while keeping messages
760 // out of redirected output.
761 if ( ini_get( 'display_errors' ) ) {
762 ini_set( 'display_errors', 'stderr' );
765 $this->loadParamsAndArgs();
767 # Set the memory limit
768 # Note we need to set it again later in cache LocalSettings changed it
769 $this->adjustMemoryLimit();
771 # Set max execution time to 0 (no limit). PHP.net says that
772 # "When running PHP from the command line the default setting is 0."
773 # But sometimes this doesn't seem to be the case.
774 ini_set( 'max_execution_time', 0 );
776 # Define us as being in MediaWiki
777 define( 'MEDIAWIKI', true );
779 $wgCommandLineMode = true;
781 # Turn off output buffering if it's on
782 while ( ob_get_level() > 0 ) {
788 * Normally we disable the memory_limit when running admin scripts.
789 * Some scripts may wish to actually set a limit, however, to avoid
790 * blowing up unexpectedly. We also support a --memory-limit option,
791 * to allow sysadmins to explicitly set one if they'd prefer to override
792 * defaults (or for people using Suhosin which yells at you for trying
793 * to disable the limits)
796 public function memoryLimit() {
797 $limit = $this->getOption( 'memory-limit', 'max' );
798 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
803 * Adjusts PHP's memory limit to better suit our needs, if needed.
805 protected function adjustMemoryLimit() {
806 $limit = $this->memoryLimit();
807 if ( $limit == 'max' ) {
808 $limit = -1; // no memory limit
810 if ( $limit != 'default' ) {
811 ini_set( 'memory_limit', $limit );
816 * Activate the profiler (assuming $wgProfiler is set)
818 protected function activateProfiler() {
819 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
821 $output = $this->getOption( 'profiler' );
826 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
827 $class = $wgProfiler['class'];
828 /** @var Profiler $profiler */
829 $profiler = new $class(
830 [ 'sampling' => 1, 'output' => [ $output ] ]
832 +
[ 'threshold' => $wgProfileLimit ]
834 $profiler->setTemplated( true );
835 Profiler
::replaceStubInstance( $profiler );
838 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
839 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
840 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
844 * Clear all params and arguments.
846 public function clearParamsAndArgs() {
847 $this->mOptions
= [];
849 $this->mInputLoaded
= false;
853 * Load params and arguments from a given array
854 * of command-line arguments
859 public function loadWithArgv( $argv ) {
862 $this->orderedOptions
= [];
865 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
866 if ( $arg == '--' ) {
867 # End of options, remainder should be considered arguments
868 $arg = next( $argv );
869 while ( $arg !== false ) {
871 $arg = next( $argv );
874 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
876 $option = substr( $arg, 2 );
877 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
878 $param = next( $argv );
879 if ( $param === false ) {
880 $this->error( "\nERROR: $option parameter needs a value after it\n" );
881 $this->maybeHelp( true );
884 $this->setParam( $options, $option, $param );
886 $bits = explode( '=', $option, 2 );
887 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
889 } elseif ( $arg == '-' ) {
890 # Lonely "-", often used to indicate stdin or stdout.
892 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
894 $argLength = strlen( $arg );
895 for ( $p = 1; $p < $argLength; $p++
) {
897 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
898 $option = $this->mShortParamsMap
[$option];
901 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
902 $param = next( $argv );
903 if ( $param === false ) {
904 $this->error( "\nERROR: $option parameter needs a value after it\n" );
905 $this->maybeHelp( true );
907 $this->setParam( $options, $option, $param );
909 $this->setParam( $options, $option, 1 );
917 $this->mOptions
= $options;
918 $this->mArgs
= $args;
919 $this->loadSpecialVars();
920 $this->mInputLoaded
= true;
924 * Helper function used solely by loadParamsAndArgs
925 * to prevent code duplication
927 * This sets the param in the options array based on
928 * whether or not it can be specified multiple times.
931 * @param array $options
932 * @param string $option
933 * @param mixed $value
935 private function setParam( &$options, $option, $value ) {
936 $this->orderedOptions
[] = [ $option, $value ];
938 if ( isset( $this->mParams
[$option] ) ) {
939 $multi = $this->mParams
[$option]['multiOccurrence'];
943 $exists = array_key_exists( $option, $options );
944 if ( $multi && $exists ) {
945 $options[$option][] = $value;
946 } elseif ( $multi ) {
947 $options[$option] = [ $value ];
948 } elseif ( !$exists ) {
949 $options[$option] = $value;
951 $this->error( "\nERROR: $option parameter given twice\n" );
952 $this->maybeHelp( true );
957 * Process command line arguments
958 * $mOptions becomes an array with keys set to the option names
959 * $mArgs becomes a zero-based array containing the non-option arguments
961 * @param string|null $self The name of the script, if any
962 * @param array|null $opts An array of options, in form of key=>value
963 * @param array|null $args An array of command line arguments
965 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
966 # If we were given opts or args, set those and return early
968 $this->mSelf
= $self;
969 $this->mInputLoaded
= true;
972 $this->mOptions
= $opts;
973 $this->mInputLoaded
= true;
976 $this->mArgs
= $args;
977 $this->mInputLoaded
= true;
980 # If we've already loaded input (either by user values or from $argv)
981 # skip on loading it again. The array_shift() will corrupt values if
982 # it's run again and again
983 if ( $this->mInputLoaded
) {
984 $this->loadSpecialVars();
990 $this->mSelf
= $argv[0];
991 $this->loadWithArgv( array_slice( $argv, 1 ) );
995 * Run some validation checks on the params, etc
997 public function validateParamsAndArgs() {
999 # Check to make sure we've got all the required options
1000 foreach ( $this->mParams
as $opt => $info ) {
1001 if ( $info['require'] && !$this->hasOption( $opt ) ) {
1002 $this->error( "Param $opt required!" );
1006 # Check arg list too
1007 foreach ( $this->mArgList
as $k => $info ) {
1008 if ( $info['require'] && !$this->hasArg( $k ) ) {
1009 $this->error( 'Argument <' . $info['name'] . '> required!' );
1013 if ( !$this->mAllowUnregisteredOptions
) {
1014 # Check for unexpected options
1015 foreach ( $this->mOptions
as $opt => $val ) {
1016 if ( !$this->supportsOption( $opt ) ) {
1017 $this->error( "Unexpected option $opt!" );
1023 $this->maybeHelp( $die );
1027 * Handle the special variables that are global to all scripts
1029 protected function loadSpecialVars() {
1030 if ( $this->hasOption( 'dbuser' ) ) {
1031 $this->mDbUser
= $this->getOption( 'dbuser' );
1033 if ( $this->hasOption( 'dbpass' ) ) {
1034 $this->mDbPass
= $this->getOption( 'dbpass' );
1036 if ( $this->hasOption( 'quiet' ) ) {
1037 $this->mQuiet
= true;
1039 if ( $this->hasOption( 'batch-size' ) ) {
1040 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1045 * Maybe show the help.
1046 * @param bool $force Whether to force the help to show, default false
1048 protected function maybeHelp( $force = false ) {
1049 if ( !$force && !$this->hasOption( 'help' ) ) {
1053 $screenWidth = 80; // TODO: Calculate this!
1055 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1057 ksort( $this->mParams
);
1058 $this->mQuiet
= false;
1061 if ( $this->mDescription
) {
1062 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1064 $output = "\nUsage: php " . basename( $this->mSelf
);
1066 // ... append parameters ...
1067 if ( $this->mParams
) {
1068 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1071 // ... and append arguments.
1072 if ( $this->mArgList
) {
1074 foreach ( $this->mArgList
as $k => $arg ) {
1075 if ( $arg['require'] ) {
1076 $output .= '<' . $arg['name'] . '>';
1078 $output .= '[' . $arg['name'] . ']';
1080 if ( $k < count( $this->mArgList
) - 1 ) {
1085 $this->output( "$output\n\n" );
1087 # TODO abstract some repetitive code below
1089 // Generic parameters
1090 $this->output( "Generic maintenance parameters:\n" );
1091 foreach ( $this->mGenericParameters
as $par => $info ) {
1092 if ( $info['shortName'] !== false ) {
1093 $par .= " (-{$info['shortName']})";
1096 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1097 "\n$tab$tab" ) . "\n"
1100 $this->output( "\n" );
1102 $scriptDependantParams = $this->mDependantParameters
;
1103 if ( count( $scriptDependantParams ) > 0 ) {
1104 $this->output( "Script dependant parameters:\n" );
1105 // Parameters description
1106 foreach ( $scriptDependantParams as $par => $info ) {
1107 if ( $info['shortName'] !== false ) {
1108 $par .= " (-{$info['shortName']})";
1111 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1112 "\n$tab$tab" ) . "\n"
1115 $this->output( "\n" );
1118 // Script specific parameters not defined on construction by
1119 // Maintenance::addDefaultParams()
1120 $scriptSpecificParams = array_diff_key(
1121 # all script parameters:
1123 # remove the Maintenance default parameters:
1124 $this->mGenericParameters
,
1125 $this->mDependantParameters
1127 if ( count( $scriptSpecificParams ) > 0 ) {
1128 $this->output( "Script specific parameters:\n" );
1129 // Parameters description
1130 foreach ( $scriptSpecificParams as $par => $info ) {
1131 if ( $info['shortName'] !== false ) {
1132 $par .= " (-{$info['shortName']})";
1135 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1136 "\n$tab$tab" ) . "\n"
1139 $this->output( "\n" );
1143 if ( count( $this->mArgList
) > 0 ) {
1144 $this->output( "Arguments:\n" );
1145 // Arguments description
1146 foreach ( $this->mArgList
as $info ) {
1147 $openChar = $info['require'] ?
'<' : '[';
1148 $closeChar = $info['require'] ?
'>' : ']';
1150 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1151 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1154 $this->output( "\n" );
1161 * Handle some last-minute setup here.
1163 public function finalSetup() {
1164 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1165 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1166 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1168 # Turn off output buffering again, it might have been turned on in the settings files
1169 if ( ob_get_level() ) {
1173 $wgCommandLineMode = true;
1175 # Override $wgServer
1176 if ( $this->hasOption( 'server' ) ) {
1177 $wgServer = $this->getOption( 'server', $wgServer );
1180 # If these were passed, use them
1181 if ( $this->mDbUser
) {
1182 $wgDBadminuser = $this->mDbUser
;
1184 if ( $this->mDbPass
) {
1185 $wgDBadminpassword = $this->mDbPass
;
1187 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1188 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1190 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1193 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1194 $wgDBuser = $wgDBadminuser;
1195 $wgDBpassword = $wgDBadminpassword;
1197 if ( $wgDBservers ) {
1199 * @var array $wgDBservers
1201 foreach ( $wgDBservers as $i => $server ) {
1202 $wgDBservers[$i]['user'] = $wgDBuser;
1203 $wgDBservers[$i]['password'] = $wgDBpassword;
1206 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1207 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1208 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1210 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1213 # Apply debug settings
1214 if ( $this->hasOption( 'mwdebug' ) ) {
1215 require __DIR__
. '/../includes/DevelopmentSettings.php';
1218 // Per-script profiling; useful for debugging
1219 $this->activateProfiler();
1221 $this->afterFinalSetup();
1223 $wgShowExceptionDetails = true;
1224 $wgShowHostnames = true;
1226 Wikimedia\
suppressWarnings();
1227 set_time_limit( 0 );
1228 Wikimedia\restoreWarnings
();
1230 $this->adjustMemoryLimit();
1234 * Execute a callback function at the end of initialisation
1236 protected function afterFinalSetup() {
1237 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1238 call_user_func( MW_CMDLINE_CALLBACK
);
1243 * Potentially debug globals. Originally a feature only
1246 public function globals() {
1247 if ( $this->hasOption( 'globals' ) ) {
1248 print_r( $GLOBALS );
1253 * Generic setup for most installs. Returns the location of LocalSettings
1256 public function loadSettings() {
1257 global $wgCommandLineMode, $IP;
1259 if ( isset( $this->mOptions
['conf'] ) ) {
1260 $settingsFile = $this->mOptions
['conf'];
1261 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1262 $settingsFile = MW_CONFIG_FILE
;
1264 $settingsFile = "$IP/LocalSettings.php";
1266 if ( isset( $this->mOptions
['wiki'] ) ) {
1267 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1268 define( 'MW_DB', $bits[0] );
1269 define( 'MW_PREFIX', $bits[1] ??
'' );
1270 } elseif ( isset( $this->mOptions
['server'] ) ) {
1271 // Provide the option for site admins to detect and configure
1272 // multiple wikis based on server names. This offers --server
1273 // as alternative to --wiki.
1274 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1275 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1278 if ( !is_readable( $settingsFile ) ) {
1279 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1280 "must exist and be readable in the source directory.\n" .
1281 "Use --conf to specify it." );
1283 $wgCommandLineMode = true;
1285 return $settingsFile;
1289 * Support function for cleaning up redundant text records
1290 * @param bool $delete Whether or not to actually delete the records
1291 * @author Rob Church <robchur@gmail.com>
1293 public function purgeRedundantText( $delete = true ) {
1294 global $wgMultiContentRevisionSchemaMigrationStage;
1296 # Data should come off the master, wrapped in a transaction
1297 $dbw = $this->getDB( DB_MASTER
);
1298 $this->beginTransaction( $dbw, __METHOD__
);
1300 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1301 # Get "active" text records from the revisions table
1303 $this->output( 'Searching for active text records in revisions table...' );
1304 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1305 foreach ( $res as $row ) {
1306 $cur[] = $row->rev_text_id
;
1308 $this->output( "done.\n" );
1310 # Get "active" text records from the archive table
1311 $this->output( 'Searching for active text records in archive table...' );
1312 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1313 foreach ( $res as $row ) {
1314 # old pre-MW 1.5 records can have null ar_text_id's.
1315 if ( $row->ar_text_id
!== null ) {
1316 $cur[] = $row->ar_text_id
;
1319 $this->output( "done.\n" );
1321 # Get "active" text records via the content table
1323 $this->output( 'Searching for active text records via contents table...' );
1324 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1325 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1326 foreach ( $res as $row ) {
1327 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1332 $this->output( "done.\n" );
1334 $this->output( "done.\n" );
1336 # Get the IDs of all text records not in these sets
1337 $this->output( 'Searching for inactive text records...' );
1338 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1339 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1341 foreach ( $res as $row ) {
1342 $old[] = $row->old_id
;
1344 $this->output( "done.\n" );
1346 # Inform the user of what we're going to do
1347 $count = count( $old );
1348 $this->output( "$count inactive items found.\n" );
1350 # Delete as appropriate
1351 if ( $delete && $count ) {
1352 $this->output( 'Deleting...' );
1353 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1354 $this->output( "done.\n" );
1357 $this->commitTransaction( $dbw, __METHOD__
);
1361 * Get the maintenance directory.
1364 protected function getDir() {
1369 * Returns a database to be used by current maintenance script. It can be set by setDB().
1370 * If not set, wfGetDB() will be used.
1371 * This function has the same parameters as wfGetDB()
1373 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1374 * @param string|string[] $groups default: empty array
1375 * @param string|bool $wiki default: current wiki
1376 * @return IMaintainableDatabase
1378 protected function getDB( $db, $groups = [], $wiki = false ) {
1379 if ( $this->mDb
=== null ) {
1380 return wfGetDB( $db, $groups, $wiki );
1386 * Sets database object to be returned by getDB().
1388 * @param IDatabase $db
1390 public function setDB( IDatabase
$db ) {
1395 * Begin a transcation on a DB
1397 * This method makes it clear that begin() is called from a maintenance script,
1398 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1400 * @param IDatabase $dbw
1401 * @param string $fname Caller name
1404 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1405 $dbw->begin( $fname );
1409 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1411 * This method makes it clear that commit() is called from a maintenance script,
1412 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1414 * @param IDatabase $dbw
1415 * @param string $fname Caller name
1416 * @return bool Whether the replica DB wait succeeded
1419 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1420 $dbw->commit( $fname );
1421 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1422 $waitSucceeded = $lbFactory->waitForReplication(
1423 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1425 $this->lastReplicationWait
= microtime( true );
1426 return $waitSucceeded;
1430 * Rollback the transcation on a DB handle
1432 * This method makes it clear that rollback() is called from a maintenance script,
1433 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1435 * @param IDatabase $dbw
1436 * @param string $fname Caller name
1439 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1440 $dbw->rollback( $fname );
1444 * Lock the search index
1445 * @param IMaintainableDatabase &$db
1447 private function lockSearchindex( $db ) {
1448 $write = [ 'searchindex' ];
1458 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1463 * @param IMaintainableDatabase &$db
1465 private function unlockSearchindex( $db ) {
1466 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1470 * Unlock and lock again
1471 * Since the lock is low-priority, queued reads will be able to complete
1472 * @param IMaintainableDatabase &$db
1474 private function relockSearchindex( $db ) {
1475 $this->unlockSearchindex( $db );
1476 $this->lockSearchindex( $db );
1480 * Perform a search index update with locking
1481 * @param int $maxLockTime The maximum time to keep the search index locked.
1482 * @param callable $callback The function that will update the function.
1483 * @param IMaintainableDatabase $dbw
1484 * @param array|IResultWrapper $results
1486 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1490 if ( $maxLockTime ) {
1491 $this->output( " --- Waiting for lock ---" );
1492 $this->lockSearchindex( $dbw );
1494 $this->output( "\n" );
1497 # Loop through the results and do a search update
1498 foreach ( $results as $row ) {
1499 # Allow reads to be processed
1500 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1501 $this->output( " --- Relocking ---" );
1502 $this->relockSearchindex( $dbw );
1504 $this->output( "\n" );
1506 call_user_func( $callback, $dbw, $row );
1509 # Unlock searchindex
1510 if ( $maxLockTime ) {
1511 $this->output( " --- Unlocking --" );
1512 $this->unlockSearchindex( $dbw );
1513 $this->output( "\n" );
1518 * Update the searchindex table for a given pageid
1519 * @param IDatabase $dbw A database write handle
1520 * @param int $pageId The page ID to update.
1521 * @return null|string
1523 public function updateSearchIndexForPage( $dbw, $pageId ) {
1524 // Get current revision
1525 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1528 $titleObj = $rev->getTitle();
1529 $title = $titleObj->getPrefixedDBkey();
1530 $this->output( "$title..." );
1531 # Update searchindex
1532 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1534 $this->output( "\n" );
1541 * Count down from $seconds to zero on the terminal, with a one-second pause
1542 * between showing each number. If the maintenance script is in quiet mode,
1543 * this function does nothing.
1547 * @codeCoverageIgnore
1548 * @param int $seconds
1550 protected function countDown( $seconds ) {
1551 if ( $this->isQuiet() ) {
1554 for ( $i = $seconds; $i >= 0; $i-- ) {
1555 if ( $i != $seconds ) {
1556 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1558 $this->output( $i );
1563 $this->output( "\n" );
1567 * Wrapper for posix_isatty()
1568 * We default as considering stdin a tty (for nice readline methods)
1569 * but treating stout as not a tty to avoid color codes
1571 * @param mixed $fd File descriptor
1574 public static function posix_isatty( $fd ) {
1575 if ( !function_exists( 'posix_isatty' ) ) {
1578 return posix_isatty( $fd );
1583 * Prompt the console for input
1584 * @param string $prompt What to begin the line with, like '> '
1585 * @return string Response
1587 public static function readconsole( $prompt = '> ' ) {
1588 static $isatty = null;
1589 if ( is_null( $isatty ) ) {
1590 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1593 if ( $isatty && function_exists( 'readline' ) ) {
1594 return readline( $prompt );
1597 $st = self
::readlineEmulation( $prompt );
1599 if ( feof( STDIN
) ) {
1602 $st = fgets( STDIN
, 1024 );
1605 if ( $st === false ) {
1608 $resp = trim( $st );
1615 * Emulate readline()
1616 * @param string $prompt What to begin the line with, like '> '
1619 private static function readlineEmulation( $prompt ) {
1620 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1621 if ( !wfIsWindows() && $bash ) {
1623 $encPrompt = Shell
::escape( $prompt );
1624 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1625 $encCommand = Shell
::escape( $command );
1626 $line = Shell
::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1628 if ( $retval == 0 ) {
1630 } elseif ( $retval == 127 ) {
1631 // Couldn't execute bash even though we thought we saw it.
1632 // Shell probably spit out an error message, sorry :(
1633 // Fall through to fgets()...
1640 // Fallback... we'll have no editing controls, EWWW
1641 if ( feof( STDIN
) ) {
1646 return fgets( STDIN
, 1024 );
1650 * Get the terminal size as a two-element array where the first element
1651 * is the width (number of columns) and the second element is the height
1656 public static function getTermSize() {
1657 $default = [ 80, 50 ];
1658 if ( wfIsWindows() ) {
1661 if ( Shell
::isDisabled() ) {
1664 // It's possible to get the screen size with VT-100 terminal escapes,
1665 // but reading the responses is not possible without setting raw mode
1666 // (unless you want to require the user to press enter), and that
1667 // requires an ioctl(), which we can't do. So we have to shell out to
1668 // something that can do the relevant syscalls. There are a few
1669 // options. Linux and Mac OS X both have "stty size" which does the
1671 $result = Shell
::command( 'stty', 'size' )
1673 if ( $result->getExitCode() !== 0 ) {
1676 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1679 return [ intval( $m[2] ), intval( $m[1] ) ];
1683 * Call this to set up the autoloader to allow classes to be used from the
1686 public static function requireTestsAutoloader() {
1687 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1692 * Fake maintenance wrapper, mostly used for the web installer/updater
1694 class FakeMaintenance
extends Maintenance
{
1695 protected $mSelf = "FakeMaintenanceScript";
1697 public function execute() {
1702 * Class for scripts that perform database maintenance and want to log the
1703 * update in `updatelog` so we can later skip it
1705 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1706 public function __construct() {
1707 parent
::__construct();
1708 $this->addOption( 'force', 'Run the update even if it was completed already' );
1709 $this->setBatchSize( 200 );
1712 public function execute() {
1713 $db = $this->getDB( DB_MASTER
);
1714 $key = $this->getUpdateKey();
1716 if ( !$this->hasOption( 'force' )
1717 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1719 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1724 if ( !$this->doDBUpdates() ) {
1728 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, [ 'IGNORE' ] );
1734 * Message to show that the update was done already and was just skipped
1737 protected function updateSkippedMessage() {
1738 $key = $this->getUpdateKey();
1740 return "Update '{$key}' already logged as completed. Use --force to run it again.";
1744 * Do the actual work. All child classes will need to implement this.
1745 * Return true to log the update as done or false (usually on failure).
1748 abstract protected function doDBUpdates();
1751 * Get the update key name to go in the update log table
1754 abstract protected function getUpdateKey();