Merge "Fix @return documentation in WANObjectCache::prefixCacheKeys()"
[mediawiki.git] / maintenance / Maintenance.php
blobf97f6dca9c5ac84630042d7a4a522c2b6e9f30fc
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 // Make sure we're on PHP5.3.3 or better
24 if ( !function_exists( 'version_compare' ) || version_compare( PHP_VERSION, '5.3.3' ) < 0 ) {
25 // We need to use dirname( __FILE__ ) here cause __DIR__ is PHP5.3+
26 require_once dirname( __FILE__ ) . '/../includes/PHPVersionError.php';
27 wfPHPVersionError( 'cli' );
30 /**
31 * @defgroup MaintenanceArchive Maintenance archives
32 * @ingroup Maintenance
35 // Define this so scripts can easily find doMaintenance.php
36 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' );
37 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
39 $maintClass = false;
41 use MediaWiki\Logger\LoggerFactory;
43 /**
44 * Abstract maintenance class for quickly writing and churning out
45 * maintenance scripts with minimal effort. All that _must_ be defined
46 * is the execute() method. See docs/maintenance.txt for more info
47 * and a quick demo of how to use it.
49 * @author Chad Horohoe <chad@anyonecanedit.org>
50 * @since 1.16
51 * @ingroup Maintenance
53 abstract class Maintenance {
54 /**
55 * Constants for DB access type
56 * @see Maintenance::getDbType()
58 const DB_NONE = 0;
59 const DB_STD = 1;
60 const DB_ADMIN = 2;
62 // Const for getStdin()
63 const STDIN_ALL = 'all';
65 // This is the desired params
66 protected $mParams = array();
68 // Array of mapping short parameters to long ones
69 protected $mShortParamsMap = array();
71 // Array of desired args
72 protected $mArgList = array();
74 // This is the list of options that were actually passed
75 protected $mOptions = array();
77 // This is the list of arguments that were actually passed
78 protected $mArgs = array();
80 // Name of the script currently running
81 protected $mSelf;
83 // Special vars for params that are always used
84 protected $mQuiet = false;
85 protected $mDbUser, $mDbPass;
87 // A description of the script, children should change this
88 protected $mDescription = '';
90 // Have we already loaded our user input?
91 protected $mInputLoaded = false;
93 /**
94 * Batch size. If a script supports this, they should set
95 * a default with setBatchSize()
97 * @var int
99 protected $mBatchSize = null;
101 // Generic options added by addDefaultParams()
102 private $mGenericParameters = array();
103 // Generic options which might or not be supported by the script
104 private $mDependantParameters = array();
107 * Used by getDB() / setDB()
108 * @var DatabaseBase
110 private $mDb = null;
113 * Used when creating separate schema files.
114 * @var resource
116 public $fileHandle;
119 * Accessible via getConfig()
121 * @var Config
123 private $config;
126 * Default constructor. Children should call this *first* if implementing
127 * their own constructors
129 public function __construct() {
130 // Setup $IP, using MW_INSTALL_PATH if it exists
131 global $IP;
132 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
133 ? getenv( 'MW_INSTALL_PATH' )
134 : realpath( __DIR__ . '/..' );
136 $this->addDefaultParams();
137 register_shutdown_function( array( $this, 'outputChanneled' ), false );
141 * Should we execute the maintenance script, or just allow it to be included
142 * as a standalone class? It checks that the call stack only includes this
143 * function and "requires" (meaning was called from the file scope)
145 * @return bool
147 public static function shouldExecute() {
148 global $wgCommandLineMode;
150 if ( !function_exists( 'debug_backtrace' ) ) {
151 // If someone has a better idea...
152 return $wgCommandLineMode;
155 $bt = debug_backtrace();
156 $count = count( $bt );
157 if ( $count < 2 ) {
158 return false; // sanity
160 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
161 return false; // last call should be to this function
163 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
164 for ( $i = 1; $i < $count; $i++ ) {
165 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
166 return false; // previous calls should all be "requires"
170 return true;
174 * Do the actual work. All child classes will need to implement this
176 abstract public function execute();
179 * Add a parameter to the script. Will be displayed on --help
180 * with the associated description
182 * @param string $name The name of the param (help, version, etc)
183 * @param string $description The description of the param to show on --help
184 * @param bool $required Is the param required?
185 * @param bool $withArg Is an argument required with this option?
186 * @param string $shortName Character to use as short name
188 protected function addOption( $name, $description, $required = false,
189 $withArg = false, $shortName = false
191 $this->mParams[$name] = array(
192 'desc' => $description,
193 'require' => $required,
194 'withArg' => $withArg,
195 'shortName' => $shortName
198 if ( $shortName !== false ) {
199 $this->mShortParamsMap[$shortName] = $name;
204 * Checks to see if a particular param exists.
205 * @param string $name The name of the param
206 * @return bool
208 protected function hasOption( $name ) {
209 return isset( $this->mOptions[$name] );
213 * Get an option, or return the default
214 * @param string $name The name of the param
215 * @param mixed $default Anything you want, default null
216 * @return mixed
218 protected function getOption( $name, $default = null ) {
219 if ( $this->hasOption( $name ) ) {
220 return $this->mOptions[$name];
221 } else {
222 // Set it so we don't have to provide the default again
223 $this->mOptions[$name] = $default;
225 return $this->mOptions[$name];
230 * Add some args that are needed
231 * @param string $arg Name of the arg, like 'start'
232 * @param string $description Short description of the arg
233 * @param bool $required Is this required?
235 protected function addArg( $arg, $description, $required = true ) {
236 $this->mArgList[] = array(
237 'name' => $arg,
238 'desc' => $description,
239 'require' => $required
244 * Remove an option. Useful for removing options that won't be used in your script.
245 * @param string $name The option to remove.
247 protected function deleteOption( $name ) {
248 unset( $this->mParams[$name] );
252 * Set the description text.
253 * @param string $text The text of the description
255 protected function addDescription( $text ) {
256 $this->mDescription = $text;
260 * Does a given argument exist?
261 * @param int $argId The integer value (from zero) for the arg
262 * @return bool
264 protected function hasArg( $argId = 0 ) {
265 return isset( $this->mArgs[$argId] );
269 * Get an argument.
270 * @param int $argId The integer value (from zero) for the arg
271 * @param mixed $default The default if it doesn't exist
272 * @return mixed
274 protected function getArg( $argId = 0, $default = null ) {
275 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
279 * Set the batch size.
280 * @param int $s The number of operations to do in a batch
282 protected function setBatchSize( $s = 0 ) {
283 $this->mBatchSize = $s;
285 // If we support $mBatchSize, show the option.
286 // Used to be in addDefaultParams, but in order for that to
287 // work, subclasses would have to call this function in the constructor
288 // before they called parent::__construct which is just weird
289 // (and really wasn't done).
290 if ( $this->mBatchSize ) {
291 $this->addOption( 'batch-size', 'Run this many operations ' .
292 'per batch, default: ' . $this->mBatchSize, false, true );
293 if ( isset( $this->mParams['batch-size'] ) ) {
294 // This seems a little ugly...
295 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
301 * Get the script's name
302 * @return string
304 public function getName() {
305 return $this->mSelf;
309 * Return input from stdin.
310 * @param int $len The number of bytes to read. If null, just return the handle.
311 * Maintenance::STDIN_ALL returns the full length
312 * @return mixed
314 protected function getStdin( $len = null ) {
315 if ( $len == Maintenance::STDIN_ALL ) {
316 return file_get_contents( 'php://stdin' );
318 $f = fopen( 'php://stdin', 'rt' );
319 if ( !$len ) {
320 return $f;
322 $input = fgets( $f, $len );
323 fclose( $f );
325 return rtrim( $input );
329 * @return bool
331 public function isQuiet() {
332 return $this->mQuiet;
336 * Throw some output to the user. Scripts can call this with no fears,
337 * as we handle all --quiet stuff here
338 * @param string $out The text to show to the user
339 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
341 protected function output( $out, $channel = null ) {
342 if ( $this->mQuiet ) {
343 return;
345 if ( $channel === null ) {
346 $this->cleanupChanneled();
347 print $out;
348 } else {
349 $out = preg_replace( '/\n\z/', '', $out );
350 $this->outputChanneled( $out, $channel );
355 * Throw an error to the user. Doesn't respect --quiet, so don't use
356 * this for non-error output
357 * @param string $err The error to display
358 * @param int $die If > 0, go ahead and die out using this int as the code
360 protected function error( $err, $die = 0 ) {
361 $this->outputChanneled( false );
362 if ( PHP_SAPI == 'cli' ) {
363 fwrite( STDERR, $err . "\n" );
364 } else {
365 print $err;
367 $die = intval( $die );
368 if ( $die > 0 ) {
369 die( $die );
373 private $atLineStart = true;
374 private $lastChannel = null;
377 * Clean up channeled output. Output a newline if necessary.
379 public function cleanupChanneled() {
380 if ( !$this->atLineStart ) {
381 print "\n";
382 $this->atLineStart = true;
387 * Message outputter with channeled message support. Messages on the
388 * same channel are concatenated, but any intervening messages in another
389 * channel start a new line.
390 * @param string $msg The message without trailing newline
391 * @param string $channel Channel identifier or null for no
392 * channel. Channel comparison uses ===.
394 public function outputChanneled( $msg, $channel = null ) {
395 if ( $msg === false ) {
396 $this->cleanupChanneled();
398 return;
401 // End the current line if necessary
402 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
403 print "\n";
406 print $msg;
408 $this->atLineStart = false;
409 if ( $channel === null ) {
410 // For unchanneled messages, output trailing newline immediately
411 print "\n";
412 $this->atLineStart = true;
414 $this->lastChannel = $channel;
418 * Does the script need different DB access? By default, we give Maintenance
419 * scripts normal rights to the DB. Sometimes, a script needs admin rights
420 * access for a reason and sometimes they want no access. Subclasses should
421 * override and return one of the following values, as needed:
422 * Maintenance::DB_NONE - For no DB access at all
423 * Maintenance::DB_STD - For normal DB access, default
424 * Maintenance::DB_ADMIN - For admin DB access
425 * @return int
427 public function getDbType() {
428 return Maintenance::DB_STD;
432 * Add the default parameters to the scripts
434 protected function addDefaultParams() {
436 # Generic (non script dependant) options:
438 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
439 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
440 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
441 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
442 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
443 $this->addOption(
444 'memory-limit',
445 'Set a specific memory limit for the script, '
446 . '"max" for no limit or "default" to avoid changing it'
448 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
449 "http://en.wikipedia.org. This is sometimes necessary because " .
450 "server name detection may fail in command line scripts.", false, true );
451 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
453 # Save generic options to display them separately in help
454 $this->mGenericParameters = $this->mParams;
456 # Script dependant options:
458 // If we support a DB, show the options
459 if ( $this->getDbType() > 0 ) {
460 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
461 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
464 # Save additional script dependant options to display
465 # them separately in help
466 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
470 * @since 1.24
471 * @return Config
473 public function getConfig() {
474 if ( $this->config === null ) {
475 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
478 return $this->config;
482 * @since 1.24
483 * @param Config $config
485 public function setConfig( Config $config ) {
486 $this->config = $config;
490 * Run a child maintenance script. Pass all of the current arguments
491 * to it.
492 * @param string $maintClass A name of a child maintenance class
493 * @param string $classFile Full path of where the child is
494 * @return Maintenance
496 public function runChild( $maintClass, $classFile = null ) {
497 // Make sure the class is loaded first
498 if ( !class_exists( $maintClass ) ) {
499 if ( $classFile ) {
500 require_once $classFile;
502 if ( !class_exists( $maintClass ) ) {
503 $this->error( "Cannot spawn child: $maintClass" );
508 * @var $child Maintenance
510 $child = new $maintClass();
511 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
512 if ( !is_null( $this->mDb ) ) {
513 $child->setDB( $this->mDb );
516 return $child;
520 * Do some sanity checking and basic setup
522 public function setup() {
523 global $IP, $wgCommandLineMode, $wgRequestTime;
525 # Abort if called from a web server
526 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
527 $this->error( 'This script must be run from the command line', true );
530 if ( $IP === null ) {
531 $this->error( "\$IP not set, aborting!\n" .
532 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
535 # Make sure we can handle script parameters
536 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
537 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
540 // Send PHP warnings and errors to stderr instead of stdout.
541 // This aids in diagnosing problems, while keeping messages
542 // out of redirected output.
543 if ( ini_get( 'display_errors' ) ) {
544 ini_set( 'display_errors', 'stderr' );
547 $this->loadParamsAndArgs();
548 $this->maybeHelp();
550 # Set the memory limit
551 # Note we need to set it again later in cache LocalSettings changed it
552 $this->adjustMemoryLimit();
554 # Set max execution time to 0 (no limit). PHP.net says that
555 # "When running PHP from the command line the default setting is 0."
556 # But sometimes this doesn't seem to be the case.
557 ini_set( 'max_execution_time', 0 );
559 $wgRequestTime = microtime( true );
561 # Define us as being in MediaWiki
562 define( 'MEDIAWIKI', true );
564 $wgCommandLineMode = true;
566 # Turn off output buffering if it's on
567 while ( ob_get_level() > 0 ) {
568 ob_end_flush();
571 $this->validateParamsAndArgs();
575 * Normally we disable the memory_limit when running admin scripts.
576 * Some scripts may wish to actually set a limit, however, to avoid
577 * blowing up unexpectedly. We also support a --memory-limit option,
578 * to allow sysadmins to explicitly set one if they'd prefer to override
579 * defaults (or for people using Suhosin which yells at you for trying
580 * to disable the limits)
581 * @return string
583 public function memoryLimit() {
584 $limit = $this->getOption( 'memory-limit', 'max' );
585 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
586 return $limit;
590 * Adjusts PHP's memory limit to better suit our needs, if needed.
592 protected function adjustMemoryLimit() {
593 $limit = $this->memoryLimit();
594 if ( $limit == 'max' ) {
595 $limit = -1; // no memory limit
597 if ( $limit != 'default' ) {
598 ini_set( 'memory_limit', $limit );
603 * Activate the profiler (assuming $wgProfiler is set)
605 protected function activateProfiler() {
606 global $wgProfiler;
608 $output = $this->getOption( 'profiler' );
609 if ( $output && is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
610 $class = $wgProfiler['class'];
611 $profiler = new $class(
612 array( 'sampling' => 1, 'output' => $output ) + $wgProfiler
614 $profiler->setTemplated( true );
615 Profiler::replaceStubInstance( $profiler );
618 $trxProfiler = Profiler::instance()->getTransactionProfiler();
619 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
620 # Catch huge single updates that lead to slave lag
621 $trxProfiler->setExpectation( 'maxAffected', 1000, __METHOD__ );
625 * Clear all params and arguments.
627 public function clearParamsAndArgs() {
628 $this->mOptions = array();
629 $this->mArgs = array();
630 $this->mInputLoaded = false;
634 * Process command line arguments
635 * $mOptions becomes an array with keys set to the option names
636 * $mArgs becomes a zero-based array containing the non-option arguments
638 * @param string $self The name of the script, if any
639 * @param array $opts An array of options, in form of key=>value
640 * @param array $args An array of command line arguments
642 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
643 # If we were given opts or args, set those and return early
644 if ( $self ) {
645 $this->mSelf = $self;
646 $this->mInputLoaded = true;
648 if ( $opts ) {
649 $this->mOptions = $opts;
650 $this->mInputLoaded = true;
652 if ( $args ) {
653 $this->mArgs = $args;
654 $this->mInputLoaded = true;
657 # If we've already loaded input (either by user values or from $argv)
658 # skip on loading it again. The array_shift() will corrupt values if
659 # it's run again and again
660 if ( $this->mInputLoaded ) {
661 $this->loadSpecialVars();
663 return;
666 global $argv;
667 $this->mSelf = array_shift( $argv );
669 $options = array();
670 $args = array();
672 # Parse arguments
673 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
674 if ( $arg == '--' ) {
675 # End of options, remainder should be considered arguments
676 $arg = next( $argv );
677 while ( $arg !== false ) {
678 $args[] = $arg;
679 $arg = next( $argv );
681 break;
682 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
683 # Long options
684 $option = substr( $arg, 2 );
685 if ( array_key_exists( $option, $options ) ) {
686 $this->error( "\nERROR: $option parameter given twice\n" );
687 $this->maybeHelp( true );
689 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
690 $param = next( $argv );
691 if ( $param === false ) {
692 $this->error( "\nERROR: $option parameter needs a value after it\n" );
693 $this->maybeHelp( true );
695 $options[$option] = $param;
696 } else {
697 $bits = explode( '=', $option, 2 );
698 if ( count( $bits ) > 1 ) {
699 $option = $bits[0];
700 $param = $bits[1];
701 } else {
702 $param = 1;
704 $options[$option] = $param;
706 } elseif ( $arg == '-' ) {
707 # Lonely "-", often used to indicate stdin or stdout.
708 $args[] = $arg;
709 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
710 # Short options
711 $argLength = strlen( $arg );
712 for ( $p = 1; $p < $argLength; $p++ ) {
713 $option = $arg[$p];
714 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
715 $option = $this->mShortParamsMap[$option];
717 if ( array_key_exists( $option, $options ) ) {
718 $this->error( "\nERROR: $option parameter given twice\n" );
719 $this->maybeHelp( true );
721 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
722 $param = next( $argv );
723 if ( $param === false ) {
724 $this->error( "\nERROR: $option parameter needs a value after it\n" );
725 $this->maybeHelp( true );
727 $options[$option] = $param;
728 } else {
729 $options[$option] = 1;
732 } else {
733 $args[] = $arg;
737 $this->mOptions = $options;
738 $this->mArgs = $args;
739 $this->loadSpecialVars();
740 $this->mInputLoaded = true;
744 * Run some validation checks on the params, etc
746 protected function validateParamsAndArgs() {
747 $die = false;
748 # Check to make sure we've got all the required options
749 foreach ( $this->mParams as $opt => $info ) {
750 if ( $info['require'] && !$this->hasOption( $opt ) ) {
751 $this->error( "Param $opt required!" );
752 $die = true;
755 # Check arg list too
756 foreach ( $this->mArgList as $k => $info ) {
757 if ( $info['require'] && !$this->hasArg( $k ) ) {
758 $this->error( 'Argument <' . $info['name'] . '> required!' );
759 $die = true;
763 if ( $die ) {
764 $this->maybeHelp( true );
769 * Handle the special variables that are global to all scripts
771 protected function loadSpecialVars() {
772 if ( $this->hasOption( 'dbuser' ) ) {
773 $this->mDbUser = $this->getOption( 'dbuser' );
775 if ( $this->hasOption( 'dbpass' ) ) {
776 $this->mDbPass = $this->getOption( 'dbpass' );
778 if ( $this->hasOption( 'quiet' ) ) {
779 $this->mQuiet = true;
781 if ( $this->hasOption( 'batch-size' ) ) {
782 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
787 * Maybe show the help.
788 * @param bool $force Whether to force the help to show, default false
790 protected function maybeHelp( $force = false ) {
791 if ( !$force && !$this->hasOption( 'help' ) ) {
792 return;
795 $screenWidth = 80; // TODO: Calculate this!
796 $tab = " ";
797 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
799 ksort( $this->mParams );
800 $this->mQuiet = false;
802 // Description ...
803 if ( $this->mDescription ) {
804 $this->output( "\n" . $this->mDescription . "\n" );
806 $output = "\nUsage: php " . basename( $this->mSelf );
808 // ... append parameters ...
809 if ( $this->mParams ) {
810 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
813 // ... and append arguments.
814 if ( $this->mArgList ) {
815 $output .= ' ';
816 foreach ( $this->mArgList as $k => $arg ) {
817 if ( $arg['require'] ) {
818 $output .= '<' . $arg['name'] . '>';
819 } else {
820 $output .= '[' . $arg['name'] . ']';
822 if ( $k < count( $this->mArgList ) - 1 ) {
823 $output .= ' ';
827 $this->output( "$output\n\n" );
829 # TODO abstract some repetitive code below
831 // Generic parameters
832 $this->output( "Generic maintenance parameters:\n" );
833 foreach ( $this->mGenericParameters as $par => $info ) {
834 if ( $info['shortName'] !== false ) {
835 $par .= " (-{$info['shortName']})";
837 $this->output(
838 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
839 "\n$tab$tab" ) . "\n"
842 $this->output( "\n" );
844 $scriptDependantParams = $this->mDependantParameters;
845 if ( count( $scriptDependantParams ) > 0 ) {
846 $this->output( "Script dependant parameters:\n" );
847 // Parameters description
848 foreach ( $scriptDependantParams as $par => $info ) {
849 if ( $info['shortName'] !== false ) {
850 $par .= " (-{$info['shortName']})";
852 $this->output(
853 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
854 "\n$tab$tab" ) . "\n"
857 $this->output( "\n" );
860 // Script specific parameters not defined on construction by
861 // Maintenance::addDefaultParams()
862 $scriptSpecificParams = array_diff_key(
863 # all script parameters:
864 $this->mParams,
865 # remove the Maintenance default parameters:
866 $this->mGenericParameters,
867 $this->mDependantParameters
869 if ( count( $scriptSpecificParams ) > 0 ) {
870 $this->output( "Script specific parameters:\n" );
871 // Parameters description
872 foreach ( $scriptSpecificParams as $par => $info ) {
873 if ( $info['shortName'] !== false ) {
874 $par .= " (-{$info['shortName']})";
876 $this->output(
877 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
878 "\n$tab$tab" ) . "\n"
881 $this->output( "\n" );
884 // Print arguments
885 if ( count( $this->mArgList ) > 0 ) {
886 $this->output( "Arguments:\n" );
887 // Arguments description
888 foreach ( $this->mArgList as $info ) {
889 $openChar = $info['require'] ? '<' : '[';
890 $closeChar = $info['require'] ? '>' : ']';
891 $this->output(
892 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
893 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
896 $this->output( "\n" );
899 die( 1 );
903 * Handle some last-minute setup here.
905 public function finalSetup() {
906 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
907 global $wgDBadminuser, $wgDBadminpassword;
908 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
910 # Turn off output buffering again, it might have been turned on in the settings files
911 if ( ob_get_level() ) {
912 ob_end_flush();
914 # Same with these
915 $wgCommandLineMode = true;
917 # Override $wgServer
918 if ( $this->hasOption( 'server' ) ) {
919 $wgServer = $this->getOption( 'server', $wgServer );
922 # If these were passed, use them
923 if ( $this->mDbUser ) {
924 $wgDBadminuser = $this->mDbUser;
926 if ( $this->mDbPass ) {
927 $wgDBadminpassword = $this->mDbPass;
930 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
931 $wgDBuser = $wgDBadminuser;
932 $wgDBpassword = $wgDBadminpassword;
934 if ( $wgDBservers ) {
936 * @var $wgDBservers array
938 foreach ( $wgDBservers as $i => $server ) {
939 $wgDBservers[$i]['user'] = $wgDBuser;
940 $wgDBservers[$i]['password'] = $wgDBpassword;
943 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
944 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
945 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
947 LBFactory::destroyInstance();
950 // Per-script profiling; useful for debugging
951 $this->activateProfiler();
953 $this->afterFinalSetup();
955 $wgShowSQLErrors = true;
957 // @codingStandardsIgnoreStart Allow error suppression. wfSuppressWarnings()
958 // is not available.
959 @set_time_limit( 0 );
960 // @codingStandardsIgnoreStart
962 $this->adjustMemoryLimit();
966 * Execute a callback function at the end of initialisation
968 protected function afterFinalSetup() {
969 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
970 call_user_func( MW_CMDLINE_CALLBACK );
975 * Potentially debug globals. Originally a feature only
976 * for refreshLinks
978 public function globals() {
979 if ( $this->hasOption( 'globals' ) ) {
980 print_r( $GLOBALS );
985 * Generic setup for most installs. Returns the location of LocalSettings
986 * @return string
988 public function loadSettings() {
989 global $wgCommandLineMode, $IP;
991 if ( isset( $this->mOptions['conf'] ) ) {
992 $settingsFile = $this->mOptions['conf'];
993 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
994 $settingsFile = MW_CONFIG_FILE;
995 } else {
996 $settingsFile = "$IP/LocalSettings.php";
998 if ( isset( $this->mOptions['wiki'] ) ) {
999 $bits = explode( '-', $this->mOptions['wiki'] );
1000 if ( count( $bits ) == 1 ) {
1001 $bits[] = '';
1003 define( 'MW_DB', $bits[0] );
1004 define( 'MW_PREFIX', $bits[1] );
1007 if ( !is_readable( $settingsFile ) ) {
1008 $this->error( "A copy of your installation's LocalSettings.php\n" .
1009 "must exist and be readable in the source directory.\n" .
1010 "Use --conf to specify it.", true );
1012 $wgCommandLineMode = true;
1014 return $settingsFile;
1018 * Support function for cleaning up redundant text records
1019 * @param bool $delete Whether or not to actually delete the records
1020 * @author Rob Church <robchur@gmail.com>
1022 public function purgeRedundantText( $delete = true ) {
1023 # Data should come off the master, wrapped in a transaction
1024 $dbw = $this->getDB( DB_MASTER );
1025 $dbw->begin( __METHOD__ );
1027 # Get "active" text records from the revisions table
1028 $this->output( 'Searching for active text records in revisions table...' );
1029 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
1030 foreach ( $res as $row ) {
1031 $cur[] = $row->rev_text_id;
1033 $this->output( "done.\n" );
1035 # Get "active" text records from the archive table
1036 $this->output( 'Searching for active text records in archive table...' );
1037 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
1038 foreach ( $res as $row ) {
1039 # old pre-MW 1.5 records can have null ar_text_id's.
1040 if ( $row->ar_text_id !== null ) {
1041 $cur[] = $row->ar_text_id;
1044 $this->output( "done.\n" );
1046 # Get the IDs of all text records not in these sets
1047 $this->output( 'Searching for inactive text records...' );
1048 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1049 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__, array( 'DISTINCT' ) );
1050 $old = array();
1051 foreach ( $res as $row ) {
1052 $old[] = $row->old_id;
1054 $this->output( "done.\n" );
1056 # Inform the user of what we're going to do
1057 $count = count( $old );
1058 $this->output( "$count inactive items found.\n" );
1060 # Delete as appropriate
1061 if ( $delete && $count ) {
1062 $this->output( 'Deleting...' );
1063 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__ );
1064 $this->output( "done.\n" );
1067 # Done
1068 $dbw->commit( __METHOD__ );
1072 * Get the maintenance directory.
1073 * @return string
1075 protected function getDir() {
1076 return __DIR__;
1080 * Returns a database to be used by current maintenance script. It can be set by setDB().
1081 * If not set, wfGetDB() will be used.
1082 * This function has the same parameters as wfGetDB()
1084 * @return DatabaseBase
1086 protected function getDB( $db, $groups = array(), $wiki = false ) {
1087 if ( is_null( $this->mDb ) ) {
1088 return wfGetDB( $db, $groups, $wiki );
1089 } else {
1090 return $this->mDb;
1095 * Sets database object to be returned by getDB().
1097 * @param DatabaseBase $db Database object to be used
1099 public function setDB( $db ) {
1100 $this->mDb = $db;
1104 * Lock the search index
1105 * @param DatabaseBase &$db
1107 private function lockSearchindex( $db ) {
1108 $write = array( 'searchindex' );
1109 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user', 'page_restrictions' );
1110 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1114 * Unlock the tables
1115 * @param DatabaseBase &$db
1117 private function unlockSearchindex( $db ) {
1118 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1122 * Unlock and lock again
1123 * Since the lock is low-priority, queued reads will be able to complete
1124 * @param DatabaseBase &$db
1126 private function relockSearchindex( $db ) {
1127 $this->unlockSearchindex( $db );
1128 $this->lockSearchindex( $db );
1132 * Perform a search index update with locking
1133 * @param int $maxLockTime The maximum time to keep the search index locked.
1134 * @param string $callback The function that will update the function.
1135 * @param DatabaseBase $dbw
1136 * @param array $results
1138 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1139 $lockTime = time();
1141 # Lock searchindex
1142 if ( $maxLockTime ) {
1143 $this->output( " --- Waiting for lock ---" );
1144 $this->lockSearchindex( $dbw );
1145 $lockTime = time();
1146 $this->output( "\n" );
1149 # Loop through the results and do a search update
1150 foreach ( $results as $row ) {
1151 # Allow reads to be processed
1152 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1153 $this->output( " --- Relocking ---" );
1154 $this->relockSearchindex( $dbw );
1155 $lockTime = time();
1156 $this->output( "\n" );
1158 call_user_func( $callback, $dbw, $row );
1161 # Unlock searchindex
1162 if ( $maxLockTime ) {
1163 $this->output( " --- Unlocking --" );
1164 $this->unlockSearchindex( $dbw );
1165 $this->output( "\n" );
1170 * Update the searchindex table for a given pageid
1171 * @param DatabaseBase $dbw A database write handle
1172 * @param int $pageId The page ID to update.
1173 * @return null|string
1175 public function updateSearchIndexForPage( $dbw, $pageId ) {
1176 // Get current revision
1177 $rev = Revision::loadFromPageId( $dbw, $pageId );
1178 $title = null;
1179 if ( $rev ) {
1180 $titleObj = $rev->getTitle();
1181 $title = $titleObj->getPrefixedDBkey();
1182 $this->output( "$title..." );
1183 # Update searchindex
1184 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1185 $u->doUpdate();
1186 $this->output( "\n" );
1189 return $title;
1193 * Wrapper for posix_isatty()
1194 * We default as considering stdin a tty (for nice readline methods)
1195 * but treating stout as not a tty to avoid color codes
1197 * @param mixed $fd File descriptor
1198 * @return bool
1200 public static function posix_isatty( $fd ) {
1201 if ( !function_exists( 'posix_isatty' ) ) {
1202 return !$fd;
1203 } else {
1204 return posix_isatty( $fd );
1209 * Prompt the console for input
1210 * @param string $prompt What to begin the line with, like '> '
1211 * @return string Response
1213 public static function readconsole( $prompt = '> ' ) {
1214 static $isatty = null;
1215 if ( is_null( $isatty ) ) {
1216 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1219 if ( $isatty && function_exists( 'readline' ) ) {
1220 $resp = readline( $prompt );
1221 if ( $resp === null ) {
1222 // Workaround for https://github.com/facebook/hhvm/issues/4776
1223 return false;
1224 } else {
1225 return $resp;
1227 } else {
1228 if ( $isatty ) {
1229 $st = self::readlineEmulation( $prompt );
1230 } else {
1231 if ( feof( STDIN ) ) {
1232 $st = false;
1233 } else {
1234 $st = fgets( STDIN, 1024 );
1237 if ( $st === false ) {
1238 return false;
1240 $resp = trim( $st );
1242 return $resp;
1247 * Emulate readline()
1248 * @param string $prompt What to begin the line with, like '> '
1249 * @return string
1251 private static function readlineEmulation( $prompt ) {
1252 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1253 if ( !wfIsWindows() && $bash ) {
1254 $retval = false;
1255 $encPrompt = wfEscapeShellArg( $prompt );
1256 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1257 $encCommand = wfEscapeShellArg( $command );
1258 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1260 if ( $retval == 0 ) {
1261 return $line;
1262 } elseif ( $retval == 127 ) {
1263 // Couldn't execute bash even though we thought we saw it.
1264 // Shell probably spit out an error message, sorry :(
1265 // Fall through to fgets()...
1266 } else {
1267 // EOF/ctrl+D
1268 return false;
1272 // Fallback... we'll have no editing controls, EWWW
1273 if ( feof( STDIN ) ) {
1274 return false;
1276 print $prompt;
1278 return fgets( STDIN, 1024 );
1283 * Fake maintenance wrapper, mostly used for the web installer/updater
1285 class FakeMaintenance extends Maintenance {
1286 protected $mSelf = "FakeMaintenanceScript";
1288 public function execute() {
1289 return;
1294 * Class for scripts that perform database maintenance and want to log the
1295 * update in `updatelog` so we can later skip it
1297 abstract class LoggedUpdateMaintenance extends Maintenance {
1298 public function __construct() {
1299 parent::__construct();
1300 $this->addOption( 'force', 'Run the update even if it was completed already' );
1301 $this->setBatchSize( 200 );
1304 public function execute() {
1305 $db = $this->getDB( DB_MASTER );
1306 $key = $this->getUpdateKey();
1308 if ( !$this->hasOption( 'force' )
1309 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ )
1311 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1313 return true;
1316 if ( !$this->doDBUpdates() ) {
1317 return false;
1320 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) ) {
1321 return true;
1322 } else {
1323 $this->output( $this->updatelogFailedMessage() . "\n" );
1325 return false;
1330 * Message to show that the update was done already and was just skipped
1331 * @return string
1333 protected function updateSkippedMessage() {
1334 $key = $this->getUpdateKey();
1336 return "Update '{$key}' already logged as completed.";
1340 * Message to show that the update log was unable to log the completion of this update
1341 * @return string
1343 protected function updatelogFailedMessage() {
1344 $key = $this->getUpdateKey();
1346 return "Unable to log update '{$key}' as completed.";
1350 * Do the actual work. All child classes will need to implement this.
1351 * Return true to log the update as done or false (usually on failure).
1352 * @return bool
1354 abstract protected function doDBUpdates();
1357 * Get the update key name to go in the update log table
1358 * @return string
1360 abstract protected function getUpdateKey();