Improved BagOStuff documentation and made some return value tweaks.
[mediawiki.git] / maintenance / Maintenance.php
blob5d76cdffb80837a04d7153c081ef4bc4f43b6bdc
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();
105 * Used by getDD() / setDB()
106 * @var DatabaseBase
108 private $mDb = null;
111 * List of all the core maintenance scripts. This is added
112 * to scripts added by extensions in $wgMaintenanceScripts
113 * and returned by getMaintenanceScripts()
115 protected static $mCoreScripts = null;
118 * Default constructor. Children should call this *first* if implementing
119 * their own constructors
121 public function __construct() {
122 // Setup $IP, using MW_INSTALL_PATH if it exists
123 global $IP;
124 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
125 ? getenv( 'MW_INSTALL_PATH' )
126 : realpath( dirname( __FILE__ ) . '/..' );
128 $this->addDefaultParams();
129 register_shutdown_function( array( $this, 'outputChanneled' ), false );
133 * Should we execute the maintenance script, or just allow it to be included
134 * as a standalone class? It checks that the call stack only includes this
135 * function and "requires" (meaning was called from the file scope)
137 * @return Boolean
139 public static function shouldExecute() {
140 $bt = debug_backtrace();
141 $count = count( $bt );
142 if ( $count < 2 ) {
143 return false; // sanity
145 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
146 return false; // last call should be to this function
148 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
149 for( $i=1; $i < $count; $i++ ) {
150 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
151 return false; // previous calls should all be "requires"
154 return true;
158 * Do the actual work. All child classes will need to implement this
160 abstract public function execute();
163 * Add a parameter to the script. Will be displayed on --help
164 * with the associated description
166 * @param $name String: the name of the param (help, version, etc)
167 * @param $description String: the description of the param to show on --help
168 * @param $required Boolean: is the param required?
169 * @param $withArg Boolean: is an argument required with this option?
170 * @param $shortName String: character to use as short name
172 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
173 $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
174 if ( $shortName !== false ) {
175 $this->mShortParamsMap[$shortName] = $name;
180 * Checks to see if a particular param exists.
181 * @param $name String: the name of the param
182 * @return Boolean
184 protected function hasOption( $name ) {
185 return isset( $this->mOptions[$name] );
189 * Get an option, or return the default
190 * @param $name String: the name of the param
191 * @param $default Mixed: anything you want, default null
192 * @return Mixed
194 protected function getOption( $name, $default = null ) {
195 if ( $this->hasOption( $name ) ) {
196 return $this->mOptions[$name];
197 } else {
198 // Set it so we don't have to provide the default again
199 $this->mOptions[$name] = $default;
200 return $this->mOptions[$name];
205 * Add some args that are needed
206 * @param $arg String: name of the arg, like 'start'
207 * @param $description String: short description of the arg
208 * @param $required Boolean: is this required?
210 protected function addArg( $arg, $description, $required = true ) {
211 $this->mArgList[] = array(
212 'name' => $arg,
213 'desc' => $description,
214 'require' => $required
219 * Remove an option. Useful for removing options that won't be used in your script.
220 * @param $name String: the option to remove.
222 protected function deleteOption( $name ) {
223 unset( $this->mParams[$name] );
227 * Set the description text.
228 * @param $text String: the text of the description
230 protected function addDescription( $text ) {
231 $this->mDescription = $text;
235 * Does a given argument exist?
236 * @param $argId Integer: the integer value (from zero) for the arg
237 * @return Boolean
239 protected function hasArg( $argId = 0 ) {
240 return isset( $this->mArgs[$argId] );
244 * Get an argument.
245 * @param $argId Integer: the integer value (from zero) for the arg
246 * @param $default Mixed: the default if it doesn't exist
247 * @return mixed
249 protected function getArg( $argId = 0, $default = null ) {
250 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
254 * Set the batch size.
255 * @param $s Integer: the number of operations to do in a batch
257 protected function setBatchSize( $s = 0 ) {
258 $this->mBatchSize = $s;
260 // If we support $mBatchSize, show the option.
261 // Used to be in addDefaultParams, but in order for that to
262 // work, subclasses would have to call this function in the constructor
263 // before they called parent::__construct which is just weird
264 // (and really wasn't done).
265 if ( $this->mBatchSize ) {
266 $this->addOption( 'batch-size', 'Run this many operations ' .
267 'per batch, default: ' . $this->mBatchSize, false, true );
268 if ( isset( $this->mParams['batch-size'] ) ) {
269 // This seems a little ugly...
270 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
276 * Get the script's name
277 * @return String
279 public function getName() {
280 return $this->mSelf;
284 * Return input from stdin.
285 * @param $len Integer: the number of bytes to read. If null,
286 * just return the handle. Maintenance::STDIN_ALL returns
287 * the full length
288 * @return Mixed
290 protected function getStdin( $len = null ) {
291 if ( $len == Maintenance::STDIN_ALL ) {
292 return file_get_contents( 'php://stdin' );
294 $f = fopen( 'php://stdin', 'rt' );
295 if ( !$len ) {
296 return $f;
298 $input = fgets( $f, $len );
299 fclose( $f );
300 return rtrim( $input );
304 * @return bool
306 public function isQuiet() {
307 return $this->mQuiet;
311 * Throw some output to the user. Scripts can call this with no fears,
312 * as we handle all --quiet stuff here
313 * @param $out String: the text to show to the user
314 * @param $channel Mixed: unique identifier for the channel. See
315 * function outputChanneled.
317 protected function output( $out, $channel = null ) {
318 if ( $this->mQuiet ) {
319 return;
321 if ( $channel === null ) {
322 $this->cleanupChanneled();
323 if( php_sapi_name() == 'cli' ) {
324 fwrite( STDOUT, $out );
325 } else {
326 print( $out );
328 } else {
329 $out = preg_replace( '/\n\z/', '', $out );
330 $this->outputChanneled( $out, $channel );
335 * Throw an error to the user. Doesn't respect --quiet, so don't use
336 * this for non-error output
337 * @param $err String: the error to display
338 * @param $die Int: if > 0, go ahead and die out using this int as the code
340 protected function error( $err, $die = 0 ) {
341 $this->outputChanneled( false );
342 if ( php_sapi_name() == 'cli' ) {
343 fwrite( STDERR, $err . "\n" );
344 } else {
345 print $err;
347 $die = intval( $die );
348 if ( $die > 0 ) {
349 die( $die );
353 private $atLineStart = true;
354 private $lastChannel = null;
357 * Clean up channeled output. Output a newline if necessary.
359 public function cleanupChanneled() {
360 if ( !$this->atLineStart ) {
361 if( php_sapi_name() == 'cli' ) {
362 fwrite( STDOUT, "\n" );
363 } else {
364 print "\n";
366 $this->atLineStart = true;
371 * Message outputter with channeled message support. Messages on the
372 * same channel are concatenated, but any intervening messages in another
373 * channel start a new line.
374 * @param $msg String: the message without trailing newline
375 * @param $channel string Channel identifier or null for no
376 * channel. Channel comparison uses ===.
378 public function outputChanneled( $msg, $channel = null ) {
379 if ( $msg === false ) {
380 $this->cleanupChanneled();
381 return;
384 $cli = php_sapi_name() == 'cli';
386 // End the current line if necessary
387 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
388 if( $cli ) {
389 fwrite( STDOUT, "\n" );
390 } else {
391 print "\n";
395 if( $cli ) {
396 fwrite( STDOUT, $msg );
397 } else {
398 print $msg;
401 $this->atLineStart = false;
402 if ( $channel === null ) {
403 // For unchanneled messages, output trailing newline immediately
404 if( $cli ) {
405 fwrite( STDOUT, "\n" );
406 } else {
407 print "\n";
409 $this->atLineStart = true;
411 $this->lastChannel = $channel;
415 * Does the script need different DB access? By default, we give Maintenance
416 * scripts normal rights to the DB. Sometimes, a script needs admin rights
417 * access for a reason and sometimes they want no access. Subclasses should
418 * override and return one of the following values, as needed:
419 * Maintenance::DB_NONE - For no DB access at all
420 * Maintenance::DB_STD - For normal DB access, default
421 * Maintenance::DB_ADMIN - For admin DB access
422 * @return Integer
424 public function getDbType() {
425 return Maintenance::DB_STD;
429 * Add the default parameters to the scripts
431 protected function addDefaultParams() {
433 # Generic (non script dependant) options:
435 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
436 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
437 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
438 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
439 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
440 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
441 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
442 "http://en.wikipedia.org. This is sometimes necessary because " .
443 "server name detection may fail in command line scripts.", false, true );
445 # Save generic options to display them separately in help
446 $this->mGenericParameters = $this->mParams ;
448 # Script dependant options:
450 // If we support a DB, show the options
451 if ( $this->getDbType() > 0 ) {
452 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
453 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
456 # Save additional script dependant options to display
457 # them separately in help
458 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
462 * Run a child maintenance script. Pass all of the current arguments
463 * to it.
464 * @param $maintClass String: a name of a child maintenance class
465 * @param $classFile String: full path of where the child is
466 * @return Maintenance child
468 public function runChild( $maintClass, $classFile = null ) {
469 // Make sure the class is loaded first
470 if ( !MWInit::classExists( $maintClass ) ) {
471 if ( $classFile ) {
472 require_once( $classFile );
474 if ( !MWInit::classExists( $maintClass ) ) {
475 $this->error( "Cannot spawn child: $maintClass" );
480 * @var $child Maintenance
482 $child = new $maintClass();
483 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
484 if ( !is_null( $this->mDb ) ) {
485 $child->setDB( $this->mDb );
487 return $child;
491 * Do some sanity checking and basic setup
493 public function setup() {
494 global $wgCommandLineMode, $wgRequestTime;
496 # Abort if called from a web server
497 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
498 $this->error( 'This script must be run from the command line', true );
501 # Make sure we can handle script parameters
502 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
503 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
506 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
507 // Send PHP warnings and errors to stderr instead of stdout.
508 // This aids in diagnosing problems, while keeping messages
509 // out of redirected output.
510 if ( ini_get( 'display_errors' ) ) {
511 ini_set( 'display_errors', 'stderr' );
514 // Don't touch the setting on earlier versions of PHP,
515 // as setting it would disable output if you'd wanted it.
517 // Note that exceptions are also sent to stderr when
518 // command-line mode is on, regardless of PHP version.
521 $this->loadParamsAndArgs();
522 $this->maybeHelp();
524 # Set the memory limit
525 # Note we need to set it again later in cache LocalSettings changed it
526 $this->adjustMemoryLimit();
528 # Set max execution time to 0 (no limit). PHP.net says that
529 # "When running PHP from the command line the default setting is 0."
530 # But sometimes this doesn't seem to be the case.
531 ini_set( 'max_execution_time', 0 );
533 $wgRequestTime = microtime( true );
535 # Define us as being in MediaWiki
536 define( 'MEDIAWIKI', true );
538 $wgCommandLineMode = true;
539 # Turn off output buffering if it's on
540 @ob_end_flush();
542 $this->validateParamsAndArgs();
546 * Normally we disable the memory_limit when running admin scripts.
547 * Some scripts may wish to actually set a limit, however, to avoid
548 * blowing up unexpectedly. We also support a --memory-limit option,
549 * to allow sysadmins to explicitly set one if they'd prefer to override
550 * defaults (or for people using Suhosin which yells at you for trying
551 * to disable the limits)
552 * @return string
554 public function memoryLimit() {
555 $limit = $this->getOption( 'memory-limit', 'max' );
556 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
557 return $limit;
561 * Adjusts PHP's memory limit to better suit our needs, if needed.
563 protected function adjustMemoryLimit() {
564 $limit = $this->memoryLimit();
565 if ( $limit == 'max' ) {
566 $limit = -1; // no memory limit
568 if ( $limit != 'default' ) {
569 ini_set( 'memory_limit', $limit );
574 * Clear all params and arguments.
576 public function clearParamsAndArgs() {
577 $this->mOptions = array();
578 $this->mArgs = array();
579 $this->mInputLoaded = false;
583 * Process command line arguments
584 * $mOptions becomes an array with keys set to the option names
585 * $mArgs becomes a zero-based array containing the non-option arguments
587 * @param $self String The name of the script, if any
588 * @param $opts Array An array of options, in form of key=>value
589 * @param $args Array An array of command line arguments
591 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
592 # If we were given opts or args, set those and return early
593 if ( $self ) {
594 $this->mSelf = $self;
595 $this->mInputLoaded = true;
597 if ( $opts ) {
598 $this->mOptions = $opts;
599 $this->mInputLoaded = true;
601 if ( $args ) {
602 $this->mArgs = $args;
603 $this->mInputLoaded = true;
606 # If we've already loaded input (either by user values or from $argv)
607 # skip on loading it again. The array_shift() will corrupt values if
608 # it's run again and again
609 if ( $this->mInputLoaded ) {
610 $this->loadSpecialVars();
611 return;
614 global $argv;
615 $this->mSelf = array_shift( $argv );
617 $options = array();
618 $args = array();
620 # Parse arguments
621 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
622 if ( $arg == '--' ) {
623 # End of options, remainder should be considered arguments
624 $arg = next( $argv );
625 while ( $arg !== false ) {
626 $args[] = $arg;
627 $arg = next( $argv );
629 break;
630 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
631 # Long options
632 $option = substr( $arg, 2 );
633 if ( array_key_exists( $option, $options ) ) {
634 $this->error( "\nERROR: $option parameter given twice\n" );
635 $this->maybeHelp( true );
637 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
638 $param = next( $argv );
639 if ( $param === false ) {
640 $this->error( "\nERROR: $option parameter needs a value after it\n" );
641 $this->maybeHelp( true );
643 $options[$option] = $param;
644 } else {
645 $bits = explode( '=', $option, 2 );
646 if ( count( $bits ) > 1 ) {
647 $option = $bits[0];
648 $param = $bits[1];
649 } else {
650 $param = 1;
652 $options[$option] = $param;
654 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
655 # Short options
656 for ( $p = 1; $p < strlen( $arg ); $p++ ) {
657 $option = $arg { $p } ;
658 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
659 $option = $this->mShortParamsMap[$option];
661 if ( array_key_exists( $option, $options ) ) {
662 $this->error( "\nERROR: $option parameter given twice\n" );
663 $this->maybeHelp( true );
665 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
666 $param = next( $argv );
667 if ( $param === false ) {
668 $this->error( "\nERROR: $option parameter needs a value after it\n" );
669 $this->maybeHelp( true );
671 $options[$option] = $param;
672 } else {
673 $options[$option] = 1;
676 } else {
677 $args[] = $arg;
681 $this->mOptions = $options;
682 $this->mArgs = $args;
683 $this->loadSpecialVars();
684 $this->mInputLoaded = true;
688 * Run some validation checks on the params, etc
690 protected function validateParamsAndArgs() {
691 $die = false;
692 # Check to make sure we've got all the required options
693 foreach ( $this->mParams as $opt => $info ) {
694 if ( $info['require'] && !$this->hasOption( $opt ) ) {
695 $this->error( "Param $opt required!" );
696 $die = true;
699 # Check arg list too
700 foreach ( $this->mArgList as $k => $info ) {
701 if ( $info['require'] && !$this->hasArg( $k ) ) {
702 $this->error( 'Argument <' . $info['name'] . '> required!' );
703 $die = true;
707 if ( $die ) {
708 $this->maybeHelp( true );
713 * Handle the special variables that are global to all scripts
715 protected function loadSpecialVars() {
716 if ( $this->hasOption( 'dbuser' ) ) {
717 $this->mDbUser = $this->getOption( 'dbuser' );
719 if ( $this->hasOption( 'dbpass' ) ) {
720 $this->mDbPass = $this->getOption( 'dbpass' );
722 if ( $this->hasOption( 'quiet' ) ) {
723 $this->mQuiet = true;
725 if ( $this->hasOption( 'batch-size' ) ) {
726 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
731 * Maybe show the help.
732 * @param $force boolean Whether to force the help to show, default false
734 protected function maybeHelp( $force = false ) {
735 if( !$force && !$this->hasOption( 'help' ) ) {
736 return;
739 $screenWidth = 80; // TODO: Caculate this!
740 $tab = " ";
741 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
743 ksort( $this->mParams );
744 $this->mQuiet = false;
746 // Description ...
747 if ( $this->mDescription ) {
748 $this->output( "\n" . $this->mDescription . "\n" );
750 $output = "\nUsage: php " . basename( $this->mSelf );
752 // ... append parameters ...
753 if ( $this->mParams ) {
754 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
757 // ... and append arguments.
758 if ( $this->mArgList ) {
759 $output .= ' ';
760 foreach ( $this->mArgList as $k => $arg ) {
761 if ( $arg['require'] ) {
762 $output .= '<' . $arg['name'] . '>';
763 } else {
764 $output .= '[' . $arg['name'] . ']';
766 if ( $k < count( $this->mArgList ) - 1 )
767 $output .= ' ';
770 $this->output( "$output\n\n" );
772 # TODO abstract some repetitive code below
774 // Generic parameters
775 $this->output( "Generic maintenance parameters:\n" );
776 foreach ( $this->mGenericParameters as $par => $info ) {
777 if ( $info['shortName'] !== false ) {
778 $par .= " (-{$info['shortName']})";
780 $this->output(
781 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
782 "\n$tab$tab" ) . "\n"
785 $this->output( "\n" );
787 $scriptDependantParams = $this->mDependantParameters;
788 if( count($scriptDependantParams) > 0 ) {
789 $this->output( "Script dependant parameters:\n" );
790 // Parameters description
791 foreach ( $scriptDependantParams as $par => $info ) {
792 if ( $info['shortName'] !== false ) {
793 $par .= " (-{$info['shortName']})";
795 $this->output(
796 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
797 "\n$tab$tab" ) . "\n"
800 $this->output( "\n" );
804 // Script specific parameters not defined on construction by
805 // Maintenance::addDefaultParams()
806 $scriptSpecificParams = array_diff_key(
807 # all script parameters:
808 $this->mParams,
809 # remove the Maintenance default parameters:
810 $this->mGenericParameters,
811 $this->mDependantParameters
813 if( count($scriptSpecificParams) > 0 ) {
814 $this->output( "Script specific parameters:\n" );
815 // Parameters description
816 foreach ( $scriptSpecificParams as $par => $info ) {
817 if ( $info['shortName'] !== false ) {
818 $par .= " (-{$info['shortName']})";
820 $this->output(
821 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
822 "\n$tab$tab" ) . "\n"
825 $this->output( "\n" );
828 // Print arguments
829 if( count( $this->mArgList ) > 0 ) {
830 $this->output( "Arguments:\n" );
831 // Arguments description
832 foreach ( $this->mArgList as $info ) {
833 $openChar = $info['require'] ? '<' : '[';
834 $closeChar = $info['require'] ? '>' : ']';
835 $this->output(
836 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
837 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
840 $this->output( "\n" );
843 die( 1 );
847 * Handle some last-minute setup here.
849 public function finalSetup() {
850 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
851 global $wgDBadminuser, $wgDBadminpassword;
852 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
854 # Turn off output buffering again, it might have been turned on in the settings files
855 if ( ob_get_level() ) {
856 ob_end_flush();
858 # Same with these
859 $wgCommandLineMode = true;
861 # Override $wgServer
862 if( $this->hasOption( 'server') ) {
863 $wgServer = $this->getOption( 'server', $wgServer );
866 # If these were passed, use them
867 if ( $this->mDbUser ) {
868 $wgDBadminuser = $this->mDbUser;
870 if ( $this->mDbPass ) {
871 $wgDBadminpassword = $this->mDbPass;
874 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
875 $wgDBuser = $wgDBadminuser;
876 $wgDBpassword = $wgDBadminpassword;
878 if ( $wgDBservers ) {
880 * @var $wgDBservers array
882 foreach ( $wgDBservers as $i => $server ) {
883 $wgDBservers[$i]['user'] = $wgDBuser;
884 $wgDBservers[$i]['password'] = $wgDBpassword;
887 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
888 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
889 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
891 LBFactory::destroyInstance();
894 $this->afterFinalSetup();
896 $wgShowSQLErrors = true;
897 @set_time_limit( 0 );
898 $this->adjustMemoryLimit();
902 * Execute a callback function at the end of initialisation
904 protected function afterFinalSetup() {
905 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
906 call_user_func( MW_CMDLINE_CALLBACK );
911 * Potentially debug globals. Originally a feature only
912 * for refreshLinks
914 public function globals() {
915 if ( $this->hasOption( 'globals' ) ) {
916 print_r( $GLOBALS );
921 * Generic setup for most installs. Returns the location of LocalSettings
922 * @return String
924 public function loadSettings() {
925 global $wgCommandLineMode, $IP;
927 if ( isset( $this->mOptions['conf'] ) ) {
928 $settingsFile = $this->mOptions['conf'];
929 } elseif ( defined("MW_CONFIG_FILE") ) {
930 $settingsFile = MW_CONFIG_FILE;
931 } else {
932 $settingsFile = "$IP/LocalSettings.php";
934 if ( isset( $this->mOptions['wiki'] ) ) {
935 $bits = explode( '-', $this->mOptions['wiki'] );
936 if ( count( $bits ) == 1 ) {
937 $bits[] = '';
939 define( 'MW_DB', $bits[0] );
940 define( 'MW_PREFIX', $bits[1] );
943 if ( !is_readable( $settingsFile ) ) {
944 $this->error( "A copy of your installation's LocalSettings.php\n" .
945 "must exist and be readable in the source directory.\n" .
946 "Use --conf to specify it." , true );
948 $wgCommandLineMode = true;
949 return $settingsFile;
953 * Support function for cleaning up redundant text records
954 * @param $delete Boolean: whether or not to actually delete the records
955 * @author Rob Church <robchur@gmail.com>
957 public function purgeRedundantText( $delete = true ) {
958 # Data should come off the master, wrapped in a transaction
959 $dbw = $this->getDB( DB_MASTER );
960 $dbw->begin( __METHOD__ );
962 $tbl_arc = $dbw->tableName( 'archive' );
963 $tbl_rev = $dbw->tableName( 'revision' );
964 $tbl_txt = $dbw->tableName( 'text' );
966 # Get "active" text records from the revisions table
967 $this->output( 'Searching for active text records in revisions table...' );
968 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
969 foreach ( $res as $row ) {
970 $cur[] = $row->rev_text_id;
972 $this->output( "done.\n" );
974 # Get "active" text records from the archive table
975 $this->output( 'Searching for active text records in archive table...' );
976 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
977 foreach ( $res as $row ) {
978 $cur[] = $row->ar_text_id;
980 $this->output( "done.\n" );
982 # Get the IDs of all text records not in these sets
983 $this->output( 'Searching for inactive text records...' );
984 $set = implode( ', ', $cur );
985 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
986 $old = array();
987 foreach ( $res as $row ) {
988 $old[] = $row->old_id;
990 $this->output( "done.\n" );
992 # Inform the user of what we're going to do
993 $count = count( $old );
994 $this->output( "$count inactive items found.\n" );
996 # Delete as appropriate
997 if ( $delete && $count ) {
998 $this->output( 'Deleting...' );
999 $set = implode( ', ', $old );
1000 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
1001 $this->output( "done.\n" );
1004 # Done
1005 $dbw->commit( __METHOD__ );
1009 * Get the maintenance directory.
1010 * @return string
1012 protected function getDir() {
1013 return dirname( __FILE__ );
1017 * Get the list of available maintenance scripts. Note
1018 * that if you call this _before_ calling doMaintenance
1019 * you won't have any extensions in it yet
1020 * @return Array
1022 public static function getMaintenanceScripts() {
1023 global $wgMaintenanceScripts;
1024 return $wgMaintenanceScripts + self::getCoreScripts();
1028 * Return all of the core maintenance scripts
1029 * @return array
1031 protected static function getCoreScripts() {
1032 if ( !self::$mCoreScripts ) {
1033 $paths = array(
1034 dirname( __FILE__ ),
1035 dirname( __FILE__ ) . '/language',
1036 dirname( __FILE__ ) . '/storage',
1038 self::$mCoreScripts = array();
1039 foreach ( $paths as $p ) {
1040 $handle = opendir( $p );
1041 while ( ( $file = readdir( $handle ) ) !== false ) {
1042 if ( $file == 'Maintenance.php' ) {
1043 continue;
1045 $file = $p . '/' . $file;
1046 if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
1047 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1048 continue;
1050 require( $file );
1051 $vars = get_defined_vars();
1052 if ( array_key_exists( 'maintClass', $vars ) ) {
1053 self::$mCoreScripts[$vars['maintClass']] = $file;
1056 closedir( $handle );
1059 return self::$mCoreScripts;
1063 * Returns a database to be used by current maintenance script. It can be set by setDB().
1064 * If not set, wfGetDB() will be used.
1065 * This function has the same parameters as wfGetDB()
1067 * @return DatabaseBase
1069 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1070 if ( is_null( $this->mDb ) ) {
1071 return wfGetDB( $db, $groups, $wiki );
1072 } else {
1073 return $this->mDb;
1078 * Sets database object to be returned by getDB().
1080 * @param $db DatabaseBase: Database object to be used
1082 public function setDB( &$db ) {
1083 $this->mDb = $db;
1087 * Lock the search index
1088 * @param &$db DatabaseBase object
1090 private function lockSearchindex( &$db ) {
1091 $write = array( 'searchindex' );
1092 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1093 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1097 * Unlock the tables
1098 * @param &$db DatabaseBase object
1100 private function unlockSearchindex( &$db ) {
1101 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1105 * Unlock and lock again
1106 * Since the lock is low-priority, queued reads will be able to complete
1107 * @param &$db DatabaseBase object
1109 private function relockSearchindex( &$db ) {
1110 $this->unlockSearchindex( $db );
1111 $this->lockSearchindex( $db );
1115 * Perform a search index update with locking
1116 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1117 * @param $callback callback String: the function that will update the function.
1118 * @param $dbw DatabaseBase object
1119 * @param $results
1121 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1122 $lockTime = time();
1124 # Lock searchindex
1125 if ( $maxLockTime ) {
1126 $this->output( " --- Waiting for lock ---" );
1127 $this->lockSearchindex( $dbw );
1128 $lockTime = time();
1129 $this->output( "\n" );
1132 # Loop through the results and do a search update
1133 foreach ( $results as $row ) {
1134 # Allow reads to be processed
1135 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1136 $this->output( " --- Relocking ---" );
1137 $this->relockSearchindex( $dbw );
1138 $lockTime = time();
1139 $this->output( "\n" );
1141 call_user_func( $callback, $dbw, $row );
1144 # Unlock searchindex
1145 if ( $maxLockTime ) {
1146 $this->output( " --- Unlocking --" );
1147 $this->unlockSearchindex( $dbw );
1148 $this->output( "\n" );
1154 * Update the searchindex table for a given pageid
1155 * @param $dbw DatabaseBase a database write handle
1156 * @param $pageId Integer: the page ID to update.
1157 * @return null|string
1159 public function updateSearchIndexForPage( $dbw, $pageId ) {
1160 // Get current revision
1161 $rev = Revision::loadFromPageId( $dbw, $pageId );
1162 $title = null;
1163 if ( $rev ) {
1164 $titleObj = $rev->getTitle();
1165 $title = $titleObj->getPrefixedDBkey();
1166 $this->output( "$title..." );
1167 # Update searchindex
1168 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1169 $u->doUpdate();
1170 $this->output( "\n" );
1172 return $title;
1176 * Wrapper for posix_isatty()
1177 * We default as considering stdin a tty (for nice readline methods)
1178 * but treating stout as not a tty to avoid color codes
1180 * @param $fd int File descriptor
1181 * @return bool
1183 public static function posix_isatty( $fd ) {
1184 if ( !MWInit::functionExists( 'posix_isatty' ) ) {
1185 return !$fd;
1186 } else {
1187 return posix_isatty( $fd );
1192 * Prompt the console for input
1193 * @param $prompt String what to begin the line with, like '> '
1194 * @return String response
1196 public static function readconsole( $prompt = '> ' ) {
1197 static $isatty = null;
1198 if ( is_null( $isatty ) ) {
1199 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1202 if ( $isatty && function_exists( 'readline' ) ) {
1203 return readline( $prompt );
1204 } else {
1205 if ( $isatty ) {
1206 $st = self::readlineEmulation( $prompt );
1207 } else {
1208 if ( feof( STDIN ) ) {
1209 $st = false;
1210 } else {
1211 $st = fgets( STDIN, 1024 );
1214 if ( $st === false ) return false;
1215 $resp = trim( $st );
1216 return $resp;
1221 * Emulate readline()
1222 * @param $prompt String what to begin the line with, like '> '
1223 * @return String
1225 private static function readlineEmulation( $prompt ) {
1226 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1227 if ( !wfIsWindows() && $bash ) {
1228 $retval = false;
1229 $encPrompt = wfEscapeShellArg( $prompt );
1230 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1231 $encCommand = wfEscapeShellArg( $command );
1232 $line = wfShellExec( "$bash -c $encCommand", $retval );
1234 if ( $retval == 0 ) {
1235 return $line;
1236 } elseif ( $retval == 127 ) {
1237 // Couldn't execute bash even though we thought we saw it.
1238 // Shell probably spit out an error message, sorry :(
1239 // Fall through to fgets()...
1240 } else {
1241 // EOF/ctrl+D
1242 return false;
1246 // Fallback... we'll have no editing controls, EWWW
1247 if ( feof( STDIN ) ) {
1248 return false;
1250 print $prompt;
1251 return fgets( STDIN, 1024 );
1256 * Fake maintenance wrapper, mostly used for the web installer/updater
1258 class FakeMaintenance extends Maintenance {
1259 protected $mSelf = "FakeMaintenanceScript";
1260 public function execute() {
1261 return;
1266 * Class for scripts that perform database maintenance and want to log the
1267 * update in `updatelog` so we can later skip it
1269 abstract class LoggedUpdateMaintenance extends Maintenance {
1270 public function __construct() {
1271 parent::__construct();
1272 $this->addOption( 'force', 'Run the update even if it was completed already' );
1273 $this->setBatchSize( 200 );
1276 public function execute() {
1277 $db = $this->getDB( DB_MASTER );
1278 $key = $this->getUpdateKey();
1280 if ( !$this->hasOption( 'force' ) &&
1281 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ ) )
1283 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1284 return true;
1287 if ( !$this->doDBUpdates() ) {
1288 return false;
1291 if (
1292 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) )
1294 return true;
1295 } else {
1296 $this->output( $this->updatelogFailedMessage() . "\n" );
1297 return false;
1302 * Message to show that the update was done already and was just skipped
1303 * @return String
1305 protected function updateSkippedMessage() {
1306 $key = $this->getUpdateKey();
1307 return "Update '{$key}' already logged as completed.";
1311 * Message to show the the update log was unable to log the completion of this update
1312 * @return String
1314 protected function updatelogFailedMessage() {
1315 $key = $this->getUpdateKey();
1316 return "Unable to log update '{$key}' as completed.";
1320 * Do the actual work. All child classes will need to implement this.
1321 * Return true to log the update as done or false (usually on failure).
1322 * @return Bool
1324 abstract protected function doDBUpdates();
1327 * Get the update key name to go in the update log table
1328 * @return String
1330 abstract protected function getUpdateKey();