Pass __METHOD__ to DatabaseBase::commit() and DatabaseBase::rollback()
[mediawiki.git] / maintenance / Maintenance.php
blobfda12f9e7e6224018d2e6b078ace8b7b0b64032f
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 /**
24 * @defgroup MaintenanceArchive Maintenance archives
25 * @ingroup Maintenance
28 // Define this so scripts can easily find doMaintenance.php
29 define( 'RUN_MAINTENANCE_IF_MAIN', dirname( __FILE__ ) . '/doMaintenance.php' );
30 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
32 $maintClass = false;
34 // Make sure we're on PHP5 or better
35 if ( !function_exists( 'version_compare' ) || version_compare( PHP_VERSION, '5.2.3' ) < 0 ) {
36 require_once( dirname( __FILE__ ) . '/../includes/PHPVersionError.php' );
37 wfPHPVersionError( 'cli' );
40 /**
41 * Abstract maintenance class for quickly writing and churning out
42 * maintenance scripts with minimal effort. All that _must_ be defined
43 * is the execute() method. See docs/maintenance.txt for more info
44 * and a quick demo of how to use it.
46 * @author Chad Horohoe <chad@anyonecanedit.org>
47 * @since 1.16
48 * @ingroup Maintenance
50 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 = array();
66 // Array of mapping short parameters to long ones
67 protected $mShortParamsMap = array();
69 // Array of desired args
70 protected $mArgList = array();
72 // This is the list of options that were actually passed
73 protected $mOptions = array();
75 // This is the list of arguments that were actually passed
76 protected $mArgs = array();
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
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 = array();
101 // Generic options which might or not be supported by the script
102 private $mDependantParameters = array();
104 // Used by getDD() / setDB()
105 private $mDb = null;
108 * List of all the core maintenance scripts. This is added
109 * to scripts added by extensions in $wgMaintenanceScripts
110 * and returned by getMaintenanceScripts()
112 protected static $mCoreScripts = null;
115 * Default constructor. Children should call this *first* if implementing
116 * their own constructors
118 public function __construct() {
119 // Setup $IP, using MW_INSTALL_PATH if it exists
120 global $IP;
121 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
122 ? getenv( 'MW_INSTALL_PATH' )
123 : realpath( dirname( __FILE__ ) . '/..' );
125 $this->addDefaultParams();
126 register_shutdown_function( array( $this, 'outputChanneled' ), false );
130 * Should we execute the maintenance script, or just allow it to be included
131 * as a standalone class? It checks that the call stack only includes this
132 * function and "requires" (meaning was called from the file scope)
134 * @return Boolean
136 public static function shouldExecute() {
137 $bt = debug_backtrace();
138 $count = count( $bt );
139 if ( $count < 2 ) {
140 return false; // sanity
142 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
143 return false; // last call should be to this function
145 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
146 for( $i=1; $i < $count; $i++ ) {
147 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
148 return false; // previous calls should all be "requires"
151 return true;
155 * Do the actual work. All child classes will need to implement this
157 abstract public function execute();
160 * Add a parameter to the script. Will be displayed on --help
161 * with the associated description
163 * @param $name String: the name of the param (help, version, etc)
164 * @param $description String: the description of the param to show on --help
165 * @param $required Boolean: is the param required?
166 * @param $withArg Boolean: is an argument required with this option?
167 * @param $shortName String: character to use as short name
169 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
170 $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
171 if ( $shortName !== false ) {
172 $this->mShortParamsMap[$shortName] = $name;
177 * Checks to see if a particular param exists.
178 * @param $name String: the name of the param
179 * @return Boolean
181 protected function hasOption( $name ) {
182 return isset( $this->mOptions[$name] );
186 * Get an option, or return the default
187 * @param $name String: the name of the param
188 * @param $default Mixed: anything you want, default null
189 * @return Mixed
191 protected function getOption( $name, $default = null ) {
192 if ( $this->hasOption( $name ) ) {
193 return $this->mOptions[$name];
194 } else {
195 // Set it so we don't have to provide the default again
196 $this->mOptions[$name] = $default;
197 return $this->mOptions[$name];
202 * Add some args that are needed
203 * @param $arg String: name of the arg, like 'start'
204 * @param $description String: short description of the arg
205 * @param $required Boolean: is this required?
207 protected function addArg( $arg, $description, $required = true ) {
208 $this->mArgList[] = array(
209 'name' => $arg,
210 'desc' => $description,
211 'require' => $required
216 * Remove an option. Useful for removing options that won't be used in your script.
217 * @param $name String: the option to remove.
219 protected function deleteOption( $name ) {
220 unset( $this->mParams[$name] );
224 * Set the description text.
225 * @param $text String: the text of the description
227 protected function addDescription( $text ) {
228 $this->mDescription = $text;
232 * Does a given argument exist?
233 * @param $argId Integer: the integer value (from zero) for the arg
234 * @return Boolean
236 protected function hasArg( $argId = 0 ) {
237 return isset( $this->mArgs[$argId] );
241 * Get an argument.
242 * @param $argId Integer: the integer value (from zero) for the arg
243 * @param $default Mixed: the default if it doesn't exist
244 * @return mixed
246 protected function getArg( $argId = 0, $default = null ) {
247 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
251 * Set the batch size.
252 * @param $s Integer: the number of operations to do in a batch
254 protected function setBatchSize( $s = 0 ) {
255 $this->mBatchSize = $s;
257 // If we support $mBatchSize, show the option.
258 // Used to be in addDefaultParams, but in order for that to
259 // work, subclasses would have to call this function in the constructor
260 // before they called parent::__construct which is just weird
261 // (and really wasn't done).
262 if ( $this->mBatchSize ) {
263 $this->addOption( 'batch-size', 'Run this many operations ' .
264 'per batch, default: ' . $this->mBatchSize, false, true );
265 if ( isset( $this->mParams['batch-size'] ) ) {
266 // This seems a little ugly...
267 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
273 * Get the script's name
274 * @return String
276 public function getName() {
277 return $this->mSelf;
281 * Return input from stdin.
282 * @param $len Integer: the number of bytes to read. If null,
283 * just return the handle. Maintenance::STDIN_ALL returns
284 * the full length
285 * @return Mixed
287 protected function getStdin( $len = null ) {
288 if ( $len == Maintenance::STDIN_ALL ) {
289 return file_get_contents( 'php://stdin' );
291 $f = fopen( 'php://stdin', 'rt' );
292 if ( !$len ) {
293 return $f;
295 $input = fgets( $f, $len );
296 fclose( $f );
297 return rtrim( $input );
301 * @return bool
303 public function isQuiet() {
304 return $this->mQuiet;
308 * Throw some output to the user. Scripts can call this with no fears,
309 * as we handle all --quiet stuff here
310 * @param $out String: the text to show to the user
311 * @param $channel Mixed: unique identifier for the channel. See
312 * function outputChanneled.
314 protected function output( $out, $channel = null ) {
315 if ( $this->mQuiet ) {
316 return;
318 if ( $channel === null ) {
319 $this->cleanupChanneled();
320 if( php_sapi_name() == 'cli' ) {
321 fwrite( STDOUT, $out );
322 } else {
323 print( $out );
325 } else {
326 $out = preg_replace( '/\n\z/', '', $out );
327 $this->outputChanneled( $out, $channel );
332 * Throw an error to the user. Doesn't respect --quiet, so don't use
333 * this for non-error output
334 * @param $err String: the error to display
335 * @param $die Int: if > 0, go ahead and die out using this int as the code
337 protected function error( $err, $die = 0 ) {
338 $this->outputChanneled( false );
339 if ( php_sapi_name() == 'cli' ) {
340 fwrite( STDERR, $err . "\n" );
341 } else {
342 print $err;
344 $die = intval( $die );
345 if ( $die > 0 ) {
346 die( $die );
350 private $atLineStart = true;
351 private $lastChannel = null;
354 * Clean up channeled output. Output a newline if necessary.
356 public function cleanupChanneled() {
357 if ( !$this->atLineStart ) {
358 if( php_sapi_name() == 'cli' ) {
359 fwrite( STDOUT, "\n" );
360 } else {
361 print "\n";
363 $this->atLineStart = true;
368 * Message outputter with channeled message support. Messages on the
369 * same channel are concatenated, but any intervening messages in another
370 * channel start a new line.
371 * @param $msg String: the message without trailing newline
372 * @param $channel string Channel identifier or null for no
373 * channel. Channel comparison uses ===.
375 public function outputChanneled( $msg, $channel = null ) {
376 if ( $msg === false ) {
377 $this->cleanupChanneled();
378 return;
381 $cli = php_sapi_name() == 'cli';
383 // End the current line if necessary
384 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
385 if( $cli ) {
386 fwrite( STDOUT, "\n" );
387 } else {
388 print "\n";
392 if( $cli ) {
393 fwrite( STDOUT, $msg );
394 } else {
395 print $msg;
398 $this->atLineStart = false;
399 if ( $channel === null ) {
400 // For unchanneled messages, output trailing newline immediately
401 if( $cli ) {
402 fwrite( STDOUT, "\n" );
403 } else {
404 print "\n";
406 $this->atLineStart = true;
408 $this->lastChannel = $channel;
412 * Does the script need different DB access? By default, we give Maintenance
413 * scripts normal rights to the DB. Sometimes, a script needs admin rights
414 * access for a reason and sometimes they want no access. Subclasses should
415 * override and return one of the following values, as needed:
416 * Maintenance::DB_NONE - For no DB access at all
417 * Maintenance::DB_STD - For normal DB access, default
418 * Maintenance::DB_ADMIN - For admin DB access
419 * @return Integer
421 public function getDbType() {
422 return Maintenance::DB_STD;
426 * Add the default parameters to the scripts
428 protected function addDefaultParams() {
430 # Generic (non script dependant) options:
432 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
433 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
434 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
435 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
436 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
437 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
438 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
439 "http://en.wikipedia.org. This is sometimes necessary because " .
440 "server name detection may fail in command line scripts.", false, true );
442 # Save generic options to display them separately in help
443 $this->mGenericParameters = $this->mParams ;
445 # Script dependant options:
447 // If we support a DB, show the options
448 if ( $this->getDbType() > 0 ) {
449 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
450 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
453 # Save additional script dependant options to display
454 # them separately in help
455 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
459 * Run a child maintenance script. Pass all of the current arguments
460 * to it.
461 * @param $maintClass String: a name of a child maintenance class
462 * @param $classFile String: full path of where the child is
463 * @return Maintenance child
465 public function runChild( $maintClass, $classFile = null ) {
466 // Make sure the class is loaded first
467 if ( !MWInit::classExists( $maintClass ) ) {
468 if ( $classFile ) {
469 require_once( $classFile );
471 if ( !MWInit::classExists( $maintClass ) ) {
472 $this->error( "Cannot spawn child: $maintClass" );
477 * @var $child Maintenance
479 $child = new $maintClass();
480 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
481 if ( !is_null( $this->mDb ) ) {
482 $child->setDB( $this->mDb );
484 return $child;
488 * Do some sanity checking and basic setup
490 public function setup() {
491 global $wgCommandLineMode, $wgRequestTime;
493 # Abort if called from a web server
494 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
495 $this->error( 'This script must be run from the command line', true );
498 # Make sure we can handle script parameters
499 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
500 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
503 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
504 // Send PHP warnings and errors to stderr instead of stdout.
505 // This aids in diagnosing problems, while keeping messages
506 // out of redirected output.
507 if ( ini_get( 'display_errors' ) ) {
508 ini_set( 'display_errors', 'stderr' );
511 // Don't touch the setting on earlier versions of PHP,
512 // as setting it would disable output if you'd wanted it.
514 // Note that exceptions are also sent to stderr when
515 // command-line mode is on, regardless of PHP version.
518 $this->loadParamsAndArgs();
519 $this->maybeHelp();
521 # Set the memory limit
522 # Note we need to set it again later in cache LocalSettings changed it
523 $this->adjustMemoryLimit();
525 # Set max execution time to 0 (no limit). PHP.net says that
526 # "When running PHP from the command line the default setting is 0."
527 # But sometimes this doesn't seem to be the case.
528 ini_set( 'max_execution_time', 0 );
530 $wgRequestTime = microtime( true );
532 # Define us as being in MediaWiki
533 define( 'MEDIAWIKI', true );
535 $wgCommandLineMode = true;
536 # Turn off output buffering if it's on
537 @ob_end_flush();
539 $this->validateParamsAndArgs();
543 * Normally we disable the memory_limit when running admin scripts.
544 * Some scripts may wish to actually set a limit, however, to avoid
545 * blowing up unexpectedly. We also support a --memory-limit option,
546 * to allow sysadmins to explicitly set one if they'd prefer to override
547 * defaults (or for people using Suhosin which yells at you for trying
548 * to disable the limits)
549 * @return string
551 public function memoryLimit() {
552 $limit = $this->getOption( 'memory-limit', 'max' );
553 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
554 return $limit;
558 * Adjusts PHP's memory limit to better suit our needs, if needed.
560 protected function adjustMemoryLimit() {
561 $limit = $this->memoryLimit();
562 if ( $limit == 'max' ) {
563 $limit = -1; // no memory limit
565 if ( $limit != 'default' ) {
566 ini_set( 'memory_limit', $limit );
571 * Clear all params and arguments.
573 public function clearParamsAndArgs() {
574 $this->mOptions = array();
575 $this->mArgs = array();
576 $this->mInputLoaded = false;
580 * Process command line arguments
581 * $mOptions becomes an array with keys set to the option names
582 * $mArgs becomes a zero-based array containing the non-option arguments
584 * @param $self String The name of the script, if any
585 * @param $opts Array An array of options, in form of key=>value
586 * @param $args Array An array of command line arguments
588 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
589 # If we were given opts or args, set those and return early
590 if ( $self ) {
591 $this->mSelf = $self;
592 $this->mInputLoaded = true;
594 if ( $opts ) {
595 $this->mOptions = $opts;
596 $this->mInputLoaded = true;
598 if ( $args ) {
599 $this->mArgs = $args;
600 $this->mInputLoaded = true;
603 # If we've already loaded input (either by user values or from $argv)
604 # skip on loading it again. The array_shift() will corrupt values if
605 # it's run again and again
606 if ( $this->mInputLoaded ) {
607 $this->loadSpecialVars();
608 return;
611 global $argv;
612 $this->mSelf = array_shift( $argv );
614 $options = array();
615 $args = array();
617 # Parse arguments
618 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
619 if ( $arg == '--' ) {
620 # End of options, remainder should be considered arguments
621 $arg = next( $argv );
622 while ( $arg !== false ) {
623 $args[] = $arg;
624 $arg = next( $argv );
626 break;
627 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
628 # Long options
629 $option = substr( $arg, 2 );
630 if ( array_key_exists( $option, $options ) ) {
631 $this->error( "\nERROR: $option parameter given twice\n" );
632 $this->maybeHelp( true );
634 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
635 $param = next( $argv );
636 if ( $param === false ) {
637 $this->error( "\nERROR: $option parameter needs a value after it\n" );
638 $this->maybeHelp( true );
640 $options[$option] = $param;
641 } else {
642 $bits = explode( '=', $option, 2 );
643 if ( count( $bits ) > 1 ) {
644 $option = $bits[0];
645 $param = $bits[1];
646 } else {
647 $param = 1;
649 $options[$option] = $param;
651 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
652 # Short options
653 for ( $p = 1; $p < strlen( $arg ); $p++ ) {
654 $option = $arg { $p } ;
655 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
656 $option = $this->mShortParamsMap[$option];
658 if ( array_key_exists( $option, $options ) ) {
659 $this->error( "\nERROR: $option parameter given twice\n" );
660 $this->maybeHelp( true );
662 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
663 $param = next( $argv );
664 if ( $param === false ) {
665 $this->error( "\nERROR: $option parameter needs a value after it\n" );
666 $this->maybeHelp( true );
668 $options[$option] = $param;
669 } else {
670 $options[$option] = 1;
673 } else {
674 $args[] = $arg;
678 $this->mOptions = $options;
679 $this->mArgs = $args;
680 $this->loadSpecialVars();
681 $this->mInputLoaded = true;
685 * Run some validation checks on the params, etc
687 protected function validateParamsAndArgs() {
688 $die = false;
689 # Check to make sure we've got all the required options
690 foreach ( $this->mParams as $opt => $info ) {
691 if ( $info['require'] && !$this->hasOption( $opt ) ) {
692 $this->error( "Param $opt required!" );
693 $die = true;
696 # Check arg list too
697 foreach ( $this->mArgList as $k => $info ) {
698 if ( $info['require'] && !$this->hasArg( $k ) ) {
699 $this->error( 'Argument <' . $info['name'] . '> required!' );
700 $die = true;
704 if ( $die ) {
705 $this->maybeHelp( true );
710 * Handle the special variables that are global to all scripts
712 protected function loadSpecialVars() {
713 if ( $this->hasOption( 'dbuser' ) ) {
714 $this->mDbUser = $this->getOption( 'dbuser' );
716 if ( $this->hasOption( 'dbpass' ) ) {
717 $this->mDbPass = $this->getOption( 'dbpass' );
719 if ( $this->hasOption( 'quiet' ) ) {
720 $this->mQuiet = true;
722 if ( $this->hasOption( 'batch-size' ) ) {
723 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
728 * Maybe show the help.
729 * @param $force boolean Whether to force the help to show, default false
731 protected function maybeHelp( $force = false ) {
732 if( !$force && !$this->hasOption( 'help' ) ) {
733 return;
736 $screenWidth = 80; // TODO: Caculate this!
737 $tab = " ";
738 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
740 ksort( $this->mParams );
741 $this->mQuiet = false;
743 // Description ...
744 if ( $this->mDescription ) {
745 $this->output( "\n" . $this->mDescription . "\n" );
747 $output = "\nUsage: php " . basename( $this->mSelf );
749 // ... append parameters ...
750 if ( $this->mParams ) {
751 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
754 // ... and append arguments.
755 if ( $this->mArgList ) {
756 $output .= ' ';
757 foreach ( $this->mArgList as $k => $arg ) {
758 if ( $arg['require'] ) {
759 $output .= '<' . $arg['name'] . '>';
760 } else {
761 $output .= '[' . $arg['name'] . ']';
763 if ( $k < count( $this->mArgList ) - 1 )
764 $output .= ' ';
767 $this->output( "$output\n\n" );
769 # TODO abstract some repetitive code below
771 // Generic parameters
772 $this->output( "Generic maintenance parameters:\n" );
773 foreach ( $this->mGenericParameters as $par => $info ) {
774 if ( $info['shortName'] !== false ) {
775 $par .= " (-{$info['shortName']})";
777 $this->output(
778 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
779 "\n$tab$tab" ) . "\n"
782 $this->output( "\n" );
784 $scriptDependantParams = $this->mDependantParameters;
785 if( count($scriptDependantParams) > 0 ) {
786 $this->output( "Script dependant parameters:\n" );
787 // Parameters description
788 foreach ( $scriptDependantParams as $par => $info ) {
789 if ( $info['shortName'] !== false ) {
790 $par .= " (-{$info['shortName']})";
792 $this->output(
793 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
794 "\n$tab$tab" ) . "\n"
797 $this->output( "\n" );
801 // Script specific parameters not defined on construction by
802 // Maintenance::addDefaultParams()
803 $scriptSpecificParams = array_diff_key(
804 # all script parameters:
805 $this->mParams,
806 # remove the Maintenance default parameters:
807 $this->mGenericParameters,
808 $this->mDependantParameters
810 if( count($scriptSpecificParams) > 0 ) {
811 $this->output( "Script specific parameters:\n" );
812 // Parameters description
813 foreach ( $scriptSpecificParams as $par => $info ) {
814 if ( $info['shortName'] !== false ) {
815 $par .= " (-{$info['shortName']})";
817 $this->output(
818 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
819 "\n$tab$tab" ) . "\n"
822 $this->output( "\n" );
825 // Print arguments
826 if( count( $this->mArgList ) > 0 ) {
827 $this->output( "Arguments:\n" );
828 // Arguments description
829 foreach ( $this->mArgList as $info ) {
830 $openChar = $info['require'] ? '<' : '[';
831 $closeChar = $info['require'] ? '>' : ']';
832 $this->output(
833 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
834 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
837 $this->output( "\n" );
840 die( 1 );
844 * Handle some last-minute setup here.
846 public function finalSetup() {
847 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
848 global $wgDBadminuser, $wgDBadminpassword;
849 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
851 # Turn off output buffering again, it might have been turned on in the settings files
852 if ( ob_get_level() ) {
853 ob_end_flush();
855 # Same with these
856 $wgCommandLineMode = true;
858 # Override $wgServer
859 if( $this->hasOption( 'server') ) {
860 $wgServer = $this->getOption( 'server', $wgServer );
863 # If these were passed, use them
864 if ( $this->mDbUser ) {
865 $wgDBadminuser = $this->mDbUser;
867 if ( $this->mDbPass ) {
868 $wgDBadminpassword = $this->mDbPass;
871 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
872 $wgDBuser = $wgDBadminuser;
873 $wgDBpassword = $wgDBadminpassword;
875 if ( $wgDBservers ) {
877 * @var $wgDBservers array
879 foreach ( $wgDBservers as $i => $server ) {
880 $wgDBservers[$i]['user'] = $wgDBuser;
881 $wgDBservers[$i]['password'] = $wgDBpassword;
884 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
885 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
886 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
888 LBFactory::destroyInstance();
891 $this->afterFinalSetup();
893 $wgShowSQLErrors = true;
894 @set_time_limit( 0 );
895 $this->adjustMemoryLimit();
899 * Execute a callback function at the end of initialisation
901 protected function afterFinalSetup() {
902 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
903 call_user_func( MW_CMDLINE_CALLBACK );
908 * Potentially debug globals. Originally a feature only
909 * for refreshLinks
911 public function globals() {
912 if ( $this->hasOption( 'globals' ) ) {
913 print_r( $GLOBALS );
918 * Generic setup for most installs. Returns the location of LocalSettings
919 * @return String
921 public function loadSettings() {
922 global $wgCommandLineMode, $IP;
924 if ( isset( $this->mOptions['conf'] ) ) {
925 $settingsFile = $this->mOptions['conf'];
926 } elseif ( defined("MW_CONFIG_FILE") ) {
927 $settingsFile = MW_CONFIG_FILE;
928 } else {
929 $settingsFile = "$IP/LocalSettings.php";
931 if ( isset( $this->mOptions['wiki'] ) ) {
932 $bits = explode( '-', $this->mOptions['wiki'] );
933 if ( count( $bits ) == 1 ) {
934 $bits[] = '';
936 define( 'MW_DB', $bits[0] );
937 define( 'MW_PREFIX', $bits[1] );
940 if ( !is_readable( $settingsFile ) ) {
941 $this->error( "A copy of your installation's LocalSettings.php\n" .
942 "must exist and be readable in the source directory.\n" .
943 "Use --conf to specify it." , true );
945 $wgCommandLineMode = true;
946 return $settingsFile;
950 * Support function for cleaning up redundant text records
951 * @param $delete Boolean: whether or not to actually delete the records
952 * @author Rob Church <robchur@gmail.com>
954 public function purgeRedundantText( $delete = true ) {
955 # Data should come off the master, wrapped in a transaction
956 $dbw = $this->getDB( DB_MASTER );
957 $dbw->begin( __METHOD__ );
959 $tbl_arc = $dbw->tableName( 'archive' );
960 $tbl_rev = $dbw->tableName( 'revision' );
961 $tbl_txt = $dbw->tableName( 'text' );
963 # Get "active" text records from the revisions table
964 $this->output( 'Searching for active text records in revisions table...' );
965 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
966 foreach ( $res as $row ) {
967 $cur[] = $row->rev_text_id;
969 $this->output( "done.\n" );
971 # Get "active" text records from the archive table
972 $this->output( 'Searching for active text records in archive table...' );
973 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
974 foreach ( $res as $row ) {
975 $cur[] = $row->ar_text_id;
977 $this->output( "done.\n" );
979 # Get the IDs of all text records not in these sets
980 $this->output( 'Searching for inactive text records...' );
981 $set = implode( ', ', $cur );
982 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
983 $old = array();
984 foreach ( $res as $row ) {
985 $old[] = $row->old_id;
987 $this->output( "done.\n" );
989 # Inform the user of what we're going to do
990 $count = count( $old );
991 $this->output( "$count inactive items found.\n" );
993 # Delete as appropriate
994 if ( $delete && $count ) {
995 $this->output( 'Deleting...' );
996 $set = implode( ', ', $old );
997 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
998 $this->output( "done.\n" );
1001 # Done
1002 $dbw->commit( __METHOD__ );
1006 * Get the maintenance directory.
1007 * @return string
1009 protected function getDir() {
1010 return dirname( __FILE__ );
1014 * Get the list of available maintenance scripts. Note
1015 * that if you call this _before_ calling doMaintenance
1016 * you won't have any extensions in it yet
1017 * @return Array
1019 public static function getMaintenanceScripts() {
1020 global $wgMaintenanceScripts;
1021 return $wgMaintenanceScripts + self::getCoreScripts();
1025 * Return all of the core maintenance scripts
1026 * @return array
1028 protected static function getCoreScripts() {
1029 if ( !self::$mCoreScripts ) {
1030 $paths = array(
1031 dirname( __FILE__ ),
1032 dirname( __FILE__ ) . '/language',
1033 dirname( __FILE__ ) . '/storage',
1035 self::$mCoreScripts = array();
1036 foreach ( $paths as $p ) {
1037 $handle = opendir( $p );
1038 while ( ( $file = readdir( $handle ) ) !== false ) {
1039 if ( $file == 'Maintenance.php' ) {
1040 continue;
1042 $file = $p . '/' . $file;
1043 if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
1044 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1045 continue;
1047 require( $file );
1048 $vars = get_defined_vars();
1049 if ( array_key_exists( 'maintClass', $vars ) ) {
1050 self::$mCoreScripts[$vars['maintClass']] = $file;
1053 closedir( $handle );
1056 return self::$mCoreScripts;
1060 * Returns a database to be used by current maintenance script. It can be set by setDB().
1061 * If not set, wfGetDB() will be used.
1062 * This function has the same parameters as wfGetDB()
1064 * @return DatabaseBase
1066 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1067 if ( is_null( $this->mDb ) ) {
1068 return wfGetDB( $db, $groups, $wiki );
1069 } else {
1070 return $this->mDb;
1075 * Sets database object to be returned by getDB().
1077 * @param $db DatabaseBase: Database object to be used
1079 public function setDB( &$db ) {
1080 $this->mDb = $db;
1084 * Lock the search index
1085 * @param &$db DatabaseBase object
1087 private function lockSearchindex( &$db ) {
1088 $write = array( 'searchindex' );
1089 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1090 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1094 * Unlock the tables
1095 * @param &$db DatabaseBase object
1097 private function unlockSearchindex( &$db ) {
1098 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1102 * Unlock and lock again
1103 * Since the lock is low-priority, queued reads will be able to complete
1104 * @param &$db DatabaseBase object
1106 private function relockSearchindex( &$db ) {
1107 $this->unlockSearchindex( $db );
1108 $this->lockSearchindex( $db );
1112 * Perform a search index update with locking
1113 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1114 * @param $callback callback String: the function that will update the function.
1115 * @param $dbw DatabaseBase object
1116 * @param $results
1118 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1119 $lockTime = time();
1121 # Lock searchindex
1122 if ( $maxLockTime ) {
1123 $this->output( " --- Waiting for lock ---" );
1124 $this->lockSearchindex( $dbw );
1125 $lockTime = time();
1126 $this->output( "\n" );
1129 # Loop through the results and do a search update
1130 foreach ( $results as $row ) {
1131 # Allow reads to be processed
1132 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1133 $this->output( " --- Relocking ---" );
1134 $this->relockSearchindex( $dbw );
1135 $lockTime = time();
1136 $this->output( "\n" );
1138 call_user_func( $callback, $dbw, $row );
1141 # Unlock searchindex
1142 if ( $maxLockTime ) {
1143 $this->output( " --- Unlocking --" );
1144 $this->unlockSearchindex( $dbw );
1145 $this->output( "\n" );
1151 * Update the searchindex table for a given pageid
1152 * @param $dbw DatabaseBase a database write handle
1153 * @param $pageId Integer: the page ID to update.
1154 * @return null|string
1156 public function updateSearchIndexForPage( $dbw, $pageId ) {
1157 // Get current revision
1158 $rev = Revision::loadFromPageId( $dbw, $pageId );
1159 $title = null;
1160 if ( $rev ) {
1161 $titleObj = $rev->getTitle();
1162 $title = $titleObj->getPrefixedDBkey();
1163 $this->output( "$title..." );
1164 # Update searchindex
1165 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1166 $u->doUpdate();
1167 $this->output( "\n" );
1169 return $title;
1173 * Wrapper for posix_isatty()
1174 * We default as considering stdin a tty (for nice readline methods)
1175 * but treating stout as not a tty to avoid color codes
1177 * @param $fd int File descriptor
1178 * @return bool
1180 public static function posix_isatty( $fd ) {
1181 if ( !MWInit::functionExists( 'posix_isatty' ) ) {
1182 return !$fd;
1183 } else {
1184 return posix_isatty( $fd );
1189 * Prompt the console for input
1190 * @param $prompt String what to begin the line with, like '> '
1191 * @return String response
1193 public static function readconsole( $prompt = '> ' ) {
1194 static $isatty = null;
1195 if ( is_null( $isatty ) ) {
1196 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1199 if ( $isatty && function_exists( 'readline' ) ) {
1200 return readline( $prompt );
1201 } else {
1202 if ( $isatty ) {
1203 $st = self::readlineEmulation( $prompt );
1204 } else {
1205 if ( feof( STDIN ) ) {
1206 $st = false;
1207 } else {
1208 $st = fgets( STDIN, 1024 );
1211 if ( $st === false ) return false;
1212 $resp = trim( $st );
1213 return $resp;
1218 * Emulate readline()
1219 * @param $prompt String what to begin the line with, like '> '
1220 * @return String
1222 private static function readlineEmulation( $prompt ) {
1223 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1224 if ( !wfIsWindows() && $bash ) {
1225 $retval = false;
1226 $encPrompt = wfEscapeShellArg( $prompt );
1227 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1228 $encCommand = wfEscapeShellArg( $command );
1229 $line = wfShellExec( "$bash -c $encCommand", $retval );
1231 if ( $retval == 0 ) {
1232 return $line;
1233 } elseif ( $retval == 127 ) {
1234 // Couldn't execute bash even though we thought we saw it.
1235 // Shell probably spit out an error message, sorry :(
1236 // Fall through to fgets()...
1237 } else {
1238 // EOF/ctrl+D
1239 return false;
1243 // Fallback... we'll have no editing controls, EWWW
1244 if ( feof( STDIN ) ) {
1245 return false;
1247 print $prompt;
1248 return fgets( STDIN, 1024 );
1253 * Fake maintenance wrapper, mostly used for the web installer/updater
1255 class FakeMaintenance extends Maintenance {
1256 protected $mSelf = "FakeMaintenanceScript";
1257 public function execute() {
1258 return;
1263 * Class for scripts that perform database maintenance and want to log the
1264 * update in `updatelog` so we can later skip it
1266 abstract class LoggedUpdateMaintenance extends Maintenance {
1267 public function __construct() {
1268 parent::__construct();
1269 $this->addOption( 'force', 'Run the update even if it was completed already' );
1270 $this->setBatchSize( 200 );
1273 public function execute() {
1274 $db = $this->getDB( DB_MASTER );
1275 $key = $this->getUpdateKey();
1277 if ( !$this->hasOption( 'force' ) &&
1278 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ ) )
1280 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1281 return true;
1284 if ( !$this->doDBUpdates() ) {
1285 return false;
1288 if (
1289 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) )
1291 return true;
1292 } else {
1293 $this->output( $this->updatelogFailedMessage() . "\n" );
1294 return false;
1299 * Message to show that the update was done already and was just skipped
1300 * @return String
1302 protected function updateSkippedMessage() {
1303 $key = $this->getUpdateKey();
1304 return "Update '{$key}' already logged as completed.";
1308 * Message to show the the update log was unable to log the completion of this update
1309 * @return String
1311 protected function updatelogFailedMessage() {
1312 $key = $this->getUpdateKey();
1313 return "Unable to log update '{$key}' as completed.";
1317 * Do the actual work. All child classes will need to implement this.
1318 * Return true to log the update as done or false (usually on failure).
1319 * @return Bool
1321 abstract protected function doDBUpdates();
1324 * Get the update key name to go in the update log table
1325 * @return String
1327 abstract protected function getUpdateKey();