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"
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,
173 $withArg = false, $shortName = false
175 $this->mParams
[$name] = array(
176 'desc' => $description,
177 'require' => $required,
178 'withArg' => $withArg,
179 'shortName' => $shortName
182 if ( $shortName !== false ) {
183 $this->mShortParamsMap
[$shortName] = $name;
188 * Checks to see if a particular param exists.
189 * @param string $name The name of the param
192 protected function hasOption( $name ) {
193 return isset( $this->mOptions
[$name] );
197 * Get an option, or return the default
198 * @param string $name The name of the param
199 * @param mixed $default Anything you want, default null
202 protected function getOption( $name, $default = null ) {
203 if ( $this->hasOption( $name ) ) {
204 return $this->mOptions
[$name];
206 // Set it so we don't have to provide the default again
207 $this->mOptions
[$name] = $default;
209 return $this->mOptions
[$name];
214 * Add some args that are needed
215 * @param string $arg Name of the arg, like 'start'
216 * @param string $description Short description of the arg
217 * @param bool $required Is this required?
219 protected function addArg( $arg, $description, $required = true ) {
220 $this->mArgList
[] = array(
222 'desc' => $description,
223 'require' => $required
228 * Remove an option. Useful for removing options that won't be used in your script.
229 * @param string $name The option to remove.
231 protected function deleteOption( $name ) {
232 unset( $this->mParams
[$name] );
236 * Set the description text.
237 * @param string $text The text of the description
239 protected function addDescription( $text ) {
240 $this->mDescription
= $text;
244 * Does a given argument exist?
245 * @param int $argId The integer value (from zero) for the arg
248 protected function hasArg( $argId = 0 ) {
249 return isset( $this->mArgs
[$argId] );
254 * @param int $argId The integer value (from zero) for the arg
255 * @param mixed $default The default if it doesn't exist
258 protected function getArg( $argId = 0, $default = null ) {
259 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
263 * Set the batch size.
264 * @param int $s The number of operations to do in a batch
266 protected function setBatchSize( $s = 0 ) {
267 $this->mBatchSize
= $s;
269 // If we support $mBatchSize, show the option.
270 // Used to be in addDefaultParams, but in order for that to
271 // work, subclasses would have to call this function in the constructor
272 // before they called parent::__construct which is just weird
273 // (and really wasn't done).
274 if ( $this->mBatchSize
) {
275 $this->addOption( 'batch-size', 'Run this many operations ' .
276 'per batch, default: ' . $this->mBatchSize
, false, true );
277 if ( isset( $this->mParams
['batch-size'] ) ) {
278 // This seems a little ugly...
279 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
285 * Get the script's name
288 public function getName() {
293 * Return input from stdin.
294 * @param int $len The number of bytes to read. If null, just return the handle.
295 * Maintenance::STDIN_ALL returns the full length
298 protected function getStdin( $len = null ) {
299 if ( $len == Maintenance
::STDIN_ALL
) {
300 return file_get_contents( 'php://stdin' );
302 $f = fopen( 'php://stdin', 'rt' );
306 $input = fgets( $f, $len );
309 return rtrim( $input );
315 public function isQuiet() {
316 return $this->mQuiet
;
320 * Throw some output to the user. Scripts can call this with no fears,
321 * as we handle all --quiet stuff here
322 * @param string $out The text to show to the user
323 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
325 protected function output( $out, $channel = null ) {
326 if ( $this->mQuiet
) {
329 if ( $channel === null ) {
330 $this->cleanupChanneled();
333 $out = preg_replace( '/\n\z/', '', $out );
334 $this->outputChanneled( $out, $channel );
339 * Throw an error to the user. Doesn't respect --quiet, so don't use
340 * this for non-error output
341 * @param string $err The error to display
342 * @param int $die If > 0, go ahead and die out using this int as the code
344 protected function error( $err, $die = 0 ) {
345 $this->outputChanneled( false );
346 if ( PHP_SAPI
== 'cli' ) {
347 fwrite( STDERR
, $err . "\n" );
351 $die = intval( $die );
357 private $atLineStart = true;
358 private $lastChannel = null;
361 * Clean up channeled output. Output a newline if necessary.
363 public function cleanupChanneled() {
364 if ( !$this->atLineStart
) {
366 $this->atLineStart
= true;
371 * Message outputter with channeled message support. Messages on the
372 * same channel are concatenated, but any intervening messages in another
373 * channel start a new line.
374 * @param string $msg The message without trailing newline
375 * @param string $channel Channel identifier or null for no
376 * channel. Channel comparison uses ===.
378 public function outputChanneled( $msg, $channel = null ) {
379 if ( $msg === false ) {
380 $this->cleanupChanneled();
385 // End the current line if necessary
386 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
392 $this->atLineStart
= false;
393 if ( $channel === null ) {
394 // For unchanneled messages, output trailing newline immediately
396 $this->atLineStart
= true;
398 $this->lastChannel
= $channel;
402 * Does the script need different DB access? By default, we give Maintenance
403 * scripts normal rights to the DB. Sometimes, a script needs admin rights
404 * access for a reason and sometimes they want no access. Subclasses should
405 * override and return one of the following values, as needed:
406 * Maintenance::DB_NONE - For no DB access at all
407 * Maintenance::DB_STD - For normal DB access, default
408 * Maintenance::DB_ADMIN - For admin DB access
411 public function getDbType() {
412 return Maintenance
::DB_STD
;
416 * Add the default parameters to the scripts
418 protected function addDefaultParams() {
420 # Generic (non script dependant) options:
422 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
423 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
424 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
425 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
426 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
429 'Set a specific memory limit for the script, '
430 . '"max" for no limit or "default" to avoid changing it'
432 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
433 "http://en.wikipedia.org. This is sometimes necessary because " .
434 "server name detection may fail in command line scripts.", false, true );
435 $this->addOption( 'profiler', 'Set to "text" or "trace" to show profiling output', false, true );
437 # Save generic options to display them separately in help
438 $this->mGenericParameters
= $this->mParams
;
440 # Script dependant options:
442 // If we support a DB, show the options
443 if ( $this->getDbType() > 0 ) {
444 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
445 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
448 # Save additional script dependant options to display
449 #Â them separately in help
450 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
454 * Run a child maintenance script. Pass all of the current arguments
456 * @param string $maintClass A name of a child maintenance class
457 * @param string $classFile Full path of where the child is
458 * @return Maintenance
460 public function runChild( $maintClass, $classFile = null ) {
461 // Make sure the class is loaded first
462 if ( !class_exists( $maintClass ) ) {
464 require_once $classFile;
466 if ( !class_exists( $maintClass ) ) {
467 $this->error( "Cannot spawn child: $maintClass" );
472 * @var $child Maintenance
474 $child = new $maintClass();
475 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
476 if ( !is_null( $this->mDb
) ) {
477 $child->setDB( $this->mDb
);
484 * Do some sanity checking and basic setup
486 public function setup() {
487 global $IP, $wgCommandLineMode, $wgRequestTime;
489 # Abort if called from a web server
490 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
491 $this->error( 'This script must be run from the command line', true );
494 if ( $IP === null ) {
495 $this->error( "\$IP not set, aborting!\n" .
496 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
499 # Make sure we can handle script parameters
500 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
501 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
504 // Send PHP warnings and errors to stderr instead of stdout.
505 // This aids in diagnosing problems, while keeping messages
506 // out of redirected output.
507 if ( ini_get( 'display_errors' ) ) {
508 ini_set( 'display_errors', 'stderr' );
511 $this->loadParamsAndArgs();
514 # Set the memory limit
515 # Note we need to set it again later in cache LocalSettings changed it
516 $this->adjustMemoryLimit();
518 # Set max execution time to 0 (no limit). PHP.net says that
519 # "When running PHP from the command line the default setting is 0."
520 # But sometimes this doesn't seem to be the case.
521 ini_set( 'max_execution_time', 0 );
523 $wgRequestTime = microtime( true );
525 # Define us as being in MediaWiki
526 define( 'MEDIAWIKI', true );
528 $wgCommandLineMode = true;
530 # Turn off output buffering if it's on
531 while ( ob_get_level() > 0 ) {
535 $this->validateParamsAndArgs();
539 * Normally we disable the memory_limit when running admin scripts.
540 * Some scripts may wish to actually set a limit, however, to avoid
541 * blowing up unexpectedly. We also support a --memory-limit option,
542 * to allow sysadmins to explicitly set one if they'd prefer to override
543 * defaults (or for people using Suhosin which yells at you for trying
544 * to disable the limits)
547 public function memoryLimit() {
548 $limit = $this->getOption( 'memory-limit', 'max' );
549 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
554 * Adjusts PHP's memory limit to better suit our needs, if needed.
556 protected function adjustMemoryLimit() {
557 $limit = $this->memoryLimit();
558 if ( $limit == 'max' ) {
559 $limit = -1; // no memory limit
561 if ( $limit != 'default' ) {
562 ini_set( 'memory_limit', $limit );
567 * Clear all params and arguments.
569 public function clearParamsAndArgs() {
570 $this->mOptions
= array();
571 $this->mArgs
= array();
572 $this->mInputLoaded
= false;
576 * Process command line arguments
577 * $mOptions becomes an array with keys set to the option names
578 * $mArgs becomes a zero-based array containing the non-option arguments
580 * @param string $self The name of the script, if any
581 * @param array $opts An array of options, in form of key=>value
582 * @param array $args An array of command line arguments
584 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
585 # If we were given opts or args, set those and return early
587 $this->mSelf
= $self;
588 $this->mInputLoaded
= true;
591 $this->mOptions
= $opts;
592 $this->mInputLoaded
= true;
595 $this->mArgs
= $args;
596 $this->mInputLoaded
= true;
599 # If we've already loaded input (either by user values or from $argv)
600 # skip on loading it again. The array_shift() will corrupt values if
601 # it's run again and again
602 if ( $this->mInputLoaded
) {
603 $this->loadSpecialVars();
609 $this->mSelf
= array_shift( $argv );
615 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
616 if ( $arg == '--' ) {
617 # End of options, remainder should be considered arguments
618 $arg = next( $argv );
619 while ( $arg !== false ) {
621 $arg = next( $argv );
624 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
626 $option = substr( $arg, 2 );
627 if ( array_key_exists( $option, $options ) ) {
628 $this->error( "\nERROR: $option parameter given twice\n" );
629 $this->maybeHelp( true );
631 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
632 $param = next( $argv );
633 if ( $param === false ) {
634 $this->error( "\nERROR: $option parameter needs a value after it\n" );
635 $this->maybeHelp( true );
637 $options[$option] = $param;
639 $bits = explode( '=', $option, 2 );
640 if ( count( $bits ) > 1 ) {
646 $options[$option] = $param;
648 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
650 $argLength = strlen( $arg );
651 for ( $p = 1; $p < $argLength; $p++
) {
653 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
654 $option = $this->mShortParamsMap
[$option];
656 if ( array_key_exists( $option, $options ) ) {
657 $this->error( "\nERROR: $option parameter given twice\n" );
658 $this->maybeHelp( true );
660 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
661 $param = next( $argv );
662 if ( $param === false ) {
663 $this->error( "\nERROR: $option parameter needs a value after it\n" );
664 $this->maybeHelp( true );
666 $options[$option] = $param;
668 $options[$option] = 1;
676 $this->mOptions
= $options;
677 $this->mArgs
= $args;
678 $this->loadSpecialVars();
679 $this->mInputLoaded
= true;
683 * Run some validation checks on the params, etc
685 protected function validateParamsAndArgs() {
687 # Check to make sure we've got all the required options
688 foreach ( $this->mParams
as $opt => $info ) {
689 if ( $info['require'] && !$this->hasOption( $opt ) ) {
690 $this->error( "Param $opt required!" );
695 foreach ( $this->mArgList
as $k => $info ) {
696 if ( $info['require'] && !$this->hasArg( $k ) ) {
697 $this->error( 'Argument <' . $info['name'] . '> required!' );
703 $this->maybeHelp( true );
708 * Handle the special variables that are global to all scripts
710 protected function loadSpecialVars() {
711 if ( $this->hasOption( 'dbuser' ) ) {
712 $this->mDbUser
= $this->getOption( 'dbuser' );
714 if ( $this->hasOption( 'dbpass' ) ) {
715 $this->mDbPass
= $this->getOption( 'dbpass' );
717 if ( $this->hasOption( 'quiet' ) ) {
718 $this->mQuiet
= true;
720 if ( $this->hasOption( 'batch-size' ) ) {
721 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
726 * Maybe show the help.
727 * @param bool $force Whether to force the help to show, default false
729 protected function maybeHelp( $force = false ) {
730 if ( !$force && !$this->hasOption( 'help' ) ) {
734 $screenWidth = 80; // TODO: Calculate this!
736 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
738 ksort( $this->mParams
);
739 $this->mQuiet
= false;
742 if ( $this->mDescription
) {
743 $this->output( "\n" . $this->mDescription
. "\n" );
745 $output = "\nUsage: php " . basename( $this->mSelf
);
747 // ... append parameters ...
748 if ( $this->mParams
) {
749 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
752 // ... and append arguments.
753 if ( $this->mArgList
) {
755 foreach ( $this->mArgList
as $k => $arg ) {
756 if ( $arg['require'] ) {
757 $output .= '<' . $arg['name'] . '>';
759 $output .= '[' . $arg['name'] . ']';
761 if ( $k < count( $this->mArgList
) - 1 ) {
766 $this->output( "$output\n\n" );
768 # TODO abstract some repetitive code below
770 // Generic parameters
771 $this->output( "Generic maintenance parameters:\n" );
772 foreach ( $this->mGenericParameters
as $par => $info ) {
773 if ( $info['shortName'] !== false ) {
774 $par .= " (-{$info['shortName']})";
777 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
778 "\n$tab$tab" ) . "\n"
781 $this->output( "\n" );
783 $scriptDependantParams = $this->mDependantParameters
;
784 if ( count( $scriptDependantParams ) > 0 ) {
785 $this->output( "Script dependant parameters:\n" );
786 // Parameters description
787 foreach ( $scriptDependantParams as $par => $info ) {
788 if ( $info['shortName'] !== false ) {
789 $par .= " (-{$info['shortName']})";
792 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
793 "\n$tab$tab" ) . "\n"
796 $this->output( "\n" );
799 // Script specific parameters not defined on construction by
800 // Maintenance::addDefaultParams()
801 $scriptSpecificParams = array_diff_key(
802 # all script parameters:
804 # remove the Maintenance default parameters:
805 $this->mGenericParameters
,
806 $this->mDependantParameters
808 if ( count( $scriptSpecificParams ) > 0 ) {
809 $this->output( "Script specific parameters:\n" );
810 // Parameters description
811 foreach ( $scriptSpecificParams as $par => $info ) {
812 if ( $info['shortName'] !== false ) {
813 $par .= " (-{$info['shortName']})";
816 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
817 "\n$tab$tab" ) . "\n"
820 $this->output( "\n" );
824 if ( count( $this->mArgList
) > 0 ) {
825 $this->output( "Arguments:\n" );
826 // Arguments description
827 foreach ( $this->mArgList
as $info ) {
828 $openChar = $info['require'] ?
'<' : '[';
829 $closeChar = $info['require'] ?
'>' : ']';
831 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
832 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
835 $this->output( "\n" );
842 * Handle some last-minute setup here.
844 public function finalSetup() {
845 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
846 global $wgDBadminuser, $wgDBadminpassword;
847 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
849 # Turn off output buffering again, it might have been turned on in the settings files
850 if ( ob_get_level() ) {
854 $wgCommandLineMode = true;
857 if ( $this->hasOption( 'server' ) ) {
858 $wgServer = $this->getOption( 'server', $wgServer );
861 # If these were passed, use them
862 if ( $this->mDbUser
) {
863 $wgDBadminuser = $this->mDbUser
;
865 if ( $this->mDbPass
) {
866 $wgDBadminpassword = $this->mDbPass
;
869 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
870 $wgDBuser = $wgDBadminuser;
871 $wgDBpassword = $wgDBadminpassword;
873 if ( $wgDBservers ) {
875 * @var $wgDBservers array
877 foreach ( $wgDBservers as $i => $server ) {
878 $wgDBservers[$i]['user'] = $wgDBuser;
879 $wgDBservers[$i]['password'] = $wgDBpassword;
882 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
883 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
884 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
886 LBFactory
::destroyInstance();
889 $this->afterFinalSetup();
891 $wgShowSQLErrors = true;
893 // @codingStandardsIgnoreStart Allow error supppression. wfSuppressWarnings()
895 @set_time_limit
( 0 );
896 // @codingStandardsIgnoreStart
898 $this->adjustMemoryLimit();
900 // Per-script profiling; useful for debugging
901 $forcedProfiler = $this->getOption( 'profiler' );
902 if ( $forcedProfiler === 'text' ) {
903 Profiler
::setInstance( new ProfilerSimpleText( array() ) );
904 Profiler
::instance()->setTemplated( true );
905 } elseif ( $forcedProfiler === 'trace' ) {
906 Profiler
::setInstance( new ProfilerSimpleTrace( array() ) );
907 Profiler
::instance()->setTemplated( true );
912 * Execute a callback function at the end of initialisation
914 protected function afterFinalSetup() {
915 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
916 call_user_func( MW_CMDLINE_CALLBACK
);
921 * Potentially debug globals. Originally a feature only
924 public function globals() {
925 if ( $this->hasOption( 'globals' ) ) {
931 * Generic setup for most installs. Returns the location of LocalSettings
934 public function loadSettings() {
935 global $wgCommandLineMode, $IP;
937 if ( isset( $this->mOptions
['conf'] ) ) {
938 $settingsFile = $this->mOptions
['conf'];
939 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
940 $settingsFile = MW_CONFIG_FILE
;
942 $settingsFile = "$IP/LocalSettings.php";
944 if ( isset( $this->mOptions
['wiki'] ) ) {
945 $bits = explode( '-', $this->mOptions
['wiki'] );
946 if ( count( $bits ) == 1 ) {
949 define( 'MW_DB', $bits[0] );
950 define( 'MW_PREFIX', $bits[1] );
953 if ( !is_readable( $settingsFile ) ) {
954 $this->error( "A copy of your installation's LocalSettings.php\n" .
955 "must exist and be readable in the source directory.\n" .
956 "Use --conf to specify it.", true );
958 $wgCommandLineMode = true;
960 return $settingsFile;
964 * Support function for cleaning up redundant text records
965 * @param bool $delete Whether or not to actually delete the records
966 * @author Rob Church <robchur@gmail.com>
968 public function purgeRedundantText( $delete = true ) {
969 # Data should come off the master, wrapped in a transaction
970 $dbw = $this->getDB( DB_MASTER
);
971 $dbw->begin( __METHOD__
);
973 # Get "active" text records from the revisions table
974 $this->output( 'Searching for active text records in revisions table...' );
975 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
976 foreach ( $res as $row ) {
977 $cur[] = $row->rev_text_id
;
979 $this->output( "done.\n" );
981 # Get "active" text records from the archive table
982 $this->output( 'Searching for active text records in archive table...' );
983 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
984 foreach ( $res as $row ) {
985 # old pre-MW 1.5 records can have null ar_text_id's.
986 if ( $row->ar_text_id
!== null ) {
987 $cur[] = $row->ar_text_id
;
990 $this->output( "done.\n" );
992 # Get the IDs of all text records not in these sets
993 $this->output( 'Searching for inactive text records...' );
994 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
995 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__
, array( 'DISTINCT' ) );
997 foreach ( $res as $row ) {
998 $old[] = $row->old_id
;
1000 $this->output( "done.\n" );
1002 # Inform the user of what we're going to do
1003 $count = count( $old );
1004 $this->output( "$count inactive items found.\n" );
1006 # Delete as appropriate
1007 if ( $delete && $count ) {
1008 $this->output( 'Deleting...' );
1009 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__
);
1010 $this->output( "done.\n" );
1014 $dbw->commit( __METHOD__
);
1018 * Get the maintenance directory.
1021 protected function getDir() {
1026 * Returns a database to be used by current maintenance script. It can be set by setDB().
1027 * If not set, wfGetDB() will be used.
1028 * This function has the same parameters as wfGetDB()
1030 * @return DatabaseBase
1032 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1033 if ( is_null( $this->mDb
) ) {
1034 return wfGetDB( $db, $groups, $wiki );
1041 * Sets database object to be returned by getDB().
1043 * @param DatabaseBase $db Database object to be used
1045 public function setDB( &$db ) {
1050 * Lock the search index
1051 * @param DatabaseBase &$db
1053 private function lockSearchindex( &$db ) {
1054 $write = array( 'searchindex' );
1055 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1056 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1061 * @param DatabaseBase &$db
1063 private function unlockSearchindex( &$db ) {
1064 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1068 * Unlock and lock again
1069 * Since the lock is low-priority, queued reads will be able to complete
1070 * @param DatabaseBase &$db
1072 private function relockSearchindex( &$db ) {
1073 $this->unlockSearchindex( $db );
1074 $this->lockSearchindex( $db );
1078 * Perform a search index update with locking
1079 * @param int $maxLockTime The maximum time to keep the search index locked.
1080 * @param string $callback The function that will update the function.
1081 * @param DatabaseBase $dbw
1082 * @param array $results
1084 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1088 if ( $maxLockTime ) {
1089 $this->output( " --- Waiting for lock ---" );
1090 $this->lockSearchindex( $dbw );
1092 $this->output( "\n" );
1095 # Loop through the results and do a search update
1096 foreach ( $results as $row ) {
1097 # Allow reads to be processed
1098 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1099 $this->output( " --- Relocking ---" );
1100 $this->relockSearchindex( $dbw );
1102 $this->output( "\n" );
1104 call_user_func( $callback, $dbw, $row );
1107 # Unlock searchindex
1108 if ( $maxLockTime ) {
1109 $this->output( " --- Unlocking --" );
1110 $this->unlockSearchindex( $dbw );
1111 $this->output( "\n" );
1116 * Update the searchindex table for a given pageid
1117 * @param DatabaseBase $dbw A database write handle
1118 * @param int $pageId The page ID to update.
1119 * @return null|string
1121 public function updateSearchIndexForPage( $dbw, $pageId ) {
1122 // Get current revision
1123 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1126 $titleObj = $rev->getTitle();
1127 $title = $titleObj->getPrefixedDBkey();
1128 $this->output( "$title..." );
1129 # Update searchindex
1130 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1132 $this->output( "\n" );
1139 * Wrapper for posix_isatty()
1140 * We default as considering stdin a tty (for nice readline methods)
1141 * but treating stout as not a tty to avoid color codes
1143 * @param int $fd File descriptor
1146 public static function posix_isatty( $fd ) {
1147 if ( !function_exists( 'posix_isatty' ) ) {
1150 return posix_isatty( $fd );
1155 * Prompt the console for input
1156 * @param string $prompt What to begin the line with, like '> '
1157 * @return string Response
1159 public static function readconsole( $prompt = '> ' ) {
1160 static $isatty = null;
1161 if ( is_null( $isatty ) ) {
1162 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1165 if ( $isatty && function_exists( 'readline' ) ) {
1166 return readline( $prompt );
1169 $st = self
::readlineEmulation( $prompt );
1171 if ( feof( STDIN
) ) {
1174 $st = fgets( STDIN
, 1024 );
1177 if ( $st === false ) {
1180 $resp = trim( $st );
1187 * Emulate readline()
1188 * @param string $prompt What to begin the line with, like '> '
1191 private static function readlineEmulation( $prompt ) {
1192 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1193 if ( !wfIsWindows() && $bash ) {
1195 $encPrompt = wfEscapeShellArg( $prompt );
1196 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1197 $encCommand = wfEscapeShellArg( $command );
1198 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1200 if ( $retval == 0 ) {
1202 } elseif ( $retval == 127 ) {
1203 // Couldn't execute bash even though we thought we saw it.
1204 // Shell probably spit out an error message, sorry :(
1205 // Fall through to fgets()...
1212 // Fallback... we'll have no editing controls, EWWW
1213 if ( feof( STDIN
) ) {
1218 return fgets( STDIN
, 1024 );
1223 * Fake maintenance wrapper, mostly used for the web installer/updater
1225 class FakeMaintenance
extends Maintenance
{
1226 protected $mSelf = "FakeMaintenanceScript";
1228 public function execute() {
1234 * Class for scripts that perform database maintenance and want to log the
1235 * update in `updatelog` so we can later skip it
1237 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1238 public function __construct() {
1239 parent
::__construct();
1240 $this->addOption( 'force', 'Run the update even if it was completed already' );
1241 $this->setBatchSize( 200 );
1244 public function execute() {
1245 $db = $this->getDB( DB_MASTER
);
1246 $key = $this->getUpdateKey();
1248 if ( !$this->hasOption( 'force' )
1249 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
)
1251 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1256 if ( !$this->doDBUpdates() ) {
1260 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) ) {
1263 $this->output( $this->updatelogFailedMessage() . "\n" );
1270 * Message to show that the update was done already and was just skipped
1273 protected function updateSkippedMessage() {
1274 $key = $this->getUpdateKey();
1276 return "Update '{$key}' already logged as completed.";
1280 * Message to show the the update log was unable to log the completion of this update
1283 protected function updatelogFailedMessage() {
1284 $key = $this->getUpdateKey();
1286 return "Unable to log update '{$key}' as completed.";
1290 * Do the actual work. All child classes will need to implement this.
1291 * Return true to log the update as done or false (usually on failure).
1294 abstract protected function doDBUpdates();
1297 * Get the update key name to go in the update log table
1300 abstract protected function getUpdateKey();