API: Document a level of 'all' in action=protect
[mediawiki.git] / maintenance / Maintenance.php
blob27d816115e5a330b55be6b4f9fecda95dd4e2a00
1 <?php
2 /**
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
18 * @file
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Bail on old versions of PHP, or if composer has not been run yet to install
24 // dependencies.
25 require_once __DIR__ . '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'cli' );
28 /**
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
37 $maintClass = false;
39 use MediaWiki\Logger\LoggerFactory;
41 /**
42 * Abstract maintenance class for quickly writing and churning out
43 * maintenance scripts with minimal effort. All that _must_ be defined
44 * is the execute() method. See docs/maintenance.txt for more info
45 * and a quick demo of how to use it.
47 * @author Chad Horohoe <chad@anyonecanedit.org>
48 * @since 1.16
49 * @ingroup Maintenance
51 abstract class Maintenance {
52 /**
53 * Constants for DB access type
54 * @see Maintenance::getDbType()
56 const DB_NONE = 0;
57 const DB_STD = 1;
58 const DB_ADMIN = 2;
60 // Const for getStdin()
61 const STDIN_ALL = 'all';
63 // This is the desired params
64 protected $mParams = [];
66 // Array of mapping short parameters to long ones
67 protected $mShortParamsMap = [];
69 // Array of desired args
70 protected $mArgList = [];
72 // This is the list of options that were actually passed
73 protected $mOptions = [];
75 // This is the list of arguments that were actually passed
76 protected $mArgs = [];
78 // Name of the script currently running
79 protected $mSelf;
81 // Special vars for params that are always used
82 protected $mQuiet = false;
83 protected $mDbUser, $mDbPass;
85 // A description of the script, children should change this via addDescription()
86 protected $mDescription = '';
88 // Have we already loaded our user input?
89 protected $mInputLoaded = false;
91 /**
92 * Batch size. If a script supports this, they should set
93 * a default with setBatchSize()
95 * @var int
97 protected $mBatchSize = null;
99 // Generic options added by addDefaultParams()
100 private $mGenericParameters = [];
101 // Generic options which might or not be supported by the script
102 private $mDependantParameters = [];
105 * Used by getDB() / setDB()
106 * @var IDatabase
108 private $mDb = null;
110 /** @var float UNIX timestamp */
111 private $lastSlaveWait = 0.0;
114 * Used when creating separate schema files.
115 * @var resource
117 public $fileHandle;
120 * Accessible via getConfig()
122 * @var Config
124 private $config;
127 * Used to read the options in the order they were passed.
128 * Useful for option chaining (Ex. dumpBackup.php). It will
129 * be an empty array if the options are passed in through
130 * loadParamsAndArgs( $self, $opts, $args ).
132 * This is an array of arrays where
133 * 0 => the option and 1 => parameter value.
135 * @var array
137 public $orderedOptions = [];
140 * Default constructor. Children should call this *first* if implementing
141 * their own constructors
143 public function __construct() {
144 // Setup $IP, using MW_INSTALL_PATH if it exists
145 global $IP;
146 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
147 ? getenv( 'MW_INSTALL_PATH' )
148 : realpath( __DIR__ . '/..' );
150 $this->addDefaultParams();
151 register_shutdown_function( [ $this, 'outputChanneled' ], false );
155 * Should we execute the maintenance script, or just allow it to be included
156 * as a standalone class? It checks that the call stack only includes this
157 * function and "requires" (meaning was called from the file scope)
159 * @return bool
161 public static function shouldExecute() {
162 global $wgCommandLineMode;
164 if ( !function_exists( 'debug_backtrace' ) ) {
165 // If someone has a better idea...
166 return $wgCommandLineMode;
169 $bt = debug_backtrace();
170 $count = count( $bt );
171 if ( $count < 2 ) {
172 return false; // sanity
174 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
175 return false; // last call should be to this function
177 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
178 for ( $i = 1; $i < $count; $i++ ) {
179 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
180 return false; // previous calls should all be "requires"
184 return true;
188 * Do the actual work. All child classes will need to implement this
190 abstract public function execute();
193 * Add a parameter to the script. Will be displayed on --help
194 * with the associated description
196 * @param string $name The name of the param (help, version, etc)
197 * @param string $description The description of the param to show on --help
198 * @param bool $required Is the param required?
199 * @param bool $withArg Is an argument required with this option?
200 * @param string $shortName Character to use as short name
201 * @param bool $multiOccurrence Can this option be passed multiple times?
203 protected function addOption( $name, $description, $required = false,
204 $withArg = false, $shortName = false, $multiOccurrence = false
206 $this->mParams[$name] = [
207 'desc' => $description,
208 'require' => $required,
209 'withArg' => $withArg,
210 'shortName' => $shortName,
211 'multiOccurrence' => $multiOccurrence
214 if ( $shortName !== false ) {
215 $this->mShortParamsMap[$shortName] = $name;
220 * Checks to see if a particular param exists.
221 * @param string $name The name of the param
222 * @return bool
224 protected function hasOption( $name ) {
225 return isset( $this->mOptions[$name] );
229 * Get an option, or return the default.
231 * If the option was added to support multiple occurrences,
232 * this will return an array.
234 * @param string $name The name of the param
235 * @param mixed $default Anything you want, default null
236 * @return mixed
238 protected function getOption( $name, $default = null ) {
239 if ( $this->hasOption( $name ) ) {
240 return $this->mOptions[$name];
241 } else {
242 // Set it so we don't have to provide the default again
243 $this->mOptions[$name] = $default;
245 return $this->mOptions[$name];
250 * Add some args that are needed
251 * @param string $arg Name of the arg, like 'start'
252 * @param string $description Short description of the arg
253 * @param bool $required Is this required?
255 protected function addArg( $arg, $description, $required = true ) {
256 $this->mArgList[] = [
257 'name' => $arg,
258 'desc' => $description,
259 'require' => $required
264 * Remove an option. Useful for removing options that won't be used in your script.
265 * @param string $name The option to remove.
267 protected function deleteOption( $name ) {
268 unset( $this->mParams[$name] );
272 * Set the description text.
273 * @param string $text The text of the description
275 protected function addDescription( $text ) {
276 $this->mDescription = $text;
280 * Does a given argument exist?
281 * @param int $argId The integer value (from zero) for the arg
282 * @return bool
284 protected function hasArg( $argId = 0 ) {
285 return isset( $this->mArgs[$argId] );
289 * Get an argument.
290 * @param int $argId The integer value (from zero) for the arg
291 * @param mixed $default The default if it doesn't exist
292 * @return mixed
294 protected function getArg( $argId = 0, $default = null ) {
295 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
299 * Set the batch size.
300 * @param int $s The number of operations to do in a batch
302 protected function setBatchSize( $s = 0 ) {
303 $this->mBatchSize = $s;
305 // If we support $mBatchSize, show the option.
306 // Used to be in addDefaultParams, but in order for that to
307 // work, subclasses would have to call this function in the constructor
308 // before they called parent::__construct which is just weird
309 // (and really wasn't done).
310 if ( $this->mBatchSize ) {
311 $this->addOption( 'batch-size', 'Run this many operations ' .
312 'per batch, default: ' . $this->mBatchSize, false, true );
313 if ( isset( $this->mParams['batch-size'] ) ) {
314 // This seems a little ugly...
315 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
321 * Get the script's name
322 * @return string
324 public function getName() {
325 return $this->mSelf;
329 * Return input from stdin.
330 * @param int $len The number of bytes to read. If null, just return the handle.
331 * Maintenance::STDIN_ALL returns the full length
332 * @return mixed
334 protected function getStdin( $len = null ) {
335 if ( $len == Maintenance::STDIN_ALL ) {
336 return file_get_contents( 'php://stdin' );
338 $f = fopen( 'php://stdin', 'rt' );
339 if ( !$len ) {
340 return $f;
342 $input = fgets( $f, $len );
343 fclose( $f );
345 return rtrim( $input );
349 * @return bool
351 public function isQuiet() {
352 return $this->mQuiet;
356 * Throw some output to the user. Scripts can call this with no fears,
357 * as we handle all --quiet stuff here
358 * @param string $out The text to show to the user
359 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
361 protected function output( $out, $channel = null ) {
362 if ( $this->mQuiet ) {
363 return;
365 if ( $channel === null ) {
366 $this->cleanupChanneled();
367 print $out;
368 } else {
369 $out = preg_replace( '/\n\z/', '', $out );
370 $this->outputChanneled( $out, $channel );
375 * Throw an error to the user. Doesn't respect --quiet, so don't use
376 * this for non-error output
377 * @param string $err The error to display
378 * @param int $die If > 0, go ahead and die out using this int as the code
380 protected function error( $err, $die = 0 ) {
381 $this->outputChanneled( false );
382 if ( PHP_SAPI == 'cli' ) {
383 fwrite( STDERR, $err . "\n" );
384 } else {
385 print $err;
387 $die = intval( $die );
388 if ( $die > 0 ) {
389 die( $die );
393 private $atLineStart = true;
394 private $lastChannel = null;
397 * Clean up channeled output. Output a newline if necessary.
399 public function cleanupChanneled() {
400 if ( !$this->atLineStart ) {
401 print "\n";
402 $this->atLineStart = true;
407 * Message outputter with channeled message support. Messages on the
408 * same channel are concatenated, but any intervening messages in another
409 * channel start a new line.
410 * @param string $msg The message without trailing newline
411 * @param string $channel Channel identifier or null for no
412 * channel. Channel comparison uses ===.
414 public function outputChanneled( $msg, $channel = null ) {
415 if ( $msg === false ) {
416 $this->cleanupChanneled();
418 return;
421 // End the current line if necessary
422 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
423 print "\n";
426 print $msg;
428 $this->atLineStart = false;
429 if ( $channel === null ) {
430 // For unchanneled messages, output trailing newline immediately
431 print "\n";
432 $this->atLineStart = true;
434 $this->lastChannel = $channel;
438 * Does the script need different DB access? By default, we give Maintenance
439 * scripts normal rights to the DB. Sometimes, a script needs admin rights
440 * access for a reason and sometimes they want no access. Subclasses should
441 * override and return one of the following values, as needed:
442 * Maintenance::DB_NONE - For no DB access at all
443 * Maintenance::DB_STD - For normal DB access, default
444 * Maintenance::DB_ADMIN - For admin DB access
445 * @return int
447 public function getDbType() {
448 return Maintenance::DB_STD;
452 * Add the default parameters to the scripts
454 protected function addDefaultParams() {
456 # Generic (non script dependant) options:
458 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
459 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
460 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
461 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
462 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
463 $this->addOption(
464 'memory-limit',
465 'Set a specific memory limit for the script, '
466 . '"max" for no limit or "default" to avoid changing it'
468 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
469 "http://en.wikipedia.org. This is sometimes necessary because " .
470 "server name detection may fail in command line scripts.", false, true );
471 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
473 # Save generic options to display them separately in help
474 $this->mGenericParameters = $this->mParams;
476 # Script dependant options:
478 // If we support a DB, show the options
479 if ( $this->getDbType() > 0 ) {
480 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
481 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
484 # Save additional script dependant options to display
485 #  them separately in help
486 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
490 * @since 1.24
491 * @return Config
493 public function getConfig() {
494 if ( $this->config === null ) {
495 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
498 return $this->config;
502 * @since 1.24
503 * @param Config $config
505 public function setConfig( Config $config ) {
506 $this->config = $config;
510 * Run a child maintenance script. Pass all of the current arguments
511 * to it.
512 * @param string $maintClass A name of a child maintenance class
513 * @param string $classFile Full path of where the child is
514 * @return Maintenance
516 public function runChild( $maintClass, $classFile = null ) {
517 // Make sure the class is loaded first
518 if ( !class_exists( $maintClass ) ) {
519 if ( $classFile ) {
520 require_once $classFile;
522 if ( !class_exists( $maintClass ) ) {
523 $this->error( "Cannot spawn child: $maintClass" );
528 * @var $child Maintenance
530 $child = new $maintClass();
531 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
532 if ( !is_null( $this->mDb ) ) {
533 $child->setDB( $this->mDb );
536 return $child;
540 * Do some sanity checking and basic setup
542 public function setup() {
543 global $IP, $wgCommandLineMode, $wgRequestTime;
545 # Abort if called from a web server
546 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
547 $this->error( 'This script must be run from the command line', true );
550 if ( $IP === null ) {
551 $this->error( "\$IP not set, aborting!\n" .
552 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
555 # Make sure we can handle script parameters
556 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
557 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
560 // Send PHP warnings and errors to stderr instead of stdout.
561 // This aids in diagnosing problems, while keeping messages
562 // out of redirected output.
563 if ( ini_get( 'display_errors' ) ) {
564 ini_set( 'display_errors', 'stderr' );
567 $this->loadParamsAndArgs();
568 $this->maybeHelp();
570 # Set the memory limit
571 # Note we need to set it again later in cache LocalSettings changed it
572 $this->adjustMemoryLimit();
574 # Set max execution time to 0 (no limit). PHP.net says that
575 # "When running PHP from the command line the default setting is 0."
576 # But sometimes this doesn't seem to be the case.
577 ini_set( 'max_execution_time', 0 );
579 $wgRequestTime = microtime( true );
581 # Define us as being in MediaWiki
582 define( 'MEDIAWIKI', true );
584 $wgCommandLineMode = true;
586 # Turn off output buffering if it's on
587 while ( ob_get_level() > 0 ) {
588 ob_end_flush();
591 $this->validateParamsAndArgs();
595 * Normally we disable the memory_limit when running admin scripts.
596 * Some scripts may wish to actually set a limit, however, to avoid
597 * blowing up unexpectedly. We also support a --memory-limit option,
598 * to allow sysadmins to explicitly set one if they'd prefer to override
599 * defaults (or for people using Suhosin which yells at you for trying
600 * to disable the limits)
601 * @return string
603 public function memoryLimit() {
604 $limit = $this->getOption( 'memory-limit', 'max' );
605 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
606 return $limit;
610 * Adjusts PHP's memory limit to better suit our needs, if needed.
612 protected function adjustMemoryLimit() {
613 $limit = $this->memoryLimit();
614 if ( $limit == 'max' ) {
615 $limit = -1; // no memory limit
617 if ( $limit != 'default' ) {
618 ini_set( 'memory_limit', $limit );
623 * Activate the profiler (assuming $wgProfiler is set)
625 protected function activateProfiler() {
626 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
628 $output = $this->getOption( 'profiler' );
629 if ( !$output ) {
630 return;
633 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
634 $class = $wgProfiler['class'];
635 $profiler = new $class(
636 [ 'sampling' => 1, 'output' => [ $output ] ]
637 + $wgProfiler
638 + [ 'threshold' => $wgProfileLimit ]
640 $profiler->setTemplated( true );
641 Profiler::replaceStubInstance( $profiler );
644 $trxProfiler = Profiler::instance()->getTransactionProfiler();
645 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
646 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
650 * Clear all params and arguments.
652 public function clearParamsAndArgs() {
653 $this->mOptions = [];
654 $this->mArgs = [];
655 $this->mInputLoaded = false;
659 * Load params and arguments from a given array
660 * of command-line arguments
662 * @since 1.27
663 * @param array $argv
665 public function loadWithArgv( $argv ) {
666 $options = [];
667 $args = [];
668 $this->orderedOptions = [];
670 # Parse arguments
671 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
672 if ( $arg == '--' ) {
673 # End of options, remainder should be considered arguments
674 $arg = next( $argv );
675 while ( $arg !== false ) {
676 $args[] = $arg;
677 $arg = next( $argv );
679 break;
680 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
681 # Long options
682 $option = substr( $arg, 2 );
683 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
684 $param = next( $argv );
685 if ( $param === false ) {
686 $this->error( "\nERROR: $option parameter needs a value after it\n" );
687 $this->maybeHelp( true );
690 $this->setParam( $options, $option, $param );
691 } else {
692 $bits = explode( '=', $option, 2 );
693 if ( count( $bits ) > 1 ) {
694 $option = $bits[0];
695 $param = $bits[1];
696 } else {
697 $param = 1;
700 $this->setParam( $options, $option, $param );
702 } elseif ( $arg == '-' ) {
703 # Lonely "-", often used to indicate stdin or stdout.
704 $args[] = $arg;
705 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
706 # Short options
707 $argLength = strlen( $arg );
708 for ( $p = 1; $p < $argLength; $p++ ) {
709 $option = $arg[$p];
710 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
711 $option = $this->mShortParamsMap[$option];
714 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
715 $param = next( $argv );
716 if ( $param === false ) {
717 $this->error( "\nERROR: $option parameter needs a value after it\n" );
718 $this->maybeHelp( true );
720 $this->setParam( $options, $option, $param );
721 } else {
722 $this->setParam( $options, $option, 1 );
725 } else {
726 $args[] = $arg;
730 $this->mOptions = $options;
731 $this->mArgs = $args;
732 $this->loadSpecialVars();
733 $this->mInputLoaded = true;
737 * Helper function used solely by loadParamsAndArgs
738 * to prevent code duplication
740 * This sets the param in the options array based on
741 * whether or not it can be specified multiple times.
743 * @since 1.27
744 * @param array $options
745 * @param string $option
746 * @param mixed $value
748 private function setParam( &$options, $option, $value ) {
749 $this->orderedOptions[] = [ $option, $value ];
751 if ( isset( $this->mParams[$option] ) ) {
752 $multi = $this->mParams[$option]['multiOccurrence'];
753 } else {
754 $multi = false;
756 $exists = array_key_exists( $option, $options );
757 if ( $multi && $exists ) {
758 $options[$option][] = $value;
759 } elseif ( $multi ) {
760 $options[$option] = [ $value ];
761 } elseif ( !$exists ) {
762 $options[$option] = $value;
763 } else {
764 $this->error( "\nERROR: $option parameter given twice\n" );
765 $this->maybeHelp( true );
770 * Process command line arguments
771 * $mOptions becomes an array with keys set to the option names
772 * $mArgs becomes a zero-based array containing the non-option arguments
774 * @param string $self The name of the script, if any
775 * @param array $opts An array of options, in form of key=>value
776 * @param array $args An array of command line arguments
778 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
779 # If we were given opts or args, set those and return early
780 if ( $self ) {
781 $this->mSelf = $self;
782 $this->mInputLoaded = true;
784 if ( $opts ) {
785 $this->mOptions = $opts;
786 $this->mInputLoaded = true;
788 if ( $args ) {
789 $this->mArgs = $args;
790 $this->mInputLoaded = true;
793 # If we've already loaded input (either by user values or from $argv)
794 # skip on loading it again. The array_shift() will corrupt values if
795 # it's run again and again
796 if ( $this->mInputLoaded ) {
797 $this->loadSpecialVars();
799 return;
802 global $argv;
803 $this->mSelf = $argv[0];
804 $this->loadWithArgv( array_slice( $argv, 1 ) );
808 * Run some validation checks on the params, etc
810 protected function validateParamsAndArgs() {
811 $die = false;
812 # Check to make sure we've got all the required options
813 foreach ( $this->mParams as $opt => $info ) {
814 if ( $info['require'] && !$this->hasOption( $opt ) ) {
815 $this->error( "Param $opt required!" );
816 $die = true;
819 # Check arg list too
820 foreach ( $this->mArgList as $k => $info ) {
821 if ( $info['require'] && !$this->hasArg( $k ) ) {
822 $this->error( 'Argument <' . $info['name'] . '> required!' );
823 $die = true;
827 if ( $die ) {
828 $this->maybeHelp( true );
833 * Handle the special variables that are global to all scripts
835 protected function loadSpecialVars() {
836 if ( $this->hasOption( 'dbuser' ) ) {
837 $this->mDbUser = $this->getOption( 'dbuser' );
839 if ( $this->hasOption( 'dbpass' ) ) {
840 $this->mDbPass = $this->getOption( 'dbpass' );
842 if ( $this->hasOption( 'quiet' ) ) {
843 $this->mQuiet = true;
845 if ( $this->hasOption( 'batch-size' ) ) {
846 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
851 * Maybe show the help.
852 * @param bool $force Whether to force the help to show, default false
854 protected function maybeHelp( $force = false ) {
855 if ( !$force && !$this->hasOption( 'help' ) ) {
856 return;
859 $screenWidth = 80; // TODO: Calculate this!
860 $tab = " ";
861 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
863 ksort( $this->mParams );
864 $this->mQuiet = false;
866 // Description ...
867 if ( $this->mDescription ) {
868 $this->output( "\n" . $this->mDescription . "\n" );
870 $output = "\nUsage: php " . basename( $this->mSelf );
872 // ... append parameters ...
873 if ( $this->mParams ) {
874 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
877 // ... and append arguments.
878 if ( $this->mArgList ) {
879 $output .= ' ';
880 foreach ( $this->mArgList as $k => $arg ) {
881 if ( $arg['require'] ) {
882 $output .= '<' . $arg['name'] . '>';
883 } else {
884 $output .= '[' . $arg['name'] . ']';
886 if ( $k < count( $this->mArgList ) - 1 ) {
887 $output .= ' ';
891 $this->output( "$output\n\n" );
893 # TODO abstract some repetitive code below
895 // Generic parameters
896 $this->output( "Generic maintenance parameters:\n" );
897 foreach ( $this->mGenericParameters as $par => $info ) {
898 if ( $info['shortName'] !== false ) {
899 $par .= " (-{$info['shortName']})";
901 $this->output(
902 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
903 "\n$tab$tab" ) . "\n"
906 $this->output( "\n" );
908 $scriptDependantParams = $this->mDependantParameters;
909 if ( count( $scriptDependantParams ) > 0 ) {
910 $this->output( "Script dependant parameters:\n" );
911 // Parameters description
912 foreach ( $scriptDependantParams as $par => $info ) {
913 if ( $info['shortName'] !== false ) {
914 $par .= " (-{$info['shortName']})";
916 $this->output(
917 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
918 "\n$tab$tab" ) . "\n"
921 $this->output( "\n" );
924 // Script specific parameters not defined on construction by
925 // Maintenance::addDefaultParams()
926 $scriptSpecificParams = array_diff_key(
927 # all script parameters:
928 $this->mParams,
929 # remove the Maintenance default parameters:
930 $this->mGenericParameters,
931 $this->mDependantParameters
933 if ( count( $scriptSpecificParams ) > 0 ) {
934 $this->output( "Script specific parameters:\n" );
935 // Parameters description
936 foreach ( $scriptSpecificParams as $par => $info ) {
937 if ( $info['shortName'] !== false ) {
938 $par .= " (-{$info['shortName']})";
940 $this->output(
941 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
942 "\n$tab$tab" ) . "\n"
945 $this->output( "\n" );
948 // Print arguments
949 if ( count( $this->mArgList ) > 0 ) {
950 $this->output( "Arguments:\n" );
951 // Arguments description
952 foreach ( $this->mArgList as $info ) {
953 $openChar = $info['require'] ? '<' : '[';
954 $closeChar = $info['require'] ? '>' : ']';
955 $this->output(
956 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
957 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
960 $this->output( "\n" );
963 die( 1 );
967 * Handle some last-minute setup here.
969 public function finalSetup() {
970 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
971 global $wgDBadminuser, $wgDBadminpassword;
972 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
974 # Turn off output buffering again, it might have been turned on in the settings files
975 if ( ob_get_level() ) {
976 ob_end_flush();
978 # Same with these
979 $wgCommandLineMode = true;
981 # Override $wgServer
982 if ( $this->hasOption( 'server' ) ) {
983 $wgServer = $this->getOption( 'server', $wgServer );
986 # If these were passed, use them
987 if ( $this->mDbUser ) {
988 $wgDBadminuser = $this->mDbUser;
990 if ( $this->mDbPass ) {
991 $wgDBadminpassword = $this->mDbPass;
994 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
995 $wgDBuser = $wgDBadminuser;
996 $wgDBpassword = $wgDBadminpassword;
998 if ( $wgDBservers ) {
1000 * @var $wgDBservers array
1002 foreach ( $wgDBservers as $i => $server ) {
1003 $wgDBservers[$i]['user'] = $wgDBuser;
1004 $wgDBservers[$i]['password'] = $wgDBpassword;
1007 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1008 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1009 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1011 LBFactory::destroyInstance();
1014 // Per-script profiling; useful for debugging
1015 $this->activateProfiler();
1017 $this->afterFinalSetup();
1019 $wgShowSQLErrors = true;
1021 MediaWiki\suppressWarnings();
1022 set_time_limit( 0 );
1023 MediaWiki\restoreWarnings();
1025 $this->adjustMemoryLimit();
1029 * Execute a callback function at the end of initialisation
1031 protected function afterFinalSetup() {
1032 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1033 call_user_func( MW_CMDLINE_CALLBACK );
1038 * Potentially debug globals. Originally a feature only
1039 * for refreshLinks
1041 public function globals() {
1042 if ( $this->hasOption( 'globals' ) ) {
1043 print_r( $GLOBALS );
1048 * Generic setup for most installs. Returns the location of LocalSettings
1049 * @return string
1051 public function loadSettings() {
1052 global $wgCommandLineMode, $IP;
1054 if ( isset( $this->mOptions['conf'] ) ) {
1055 $settingsFile = $this->mOptions['conf'];
1056 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1057 $settingsFile = MW_CONFIG_FILE;
1058 } else {
1059 $settingsFile = "$IP/LocalSettings.php";
1061 if ( isset( $this->mOptions['wiki'] ) ) {
1062 $bits = explode( '-', $this->mOptions['wiki'] );
1063 if ( count( $bits ) == 1 ) {
1064 $bits[] = '';
1066 define( 'MW_DB', $bits[0] );
1067 define( 'MW_PREFIX', $bits[1] );
1070 if ( !is_readable( $settingsFile ) ) {
1071 $this->error( "A copy of your installation's LocalSettings.php\n" .
1072 "must exist and be readable in the source directory.\n" .
1073 "Use --conf to specify it.", true );
1075 $wgCommandLineMode = true;
1077 return $settingsFile;
1081 * Support function for cleaning up redundant text records
1082 * @param bool $delete Whether or not to actually delete the records
1083 * @author Rob Church <robchur@gmail.com>
1085 public function purgeRedundantText( $delete = true ) {
1086 # Data should come off the master, wrapped in a transaction
1087 $dbw = $this->getDB( DB_MASTER );
1088 $this->beginTransaction( $dbw, __METHOD__ );
1090 # Get "active" text records from the revisions table
1091 $this->output( 'Searching for active text records in revisions table...' );
1092 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1093 foreach ( $res as $row ) {
1094 $cur[] = $row->rev_text_id;
1096 $this->output( "done.\n" );
1098 # Get "active" text records from the archive table
1099 $this->output( 'Searching for active text records in archive table...' );
1100 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1101 foreach ( $res as $row ) {
1102 # old pre-MW 1.5 records can have null ar_text_id's.
1103 if ( $row->ar_text_id !== null ) {
1104 $cur[] = $row->ar_text_id;
1107 $this->output( "done.\n" );
1109 # Get the IDs of all text records not in these sets
1110 $this->output( 'Searching for inactive text records...' );
1111 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1112 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1113 $old = [];
1114 foreach ( $res as $row ) {
1115 $old[] = $row->old_id;
1117 $this->output( "done.\n" );
1119 # Inform the user of what we're going to do
1120 $count = count( $old );
1121 $this->output( "$count inactive items found.\n" );
1123 # Delete as appropriate
1124 if ( $delete && $count ) {
1125 $this->output( 'Deleting...' );
1126 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1127 $this->output( "done.\n" );
1130 # Done
1131 $this->commitTransaction( $dbw, __METHOD__ );
1135 * Get the maintenance directory.
1136 * @return string
1138 protected function getDir() {
1139 return __DIR__;
1143 * Returns a database to be used by current maintenance script. It can be set by setDB().
1144 * If not set, wfGetDB() will be used.
1145 * This function has the same parameters as wfGetDB()
1147 * @param integer $db DB index (DB_SLAVE/DB_MASTER)
1148 * @param array $groups; default: empty array
1149 * @param string|bool $wiki; default: current wiki
1150 * @return IDatabase
1152 protected function getDB( $db, $groups = [], $wiki = false ) {
1153 if ( is_null( $this->mDb ) ) {
1154 return wfGetDB( $db, $groups, $wiki );
1155 } else {
1156 return $this->mDb;
1161 * Sets database object to be returned by getDB().
1163 * @param IDatabase $db Database object to be used
1165 public function setDB( IDatabase $db ) {
1166 $this->mDb = $db;
1170 * Begin a transcation on a DB
1172 * This method makes it clear that begin() is called from a maintenance script,
1173 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1175 * @param IDatabase $dbw
1176 * @param string $fname Caller name
1177 * @since 1.27
1179 protected function beginTransaction( IDatabase $dbw, $fname ) {
1180 $dbw->begin( $fname );
1184 * Commit the transcation on a DB handle and wait for slaves to catch up
1186 * This method makes it clear that commit() is called from a maintenance script,
1187 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1189 * @param IDatabase $dbw
1190 * @param string $fname Caller name
1191 * @return bool Whether the slave wait succeeded
1192 * @since 1.27
1194 protected function commitTransaction( IDatabase $dbw, $fname ) {
1195 $dbw->commit( $fname );
1197 $ok = wfWaitForSlaves( $this->lastSlaveWait, false, '*', 30 );
1198 $this->lastSlaveWait = microtime( true );
1200 return $ok;
1204 * Rollback the transcation on a DB handle
1206 * This method makes it clear that rollback() is called from a maintenance script,
1207 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1209 * @param IDatabase $dbw
1210 * @param string $fname Caller name
1211 * @since 1.27
1213 protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1214 $dbw->rollback( $fname );
1218 * Lock the search index
1219 * @param DatabaseBase &$db
1221 private function lockSearchindex( $db ) {
1222 $write = [ 'searchindex' ];
1223 $read = [
1224 'page',
1225 'revision',
1226 'text',
1227 'interwiki',
1228 'l10n_cache',
1229 'user',
1230 'page_restrictions'
1232 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1236 * Unlock the tables
1237 * @param DatabaseBase &$db
1239 private function unlockSearchindex( $db ) {
1240 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1244 * Unlock and lock again
1245 * Since the lock is low-priority, queued reads will be able to complete
1246 * @param DatabaseBase &$db
1248 private function relockSearchindex( $db ) {
1249 $this->unlockSearchindex( $db );
1250 $this->lockSearchindex( $db );
1254 * Perform a search index update with locking
1255 * @param int $maxLockTime The maximum time to keep the search index locked.
1256 * @param string $callback The function that will update the function.
1257 * @param DatabaseBase $dbw
1258 * @param array $results
1260 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1261 $lockTime = time();
1263 # Lock searchindex
1264 if ( $maxLockTime ) {
1265 $this->output( " --- Waiting for lock ---" );
1266 $this->lockSearchindex( $dbw );
1267 $lockTime = time();
1268 $this->output( "\n" );
1271 # Loop through the results and do a search update
1272 foreach ( $results as $row ) {
1273 # Allow reads to be processed
1274 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1275 $this->output( " --- Relocking ---" );
1276 $this->relockSearchindex( $dbw );
1277 $lockTime = time();
1278 $this->output( "\n" );
1280 call_user_func( $callback, $dbw, $row );
1283 # Unlock searchindex
1284 if ( $maxLockTime ) {
1285 $this->output( " --- Unlocking --" );
1286 $this->unlockSearchindex( $dbw );
1287 $this->output( "\n" );
1292 * Update the searchindex table for a given pageid
1293 * @param DatabaseBase $dbw A database write handle
1294 * @param int $pageId The page ID to update.
1295 * @return null|string
1297 public function updateSearchIndexForPage( $dbw, $pageId ) {
1298 // Get current revision
1299 $rev = Revision::loadFromPageId( $dbw, $pageId );
1300 $title = null;
1301 if ( $rev ) {
1302 $titleObj = $rev->getTitle();
1303 $title = $titleObj->getPrefixedDBkey();
1304 $this->output( "$title..." );
1305 # Update searchindex
1306 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1307 $u->doUpdate();
1308 $this->output( "\n" );
1311 return $title;
1315 * Wrapper for posix_isatty()
1316 * We default as considering stdin a tty (for nice readline methods)
1317 * but treating stout as not a tty to avoid color codes
1319 * @param mixed $fd File descriptor
1320 * @return bool
1322 public static function posix_isatty( $fd ) {
1323 if ( !function_exists( 'posix_isatty' ) ) {
1324 return !$fd;
1325 } else {
1326 return posix_isatty( $fd );
1331 * Prompt the console for input
1332 * @param string $prompt What to begin the line with, like '> '
1333 * @return string Response
1335 public static function readconsole( $prompt = '> ' ) {
1336 static $isatty = null;
1337 if ( is_null( $isatty ) ) {
1338 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1341 if ( $isatty && function_exists( 'readline' ) ) {
1342 $resp = readline( $prompt );
1343 if ( $resp === null ) {
1344 // Workaround for https://github.com/facebook/hhvm/issues/4776
1345 return false;
1346 } else {
1347 return $resp;
1349 } else {
1350 if ( $isatty ) {
1351 $st = self::readlineEmulation( $prompt );
1352 } else {
1353 if ( feof( STDIN ) ) {
1354 $st = false;
1355 } else {
1356 $st = fgets( STDIN, 1024 );
1359 if ( $st === false ) {
1360 return false;
1362 $resp = trim( $st );
1364 return $resp;
1369 * Emulate readline()
1370 * @param string $prompt What to begin the line with, like '> '
1371 * @return string
1373 private static function readlineEmulation( $prompt ) {
1374 $bash = Installer::locateExecutableInDefaultPaths( [ 'bash' ] );
1375 if ( !wfIsWindows() && $bash ) {
1376 $retval = false;
1377 $encPrompt = wfEscapeShellArg( $prompt );
1378 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1379 $encCommand = wfEscapeShellArg( $command );
1380 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1382 if ( $retval == 0 ) {
1383 return $line;
1384 } elseif ( $retval == 127 ) {
1385 // Couldn't execute bash even though we thought we saw it.
1386 // Shell probably spit out an error message, sorry :(
1387 // Fall through to fgets()...
1388 } else {
1389 // EOF/ctrl+D
1390 return false;
1394 // Fallback... we'll have no editing controls, EWWW
1395 if ( feof( STDIN ) ) {
1396 return false;
1398 print $prompt;
1400 return fgets( STDIN, 1024 );
1405 * Fake maintenance wrapper, mostly used for the web installer/updater
1407 class FakeMaintenance extends Maintenance {
1408 protected $mSelf = "FakeMaintenanceScript";
1410 public function execute() {
1411 return;
1416 * Class for scripts that perform database maintenance and want to log the
1417 * update in `updatelog` so we can later skip it
1419 abstract class LoggedUpdateMaintenance extends Maintenance {
1420 public function __construct() {
1421 parent::__construct();
1422 $this->addOption( 'force', 'Run the update even if it was completed already' );
1423 $this->setBatchSize( 200 );
1426 public function execute() {
1427 $db = $this->getDB( DB_MASTER );
1428 $key = $this->getUpdateKey();
1430 if ( !$this->hasOption( 'force' )
1431 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
1433 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1435 return true;
1438 if ( !$this->doDBUpdates() ) {
1439 return false;
1442 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, 'IGNORE' ) ) {
1443 return true;
1444 } else {
1445 $this->output( $this->updatelogFailedMessage() . "\n" );
1447 return false;
1452 * Message to show that the update was done already and was just skipped
1453 * @return string
1455 protected function updateSkippedMessage() {
1456 $key = $this->getUpdateKey();
1458 return "Update '{$key}' already logged as completed.";
1462 * Message to show that the update log was unable to log the completion of this update
1463 * @return string
1465 protected function updatelogFailedMessage() {
1466 $key = $this->getUpdateKey();
1468 return "Unable to log update '{$key}' as completed.";
1472 * Do the actual work. All child classes will need to implement this.
1473 * Return true to log the update as done or false (usually on failure).
1474 * @return bool
1476 abstract protected function doDBUpdates();
1479 * Get the update key name to go in the update log table
1480 * @return string
1482 abstract protected function getUpdateKey();