3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Define this so scripts can easily find doMaintenance.php
24 define( 'RUN_MAINTENANCE_IF_MAIN', dirname( __FILE__
) . '/doMaintenance.php' );
25 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
29 // Make sure we're on PHP5 or better
30 if ( !function_exists( 'version_compare' ) ||
version_compare( PHP_VERSION
, '5.2.3' ) < 0 ) {
31 require_once( dirname( __FILE__
) . '/../includes/PHPVersionError.php' );
32 wfPHPVersionError( 'cli' );
36 * Abstract maintenance class for quickly writing and churning out
37 * maintenance scripts with minimal effort. All that _must_ be defined
38 * is the execute() method. See docs/maintenance.txt for more info
39 * and a quick demo of how to use it.
41 * @author Chad Horohoe <chad@anyonecanedit.org>
43 * @ingroup Maintenance
45 abstract class Maintenance
{
48 * Constants for DB access type
49 * @see Maintenance::getDbType()
55 // Const for getStdin()
56 const STDIN_ALL
= 'all';
58 // This is the desired params
59 protected $mParams = array();
61 // Array of mapping short parameters to long ones
62 protected $mShortParamsMap = array();
64 // Array of desired args
65 protected $mArgList = array();
67 // This is the list of options that were actually passed
68 protected $mOptions = array();
70 // This is the list of arguments that were actually passed
71 protected $mArgs = array();
73 // Name of the script currently running
76 // Special vars for params that are always used
77 protected $mQuiet = false;
78 protected $mDbUser, $mDbPass;
80 // A description of the script, children should change this
81 protected $mDescription = '';
83 // Have we already loaded our user input?
84 protected $mInputLoaded = false;
87 * Batch size. If a script supports this, they should set
88 * a default with setBatchSize()
92 protected $mBatchSize = null;
94 // Generic options added by addDefaultParams()
95 private $mGenericParameters = array();
96 // Generic options which might or not be supported by the script
97 private $mDependantParameters = array();
99 // Used by getDD() / setDB()
103 * List of all the core maintenance scripts. This is added
104 * to scripts added by extensions in $wgMaintenanceScripts
105 * and returned by getMaintenanceScripts()
107 protected static $mCoreScripts = null;
110 * Default constructor. Children should call this *first* if implementing
111 * their own constructors
113 public function __construct() {
114 // Setup $IP, using MW_INSTALL_PATH if it exists
116 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
117 ?
getenv( 'MW_INSTALL_PATH' )
118 : realpath( dirname( __FILE__
) . '/..' );
120 $this->addDefaultParams();
121 register_shutdown_function( array( $this, 'outputChanneled' ), false );
125 * Should we execute the maintenance script, or just allow it to be included
126 * as a standalone class? It checks that the call stack only includes this
127 * function and "requires" (meaning was called from the file scope)
131 public static function shouldExecute() {
132 $bt = debug_backtrace();
133 $count = count( $bt );
135 return false; // sanity
137 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
138 return false; // last call should be to this function
140 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
141 for( $i=1; $i < $count; $i++
) {
142 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
143 return false; // previous calls should all be "requires"
150 * Do the actual work. All child classes will need to implement this
152 abstract public function execute();
155 * Add a parameter to the script. Will be displayed on --help
156 * with the associated description
158 * @param $name String: the name of the param (help, version, etc)
159 * @param $description String: the description of the param to show on --help
160 * @param $required Boolean: is the param required?
161 * @param $withArg Boolean: is an argument required with this option?
162 * @param $shortName String: character to use as short name
164 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
165 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
166 if ( $shortName !== false ) {
167 $this->mShortParamsMap
[$shortName] = $name;
172 * Checks to see if a particular param exists.
173 * @param $name String: the name of the param
176 protected function hasOption( $name ) {
177 return isset( $this->mOptions
[$name] );
181 * Get an option, or return the default
182 * @param $name String: the name of the param
183 * @param $default Mixed: anything you want, default null
186 protected function getOption( $name, $default = null ) {
187 if ( $this->hasOption( $name ) ) {
188 return $this->mOptions
[$name];
190 // Set it so we don't have to provide the default again
191 $this->mOptions
[$name] = $default;
192 return $this->mOptions
[$name];
197 * Add some args that are needed
198 * @param $arg String: name of the arg, like 'start'
199 * @param $description String: short description of the arg
200 * @param $required Boolean: is this required?
202 protected function addArg( $arg, $description, $required = true ) {
203 $this->mArgList
[] = array(
205 'desc' => $description,
206 'require' => $required
211 * Remove an option. Useful for removing options that won't be used in your script.
212 * @param $name String: the option to remove.
214 protected function deleteOption( $name ) {
215 unset( $this->mParams
[$name] );
219 * Set the description text.
220 * @param $text String: the text of the description
222 protected function addDescription( $text ) {
223 $this->mDescription
= $text;
227 * Does a given argument exist?
228 * @param $argId Integer: the integer value (from zero) for the arg
231 protected function hasArg( $argId = 0 ) {
232 return isset( $this->mArgs
[$argId] );
237 * @param $argId Integer: the integer value (from zero) for the arg
238 * @param $default Mixed: the default if it doesn't exist
241 protected function getArg( $argId = 0, $default = null ) {
242 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
246 * Set the batch size.
247 * @param $s Integer: the number of operations to do in a batch
249 protected function setBatchSize( $s = 0 ) {
250 $this->mBatchSize
= $s;
252 // If we support $mBatchSize, show the option.
253 // Used to be in addDefaultParams, but in order for that to
254 // work, subclasses would have to call this function in the constructor
255 // before they called parent::__construct which is just weird
256 // (and really wasn't done).
257 if ( $this->mBatchSize
) {
258 $this->addOption( 'batch-size', 'Run this many operations ' .
259 'per batch, default: ' . $this->mBatchSize
, false, true );
260 if ( isset( $this->mParams
['batch-size'] ) ) {
261 // This seems a little ugly...
262 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
268 * Get the script's name
271 public function getName() {
276 * Return input from stdin.
277 * @param $len Integer: the number of bytes to read. If null,
278 * just return the handle. Maintenance::STDIN_ALL returns
282 protected function getStdin( $len = null ) {
283 if ( $len == Maintenance
::STDIN_ALL
) {
284 return file_get_contents( 'php://stdin' );
286 $f = fopen( 'php://stdin', 'rt' );
290 $input = fgets( $f, $len );
292 return rtrim( $input );
295 public function isQuiet() {
296 return $this->mQuiet
;
300 * Throw some output to the user. Scripts can call this with no fears,
301 * as we handle all --quiet stuff here
302 * @param $out String: the text to show to the user
303 * @param $channel Mixed: unique identifier for the channel. See
304 * function outputChanneled.
306 protected function output( $out, $channel = null ) {
307 if ( $this->mQuiet
) {
310 if ( $channel === null ) {
311 $this->cleanupChanneled();
312 if( php_sapi_name() == 'cli' ) {
313 fwrite( STDOUT
, $out );
318 $out = preg_replace( '/\n\z/', '', $out );
319 $this->outputChanneled( $out, $channel );
324 * Throw an error to the user. Doesn't respect --quiet, so don't use
325 * this for non-error output
326 * @param $err String: the error to display
327 * @param $die Int: if > 0, go ahead and die out using this int as the code
329 protected function error( $err, $die = 0 ) {
330 $this->outputChanneled( false );
331 if ( php_sapi_name() == 'cli' ) {
332 fwrite( STDERR
, $err . "\n" );
336 $die = intval( $die );
342 private $atLineStart = true;
343 private $lastChannel = null;
346 * Clean up channeled output. Output a newline if necessary.
348 public function cleanupChanneled() {
349 if ( !$this->atLineStart
) {
350 if( php_sapi_name() == 'cli' ) {
351 fwrite( STDOUT
, "\n" );
355 $this->atLineStart
= true;
360 * Message outputter with channeled message support. Messages on the
361 * same channel are concatenated, but any intervening messages in another
362 * channel start a new line.
363 * @param $msg String: the message without trailing newline
364 * @param $channel Channel identifier or null for no
365 * channel. Channel comparison uses ===.
367 public function outputChanneled( $msg, $channel = null ) {
368 if ( $msg === false ) {
369 $this->cleanupChanneled();
373 $cli = php_sapi_name() == 'cli';
375 // End the current line if necessary
376 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
378 fwrite( STDOUT
, "\n" );
385 fwrite( STDOUT
, $msg );
390 $this->atLineStart
= false;
391 if ( $channel === null ) {
392 // For unchanneled messages, output trailing newline immediately
394 fwrite( STDOUT
, "\n" );
398 $this->atLineStart
= true;
400 $this->lastChannel
= $channel;
404 * Does the script need different DB access? By default, we give Maintenance
405 * scripts normal rights to the DB. Sometimes, a script needs admin rights
406 * access for a reason and sometimes they want no access. Subclasses should
407 * override and return one of the following values, as needed:
408 * Maintenance::DB_NONE - For no DB access at all
409 * Maintenance::DB_STD - For normal DB access, default
410 * Maintenance::DB_ADMIN - For admin DB access
413 public function getDbType() {
414 return Maintenance
::DB_STD
;
418 * Add the default parameters to the scripts
420 protected function addDefaultParams() {
422 # Generic (non script dependant) options:
424 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
425 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
426 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
427 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
428 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
429 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
430 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
431 "http://en.wikipedia.org. This is sometimes necessary because " .
432 "server name detection may fail in command line scripts.", false, true );
434 # Save generic options to display them separately in help
435 $this->mGenericParameters
= $this->mParams
;
437 # Script dependant options:
439 // If we support a DB, show the options
440 if ( $this->getDbType() > 0 ) {
441 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
442 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
445 # Save additional script dependant options to display
446 #Â them separately in help
447 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
451 * Run a child maintenance script. Pass all of the current arguments
453 * @param $maintClass String: a name of a child maintenance class
454 * @param $classFile String: full path of where the child is
455 * @return Maintenance child
457 public function runChild( $maintClass, $classFile = null ) {
458 // Make sure the class is loaded first
459 if ( !MWInit
::classExists( $maintClass ) ) {
461 require_once( $classFile );
463 if ( !MWInit
::classExists( $maintClass ) ) {
464 $this->error( "Cannot spawn child: $maintClass" );
469 * @var $child Maintenance
471 $child = new $maintClass();
472 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
473 if ( !is_null( $this->mDb
) ) {
474 $child->setDB( $this->mDb
);
480 * Do some sanity checking and basic setup
482 public function setup() {
483 global $wgCommandLineMode, $wgRequestTime;
485 # Abort if called from a web server
486 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
487 $this->error( 'This script must be run from the command line', true );
490 # Make sure we can handle script parameters
491 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
492 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
495 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
496 // Send PHP warnings and errors to stderr instead of stdout.
497 // This aids in diagnosing problems, while keeping messages
498 // out of redirected output.
499 if ( ini_get( 'display_errors' ) ) {
500 ini_set( 'display_errors', 'stderr' );
503 // Don't touch the setting on earlier versions of PHP,
504 // as setting it would disable output if you'd wanted it.
506 // Note that exceptions are also sent to stderr when
507 // command-line mode is on, regardless of PHP version.
510 $this->loadParamsAndArgs();
513 # Set the memory limit
514 # Note we need to set it again later in cache LocalSettings changed it
515 $this->adjustMemoryLimit();
517 # Set max execution time to 0 (no limit). PHP.net says that
518 # "When running PHP from the command line the default setting is 0."
519 # But sometimes this doesn't seem to be the case.
520 ini_set( 'max_execution_time', 0 );
522 $wgRequestTime = microtime( true );
524 # Define us as being in MediaWiki
525 define( 'MEDIAWIKI', true );
527 $wgCommandLineMode = true;
528 # Turn off output buffering if it's on
531 $this->validateParamsAndArgs();
535 * Normally we disable the memory_limit when running admin scripts.
536 * Some scripts may wish to actually set a limit, however, to avoid
537 * blowing up unexpectedly. We also support a --memory-limit option,
538 * to allow sysadmins to explicitly set one if they'd prefer to override
539 * defaults (or for people using Suhosin which yells at you for trying
540 * to disable the limits)
543 public function memoryLimit() {
544 $limit = $this->getOption( 'memory-limit', 'max' );
545 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
550 * Adjusts PHP's memory limit to better suit our needs, if needed.
552 protected function adjustMemoryLimit() {
553 $limit = $this->memoryLimit();
554 if ( $limit == 'max' ) {
555 $limit = -1; // no memory limit
557 if ( $limit != 'default' ) {
558 ini_set( 'memory_limit', $limit );
563 * Clear all params and arguments.
565 public function clearParamsAndArgs() {
566 $this->mOptions
= array();
567 $this->mArgs
= array();
568 $this->mInputLoaded
= false;
572 * Process command line arguments
573 * $mOptions becomes an array with keys set to the option names
574 * $mArgs becomes a zero-based array containing the non-option arguments
576 * @param $self String The name of the script, if any
577 * @param $opts Array An array of options, in form of key=>value
578 * @param $args Array An array of command line arguments
580 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
581 # If we were given opts or args, set those and return early
583 $this->mSelf
= $self;
584 $this->mInputLoaded
= true;
587 $this->mOptions
= $opts;
588 $this->mInputLoaded
= true;
591 $this->mArgs
= $args;
592 $this->mInputLoaded
= true;
595 # If we've already loaded input (either by user values or from $argv)
596 # skip on loading it again. The array_shift() will corrupt values if
597 # it's run again and again
598 if ( $this->mInputLoaded
) {
599 $this->loadSpecialVars();
604 $this->mSelf
= array_shift( $argv );
610 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
611 if ( $arg == '--' ) {
612 # End of options, remainder should be considered arguments
613 $arg = next( $argv );
614 while ( $arg !== false ) {
616 $arg = next( $argv );
619 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
621 $option = substr( $arg, 2 );
622 if ( array_key_exists( $option, $options ) ) {
623 $this->error( "\nERROR: $option parameter given twice\n" );
624 $this->maybeHelp( true );
626 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
627 $param = next( $argv );
628 if ( $param === false ) {
629 $this->error( "\nERROR: $option parameter needs a value after it\n" );
630 $this->maybeHelp( true );
632 $options[$option] = $param;
634 $bits = explode( '=', $option, 2 );
635 if ( count( $bits ) > 1 ) {
641 $options[$option] = $param;
643 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
645 for ( $p = 1; $p < strlen( $arg ); $p++
) {
646 $option = $arg { $p } ;
647 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
648 $option = $this->mShortParamsMap
[$option];
650 if ( array_key_exists( $option, $options ) ) {
651 $this->error( "\nERROR: $option parameter given twice\n" );
652 $this->maybeHelp( true );
654 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
655 $param = next( $argv );
656 if ( $param === false ) {
657 $this->error( "\nERROR: $option parameter needs a value after it\n" );
658 $this->maybeHelp( true );
660 $options[$option] = $param;
662 $options[$option] = 1;
670 $this->mOptions
= $options;
671 $this->mArgs
= $args;
672 $this->loadSpecialVars();
673 $this->mInputLoaded
= true;
677 * Run some validation checks on the params, etc
679 protected function validateParamsAndArgs() {
681 # Check to make sure we've got all the required options
682 foreach ( $this->mParams
as $opt => $info ) {
683 if ( $info['require'] && !$this->hasOption( $opt ) ) {
684 $this->error( "Param $opt required!" );
689 foreach ( $this->mArgList
as $k => $info ) {
690 if ( $info['require'] && !$this->hasArg( $k ) ) {
691 $this->error( 'Argument <' . $info['name'] . '> required!' );
697 $this->maybeHelp( true );
702 * Handle the special variables that are global to all scripts
704 protected function loadSpecialVars() {
705 if ( $this->hasOption( 'dbuser' ) ) {
706 $this->mDbUser
= $this->getOption( 'dbuser' );
708 if ( $this->hasOption( 'dbpass' ) ) {
709 $this->mDbPass
= $this->getOption( 'dbpass' );
711 if ( $this->hasOption( 'quiet' ) ) {
712 $this->mQuiet
= true;
714 if ( $this->hasOption( 'batch-size' ) ) {
715 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
720 * Maybe show the help.
721 * @param $force boolean Whether to force the help to show, default false
723 protected function maybeHelp( $force = false ) {
724 if( !$force && !$this->hasOption( 'help' ) ) {
728 $screenWidth = 80; // TODO: Caculate this!
730 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
732 ksort( $this->mParams
);
733 $this->mQuiet
= false;
736 if ( $this->mDescription
) {
737 $this->output( "\n" . $this->mDescription
. "\n" );
739 $output = "\nUsage: php " . basename( $this->mSelf
);
741 // ... append parameters ...
742 if ( $this->mParams
) {
743 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
746 // ... and append arguments.
747 if ( $this->mArgList
) {
749 foreach ( $this->mArgList
as $k => $arg ) {
750 if ( $arg['require'] ) {
751 $output .= '<' . $arg['name'] . '>';
753 $output .= '[' . $arg['name'] . ']';
755 if ( $k < count( $this->mArgList
) - 1 )
759 $this->output( "$output\n\n" );
761 # TODO abstract some repetitive code below
763 // Generic parameters
764 $this->output( "Generic maintenance parameters:\n" );
765 foreach ( $this->mGenericParameters
as $par => $info ) {
766 if ( $info['shortName'] !== false ) {
767 $par .= " (-{$info['shortName']})";
770 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
771 "\n$tab$tab" ) . "\n"
774 $this->output( "\n" );
776 $scriptDependantParams = $this->mDependantParameters
;
777 if( count($scriptDependantParams) > 0 ) {
778 $this->output( "Script dependant parameters:\n" );
779 // Parameters description
780 foreach ( $scriptDependantParams as $par => $info ) {
781 if ( $info['shortName'] !== false ) {
782 $par .= " (-{$info['shortName']})";
785 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
786 "\n$tab$tab" ) . "\n"
789 $this->output( "\n" );
793 // Script specific parameters not defined on construction by
794 // Maintenance::addDefaultParams()
795 $scriptSpecificParams = array_diff_key(
796 # all script parameters:
798 # remove the Maintenance default parameters:
799 $this->mGenericParameters
,
800 $this->mDependantParameters
802 if( count($scriptSpecificParams) > 0 ) {
803 $this->output( "Script specific parameters:\n" );
804 // Parameters description
805 foreach ( $scriptSpecificParams as $par => $info ) {
806 if ( $info['shortName'] !== false ) {
807 $par .= " (-{$info['shortName']})";
810 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
811 "\n$tab$tab" ) . "\n"
814 $this->output( "\n" );
818 if( count( $this->mArgList
) > 0 ) {
819 $this->output( "Arguments:\n" );
820 // Arguments description
821 foreach ( $this->mArgList
as $info ) {
822 $openChar = $info['require'] ?
'<' : '[';
823 $closeChar = $info['require'] ?
'>' : ']';
825 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
826 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
829 $this->output( "\n" );
836 * Handle some last-minute setup here.
838 public function finalSetup() {
839 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
840 global $wgDBadminuser, $wgDBadminpassword;
841 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
843 # Turn off output buffering again, it might have been turned on in the settings files
844 if ( ob_get_level() ) {
848 $wgCommandLineMode = true;
851 if( $this->hasOption( 'server') ) {
852 $wgServer = $this->getOption( 'server', $wgServer );
855 # If these were passed, use them
856 if ( $this->mDbUser
) {
857 $wgDBadminuser = $this->mDbUser
;
859 if ( $this->mDbPass
) {
860 $wgDBadminpassword = $this->mDbPass
;
863 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
864 $wgDBuser = $wgDBadminuser;
865 $wgDBpassword = $wgDBadminpassword;
867 if ( $wgDBservers ) {
869 * @var $wgDBservers array
871 foreach ( $wgDBservers as $i => $server ) {
872 $wgDBservers[$i]['user'] = $wgDBuser;
873 $wgDBservers[$i]['password'] = $wgDBpassword;
876 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
877 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
878 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
880 LBFactory
::destroyInstance();
883 $this->afterFinalSetup();
885 $wgShowSQLErrors = true;
886 @set_time_limit
( 0 );
887 $this->adjustMemoryLimit();
891 * Execute a callback function at the end of initialisation
893 protected function afterFinalSetup() {
894 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
895 call_user_func( MW_CMDLINE_CALLBACK
);
900 * Potentially debug globals. Originally a feature only
903 public function globals() {
904 if ( $this->hasOption( 'globals' ) ) {
910 * Generic setup for most installs. Returns the location of LocalSettings
913 public function loadSettings() {
914 global $wgCommandLineMode, $IP;
916 if ( isset( $this->mOptions
['conf'] ) ) {
917 $settingsFile = $this->mOptions
['conf'];
918 } elseif ( defined("MW_CONFIG_FILE") ) {
919 $settingsFile = MW_CONFIG_FILE
;
921 $settingsFile = "$IP/LocalSettings.php";
923 if ( isset( $this->mOptions
['wiki'] ) ) {
924 $bits = explode( '-', $this->mOptions
['wiki'] );
925 if ( count( $bits ) == 1 ) {
928 define( 'MW_DB', $bits[0] );
929 define( 'MW_PREFIX', $bits[1] );
932 if ( !is_readable( $settingsFile ) ) {
933 $this->error( "A copy of your installation's LocalSettings.php\n" .
934 "must exist and be readable in the source directory.\n" .
935 "Use --conf to specify it." , true );
937 $wgCommandLineMode = true;
938 return $settingsFile;
942 * Support function for cleaning up redundant text records
943 * @param $delete Boolean: whether or not to actually delete the records
944 * @author Rob Church <robchur@gmail.com>
946 public function purgeRedundantText( $delete = true ) {
947 # Data should come off the master, wrapped in a transaction
948 $dbw = $this->getDB( DB_MASTER
);
951 $tbl_arc = $dbw->tableName( 'archive' );
952 $tbl_rev = $dbw->tableName( 'revision' );
953 $tbl_txt = $dbw->tableName( 'text' );
955 # Get "active" text records from the revisions table
956 $this->output( 'Searching for active text records in revisions table...' );
957 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
958 foreach ( $res as $row ) {
959 $cur[] = $row->rev_text_id
;
961 $this->output( "done.\n" );
963 # Get "active" text records from the archive table
964 $this->output( 'Searching for active text records in archive table...' );
965 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
966 foreach ( $res as $row ) {
967 $cur[] = $row->ar_text_id
;
969 $this->output( "done.\n" );
971 # Get the IDs of all text records not in these sets
972 $this->output( 'Searching for inactive text records...' );
973 $set = implode( ', ', $cur );
974 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
976 foreach ( $res as $row ) {
977 $old[] = $row->old_id
;
979 $this->output( "done.\n" );
981 # Inform the user of what we're going to do
982 $count = count( $old );
983 $this->output( "$count inactive items found.\n" );
985 # Delete as appropriate
986 if ( $delete && $count ) {
987 $this->output( 'Deleting...' );
988 $set = implode( ', ', $old );
989 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
990 $this->output( "done.\n" );
998 * Get the maintenance directory.
1001 protected function getDir() {
1002 return dirname( __FILE__
);
1006 * Get the list of available maintenance scripts. Note
1007 * that if you call this _before_ calling doMaintenance
1008 * you won't have any extensions in it yet
1011 public static function getMaintenanceScripts() {
1012 global $wgMaintenanceScripts;
1013 return $wgMaintenanceScripts + self
::getCoreScripts();
1017 * Return all of the core maintenance scripts
1020 protected static function getCoreScripts() {
1021 if ( !self
::$mCoreScripts ) {
1023 dirname( __FILE__
),
1024 dirname( __FILE__
) . '/gearman',
1025 dirname( __FILE__
) . '/language',
1026 dirname( __FILE__
) . '/storage',
1028 self
::$mCoreScripts = array();
1029 foreach ( $paths as $p ) {
1030 $handle = opendir( $p );
1031 while ( ( $file = readdir( $handle ) ) !== false ) {
1032 if ( $file == 'Maintenance.php' ) {
1035 $file = $p . '/' . $file;
1036 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
1037 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1041 $vars = get_defined_vars();
1042 if ( array_key_exists( 'maintClass', $vars ) ) {
1043 self
::$mCoreScripts[$vars['maintClass']] = $file;
1046 closedir( $handle );
1049 return self
::$mCoreScripts;
1053 * Returns a database to be used by current maintenance script. It can be set by setDB().
1054 * If not set, wfGetDB() will be used.
1055 * This function has the same parameters as wfGetDB()
1057 * @return DatabaseBase
1059 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1060 if ( is_null( $this->mDb
) ) {
1061 return wfGetDB( $db, $groups, $wiki );
1068 * Sets database object to be returned by getDB().
1070 * @param $db DatabaseBase: Database object to be used
1072 public function setDB( &$db ) {
1077 * Lock the search index
1078 * @param &$db Database object
1080 private function lockSearchindex( &$db ) {
1081 $write = array( 'searchindex' );
1082 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1083 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1088 * @param &$db Database object
1090 private function unlockSearchindex( &$db ) {
1091 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1095 * Unlock and lock again
1096 * Since the lock is low-priority, queued reads will be able to complete
1097 * @param &$db Database object
1099 private function relockSearchindex( &$db ) {
1100 $this->unlockSearchindex( $db );
1101 $this->lockSearchindex( $db );
1105 * Perform a search index update with locking
1106 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1107 * @param $callback callback String: the function that will update the function.
1108 * @param $dbw DatabaseBase object
1111 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1115 if ( $maxLockTime ) {
1116 $this->output( " --- Waiting for lock ---" );
1117 $this->lockSearchindex( $dbw );
1119 $this->output( "\n" );
1122 # Loop through the results and do a search update
1123 foreach ( $results as $row ) {
1124 # Allow reads to be processed
1125 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1126 $this->output( " --- Relocking ---" );
1127 $this->relockSearchindex( $dbw );
1129 $this->output( "\n" );
1131 call_user_func( $callback, $dbw, $row );
1134 # Unlock searchindex
1135 if ( $maxLockTime ) {
1136 $this->output( " --- Unlocking --" );
1137 $this->unlockSearchindex( $dbw );
1138 $this->output( "\n" );
1144 * Update the searchindex table for a given pageid
1145 * @param $dbw Database: a database write handle
1146 * @param $pageId Integer: the page ID to update.
1147 * @return null|string
1149 public function updateSearchIndexForPage( $dbw, $pageId ) {
1150 // Get current revision
1151 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1154 $titleObj = $rev->getTitle();
1155 $title = $titleObj->getPrefixedDBkey();
1156 $this->output( "$title..." );
1157 # Update searchindex
1158 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1160 $this->output( "\n" );
1166 * Wrapper for posix_isatty()
1167 * We default as considering stdin a tty (for nice readline methods)
1168 * but treating stout as not a tty to avoid color codes
1170 * @param $fd int File descriptor
1173 public static function posix_isatty( $fd ) {
1174 if ( !MWInit
::functionExists( 'posix_isatty' ) ) {
1177 return posix_isatty( $fd );
1182 * Prompt the console for input
1183 * @param $prompt String what to begin the line with, like '> '
1184 * @return String response
1186 public static function readconsole( $prompt = '> ' ) {
1187 static $isatty = null;
1188 if ( is_null( $isatty ) ) {
1189 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1192 if ( $isatty && function_exists( 'readline' ) ) {
1193 return readline( $prompt );
1196 $st = self
::readlineEmulation( $prompt );
1198 if ( feof( STDIN
) ) {
1201 $st = fgets( STDIN
, 1024 );
1204 if ( $st === false ) return false;
1205 $resp = trim( $st );
1211 * Emulate readline()
1212 * @param $prompt String what to begin the line with, like '> '
1215 private static function readlineEmulation( $prompt ) {
1216 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1217 if ( !wfIsWindows() && $bash ) {
1219 $encPrompt = wfEscapeShellArg( $prompt );
1220 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1221 $encCommand = wfEscapeShellArg( $command );
1222 $line = wfShellExec( "$bash -c $encCommand", $retval );
1224 if ( $retval == 0 ) {
1226 } elseif ( $retval == 127 ) {
1227 // Couldn't execute bash even though we thought we saw it.
1228 // Shell probably spit out an error message, sorry :(
1229 // Fall through to fgets()...
1236 // Fallback... we'll have no editing controls, EWWW
1237 if ( feof( STDIN
) ) {
1241 return fgets( STDIN
, 1024 );
1246 * Fake maintenance wrapper, mostly used for the web installer/updater
1248 class FakeMaintenance
extends Maintenance
{
1249 protected $mSelf = "FakeMaintenanceScript";
1250 public function execute() {
1256 * Class for scripts that perform database maintenance and want to log the
1257 * update in `updatelog` so we can later skip it
1259 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1260 public function __construct() {
1261 parent
::__construct();
1262 $this->addOption( 'force', 'Run the update even if it was completed already' );
1263 $this->setBatchSize( 200 );
1266 public function execute() {
1267 $db = $this->getDB( DB_MASTER
);
1268 $key = $this->getUpdateKey();
1270 if ( !$this->hasOption( 'force' ) &&
1271 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
) )
1273 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1277 if ( !$this->doDBUpdates() ) {
1282 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) )
1286 $this->output( $this->updatelogFailedMessage() . "\n" );
1292 * Message to show that the update was done already and was just skipped
1295 protected function updateSkippedMessage() {
1296 $key = $this->getUpdateKey();
1297 return "Update '{$key}' already logged as completed.";
1301 * Message to show the the update log was unable to log the completion of this update
1304 protected function updatelogFailedMessage() {
1305 $key = $this->getUpdateKey();
1306 return "Unable to log update '{$key}' as completed.";
1310 * Do the actual work. All child classes will need to implement this.
1311 * Return true to log the update as done or false (usually on failure).
1314 abstract protected function doDBUpdates();
1317 * Get the update key name to go in the update log table
1320 abstract protected function getUpdateKey();