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 * Used when creating separate schema files.
118 * Default constructor. Children should call this *first* if implementing
119 * their own constructors
121 public function __construct() {
122 // Setup $IP, using MW_INSTALL_PATH if it exists
124 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
125 ?
getenv( 'MW_INSTALL_PATH' )
126 : realpath( __DIR__
. '/..' );
128 $this->addDefaultParams();
129 register_shutdown_function( array( $this, 'outputChanneled' ), false );
133 * Should we execute the maintenance script, or just allow it to be included
134 * as a standalone class? It checks that the call stack only includes this
135 * function and "requires" (meaning was called from the file scope)
139 public static function shouldExecute() {
140 $bt = debug_backtrace();
141 $count = count( $bt );
143 return false; // sanity
145 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
146 return false; // last call should be to this function
148 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
149 for ( $i = 1; $i < $count; $i++
) {
150 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
151 return false; // previous calls should all be "requires"
158 * Do the actual work. All child classes will need to implement this
160 abstract public function execute();
163 * Add a parameter to the script. Will be displayed on --help
164 * with the associated description
166 * @param string $name The name of the param (help, version, etc)
167 * @param string $description The description of the param to show on --help
168 * @param bool $required Is the param required?
169 * @param bool $withArg Is an argument required with this option?
170 * @param string $shortName Character to use as short name
172 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
173 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
174 if ( $shortName !== false ) {
175 $this->mShortParamsMap
[$shortName] = $name;
180 * Checks to see if a particular param exists.
181 * @param string $name The name of the param
184 protected function hasOption( $name ) {
185 return isset( $this->mOptions
[$name] );
189 * Get an option, or return the default
190 * @param string $name The name of the param
191 * @param mixed $default Anything you want, default null
194 protected function getOption( $name, $default = null ) {
195 if ( $this->hasOption( $name ) ) {
196 return $this->mOptions
[$name];
198 // Set it so we don't have to provide the default again
199 $this->mOptions
[$name] = $default;
200 return $this->mOptions
[$name];
205 * Add some args that are needed
206 * @param string $arg Name of the arg, like 'start'
207 * @param string $description Short description of the arg
208 * @param bool $required Is this required?
210 protected function addArg( $arg, $description, $required = true ) {
211 $this->mArgList
[] = array(
213 'desc' => $description,
214 'require' => $required
219 * Remove an option. Useful for removing options that won't be used in your script.
220 * @param string $name The option to remove.
222 protected function deleteOption( $name ) {
223 unset( $this->mParams
[$name] );
227 * Set the description text.
228 * @param string $text The text of the description
230 protected function addDescription( $text ) {
231 $this->mDescription
= $text;
235 * Does a given argument exist?
236 * @param int $argId The integer value (from zero) for the arg
239 protected function hasArg( $argId = 0 ) {
240 return isset( $this->mArgs
[$argId] );
245 * @param int $argId The integer value (from zero) for the arg
246 * @param mixed $default The default if it doesn't exist
249 protected function getArg( $argId = 0, $default = null ) {
250 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
254 * Set the batch size.
255 * @param int $s The number of operations to do in a batch
257 protected function setBatchSize( $s = 0 ) {
258 $this->mBatchSize
= $s;
260 // If we support $mBatchSize, show the option.
261 // Used to be in addDefaultParams, but in order for that to
262 // work, subclasses would have to call this function in the constructor
263 // before they called parent::__construct which is just weird
264 // (and really wasn't done).
265 if ( $this->mBatchSize
) {
266 $this->addOption( 'batch-size', 'Run this many operations ' .
267 'per batch, default: ' . $this->mBatchSize
, false, true );
268 if ( isset( $this->mParams
['batch-size'] ) ) {
269 // This seems a little ugly...
270 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
276 * Get the script's name
279 public function getName() {
284 * Return input from stdin.
285 * @param int $len The number of bytes to read. If null, just return the handle.
286 * Maintenance::STDIN_ALL returns the full length
289 protected function getStdin( $len = null ) {
290 if ( $len == Maintenance
::STDIN_ALL
) {
291 return file_get_contents( 'php://stdin' );
293 $f = fopen( 'php://stdin', 'rt' );
297 $input = fgets( $f, $len );
299 return rtrim( $input );
305 public function isQuiet() {
306 return $this->mQuiet
;
310 * Throw some output to the user. Scripts can call this with no fears,
311 * as we handle all --quiet stuff here
312 * @param string $out The text to show to the user
313 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
315 protected function output( $out, $channel = null ) {
316 if ( $this->mQuiet
) {
319 if ( $channel === null ) {
320 $this->cleanupChanneled();
323 $out = preg_replace( '/\n\z/', '', $out );
324 $this->outputChanneled( $out, $channel );
329 * Throw an error to the user. Doesn't respect --quiet, so don't use
330 * this for non-error output
331 * @param string $err The error to display
332 * @param int $die If > 0, go ahead and die out using this int as the code
334 protected function error( $err, $die = 0 ) {
335 $this->outputChanneled( false );
336 if ( PHP_SAPI
== 'cli' ) {
337 fwrite( STDERR
, $err . "\n" );
341 $die = intval( $die );
347 private $atLineStart = true;
348 private $lastChannel = null;
351 * Clean up channeled output. Output a newline if necessary.
353 public function cleanupChanneled() {
354 if ( !$this->atLineStart
) {
356 $this->atLineStart
= true;
361 * Message outputter with channeled message support. Messages on the
362 * same channel are concatenated, but any intervening messages in another
363 * channel start a new line.
364 * @param string $msg The message without trailing newline
365 * @param string $channel Channel identifier or null for no
366 * channel. Channel comparison uses ===.
368 public function outputChanneled( $msg, $channel = null ) {
369 if ( $msg === false ) {
370 $this->cleanupChanneled();
374 // End the current line if necessary
375 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
381 $this->atLineStart
= false;
382 if ( $channel === null ) {
383 // For unchanneled messages, output trailing newline immediately
385 $this->atLineStart
= true;
387 $this->lastChannel
= $channel;
391 * Does the script need different DB access? By default, we give Maintenance
392 * scripts normal rights to the DB. Sometimes, a script needs admin rights
393 * access for a reason and sometimes they want no access. Subclasses should
394 * override and return one of the following values, as needed:
395 * Maintenance::DB_NONE - For no DB access at all
396 * Maintenance::DB_STD - For normal DB access, default
397 * Maintenance::DB_ADMIN - For admin DB access
400 public function getDbType() {
401 return Maintenance
::DB_STD
;
405 * Add the default parameters to the scripts
407 protected function addDefaultParams() {
409 # Generic (non script dependant) options:
411 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
412 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
413 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
414 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
415 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
416 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
417 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
418 "http://en.wikipedia.org. This is sometimes necessary because " .
419 "server name detection may fail in command line scripts.", false, true );
420 $this->addOption( 'profiler', 'Set to "text" or "trace" to show profiling output', false, true );
422 # Save generic options to display them separately in help
423 $this->mGenericParameters
= $this->mParams
;
425 # Script dependant options:
427 // If we support a DB, show the options
428 if ( $this->getDbType() > 0 ) {
429 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
430 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
433 # Save additional script dependant options to display
434 #Â them separately in help
435 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
439 * Run a child maintenance script. Pass all of the current arguments
441 * @param string $maintClass A name of a child maintenance class
442 * @param string $classFile Full path of where the child is
443 * @return Maintenance
445 public function runChild( $maintClass, $classFile = null ) {
446 // Make sure the class is loaded first
447 if ( !class_exists( $maintClass ) ) {
449 require_once $classFile;
451 if ( !class_exists( $maintClass ) ) {
452 $this->error( "Cannot spawn child: $maintClass" );
457 * @var $child Maintenance
459 $child = new $maintClass();
460 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
461 if ( !is_null( $this->mDb
) ) {
462 $child->setDB( $this->mDb
);
468 * Do some sanity checking and basic setup
470 public function setup() {
471 global $IP, $wgCommandLineMode, $wgRequestTime;
473 # Abort if called from a web server
474 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
475 $this->error( 'This script must be run from the command line', true );
478 if ( $IP === null ) {
479 $this->error( "\$IP not set, aborting!\n" .
480 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
483 # Make sure we can handle script parameters
484 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
485 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
488 // Send PHP warnings and errors to stderr instead of stdout.
489 // This aids in diagnosing problems, while keeping messages
490 // out of redirected output.
491 if ( ini_get( 'display_errors' ) ) {
492 ini_set( 'display_errors', 'stderr' );
495 $this->loadParamsAndArgs();
498 # Set the memory limit
499 # Note we need to set it again later in cache LocalSettings changed it
500 $this->adjustMemoryLimit();
502 # Set max execution time to 0 (no limit). PHP.net says that
503 # "When running PHP from the command line the default setting is 0."
504 # But sometimes this doesn't seem to be the case.
505 ini_set( 'max_execution_time', 0 );
507 $wgRequestTime = microtime( true );
509 # Define us as being in MediaWiki
510 define( 'MEDIAWIKI', true );
512 $wgCommandLineMode = true;
514 # Turn off output buffering if it's on
515 while ( ob_get_level() > 0 ) {
519 $this->validateParamsAndArgs();
523 * Normally we disable the memory_limit when running admin scripts.
524 * Some scripts may wish to actually set a limit, however, to avoid
525 * blowing up unexpectedly. We also support a --memory-limit option,
526 * to allow sysadmins to explicitly set one if they'd prefer to override
527 * defaults (or for people using Suhosin which yells at you for trying
528 * to disable the limits)
531 public function memoryLimit() {
532 $limit = $this->getOption( 'memory-limit', 'max' );
533 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
538 * Adjusts PHP's memory limit to better suit our needs, if needed.
540 protected function adjustMemoryLimit() {
541 $limit = $this->memoryLimit();
542 if ( $limit == 'max' ) {
543 $limit = -1; // no memory limit
545 if ( $limit != 'default' ) {
546 ini_set( 'memory_limit', $limit );
551 * Clear all params and arguments.
553 public function clearParamsAndArgs() {
554 $this->mOptions
= array();
555 $this->mArgs
= array();
556 $this->mInputLoaded
= false;
560 * Process command line arguments
561 * $mOptions becomes an array with keys set to the option names
562 * $mArgs becomes a zero-based array containing the non-option arguments
564 * @param string $self The name of the script, if any
565 * @param array $opts An array of options, in form of key=>value
566 * @param array $args An array of command line arguments
568 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
569 # If we were given opts or args, set those and return early
571 $this->mSelf
= $self;
572 $this->mInputLoaded
= true;
575 $this->mOptions
= $opts;
576 $this->mInputLoaded
= true;
579 $this->mArgs
= $args;
580 $this->mInputLoaded
= true;
583 # If we've already loaded input (either by user values or from $argv)
584 # skip on loading it again. The array_shift() will corrupt values if
585 # it's run again and again
586 if ( $this->mInputLoaded
) {
587 $this->loadSpecialVars();
592 $this->mSelf
= array_shift( $argv );
598 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
599 if ( $arg == '--' ) {
600 # End of options, remainder should be considered arguments
601 $arg = next( $argv );
602 while ( $arg !== false ) {
604 $arg = next( $argv );
607 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
609 $option = substr( $arg, 2 );
610 if ( array_key_exists( $option, $options ) ) {
611 $this->error( "\nERROR: $option parameter given twice\n" );
612 $this->maybeHelp( true );
614 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
615 $param = next( $argv );
616 if ( $param === false ) {
617 $this->error( "\nERROR: $option parameter needs a value after it\n" );
618 $this->maybeHelp( true );
620 $options[$option] = $param;
622 $bits = explode( '=', $option, 2 );
623 if ( count( $bits ) > 1 ) {
629 $options[$option] = $param;
631 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
633 for ( $p = 1; $p < strlen( $arg ); $p++
) {
634 $option = $arg { $p };
635 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
636 $option = $this->mShortParamsMap
[$option];
638 if ( array_key_exists( $option, $options ) ) {
639 $this->error( "\nERROR: $option parameter given twice\n" );
640 $this->maybeHelp( true );
642 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
643 $param = next( $argv );
644 if ( $param === false ) {
645 $this->error( "\nERROR: $option parameter needs a value after it\n" );
646 $this->maybeHelp( true );
648 $options[$option] = $param;
650 $options[$option] = 1;
658 $this->mOptions
= $options;
659 $this->mArgs
= $args;
660 $this->loadSpecialVars();
661 $this->mInputLoaded
= true;
665 * Run some validation checks on the params, etc
667 protected function validateParamsAndArgs() {
669 # Check to make sure we've got all the required options
670 foreach ( $this->mParams
as $opt => $info ) {
671 if ( $info['require'] && !$this->hasOption( $opt ) ) {
672 $this->error( "Param $opt required!" );
677 foreach ( $this->mArgList
as $k => $info ) {
678 if ( $info['require'] && !$this->hasArg( $k ) ) {
679 $this->error( 'Argument <' . $info['name'] . '> required!' );
685 $this->maybeHelp( true );
690 * Handle the special variables that are global to all scripts
692 protected function loadSpecialVars() {
693 if ( $this->hasOption( 'dbuser' ) ) {
694 $this->mDbUser
= $this->getOption( 'dbuser' );
696 if ( $this->hasOption( 'dbpass' ) ) {
697 $this->mDbPass
= $this->getOption( 'dbpass' );
699 if ( $this->hasOption( 'quiet' ) ) {
700 $this->mQuiet
= true;
702 if ( $this->hasOption( 'batch-size' ) ) {
703 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
708 * Maybe show the help.
709 * @param bool $force Whether to force the help to show, default false
711 protected function maybeHelp( $force = false ) {
712 if ( !$force && !$this->hasOption( 'help' ) ) {
716 $screenWidth = 80; // TODO: Caculate this!
718 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
720 ksort( $this->mParams
);
721 $this->mQuiet
= false;
724 if ( $this->mDescription
) {
725 $this->output( "\n" . $this->mDescription
. "\n" );
727 $output = "\nUsage: php " . basename( $this->mSelf
);
729 // ... append parameters ...
730 if ( $this->mParams
) {
731 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
734 // ... and append arguments.
735 if ( $this->mArgList
) {
737 foreach ( $this->mArgList
as $k => $arg ) {
738 if ( $arg['require'] ) {
739 $output .= '<' . $arg['name'] . '>';
741 $output .= '[' . $arg['name'] . ']';
743 if ( $k < count( $this->mArgList
) - 1 ) {
748 $this->output( "$output\n\n" );
750 # TODO abstract some repetitive code below
752 // Generic parameters
753 $this->output( "Generic maintenance parameters:\n" );
754 foreach ( $this->mGenericParameters
as $par => $info ) {
755 if ( $info['shortName'] !== false ) {
756 $par .= " (-{$info['shortName']})";
759 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
760 "\n$tab$tab" ) . "\n"
763 $this->output( "\n" );
765 $scriptDependantParams = $this->mDependantParameters
;
766 if ( count( $scriptDependantParams ) > 0 ) {
767 $this->output( "Script dependant parameters:\n" );
768 // Parameters description
769 foreach ( $scriptDependantParams as $par => $info ) {
770 if ( $info['shortName'] !== false ) {
771 $par .= " (-{$info['shortName']})";
774 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
775 "\n$tab$tab" ) . "\n"
778 $this->output( "\n" );
781 // Script specific parameters not defined on construction by
782 // Maintenance::addDefaultParams()
783 $scriptSpecificParams = array_diff_key(
784 # all script parameters:
786 # remove the Maintenance default parameters:
787 $this->mGenericParameters
,
788 $this->mDependantParameters
790 if ( count( $scriptSpecificParams ) > 0 ) {
791 $this->output( "Script specific parameters:\n" );
792 // Parameters description
793 foreach ( $scriptSpecificParams as $par => $info ) {
794 if ( $info['shortName'] !== false ) {
795 $par .= " (-{$info['shortName']})";
798 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
799 "\n$tab$tab" ) . "\n"
802 $this->output( "\n" );
806 if ( count( $this->mArgList
) > 0 ) {
807 $this->output( "Arguments:\n" );
808 // Arguments description
809 foreach ( $this->mArgList
as $info ) {
810 $openChar = $info['require'] ?
'<' : '[';
811 $closeChar = $info['require'] ?
'>' : ']';
813 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
814 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
817 $this->output( "\n" );
824 * Handle some last-minute setup here.
826 public function finalSetup() {
827 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
828 global $wgDBadminuser, $wgDBadminpassword;
829 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
831 # Turn off output buffering again, it might have been turned on in the settings files
832 if ( ob_get_level() ) {
836 $wgCommandLineMode = true;
839 if ( $this->hasOption( 'server' ) ) {
840 $wgServer = $this->getOption( 'server', $wgServer );
843 # If these were passed, use them
844 if ( $this->mDbUser
) {
845 $wgDBadminuser = $this->mDbUser
;
847 if ( $this->mDbPass
) {
848 $wgDBadminpassword = $this->mDbPass
;
851 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
852 $wgDBuser = $wgDBadminuser;
853 $wgDBpassword = $wgDBadminpassword;
855 if ( $wgDBservers ) {
857 * @var $wgDBservers array
859 foreach ( $wgDBservers as $i => $server ) {
860 $wgDBservers[$i]['user'] = $wgDBuser;
861 $wgDBservers[$i]['password'] = $wgDBpassword;
864 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
865 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
866 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
868 LBFactory
::destroyInstance();
871 $this->afterFinalSetup();
873 $wgShowSQLErrors = true;
874 @set_time_limit
( 0 );
875 $this->adjustMemoryLimit();
877 // Per-script profiling; useful for debugging
878 $forcedProfiler = $this->getOption( 'profiler' );
879 if ( $forcedProfiler === 'text' ) {
880 Profiler
::setInstance( new ProfilerSimpleText( array() ) );
881 Profiler
::instance()->setTemplated( true );
882 } elseif ( $forcedProfiler === 'trace' ) {
883 Profiler
::setInstance( new ProfilerSimpleTrace( array() ) );
884 Profiler
::instance()->setTemplated( true );
889 * Execute a callback function at the end of initialisation
891 protected function afterFinalSetup() {
892 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
893 call_user_func( MW_CMDLINE_CALLBACK
);
898 * Potentially debug globals. Originally a feature only
901 public function globals() {
902 if ( $this->hasOption( 'globals' ) ) {
908 * Generic setup for most installs. Returns the location of LocalSettings
911 public function loadSettings() {
912 global $wgCommandLineMode, $IP;
914 if ( isset( $this->mOptions
['conf'] ) ) {
915 $settingsFile = $this->mOptions
['conf'];
916 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
917 $settingsFile = MW_CONFIG_FILE
;
919 $settingsFile = "$IP/LocalSettings.php";
921 if ( isset( $this->mOptions
['wiki'] ) ) {
922 $bits = explode( '-', $this->mOptions
['wiki'] );
923 if ( count( $bits ) == 1 ) {
926 define( 'MW_DB', $bits[0] );
927 define( 'MW_PREFIX', $bits[1] );
930 if ( !is_readable( $settingsFile ) ) {
931 $this->error( "A copy of your installation's LocalSettings.php\n" .
932 "must exist and be readable in the source directory.\n" .
933 "Use --conf to specify it.", true );
935 $wgCommandLineMode = true;
936 return $settingsFile;
940 * Support function for cleaning up redundant text records
941 * @param bool $delete Whether or not to actually delete the records
942 * @author Rob Church <robchur@gmail.com>
944 public function purgeRedundantText( $delete = true ) {
945 # Data should come off the master, wrapped in a transaction
946 $dbw = $this->getDB( DB_MASTER
);
947 $dbw->begin( __METHOD__
);
949 # Get "active" text records from the revisions table
950 $this->output( 'Searching for active text records in revisions table...' );
951 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
952 foreach ( $res as $row ) {
953 $cur[] = $row->rev_text_id
;
955 $this->output( "done.\n" );
957 # Get "active" text records from the archive table
958 $this->output( 'Searching for active text records in archive table...' );
959 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
960 foreach ( $res as $row ) {
961 # old pre-MW 1.5 records can have null ar_text_id's.
962 if ( $row->ar_text_id
!== null ) {
963 $cur[] = $row->ar_text_id
;
966 $this->output( "done.\n" );
968 # Get the IDs of all text records not in these sets
969 $this->output( 'Searching for inactive text records...' );
970 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
971 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__
, array( 'DISTINCT' ) );
973 foreach ( $res as $row ) {
974 $old[] = $row->old_id
;
976 $this->output( "done.\n" );
978 # Inform the user of what we're going to do
979 $count = count( $old );
980 $this->output( "$count inactive items found.\n" );
982 # Delete as appropriate
983 if ( $delete && $count ) {
984 $this->output( 'Deleting...' );
985 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__
);
986 $this->output( "done.\n" );
990 $dbw->commit( __METHOD__
);
994 * Get the maintenance directory.
997 protected function getDir() {
1002 * Returns a database to be used by current maintenance script. It can be set by setDB().
1003 * If not set, wfGetDB() will be used.
1004 * This function has the same parameters as wfGetDB()
1006 * @return DatabaseBase
1008 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1009 if ( is_null( $this->mDb
) ) {
1010 return wfGetDB( $db, $groups, $wiki );
1017 * Sets database object to be returned by getDB().
1019 * @param DatabaseBase $db Database object to be used
1021 public function setDB( &$db ) {
1026 * Lock the search index
1027 * @param DatabaseBase &$db
1029 private function lockSearchindex( &$db ) {
1030 $write = array( 'searchindex' );
1031 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1032 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1037 * @param DatabaseBase &$db
1039 private function unlockSearchindex( &$db ) {
1040 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1044 * Unlock and lock again
1045 * Since the lock is low-priority, queued reads will be able to complete
1046 * @param DatabaseBase &$db
1048 private function relockSearchindex( &$db ) {
1049 $this->unlockSearchindex( $db );
1050 $this->lockSearchindex( $db );
1054 * Perform a search index update with locking
1055 * @param int $maxLockTime The maximum time to keep the search index locked.
1056 * @param string $callback The function that will update the function.
1057 * @param DatabaseBase $dbw
1058 * @param array $results
1060 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1064 if ( $maxLockTime ) {
1065 $this->output( " --- Waiting for lock ---" );
1066 $this->lockSearchindex( $dbw );
1068 $this->output( "\n" );
1071 # Loop through the results and do a search update
1072 foreach ( $results as $row ) {
1073 # Allow reads to be processed
1074 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1075 $this->output( " --- Relocking ---" );
1076 $this->relockSearchindex( $dbw );
1078 $this->output( "\n" );
1080 call_user_func( $callback, $dbw, $row );
1083 # Unlock searchindex
1084 if ( $maxLockTime ) {
1085 $this->output( " --- Unlocking --" );
1086 $this->unlockSearchindex( $dbw );
1087 $this->output( "\n" );
1093 * Update the searchindex table for a given pageid
1094 * @param DatabaseBase $dbw A database write handle
1095 * @param int $pageId The page ID to update.
1096 * @return null|string
1098 public function updateSearchIndexForPage( $dbw, $pageId ) {
1099 // Get current revision
1100 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1103 $titleObj = $rev->getTitle();
1104 $title = $titleObj->getPrefixedDBkey();
1105 $this->output( "$title..." );
1106 # Update searchindex
1107 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1109 $this->output( "\n" );
1115 * Wrapper for posix_isatty()
1116 * We default as considering stdin a tty (for nice readline methods)
1117 * but treating stout as not a tty to avoid color codes
1119 * @param int $fd File descriptor
1122 public static function posix_isatty( $fd ) {
1123 if ( !function_exists( 'posix_isatty' ) ) {
1126 return posix_isatty( $fd );
1131 * Prompt the console for input
1132 * @param string $prompt What to begin the line with, like '> '
1133 * @return string Response
1135 public static function readconsole( $prompt = '> ' ) {
1136 static $isatty = null;
1137 if ( is_null( $isatty ) ) {
1138 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1141 if ( $isatty && function_exists( 'readline' ) ) {
1142 return readline( $prompt );
1145 $st = self
::readlineEmulation( $prompt );
1147 if ( feof( STDIN
) ) {
1150 $st = fgets( STDIN
, 1024 );
1153 if ( $st === false ) {
1156 $resp = trim( $st );
1162 * Emulate readline()
1163 * @param string $prompt What to begin the line with, like '> '
1166 private static function readlineEmulation( $prompt ) {
1167 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1168 if ( !wfIsWindows() && $bash ) {
1170 $encPrompt = wfEscapeShellArg( $prompt );
1171 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1172 $encCommand = wfEscapeShellArg( $command );
1173 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1175 if ( $retval == 0 ) {
1177 } elseif ( $retval == 127 ) {
1178 // Couldn't execute bash even though we thought we saw it.
1179 // Shell probably spit out an error message, sorry :(
1180 // Fall through to fgets()...
1187 // Fallback... we'll have no editing controls, EWWW
1188 if ( feof( STDIN
) ) {
1192 return fgets( STDIN
, 1024 );
1197 * Fake maintenance wrapper, mostly used for the web installer/updater
1199 class FakeMaintenance
extends Maintenance
{
1200 protected $mSelf = "FakeMaintenanceScript";
1201 public function execute() {
1207 * Class for scripts that perform database maintenance and want to log the
1208 * update in `updatelog` so we can later skip it
1210 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1211 public function __construct() {
1212 parent
::__construct();
1213 $this->addOption( 'force', 'Run the update even if it was completed already' );
1214 $this->setBatchSize( 200 );
1217 public function execute() {
1218 $db = $this->getDB( DB_MASTER
);
1219 $key = $this->getUpdateKey();
1221 if ( !$this->hasOption( 'force' )
1222 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
)
1224 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1228 if ( !$this->doDBUpdates() ) {
1232 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) ) {
1235 $this->output( $this->updatelogFailedMessage() . "\n" );
1241 * Message to show that the update was done already and was just skipped
1244 protected function updateSkippedMessage() {
1245 $key = $this->getUpdateKey();
1246 return "Update '{$key}' already logged as completed.";
1250 * Message to show the the update log was unable to log the completion of this update
1253 protected function updatelogFailedMessage() {
1254 $key = $this->getUpdateKey();
1255 return "Unable to log update '{$key}' as completed.";
1259 * Do the actual work. All child classes will need to implement this.
1260 * Return true to log the update as done or false (usually on failure).
1263 abstract protected function doDBUpdates();
1266 * Get the update key name to go in the update log table
1269 abstract protected function getUpdateKey();