9cd853860c5f42579887c19521543552662f5c24
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;
254 * Get the script's name
257 public function getName() {
262 * Return input from stdin.
263 * @param $len Integer: the number of bytes to read. If null,
264 * just return the handle. Maintenance::STDIN_ALL returns
268 protected function getStdin( $len = null ) {
269 if ( $len == Maintenance
::STDIN_ALL
) {
270 return file_get_contents( 'php://stdin' );
272 $f = fopen( 'php://stdin', 'rt' );
276 $input = fgets( $f, $len );
278 return rtrim( $input );
281 public function isQuiet() {
282 return $this->mQuiet
;
286 * Throw some output to the user. Scripts can call this with no fears,
287 * as we handle all --quiet stuff here
288 * @param $out String: the text to show to the user
289 * @param $channel Mixed: unique identifier for the channel. See
290 * function outputChanneled.
292 protected function output( $out, $channel = null ) {
293 if ( $this->mQuiet
) {
296 if ( $channel === null ) {
297 $this->cleanupChanneled();
299 $f = fopen( 'php://stdout', 'w' );
304 $out = preg_replace( '/\n\z/', '', $out );
305 $this->outputChanneled( $out, $channel );
310 * Throw an error to the user. Doesn't respect --quiet, so don't use
311 * this for non-error output
312 * @param $err String: the error to display
313 * @param $die Int: if > 0, go ahead and die out using this int as the code
315 protected function error( $err, $die = 0 ) {
316 $this->outputChanneled( false );
317 if ( php_sapi_name() == 'cli' ) {
318 fwrite( STDERR
, $err . "\n" );
320 $f = fopen( 'php://stderr', 'w' );
321 fwrite( $f, $err . "\n" );
324 $die = intval( $die );
330 private $atLineStart = true;
331 private $lastChannel = null;
334 * Clean up channeled output. Output a newline if necessary.
336 public function cleanupChanneled() {
337 if ( !$this->atLineStart
) {
338 $handle = fopen( 'php://stdout', 'w' );
339 fwrite( $handle, "\n" );
341 $this->atLineStart
= true;
346 * Message outputter with channeled message support. Messages on the
347 * same channel are concatenated, but any intervening messages in another
348 * channel start a new line.
349 * @param $msg String: the message without trailing newline
350 * @param $channel Channel identifier or null for no
351 * channel. Channel comparison uses ===.
353 public function outputChanneled( $msg, $channel = null ) {
354 if ( $msg === false ) {
355 $this->cleanupChanneled();
359 $handle = fopen( 'php://stdout', 'w' );
361 // End the current line if necessary
362 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
363 fwrite( $handle, "\n" );
366 fwrite( $handle, $msg );
368 $this->atLineStart
= false;
369 if ( $channel === null ) {
370 // For unchanneled messages, output trailing newline immediately
371 fwrite( $handle, "\n" );
372 $this->atLineStart
= true;
374 $this->lastChannel
= $channel;
381 * Does the script need different DB access? By default, we give Maintenance
382 * scripts normal rights to the DB. Sometimes, a script needs admin rights
383 * access for a reason and sometimes they want no access. Subclasses should
384 * override and return one of the following values, as needed:
385 * Maintenance::DB_NONE - For no DB access at all
386 * Maintenance::DB_STD - For normal DB access, default
387 * Maintenance::DB_ADMIN - For admin DB access
390 public function getDbType() {
391 return Maintenance
::DB_STD
;
395 * Add the default parameters to the scripts
397 protected function addDefaultParams() {
399 # Generic (non script dependant) options:
401 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
402 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
403 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
404 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
405 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
406 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
407 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
408 "http://en.wikipedia.org. This is sometimes necessary because " .
409 "server name detection may fail in command line scripts.", false, true );
411 # Save generic options to display them separately in help
412 $this->mGenericParameters
= $this->mParams
;
414 # Script dependant options:
416 // If we support a DB, show the options
417 if ( $this->getDbType() > 0 ) {
418 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
419 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
421 // If we support $mBatchSize, show the option
422 if ( $this->mBatchSize
) {
423 $this->addOption( 'batch-size', 'Run this many operations ' .
424 'per batch, default: ' . $this->mBatchSize
, false, true );
426 # Save additional script dependant options to display
427 #Â them separately in help
428 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
432 * Run a child maintenance script. Pass all of the current arguments
434 * @param $maintClass String: a name of a child maintenance class
435 * @param $classFile String: full path of where the child is
436 * @return Maintenance child
438 public function runChild( $maintClass, $classFile = null ) {
439 // Make sure the class is loaded first
440 if ( !MWInit
::classExists( $maintClass ) ) {
442 require_once( $classFile );
444 if ( !MWInit
::classExists( $maintClass ) ) {
445 $this->error( "Cannot spawn child: $maintClass" );
449 $child = new $maintClass();
450 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
451 if ( !is_null( $this->mDb
) ) {
452 $child->setDB( $this->mDb
);
458 * Do some sanity checking and basic setup
460 public function setup() {
461 global $wgCommandLineMode, $wgRequestTime;
463 # Abort if called from a web server
464 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
465 $this->error( 'This script must be run from the command line', true );
468 # Make sure we can handle script parameters
469 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
470 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
473 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
474 // Send PHP warnings and errors to stderr instead of stdout.
475 // This aids in diagnosing problems, while keeping messages
476 // out of redirected output.
477 if ( ini_get( 'display_errors' ) ) {
478 ini_set( 'display_errors', 'stderr' );
481 // Don't touch the setting on earlier versions of PHP,
482 // as setting it would disable output if you'd wanted it.
484 // Note that exceptions are also sent to stderr when
485 // command-line mode is on, regardless of PHP version.
488 $this->loadParamsAndArgs();
491 # Set the memory limit
492 # Note we need to set it again later in cache LocalSettings changed it
493 $this->adjustMemoryLimit();
495 # Set max execution time to 0 (no limit). PHP.net says that
496 # "When running PHP from the command line the default setting is 0."
497 # But sometimes this doesn't seem to be the case.
498 ini_set( 'max_execution_time', 0 );
500 $wgRequestTime = microtime( true );
502 # Define us as being in MediaWiki
503 define( 'MEDIAWIKI', true );
505 $wgCommandLineMode = true;
506 # Turn off output buffering if it's on
509 $this->validateParamsAndArgs();
513 * Normally we disable the memory_limit when running admin scripts.
514 * Some scripts may wish to actually set a limit, however, to avoid
515 * blowing up unexpectedly. We also support a --memory-limit option,
516 * to allow sysadmins to explicitly set one if they'd prefer to override
517 * defaults (or for people using Suhosin which yells at you for trying
518 * to disable the limits)
520 public function memoryLimit() {
521 $limit = $this->getOption( 'memory-limit', 'max' );
522 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
527 * Adjusts PHP's memory limit to better suit our needs, if needed.
529 protected function adjustMemoryLimit() {
530 $limit = $this->memoryLimit();
531 if ( $limit == 'max' ) {
532 $limit = -1; // no memory limit
534 if ( $limit != 'default' ) {
535 ini_set( 'memory_limit', $limit );
540 * Clear all params and arguments.
542 public function clearParamsAndArgs() {
543 $this->mOptions
= array();
544 $this->mArgs
= array();
545 $this->mInputLoaded
= false;
549 * Process command line arguments
550 * $mOptions becomes an array with keys set to the option names
551 * $mArgs becomes a zero-based array containing the non-option arguments
553 * @param $self String The name of the script, if any
554 * @param $opts Array An array of options, in form of key=>value
555 * @param $args Array An array of command line arguments
557 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
558 # If we were given opts or args, set those and return early
560 $this->mSelf
= $self;
561 $this->mInputLoaded
= true;
564 $this->mOptions
= $opts;
565 $this->mInputLoaded
= true;
568 $this->mArgs
= $args;
569 $this->mInputLoaded
= true;
572 # If we've already loaded input (either by user values or from $argv)
573 # skip on loading it again. The array_shift() will corrupt values if
574 # it's run again and again
575 if ( $this->mInputLoaded
) {
576 $this->loadSpecialVars();
581 $this->mSelf
= array_shift( $argv );
587 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
588 if ( $arg == '--' ) {
589 # End of options, remainder should be considered arguments
590 $arg = next( $argv );
591 while ( $arg !== false ) {
593 $arg = next( $argv );
596 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
598 $option = substr( $arg, 2 );
599 if ( array_key_exists( $option, $options ) ) {
600 $this->error( "\nERROR: $option parameter given twice\n" );
601 $this->maybeHelp( true );
603 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
604 $param = next( $argv );
605 if ( $param === false ) {
606 $this->error( "\nERROR: $option parameter needs a value after it\n" );
607 $this->maybeHelp( true );
609 $options[$option] = $param;
611 $bits = explode( '=', $option, 2 );
612 if ( count( $bits ) > 1 ) {
618 $options[$option] = $param;
620 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
622 for ( $p = 1; $p < strlen( $arg ); $p++
) {
623 $option = $arg { $p } ;
624 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
625 $option = $this->mShortParamsMap
[$option];
627 if ( array_key_exists( $option, $options ) ) {
628 $this->error( "\nERROR: $option parameter given twice\n" );
629 $this->maybeHelp( true );
631 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
632 $param = next( $argv );
633 if ( $param === false ) {
634 $this->error( "\nERROR: $option parameter needs a value after it\n" );
635 $this->maybeHelp( true );
637 $options[$option] = $param;
639 $options[$option] = 1;
647 $this->mOptions
= $options;
648 $this->mArgs
= $args;
649 $this->loadSpecialVars();
650 $this->mInputLoaded
= true;
654 * Run some validation checks on the params, etc
656 protected function validateParamsAndArgs() {
658 # Check to make sure we've got all the required options
659 foreach ( $this->mParams
as $opt => $info ) {
660 if ( $info['require'] && !$this->hasOption( $opt ) ) {
661 $this->error( "Param $opt required!" );
666 foreach ( $this->mArgList
as $k => $info ) {
667 if ( $info['require'] && !$this->hasArg( $k ) ) {
668 $this->error( 'Argument <' . $info['name'] . '> required!' );
674 $this->maybeHelp( true );
679 * Handle the special variables that are global to all scripts
681 protected function loadSpecialVars() {
682 if ( $this->hasOption( 'dbuser' ) ) {
683 $this->mDbUser
= $this->getOption( 'dbuser' );
685 if ( $this->hasOption( 'dbpass' ) ) {
686 $this->mDbPass
= $this->getOption( 'dbpass' );
688 if ( $this->hasOption( 'quiet' ) ) {
689 $this->mQuiet
= true;
691 if ( $this->hasOption( 'batch-size' ) ) {
692 $this->mBatchSize
= $this->getOption( 'batch-size' );
697 * Maybe show the help.
698 * @param $force boolean Whether to force the help to show, default false
700 protected function maybeHelp( $force = false ) {
701 if( !$force && !$this->hasOption( 'help' ) ) {
705 $screenWidth = 80; // TODO: Caculate this!
707 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
709 ksort( $this->mParams
);
710 $this->mQuiet
= false;
713 if ( $this->mDescription
) {
714 $this->output( "\n" . $this->mDescription
. "\n" );
716 $output = "\nUsage: php " . basename( $this->mSelf
);
718 // ... append parameters ...
719 if ( $this->mParams
) {
720 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
723 // ... and append arguments.
724 if ( $this->mArgList
) {
726 foreach ( $this->mArgList
as $k => $arg ) {
727 if ( $arg['require'] ) {
728 $output .= '<' . $arg['name'] . '>';
730 $output .= '[' . $arg['name'] . ']';
732 if ( $k < count( $this->mArgList
) - 1 )
736 $this->output( "$output\n\n" );
738 # TODO abstract some repetitive code below
740 // Generic parameters
741 $this->output( "Generic maintenance parameters:\n" );
742 foreach ( $this->mGenericParameters
as $par => $info ) {
743 if ( $info['shortName'] !== false ) {
744 $par .= " (-{$info['shortName']})";
747 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
748 "\n$tab$tab" ) . "\n"
751 $this->output( "\n" );
753 $scriptDependantParams = $this->mDependantParameters
;
754 if( count($scriptDependantParams) > 0 ) {
755 $this->output( "Script dependant parameters:\n" );
756 // Parameters description
757 foreach ( $scriptDependantParams as $par => $info ) {
758 if ( $info['shortName'] !== false ) {
759 $par .= " (-{$info['shortName']})";
762 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
763 "\n$tab$tab" ) . "\n"
766 $this->output( "\n" );
770 // Script specific parameters not defined on construction by
771 // Maintenance::addDefaultParams()
772 $scriptSpecificParams = array_diff_key(
773 # all script parameters:
775 # remove the Maintenance default parameters:
776 $this->mGenericParameters
,
777 $this->mDependantParameters
779 if( count($scriptSpecificParams) > 0 ) {
780 $this->output( "Script specific parameters:\n" );
781 // Parameters description
782 foreach ( $scriptSpecificParams as $par => $info ) {
783 if ( $info['shortName'] !== false ) {
784 $par .= " (-{$info['shortName']})";
787 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
788 "\n$tab$tab" ) . "\n"
791 $this->output( "\n" );
795 if( count( $this->mArgList
) > 0 ) {
796 $this->output( "Arguments:\n" );
797 // Arguments description
798 foreach ( $this->mArgList
as $info ) {
799 $openChar = $info['require'] ?
'<' : '[';
800 $closeChar = $info['require'] ?
'>' : ']';
802 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
803 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
806 $this->output( "\n" );
813 * Handle some last-minute setup here.
815 public function finalSetup() {
816 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
817 global $wgDBadminuser, $wgDBadminpassword;
818 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
820 # Turn off output buffering again, it might have been turned on in the settings files
821 if ( ob_get_level() ) {
825 $wgCommandLineMode = true;
828 if( $this->hasOption( 'server') ) {
829 $wgServer = $this->getOption( 'server', $wgServer );
832 # If these were passed, use them
833 if ( $this->mDbUser
) {
834 $wgDBadminuser = $this->mDbUser
;
836 if ( $this->mDbPass
) {
837 $wgDBadminpassword = $this->mDbPass
;
840 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
841 $wgDBuser = $wgDBadminuser;
842 $wgDBpassword = $wgDBadminpassword;
844 if ( $wgDBservers ) {
845 foreach ( $wgDBservers as $i => $server ) {
846 $wgDBservers[$i]['user'] = $wgDBuser;
847 $wgDBservers[$i]['password'] = $wgDBpassword;
850 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
851 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
852 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
854 LBFactory
::destroyInstance();
857 $this->afterFinalSetup();
859 $wgShowSQLErrors = true;
860 @set_time_limit
( 0 );
861 $this->adjustMemoryLimit();
865 * Execute a callback function at the end of initialisation
867 protected function afterFinalSetup() {
868 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
869 call_user_func( MW_CMDLINE_CALLBACK
);
874 * Potentially debug globals. Originally a feature only
877 public function globals() {
878 if ( $this->hasOption( 'globals' ) ) {
884 * Do setup specific to WMF
886 public function loadWikimediaSettings() {
887 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
889 if ( empty( $wgNoDBParam ) ) {
890 # Check if we were passed a db name
891 if ( isset( $this->mOptions
['wiki'] ) ) {
892 $db = $this->mOptions
['wiki'];
894 $db = array_shift( $this->mArgs
);
896 list( $site, $lang ) = $wgConf->siteFromDB( $db );
898 # If not, work out the language and site the old way
899 if ( is_null( $site ) ||
is_null( $lang ) ) {
905 if ( isset( $this->mArgs
[0] ) ) {
906 $site = array_shift( $this->mArgs
);
916 # This is for the IRC scripts, which now run as the apache user
917 # The apache user doesn't have access to the wikiadmin_pass command
918 if ( $_ENV['USER'] == 'apache' ) {
919 # if ( posix_geteuid() == 48 ) {
920 $wgUseNormalUser = true;
923 putenv( 'wikilang=' . $lang );
925 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
927 if ( $lang == 'test' && $site == 'wikipedia' ) {
928 if ( !defined( 'TESTWIKI' ) ) {
929 define( 'TESTWIKI', 1 );
935 * Generic setup for most installs. Returns the location of LocalSettings
938 public function loadSettings() {
939 global $wgCommandLineMode, $IP;
941 if ( isset( $this->mOptions
['conf'] ) ) {
942 $settingsFile = $this->mOptions
['conf'];
943 } elseif ( defined("MW_CONFIG_FILE") ) {
944 $settingsFile = MW_CONFIG_FILE
;
946 $settingsFile = "$IP/LocalSettings.php";
948 if ( isset( $this->mOptions
['wiki'] ) ) {
949 $bits = explode( '-', $this->mOptions
['wiki'] );
950 if ( count( $bits ) == 1 ) {
953 define( 'MW_DB', $bits[0] );
954 define( 'MW_PREFIX', $bits[1] );
957 if ( !is_readable( $settingsFile ) ) {
958 $this->error( "A copy of your installation's LocalSettings.php\n" .
959 "must exist and be readable in the source directory.\n" .
960 "Use --conf to specify it." , true );
962 $wgCommandLineMode = true;
963 return $settingsFile;
967 * Support function for cleaning up redundant text records
968 * @param $delete Boolean: whether or not to actually delete the records
969 * @author Rob Church <robchur@gmail.com>
971 public function purgeRedundantText( $delete = true ) {
972 # Data should come off the master, wrapped in a transaction
973 $dbw = $this->getDB( DB_MASTER
);
976 $tbl_arc = $dbw->tableName( 'archive' );
977 $tbl_rev = $dbw->tableName( 'revision' );
978 $tbl_txt = $dbw->tableName( 'text' );
980 # Get "active" text records from the revisions table
981 $this->output( 'Searching for active text records in revisions table...' );
982 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
983 foreach ( $res as $row ) {
984 $cur[] = $row->rev_text_id
;
986 $this->output( "done.\n" );
988 # Get "active" text records from the archive table
989 $this->output( 'Searching for active text records in archive table...' );
990 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
991 foreach ( $res as $row ) {
992 $cur[] = $row->ar_text_id
;
994 $this->output( "done.\n" );
996 # Get the IDs of all text records not in these sets
997 $this->output( 'Searching for inactive text records...' );
998 $set = implode( ', ', $cur );
999 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
1001 foreach ( $res as $row ) {
1002 $old[] = $row->old_id
;
1004 $this->output( "done.\n" );
1006 # Inform the user of what we're going to do
1007 $count = count( $old );
1008 $this->output( "$count inactive items found.\n" );
1010 # Delete as appropriate
1011 if ( $delete && $count ) {
1012 $this->output( 'Deleting...' );
1013 $set = implode( ', ', $old );
1014 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
1015 $this->output( "done.\n" );
1023 * Get the maintenance directory.
1025 protected function getDir() {
1026 return dirname( __FILE__
);
1030 * Get the list of available maintenance scripts. Note
1031 * that if you call this _before_ calling doMaintenance
1032 * you won't have any extensions in it yet
1035 public static function getMaintenanceScripts() {
1036 global $wgMaintenanceScripts;
1037 return $wgMaintenanceScripts + self
::getCoreScripts();
1041 * Return all of the core maintenance scripts
1044 protected static function getCoreScripts() {
1045 if ( !self
::$mCoreScripts ) {
1047 dirname( __FILE__
),
1048 dirname( __FILE__
) . '/gearman',
1049 dirname( __FILE__
) . '/language',
1050 dirname( __FILE__
) . '/storage',
1052 self
::$mCoreScripts = array();
1053 foreach ( $paths as $p ) {
1054 $handle = opendir( $p );
1055 while ( ( $file = readdir( $handle ) ) !== false ) {
1056 if ( $file == 'Maintenance.php' ) {
1059 $file = $p . '/' . $file;
1060 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
1061 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1065 $vars = get_defined_vars();
1066 if ( array_key_exists( 'maintClass', $vars ) ) {
1067 self
::$mCoreScripts[$vars['maintClass']] = $file;
1070 closedir( $handle );
1073 return self
::$mCoreScripts;
1077 * Returns a database to be used by current maintenance script. It can be set by setDB().
1078 * If not set, wfGetDB() will be used.
1079 * This function has the same parameters as wfGetDB()
1081 * @return DatabaseBase
1083 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1084 if ( is_null( $this->mDb
) ) {
1085 return wfGetDB( $db, $groups, $wiki );
1092 * Sets database object to be returned by getDB().
1094 * @param $db DatabaseBase: Database object to be used
1096 public function setDB( &$db ) {
1101 * Lock the search index
1102 * @param &$db Database object
1104 private function lockSearchindex( &$db ) {
1105 $write = array( 'searchindex' );
1106 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1107 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1112 * @param &$db Database object
1114 private function unlockSearchindex( &$db ) {
1115 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1119 * Unlock and lock again
1120 * Since the lock is low-priority, queued reads will be able to complete
1121 * @param &$db Database object
1123 private function relockSearchindex( &$db ) {
1124 $this->unlockSearchindex( $db );
1125 $this->lockSearchindex( $db );
1129 * Perform a search index update with locking
1130 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1131 * @param $callback callback String: the function that will update the function.
1132 * @param $dbw DatabaseBase object
1135 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1139 if ( $maxLockTime ) {
1140 $this->output( " --- Waiting for lock ---" );
1141 $this->lockSearchindex( $dbw );
1143 $this->output( "\n" );
1146 # Loop through the results and do a search update
1147 foreach ( $results as $row ) {
1148 # Allow reads to be processed
1149 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1150 $this->output( " --- Relocking ---" );
1151 $this->relockSearchindex( $dbw );
1153 $this->output( "\n" );
1155 call_user_func( $callback, $dbw, $row );
1158 # Unlock searchindex
1159 if ( $maxLockTime ) {
1160 $this->output( " --- Unlocking --" );
1161 $this->unlockSearchindex( $dbw );
1162 $this->output( "\n" );
1168 * Update the searchindex table for a given pageid
1169 * @param $dbw Database: a database write handle
1170 * @param $pageId Integer: the page ID to update.
1172 public function updateSearchIndexForPage( $dbw, $pageId ) {
1173 // Get current revision
1174 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1177 $titleObj = $rev->getTitle();
1178 $title = $titleObj->getPrefixedDBkey();
1179 $this->output( "$title..." );
1180 # Update searchindex
1181 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1183 $this->output( "\n" );
1189 * Wrapper for posix_isatty()
1190 * We default as considering stdin a tty (for nice readline methods)
1191 * but treating stout as not a tty to avoid color codes
1193 * @param $fd int File descriptor
1196 public static function posix_isatty( $fd ) {
1197 if ( !MWInit
::functionExists( 'posix_isatty' ) ) {
1200 return posix_isatty( $fd );
1205 * Prompt the console for input
1206 * @param $prompt String what to begin the line with, like '> '
1207 * @return String response
1209 public static function readconsole( $prompt = '> ' ) {
1210 static $isatty = null;
1211 if ( is_null( $isatty ) ) {
1212 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1215 if ( $isatty && function_exists( 'readline' ) ) {
1216 return readline( $prompt );
1219 $st = self
::readlineEmulation( $prompt );
1221 if ( feof( STDIN
) ) {
1224 $st = fgets( STDIN
, 1024 );
1227 if ( $st === false ) return false;
1228 $resp = trim( $st );
1234 * Emulate readline()
1235 * @param $prompt String what to begin the line with, like '> '
1238 private static function readlineEmulation( $prompt ) {
1239 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1240 if ( !wfIsWindows() && $bash ) {
1242 $encPrompt = wfEscapeShellArg( $prompt );
1243 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1244 $encCommand = wfEscapeShellArg( $command );
1245 $line = wfShellExec( "$bash -c $encCommand", $retval );
1247 if ( $retval == 0 ) {
1249 } elseif ( $retval == 127 ) {
1250 // Couldn't execute bash even though we thought we saw it.
1251 // Shell probably spit out an error message, sorry :(
1252 // Fall through to fgets()...
1259 // Fallback... we'll have no editing controls, EWWW
1260 if ( feof( STDIN
) ) {
1264 return fgets( STDIN
, 1024 );
1268 class FakeMaintenance
extends Maintenance
{
1269 protected $mSelf = "FakeMaintenanceScript";
1270 public function execute() {
1275 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1276 public function __construct() {
1277 parent
::__construct();
1278 $this->addOption( 'force', 'Run the update even if it was completed already' );
1281 public function execute() {
1282 $db = $this->getDB( DB_MASTER
);
1283 $key = $this->getUpdateKey();
1285 if ( !$this->hasOption( 'force' ) &&
1286 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
) )
1288 $this->output( $this->updateSkippedMessage() . "\n" );
1292 if ( !$this->doDBUpdates() ) {
1297 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) )
1301 $this->output( $this->updatelogFailedMessage() . "\n" );
1307 * Do the actual work. All child classes will need to implement this.
1308 * Return true to log the update as done or false (usually on failure).
1311 abstract protected function doDBUpdates();
1314 * Get the update key name to go in the update log table
1317 abstract protected function getUpdateKey();
1320 * Message to show that the update was done already and was just skipped
1323 abstract protected function updateSkippedMessage();
1326 * Message to show the the update log was unable to log the completion of this update
1329 abstract protected function updatelogFailedMessage();