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( 'cli' );
29 * @defgroup MaintenanceArchive Maintenance archives
30 * @ingroup Maintenance
33 // Define this so scripts can easily find doMaintenance.php
34 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
35 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
39 use MediaWiki\Logger\LoggerFactory
;
40 use MediaWiki\MediaWikiServices
;
41 use Wikimedia\Rdbms\LBFactory
;
44 * Abstract maintenance class for quickly writing and churning out
45 * maintenance scripts with minimal effort. All that _must_ be defined
46 * is the execute() method. See docs/maintenance.txt for more info
47 * and a quick demo of how to use it.
49 * @author Chad Horohoe <chad@anyonecanedit.org>
51 * @ingroup Maintenance
53 abstract class Maintenance
{
55 * Constants for DB access type
56 * @see Maintenance::getDbType()
62 // Const for getStdin()
63 const STDIN_ALL
= 'all';
65 // This is the desired params
66 protected $mParams = [];
68 // Array of mapping short parameters to long ones
69 protected $mShortParamsMap = [];
71 // Array of desired args
72 protected $mArgList = [];
74 // This is the list of options that were actually passed
75 protected $mOptions = [];
77 // This is the list of arguments that were actually passed
78 protected $mArgs = [];
80 // Name of the script currently running
83 // Special vars for params that are always used
84 protected $mQuiet = false;
85 protected $mDbUser, $mDbPass;
87 // A description of the script, children should change this via addDescription()
88 protected $mDescription = '';
90 // Have we already loaded our user input?
91 protected $mInputLoaded = false;
94 * Batch size. If a script supports this, they should set
95 * a default with setBatchSize()
99 protected $mBatchSize = null;
101 // Generic options added by addDefaultParams()
102 private $mGenericParameters = [];
103 // Generic options which might or not be supported by the script
104 private $mDependantParameters = [];
107 * Used by getDB() / setDB()
112 /** @var float UNIX timestamp */
113 private $lastReplicationWait = 0.0;
116 * Used when creating separate schema files.
122 * Accessible via getConfig()
129 * @see Maintenance::requireExtension
132 private $requiredExtensions = [];
135 * Used to read the options in the order they were passed.
136 * Useful for option chaining (Ex. dumpBackup.php). It will
137 * be an empty array if the options are passed in through
138 * loadParamsAndArgs( $self, $opts, $args ).
140 * This is an array of arrays where
141 * 0 => the option and 1 => parameter value.
145 public $orderedOptions = [];
148 * Default constructor. Children should call this *first* if implementing
149 * their own constructors
151 public function __construct() {
152 // Setup $IP, using MW_INSTALL_PATH if it exists
154 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
155 ?
getenv( 'MW_INSTALL_PATH' )
156 : realpath( __DIR__
. '/..' );
158 $this->addDefaultParams();
159 register_shutdown_function( [ $this, 'outputChanneled' ], false );
163 * Should we execute the maintenance script, or just allow it to be included
164 * as a standalone class? It checks that the call stack only includes this
165 * function and "requires" (meaning was called from the file scope)
169 public static function shouldExecute() {
170 global $wgCommandLineMode;
172 if ( !function_exists( 'debug_backtrace' ) ) {
173 // If someone has a better idea...
174 return $wgCommandLineMode;
177 $bt = debug_backtrace();
178 $count = count( $bt );
180 return false; // sanity
182 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
183 return false; // last call should be to this function
185 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
186 for ( $i = 1; $i < $count; $i++
) {
187 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
188 return false; // previous calls should all be "requires"
196 * Do the actual work. All child classes will need to implement this
198 abstract public function execute();
201 * Add a parameter to the script. Will be displayed on --help
202 * with the associated description
204 * @param string $name The name of the param (help, version, etc)
205 * @param string $description The description of the param to show on --help
206 * @param bool $required Is the param required?
207 * @param bool $withArg Is an argument required with this option?
208 * @param string $shortName Character to use as short name
209 * @param bool $multiOccurrence Can this option be passed multiple times?
211 protected function addOption( $name, $description, $required = false,
212 $withArg = false, $shortName = false, $multiOccurrence = false
214 $this->mParams
[$name] = [
215 'desc' => $description,
216 'require' => $required,
217 'withArg' => $withArg,
218 'shortName' => $shortName,
219 'multiOccurrence' => $multiOccurrence
222 if ( $shortName !== false ) {
223 $this->mShortParamsMap
[$shortName] = $name;
228 * Checks to see if a particular param exists.
229 * @param string $name The name of the param
232 protected function hasOption( $name ) {
233 return isset( $this->mOptions
[$name] );
237 * Get an option, or return the default.
239 * If the option was added to support multiple occurrences,
240 * this will return an array.
242 * @param string $name The name of the param
243 * @param mixed $default Anything you want, default null
246 protected function getOption( $name, $default = null ) {
247 if ( $this->hasOption( $name ) ) {
248 return $this->mOptions
[$name];
250 // Set it so we don't have to provide the default again
251 $this->mOptions
[$name] = $default;
253 return $this->mOptions
[$name];
258 * Add some args that are needed
259 * @param string $arg Name of the arg, like 'start'
260 * @param string $description Short description of the arg
261 * @param bool $required Is this required?
263 protected function addArg( $arg, $description, $required = true ) {
264 $this->mArgList
[] = [
266 'desc' => $description,
267 'require' => $required
272 * Remove an option. Useful for removing options that won't be used in your script.
273 * @param string $name The option to remove.
275 protected function deleteOption( $name ) {
276 unset( $this->mParams
[$name] );
280 * Set the description text.
281 * @param string $text The text of the description
283 protected function addDescription( $text ) {
284 $this->mDescription
= $text;
288 * Does a given argument exist?
289 * @param int $argId The integer value (from zero) for the arg
292 protected function hasArg( $argId = 0 ) {
293 return isset( $this->mArgs
[$argId] );
298 * @param int $argId The integer value (from zero) for the arg
299 * @param mixed $default The default if it doesn't exist
302 protected function getArg( $argId = 0, $default = null ) {
303 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
307 * Set the batch size.
308 * @param int $s The number of operations to do in a batch
310 protected function setBatchSize( $s = 0 ) {
311 $this->mBatchSize
= $s;
313 // If we support $mBatchSize, show the option.
314 // Used to be in addDefaultParams, but in order for that to
315 // work, subclasses would have to call this function in the constructor
316 // before they called parent::__construct which is just weird
317 // (and really wasn't done).
318 if ( $this->mBatchSize
) {
319 $this->addOption( 'batch-size', 'Run this many operations ' .
320 'per batch, default: ' . $this->mBatchSize
, false, true );
321 if ( isset( $this->mParams
['batch-size'] ) ) {
322 // This seems a little ugly...
323 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
329 * Get the script's name
332 public function getName() {
337 * Return input from stdin.
338 * @param int $len The number of bytes to read. If null, just return the handle.
339 * Maintenance::STDIN_ALL returns the full length
342 protected function getStdin( $len = null ) {
343 if ( $len == Maintenance
::STDIN_ALL
) {
344 return file_get_contents( 'php://stdin' );
346 $f = fopen( 'php://stdin', 'rt' );
350 $input = fgets( $f, $len );
353 return rtrim( $input );
359 public function isQuiet() {
360 return $this->mQuiet
;
364 * Throw some output to the user. Scripts can call this with no fears,
365 * as we handle all --quiet stuff here
366 * @param string $out The text to show to the user
367 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
369 protected function output( $out, $channel = null ) {
370 if ( $this->mQuiet
) {
373 if ( $channel === null ) {
374 $this->cleanupChanneled();
377 $out = preg_replace( '/\n\z/', '', $out );
378 $this->outputChanneled( $out, $channel );
383 * Throw an error to the user. Doesn't respect --quiet, so don't use
384 * this for non-error output
385 * @param string $err The error to display
386 * @param int $die If > 0, go ahead and die out using this int as the code
388 protected function error( $err, $die = 0 ) {
389 $this->outputChanneled( false );
390 if ( PHP_SAPI
== 'cli' ) {
391 fwrite( STDERR
, $err . "\n" );
395 $die = intval( $die );
401 private $atLineStart = true;
402 private $lastChannel = null;
405 * Clean up channeled output. Output a newline if necessary.
407 public function cleanupChanneled() {
408 if ( !$this->atLineStart
) {
410 $this->atLineStart
= true;
415 * Message outputter with channeled message support. Messages on the
416 * same channel are concatenated, but any intervening messages in another
417 * channel start a new line.
418 * @param string $msg The message without trailing newline
419 * @param string $channel Channel identifier or null for no
420 * channel. Channel comparison uses ===.
422 public function outputChanneled( $msg, $channel = null ) {
423 if ( $msg === false ) {
424 $this->cleanupChanneled();
429 // End the current line if necessary
430 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
436 $this->atLineStart
= false;
437 if ( $channel === null ) {
438 // For unchanneled messages, output trailing newline immediately
440 $this->atLineStart
= true;
442 $this->lastChannel
= $channel;
446 * Does the script need different DB access? By default, we give Maintenance
447 * scripts normal rights to the DB. Sometimes, a script needs admin rights
448 * access for a reason and sometimes they want no access. Subclasses should
449 * override and return one of the following values, as needed:
450 * Maintenance::DB_NONE - For no DB access at all
451 * Maintenance::DB_STD - For normal DB access, default
452 * Maintenance::DB_ADMIN - For admin DB access
455 public function getDbType() {
456 return Maintenance
::DB_STD
;
460 * Add the default parameters to the scripts
462 protected function addDefaultParams() {
463 # Generic (non script dependant) options:
465 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
466 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
467 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
468 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
469 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
472 'Set a specific memory limit for the script, '
473 . '"max" for no limit or "default" to avoid changing it'
475 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
476 "http://en.wikipedia.org. This is sometimes necessary because " .
477 "server name detection may fail in command line scripts.", false, true );
478 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
480 # Save generic options to display them separately in help
481 $this->mGenericParameters
= $this->mParams
;
483 # Script dependant options:
485 // If we support a DB, show the options
486 if ( $this->getDbType() > 0 ) {
487 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
488 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
491 # Save additional script dependant options to display
492 # Â them separately in help
493 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
500 public function getConfig() {
501 if ( $this->config
=== null ) {
502 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
505 return $this->config
;
510 * @param Config $config
512 public function setConfig( Config
$config ) {
513 $this->config
= $config;
517 * Indicate that the specified extension must be
518 * loaded before the script can run.
520 * This *must* be called in the constructor.
523 * @param string $name
525 protected function requireExtension( $name ) {
526 $this->requiredExtensions
[] = $name;
530 * Verify that the required extensions are installed
534 public function checkRequiredExtensions() {
535 $registry = ExtensionRegistry
::getInstance();
537 foreach ( $this->requiredExtensions
as $name ) {
538 if ( !$registry->isLoaded( $name ) ) {
544 $joined = implode( ', ', $missing );
545 $msg = "The following extensions are required to be installed "
546 . "for this script to run: $joined. Please enable them and then try again.";
547 $this->error( $msg, 1 );
552 * Set triggers like when to try to run deferred updates
555 public function setAgentAndTriggers() {
556 if ( function_exists( 'posix_getpwuid' ) ) {
557 $agent = posix_getpwuid( posix_geteuid() )['name'];
561 $agent .= '@' . wfHostname();
563 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
564 // Add a comment for easy SHOW PROCESSLIST interpretation
565 $lbFactory->setAgentName(
566 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
568 self
::setLBFactoryTriggers( $lbFactory );
572 * @param LBFactory $LBFactory
575 public static function setLBFactoryTriggers( LBFactory
$LBFactory ) {
576 // Hook into period lag checks which often happen in long-running scripts
577 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
578 $lbFactory->setWaitForReplicationListener(
581 global $wgCommandLineMode;
582 // Check config in case of JobRunner and unit tests
583 if ( $wgCommandLineMode ) {
584 DeferredUpdates
::tryOpportunisticExecute( 'run' );
588 // Check for other windows to run them. A script may read or do a few writes
589 // to the master but mostly be writing to something else, like a file store.
590 $lbFactory->getMainLB()->setTransactionListener(
592 function ( $trigger ) {
593 global $wgCommandLineMode;
594 // Check config in case of JobRunner and unit tests
595 if ( $wgCommandLineMode && $trigger === IDatabase
::TRIGGER_COMMIT
) {
596 DeferredUpdates
::tryOpportunisticExecute( 'run' );
603 * Run a child maintenance script. Pass all of the current arguments
605 * @param string $maintClass A name of a child maintenance class
606 * @param string $classFile Full path of where the child is
607 * @return Maintenance
609 public function runChild( $maintClass, $classFile = null ) {
610 // Make sure the class is loaded first
611 if ( !class_exists( $maintClass ) ) {
613 require_once $classFile;
615 if ( !class_exists( $maintClass ) ) {
616 $this->error( "Cannot spawn child: $maintClass" );
621 * @var $child Maintenance
623 $child = new $maintClass();
624 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
625 if ( !is_null( $this->mDb
) ) {
626 $child->setDB( $this->mDb
);
633 * Do some sanity checking and basic setup
635 public function setup() {
636 global $IP, $wgCommandLineMode, $wgRequestTime;
638 # Abort if called from a web server
639 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
640 $this->error( 'This script must be run from the command line', true );
643 if ( $IP === null ) {
644 $this->error( "\$IP not set, aborting!\n" .
645 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
648 # Make sure we can handle script parameters
649 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
650 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
653 // Send PHP warnings and errors to stderr instead of stdout.
654 // This aids in diagnosing problems, while keeping messages
655 // out of redirected output.
656 if ( ini_get( 'display_errors' ) ) {
657 ini_set( 'display_errors', 'stderr' );
660 $this->loadParamsAndArgs();
663 # Set the memory limit
664 # Note we need to set it again later in cache LocalSettings changed it
665 $this->adjustMemoryLimit();
667 # Set max execution time to 0 (no limit). PHP.net says that
668 # "When running PHP from the command line the default setting is 0."
669 # But sometimes this doesn't seem to be the case.
670 ini_set( 'max_execution_time', 0 );
672 $wgRequestTime = microtime( true );
674 # Define us as being in MediaWiki
675 define( 'MEDIAWIKI', true );
677 $wgCommandLineMode = true;
679 # Turn off output buffering if it's on
680 while ( ob_get_level() > 0 ) {
684 $this->validateParamsAndArgs();
688 * Normally we disable the memory_limit when running admin scripts.
689 * Some scripts may wish to actually set a limit, however, to avoid
690 * blowing up unexpectedly. We also support a --memory-limit option,
691 * to allow sysadmins to explicitly set one if they'd prefer to override
692 * defaults (or for people using Suhosin which yells at you for trying
693 * to disable the limits)
696 public function memoryLimit() {
697 $limit = $this->getOption( 'memory-limit', 'max' );
698 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
703 * Adjusts PHP's memory limit to better suit our needs, if needed.
705 protected function adjustMemoryLimit() {
706 $limit = $this->memoryLimit();
707 if ( $limit == 'max' ) {
708 $limit = -1; // no memory limit
710 if ( $limit != 'default' ) {
711 ini_set( 'memory_limit', $limit );
716 * Activate the profiler (assuming $wgProfiler is set)
718 protected function activateProfiler() {
719 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
721 $output = $this->getOption( 'profiler' );
726 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
727 $class = $wgProfiler['class'];
728 /** @var Profiler $profiler */
729 $profiler = new $class(
730 [ 'sampling' => 1, 'output' => [ $output ] ]
732 +
[ 'threshold' => $wgProfileLimit ]
734 $profiler->setTemplated( true );
735 Profiler
::replaceStubInstance( $profiler );
738 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
739 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
740 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
744 * Clear all params and arguments.
746 public function clearParamsAndArgs() {
747 $this->mOptions
= [];
749 $this->mInputLoaded
= false;
753 * Load params and arguments from a given array
754 * of command-line arguments
759 public function loadWithArgv( $argv ) {
762 $this->orderedOptions
= [];
765 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
766 if ( $arg == '--' ) {
767 # End of options, remainder should be considered arguments
768 $arg = next( $argv );
769 while ( $arg !== false ) {
771 $arg = next( $argv );
774 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
776 $option = substr( $arg, 2 );
777 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
778 $param = next( $argv );
779 if ( $param === false ) {
780 $this->error( "\nERROR: $option parameter needs a value after it\n" );
781 $this->maybeHelp( true );
784 $this->setParam( $options, $option, $param );
786 $bits = explode( '=', $option, 2 );
787 if ( count( $bits ) > 1 ) {
794 $this->setParam( $options, $option, $param );
796 } elseif ( $arg == '-' ) {
797 # Lonely "-", often used to indicate stdin or stdout.
799 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
801 $argLength = strlen( $arg );
802 for ( $p = 1; $p < $argLength; $p++
) {
804 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
805 $option = $this->mShortParamsMap
[$option];
808 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
809 $param = next( $argv );
810 if ( $param === false ) {
811 $this->error( "\nERROR: $option parameter needs a value after it\n" );
812 $this->maybeHelp( true );
814 $this->setParam( $options, $option, $param );
816 $this->setParam( $options, $option, 1 );
824 $this->mOptions
= $options;
825 $this->mArgs
= $args;
826 $this->loadSpecialVars();
827 $this->mInputLoaded
= true;
831 * Helper function used solely by loadParamsAndArgs
832 * to prevent code duplication
834 * This sets the param in the options array based on
835 * whether or not it can be specified multiple times.
838 * @param array $options
839 * @param string $option
840 * @param mixed $value
842 private function setParam( &$options, $option, $value ) {
843 $this->orderedOptions
[] = [ $option, $value ];
845 if ( isset( $this->mParams
[$option] ) ) {
846 $multi = $this->mParams
[$option]['multiOccurrence'];
850 $exists = array_key_exists( $option, $options );
851 if ( $multi && $exists ) {
852 $options[$option][] = $value;
853 } elseif ( $multi ) {
854 $options[$option] = [ $value ];
855 } elseif ( !$exists ) {
856 $options[$option] = $value;
858 $this->error( "\nERROR: $option parameter given twice\n" );
859 $this->maybeHelp( true );
864 * Process command line arguments
865 * $mOptions becomes an array with keys set to the option names
866 * $mArgs becomes a zero-based array containing the non-option arguments
868 * @param string $self The name of the script, if any
869 * @param array $opts An array of options, in form of key=>value
870 * @param array $args An array of command line arguments
872 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
873 # If we were given opts or args, set those and return early
875 $this->mSelf
= $self;
876 $this->mInputLoaded
= true;
879 $this->mOptions
= $opts;
880 $this->mInputLoaded
= true;
883 $this->mArgs
= $args;
884 $this->mInputLoaded
= true;
887 # If we've already loaded input (either by user values or from $argv)
888 # skip on loading it again. The array_shift() will corrupt values if
889 # it's run again and again
890 if ( $this->mInputLoaded
) {
891 $this->loadSpecialVars();
897 $this->mSelf
= $argv[0];
898 $this->loadWithArgv( array_slice( $argv, 1 ) );
902 * Run some validation checks on the params, etc
904 protected function validateParamsAndArgs() {
906 # Check to make sure we've got all the required options
907 foreach ( $this->mParams
as $opt => $info ) {
908 if ( $info['require'] && !$this->hasOption( $opt ) ) {
909 $this->error( "Param $opt required!" );
914 foreach ( $this->mArgList
as $k => $info ) {
915 if ( $info['require'] && !$this->hasArg( $k ) ) {
916 $this->error( 'Argument <' . $info['name'] . '> required!' );
922 $this->maybeHelp( true );
927 * Handle the special variables that are global to all scripts
929 protected function loadSpecialVars() {
930 if ( $this->hasOption( 'dbuser' ) ) {
931 $this->mDbUser
= $this->getOption( 'dbuser' );
933 if ( $this->hasOption( 'dbpass' ) ) {
934 $this->mDbPass
= $this->getOption( 'dbpass' );
936 if ( $this->hasOption( 'quiet' ) ) {
937 $this->mQuiet
= true;
939 if ( $this->hasOption( 'batch-size' ) ) {
940 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
945 * Maybe show the help.
946 * @param bool $force Whether to force the help to show, default false
948 protected function maybeHelp( $force = false ) {
949 if ( !$force && !$this->hasOption( 'help' ) ) {
953 $screenWidth = 80; // TODO: Calculate this!
955 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
957 ksort( $this->mParams
);
958 $this->mQuiet
= false;
961 if ( $this->mDescription
) {
962 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
964 $output = "\nUsage: php " . basename( $this->mSelf
);
966 // ... append parameters ...
967 if ( $this->mParams
) {
968 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
971 // ... and append arguments.
972 if ( $this->mArgList
) {
974 foreach ( $this->mArgList
as $k => $arg ) {
975 if ( $arg['require'] ) {
976 $output .= '<' . $arg['name'] . '>';
978 $output .= '[' . $arg['name'] . ']';
980 if ( $k < count( $this->mArgList
) - 1 ) {
985 $this->output( "$output\n\n" );
987 # TODO abstract some repetitive code below
989 // Generic parameters
990 $this->output( "Generic maintenance parameters:\n" );
991 foreach ( $this->mGenericParameters
as $par => $info ) {
992 if ( $info['shortName'] !== false ) {
993 $par .= " (-{$info['shortName']})";
996 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
997 "\n$tab$tab" ) . "\n"
1000 $this->output( "\n" );
1002 $scriptDependantParams = $this->mDependantParameters
;
1003 if ( count( $scriptDependantParams ) > 0 ) {
1004 $this->output( "Script dependant parameters:\n" );
1005 // Parameters description
1006 foreach ( $scriptDependantParams as $par => $info ) {
1007 if ( $info['shortName'] !== false ) {
1008 $par .= " (-{$info['shortName']})";
1011 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1012 "\n$tab$tab" ) . "\n"
1015 $this->output( "\n" );
1018 // Script specific parameters not defined on construction by
1019 // Maintenance::addDefaultParams()
1020 $scriptSpecificParams = array_diff_key(
1021 # all script parameters:
1023 # remove the Maintenance default parameters:
1024 $this->mGenericParameters
,
1025 $this->mDependantParameters
1027 if ( count( $scriptSpecificParams ) > 0 ) {
1028 $this->output( "Script specific parameters:\n" );
1029 // Parameters description
1030 foreach ( $scriptSpecificParams as $par => $info ) {
1031 if ( $info['shortName'] !== false ) {
1032 $par .= " (-{$info['shortName']})";
1035 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1036 "\n$tab$tab" ) . "\n"
1039 $this->output( "\n" );
1043 if ( count( $this->mArgList
) > 0 ) {
1044 $this->output( "Arguments:\n" );
1045 // Arguments description
1046 foreach ( $this->mArgList
as $info ) {
1047 $openChar = $info['require'] ?
'<' : '[';
1048 $closeChar = $info['require'] ?
'>' : ']';
1050 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1051 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1054 $this->output( "\n" );
1061 * Handle some last-minute setup here.
1063 public function finalSetup() {
1064 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1065 global $wgDBadminuser, $wgDBadminpassword;
1066 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1068 # Turn off output buffering again, it might have been turned on in the settings files
1069 if ( ob_get_level() ) {
1073 $wgCommandLineMode = true;
1075 # Override $wgServer
1076 if ( $this->hasOption( 'server' ) ) {
1077 $wgServer = $this->getOption( 'server', $wgServer );
1080 # If these were passed, use them
1081 if ( $this->mDbUser
) {
1082 $wgDBadminuser = $this->mDbUser
;
1084 if ( $this->mDbPass
) {
1085 $wgDBadminpassword = $this->mDbPass
;
1088 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1089 $wgDBuser = $wgDBadminuser;
1090 $wgDBpassword = $wgDBadminpassword;
1092 if ( $wgDBservers ) {
1094 * @var $wgDBservers array
1096 foreach ( $wgDBservers as $i => $server ) {
1097 $wgDBservers[$i]['user'] = $wgDBuser;
1098 $wgDBservers[$i]['password'] = $wgDBpassword;
1101 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1102 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1103 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1105 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1108 // Per-script profiling; useful for debugging
1109 $this->activateProfiler();
1111 $this->afterFinalSetup();
1113 $wgShowSQLErrors = true;
1115 MediaWiki\
suppressWarnings();
1116 set_time_limit( 0 );
1117 MediaWiki\restoreWarnings
();
1119 $this->adjustMemoryLimit();
1123 * Execute a callback function at the end of initialisation
1125 protected function afterFinalSetup() {
1126 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1127 call_user_func( MW_CMDLINE_CALLBACK
);
1132 * Potentially debug globals. Originally a feature only
1135 public function globals() {
1136 if ( $this->hasOption( 'globals' ) ) {
1137 print_r( $GLOBALS );
1142 * Generic setup for most installs. Returns the location of LocalSettings
1145 public function loadSettings() {
1146 global $wgCommandLineMode, $IP;
1148 if ( isset( $this->mOptions
['conf'] ) ) {
1149 $settingsFile = $this->mOptions
['conf'];
1150 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1151 $settingsFile = MW_CONFIG_FILE
;
1153 $settingsFile = "$IP/LocalSettings.php";
1155 if ( isset( $this->mOptions
['wiki'] ) ) {
1156 $bits = explode( '-', $this->mOptions
['wiki'] );
1157 if ( count( $bits ) == 1 ) {
1160 define( 'MW_DB', $bits[0] );
1161 define( 'MW_PREFIX', $bits[1] );
1164 if ( !is_readable( $settingsFile ) ) {
1165 $this->error( "A copy of your installation's LocalSettings.php\n" .
1166 "must exist and be readable in the source directory.\n" .
1167 "Use --conf to specify it.", true );
1169 $wgCommandLineMode = true;
1171 return $settingsFile;
1175 * Support function for cleaning up redundant text records
1176 * @param bool $delete Whether or not to actually delete the records
1177 * @author Rob Church <robchur@gmail.com>
1179 public function purgeRedundantText( $delete = true ) {
1180 # Data should come off the master, wrapped in a transaction
1181 $dbw = $this->getDB( DB_MASTER
);
1182 $this->beginTransaction( $dbw, __METHOD__
);
1184 # Get "active" text records from the revisions table
1186 $this->output( 'Searching for active text records in revisions table...' );
1187 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1188 foreach ( $res as $row ) {
1189 $cur[] = $row->rev_text_id
;
1191 $this->output( "done.\n" );
1193 # Get "active" text records from the archive table
1194 $this->output( 'Searching for active text records in archive table...' );
1195 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1196 foreach ( $res as $row ) {
1197 # old pre-MW 1.5 records can have null ar_text_id's.
1198 if ( $row->ar_text_id
!== null ) {
1199 $cur[] = $row->ar_text_id
;
1202 $this->output( "done.\n" );
1204 # Get the IDs of all text records not in these sets
1205 $this->output( 'Searching for inactive text records...' );
1206 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1207 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1209 foreach ( $res as $row ) {
1210 $old[] = $row->old_id
;
1212 $this->output( "done.\n" );
1214 # Inform the user of what we're going to do
1215 $count = count( $old );
1216 $this->output( "$count inactive items found.\n" );
1218 # Delete as appropriate
1219 if ( $delete && $count ) {
1220 $this->output( 'Deleting...' );
1221 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1222 $this->output( "done.\n" );
1226 $this->commitTransaction( $dbw, __METHOD__
);
1230 * Get the maintenance directory.
1233 protected function getDir() {
1238 * Returns a database to be used by current maintenance script. It can be set by setDB().
1239 * If not set, wfGetDB() will be used.
1240 * This function has the same parameters as wfGetDB()
1242 * @param integer $db DB index (DB_REPLICA/DB_MASTER)
1243 * @param array $groups; default: empty array
1244 * @param string|bool $wiki; default: current wiki
1247 protected function getDB( $db, $groups = [], $wiki = false ) {
1248 if ( is_null( $this->mDb
) ) {
1249 return wfGetDB( $db, $groups, $wiki );
1256 * Sets database object to be returned by getDB().
1258 * @param IDatabase $db Database object to be used
1260 public function setDB( IDatabase
$db ) {
1265 * Begin a transcation on a DB
1267 * This method makes it clear that begin() is called from a maintenance script,
1268 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1270 * @param IDatabase $dbw
1271 * @param string $fname Caller name
1274 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1275 $dbw->begin( $fname );
1279 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1281 * This method makes it clear that commit() is called from a maintenance script,
1282 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1284 * @param IDatabase $dbw
1285 * @param string $fname Caller name
1286 * @return bool Whether the replica DB wait succeeded
1289 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1290 $dbw->commit( $fname );
1292 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1293 $lbFactory->waitForReplication(
1294 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1296 $this->lastReplicationWait
= microtime( true );
1299 } catch ( DBReplicationWaitError
$e ) {
1305 * Rollback the transcation on a DB handle
1307 * This method makes it clear that rollback() is called from a maintenance script,
1308 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1310 * @param IDatabase $dbw
1311 * @param string $fname Caller name
1314 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1315 $dbw->rollback( $fname );
1319 * Lock the search index
1320 * @param Database &$db
1322 private function lockSearchindex( $db ) {
1323 $write = [ 'searchindex' ];
1333 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1338 * @param Database &$db
1340 private function unlockSearchindex( $db ) {
1341 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1345 * Unlock and lock again
1346 * Since the lock is low-priority, queued reads will be able to complete
1347 * @param Database &$db
1349 private function relockSearchindex( $db ) {
1350 $this->unlockSearchindex( $db );
1351 $this->lockSearchindex( $db );
1355 * Perform a search index update with locking
1356 * @param int $maxLockTime The maximum time to keep the search index locked.
1357 * @param string $callback The function that will update the function.
1358 * @param Database $dbw
1359 * @param array $results
1361 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1365 if ( $maxLockTime ) {
1366 $this->output( " --- Waiting for lock ---" );
1367 $this->lockSearchindex( $dbw );
1369 $this->output( "\n" );
1372 # Loop through the results and do a search update
1373 foreach ( $results as $row ) {
1374 # Allow reads to be processed
1375 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1376 $this->output( " --- Relocking ---" );
1377 $this->relockSearchindex( $dbw );
1379 $this->output( "\n" );
1381 call_user_func( $callback, $dbw, $row );
1384 # Unlock searchindex
1385 if ( $maxLockTime ) {
1386 $this->output( " --- Unlocking --" );
1387 $this->unlockSearchindex( $dbw );
1388 $this->output( "\n" );
1393 * Update the searchindex table for a given pageid
1394 * @param Database $dbw A database write handle
1395 * @param int $pageId The page ID to update.
1396 * @return null|string
1398 public function updateSearchIndexForPage( $dbw, $pageId ) {
1399 // Get current revision
1400 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1403 $titleObj = $rev->getTitle();
1404 $title = $titleObj->getPrefixedDBkey();
1405 $this->output( "$title..." );
1406 # Update searchindex
1407 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1409 $this->output( "\n" );
1416 * Wrapper for posix_isatty()
1417 * We default as considering stdin a tty (for nice readline methods)
1418 * but treating stout as not a tty to avoid color codes
1420 * @param mixed $fd File descriptor
1423 public static function posix_isatty( $fd ) {
1424 if ( !function_exists( 'posix_isatty' ) ) {
1427 return posix_isatty( $fd );
1432 * Prompt the console for input
1433 * @param string $prompt What to begin the line with, like '> '
1434 * @return string Response
1436 public static function readconsole( $prompt = '> ' ) {
1437 static $isatty = null;
1438 if ( is_null( $isatty ) ) {
1439 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1442 if ( $isatty && function_exists( 'readline' ) ) {
1443 $resp = readline( $prompt );
1444 if ( $resp === null ) {
1445 // Workaround for https://github.com/facebook/hhvm/issues/4776
1452 $st = self
::readlineEmulation( $prompt );
1454 if ( feof( STDIN
) ) {
1457 $st = fgets( STDIN
, 1024 );
1460 if ( $st === false ) {
1463 $resp = trim( $st );
1470 * Emulate readline()
1471 * @param string $prompt What to begin the line with, like '> '
1474 private static function readlineEmulation( $prompt ) {
1475 $bash = Installer
::locateExecutableInDefaultPaths( [ 'bash' ] );
1476 if ( !wfIsWindows() && $bash ) {
1478 $encPrompt = wfEscapeShellArg( $prompt );
1479 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1480 $encCommand = wfEscapeShellArg( $command );
1481 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1483 if ( $retval == 0 ) {
1485 } elseif ( $retval == 127 ) {
1486 // Couldn't execute bash even though we thought we saw it.
1487 // Shell probably spit out an error message, sorry :(
1488 // Fall through to fgets()...
1495 // Fallback... we'll have no editing controls, EWWW
1496 if ( feof( STDIN
) ) {
1501 return fgets( STDIN
, 1024 );
1505 * Get the terminal size as a two-element array where the first element
1506 * is the width (number of columns) and the second element is the height
1511 public static function getTermSize() {
1512 $default = [ 80, 50 ];
1513 if ( wfIsWindows() ) {
1516 // It's possible to get the screen size with VT-100 terminal escapes,
1517 // but reading the responses is not possible without setting raw mode
1518 // (unless you want to require the user to press enter), and that
1519 // requires an ioctl(), which we can't do. So we have to shell out to
1520 // something that can do the relevant syscalls. There are a few
1521 // options. Linux and Mac OS X both have "stty size" which does the
1524 $size = wfShellExec( 'stty size', $retval );
1525 if ( $retval !== 0 ) {
1528 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1531 return [ intval( $m[2] ), intval( $m[1] ) ];
1535 * Call this to set up the autoloader to allow classes to be used from the
1538 public static function requireTestsAutoloader() {
1539 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1544 * Fake maintenance wrapper, mostly used for the web installer/updater
1546 class FakeMaintenance
extends Maintenance
{
1547 protected $mSelf = "FakeMaintenanceScript";
1549 public function execute() {
1555 * Class for scripts that perform database maintenance and want to log the
1556 * update in `updatelog` so we can later skip it
1558 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1559 public function __construct() {
1560 parent
::__construct();
1561 $this->addOption( 'force', 'Run the update even if it was completed already' );
1562 $this->setBatchSize( 200 );
1565 public function execute() {
1566 $db = $this->getDB( DB_MASTER
);
1567 $key = $this->getUpdateKey();
1569 if ( !$this->hasOption( 'force' )
1570 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1572 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1577 if ( !$this->doDBUpdates() ) {
1581 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1584 $this->output( $this->updatelogFailedMessage() . "\n" );
1591 * Message to show that the update was done already and was just skipped
1594 protected function updateSkippedMessage() {
1595 $key = $this->getUpdateKey();
1597 return "Update '{$key}' already logged as completed.";
1601 * Message to show that the update log was unable to log the completion of this update
1604 protected function updatelogFailedMessage() {
1605 $key = $this->getUpdateKey();
1607 return "Unable to log update '{$key}' as completed.";
1611 * Do the actual work. All child classes will need to implement this.
1612 * Return true to log the update as done or false (usually on failure).
1615 abstract protected function doDBUpdates();
1618 * Get the update key name to go in the update log table
1621 abstract protected function getUpdateKey();