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 // Make sure we're on PHP5.3.2 or better
24 if ( !function_exists( 'version_compare' ) ||
version_compare( PHP_VERSION
, '5.3.2' ) < 0 ) {
25 // We need to use dirname( __FILE__ ) here cause __DIR__ is PHP5.3+
26 require_once( dirname( __FILE__
) . '/../includes/PHPVersionError.php' );
27 wfPHPVersionError( 'cli' );
31 * @defgroup MaintenanceArchive Maintenance archives
32 * @ingroup Maintenance
35 // Define this so scripts can easily find doMaintenance.php
36 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
37 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
42 * Abstract maintenance class for quickly writing and churning out
43 * maintenance scripts with minimal effort. All that _must_ be defined
44 * is the execute() method. See docs/maintenance.txt for more info
45 * and a quick demo of how to use it.
47 * @author Chad Horohoe <chad@anyonecanedit.org>
49 * @ingroup Maintenance
51 abstract class Maintenance
{
54 * Constants for DB access type
55 * @see Maintenance::getDbType()
61 // Const for getStdin()
62 const STDIN_ALL
= 'all';
64 // This is the desired params
65 protected $mParams = array();
67 // Array of mapping short parameters to long ones
68 protected $mShortParamsMap = array();
70 // Array of desired args
71 protected $mArgList = array();
73 // This is the list of options that were actually passed
74 protected $mOptions = array();
76 // This is the list of arguments that were actually passed
77 protected $mArgs = array();
79 // Name of the script currently running
82 // Special vars for params that are always used
83 protected $mQuiet = false;
84 protected $mDbUser, $mDbPass;
86 // A description of the script, children should change this
87 protected $mDescription = '';
89 // Have we already loaded our user input?
90 protected $mInputLoaded = false;
93 * Batch size. If a script supports this, they should set
94 * a default with setBatchSize()
98 protected $mBatchSize = null;
100 // Generic options added by addDefaultParams()
101 private $mGenericParameters = array();
102 // Generic options which might or not be supported by the script
103 private $mDependantParameters = array();
106 * Used by getDD() / setDB()
112 * List of all the core maintenance scripts. This is added
113 * to scripts added by extensions in $wgMaintenanceScripts
114 * and returned by getMaintenanceScripts()
116 protected static $mCoreScripts = null;
119 * Default constructor. Children should call this *first* if implementing
120 * their own constructors
122 public function __construct() {
123 // Setup $IP, using MW_INSTALL_PATH if it exists
125 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
126 ?
getenv( 'MW_INSTALL_PATH' )
127 : realpath( __DIR__
. '/..' );
129 $this->addDefaultParams();
130 register_shutdown_function( array( $this, 'outputChanneled' ), false );
134 * Should we execute the maintenance script, or just allow it to be included
135 * as a standalone class? It checks that the call stack only includes this
136 * function and "requires" (meaning was called from the file scope)
140 public static function shouldExecute() {
141 $bt = debug_backtrace();
142 $count = count( $bt );
144 return false; // sanity
146 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
147 return false; // last call should be to this function
149 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
150 for( $i=1; $i < $count; $i++
) {
151 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
152 return false; // previous calls should all be "requires"
159 * Do the actual work. All child classes will need to implement this
161 abstract public function execute();
164 * Add a parameter to the script. Will be displayed on --help
165 * with the associated description
167 * @param $name String: the name of the param (help, version, etc)
168 * @param $description String: the description of the param to show on --help
169 * @param $required Boolean: is the param required?
170 * @param $withArg Boolean: is an argument required with this option?
171 * @param $shortName String: character to use as short name
173 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
174 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
175 if ( $shortName !== false ) {
176 $this->mShortParamsMap
[$shortName] = $name;
181 * Checks to see if a particular param exists.
182 * @param $name String: the name of the param
185 protected function hasOption( $name ) {
186 return isset( $this->mOptions
[$name] );
190 * Get an option, or return the default
191 * @param $name String: the name of the param
192 * @param $default Mixed: anything you want, default null
195 protected function getOption( $name, $default = null ) {
196 if ( $this->hasOption( $name ) ) {
197 return $this->mOptions
[$name];
199 // Set it so we don't have to provide the default again
200 $this->mOptions
[$name] = $default;
201 return $this->mOptions
[$name];
206 * Add some args that are needed
207 * @param $arg String: name of the arg, like 'start'
208 * @param $description String: short description of the arg
209 * @param $required Boolean: is this required?
211 protected function addArg( $arg, $description, $required = true ) {
212 $this->mArgList
[] = array(
214 'desc' => $description,
215 'require' => $required
220 * Remove an option. Useful for removing options that won't be used in your script.
221 * @param $name String: the option to remove.
223 protected function deleteOption( $name ) {
224 unset( $this->mParams
[$name] );
228 * Set the description text.
229 * @param $text String: the text of the description
231 protected function addDescription( $text ) {
232 $this->mDescription
= $text;
236 * Does a given argument exist?
237 * @param $argId Integer: the integer value (from zero) for the arg
240 protected function hasArg( $argId = 0 ) {
241 return isset( $this->mArgs
[$argId] );
246 * @param $argId Integer: the integer value (from zero) for the arg
247 * @param $default Mixed: the default if it doesn't exist
250 protected function getArg( $argId = 0, $default = null ) {
251 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
255 * Set the batch size.
256 * @param $s Integer: the number of operations to do in a batch
258 protected function setBatchSize( $s = 0 ) {
259 $this->mBatchSize
= $s;
261 // If we support $mBatchSize, show the option.
262 // Used to be in addDefaultParams, but in order for that to
263 // work, subclasses would have to call this function in the constructor
264 // before they called parent::__construct which is just weird
265 // (and really wasn't done).
266 if ( $this->mBatchSize
) {
267 $this->addOption( 'batch-size', 'Run this many operations ' .
268 'per batch, default: ' . $this->mBatchSize
, false, true );
269 if ( isset( $this->mParams
['batch-size'] ) ) {
270 // This seems a little ugly...
271 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
277 * Get the script's name
280 public function getName() {
285 * Return input from stdin.
286 * @param $len Integer: the number of bytes to read. If null,
287 * just return the handle. Maintenance::STDIN_ALL returns
291 protected function getStdin( $len = null ) {
292 if ( $len == Maintenance
::STDIN_ALL
) {
293 return file_get_contents( 'php://stdin' );
295 $f = fopen( 'php://stdin', 'rt' );
299 $input = fgets( $f, $len );
301 return rtrim( $input );
307 public function isQuiet() {
308 return $this->mQuiet
;
312 * Throw some output to the user. Scripts can call this with no fears,
313 * as we handle all --quiet stuff here
314 * @param $out String: the text to show to the user
315 * @param $channel Mixed: unique identifier for the channel. See
316 * function outputChanneled.
318 protected function output( $out, $channel = null ) {
319 if ( $this->mQuiet
) {
322 if ( $channel === null ) {
323 $this->cleanupChanneled();
326 $out = preg_replace( '/\n\z/', '', $out );
327 $this->outputChanneled( $out, $channel );
332 * Throw an error to the user. Doesn't respect --quiet, so don't use
333 * this for non-error output
334 * @param $err String: the error to display
335 * @param $die Int: if > 0, go ahead and die out using this int as the code
337 protected function error( $err, $die = 0 ) {
338 $this->outputChanneled( false );
339 if ( php_sapi_name() == 'cli' ) {
340 fwrite( STDERR
, $err . "\n" );
344 $die = intval( $die );
350 private $atLineStart = true;
351 private $lastChannel = null;
354 * Clean up channeled output. Output a newline if necessary.
356 public function cleanupChanneled() {
357 if ( !$this->atLineStart
) {
359 $this->atLineStart
= true;
364 * Message outputter with channeled message support. Messages on the
365 * same channel are concatenated, but any intervening messages in another
366 * channel start a new line.
367 * @param $msg String: the message without trailing newline
368 * @param $channel string Channel identifier or null for no
369 * channel. Channel comparison uses ===.
371 public function outputChanneled( $msg, $channel = null ) {
372 if ( $msg === false ) {
373 $this->cleanupChanneled();
377 // End the current line if necessary
378 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
384 $this->atLineStart
= false;
385 if ( $channel === null ) {
386 // For unchanneled messages, output trailing newline immediately
388 $this->atLineStart
= true;
390 $this->lastChannel
= $channel;
394 * Does the script need different DB access? By default, we give Maintenance
395 * scripts normal rights to the DB. Sometimes, a script needs admin rights
396 * access for a reason and sometimes they want no access. Subclasses should
397 * override and return one of the following values, as needed:
398 * Maintenance::DB_NONE - For no DB access at all
399 * Maintenance::DB_STD - For normal DB access, default
400 * Maintenance::DB_ADMIN - For admin DB access
403 public function getDbType() {
404 return Maintenance
::DB_STD
;
408 * Add the default parameters to the scripts
410 protected function addDefaultParams() {
412 # Generic (non script dependant) options:
414 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
415 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
416 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
417 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
418 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
419 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
420 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
421 "http://en.wikipedia.org. This is sometimes necessary because " .
422 "server name detection may fail in command line scripts.", false, true );
424 # Save generic options to display them separately in help
425 $this->mGenericParameters
= $this->mParams
;
427 # Script dependant options:
429 // If we support a DB, show the options
430 if ( $this->getDbType() > 0 ) {
431 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
432 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
435 # Save additional script dependant options to display
436 #Â them separately in help
437 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
441 * Run a child maintenance script. Pass all of the current arguments
443 * @param $maintClass String: a name of a child maintenance class
444 * @param $classFile String: full path of where the child is
445 * @return Maintenance child
447 public function runChild( $maintClass, $classFile = null ) {
448 // Make sure the class is loaded first
449 if ( !MWInit
::classExists( $maintClass ) ) {
451 require_once( $classFile );
453 if ( !MWInit
::classExists( $maintClass ) ) {
454 $this->error( "Cannot spawn child: $maintClass" );
459 * @var $child Maintenance
461 $child = new $maintClass();
462 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
463 if ( !is_null( $this->mDb
) ) {
464 $child->setDB( $this->mDb
);
470 * Do some sanity checking and basic setup
472 public function setup() {
473 global $wgCommandLineMode, $wgRequestTime;
475 # Abort if called from a web server
476 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
477 $this->error( 'This script must be run from the command line', true );
480 # Make sure we can handle script parameters
481 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
482 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
485 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
486 // Send PHP warnings and errors to stderr instead of stdout.
487 // This aids in diagnosing problems, while keeping messages
488 // out of redirected output.
489 if ( ini_get( 'display_errors' ) ) {
490 ini_set( 'display_errors', 'stderr' );
493 // Don't touch the setting on earlier versions of PHP,
494 // as setting it would disable output if you'd wanted it.
496 // Note that exceptions are also sent to stderr when
497 // command-line mode is on, regardless of PHP version.
500 $this->loadParamsAndArgs();
503 # Set the memory limit
504 # Note we need to set it again later in cache LocalSettings changed it
505 $this->adjustMemoryLimit();
507 # Set max execution time to 0 (no limit). PHP.net says that
508 # "When running PHP from the command line the default setting is 0."
509 # But sometimes this doesn't seem to be the case.
510 ini_set( 'max_execution_time', 0 );
512 $wgRequestTime = microtime( true );
514 # Define us as being in MediaWiki
515 define( 'MEDIAWIKI', true );
517 $wgCommandLineMode = true;
518 # Turn off output buffering if it's on
521 $this->validateParamsAndArgs();
525 * Normally we disable the memory_limit when running admin scripts.
526 * Some scripts may wish to actually set a limit, however, to avoid
527 * blowing up unexpectedly. We also support a --memory-limit option,
528 * to allow sysadmins to explicitly set one if they'd prefer to override
529 * defaults (or for people using Suhosin which yells at you for trying
530 * to disable the limits)
533 public function memoryLimit() {
534 $limit = $this->getOption( 'memory-limit', 'max' );
535 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
540 * Adjusts PHP's memory limit to better suit our needs, if needed.
542 protected function adjustMemoryLimit() {
543 $limit = $this->memoryLimit();
544 if ( $limit == 'max' ) {
545 $limit = -1; // no memory limit
547 if ( $limit != 'default' ) {
548 ini_set( 'memory_limit', $limit );
553 * Clear all params and arguments.
555 public function clearParamsAndArgs() {
556 $this->mOptions
= array();
557 $this->mArgs
= array();
558 $this->mInputLoaded
= false;
562 * Process command line arguments
563 * $mOptions becomes an array with keys set to the option names
564 * $mArgs becomes a zero-based array containing the non-option arguments
566 * @param $self String The name of the script, if any
567 * @param $opts Array An array of options, in form of key=>value
568 * @param $args Array An array of command line arguments
570 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
571 # If we were given opts or args, set those and return early
573 $this->mSelf
= $self;
574 $this->mInputLoaded
= true;
577 $this->mOptions
= $opts;
578 $this->mInputLoaded
= true;
581 $this->mArgs
= $args;
582 $this->mInputLoaded
= true;
585 # If we've already loaded input (either by user values or from $argv)
586 # skip on loading it again. The array_shift() will corrupt values if
587 # it's run again and again
588 if ( $this->mInputLoaded
) {
589 $this->loadSpecialVars();
594 $this->mSelf
= array_shift( $argv );
600 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
601 if ( $arg == '--' ) {
602 # End of options, remainder should be considered arguments
603 $arg = next( $argv );
604 while ( $arg !== false ) {
606 $arg = next( $argv );
609 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
611 $option = substr( $arg, 2 );
612 if ( array_key_exists( $option, $options ) ) {
613 $this->error( "\nERROR: $option parameter given twice\n" );
614 $this->maybeHelp( true );
616 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
617 $param = next( $argv );
618 if ( $param === false ) {
619 $this->error( "\nERROR: $option parameter needs a value after it\n" );
620 $this->maybeHelp( true );
622 $options[$option] = $param;
624 $bits = explode( '=', $option, 2 );
625 if ( count( $bits ) > 1 ) {
631 $options[$option] = $param;
633 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
635 for ( $p = 1; $p < strlen( $arg ); $p++
) {
636 $option = $arg { $p } ;
637 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
638 $option = $this->mShortParamsMap
[$option];
640 if ( array_key_exists( $option, $options ) ) {
641 $this->error( "\nERROR: $option parameter given twice\n" );
642 $this->maybeHelp( true );
644 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
645 $param = next( $argv );
646 if ( $param === false ) {
647 $this->error( "\nERROR: $option parameter needs a value after it\n" );
648 $this->maybeHelp( true );
650 $options[$option] = $param;
652 $options[$option] = 1;
660 $this->mOptions
= $options;
661 $this->mArgs
= $args;
662 $this->loadSpecialVars();
663 $this->mInputLoaded
= true;
667 * Run some validation checks on the params, etc
669 protected function validateParamsAndArgs() {
671 # Check to make sure we've got all the required options
672 foreach ( $this->mParams
as $opt => $info ) {
673 if ( $info['require'] && !$this->hasOption( $opt ) ) {
674 $this->error( "Param $opt required!" );
679 foreach ( $this->mArgList
as $k => $info ) {
680 if ( $info['require'] && !$this->hasArg( $k ) ) {
681 $this->error( 'Argument <' . $info['name'] . '> required!' );
687 $this->maybeHelp( true );
692 * Handle the special variables that are global to all scripts
694 protected function loadSpecialVars() {
695 if ( $this->hasOption( 'dbuser' ) ) {
696 $this->mDbUser
= $this->getOption( 'dbuser' );
698 if ( $this->hasOption( 'dbpass' ) ) {
699 $this->mDbPass
= $this->getOption( 'dbpass' );
701 if ( $this->hasOption( 'quiet' ) ) {
702 $this->mQuiet
= true;
704 if ( $this->hasOption( 'batch-size' ) ) {
705 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
710 * Maybe show the help.
711 * @param $force boolean Whether to force the help to show, default false
713 protected function maybeHelp( $force = false ) {
714 if( !$force && !$this->hasOption( 'help' ) ) {
718 $screenWidth = 80; // TODO: Caculate this!
720 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
722 ksort( $this->mParams
);
723 $this->mQuiet
= false;
726 if ( $this->mDescription
) {
727 $this->output( "\n" . $this->mDescription
. "\n" );
729 $output = "\nUsage: php " . basename( $this->mSelf
);
731 // ... append parameters ...
732 if ( $this->mParams
) {
733 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
736 // ... and append arguments.
737 if ( $this->mArgList
) {
739 foreach ( $this->mArgList
as $k => $arg ) {
740 if ( $arg['require'] ) {
741 $output .= '<' . $arg['name'] . '>';
743 $output .= '[' . $arg['name'] . ']';
745 if ( $k < count( $this->mArgList
) - 1 )
749 $this->output( "$output\n\n" );
751 # TODO abstract some repetitive code below
753 // Generic parameters
754 $this->output( "Generic maintenance parameters:\n" );
755 foreach ( $this->mGenericParameters
as $par => $info ) {
756 if ( $info['shortName'] !== false ) {
757 $par .= " (-{$info['shortName']})";
760 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
761 "\n$tab$tab" ) . "\n"
764 $this->output( "\n" );
766 $scriptDependantParams = $this->mDependantParameters
;
767 if( count($scriptDependantParams) > 0 ) {
768 $this->output( "Script dependant parameters:\n" );
769 // Parameters description
770 foreach ( $scriptDependantParams as $par => $info ) {
771 if ( $info['shortName'] !== false ) {
772 $par .= " (-{$info['shortName']})";
775 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
776 "\n$tab$tab" ) . "\n"
779 $this->output( "\n" );
783 // Script specific parameters not defined on construction by
784 // Maintenance::addDefaultParams()
785 $scriptSpecificParams = array_diff_key(
786 # all script parameters:
788 # remove the Maintenance default parameters:
789 $this->mGenericParameters
,
790 $this->mDependantParameters
792 if( count($scriptSpecificParams) > 0 ) {
793 $this->output( "Script specific parameters:\n" );
794 // Parameters description
795 foreach ( $scriptSpecificParams as $par => $info ) {
796 if ( $info['shortName'] !== false ) {
797 $par .= " (-{$info['shortName']})";
800 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
801 "\n$tab$tab" ) . "\n"
804 $this->output( "\n" );
808 if( count( $this->mArgList
) > 0 ) {
809 $this->output( "Arguments:\n" );
810 // Arguments description
811 foreach ( $this->mArgList
as $info ) {
812 $openChar = $info['require'] ?
'<' : '[';
813 $closeChar = $info['require'] ?
'>' : ']';
815 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
816 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
819 $this->output( "\n" );
826 * Handle some last-minute setup here.
828 public function finalSetup() {
829 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
830 global $wgDBadminuser, $wgDBadminpassword;
831 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
833 # Turn off output buffering again, it might have been turned on in the settings files
834 if ( ob_get_level() ) {
838 $wgCommandLineMode = true;
841 if( $this->hasOption( 'server') ) {
842 $wgServer = $this->getOption( 'server', $wgServer );
845 # If these were passed, use them
846 if ( $this->mDbUser
) {
847 $wgDBadminuser = $this->mDbUser
;
849 if ( $this->mDbPass
) {
850 $wgDBadminpassword = $this->mDbPass
;
853 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
854 $wgDBuser = $wgDBadminuser;
855 $wgDBpassword = $wgDBadminpassword;
857 if ( $wgDBservers ) {
859 * @var $wgDBservers array
861 foreach ( $wgDBservers as $i => $server ) {
862 $wgDBservers[$i]['user'] = $wgDBuser;
863 $wgDBservers[$i]['password'] = $wgDBpassword;
866 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
867 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
868 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
870 LBFactory
::destroyInstance();
873 $this->afterFinalSetup();
875 $wgShowSQLErrors = true;
876 @set_time_limit
( 0 );
877 $this->adjustMemoryLimit();
881 * Execute a callback function at the end of initialisation
883 protected function afterFinalSetup() {
884 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
885 call_user_func( MW_CMDLINE_CALLBACK
);
890 * Potentially debug globals. Originally a feature only
893 public function globals() {
894 if ( $this->hasOption( 'globals' ) ) {
900 * Generic setup for most installs. Returns the location of LocalSettings
903 public function loadSettings() {
904 global $wgCommandLineMode, $IP;
906 if ( isset( $this->mOptions
['conf'] ) ) {
907 $settingsFile = $this->mOptions
['conf'];
908 } elseif ( defined("MW_CONFIG_FILE") ) {
909 $settingsFile = MW_CONFIG_FILE
;
911 $settingsFile = "$IP/LocalSettings.php";
913 if ( isset( $this->mOptions
['wiki'] ) ) {
914 $bits = explode( '-', $this->mOptions
['wiki'] );
915 if ( count( $bits ) == 1 ) {
918 define( 'MW_DB', $bits[0] );
919 define( 'MW_PREFIX', $bits[1] );
922 if ( !is_readable( $settingsFile ) ) {
923 $this->error( "A copy of your installation's LocalSettings.php\n" .
924 "must exist and be readable in the source directory.\n" .
925 "Use --conf to specify it." , true );
927 $wgCommandLineMode = true;
928 return $settingsFile;
932 * Support function for cleaning up redundant text records
933 * @param $delete Boolean: whether or not to actually delete the records
934 * @author Rob Church <robchur@gmail.com>
936 public function purgeRedundantText( $delete = true ) {
937 # Data should come off the master, wrapped in a transaction
938 $dbw = $this->getDB( DB_MASTER
);
939 $dbw->begin( __METHOD__
);
941 $tbl_arc = $dbw->tableName( 'archive' );
942 $tbl_rev = $dbw->tableName( 'revision' );
943 $tbl_txt = $dbw->tableName( 'text' );
945 # Get "active" text records from the revisions table
946 $this->output( 'Searching for active text records in revisions table...' );
947 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
948 foreach ( $res as $row ) {
949 $cur[] = $row->rev_text_id
;
951 $this->output( "done.\n" );
953 # Get "active" text records from the archive table
954 $this->output( 'Searching for active text records in archive table...' );
955 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
956 foreach ( $res as $row ) {
957 $cur[] = $row->ar_text_id
;
959 $this->output( "done.\n" );
961 # Get the IDs of all text records not in these sets
962 $this->output( 'Searching for inactive text records...' );
963 $set = implode( ', ', $cur );
964 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
966 foreach ( $res as $row ) {
967 $old[] = $row->old_id
;
969 $this->output( "done.\n" );
971 # Inform the user of what we're going to do
972 $count = count( $old );
973 $this->output( "$count inactive items found.\n" );
975 # Delete as appropriate
976 if ( $delete && $count ) {
977 $this->output( 'Deleting...' );
978 $set = implode( ', ', $old );
979 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
980 $this->output( "done.\n" );
984 $dbw->commit( __METHOD__
);
988 * Get the maintenance directory.
991 protected function getDir() {
996 * Get the list of available maintenance scripts. Note
997 * that if you call this _before_ calling doMaintenance
998 * you won't have any extensions in it yet
1001 public static function getMaintenanceScripts() {
1002 global $wgMaintenanceScripts;
1003 return $wgMaintenanceScripts + self
::getCoreScripts();
1007 * Return all of the core maintenance scripts
1010 protected static function getCoreScripts() {
1011 if ( !self
::$mCoreScripts ) {
1014 __DIR__
. '/language',
1015 __DIR__
. '/storage',
1017 self
::$mCoreScripts = array();
1018 foreach ( $paths as $p ) {
1019 $handle = opendir( $p );
1020 while ( ( $file = readdir( $handle ) ) !== false ) {
1021 if ( $file == 'Maintenance.php' ) {
1024 $file = $p . '/' . $file;
1025 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
1026 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1030 $vars = get_defined_vars();
1031 if ( array_key_exists( 'maintClass', $vars ) ) {
1032 self
::$mCoreScripts[$vars['maintClass']] = $file;
1035 closedir( $handle );
1038 return self
::$mCoreScripts;
1042 * Returns a database to be used by current maintenance script. It can be set by setDB().
1043 * If not set, wfGetDB() will be used.
1044 * This function has the same parameters as wfGetDB()
1046 * @return DatabaseBase
1048 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1049 if ( is_null( $this->mDb
) ) {
1050 return wfGetDB( $db, $groups, $wiki );
1057 * Sets database object to be returned by getDB().
1059 * @param $db DatabaseBase: Database object to be used
1061 public function setDB( &$db ) {
1066 * Lock the search index
1067 * @param &$db DatabaseBase object
1069 private function lockSearchindex( &$db ) {
1070 $write = array( 'searchindex' );
1071 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1072 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1077 * @param &$db DatabaseBase object
1079 private function unlockSearchindex( &$db ) {
1080 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1084 * Unlock and lock again
1085 * Since the lock is low-priority, queued reads will be able to complete
1086 * @param &$db DatabaseBase object
1088 private function relockSearchindex( &$db ) {
1089 $this->unlockSearchindex( $db );
1090 $this->lockSearchindex( $db );
1094 * Perform a search index update with locking
1095 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1096 * @param $callback callback String: the function that will update the function.
1097 * @param $dbw DatabaseBase object
1100 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1104 if ( $maxLockTime ) {
1105 $this->output( " --- Waiting for lock ---" );
1106 $this->lockSearchindex( $dbw );
1108 $this->output( "\n" );
1111 # Loop through the results and do a search update
1112 foreach ( $results as $row ) {
1113 # Allow reads to be processed
1114 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1115 $this->output( " --- Relocking ---" );
1116 $this->relockSearchindex( $dbw );
1118 $this->output( "\n" );
1120 call_user_func( $callback, $dbw, $row );
1123 # Unlock searchindex
1124 if ( $maxLockTime ) {
1125 $this->output( " --- Unlocking --" );
1126 $this->unlockSearchindex( $dbw );
1127 $this->output( "\n" );
1133 * Update the searchindex table for a given pageid
1134 * @param $dbw DatabaseBase a database write handle
1135 * @param $pageId Integer: the page ID to update.
1136 * @return null|string
1138 public function updateSearchIndexForPage( $dbw, $pageId ) {
1139 // Get current revision
1140 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1143 $titleObj = $rev->getTitle();
1144 $title = $titleObj->getPrefixedDBkey();
1145 $this->output( "$title..." );
1146 # Update searchindex
1147 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1149 $this->output( "\n" );
1155 * Wrapper for posix_isatty()
1156 * We default as considering stdin a tty (for nice readline methods)
1157 * but treating stout as not a tty to avoid color codes
1159 * @param $fd int File descriptor
1162 public static function posix_isatty( $fd ) {
1163 if ( !MWInit
::functionExists( 'posix_isatty' ) ) {
1166 return posix_isatty( $fd );
1171 * Prompt the console for input
1172 * @param $prompt String what to begin the line with, like '> '
1173 * @return String response
1175 public static function readconsole( $prompt = '> ' ) {
1176 static $isatty = null;
1177 if ( is_null( $isatty ) ) {
1178 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1181 if ( $isatty && function_exists( 'readline' ) ) {
1182 return readline( $prompt );
1185 $st = self
::readlineEmulation( $prompt );
1187 if ( feof( STDIN
) ) {
1190 $st = fgets( STDIN
, 1024 );
1193 if ( $st === false ) return false;
1194 $resp = trim( $st );
1200 * Emulate readline()
1201 * @param $prompt String what to begin the line with, like '> '
1204 private static function readlineEmulation( $prompt ) {
1205 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1206 if ( !wfIsWindows() && $bash ) {
1208 $encPrompt = wfEscapeShellArg( $prompt );
1209 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1210 $encCommand = wfEscapeShellArg( $command );
1211 $line = wfShellExec( "$bash -c $encCommand", $retval );
1213 if ( $retval == 0 ) {
1215 } elseif ( $retval == 127 ) {
1216 // Couldn't execute bash even though we thought we saw it.
1217 // Shell probably spit out an error message, sorry :(
1218 // Fall through to fgets()...
1225 // Fallback... we'll have no editing controls, EWWW
1226 if ( feof( STDIN
) ) {
1230 return fgets( STDIN
, 1024 );
1235 * Fake maintenance wrapper, mostly used for the web installer/updater
1237 class FakeMaintenance
extends Maintenance
{
1238 protected $mSelf = "FakeMaintenanceScript";
1239 public function execute() {
1245 * Class for scripts that perform database maintenance and want to log the
1246 * update in `updatelog` so we can later skip it
1248 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1249 public function __construct() {
1250 parent
::__construct();
1251 $this->addOption( 'force', 'Run the update even if it was completed already' );
1252 $this->setBatchSize( 200 );
1255 public function execute() {
1256 $db = $this->getDB( DB_MASTER
);
1257 $key = $this->getUpdateKey();
1259 if ( !$this->hasOption( 'force' ) &&
1260 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
) )
1262 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1266 if ( !$this->doDBUpdates() ) {
1271 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) )
1275 $this->output( $this->updatelogFailedMessage() . "\n" );
1281 * Message to show that the update was done already and was just skipped
1284 protected function updateSkippedMessage() {
1285 $key = $this->getUpdateKey();
1286 return "Update '{$key}' already logged as completed.";
1290 * Message to show the the update log was unable to log the completion of this update
1293 protected function updatelogFailedMessage() {
1294 $key = $this->getUpdateKey();
1295 return "Unable to log update '{$key}' as completed.";
1299 * Do the actual work. All child classes will need to implement this.
1300 * Return true to log the update as done or false (usually on failure).
1303 abstract protected function doDBUpdates();
1306 * Get the update key name to go in the update log table
1309 abstract protected function getUpdateKey();