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
;
43 * Abstract maintenance class for quickly writing and churning out
44 * maintenance scripts with minimal effort. All that _must_ be defined
45 * is the execute() method. See docs/maintenance.txt for more info
46 * and a quick demo of how to use it.
48 * @author Chad Horohoe <chad@anyonecanedit.org>
50 * @ingroup Maintenance
52 abstract class Maintenance
{
54 * Constants for DB access type
55 * @see Maintenance::getDbType()
61 // Const for getStdin()
62 const STDIN_ALL
= 'all';
64 // This is the desired params
65 protected $mParams = [];
67 // Array of mapping short parameters to long ones
68 protected $mShortParamsMap = [];
70 // Array of desired args
71 protected $mArgList = [];
73 // This is the list of options that were actually passed
74 protected $mOptions = [];
76 // This is the list of arguments that were actually passed
77 protected $mArgs = [];
79 // Name of the script currently running
82 // Special vars for params that are always used
83 protected $mQuiet = false;
84 protected $mDbUser, $mDbPass;
86 // A description of the script, children should change this via addDescription()
87 protected $mDescription = '';
89 // Have we already loaded our user input?
90 protected $mInputLoaded = false;
93 * Batch size. If a script supports this, they should set
94 * a default with setBatchSize()
98 protected $mBatchSize = null;
100 // Generic options added by addDefaultParams()
101 private $mGenericParameters = [];
102 // Generic options which might or not be supported by the script
103 private $mDependantParameters = [];
106 * Used by getDB() / setDB()
111 /** @var float UNIX timestamp */
112 private $lastSlaveWait = 0.0;
115 * Used when creating separate schema files.
121 * Accessible via getConfig()
128 * @see Maintenance::requireExtension
131 private $requiredExtensions = [];
134 * Used to read the options in the order they were passed.
135 * Useful for option chaining (Ex. dumpBackup.php). It will
136 * be an empty array if the options are passed in through
137 * loadParamsAndArgs( $self, $opts, $args ).
139 * This is an array of arrays where
140 * 0 => the option and 1 => parameter value.
144 public $orderedOptions = [];
147 * Default constructor. Children should call this *first* if implementing
148 * their own constructors
150 public function __construct() {
151 // Setup $IP, using MW_INSTALL_PATH if it exists
153 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
154 ?
getenv( 'MW_INSTALL_PATH' )
155 : realpath( __DIR__
. '/..' );
157 $this->addDefaultParams();
158 register_shutdown_function( [ $this, 'outputChanneled' ], false );
162 * Should we execute the maintenance script, or just allow it to be included
163 * as a standalone class? It checks that the call stack only includes this
164 * function and "requires" (meaning was called from the file scope)
168 public static function shouldExecute() {
169 global $wgCommandLineMode;
171 if ( !function_exists( 'debug_backtrace' ) ) {
172 // If someone has a better idea...
173 return $wgCommandLineMode;
176 $bt = debug_backtrace();
177 $count = count( $bt );
179 return false; // sanity
181 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
182 return false; // last call should be to this function
184 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
185 for ( $i = 1; $i < $count; $i++
) {
186 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
187 return false; // previous calls should all be "requires"
195 * Do the actual work. All child classes will need to implement this
197 abstract public function execute();
200 * Add a parameter to the script. Will be displayed on --help
201 * with the associated description
203 * @param string $name The name of the param (help, version, etc)
204 * @param string $description The description of the param to show on --help
205 * @param bool $required Is the param required?
206 * @param bool $withArg Is an argument required with this option?
207 * @param string $shortName Character to use as short name
208 * @param bool $multiOccurrence Can this option be passed multiple times?
210 protected function addOption( $name, $description, $required = false,
211 $withArg = false, $shortName = false, $multiOccurrence = false
213 $this->mParams
[$name] = [
214 'desc' => $description,
215 'require' => $required,
216 'withArg' => $withArg,
217 'shortName' => $shortName,
218 'multiOccurrence' => $multiOccurrence
221 if ( $shortName !== false ) {
222 $this->mShortParamsMap
[$shortName] = $name;
227 * Checks to see if a particular param exists.
228 * @param string $name The name of the param
231 protected function hasOption( $name ) {
232 return isset( $this->mOptions
[$name] );
236 * Get an option, or return the default.
238 * If the option was added to support multiple occurrences,
239 * this will return an array.
241 * @param string $name The name of the param
242 * @param mixed $default Anything you want, default null
245 protected function getOption( $name, $default = null ) {
246 if ( $this->hasOption( $name ) ) {
247 return $this->mOptions
[$name];
249 // Set it so we don't have to provide the default again
250 $this->mOptions
[$name] = $default;
252 return $this->mOptions
[$name];
257 * Add some args that are needed
258 * @param string $arg Name of the arg, like 'start'
259 * @param string $description Short description of the arg
260 * @param bool $required Is this required?
262 protected function addArg( $arg, $description, $required = true ) {
263 $this->mArgList
[] = [
265 'desc' => $description,
266 'require' => $required
271 * Remove an option. Useful for removing options that won't be used in your script.
272 * @param string $name The option to remove.
274 protected function deleteOption( $name ) {
275 unset( $this->mParams
[$name] );
279 * Set the description text.
280 * @param string $text The text of the description
282 protected function addDescription( $text ) {
283 $this->mDescription
= $text;
287 * Does a given argument exist?
288 * @param int $argId The integer value (from zero) for the arg
291 protected function hasArg( $argId = 0 ) {
292 return isset( $this->mArgs
[$argId] );
297 * @param int $argId The integer value (from zero) for the arg
298 * @param mixed $default The default if it doesn't exist
301 protected function getArg( $argId = 0, $default = null ) {
302 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
306 * Set the batch size.
307 * @param int $s The number of operations to do in a batch
309 protected function setBatchSize( $s = 0 ) {
310 $this->mBatchSize
= $s;
312 // If we support $mBatchSize, show the option.
313 // Used to be in addDefaultParams, but in order for that to
314 // work, subclasses would have to call this function in the constructor
315 // before they called parent::__construct which is just weird
316 // (and really wasn't done).
317 if ( $this->mBatchSize
) {
318 $this->addOption( 'batch-size', 'Run this many operations ' .
319 'per batch, default: ' . $this->mBatchSize
, false, true );
320 if ( isset( $this->mParams
['batch-size'] ) ) {
321 // This seems a little ugly...
322 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
328 * Get the script's name
331 public function getName() {
336 * Return input from stdin.
337 * @param int $len The number of bytes to read. If null, just return the handle.
338 * Maintenance::STDIN_ALL returns the full length
341 protected function getStdin( $len = null ) {
342 if ( $len == Maintenance
::STDIN_ALL
) {
343 return file_get_contents( 'php://stdin' );
345 $f = fopen( 'php://stdin', 'rt' );
349 $input = fgets( $f, $len );
352 return rtrim( $input );
358 public function isQuiet() {
359 return $this->mQuiet
;
363 * Throw some output to the user. Scripts can call this with no fears,
364 * as we handle all --quiet stuff here
365 * @param string $out The text to show to the user
366 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
368 protected function output( $out, $channel = null ) {
369 if ( $this->mQuiet
) {
372 if ( $channel === null ) {
373 $this->cleanupChanneled();
376 $out = preg_replace( '/\n\z/', '', $out );
377 $this->outputChanneled( $out, $channel );
382 * Throw an error to the user. Doesn't respect --quiet, so don't use
383 * this for non-error output
384 * @param string $err The error to display
385 * @param int $die If > 0, go ahead and die out using this int as the code
387 protected function error( $err, $die = 0 ) {
388 $this->outputChanneled( false );
389 if ( PHP_SAPI
== 'cli' ) {
390 fwrite( STDERR
, $err . "\n" );
394 $die = intval( $die );
400 private $atLineStart = true;
401 private $lastChannel = null;
404 * Clean up channeled output. Output a newline if necessary.
406 public function cleanupChanneled() {
407 if ( !$this->atLineStart
) {
409 $this->atLineStart
= true;
414 * Message outputter with channeled message support. Messages on the
415 * same channel are concatenated, but any intervening messages in another
416 * channel start a new line.
417 * @param string $msg The message without trailing newline
418 * @param string $channel Channel identifier or null for no
419 * channel. Channel comparison uses ===.
421 public function outputChanneled( $msg, $channel = null ) {
422 if ( $msg === false ) {
423 $this->cleanupChanneled();
428 // End the current line if necessary
429 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
435 $this->atLineStart
= false;
436 if ( $channel === null ) {
437 // For unchanneled messages, output trailing newline immediately
439 $this->atLineStart
= true;
441 $this->lastChannel
= $channel;
445 * Does the script need different DB access? By default, we give Maintenance
446 * scripts normal rights to the DB. Sometimes, a script needs admin rights
447 * access for a reason and sometimes they want no access. Subclasses should
448 * override and return one of the following values, as needed:
449 * Maintenance::DB_NONE - For no DB access at all
450 * Maintenance::DB_STD - For normal DB access, default
451 * Maintenance::DB_ADMIN - For admin DB access
454 public function getDbType() {
455 return Maintenance
::DB_STD
;
459 * Add the default parameters to the scripts
461 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
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
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 );
553 * Set triggers like when to try to run deferred updates
556 public function setTriggers() {
557 // Hook into period lag checks which often happen in long-running scripts
558 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
559 $lbFactory->setWaitForReplicationListener(
561 [ 'DeferredUpdates', 'tryOpportunisticExecute' ]
566 * Run a child maintenance script. Pass all of the current arguments
568 * @param string $maintClass A name of a child maintenance class
569 * @param string $classFile Full path of where the child is
570 * @return Maintenance
572 public function runChild( $maintClass, $classFile = null ) {
573 // Make sure the class is loaded first
574 if ( !class_exists( $maintClass ) ) {
576 require_once $classFile;
578 if ( !class_exists( $maintClass ) ) {
579 $this->error( "Cannot spawn child: $maintClass" );
584 * @var $child Maintenance
586 $child = new $maintClass();
587 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
588 if ( !is_null( $this->mDb
) ) {
589 $child->setDB( $this->mDb
);
596 * Do some sanity checking and basic setup
598 public function setup() {
599 global $IP, $wgCommandLineMode, $wgRequestTime;
601 # Abort if called from a web server
602 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
603 $this->error( 'This script must be run from the command line', true );
606 if ( $IP === null ) {
607 $this->error( "\$IP not set, aborting!\n" .
608 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
611 # Make sure we can handle script parameters
612 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
613 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
616 // Send PHP warnings and errors to stderr instead of stdout.
617 // This aids in diagnosing problems, while keeping messages
618 // out of redirected output.
619 if ( ini_get( 'display_errors' ) ) {
620 ini_set( 'display_errors', 'stderr' );
623 $this->loadParamsAndArgs();
626 # Set the memory limit
627 # Note we need to set it again later in cache LocalSettings changed it
628 $this->adjustMemoryLimit();
630 # Set max execution time to 0 (no limit). PHP.net says that
631 # "When running PHP from the command line the default setting is 0."
632 # But sometimes this doesn't seem to be the case.
633 ini_set( 'max_execution_time', 0 );
635 $wgRequestTime = microtime( true );
637 # Define us as being in MediaWiki
638 define( 'MEDIAWIKI', true );
640 $wgCommandLineMode = true;
642 # Turn off output buffering if it's on
643 while ( ob_get_level() > 0 ) {
647 $this->validateParamsAndArgs();
651 * Normally we disable the memory_limit when running admin scripts.
652 * Some scripts may wish to actually set a limit, however, to avoid
653 * blowing up unexpectedly. We also support a --memory-limit option,
654 * to allow sysadmins to explicitly set one if they'd prefer to override
655 * defaults (or for people using Suhosin which yells at you for trying
656 * to disable the limits)
659 public function memoryLimit() {
660 $limit = $this->getOption( 'memory-limit', 'max' );
661 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
666 * Adjusts PHP's memory limit to better suit our needs, if needed.
668 protected function adjustMemoryLimit() {
669 $limit = $this->memoryLimit();
670 if ( $limit == 'max' ) {
671 $limit = -1; // no memory limit
673 if ( $limit != 'default' ) {
674 ini_set( 'memory_limit', $limit );
679 * Activate the profiler (assuming $wgProfiler is set)
681 protected function activateProfiler() {
682 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
684 $output = $this->getOption( 'profiler' );
689 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
690 $class = $wgProfiler['class'];
691 $profiler = new $class(
692 [ 'sampling' => 1, 'output' => [ $output ] ]
694 +
[ 'threshold' => $wgProfileLimit ]
696 $profiler->setTemplated( true );
697 Profiler
::replaceStubInstance( $profiler );
700 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
701 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
702 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
706 * Clear all params and arguments.
708 public function clearParamsAndArgs() {
709 $this->mOptions
= [];
711 $this->mInputLoaded
= false;
715 * Load params and arguments from a given array
716 * of command-line arguments
721 public function loadWithArgv( $argv ) {
724 $this->orderedOptions
= [];
727 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
728 if ( $arg == '--' ) {
729 # End of options, remainder should be considered arguments
730 $arg = next( $argv );
731 while ( $arg !== false ) {
733 $arg = next( $argv );
736 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
738 $option = substr( $arg, 2 );
739 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
740 $param = next( $argv );
741 if ( $param === false ) {
742 $this->error( "\nERROR: $option parameter needs a value after it\n" );
743 $this->maybeHelp( true );
746 $this->setParam( $options, $option, $param );
748 $bits = explode( '=', $option, 2 );
749 if ( count( $bits ) > 1 ) {
756 $this->setParam( $options, $option, $param );
758 } elseif ( $arg == '-' ) {
759 # Lonely "-", often used to indicate stdin or stdout.
761 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
763 $argLength = strlen( $arg );
764 for ( $p = 1; $p < $argLength; $p++
) {
766 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
767 $option = $this->mShortParamsMap
[$option];
770 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
771 $param = next( $argv );
772 if ( $param === false ) {
773 $this->error( "\nERROR: $option parameter needs a value after it\n" );
774 $this->maybeHelp( true );
776 $this->setParam( $options, $option, $param );
778 $this->setParam( $options, $option, 1 );
786 $this->mOptions
= $options;
787 $this->mArgs
= $args;
788 $this->loadSpecialVars();
789 $this->mInputLoaded
= true;
793 * Helper function used solely by loadParamsAndArgs
794 * to prevent code duplication
796 * This sets the param in the options array based on
797 * whether or not it can be specified multiple times.
800 * @param array $options
801 * @param string $option
802 * @param mixed $value
804 private function setParam( &$options, $option, $value ) {
805 $this->orderedOptions
[] = [ $option, $value ];
807 if ( isset( $this->mParams
[$option] ) ) {
808 $multi = $this->mParams
[$option]['multiOccurrence'];
812 $exists = array_key_exists( $option, $options );
813 if ( $multi && $exists ) {
814 $options[$option][] = $value;
815 } elseif ( $multi ) {
816 $options[$option] = [ $value ];
817 } elseif ( !$exists ) {
818 $options[$option] = $value;
820 $this->error( "\nERROR: $option parameter given twice\n" );
821 $this->maybeHelp( true );
826 * Process command line arguments
827 * $mOptions becomes an array with keys set to the option names
828 * $mArgs becomes a zero-based array containing the non-option arguments
830 * @param string $self The name of the script, if any
831 * @param array $opts An array of options, in form of key=>value
832 * @param array $args An array of command line arguments
834 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
835 # If we were given opts or args, set those and return early
837 $this->mSelf
= $self;
838 $this->mInputLoaded
= true;
841 $this->mOptions
= $opts;
842 $this->mInputLoaded
= true;
845 $this->mArgs
= $args;
846 $this->mInputLoaded
= true;
849 # If we've already loaded input (either by user values or from $argv)
850 # skip on loading it again. The array_shift() will corrupt values if
851 # it's run again and again
852 if ( $this->mInputLoaded
) {
853 $this->loadSpecialVars();
859 $this->mSelf
= $argv[0];
860 $this->loadWithArgv( array_slice( $argv, 1 ) );
864 * Run some validation checks on the params, etc
866 protected function validateParamsAndArgs() {
868 # Check to make sure we've got all the required options
869 foreach ( $this->mParams
as $opt => $info ) {
870 if ( $info['require'] && !$this->hasOption( $opt ) ) {
871 $this->error( "Param $opt required!" );
876 foreach ( $this->mArgList
as $k => $info ) {
877 if ( $info['require'] && !$this->hasArg( $k ) ) {
878 $this->error( 'Argument <' . $info['name'] . '> required!' );
884 $this->maybeHelp( true );
889 * Handle the special variables that are global to all scripts
891 protected function loadSpecialVars() {
892 if ( $this->hasOption( 'dbuser' ) ) {
893 $this->mDbUser
= $this->getOption( 'dbuser' );
895 if ( $this->hasOption( 'dbpass' ) ) {
896 $this->mDbPass
= $this->getOption( 'dbpass' );
898 if ( $this->hasOption( 'quiet' ) ) {
899 $this->mQuiet
= true;
901 if ( $this->hasOption( 'batch-size' ) ) {
902 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
907 * Maybe show the help.
908 * @param bool $force Whether to force the help to show, default false
910 protected function maybeHelp( $force = false ) {
911 if ( !$force && !$this->hasOption( 'help' ) ) {
915 $screenWidth = 80; // TODO: Calculate this!
917 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
919 ksort( $this->mParams
);
920 $this->mQuiet
= false;
923 if ( $this->mDescription
) {
924 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
926 $output = "\nUsage: php " . basename( $this->mSelf
);
928 // ... append parameters ...
929 if ( $this->mParams
) {
930 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
933 // ... and append arguments.
934 if ( $this->mArgList
) {
936 foreach ( $this->mArgList
as $k => $arg ) {
937 if ( $arg['require'] ) {
938 $output .= '<' . $arg['name'] . '>';
940 $output .= '[' . $arg['name'] . ']';
942 if ( $k < count( $this->mArgList
) - 1 ) {
947 $this->output( "$output\n\n" );
949 # TODO abstract some repetitive code below
951 // Generic parameters
952 $this->output( "Generic maintenance parameters:\n" );
953 foreach ( $this->mGenericParameters
as $par => $info ) {
954 if ( $info['shortName'] !== false ) {
955 $par .= " (-{$info['shortName']})";
958 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
959 "\n$tab$tab" ) . "\n"
962 $this->output( "\n" );
964 $scriptDependantParams = $this->mDependantParameters
;
965 if ( count( $scriptDependantParams ) > 0 ) {
966 $this->output( "Script dependant parameters:\n" );
967 // Parameters description
968 foreach ( $scriptDependantParams as $par => $info ) {
969 if ( $info['shortName'] !== false ) {
970 $par .= " (-{$info['shortName']})";
973 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
974 "\n$tab$tab" ) . "\n"
977 $this->output( "\n" );
980 // Script specific parameters not defined on construction by
981 // Maintenance::addDefaultParams()
982 $scriptSpecificParams = array_diff_key(
983 # all script parameters:
985 # remove the Maintenance default parameters:
986 $this->mGenericParameters
,
987 $this->mDependantParameters
989 if ( count( $scriptSpecificParams ) > 0 ) {
990 $this->output( "Script specific parameters:\n" );
991 // Parameters description
992 foreach ( $scriptSpecificParams as $par => $info ) {
993 if ( $info['shortName'] !== false ) {
994 $par .= " (-{$info['shortName']})";
997 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
998 "\n$tab$tab" ) . "\n"
1001 $this->output( "\n" );
1005 if ( count( $this->mArgList
) > 0 ) {
1006 $this->output( "Arguments:\n" );
1007 // Arguments description
1008 foreach ( $this->mArgList
as $info ) {
1009 $openChar = $info['require'] ?
'<' : '[';
1010 $closeChar = $info['require'] ?
'>' : ']';
1012 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1013 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1016 $this->output( "\n" );
1023 * Handle some last-minute setup here.
1025 public function finalSetup() {
1026 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1027 global $wgDBadminuser, $wgDBadminpassword;
1028 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1030 # Turn off output buffering again, it might have been turned on in the settings files
1031 if ( ob_get_level() ) {
1035 $wgCommandLineMode = true;
1037 # Override $wgServer
1038 if ( $this->hasOption( 'server' ) ) {
1039 $wgServer = $this->getOption( 'server', $wgServer );
1042 # If these were passed, use them
1043 if ( $this->mDbUser
) {
1044 $wgDBadminuser = $this->mDbUser
;
1046 if ( $this->mDbPass
) {
1047 $wgDBadminpassword = $this->mDbPass
;
1050 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1051 $wgDBuser = $wgDBadminuser;
1052 $wgDBpassword = $wgDBadminpassword;
1054 if ( $wgDBservers ) {
1056 * @var $wgDBservers array
1058 foreach ( $wgDBservers as $i => $server ) {
1059 $wgDBservers[$i]['user'] = $wgDBuser;
1060 $wgDBservers[$i]['password'] = $wgDBpassword;
1063 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1064 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1065 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1067 LBFactory
::destroyInstance();
1070 // Per-script profiling; useful for debugging
1071 $this->activateProfiler();
1073 $this->afterFinalSetup();
1075 $wgShowSQLErrors = true;
1077 MediaWiki\
suppressWarnings();
1078 set_time_limit( 0 );
1079 MediaWiki\restoreWarnings
();
1081 $this->adjustMemoryLimit();
1085 * Execute a callback function at the end of initialisation
1087 protected function afterFinalSetup() {
1088 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1089 call_user_func( MW_CMDLINE_CALLBACK
);
1094 * Potentially debug globals. Originally a feature only
1097 public function globals() {
1098 if ( $this->hasOption( 'globals' ) ) {
1099 print_r( $GLOBALS );
1104 * Generic setup for most installs. Returns the location of LocalSettings
1107 public function loadSettings() {
1108 global $wgCommandLineMode, $IP;
1110 if ( isset( $this->mOptions
['conf'] ) ) {
1111 $settingsFile = $this->mOptions
['conf'];
1112 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1113 $settingsFile = MW_CONFIG_FILE
;
1115 $settingsFile = "$IP/LocalSettings.php";
1117 if ( isset( $this->mOptions
['wiki'] ) ) {
1118 $bits = explode( '-', $this->mOptions
['wiki'] );
1119 if ( count( $bits ) == 1 ) {
1122 define( 'MW_DB', $bits[0] );
1123 define( 'MW_PREFIX', $bits[1] );
1126 if ( !is_readable( $settingsFile ) ) {
1127 $this->error( "A copy of your installation's LocalSettings.php\n" .
1128 "must exist and be readable in the source directory.\n" .
1129 "Use --conf to specify it.", true );
1131 $wgCommandLineMode = true;
1133 return $settingsFile;
1137 * Support function for cleaning up redundant text records
1138 * @param bool $delete Whether or not to actually delete the records
1139 * @author Rob Church <robchur@gmail.com>
1141 public function purgeRedundantText( $delete = true ) {
1142 # Data should come off the master, wrapped in a transaction
1143 $dbw = $this->getDB( DB_MASTER
);
1144 $this->beginTransaction( $dbw, __METHOD__
);
1146 # Get "active" text records from the revisions table
1147 $this->output( 'Searching for active text records in revisions table...' );
1148 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1149 foreach ( $res as $row ) {
1150 $cur[] = $row->rev_text_id
;
1152 $this->output( "done.\n" );
1154 # Get "active" text records from the archive table
1155 $this->output( 'Searching for active text records in archive table...' );
1156 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1157 foreach ( $res as $row ) {
1158 # old pre-MW 1.5 records can have null ar_text_id's.
1159 if ( $row->ar_text_id
!== null ) {
1160 $cur[] = $row->ar_text_id
;
1163 $this->output( "done.\n" );
1165 # Get the IDs of all text records not in these sets
1166 $this->output( 'Searching for inactive text records...' );
1167 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1168 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1170 foreach ( $res as $row ) {
1171 $old[] = $row->old_id
;
1173 $this->output( "done.\n" );
1175 # Inform the user of what we're going to do
1176 $count = count( $old );
1177 $this->output( "$count inactive items found.\n" );
1179 # Delete as appropriate
1180 if ( $delete && $count ) {
1181 $this->output( 'Deleting...' );
1182 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1183 $this->output( "done.\n" );
1187 $this->commitTransaction( $dbw, __METHOD__
);
1191 * Get the maintenance directory.
1194 protected function getDir() {
1199 * Returns a database to be used by current maintenance script. It can be set by setDB().
1200 * If not set, wfGetDB() will be used.
1201 * This function has the same parameters as wfGetDB()
1203 * @param integer $db DB index (DB_SLAVE/DB_MASTER)
1204 * @param array $groups; default: empty array
1205 * @param string|bool $wiki; default: current wiki
1208 protected function getDB( $db, $groups = [], $wiki = false ) {
1209 if ( is_null( $this->mDb
) ) {
1210 return wfGetDB( $db, $groups, $wiki );
1217 * Sets database object to be returned by getDB().
1219 * @param IDatabase $db Database object to be used
1221 public function setDB( IDatabase
$db ) {
1226 * Begin a transcation on a DB
1228 * This method makes it clear that begin() is called from a maintenance script,
1229 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1231 * @param IDatabase $dbw
1232 * @param string $fname Caller name
1235 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1236 $dbw->begin( $fname );
1240 * Commit the transcation on a DB handle and wait for slaves to catch up
1242 * This method makes it clear that commit() is called from a maintenance script,
1243 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1245 * @param IDatabase $dbw
1246 * @param string $fname Caller name
1247 * @return bool Whether the slave wait succeeded
1250 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1251 $dbw->commit( $fname );
1253 $ok = wfWaitForSlaves( $this->lastSlaveWait
, false, '*', 30 );
1254 $this->lastSlaveWait
= microtime( true );
1260 * Rollback the transcation on a DB handle
1262 * This method makes it clear that rollback() is called from a maintenance script,
1263 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1265 * @param IDatabase $dbw
1266 * @param string $fname Caller name
1269 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1270 $dbw->rollback( $fname );
1274 * Lock the search index
1275 * @param DatabaseBase &$db
1277 private function lockSearchindex( $db ) {
1278 $write = [ 'searchindex' ];
1288 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1293 * @param DatabaseBase &$db
1295 private function unlockSearchindex( $db ) {
1296 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1300 * Unlock and lock again
1301 * Since the lock is low-priority, queued reads will be able to complete
1302 * @param DatabaseBase &$db
1304 private function relockSearchindex( $db ) {
1305 $this->unlockSearchindex( $db );
1306 $this->lockSearchindex( $db );
1310 * Perform a search index update with locking
1311 * @param int $maxLockTime The maximum time to keep the search index locked.
1312 * @param string $callback The function that will update the function.
1313 * @param DatabaseBase $dbw
1314 * @param array $results
1316 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1320 if ( $maxLockTime ) {
1321 $this->output( " --- Waiting for lock ---" );
1322 $this->lockSearchindex( $dbw );
1324 $this->output( "\n" );
1327 # Loop through the results and do a search update
1328 foreach ( $results as $row ) {
1329 # Allow reads to be processed
1330 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1331 $this->output( " --- Relocking ---" );
1332 $this->relockSearchindex( $dbw );
1334 $this->output( "\n" );
1336 call_user_func( $callback, $dbw, $row );
1339 # Unlock searchindex
1340 if ( $maxLockTime ) {
1341 $this->output( " --- Unlocking --" );
1342 $this->unlockSearchindex( $dbw );
1343 $this->output( "\n" );
1348 * Update the searchindex table for a given pageid
1349 * @param DatabaseBase $dbw A database write handle
1350 * @param int $pageId The page ID to update.
1351 * @return null|string
1353 public function updateSearchIndexForPage( $dbw, $pageId ) {
1354 // Get current revision
1355 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1358 $titleObj = $rev->getTitle();
1359 $title = $titleObj->getPrefixedDBkey();
1360 $this->output( "$title..." );
1361 # Update searchindex
1362 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1364 $this->output( "\n" );
1371 * Wrapper for posix_isatty()
1372 * We default as considering stdin a tty (for nice readline methods)
1373 * but treating stout as not a tty to avoid color codes
1375 * @param mixed $fd File descriptor
1378 public static function posix_isatty( $fd ) {
1379 if ( !function_exists( 'posix_isatty' ) ) {
1382 return posix_isatty( $fd );
1387 * Prompt the console for input
1388 * @param string $prompt What to begin the line with, like '> '
1389 * @return string Response
1391 public static function readconsole( $prompt = '> ' ) {
1392 static $isatty = null;
1393 if ( is_null( $isatty ) ) {
1394 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1397 if ( $isatty && function_exists( 'readline' ) ) {
1398 $resp = readline( $prompt );
1399 if ( $resp === null ) {
1400 // Workaround for https://github.com/facebook/hhvm/issues/4776
1407 $st = self
::readlineEmulation( $prompt );
1409 if ( feof( STDIN
) ) {
1412 $st = fgets( STDIN
, 1024 );
1415 if ( $st === false ) {
1418 $resp = trim( $st );
1425 * Emulate readline()
1426 * @param string $prompt What to begin the line with, like '> '
1429 private static function readlineEmulation( $prompt ) {
1430 $bash = Installer
::locateExecutableInDefaultPaths( [ 'bash' ] );
1431 if ( !wfIsWindows() && $bash ) {
1433 $encPrompt = wfEscapeShellArg( $prompt );
1434 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1435 $encCommand = wfEscapeShellArg( $command );
1436 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1438 if ( $retval == 0 ) {
1440 } elseif ( $retval == 127 ) {
1441 // Couldn't execute bash even though we thought we saw it.
1442 // Shell probably spit out an error message, sorry :(
1443 // Fall through to fgets()...
1450 // Fallback... we'll have no editing controls, EWWW
1451 if ( feof( STDIN
) ) {
1456 return fgets( STDIN
, 1024 );
1461 * Fake maintenance wrapper, mostly used for the web installer/updater
1463 class FakeMaintenance
extends Maintenance
{
1464 protected $mSelf = "FakeMaintenanceScript";
1466 public function execute() {
1472 * Class for scripts that perform database maintenance and want to log the
1473 * update in `updatelog` so we can later skip it
1475 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1476 public function __construct() {
1477 parent
::__construct();
1478 $this->addOption( 'force', 'Run the update even if it was completed already' );
1479 $this->setBatchSize( 200 );
1482 public function execute() {
1483 $db = $this->getDB( DB_MASTER
);
1484 $key = $this->getUpdateKey();
1486 if ( !$this->hasOption( 'force' )
1487 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1489 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1494 if ( !$this->doDBUpdates() ) {
1498 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1501 $this->output( $this->updatelogFailedMessage() . "\n" );
1508 * Message to show that the update was done already and was just skipped
1511 protected function updateSkippedMessage() {
1512 $key = $this->getUpdateKey();
1514 return "Update '{$key}' already logged as completed.";
1518 * Message to show that the update log was unable to log the completion of this update
1521 protected function updatelogFailedMessage() {
1522 $key = $this->getUpdateKey();
1524 return "Unable to log update '{$key}' as completed.";
1528 * Do the actual work. All child classes will need to implement this.
1529 * Return true to log the update as done or false (usually on failure).
1532 abstract protected function doDBUpdates();
1535 * Get the update key name to go in the update log table
1538 abstract protected function getUpdateKey();