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 Wikimedia\Rdbms\IDatabase
;
40 use MediaWiki\Logger\LoggerFactory
;
41 use MediaWiki\MediaWikiServices
;
42 use Wikimedia\Rdbms\LBFactory
;
43 use Wikimedia\Rdbms\IMaintainableDatabase
;
46 * Abstract maintenance class for quickly writing and churning out
47 * maintenance scripts with minimal effort. All that _must_ be defined
48 * is the execute() method. See docs/maintenance.txt for more info
49 * and a quick demo of how to use it.
51 * @author Chad Horohoe <chad@anyonecanedit.org>
53 * @ingroup Maintenance
55 abstract class Maintenance
{
57 * Constants for DB access type
58 * @see Maintenance::getDbType()
64 // Const for getStdin()
65 const STDIN_ALL
= 'all';
67 // This is the desired params
68 protected $mParams = [];
70 // Array of mapping short parameters to long ones
71 protected $mShortParamsMap = [];
73 // Array of desired args
74 protected $mArgList = [];
76 // This is the list of options that were actually passed
77 protected $mOptions = [];
79 // This is the list of arguments that were actually passed
80 protected $mArgs = [];
82 // Name of the script currently running
85 // Special vars for params that are always used
86 protected $mQuiet = false;
87 protected $mDbUser, $mDbPass;
89 // A description of the script, children should change this via addDescription()
90 protected $mDescription = '';
92 // Have we already loaded our user input?
93 protected $mInputLoaded = false;
96 * Batch size. If a script supports this, they should set
97 * a default with setBatchSize()
101 protected $mBatchSize = null;
103 // Generic options added by addDefaultParams()
104 private $mGenericParameters = [];
105 // Generic options which might or not be supported by the script
106 private $mDependantParameters = [];
109 * Used by getDB() / setDB()
110 * @var IMaintainableDatabase
114 /** @var float UNIX timestamp */
115 private $lastReplicationWait = 0.0;
118 * Used when creating separate schema files.
124 * Accessible via getConfig()
131 * @see Maintenance::requireExtension
134 private $requiredExtensions = [];
137 * Used to read the options in the order they were passed.
138 * Useful for option chaining (Ex. dumpBackup.php). It will
139 * be an empty array if the options are passed in through
140 * loadParamsAndArgs( $self, $opts, $args ).
142 * This is an array of arrays where
143 * 0 => the option and 1 => parameter value.
147 public $orderedOptions = [];
150 * Default constructor. Children should call this *first* if implementing
151 * their own constructors
153 public function __construct() {
154 // Setup $IP, using MW_INSTALL_PATH if it exists
156 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
157 ?
getenv( 'MW_INSTALL_PATH' )
158 : realpath( __DIR__
. '/..' );
160 $this->addDefaultParams();
161 register_shutdown_function( [ $this, 'outputChanneled' ], false );
165 * Should we execute the maintenance script, or just allow it to be included
166 * as a standalone class? It checks that the call stack only includes this
167 * function and "requires" (meaning was called from the file scope)
171 public static function shouldExecute() {
172 global $wgCommandLineMode;
174 if ( !function_exists( 'debug_backtrace' ) ) {
175 // If someone has a better idea...
176 return $wgCommandLineMode;
179 $bt = debug_backtrace();
180 $count = count( $bt );
182 return false; // sanity
184 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
185 return false; // last call should be to this function
187 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
188 for ( $i = 1; $i < $count; $i++
) {
189 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
190 return false; // previous calls should all be "requires"
198 * Do the actual work. All child classes will need to implement this
200 abstract public function execute();
203 * Add a parameter to the script. Will be displayed on --help
204 * with the associated description
206 * @param string $name The name of the param (help, version, etc)
207 * @param string $description The description of the param to show on --help
208 * @param bool $required Is the param required?
209 * @param bool $withArg Is an argument required with this option?
210 * @param string|bool $shortName Character to use as short name
211 * @param bool $multiOccurrence Can this option be passed multiple times?
213 protected function addOption( $name, $description, $required = false,
214 $withArg = false, $shortName = false, $multiOccurrence = false
216 $this->mParams
[$name] = [
217 'desc' => $description,
218 'require' => $required,
219 'withArg' => $withArg,
220 'shortName' => $shortName,
221 'multiOccurrence' => $multiOccurrence
224 if ( $shortName !== false ) {
225 $this->mShortParamsMap
[$shortName] = $name;
230 * Checks to see if a particular param exists.
231 * @param string $name The name of the param
234 protected function hasOption( $name ) {
235 return isset( $this->mOptions
[$name] );
239 * Get an option, or return the default.
241 * If the option was added to support multiple occurrences,
242 * this will return an array.
244 * @param string $name The name of the param
245 * @param mixed $default Anything you want, default null
248 protected function getOption( $name, $default = null ) {
249 if ( $this->hasOption( $name ) ) {
250 return $this->mOptions
[$name];
252 // Set it so we don't have to provide the default again
253 $this->mOptions
[$name] = $default;
255 return $this->mOptions
[$name];
260 * Add some args that are needed
261 * @param string $arg Name of the arg, like 'start'
262 * @param string $description Short description of the arg
263 * @param bool $required Is this required?
265 protected function addArg( $arg, $description, $required = true ) {
266 $this->mArgList
[] = [
268 'desc' => $description,
269 'require' => $required
274 * Remove an option. Useful for removing options that won't be used in your script.
275 * @param string $name The option to remove.
277 protected function deleteOption( $name ) {
278 unset( $this->mParams
[$name] );
282 * Set the description text.
283 * @param string $text The text of the description
285 protected function addDescription( $text ) {
286 $this->mDescription
= $text;
290 * Does a given argument exist?
291 * @param int $argId The integer value (from zero) for the arg
294 protected function hasArg( $argId = 0 ) {
295 return isset( $this->mArgs
[$argId] );
300 * @param int $argId The integer value (from zero) for the arg
301 * @param mixed $default The default if it doesn't exist
304 protected function getArg( $argId = 0, $default = null ) {
305 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
309 * Set the batch size.
310 * @param int $s The number of operations to do in a batch
312 protected function setBatchSize( $s = 0 ) {
313 $this->mBatchSize
= $s;
315 // If we support $mBatchSize, show the option.
316 // Used to be in addDefaultParams, but in order for that to
317 // work, subclasses would have to call this function in the constructor
318 // before they called parent::__construct which is just weird
319 // (and really wasn't done).
320 if ( $this->mBatchSize
) {
321 $this->addOption( 'batch-size', 'Run this many operations ' .
322 'per batch, default: ' . $this->mBatchSize
, false, true );
323 if ( isset( $this->mParams
['batch-size'] ) ) {
324 // This seems a little ugly...
325 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
331 * Get the script's name
334 public function getName() {
339 * Return input from stdin.
340 * @param int $len The number of bytes to read. If null, just return the handle.
341 * Maintenance::STDIN_ALL returns the full length
344 protected function getStdin( $len = null ) {
345 if ( $len == Maintenance
::STDIN_ALL
) {
346 return file_get_contents( 'php://stdin' );
348 $f = fopen( 'php://stdin', 'rt' );
352 $input = fgets( $f, $len );
355 return rtrim( $input );
361 public function isQuiet() {
362 return $this->mQuiet
;
366 * Throw some output to the user. Scripts can call this with no fears,
367 * as we handle all --quiet stuff here
368 * @param string $out The text to show to the user
369 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
371 protected function output( $out, $channel = null ) {
372 if ( $this->mQuiet
) {
375 if ( $channel === null ) {
376 $this->cleanupChanneled();
379 $out = preg_replace( '/\n\z/', '', $out );
380 $this->outputChanneled( $out, $channel );
385 * Throw an error to the user. Doesn't respect --quiet, so don't use
386 * this for non-error output
387 * @param string $err The error to display
388 * @param int $die If > 0, go ahead and die out using this int as the code
390 protected function error( $err, $die = 0 ) {
391 $this->outputChanneled( false );
392 if ( PHP_SAPI
== 'cli' ) {
393 fwrite( STDERR
, $err . "\n" );
397 $die = intval( $die );
403 private $atLineStart = true;
404 private $lastChannel = null;
407 * Clean up channeled output. Output a newline if necessary.
409 public function cleanupChanneled() {
410 if ( !$this->atLineStart
) {
412 $this->atLineStart
= true;
417 * Message outputter with channeled message support. Messages on the
418 * same channel are concatenated, but any intervening messages in another
419 * channel start a new line.
420 * @param string $msg The message without trailing newline
421 * @param string $channel Channel identifier or null for no
422 * channel. Channel comparison uses ===.
424 public function outputChanneled( $msg, $channel = null ) {
425 if ( $msg === false ) {
426 $this->cleanupChanneled();
431 // End the current line if necessary
432 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
438 $this->atLineStart
= false;
439 if ( $channel === null ) {
440 // For unchanneled messages, output trailing newline immediately
442 $this->atLineStart
= true;
444 $this->lastChannel
= $channel;
448 * Does the script need different DB access? By default, we give Maintenance
449 * scripts normal rights to the DB. Sometimes, a script needs admin rights
450 * access for a reason and sometimes they want no access. Subclasses should
451 * override and return one of the following values, as needed:
452 * Maintenance::DB_NONE - For no DB access at all
453 * Maintenance::DB_STD - For normal DB access, default
454 * Maintenance::DB_ADMIN - For admin DB access
457 public function getDbType() {
458 return Maintenance
::DB_STD
;
462 * Add the default parameters to the scripts
464 protected function addDefaultParams() {
465 # Generic (non script dependant) options:
467 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
468 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
469 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
470 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
471 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
474 'Set a specific memory limit for the script, '
475 . '"max" for no limit or "default" to avoid changing it'
477 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
478 "http://en.wikipedia.org. This is sometimes necessary because " .
479 "server name detection may fail in command line scripts.", false, true );
480 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
482 # Save generic options to display them separately in help
483 $this->mGenericParameters
= $this->mParams
;
485 # Script dependant options:
487 // If we support a DB, show the options
488 if ( $this->getDbType() > 0 ) {
489 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
490 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
493 # Save additional script dependant options to display
494 # Â them separately in help
495 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
502 public function getConfig() {
503 if ( $this->config
=== null ) {
504 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
507 return $this->config
;
512 * @param Config $config
514 public function setConfig( Config
$config ) {
515 $this->config
= $config;
519 * Indicate that the specified extension must be
520 * loaded before the script can run.
522 * This *must* be called in the constructor.
525 * @param string $name
527 protected function requireExtension( $name ) {
528 $this->requiredExtensions
[] = $name;
532 * Verify that the required extensions are installed
536 public function checkRequiredExtensions() {
537 $registry = ExtensionRegistry
::getInstance();
539 foreach ( $this->requiredExtensions
as $name ) {
540 if ( !$registry->isLoaded( $name ) ) {
546 $joined = implode( ', ', $missing );
547 $msg = "The following extensions are required to be installed "
548 . "for this script to run: $joined. Please enable them and then try again.";
549 $this->error( $msg, 1 );
554 * Set triggers like when to try to run deferred updates
557 public function setAgentAndTriggers() {
558 if ( function_exists( 'posix_getpwuid' ) ) {
559 $agent = posix_getpwuid( posix_geteuid() )['name'];
563 $agent .= '@' . wfHostname();
565 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
566 // Add a comment for easy SHOW PROCESSLIST interpretation
567 $lbFactory->setAgentName(
568 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
570 self
::setLBFactoryTriggers( $lbFactory );
574 * @param LBFactory $LBFactory
577 public static function setLBFactoryTriggers( LBFactory
$LBFactory ) {
578 // Hook into period lag checks which often happen in long-running scripts
579 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
580 $lbFactory->setWaitForReplicationListener(
583 global $wgCommandLineMode;
584 // Check config in case of JobRunner and unit tests
585 if ( $wgCommandLineMode ) {
586 DeferredUpdates
::tryOpportunisticExecute( 'run' );
590 // Check for other windows to run them. A script may read or do a few writes
591 // to the master but mostly be writing to something else, like a file store.
592 $lbFactory->getMainLB()->setTransactionListener(
594 function ( $trigger ) {
595 global $wgCommandLineMode;
596 // Check config in case of JobRunner and unit tests
597 if ( $wgCommandLineMode && $trigger === IDatabase
::TRIGGER_COMMIT
) {
598 DeferredUpdates
::tryOpportunisticExecute( 'run' );
605 * Run a child maintenance script. Pass all of the current arguments
607 * @param string $maintClass A name of a child maintenance class
608 * @param string $classFile Full path of where the child is
609 * @return Maintenance
611 public function runChild( $maintClass, $classFile = null ) {
612 // Make sure the class is loaded first
613 if ( !class_exists( $maintClass ) ) {
615 require_once $classFile;
617 if ( !class_exists( $maintClass ) ) {
618 $this->error( "Cannot spawn child: $maintClass" );
623 * @var $child Maintenance
625 $child = new $maintClass();
626 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
627 if ( !is_null( $this->mDb
) ) {
628 $child->setDB( $this->mDb
);
635 * Do some sanity checking and basic setup
637 public function setup() {
638 global $IP, $wgCommandLineMode, $wgRequestTime;
640 # Abort if called from a web server
641 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
642 $this->error( 'This script must be run from the command line', true );
645 if ( $IP === null ) {
646 $this->error( "\$IP not set, aborting!\n" .
647 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
650 # Make sure we can handle script parameters
651 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
652 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
655 // Send PHP warnings and errors to stderr instead of stdout.
656 // This aids in diagnosing problems, while keeping messages
657 // out of redirected output.
658 if ( ini_get( 'display_errors' ) ) {
659 ini_set( 'display_errors', 'stderr' );
662 $this->loadParamsAndArgs();
665 # Set the memory limit
666 # Note we need to set it again later in cache LocalSettings changed it
667 $this->adjustMemoryLimit();
669 # Set max execution time to 0 (no limit). PHP.net says that
670 # "When running PHP from the command line the default setting is 0."
671 # But sometimes this doesn't seem to be the case.
672 ini_set( 'max_execution_time', 0 );
674 $wgRequestTime = microtime( true );
676 # Define us as being in MediaWiki
677 define( 'MEDIAWIKI', true );
679 $wgCommandLineMode = true;
681 # Turn off output buffering if it's on
682 while ( ob_get_level() > 0 ) {
686 $this->validateParamsAndArgs();
690 * Normally we disable the memory_limit when running admin scripts.
691 * Some scripts may wish to actually set a limit, however, to avoid
692 * blowing up unexpectedly. We also support a --memory-limit option,
693 * to allow sysadmins to explicitly set one if they'd prefer to override
694 * defaults (or for people using Suhosin which yells at you for trying
695 * to disable the limits)
698 public function memoryLimit() {
699 $limit = $this->getOption( 'memory-limit', 'max' );
700 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
705 * Adjusts PHP's memory limit to better suit our needs, if needed.
707 protected function adjustMemoryLimit() {
708 $limit = $this->memoryLimit();
709 if ( $limit == 'max' ) {
710 $limit = -1; // no memory limit
712 if ( $limit != 'default' ) {
713 ini_set( 'memory_limit', $limit );
718 * Activate the profiler (assuming $wgProfiler is set)
720 protected function activateProfiler() {
721 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
723 $output = $this->getOption( 'profiler' );
728 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
729 $class = $wgProfiler['class'];
730 /** @var Profiler $profiler */
731 $profiler = new $class(
732 [ 'sampling' => 1, 'output' => [ $output ] ]
734 +
[ 'threshold' => $wgProfileLimit ]
736 $profiler->setTemplated( true );
737 Profiler
::replaceStubInstance( $profiler );
740 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
741 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
742 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
746 * Clear all params and arguments.
748 public function clearParamsAndArgs() {
749 $this->mOptions
= [];
751 $this->mInputLoaded
= false;
755 * Load params and arguments from a given array
756 * of command-line arguments
761 public function loadWithArgv( $argv ) {
764 $this->orderedOptions
= [];
767 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
768 if ( $arg == '--' ) {
769 # End of options, remainder should be considered arguments
770 $arg = next( $argv );
771 while ( $arg !== false ) {
773 $arg = next( $argv );
776 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
778 $option = substr( $arg, 2 );
779 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
780 $param = next( $argv );
781 if ( $param === false ) {
782 $this->error( "\nERROR: $option parameter needs a value after it\n" );
783 $this->maybeHelp( true );
786 $this->setParam( $options, $option, $param );
788 $bits = explode( '=', $option, 2 );
789 if ( count( $bits ) > 1 ) {
796 $this->setParam( $options, $option, $param );
798 } elseif ( $arg == '-' ) {
799 # Lonely "-", often used to indicate stdin or stdout.
801 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
803 $argLength = strlen( $arg );
804 for ( $p = 1; $p < $argLength; $p++
) {
806 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
807 $option = $this->mShortParamsMap
[$option];
810 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
811 $param = next( $argv );
812 if ( $param === false ) {
813 $this->error( "\nERROR: $option parameter needs a value after it\n" );
814 $this->maybeHelp( true );
816 $this->setParam( $options, $option, $param );
818 $this->setParam( $options, $option, 1 );
826 $this->mOptions
= $options;
827 $this->mArgs
= $args;
828 $this->loadSpecialVars();
829 $this->mInputLoaded
= true;
833 * Helper function used solely by loadParamsAndArgs
834 * to prevent code duplication
836 * This sets the param in the options array based on
837 * whether or not it can be specified multiple times.
840 * @param array $options
841 * @param string $option
842 * @param mixed $value
844 private function setParam( &$options, $option, $value ) {
845 $this->orderedOptions
[] = [ $option, $value ];
847 if ( isset( $this->mParams
[$option] ) ) {
848 $multi = $this->mParams
[$option]['multiOccurrence'];
852 $exists = array_key_exists( $option, $options );
853 if ( $multi && $exists ) {
854 $options[$option][] = $value;
855 } elseif ( $multi ) {
856 $options[$option] = [ $value ];
857 } elseif ( !$exists ) {
858 $options[$option] = $value;
860 $this->error( "\nERROR: $option parameter given twice\n" );
861 $this->maybeHelp( true );
866 * Process command line arguments
867 * $mOptions becomes an array with keys set to the option names
868 * $mArgs becomes a zero-based array containing the non-option arguments
870 * @param string $self The name of the script, if any
871 * @param array $opts An array of options, in form of key=>value
872 * @param array $args An array of command line arguments
874 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
875 # If we were given opts or args, set those and return early
877 $this->mSelf
= $self;
878 $this->mInputLoaded
= true;
881 $this->mOptions
= $opts;
882 $this->mInputLoaded
= true;
885 $this->mArgs
= $args;
886 $this->mInputLoaded
= true;
889 # If we've already loaded input (either by user values or from $argv)
890 # skip on loading it again. The array_shift() will corrupt values if
891 # it's run again and again
892 if ( $this->mInputLoaded
) {
893 $this->loadSpecialVars();
899 $this->mSelf
= $argv[0];
900 $this->loadWithArgv( array_slice( $argv, 1 ) );
904 * Run some validation checks on the params, etc
906 protected function validateParamsAndArgs() {
908 # Check to make sure we've got all the required options
909 foreach ( $this->mParams
as $opt => $info ) {
910 if ( $info['require'] && !$this->hasOption( $opt ) ) {
911 $this->error( "Param $opt required!" );
916 foreach ( $this->mArgList
as $k => $info ) {
917 if ( $info['require'] && !$this->hasArg( $k ) ) {
918 $this->error( 'Argument <' . $info['name'] . '> required!' );
924 $this->maybeHelp( true );
929 * Handle the special variables that are global to all scripts
931 protected function loadSpecialVars() {
932 if ( $this->hasOption( 'dbuser' ) ) {
933 $this->mDbUser
= $this->getOption( 'dbuser' );
935 if ( $this->hasOption( 'dbpass' ) ) {
936 $this->mDbPass
= $this->getOption( 'dbpass' );
938 if ( $this->hasOption( 'quiet' ) ) {
939 $this->mQuiet
= true;
941 if ( $this->hasOption( 'batch-size' ) ) {
942 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
947 * Maybe show the help.
948 * @param bool $force Whether to force the help to show, default false
950 protected function maybeHelp( $force = false ) {
951 if ( !$force && !$this->hasOption( 'help' ) ) {
955 $screenWidth = 80; // TODO: Calculate this!
957 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
959 ksort( $this->mParams
);
960 $this->mQuiet
= false;
963 if ( $this->mDescription
) {
964 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
966 $output = "\nUsage: php " . basename( $this->mSelf
);
968 // ... append parameters ...
969 if ( $this->mParams
) {
970 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
973 // ... and append arguments.
974 if ( $this->mArgList
) {
976 foreach ( $this->mArgList
as $k => $arg ) {
977 if ( $arg['require'] ) {
978 $output .= '<' . $arg['name'] . '>';
980 $output .= '[' . $arg['name'] . ']';
982 if ( $k < count( $this->mArgList
) - 1 ) {
987 $this->output( "$output\n\n" );
989 # TODO abstract some repetitive code below
991 // Generic parameters
992 $this->output( "Generic maintenance parameters:\n" );
993 foreach ( $this->mGenericParameters
as $par => $info ) {
994 if ( $info['shortName'] !== false ) {
995 $par .= " (-{$info['shortName']})";
998 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
999 "\n$tab$tab" ) . "\n"
1002 $this->output( "\n" );
1004 $scriptDependantParams = $this->mDependantParameters
;
1005 if ( count( $scriptDependantParams ) > 0 ) {
1006 $this->output( "Script dependant parameters:\n" );
1007 // Parameters description
1008 foreach ( $scriptDependantParams as $par => $info ) {
1009 if ( $info['shortName'] !== false ) {
1010 $par .= " (-{$info['shortName']})";
1013 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1014 "\n$tab$tab" ) . "\n"
1017 $this->output( "\n" );
1020 // Script specific parameters not defined on construction by
1021 // Maintenance::addDefaultParams()
1022 $scriptSpecificParams = array_diff_key(
1023 # all script parameters:
1025 # remove the Maintenance default parameters:
1026 $this->mGenericParameters
,
1027 $this->mDependantParameters
1029 if ( count( $scriptSpecificParams ) > 0 ) {
1030 $this->output( "Script specific parameters:\n" );
1031 // Parameters description
1032 foreach ( $scriptSpecificParams as $par => $info ) {
1033 if ( $info['shortName'] !== false ) {
1034 $par .= " (-{$info['shortName']})";
1037 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1038 "\n$tab$tab" ) . "\n"
1041 $this->output( "\n" );
1045 if ( count( $this->mArgList
) > 0 ) {
1046 $this->output( "Arguments:\n" );
1047 // Arguments description
1048 foreach ( $this->mArgList
as $info ) {
1049 $openChar = $info['require'] ?
'<' : '[';
1050 $closeChar = $info['require'] ?
'>' : ']';
1052 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1053 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1056 $this->output( "\n" );
1063 * Handle some last-minute setup here.
1065 public function finalSetup() {
1066 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1067 global $wgDBadminuser, $wgDBadminpassword;
1068 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1070 # Turn off output buffering again, it might have been turned on in the settings files
1071 if ( ob_get_level() ) {
1075 $wgCommandLineMode = true;
1077 # Override $wgServer
1078 if ( $this->hasOption( 'server' ) ) {
1079 $wgServer = $this->getOption( 'server', $wgServer );
1082 # If these were passed, use them
1083 if ( $this->mDbUser
) {
1084 $wgDBadminuser = $this->mDbUser
;
1086 if ( $this->mDbPass
) {
1087 $wgDBadminpassword = $this->mDbPass
;
1090 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1091 $wgDBuser = $wgDBadminuser;
1092 $wgDBpassword = $wgDBadminpassword;
1094 if ( $wgDBservers ) {
1096 * @var $wgDBservers array
1098 foreach ( $wgDBservers as $i => $server ) {
1099 $wgDBservers[$i]['user'] = $wgDBuser;
1100 $wgDBservers[$i]['password'] = $wgDBpassword;
1103 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1104 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1105 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1107 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1110 // Per-script profiling; useful for debugging
1111 $this->activateProfiler();
1113 $this->afterFinalSetup();
1115 $wgShowSQLErrors = true;
1117 MediaWiki\
suppressWarnings();
1118 set_time_limit( 0 );
1119 MediaWiki\restoreWarnings
();
1121 $this->adjustMemoryLimit();
1125 * Execute a callback function at the end of initialisation
1127 protected function afterFinalSetup() {
1128 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1129 call_user_func( MW_CMDLINE_CALLBACK
);
1134 * Potentially debug globals. Originally a feature only
1137 public function globals() {
1138 if ( $this->hasOption( 'globals' ) ) {
1139 print_r( $GLOBALS );
1144 * Generic setup for most installs. Returns the location of LocalSettings
1147 public function loadSettings() {
1148 global $wgCommandLineMode, $IP;
1150 if ( isset( $this->mOptions
['conf'] ) ) {
1151 $settingsFile = $this->mOptions
['conf'];
1152 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1153 $settingsFile = MW_CONFIG_FILE
;
1155 $settingsFile = "$IP/LocalSettings.php";
1157 if ( isset( $this->mOptions
['wiki'] ) ) {
1158 $bits = explode( '-', $this->mOptions
['wiki'] );
1159 if ( count( $bits ) == 1 ) {
1162 define( 'MW_DB', $bits[0] );
1163 define( 'MW_PREFIX', $bits[1] );
1166 if ( !is_readable( $settingsFile ) ) {
1167 $this->error( "A copy of your installation's LocalSettings.php\n" .
1168 "must exist and be readable in the source directory.\n" .
1169 "Use --conf to specify it.", true );
1171 $wgCommandLineMode = true;
1173 return $settingsFile;
1177 * Support function for cleaning up redundant text records
1178 * @param bool $delete Whether or not to actually delete the records
1179 * @author Rob Church <robchur@gmail.com>
1181 public function purgeRedundantText( $delete = true ) {
1182 # Data should come off the master, wrapped in a transaction
1183 $dbw = $this->getDB( DB_MASTER
);
1184 $this->beginTransaction( $dbw, __METHOD__
);
1186 # Get "active" text records from the revisions table
1188 $this->output( 'Searching for active text records in revisions table...' );
1189 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1190 foreach ( $res as $row ) {
1191 $cur[] = $row->rev_text_id
;
1193 $this->output( "done.\n" );
1195 # Get "active" text records from the archive table
1196 $this->output( 'Searching for active text records in archive table...' );
1197 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1198 foreach ( $res as $row ) {
1199 # old pre-MW 1.5 records can have null ar_text_id's.
1200 if ( $row->ar_text_id
!== null ) {
1201 $cur[] = $row->ar_text_id
;
1204 $this->output( "done.\n" );
1206 # Get the IDs of all text records not in these sets
1207 $this->output( 'Searching for inactive text records...' );
1208 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1209 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1211 foreach ( $res as $row ) {
1212 $old[] = $row->old_id
;
1214 $this->output( "done.\n" );
1216 # Inform the user of what we're going to do
1217 $count = count( $old );
1218 $this->output( "$count inactive items found.\n" );
1220 # Delete as appropriate
1221 if ( $delete && $count ) {
1222 $this->output( 'Deleting...' );
1223 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1224 $this->output( "done.\n" );
1228 $this->commitTransaction( $dbw, __METHOD__
);
1232 * Get the maintenance directory.
1235 protected function getDir() {
1240 * Returns a database to be used by current maintenance script. It can be set by setDB().
1241 * If not set, wfGetDB() will be used.
1242 * This function has the same parameters as wfGetDB()
1244 * @param integer $db DB index (DB_REPLICA/DB_MASTER)
1245 * @param array $groups; default: empty array
1246 * @param string|bool $wiki; default: current wiki
1247 * @return IMaintainableDatabase
1249 protected function getDB( $db, $groups = [], $wiki = false ) {
1250 if ( is_null( $this->mDb
) ) {
1251 return wfGetDB( $db, $groups, $wiki );
1258 * Sets database object to be returned by getDB().
1260 * @param IDatabase $db
1262 public function setDB( IDatabase
$db ) {
1267 * Begin a transcation on a DB
1269 * This method makes it clear that begin() is called from a maintenance script,
1270 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1272 * @param IDatabase $dbw
1273 * @param string $fname Caller name
1276 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1277 $dbw->begin( $fname );
1281 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1283 * This method makes it clear that commit() is called from a maintenance script,
1284 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1286 * @param IDatabase $dbw
1287 * @param string $fname Caller name
1288 * @return bool Whether the replica DB wait succeeded
1291 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1292 $dbw->commit( $fname );
1294 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1295 $lbFactory->waitForReplication(
1296 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1298 $this->lastReplicationWait
= microtime( true );
1301 } catch ( DBReplicationWaitError
$e ) {
1307 * Rollback the transcation on a DB handle
1309 * This method makes it clear that rollback() is called from a maintenance script,
1310 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1312 * @param IDatabase $dbw
1313 * @param string $fname Caller name
1316 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1317 $dbw->rollback( $fname );
1321 * Lock the search index
1322 * @param IMaintainableDatabase &$db
1324 private function lockSearchindex( $db ) {
1325 $write = [ 'searchindex' ];
1335 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1340 * @param IMaintainableDatabase &$db
1342 private function unlockSearchindex( $db ) {
1343 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1347 * Unlock and lock again
1348 * Since the lock is low-priority, queued reads will be able to complete
1349 * @param IMaintainableDatabase &$db
1351 private function relockSearchindex( $db ) {
1352 $this->unlockSearchindex( $db );
1353 $this->lockSearchindex( $db );
1357 * Perform a search index update with locking
1358 * @param int $maxLockTime The maximum time to keep the search index locked.
1359 * @param string $callback The function that will update the function.
1360 * @param IMaintainableDatabase $dbw
1361 * @param array $results
1363 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1367 if ( $maxLockTime ) {
1368 $this->output( " --- Waiting for lock ---" );
1369 $this->lockSearchindex( $dbw );
1371 $this->output( "\n" );
1374 # Loop through the results and do a search update
1375 foreach ( $results as $row ) {
1376 # Allow reads to be processed
1377 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1378 $this->output( " --- Relocking ---" );
1379 $this->relockSearchindex( $dbw );
1381 $this->output( "\n" );
1383 call_user_func( $callback, $dbw, $row );
1386 # Unlock searchindex
1387 if ( $maxLockTime ) {
1388 $this->output( " --- Unlocking --" );
1389 $this->unlockSearchindex( $dbw );
1390 $this->output( "\n" );
1395 * Update the searchindex table for a given pageid
1396 * @param IDatabase $dbw A database write handle
1397 * @param int $pageId The page ID to update.
1398 * @return null|string
1400 public function updateSearchIndexForPage( $dbw, $pageId ) {
1401 // Get current revision
1402 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1405 $titleObj = $rev->getTitle();
1406 $title = $titleObj->getPrefixedDBkey();
1407 $this->output( "$title..." );
1408 # Update searchindex
1409 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1411 $this->output( "\n" );
1418 * Wrapper for posix_isatty()
1419 * We default as considering stdin a tty (for nice readline methods)
1420 * but treating stout as not a tty to avoid color codes
1422 * @param mixed $fd File descriptor
1425 public static function posix_isatty( $fd ) {
1426 if ( !function_exists( 'posix_isatty' ) ) {
1429 return posix_isatty( $fd );
1434 * Prompt the console for input
1435 * @param string $prompt What to begin the line with, like '> '
1436 * @return string Response
1438 public static function readconsole( $prompt = '> ' ) {
1439 static $isatty = null;
1440 if ( is_null( $isatty ) ) {
1441 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1444 if ( $isatty && function_exists( 'readline' ) ) {
1445 $resp = readline( $prompt );
1446 if ( $resp === null ) {
1447 // Workaround for https://github.com/facebook/hhvm/issues/4776
1454 $st = self
::readlineEmulation( $prompt );
1456 if ( feof( STDIN
) ) {
1459 $st = fgets( STDIN
, 1024 );
1462 if ( $st === false ) {
1465 $resp = trim( $st );
1472 * Emulate readline()
1473 * @param string $prompt What to begin the line with, like '> '
1476 private static function readlineEmulation( $prompt ) {
1477 $bash = Installer
::locateExecutableInDefaultPaths( [ 'bash' ] );
1478 if ( !wfIsWindows() && $bash ) {
1480 $encPrompt = wfEscapeShellArg( $prompt );
1481 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1482 $encCommand = wfEscapeShellArg( $command );
1483 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1485 if ( $retval == 0 ) {
1487 } elseif ( $retval == 127 ) {
1488 // Couldn't execute bash even though we thought we saw it.
1489 // Shell probably spit out an error message, sorry :(
1490 // Fall through to fgets()...
1497 // Fallback... we'll have no editing controls, EWWW
1498 if ( feof( STDIN
) ) {
1503 return fgets( STDIN
, 1024 );
1507 * Get the terminal size as a two-element array where the first element
1508 * is the width (number of columns) and the second element is the height
1513 public static function getTermSize() {
1514 $default = [ 80, 50 ];
1515 if ( wfIsWindows() ) {
1518 // It's possible to get the screen size with VT-100 terminal escapes,
1519 // but reading the responses is not possible without setting raw mode
1520 // (unless you want to require the user to press enter), and that
1521 // requires an ioctl(), which we can't do. So we have to shell out to
1522 // something that can do the relevant syscalls. There are a few
1523 // options. Linux and Mac OS X both have "stty size" which does the
1526 $size = wfShellExec( 'stty size', $retval );
1527 if ( $retval !== 0 ) {
1530 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1533 return [ intval( $m[2] ), intval( $m[1] ) ];
1537 * Call this to set up the autoloader to allow classes to be used from the
1540 public static function requireTestsAutoloader() {
1541 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1546 * Fake maintenance wrapper, mostly used for the web installer/updater
1548 class FakeMaintenance
extends Maintenance
{
1549 protected $mSelf = "FakeMaintenanceScript";
1551 public function execute() {
1557 * Class for scripts that perform database maintenance and want to log the
1558 * update in `updatelog` so we can later skip it
1560 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1561 public function __construct() {
1562 parent
::__construct();
1563 $this->addOption( 'force', 'Run the update even if it was completed already' );
1564 $this->setBatchSize( 200 );
1567 public function execute() {
1568 $db = $this->getDB( DB_MASTER
);
1569 $key = $this->getUpdateKey();
1571 if ( !$this->hasOption( 'force' )
1572 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1574 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1579 if ( !$this->doDBUpdates() ) {
1583 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1586 $this->output( $this->updatelogFailedMessage() . "\n" );
1593 * Message to show that the update was done already and was just skipped
1596 protected function updateSkippedMessage() {
1597 $key = $this->getUpdateKey();
1599 return "Update '{$key}' already logged as completed.";
1603 * Message to show that the update log was unable to log the completion of this update
1606 protected function updatelogFailedMessage() {
1607 $key = $this->getUpdateKey();
1609 return "Unable to log update '{$key}' as completed.";
1613 * Do the actual work. All child classes will need to implement this.
1614 * Return true to log the update as done or false (usually on failure).
1617 abstract protected function doDBUpdates();
1620 * Get the update key name to go in the update log table
1623 abstract protected function getUpdateKey();