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' );
28 use Wikimedia\Rdbms\DBReplicationWaitError
;
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' );
37 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
41 use Wikimedia\Rdbms\IDatabase
;
42 use MediaWiki\Logger\LoggerFactory
;
43 use MediaWiki\MediaWikiServices
;
44 use Wikimedia\Rdbms\LBFactory
;
45 use Wikimedia\Rdbms\IMaintainableDatabase
;
48 * Abstract maintenance class for quickly writing and churning out
49 * maintenance scripts with minimal effort. All that _must_ be defined
50 * is the execute() method. See docs/maintenance.txt for more info
51 * and a quick demo of how to use it.
53 * @author Chad Horohoe <chad@anyonecanedit.org>
55 * @ingroup Maintenance
57 abstract class Maintenance
{
59 * Constants for DB access type
60 * @see Maintenance::getDbType()
66 // Const for getStdin()
67 const STDIN_ALL
= 'all';
69 // This is the desired params
70 protected $mParams = [];
72 // Array of mapping short parameters to long ones
73 protected $mShortParamsMap = [];
75 // Array of desired args
76 protected $mArgList = [];
78 // This is the list of options that were actually passed
79 protected $mOptions = [];
81 // This is the list of arguments that were actually passed
82 protected $mArgs = [];
84 // Name of the script currently running
87 // Special vars for params that are always used
88 protected $mQuiet = false;
89 protected $mDbUser, $mDbPass;
91 // A description of the script, children should change this via addDescription()
92 protected $mDescription = '';
94 // Have we already loaded our user input?
95 protected $mInputLoaded = false;
98 * Batch size. If a script supports this, they should set
99 * a default with setBatchSize()
103 protected $mBatchSize = null;
105 // Generic options added by addDefaultParams()
106 private $mGenericParameters = [];
107 // Generic options which might or not be supported by the script
108 private $mDependantParameters = [];
111 * Used by getDB() / setDB()
112 * @var IMaintainableDatabase
116 /** @var float UNIX timestamp */
117 private $lastReplicationWait = 0.0;
120 * Used when creating separate schema files.
126 * Accessible via getConfig()
133 * @see Maintenance::requireExtension
136 private $requiredExtensions = [];
139 * Used to read the options in the order they were passed.
140 * Useful for option chaining (Ex. dumpBackup.php). It will
141 * be an empty array if the options are passed in through
142 * loadParamsAndArgs( $self, $opts, $args ).
144 * This is an array of arrays where
145 * 0 => the option and 1 => parameter value.
149 public $orderedOptions = [];
152 * Default constructor. Children should call this *first* if implementing
153 * their own constructors
155 public function __construct() {
156 // Setup $IP, using MW_INSTALL_PATH if it exists
158 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
159 ?
getenv( 'MW_INSTALL_PATH' )
160 : realpath( __DIR__
. '/..' );
162 $this->addDefaultParams();
163 register_shutdown_function( [ $this, 'outputChanneled' ], false );
167 * Should we execute the maintenance script, or just allow it to be included
168 * as a standalone class? It checks that the call stack only includes this
169 * function and "requires" (meaning was called from the file scope)
173 public static function shouldExecute() {
174 global $wgCommandLineMode;
176 if ( !function_exists( 'debug_backtrace' ) ) {
177 // If someone has a better idea...
178 return $wgCommandLineMode;
181 $bt = debug_backtrace();
182 $count = count( $bt );
184 return false; // sanity
186 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
187 return false; // last call should be to this function
189 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
190 for ( $i = 1; $i < $count; $i++
) {
191 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
192 return false; // previous calls should all be "requires"
200 * Do the actual work. All child classes will need to implement this
202 abstract public function execute();
205 * Add a parameter to the script. Will be displayed on --help
206 * with the associated description
208 * @param string $name The name of the param (help, version, etc)
209 * @param string $description The description of the param to show on --help
210 * @param bool $required Is the param required?
211 * @param bool $withArg Is an argument required with this option?
212 * @param string|bool $shortName Character to use as short name
213 * @param bool $multiOccurrence Can this option be passed multiple times?
215 protected function addOption( $name, $description, $required = false,
216 $withArg = false, $shortName = false, $multiOccurrence = false
218 $this->mParams
[$name] = [
219 'desc' => $description,
220 'require' => $required,
221 'withArg' => $withArg,
222 'shortName' => $shortName,
223 'multiOccurrence' => $multiOccurrence
226 if ( $shortName !== false ) {
227 $this->mShortParamsMap
[$shortName] = $name;
232 * Checks to see if a particular param exists.
233 * @param string $name The name of the param
236 protected function hasOption( $name ) {
237 return isset( $this->mOptions
[$name] );
241 * Get an option, or return the default.
243 * If the option was added to support multiple occurrences,
244 * this will return an array.
246 * @param string $name The name of the param
247 * @param mixed $default Anything you want, default null
250 protected function getOption( $name, $default = null ) {
251 if ( $this->hasOption( $name ) ) {
252 return $this->mOptions
[$name];
254 // Set it so we don't have to provide the default again
255 $this->mOptions
[$name] = $default;
257 return $this->mOptions
[$name];
262 * Add some args that are needed
263 * @param string $arg Name of the arg, like 'start'
264 * @param string $description Short description of the arg
265 * @param bool $required Is this required?
267 protected function addArg( $arg, $description, $required = true ) {
268 $this->mArgList
[] = [
270 'desc' => $description,
271 'require' => $required
276 * Remove an option. Useful for removing options that won't be used in your script.
277 * @param string $name The option to remove.
279 protected function deleteOption( $name ) {
280 unset( $this->mParams
[$name] );
284 * Set the description text.
285 * @param string $text The text of the description
287 protected function addDescription( $text ) {
288 $this->mDescription
= $text;
292 * Does a given argument exist?
293 * @param int $argId The integer value (from zero) for the arg
296 protected function hasArg( $argId = 0 ) {
297 return isset( $this->mArgs
[$argId] );
302 * @param int $argId The integer value (from zero) for the arg
303 * @param mixed $default The default if it doesn't exist
306 protected function getArg( $argId = 0, $default = null ) {
307 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
311 * Set the batch size.
312 * @param int $s The number of operations to do in a batch
314 protected function setBatchSize( $s = 0 ) {
315 $this->mBatchSize
= $s;
317 // If we support $mBatchSize, show the option.
318 // Used to be in addDefaultParams, but in order for that to
319 // work, subclasses would have to call this function in the constructor
320 // before they called parent::__construct which is just weird
321 // (and really wasn't done).
322 if ( $this->mBatchSize
) {
323 $this->addOption( 'batch-size', 'Run this many operations ' .
324 'per batch, default: ' . $this->mBatchSize
, false, true );
325 if ( isset( $this->mParams
['batch-size'] ) ) {
326 // This seems a little ugly...
327 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
333 * Get the script's name
336 public function getName() {
341 * Return input from stdin.
342 * @param int $len The number of bytes to read. If null, just return the handle.
343 * Maintenance::STDIN_ALL returns the full length
346 protected function getStdin( $len = null ) {
347 if ( $len == self
::STDIN_ALL
) {
348 return file_get_contents( 'php://stdin' );
350 $f = fopen( 'php://stdin', 'rt' );
354 $input = fgets( $f, $len );
357 return rtrim( $input );
363 public function isQuiet() {
364 return $this->mQuiet
;
368 * Throw some output to the user. Scripts can call this with no fears,
369 * as we handle all --quiet stuff here
370 * @param string $out The text to show to the user
371 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
373 protected function output( $out, $channel = null ) {
374 if ( $this->mQuiet
) {
377 if ( $channel === null ) {
378 $this->cleanupChanneled();
381 $out = preg_replace( '/\n\z/', '', $out );
382 $this->outputChanneled( $out, $channel );
387 * Throw an error to the user. Doesn't respect --quiet, so don't use
388 * this for non-error output
389 * @param string $err The error to display
390 * @param int $die If > 0, go ahead and die out using this int as the code
392 protected function error( $err, $die = 0 ) {
393 $this->outputChanneled( false );
394 if ( PHP_SAPI
== 'cli' ) {
395 fwrite( STDERR
, $err . "\n" );
399 $die = intval( $die );
405 private $atLineStart = true;
406 private $lastChannel = null;
409 * Clean up channeled output. Output a newline if necessary.
411 public function cleanupChanneled() {
412 if ( !$this->atLineStart
) {
414 $this->atLineStart
= true;
419 * Message outputter with channeled message support. Messages on the
420 * same channel are concatenated, but any intervening messages in another
421 * channel start a new line.
422 * @param string $msg The message without trailing newline
423 * @param string $channel Channel identifier or null for no
424 * channel. Channel comparison uses ===.
426 public function outputChanneled( $msg, $channel = null ) {
427 if ( $msg === false ) {
428 $this->cleanupChanneled();
433 // End the current line if necessary
434 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
440 $this->atLineStart
= false;
441 if ( $channel === null ) {
442 // For unchanneled messages, output trailing newline immediately
444 $this->atLineStart
= true;
446 $this->lastChannel
= $channel;
450 * Does the script need different DB access? By default, we give Maintenance
451 * scripts normal rights to the DB. Sometimes, a script needs admin rights
452 * access for a reason and sometimes they want no access. Subclasses should
453 * override and return one of the following values, as needed:
454 * Maintenance::DB_NONE - For no DB access at all
455 * Maintenance::DB_STD - For normal DB access, default
456 * Maintenance::DB_ADMIN - For admin DB access
459 public function getDbType() {
464 * Add the default parameters to the scripts
466 protected function addDefaultParams() {
467 # Generic (non script dependant) options:
469 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
470 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
471 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
472 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
473 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
476 'Set a specific memory limit for the script, '
477 . '"max" for no limit or "default" to avoid changing it'
479 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
480 "http://en.wikipedia.org. This is sometimes necessary because " .
481 "server name detection may fail in command line scripts.", false, true );
482 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
484 # Save generic options to display them separately in help
485 $this->mGenericParameters
= $this->mParams
;
487 # Script dependant options:
489 // If we support a DB, show the options
490 if ( $this->getDbType() > 0 ) {
491 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
492 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
495 # Save additional script dependant options to display
496 # Â them separately in help
497 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
504 public function getConfig() {
505 if ( $this->config
=== null ) {
506 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
509 return $this->config
;
514 * @param Config $config
516 public function setConfig( Config
$config ) {
517 $this->config
= $config;
521 * Indicate that the specified extension must be
522 * loaded before the script can run.
524 * This *must* be called in the constructor.
527 * @param string $name
529 protected function requireExtension( $name ) {
530 $this->requiredExtensions
[] = $name;
534 * Verify that the required extensions are installed
538 public function checkRequiredExtensions() {
539 $registry = ExtensionRegistry
::getInstance();
541 foreach ( $this->requiredExtensions
as $name ) {
542 if ( !$registry->isLoaded( $name ) ) {
548 $joined = implode( ', ', $missing );
549 $msg = "The following extensions are required to be installed "
550 . "for this script to run: $joined. Please enable them and then try again.";
551 $this->error( $msg, 1 );
556 * Set triggers like when to try to run deferred updates
559 public function setAgentAndTriggers() {
560 if ( function_exists( 'posix_getpwuid' ) ) {
561 $agent = posix_getpwuid( posix_geteuid() )['name'];
565 $agent .= '@' . wfHostname();
567 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
568 // Add a comment for easy SHOW PROCESSLIST interpretation
569 $lbFactory->setAgentName(
570 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
572 self
::setLBFactoryTriggers( $lbFactory );
576 * @param LBFactory $LBFactory
579 public static function setLBFactoryTriggers( LBFactory
$LBFactory ) {
580 // Hook into period lag checks which often happen in long-running scripts
581 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
582 $lbFactory->setWaitForReplicationListener(
585 global $wgCommandLineMode;
586 // Check config in case of JobRunner and unit tests
587 if ( $wgCommandLineMode ) {
588 DeferredUpdates
::tryOpportunisticExecute( 'run' );
592 // Check for other windows to run them. A script may read or do a few writes
593 // to the master but mostly be writing to something else, like a file store.
594 $lbFactory->getMainLB()->setTransactionListener(
596 function ( $trigger ) {
597 global $wgCommandLineMode;
598 // Check config in case of JobRunner and unit tests
599 if ( $wgCommandLineMode && $trigger === IDatabase
::TRIGGER_COMMIT
) {
600 DeferredUpdates
::tryOpportunisticExecute( 'run' );
607 * Run a child maintenance script. Pass all of the current arguments
609 * @param string $maintClass A name of a child maintenance class
610 * @param string $classFile Full path of where the child is
611 * @return Maintenance
613 public function runChild( $maintClass, $classFile = null ) {
614 // Make sure the class is loaded first
615 if ( !class_exists( $maintClass ) ) {
617 require_once $classFile;
619 if ( !class_exists( $maintClass ) ) {
620 $this->error( "Cannot spawn child: $maintClass" );
625 * @var $child Maintenance
627 $child = new $maintClass();
628 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
629 if ( !is_null( $this->mDb
) ) {
630 $child->setDB( $this->mDb
);
637 * Do some sanity checking and basic setup
639 public function setup() {
640 global $IP, $wgCommandLineMode, $wgRequestTime;
642 # Abort if called from a web server
643 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
644 $this->error( 'This script must be run from the command line', true );
647 if ( $IP === null ) {
648 $this->error( "\$IP not set, aborting!\n" .
649 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
652 # Make sure we can handle script parameters
653 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
654 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
657 // Send PHP warnings and errors to stderr instead of stdout.
658 // This aids in diagnosing problems, while keeping messages
659 // out of redirected output.
660 if ( ini_get( 'display_errors' ) ) {
661 ini_set( 'display_errors', 'stderr' );
664 $this->loadParamsAndArgs();
667 # Set the memory limit
668 # Note we need to set it again later in cache LocalSettings changed it
669 $this->adjustMemoryLimit();
671 # Set max execution time to 0 (no limit). PHP.net says that
672 # "When running PHP from the command line the default setting is 0."
673 # But sometimes this doesn't seem to be the case.
674 ini_set( 'max_execution_time', 0 );
676 $wgRequestTime = microtime( true );
678 # Define us as being in MediaWiki
679 define( 'MEDIAWIKI', true );
681 $wgCommandLineMode = true;
683 # Turn off output buffering if it's on
684 while ( ob_get_level() > 0 ) {
688 $this->validateParamsAndArgs();
692 * Normally we disable the memory_limit when running admin scripts.
693 * Some scripts may wish to actually set a limit, however, to avoid
694 * blowing up unexpectedly. We also support a --memory-limit option,
695 * to allow sysadmins to explicitly set one if they'd prefer to override
696 * defaults (or for people using Suhosin which yells at you for trying
697 * to disable the limits)
700 public function memoryLimit() {
701 $limit = $this->getOption( 'memory-limit', 'max' );
702 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
707 * Adjusts PHP's memory limit to better suit our needs, if needed.
709 protected function adjustMemoryLimit() {
710 $limit = $this->memoryLimit();
711 if ( $limit == 'max' ) {
712 $limit = -1; // no memory limit
714 if ( $limit != 'default' ) {
715 ini_set( 'memory_limit', $limit );
720 * Activate the profiler (assuming $wgProfiler is set)
722 protected function activateProfiler() {
723 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
725 $output = $this->getOption( 'profiler' );
730 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
731 $class = $wgProfiler['class'];
732 /** @var Profiler $profiler */
733 $profiler = new $class(
734 [ 'sampling' => 1, 'output' => [ $output ] ]
736 +
[ 'threshold' => $wgProfileLimit ]
738 $profiler->setTemplated( true );
739 Profiler
::replaceStubInstance( $profiler );
742 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
743 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
744 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
748 * Clear all params and arguments.
750 public function clearParamsAndArgs() {
751 $this->mOptions
= [];
753 $this->mInputLoaded
= false;
757 * Load params and arguments from a given array
758 * of command-line arguments
763 public function loadWithArgv( $argv ) {
766 $this->orderedOptions
= [];
769 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
770 if ( $arg == '--' ) {
771 # End of options, remainder should be considered arguments
772 $arg = next( $argv );
773 while ( $arg !== false ) {
775 $arg = next( $argv );
778 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
780 $option = substr( $arg, 2 );
781 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
782 $param = next( $argv );
783 if ( $param === false ) {
784 $this->error( "\nERROR: $option parameter needs a value after it\n" );
785 $this->maybeHelp( true );
788 $this->setParam( $options, $option, $param );
790 $bits = explode( '=', $option, 2 );
791 if ( count( $bits ) > 1 ) {
798 $this->setParam( $options, $option, $param );
800 } elseif ( $arg == '-' ) {
801 # Lonely "-", often used to indicate stdin or stdout.
803 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
805 $argLength = strlen( $arg );
806 for ( $p = 1; $p < $argLength; $p++
) {
808 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
809 $option = $this->mShortParamsMap
[$option];
812 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
813 $param = next( $argv );
814 if ( $param === false ) {
815 $this->error( "\nERROR: $option parameter needs a value after it\n" );
816 $this->maybeHelp( true );
818 $this->setParam( $options, $option, $param );
820 $this->setParam( $options, $option, 1 );
828 $this->mOptions
= $options;
829 $this->mArgs
= $args;
830 $this->loadSpecialVars();
831 $this->mInputLoaded
= true;
835 * Helper function used solely by loadParamsAndArgs
836 * to prevent code duplication
838 * This sets the param in the options array based on
839 * whether or not it can be specified multiple times.
842 * @param array $options
843 * @param string $option
844 * @param mixed $value
846 private function setParam( &$options, $option, $value ) {
847 $this->orderedOptions
[] = [ $option, $value ];
849 if ( isset( $this->mParams
[$option] ) ) {
850 $multi = $this->mParams
[$option]['multiOccurrence'];
854 $exists = array_key_exists( $option, $options );
855 if ( $multi && $exists ) {
856 $options[$option][] = $value;
857 } elseif ( $multi ) {
858 $options[$option] = [ $value ];
859 } elseif ( !$exists ) {
860 $options[$option] = $value;
862 $this->error( "\nERROR: $option parameter given twice\n" );
863 $this->maybeHelp( true );
868 * Process command line arguments
869 * $mOptions becomes an array with keys set to the option names
870 * $mArgs becomes a zero-based array containing the non-option arguments
872 * @param string $self The name of the script, if any
873 * @param array $opts An array of options, in form of key=>value
874 * @param array $args An array of command line arguments
876 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
877 # If we were given opts or args, set those and return early
879 $this->mSelf
= $self;
880 $this->mInputLoaded
= true;
883 $this->mOptions
= $opts;
884 $this->mInputLoaded
= true;
887 $this->mArgs
= $args;
888 $this->mInputLoaded
= true;
891 # If we've already loaded input (either by user values or from $argv)
892 # skip on loading it again. The array_shift() will corrupt values if
893 # it's run again and again
894 if ( $this->mInputLoaded
) {
895 $this->loadSpecialVars();
901 $this->mSelf
= $argv[0];
902 $this->loadWithArgv( array_slice( $argv, 1 ) );
906 * Run some validation checks on the params, etc
908 protected function validateParamsAndArgs() {
910 # Check to make sure we've got all the required options
911 foreach ( $this->mParams
as $opt => $info ) {
912 if ( $info['require'] && !$this->hasOption( $opt ) ) {
913 $this->error( "Param $opt required!" );
918 foreach ( $this->mArgList
as $k => $info ) {
919 if ( $info['require'] && !$this->hasArg( $k ) ) {
920 $this->error( 'Argument <' . $info['name'] . '> required!' );
926 $this->maybeHelp( true );
931 * Handle the special variables that are global to all scripts
933 protected function loadSpecialVars() {
934 if ( $this->hasOption( 'dbuser' ) ) {
935 $this->mDbUser
= $this->getOption( 'dbuser' );
937 if ( $this->hasOption( 'dbpass' ) ) {
938 $this->mDbPass
= $this->getOption( 'dbpass' );
940 if ( $this->hasOption( 'quiet' ) ) {
941 $this->mQuiet
= true;
943 if ( $this->hasOption( 'batch-size' ) ) {
944 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
949 * Maybe show the help.
950 * @param bool $force Whether to force the help to show, default false
952 protected function maybeHelp( $force = false ) {
953 if ( !$force && !$this->hasOption( 'help' ) ) {
957 $screenWidth = 80; // TODO: Calculate this!
959 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
961 ksort( $this->mParams
);
962 $this->mQuiet
= false;
965 if ( $this->mDescription
) {
966 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
968 $output = "\nUsage: php " . basename( $this->mSelf
);
970 // ... append parameters ...
971 if ( $this->mParams
) {
972 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
975 // ... and append arguments.
976 if ( $this->mArgList
) {
978 foreach ( $this->mArgList
as $k => $arg ) {
979 if ( $arg['require'] ) {
980 $output .= '<' . $arg['name'] . '>';
982 $output .= '[' . $arg['name'] . ']';
984 if ( $k < count( $this->mArgList
) - 1 ) {
989 $this->output( "$output\n\n" );
991 # TODO abstract some repetitive code below
993 // Generic parameters
994 $this->output( "Generic maintenance parameters:\n" );
995 foreach ( $this->mGenericParameters
as $par => $info ) {
996 if ( $info['shortName'] !== false ) {
997 $par .= " (-{$info['shortName']})";
1000 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1001 "\n$tab$tab" ) . "\n"
1004 $this->output( "\n" );
1006 $scriptDependantParams = $this->mDependantParameters
;
1007 if ( count( $scriptDependantParams ) > 0 ) {
1008 $this->output( "Script dependant parameters:\n" );
1009 // Parameters description
1010 foreach ( $scriptDependantParams as $par => $info ) {
1011 if ( $info['shortName'] !== false ) {
1012 $par .= " (-{$info['shortName']})";
1015 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1016 "\n$tab$tab" ) . "\n"
1019 $this->output( "\n" );
1022 // Script specific parameters not defined on construction by
1023 // Maintenance::addDefaultParams()
1024 $scriptSpecificParams = array_diff_key(
1025 # all script parameters:
1027 # remove the Maintenance default parameters:
1028 $this->mGenericParameters
,
1029 $this->mDependantParameters
1031 if ( count( $scriptSpecificParams ) > 0 ) {
1032 $this->output( "Script specific parameters:\n" );
1033 // Parameters description
1034 foreach ( $scriptSpecificParams as $par => $info ) {
1035 if ( $info['shortName'] !== false ) {
1036 $par .= " (-{$info['shortName']})";
1039 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1040 "\n$tab$tab" ) . "\n"
1043 $this->output( "\n" );
1047 if ( count( $this->mArgList
) > 0 ) {
1048 $this->output( "Arguments:\n" );
1049 // Arguments description
1050 foreach ( $this->mArgList
as $info ) {
1051 $openChar = $info['require'] ?
'<' : '[';
1052 $closeChar = $info['require'] ?
'>' : ']';
1054 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1055 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1058 $this->output( "\n" );
1065 * Handle some last-minute setup here.
1067 public function finalSetup() {
1068 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1069 global $wgDBadminuser, $wgDBadminpassword;
1070 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1072 # Turn off output buffering again, it might have been turned on in the settings files
1073 if ( ob_get_level() ) {
1077 $wgCommandLineMode = true;
1079 # Override $wgServer
1080 if ( $this->hasOption( 'server' ) ) {
1081 $wgServer = $this->getOption( 'server', $wgServer );
1084 # If these were passed, use them
1085 if ( $this->mDbUser
) {
1086 $wgDBadminuser = $this->mDbUser
;
1088 if ( $this->mDbPass
) {
1089 $wgDBadminpassword = $this->mDbPass
;
1092 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1093 $wgDBuser = $wgDBadminuser;
1094 $wgDBpassword = $wgDBadminpassword;
1096 if ( $wgDBservers ) {
1098 * @var $wgDBservers array
1100 foreach ( $wgDBservers as $i => $server ) {
1101 $wgDBservers[$i]['user'] = $wgDBuser;
1102 $wgDBservers[$i]['password'] = $wgDBpassword;
1105 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1106 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1107 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1109 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1112 // Per-script profiling; useful for debugging
1113 $this->activateProfiler();
1115 $this->afterFinalSetup();
1117 $wgShowSQLErrors = true;
1119 MediaWiki\
suppressWarnings();
1120 set_time_limit( 0 );
1121 MediaWiki\restoreWarnings
();
1123 $this->adjustMemoryLimit();
1127 * Execute a callback function at the end of initialisation
1129 protected function afterFinalSetup() {
1130 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1131 call_user_func( MW_CMDLINE_CALLBACK
);
1136 * Potentially debug globals. Originally a feature only
1139 public function globals() {
1140 if ( $this->hasOption( 'globals' ) ) {
1141 print_r( $GLOBALS );
1146 * Generic setup for most installs. Returns the location of LocalSettings
1149 public function loadSettings() {
1150 global $wgCommandLineMode, $IP;
1152 if ( isset( $this->mOptions
['conf'] ) ) {
1153 $settingsFile = $this->mOptions
['conf'];
1154 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1155 $settingsFile = MW_CONFIG_FILE
;
1157 $settingsFile = "$IP/LocalSettings.php";
1159 if ( isset( $this->mOptions
['wiki'] ) ) {
1160 $bits = explode( '-', $this->mOptions
['wiki'] );
1161 if ( count( $bits ) == 1 ) {
1164 define( 'MW_DB', $bits[0] );
1165 define( 'MW_PREFIX', $bits[1] );
1168 if ( !is_readable( $settingsFile ) ) {
1169 $this->error( "A copy of your installation's LocalSettings.php\n" .
1170 "must exist and be readable in the source directory.\n" .
1171 "Use --conf to specify it.", true );
1173 $wgCommandLineMode = true;
1175 return $settingsFile;
1179 * Support function for cleaning up redundant text records
1180 * @param bool $delete Whether or not to actually delete the records
1181 * @author Rob Church <robchur@gmail.com>
1183 public function purgeRedundantText( $delete = true ) {
1184 # Data should come off the master, wrapped in a transaction
1185 $dbw = $this->getDB( DB_MASTER
);
1186 $this->beginTransaction( $dbw, __METHOD__
);
1188 # Get "active" text records from the revisions table
1190 $this->output( 'Searching for active text records in revisions table...' );
1191 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1192 foreach ( $res as $row ) {
1193 $cur[] = $row->rev_text_id
;
1195 $this->output( "done.\n" );
1197 # Get "active" text records from the archive table
1198 $this->output( 'Searching for active text records in archive table...' );
1199 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1200 foreach ( $res as $row ) {
1201 # old pre-MW 1.5 records can have null ar_text_id's.
1202 if ( $row->ar_text_id
!== null ) {
1203 $cur[] = $row->ar_text_id
;
1206 $this->output( "done.\n" );
1208 # Get the IDs of all text records not in these sets
1209 $this->output( 'Searching for inactive text records...' );
1210 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1211 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1213 foreach ( $res as $row ) {
1214 $old[] = $row->old_id
;
1216 $this->output( "done.\n" );
1218 # Inform the user of what we're going to do
1219 $count = count( $old );
1220 $this->output( "$count inactive items found.\n" );
1222 # Delete as appropriate
1223 if ( $delete && $count ) {
1224 $this->output( 'Deleting...' );
1225 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1226 $this->output( "done.\n" );
1230 $this->commitTransaction( $dbw, __METHOD__
);
1234 * Get the maintenance directory.
1237 protected function getDir() {
1242 * Returns a database to be used by current maintenance script. It can be set by setDB().
1243 * If not set, wfGetDB() will be used.
1244 * This function has the same parameters as wfGetDB()
1246 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1247 * @param array $groups default: empty array
1248 * @param string|bool $wiki default: current wiki
1249 * @return IMaintainableDatabase
1251 protected function getDB( $db, $groups = [], $wiki = false ) {
1252 if ( is_null( $this->mDb
) ) {
1253 return wfGetDB( $db, $groups, $wiki );
1260 * Sets database object to be returned by getDB().
1262 * @param IDatabase $db
1264 public function setDB( IDatabase
$db ) {
1269 * Begin a transcation on a DB
1271 * This method makes it clear that begin() is called from a maintenance script,
1272 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1274 * @param IDatabase $dbw
1275 * @param string $fname Caller name
1278 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1279 $dbw->begin( $fname );
1283 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1285 * This method makes it clear that commit() is called from a maintenance script,
1286 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1288 * @param IDatabase $dbw
1289 * @param string $fname Caller name
1290 * @return bool Whether the replica DB wait succeeded
1293 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1294 $dbw->commit( $fname );
1296 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1297 $lbFactory->waitForReplication(
1298 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1300 $this->lastReplicationWait
= microtime( true );
1303 } catch ( DBReplicationWaitError
$e ) {
1309 * Rollback the transcation on a DB handle
1311 * This method makes it clear that rollback() is called from a maintenance script,
1312 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1314 * @param IDatabase $dbw
1315 * @param string $fname Caller name
1318 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1319 $dbw->rollback( $fname );
1323 * Lock the search index
1324 * @param IMaintainableDatabase &$db
1326 private function lockSearchindex( $db ) {
1327 $write = [ 'searchindex' ];
1337 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1342 * @param IMaintainableDatabase &$db
1344 private function unlockSearchindex( $db ) {
1345 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1349 * Unlock and lock again
1350 * Since the lock is low-priority, queued reads will be able to complete
1351 * @param IMaintainableDatabase &$db
1353 private function relockSearchindex( $db ) {
1354 $this->unlockSearchindex( $db );
1355 $this->lockSearchindex( $db );
1359 * Perform a search index update with locking
1360 * @param int $maxLockTime The maximum time to keep the search index locked.
1361 * @param string $callback The function that will update the function.
1362 * @param IMaintainableDatabase $dbw
1363 * @param array $results
1365 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1369 if ( $maxLockTime ) {
1370 $this->output( " --- Waiting for lock ---" );
1371 $this->lockSearchindex( $dbw );
1373 $this->output( "\n" );
1376 # Loop through the results and do a search update
1377 foreach ( $results as $row ) {
1378 # Allow reads to be processed
1379 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1380 $this->output( " --- Relocking ---" );
1381 $this->relockSearchindex( $dbw );
1383 $this->output( "\n" );
1385 call_user_func( $callback, $dbw, $row );
1388 # Unlock searchindex
1389 if ( $maxLockTime ) {
1390 $this->output( " --- Unlocking --" );
1391 $this->unlockSearchindex( $dbw );
1392 $this->output( "\n" );
1397 * Update the searchindex table for a given pageid
1398 * @param IDatabase $dbw A database write handle
1399 * @param int $pageId The page ID to update.
1400 * @return null|string
1402 public function updateSearchIndexForPage( $dbw, $pageId ) {
1403 // Get current revision
1404 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1407 $titleObj = $rev->getTitle();
1408 $title = $titleObj->getPrefixedDBkey();
1409 $this->output( "$title..." );
1410 # Update searchindex
1411 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1413 $this->output( "\n" );
1420 * Count down from $seconds to zero on the terminal, with a one-second pause
1421 * between showing each number. If the maintenance script is in quiet mode,
1422 * this function does nothing.
1426 * @codeCoverageIgnore
1427 * @param int $seconds
1429 protected function countDown( $seconds ) {
1430 if ( $this->isQuiet() ) {
1433 for ( $i = $seconds; $i >= 0; $i-- ) {
1434 if ( $i != $seconds ) {
1435 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1437 $this->output( $i );
1442 $this->output( "\n" );
1446 * Wrapper for posix_isatty()
1447 * We default as considering stdin a tty (for nice readline methods)
1448 * but treating stout as not a tty to avoid color codes
1450 * @param mixed $fd File descriptor
1453 public static function posix_isatty( $fd ) {
1454 if ( !function_exists( 'posix_isatty' ) ) {
1457 return posix_isatty( $fd );
1462 * Prompt the console for input
1463 * @param string $prompt What to begin the line with, like '> '
1464 * @return string Response
1466 public static function readconsole( $prompt = '> ' ) {
1467 static $isatty = null;
1468 if ( is_null( $isatty ) ) {
1469 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1472 if ( $isatty && function_exists( 'readline' ) ) {
1473 $resp = readline( $prompt );
1474 if ( $resp === null ) {
1475 // Workaround for https://github.com/facebook/hhvm/issues/4776
1482 $st = self
::readlineEmulation( $prompt );
1484 if ( feof( STDIN
) ) {
1487 $st = fgets( STDIN
, 1024 );
1490 if ( $st === false ) {
1493 $resp = trim( $st );
1500 * Emulate readline()
1501 * @param string $prompt What to begin the line with, like '> '
1504 private static function readlineEmulation( $prompt ) {
1505 $bash = Installer
::locateExecutableInDefaultPaths( [ 'bash' ] );
1506 if ( !wfIsWindows() && $bash ) {
1508 $encPrompt = wfEscapeShellArg( $prompt );
1509 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1510 $encCommand = wfEscapeShellArg( $command );
1511 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1513 if ( $retval == 0 ) {
1515 } elseif ( $retval == 127 ) {
1516 // Couldn't execute bash even though we thought we saw it.
1517 // Shell probably spit out an error message, sorry :(
1518 // Fall through to fgets()...
1525 // Fallback... we'll have no editing controls, EWWW
1526 if ( feof( STDIN
) ) {
1531 return fgets( STDIN
, 1024 );
1535 * Get the terminal size as a two-element array where the first element
1536 * is the width (number of columns) and the second element is the height
1541 public static function getTermSize() {
1542 $default = [ 80, 50 ];
1543 if ( wfIsWindows() ) {
1546 // It's possible to get the screen size with VT-100 terminal escapes,
1547 // but reading the responses is not possible without setting raw mode
1548 // (unless you want to require the user to press enter), and that
1549 // requires an ioctl(), which we can't do. So we have to shell out to
1550 // something that can do the relevant syscalls. There are a few
1551 // options. Linux and Mac OS X both have "stty size" which does the
1554 $size = wfShellExec( 'stty size', $retval );
1555 if ( $retval !== 0 ) {
1558 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1561 return [ intval( $m[2] ), intval( $m[1] ) ];
1565 * Call this to set up the autoloader to allow classes to be used from the
1568 public static function requireTestsAutoloader() {
1569 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1574 * Fake maintenance wrapper, mostly used for the web installer/updater
1576 class FakeMaintenance
extends Maintenance
{
1577 protected $mSelf = "FakeMaintenanceScript";
1579 public function execute() {
1585 * Class for scripts that perform database maintenance and want to log the
1586 * update in `updatelog` so we can later skip it
1588 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1589 public function __construct() {
1590 parent
::__construct();
1591 $this->addOption( 'force', 'Run the update even if it was completed already' );
1592 $this->setBatchSize( 200 );
1595 public function execute() {
1596 $db = $this->getDB( DB_MASTER
);
1597 $key = $this->getUpdateKey();
1599 if ( !$this->hasOption( 'force' )
1600 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1602 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1607 if ( !$this->doDBUpdates() ) {
1611 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1614 $this->output( $this->updatelogFailedMessage() . "\n" );
1621 * Message to show that the update was done already and was just skipped
1624 protected function updateSkippedMessage() {
1625 $key = $this->getUpdateKey();
1627 return "Update '{$key}' already logged as completed.";
1631 * Message to show that the update log was unable to log the completion of this update
1634 protected function updatelogFailedMessage() {
1635 $key = $this->getUpdateKey();
1637 return "Unable to log update '{$key}' as completed.";
1641 * Do the actual work. All child classes will need to implement this.
1642 * Return true to log the update as done or false (usually on failure).
1645 abstract protected function doDBUpdates();
1648 * Get the update key name to go in the update log table
1651 abstract protected function getUpdateKey();