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
{
53 * Constants for DB access type
54 * @see Maintenance::getDbType()
60 // Const for getStdin()
61 const STDIN_ALL
= 'all';
63 // This is the desired params
64 protected $mParams = array();
66 // Array of mapping short parameters to long ones
67 protected $mShortParamsMap = array();
69 // Array of desired args
70 protected $mArgList = array();
72 // This is the list of options that were actually passed
73 protected $mOptions = array();
75 // This is the list of arguments that were actually passed
76 protected $mArgs = array();
78 // Name of the script currently running
81 // Special vars for params that are always used
82 protected $mQuiet = false;
83 protected $mDbUser, $mDbPass;
85 // A description of the script, children should change this
86 protected $mDescription = '';
88 // Have we already loaded our user input?
89 protected $mInputLoaded = false;
92 * Batch size. If a script supports this, they should set
93 * a default with setBatchSize()
97 protected $mBatchSize = null;
99 // Generic options added by addDefaultParams()
100 private $mGenericParameters = array();
101 // Generic options which might or not be supported by the script
102 private $mDependantParameters = array();
105 * Used by getDD() / setDB()
111 * Used when creating separate schema files.
117 * Default constructor. Children should call this *first* if implementing
118 * their own constructors
120 public function __construct() {
121 // Setup $IP, using MW_INSTALL_PATH if it exists
123 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
124 ?
getenv( 'MW_INSTALL_PATH' )
125 : realpath( __DIR__
. '/..' );
127 $this->addDefaultParams();
128 register_shutdown_function( array( $this, 'outputChanneled' ), false );
132 * Should we execute the maintenance script, or just allow it to be included
133 * as a standalone class? It checks that the call stack only includes this
134 * function and "requires" (meaning was called from the file scope)
138 public static function shouldExecute() {
139 $bt = debug_backtrace();
140 $count = count( $bt );
142 return false; // sanity
144 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
145 return false; // last call should be to this function
147 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
148 for ( $i = 1; $i < $count; $i++
) {
149 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
150 return false; // previous calls should all be "requires"
157 * Do the actual work. All child classes will need to implement this
159 abstract public function execute();
162 * Add a parameter to the script. Will be displayed on --help
163 * with the associated description
165 * @param string $name The name of the param (help, version, etc)
166 * @param string $description The description of the param to show on --help
167 * @param bool $required Is the param required?
168 * @param bool $withArg Is an argument required with this option?
169 * @param string $shortName Character to use as short name
171 protected function addOption( $name, $description, $required = false,
172 $withArg = false, $shortName = false
174 $this->mParams
[$name] = array(
175 'desc' => $description,
176 'require' => $required,
177 'withArg' => $withArg,
178 'shortName' => $shortName
181 if ( $shortName !== false ) {
182 $this->mShortParamsMap
[$shortName] = $name;
187 * Checks to see if a particular param exists.
188 * @param string $name The name of the param
191 protected function hasOption( $name ) {
192 return isset( $this->mOptions
[$name] );
196 * Get an option, or return the default
197 * @param string $name The name of the param
198 * @param mixed $default Anything you want, default null
201 protected function getOption( $name, $default = null ) {
202 if ( $this->hasOption( $name ) ) {
203 return $this->mOptions
[$name];
205 // Set it so we don't have to provide the default again
206 $this->mOptions
[$name] = $default;
207 return $this->mOptions
[$name];
212 * Add some args that are needed
213 * @param string $arg Name of the arg, like 'start'
214 * @param string $description Short description of the arg
215 * @param bool $required Is this required?
217 protected function addArg( $arg, $description, $required = true ) {
218 $this->mArgList
[] = array(
220 'desc' => $description,
221 'require' => $required
226 * Remove an option. Useful for removing options that won't be used in your script.
227 * @param string $name The option to remove.
229 protected function deleteOption( $name ) {
230 unset( $this->mParams
[$name] );
234 * Set the description text.
235 * @param string $text The text of the description
237 protected function addDescription( $text ) {
238 $this->mDescription
= $text;
242 * Does a given argument exist?
243 * @param int $argId The integer value (from zero) for the arg
246 protected function hasArg( $argId = 0 ) {
247 return isset( $this->mArgs
[$argId] );
252 * @param int $argId The integer value (from zero) for the arg
253 * @param mixed $default The default if it doesn't exist
256 protected function getArg( $argId = 0, $default = null ) {
257 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
261 * Set the batch size.
262 * @param int $s The number of operations to do in a batch
264 protected function setBatchSize( $s = 0 ) {
265 $this->mBatchSize
= $s;
267 // If we support $mBatchSize, show the option.
268 // Used to be in addDefaultParams, but in order for that to
269 // work, subclasses would have to call this function in the constructor
270 // before they called parent::__construct which is just weird
271 // (and really wasn't done).
272 if ( $this->mBatchSize
) {
273 $this->addOption( 'batch-size', 'Run this many operations ' .
274 'per batch, default: ' . $this->mBatchSize
, false, true );
275 if ( isset( $this->mParams
['batch-size'] ) ) {
276 // This seems a little ugly...
277 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
283 * Get the script's name
286 public function getName() {
291 * Return input from stdin.
292 * @param int $len The number of bytes to read. If null, just return the handle.
293 * Maintenance::STDIN_ALL returns the full length
296 protected function getStdin( $len = null ) {
297 if ( $len == Maintenance
::STDIN_ALL
) {
298 return file_get_contents( 'php://stdin' );
300 $f = fopen( 'php://stdin', 'rt' );
304 $input = fgets( $f, $len );
306 return rtrim( $input );
312 public function isQuiet() {
313 return $this->mQuiet
;
317 * Throw some output to the user. Scripts can call this with no fears,
318 * as we handle all --quiet stuff here
319 * @param string $out The text to show to the user
320 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
322 protected function output( $out, $channel = null ) {
323 if ( $this->mQuiet
) {
326 if ( $channel === null ) {
327 $this->cleanupChanneled();
330 $out = preg_replace( '/\n\z/', '', $out );
331 $this->outputChanneled( $out, $channel );
336 * Throw an error to the user. Doesn't respect --quiet, so don't use
337 * this for non-error output
338 * @param string $err The error to display
339 * @param int $die If > 0, go ahead and die out using this int as the code
341 protected function error( $err, $die = 0 ) {
342 $this->outputChanneled( false );
343 if ( PHP_SAPI
== 'cli' ) {
344 fwrite( STDERR
, $err . "\n" );
348 $die = intval( $die );
354 private $atLineStart = true;
355 private $lastChannel = null;
358 * Clean up channeled output. Output a newline if necessary.
360 public function cleanupChanneled() {
361 if ( !$this->atLineStart
) {
363 $this->atLineStart
= true;
368 * Message outputter with channeled message support. Messages on the
369 * same channel are concatenated, but any intervening messages in another
370 * channel start a new line.
371 * @param string $msg The message without trailing newline
372 * @param string $channel Channel identifier or null for no
373 * channel. Channel comparison uses ===.
375 public function outputChanneled( $msg, $channel = null ) {
376 if ( $msg === false ) {
377 $this->cleanupChanneled();
381 // End the current line if necessary
382 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
388 $this->atLineStart
= false;
389 if ( $channel === null ) {
390 // For unchanneled messages, output trailing newline immediately
392 $this->atLineStart
= true;
394 $this->lastChannel
= $channel;
398 * Does the script need different DB access? By default, we give Maintenance
399 * scripts normal rights to the DB. Sometimes, a script needs admin rights
400 * access for a reason and sometimes they want no access. Subclasses should
401 * override and return one of the following values, as needed:
402 * Maintenance::DB_NONE - For no DB access at all
403 * Maintenance::DB_STD - For normal DB access, default
404 * Maintenance::DB_ADMIN - For admin DB access
407 public function getDbType() {
408 return Maintenance
::DB_STD
;
412 * Add the default parameters to the scripts
414 protected function addDefaultParams() {
416 # Generic (non script dependant) options:
418 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
419 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
420 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
421 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
422 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
425 'Set a specific memory limit for the script, '
426 . '"max" for no limit or "default" to avoid changing it'
428 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
429 "http://en.wikipedia.org. This is sometimes necessary because " .
430 "server name detection may fail in command line scripts.", false, true );
431 $this->addOption( 'profiler', 'Set to "text" or "trace" to show profiling output', false, true );
433 # Save generic options to display them separately in help
434 $this->mGenericParameters
= $this->mParams
;
436 # Script dependant options:
438 // If we support a DB, show the options
439 if ( $this->getDbType() > 0 ) {
440 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
441 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
444 # Save additional script dependant options to display
445 #Â them separately in help
446 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
450 * Run a child maintenance script. Pass all of the current arguments
452 * @param string $maintClass A name of a child maintenance class
453 * @param string $classFile Full path of where the child is
454 * @return Maintenance
456 public function runChild( $maintClass, $classFile = null ) {
457 // Make sure the class is loaded first
458 if ( !class_exists( $maintClass ) ) {
460 require_once $classFile;
462 if ( !class_exists( $maintClass ) ) {
463 $this->error( "Cannot spawn child: $maintClass" );
468 * @var $child Maintenance
470 $child = new $maintClass();
471 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
472 if ( !is_null( $this->mDb
) ) {
473 $child->setDB( $this->mDb
);
479 * Do some sanity checking and basic setup
481 public function setup() {
482 global $IP, $wgCommandLineMode, $wgRequestTime;
484 # Abort if called from a web server
485 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
486 $this->error( 'This script must be run from the command line', true );
489 if ( $IP === null ) {
490 $this->error( "\$IP not set, aborting!\n" .
491 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
494 # Make sure we can handle script parameters
495 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
496 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
499 // Send PHP warnings and errors to stderr instead of stdout.
500 // This aids in diagnosing problems, while keeping messages
501 // out of redirected output.
502 if ( ini_get( 'display_errors' ) ) {
503 ini_set( 'display_errors', 'stderr' );
506 $this->loadParamsAndArgs();
509 # Set the memory limit
510 # Note we need to set it again later in cache LocalSettings changed it
511 $this->adjustMemoryLimit();
513 # Set max execution time to 0 (no limit). PHP.net says that
514 # "When running PHP from the command line the default setting is 0."
515 # But sometimes this doesn't seem to be the case.
516 ini_set( 'max_execution_time', 0 );
518 $wgRequestTime = microtime( true );
520 # Define us as being in MediaWiki
521 define( 'MEDIAWIKI', true );
523 $wgCommandLineMode = true;
525 # Turn off output buffering if it's on
526 while ( ob_get_level() > 0 ) {
530 $this->validateParamsAndArgs();
534 * Normally we disable the memory_limit when running admin scripts.
535 * Some scripts may wish to actually set a limit, however, to avoid
536 * blowing up unexpectedly. We also support a --memory-limit option,
537 * to allow sysadmins to explicitly set one if they'd prefer to override
538 * defaults (or for people using Suhosin which yells at you for trying
539 * to disable the limits)
542 public function memoryLimit() {
543 $limit = $this->getOption( 'memory-limit', 'max' );
544 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
549 * Adjusts PHP's memory limit to better suit our needs, if needed.
551 protected function adjustMemoryLimit() {
552 $limit = $this->memoryLimit();
553 if ( $limit == 'max' ) {
554 $limit = -1; // no memory limit
556 if ( $limit != 'default' ) {
557 ini_set( 'memory_limit', $limit );
562 * Clear all params and arguments.
564 public function clearParamsAndArgs() {
565 $this->mOptions
= array();
566 $this->mArgs
= array();
567 $this->mInputLoaded
= false;
571 * Process command line arguments
572 * $mOptions becomes an array with keys set to the option names
573 * $mArgs becomes a zero-based array containing the non-option arguments
575 * @param string $self The name of the script, if any
576 * @param array $opts An array of options, in form of key=>value
577 * @param array $args An array of command line arguments
579 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
580 # If we were given opts or args, set those and return early
582 $this->mSelf
= $self;
583 $this->mInputLoaded
= true;
586 $this->mOptions
= $opts;
587 $this->mInputLoaded
= true;
590 $this->mArgs
= $args;
591 $this->mInputLoaded
= true;
594 # If we've already loaded input (either by user values or from $argv)
595 # skip on loading it again. The array_shift() will corrupt values if
596 # it's run again and again
597 if ( $this->mInputLoaded
) {
598 $this->loadSpecialVars();
603 $this->mSelf
= array_shift( $argv );
609 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
610 if ( $arg == '--' ) {
611 # End of options, remainder should be considered arguments
612 $arg = next( $argv );
613 while ( $arg !== false ) {
615 $arg = next( $argv );
618 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
620 $option = substr( $arg, 2 );
621 if ( array_key_exists( $option, $options ) ) {
622 $this->error( "\nERROR: $option parameter given twice\n" );
623 $this->maybeHelp( true );
625 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
626 $param = next( $argv );
627 if ( $param === false ) {
628 $this->error( "\nERROR: $option parameter needs a value after it\n" );
629 $this->maybeHelp( true );
631 $options[$option] = $param;
633 $bits = explode( '=', $option, 2 );
634 if ( count( $bits ) > 1 ) {
640 $options[$option] = $param;
642 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
644 $argLength = strlen( $arg );
645 for ( $p = 1; $p < $argLength; $p++
) {
646 $option = $arg { $p };
647 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
648 $option = $this->mShortParamsMap
[$option];
650 if ( array_key_exists( $option, $options ) ) {
651 $this->error( "\nERROR: $option parameter given twice\n" );
652 $this->maybeHelp( true );
654 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
655 $param = next( $argv );
656 if ( $param === false ) {
657 $this->error( "\nERROR: $option parameter needs a value after it\n" );
658 $this->maybeHelp( true );
660 $options[$option] = $param;
662 $options[$option] = 1;
670 $this->mOptions
= $options;
671 $this->mArgs
= $args;
672 $this->loadSpecialVars();
673 $this->mInputLoaded
= true;
677 * Run some validation checks on the params, etc
679 protected function validateParamsAndArgs() {
681 # Check to make sure we've got all the required options
682 foreach ( $this->mParams
as $opt => $info ) {
683 if ( $info['require'] && !$this->hasOption( $opt ) ) {
684 $this->error( "Param $opt required!" );
689 foreach ( $this->mArgList
as $k => $info ) {
690 if ( $info['require'] && !$this->hasArg( $k ) ) {
691 $this->error( 'Argument <' . $info['name'] . '> required!' );
697 $this->maybeHelp( true );
702 * Handle the special variables that are global to all scripts
704 protected function loadSpecialVars() {
705 if ( $this->hasOption( 'dbuser' ) ) {
706 $this->mDbUser
= $this->getOption( 'dbuser' );
708 if ( $this->hasOption( 'dbpass' ) ) {
709 $this->mDbPass
= $this->getOption( 'dbpass' );
711 if ( $this->hasOption( 'quiet' ) ) {
712 $this->mQuiet
= true;
714 if ( $this->hasOption( 'batch-size' ) ) {
715 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
720 * Maybe show the help.
721 * @param bool $force Whether to force the help to show, default false
723 protected function maybeHelp( $force = false ) {
724 if ( !$force && !$this->hasOption( 'help' ) ) {
728 $screenWidth = 80; // TODO: Caculate this!
730 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
732 ksort( $this->mParams
);
733 $this->mQuiet
= false;
736 if ( $this->mDescription
) {
737 $this->output( "\n" . $this->mDescription
. "\n" );
739 $output = "\nUsage: php " . basename( $this->mSelf
);
741 // ... append parameters ...
742 if ( $this->mParams
) {
743 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
746 // ... and append arguments.
747 if ( $this->mArgList
) {
749 foreach ( $this->mArgList
as $k => $arg ) {
750 if ( $arg['require'] ) {
751 $output .= '<' . $arg['name'] . '>';
753 $output .= '[' . $arg['name'] . ']';
755 if ( $k < count( $this->mArgList
) - 1 ) {
760 $this->output( "$output\n\n" );
762 # TODO abstract some repetitive code below
764 // Generic parameters
765 $this->output( "Generic maintenance parameters:\n" );
766 foreach ( $this->mGenericParameters
as $par => $info ) {
767 if ( $info['shortName'] !== false ) {
768 $par .= " (-{$info['shortName']})";
771 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
772 "\n$tab$tab" ) . "\n"
775 $this->output( "\n" );
777 $scriptDependantParams = $this->mDependantParameters
;
778 if ( count( $scriptDependantParams ) > 0 ) {
779 $this->output( "Script dependant parameters:\n" );
780 // Parameters description
781 foreach ( $scriptDependantParams as $par => $info ) {
782 if ( $info['shortName'] !== false ) {
783 $par .= " (-{$info['shortName']})";
786 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
787 "\n$tab$tab" ) . "\n"
790 $this->output( "\n" );
793 // Script specific parameters not defined on construction by
794 // Maintenance::addDefaultParams()
795 $scriptSpecificParams = array_diff_key(
796 # all script parameters:
798 # remove the Maintenance default parameters:
799 $this->mGenericParameters
,
800 $this->mDependantParameters
802 if ( count( $scriptSpecificParams ) > 0 ) {
803 $this->output( "Script specific parameters:\n" );
804 // Parameters description
805 foreach ( $scriptSpecificParams as $par => $info ) {
806 if ( $info['shortName'] !== false ) {
807 $par .= " (-{$info['shortName']})";
810 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
811 "\n$tab$tab" ) . "\n"
814 $this->output( "\n" );
818 if ( count( $this->mArgList
) > 0 ) {
819 $this->output( "Arguments:\n" );
820 // Arguments description
821 foreach ( $this->mArgList
as $info ) {
822 $openChar = $info['require'] ?
'<' : '[';
823 $closeChar = $info['require'] ?
'>' : ']';
825 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
826 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
829 $this->output( "\n" );
836 * Handle some last-minute setup here.
838 public function finalSetup() {
839 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
840 global $wgDBadminuser, $wgDBadminpassword;
841 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
843 # Turn off output buffering again, it might have been turned on in the settings files
844 if ( ob_get_level() ) {
848 $wgCommandLineMode = true;
851 if ( $this->hasOption( 'server' ) ) {
852 $wgServer = $this->getOption( 'server', $wgServer );
855 # If these were passed, use them
856 if ( $this->mDbUser
) {
857 $wgDBadminuser = $this->mDbUser
;
859 if ( $this->mDbPass
) {
860 $wgDBadminpassword = $this->mDbPass
;
863 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
864 $wgDBuser = $wgDBadminuser;
865 $wgDBpassword = $wgDBadminpassword;
867 if ( $wgDBservers ) {
869 * @var $wgDBservers array
871 foreach ( $wgDBservers as $i => $server ) {
872 $wgDBservers[$i]['user'] = $wgDBuser;
873 $wgDBservers[$i]['password'] = $wgDBpassword;
876 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
877 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
878 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
880 LBFactory
::destroyInstance();
883 $this->afterFinalSetup();
885 $wgShowSQLErrors = true;
887 // @codingStandardsIgnoreStart Allow error supppression. wfSuppressWarnings()
889 @set_time_limit
( 0 );
890 // @codingStandardsIgnoreStart
892 $this->adjustMemoryLimit();
894 // Per-script profiling; useful for debugging
895 $forcedProfiler = $this->getOption( 'profiler' );
896 if ( $forcedProfiler === 'text' ) {
897 Profiler
::setInstance( new ProfilerSimpleText( array() ) );
898 Profiler
::instance()->setTemplated( true );
899 } elseif ( $forcedProfiler === 'trace' ) {
900 Profiler
::setInstance( new ProfilerSimpleTrace( array() ) );
901 Profiler
::instance()->setTemplated( true );
906 * Execute a callback function at the end of initialisation
908 protected function afterFinalSetup() {
909 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
910 call_user_func( MW_CMDLINE_CALLBACK
);
915 * Potentially debug globals. Originally a feature only
918 public function globals() {
919 if ( $this->hasOption( 'globals' ) ) {
925 * Generic setup for most installs. Returns the location of LocalSettings
928 public function loadSettings() {
929 global $wgCommandLineMode, $IP;
931 if ( isset( $this->mOptions
['conf'] ) ) {
932 $settingsFile = $this->mOptions
['conf'];
933 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
934 $settingsFile = MW_CONFIG_FILE
;
936 $settingsFile = "$IP/LocalSettings.php";
938 if ( isset( $this->mOptions
['wiki'] ) ) {
939 $bits = explode( '-', $this->mOptions
['wiki'] );
940 if ( count( $bits ) == 1 ) {
943 define( 'MW_DB', $bits[0] );
944 define( 'MW_PREFIX', $bits[1] );
947 if ( !is_readable( $settingsFile ) ) {
948 $this->error( "A copy of your installation's LocalSettings.php\n" .
949 "must exist and be readable in the source directory.\n" .
950 "Use --conf to specify it.", true );
952 $wgCommandLineMode = true;
953 return $settingsFile;
957 * Support function for cleaning up redundant text records
958 * @param bool $delete Whether or not to actually delete the records
959 * @author Rob Church <robchur@gmail.com>
961 public function purgeRedundantText( $delete = true ) {
962 # Data should come off the master, wrapped in a transaction
963 $dbw = $this->getDB( DB_MASTER
);
964 $dbw->begin( __METHOD__
);
966 # Get "active" text records from the revisions table
967 $this->output( 'Searching for active text records in revisions table...' );
968 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
969 foreach ( $res as $row ) {
970 $cur[] = $row->rev_text_id
;
972 $this->output( "done.\n" );
974 # Get "active" text records from the archive table
975 $this->output( 'Searching for active text records in archive table...' );
976 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
977 foreach ( $res as $row ) {
978 # old pre-MW 1.5 records can have null ar_text_id's.
979 if ( $row->ar_text_id
!== null ) {
980 $cur[] = $row->ar_text_id
;
983 $this->output( "done.\n" );
985 # Get the IDs of all text records not in these sets
986 $this->output( 'Searching for inactive text records...' );
987 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
988 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__
, array( 'DISTINCT' ) );
990 foreach ( $res as $row ) {
991 $old[] = $row->old_id
;
993 $this->output( "done.\n" );
995 # Inform the user of what we're going to do
996 $count = count( $old );
997 $this->output( "$count inactive items found.\n" );
999 # Delete as appropriate
1000 if ( $delete && $count ) {
1001 $this->output( 'Deleting...' );
1002 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__
);
1003 $this->output( "done.\n" );
1007 $dbw->commit( __METHOD__
);
1011 * Get the maintenance directory.
1014 protected function getDir() {
1019 * Returns a database to be used by current maintenance script. It can be set by setDB().
1020 * If not set, wfGetDB() will be used.
1021 * This function has the same parameters as wfGetDB()
1023 * @return DatabaseBase
1025 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1026 if ( is_null( $this->mDb
) ) {
1027 return wfGetDB( $db, $groups, $wiki );
1034 * Sets database object to be returned by getDB().
1036 * @param DatabaseBase $db Database object to be used
1038 public function setDB( &$db ) {
1043 * Lock the search index
1044 * @param DatabaseBase &$db
1046 private function lockSearchindex( &$db ) {
1047 $write = array( 'searchindex' );
1048 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1049 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1054 * @param DatabaseBase &$db
1056 private function unlockSearchindex( &$db ) {
1057 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1061 * Unlock and lock again
1062 * Since the lock is low-priority, queued reads will be able to complete
1063 * @param DatabaseBase &$db
1065 private function relockSearchindex( &$db ) {
1066 $this->unlockSearchindex( $db );
1067 $this->lockSearchindex( $db );
1071 * Perform a search index update with locking
1072 * @param int $maxLockTime The maximum time to keep the search index locked.
1073 * @param string $callback The function that will update the function.
1074 * @param DatabaseBase $dbw
1075 * @param array $results
1077 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1081 if ( $maxLockTime ) {
1082 $this->output( " --- Waiting for lock ---" );
1083 $this->lockSearchindex( $dbw );
1085 $this->output( "\n" );
1088 # Loop through the results and do a search update
1089 foreach ( $results as $row ) {
1090 # Allow reads to be processed
1091 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1092 $this->output( " --- Relocking ---" );
1093 $this->relockSearchindex( $dbw );
1095 $this->output( "\n" );
1097 call_user_func( $callback, $dbw, $row );
1100 # Unlock searchindex
1101 if ( $maxLockTime ) {
1102 $this->output( " --- Unlocking --" );
1103 $this->unlockSearchindex( $dbw );
1104 $this->output( "\n" );
1110 * Update the searchindex table for a given pageid
1111 * @param DatabaseBase $dbw A database write handle
1112 * @param int $pageId The page ID to update.
1113 * @return null|string
1115 public function updateSearchIndexForPage( $dbw, $pageId ) {
1116 // Get current revision
1117 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1120 $titleObj = $rev->getTitle();
1121 $title = $titleObj->getPrefixedDBkey();
1122 $this->output( "$title..." );
1123 # Update searchindex
1124 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1126 $this->output( "\n" );
1132 * Wrapper for posix_isatty()
1133 * We default as considering stdin a tty (for nice readline methods)
1134 * but treating stout as not a tty to avoid color codes
1136 * @param int $fd File descriptor
1139 public static function posix_isatty( $fd ) {
1140 if ( !function_exists( 'posix_isatty' ) ) {
1143 return posix_isatty( $fd );
1148 * Prompt the console for input
1149 * @param string $prompt What to begin the line with, like '> '
1150 * @return string Response
1152 public static function readconsole( $prompt = '> ' ) {
1153 static $isatty = null;
1154 if ( is_null( $isatty ) ) {
1155 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1158 if ( $isatty && function_exists( 'readline' ) ) {
1159 return readline( $prompt );
1162 $st = self
::readlineEmulation( $prompt );
1164 if ( feof( STDIN
) ) {
1167 $st = fgets( STDIN
, 1024 );
1170 if ( $st === false ) {
1173 $resp = trim( $st );
1179 * Emulate readline()
1180 * @param string $prompt What to begin the line with, like '> '
1183 private static function readlineEmulation( $prompt ) {
1184 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1185 if ( !wfIsWindows() && $bash ) {
1187 $encPrompt = wfEscapeShellArg( $prompt );
1188 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1189 $encCommand = wfEscapeShellArg( $command );
1190 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1192 if ( $retval == 0 ) {
1194 } elseif ( $retval == 127 ) {
1195 // Couldn't execute bash even though we thought we saw it.
1196 // Shell probably spit out an error message, sorry :(
1197 // Fall through to fgets()...
1204 // Fallback... we'll have no editing controls, EWWW
1205 if ( feof( STDIN
) ) {
1209 return fgets( STDIN
, 1024 );
1214 * Fake maintenance wrapper, mostly used for the web installer/updater
1216 class FakeMaintenance
extends Maintenance
{
1217 protected $mSelf = "FakeMaintenanceScript";
1218 public function execute() {
1224 * Class for scripts that perform database maintenance and want to log the
1225 * update in `updatelog` so we can later skip it
1227 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1228 public function __construct() {
1229 parent
::__construct();
1230 $this->addOption( 'force', 'Run the update even if it was completed already' );
1231 $this->setBatchSize( 200 );
1234 public function execute() {
1235 $db = $this->getDB( DB_MASTER
);
1236 $key = $this->getUpdateKey();
1238 if ( !$this->hasOption( 'force' )
1239 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
)
1241 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1245 if ( !$this->doDBUpdates() ) {
1249 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) ) {
1252 $this->output( $this->updatelogFailedMessage() . "\n" );
1258 * Message to show that the update was done already and was just skipped
1261 protected function updateSkippedMessage() {
1262 $key = $this->getUpdateKey();
1263 return "Update '{$key}' already logged as completed.";
1267 * Message to show the the update log was unable to log the completion of this update
1270 protected function updatelogFailedMessage() {
1271 $key = $this->getUpdateKey();
1272 return "Unable to log update '{$key}' as completed.";
1276 * Do the actual work. All child classes will need to implement this.
1277 * Return true to log the update as done or false (usually on failure).
1280 abstract protected function doDBUpdates();
1283 * Get the update key name to go in the update log table
1286 abstract protected function getUpdateKey();