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 global $wgCommandLineMode;
141 if ( !function_exists( 'debug_backtrace' ) ) {
142 // If someone has a better idea...
143 return $wgCommandLineMode;
146 $bt = debug_backtrace();
147 $count = count( $bt );
149 return false; // sanity
151 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
152 return false; // last call should be to this function
154 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
155 for ( $i = 1; $i < $count; $i++
) {
156 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
157 return false; // previous calls should all be "requires"
165 * Do the actual work. All child classes will need to implement this
167 abstract public function execute();
170 * Add a parameter to the script. Will be displayed on --help
171 * with the associated description
173 * @param string $name The name of the param (help, version, etc)
174 * @param string $description The description of the param to show on --help
175 * @param bool $required Is the param required?
176 * @param bool $withArg Is an argument required with this option?
177 * @param string $shortName Character to use as short name
179 protected function addOption( $name, $description, $required = false,
180 $withArg = false, $shortName = false
182 $this->mParams
[$name] = array(
183 'desc' => $description,
184 'require' => $required,
185 'withArg' => $withArg,
186 'shortName' => $shortName
189 if ( $shortName !== false ) {
190 $this->mShortParamsMap
[$shortName] = $name;
195 * Checks to see if a particular param exists.
196 * @param string $name The name of the param
199 protected function hasOption( $name ) {
200 return isset( $this->mOptions
[$name] );
204 * Get an option, or return the default
205 * @param string $name The name of the param
206 * @param mixed $default Anything you want, default null
209 protected function getOption( $name, $default = null ) {
210 if ( $this->hasOption( $name ) ) {
211 return $this->mOptions
[$name];
213 // Set it so we don't have to provide the default again
214 $this->mOptions
[$name] = $default;
216 return $this->mOptions
[$name];
221 * Add some args that are needed
222 * @param string $arg Name of the arg, like 'start'
223 * @param string $description Short description of the arg
224 * @param bool $required Is this required?
226 protected function addArg( $arg, $description, $required = true ) {
227 $this->mArgList
[] = array(
229 'desc' => $description,
230 'require' => $required
235 * Remove an option. Useful for removing options that won't be used in your script.
236 * @param string $name The option to remove.
238 protected function deleteOption( $name ) {
239 unset( $this->mParams
[$name] );
243 * Set the description text.
244 * @param string $text The text of the description
246 protected function addDescription( $text ) {
247 $this->mDescription
= $text;
251 * Does a given argument exist?
252 * @param int $argId The integer value (from zero) for the arg
255 protected function hasArg( $argId = 0 ) {
256 return isset( $this->mArgs
[$argId] );
261 * @param int $argId The integer value (from zero) for the arg
262 * @param mixed $default The default if it doesn't exist
265 protected function getArg( $argId = 0, $default = null ) {
266 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
270 * Set the batch size.
271 * @param int $s The number of operations to do in a batch
273 protected function setBatchSize( $s = 0 ) {
274 $this->mBatchSize
= $s;
276 // If we support $mBatchSize, show the option.
277 // Used to be in addDefaultParams, but in order for that to
278 // work, subclasses would have to call this function in the constructor
279 // before they called parent::__construct which is just weird
280 // (and really wasn't done).
281 if ( $this->mBatchSize
) {
282 $this->addOption( 'batch-size', 'Run this many operations ' .
283 'per batch, default: ' . $this->mBatchSize
, false, true );
284 if ( isset( $this->mParams
['batch-size'] ) ) {
285 // This seems a little ugly...
286 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
292 * Get the script's name
295 public function getName() {
300 * Return input from stdin.
301 * @param int $len The number of bytes to read. If null, just return the handle.
302 * Maintenance::STDIN_ALL returns the full length
305 protected function getStdin( $len = null ) {
306 if ( $len == Maintenance
::STDIN_ALL
) {
307 return file_get_contents( 'php://stdin' );
309 $f = fopen( 'php://stdin', 'rt' );
313 $input = fgets( $f, $len );
316 return rtrim( $input );
322 public function isQuiet() {
323 return $this->mQuiet
;
327 * Throw some output to the user. Scripts can call this with no fears,
328 * as we handle all --quiet stuff here
329 * @param string $out The text to show to the user
330 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
332 protected function output( $out, $channel = null ) {
333 if ( $this->mQuiet
) {
336 if ( $channel === null ) {
337 $this->cleanupChanneled();
340 $out = preg_replace( '/\n\z/', '', $out );
341 $this->outputChanneled( $out, $channel );
346 * Throw an error to the user. Doesn't respect --quiet, so don't use
347 * this for non-error output
348 * @param string $err The error to display
349 * @param int $die If > 0, go ahead and die out using this int as the code
351 protected function error( $err, $die = 0 ) {
352 $this->outputChanneled( false );
353 if ( PHP_SAPI
== 'cli' ) {
354 fwrite( STDERR
, $err . "\n" );
358 $die = intval( $die );
364 private $atLineStart = true;
365 private $lastChannel = null;
368 * Clean up channeled output. Output a newline if necessary.
370 public function cleanupChanneled() {
371 if ( !$this->atLineStart
) {
373 $this->atLineStart
= true;
378 * Message outputter with channeled message support. Messages on the
379 * same channel are concatenated, but any intervening messages in another
380 * channel start a new line.
381 * @param string $msg The message without trailing newline
382 * @param string $channel Channel identifier or null for no
383 * channel. Channel comparison uses ===.
385 public function outputChanneled( $msg, $channel = null ) {
386 if ( $msg === false ) {
387 $this->cleanupChanneled();
392 // End the current line if necessary
393 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
399 $this->atLineStart
= false;
400 if ( $channel === null ) {
401 // For unchanneled messages, output trailing newline immediately
403 $this->atLineStart
= true;
405 $this->lastChannel
= $channel;
409 * Does the script need different DB access? By default, we give Maintenance
410 * scripts normal rights to the DB. Sometimes, a script needs admin rights
411 * access for a reason and sometimes they want no access. Subclasses should
412 * override and return one of the following values, as needed:
413 * Maintenance::DB_NONE - For no DB access at all
414 * Maintenance::DB_STD - For normal DB access, default
415 * Maintenance::DB_ADMIN - For admin DB access
418 public function getDbType() {
419 return Maintenance
::DB_STD
;
423 * Add the default parameters to the scripts
425 protected function addDefaultParams() {
427 # Generic (non script dependant) options:
429 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
430 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
431 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
432 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
433 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
436 'Set a specific memory limit for the script, '
437 . '"max" for no limit or "default" to avoid changing it'
439 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
440 "http://en.wikipedia.org. This is sometimes necessary because " .
441 "server name detection may fail in command line scripts.", false, true );
442 $this->addOption( 'profiler', 'Set to "text" or "trace" to show profiling output', false, true );
444 # Save generic options to display them separately in help
445 $this->mGenericParameters
= $this->mParams
;
447 # Script dependant options:
449 // If we support a DB, show the options
450 if ( $this->getDbType() > 0 ) {
451 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
452 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
455 # Save additional script dependant options to display
456 #Â them separately in help
457 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
461 * Run a child maintenance script. Pass all of the current arguments
463 * @param string $maintClass A name of a child maintenance class
464 * @param string $classFile Full path of where the child is
465 * @return Maintenance
467 public function runChild( $maintClass, $classFile = null ) {
468 // Make sure the class is loaded first
469 if ( !class_exists( $maintClass ) ) {
471 require_once $classFile;
473 if ( !class_exists( $maintClass ) ) {
474 $this->error( "Cannot spawn child: $maintClass" );
479 * @var $child Maintenance
481 $child = new $maintClass();
482 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
483 if ( !is_null( $this->mDb
) ) {
484 $child->setDB( $this->mDb
);
491 * Do some sanity checking and basic setup
493 public function setup() {
494 global $IP, $wgCommandLineMode, $wgRequestTime;
496 # Abort if called from a web server
497 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
498 $this->error( 'This script must be run from the command line', true );
501 if ( $IP === null ) {
502 $this->error( "\$IP not set, aborting!\n" .
503 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
506 # Make sure we can handle script parameters
507 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
508 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
511 // Send PHP warnings and errors to stderr instead of stdout.
512 // This aids in diagnosing problems, while keeping messages
513 // out of redirected output.
514 if ( ini_get( 'display_errors' ) ) {
515 ini_set( 'display_errors', 'stderr' );
518 $this->loadParamsAndArgs();
521 # Set the memory limit
522 # Note we need to set it again later in cache LocalSettings changed it
523 $this->adjustMemoryLimit();
525 # Set max execution time to 0 (no limit). PHP.net says that
526 # "When running PHP from the command line the default setting is 0."
527 # But sometimes this doesn't seem to be the case.
528 ini_set( 'max_execution_time', 0 );
530 $wgCommandLineMode = true;
532 # Turn off output buffering if it's on
533 while ( ob_get_level() > 0 ) {
537 $this->validateParamsAndArgs();
541 * Normally we disable the memory_limit when running admin scripts.
542 * Some scripts may wish to actually set a limit, however, to avoid
543 * blowing up unexpectedly. We also support a --memory-limit option,
544 * to allow sysadmins to explicitly set one if they'd prefer to override
545 * defaults (or for people using Suhosin which yells at you for trying
546 * to disable the limits)
549 public function memoryLimit() {
550 $limit = $this->getOption( 'memory-limit', 'max' );
551 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
556 * Adjusts PHP's memory limit to better suit our needs, if needed.
558 protected function adjustMemoryLimit() {
559 $limit = $this->memoryLimit();
560 if ( $limit == 'max' ) {
561 $limit = -1; // no memory limit
563 if ( $limit != 'default' ) {
564 ini_set( 'memory_limit', $limit );
569 * Clear all params and arguments.
571 public function clearParamsAndArgs() {
572 $this->mOptions
= array();
573 $this->mArgs
= array();
574 $this->mInputLoaded
= false;
578 * Process command line arguments
579 * $mOptions becomes an array with keys set to the option names
580 * $mArgs becomes a zero-based array containing the non-option arguments
582 * @param string $self The name of the script, if any
583 * @param array $opts An array of options, in form of key=>value
584 * @param array $args An array of command line arguments
586 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
587 # If we were given opts or args, set those and return early
589 $this->mSelf
= $self;
590 $this->mInputLoaded
= true;
593 $this->mOptions
= $opts;
594 $this->mInputLoaded
= true;
597 $this->mArgs
= $args;
598 $this->mInputLoaded
= true;
601 # If we've already loaded input (either by user values or from $argv)
602 # skip on loading it again. The array_shift() will corrupt values if
603 # it's run again and again
604 if ( $this->mInputLoaded
) {
605 $this->loadSpecialVars();
611 $this->mSelf
= array_shift( $argv );
617 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
618 if ( $arg == '--' ) {
619 # End of options, remainder should be considered arguments
620 $arg = next( $argv );
621 while ( $arg !== false ) {
623 $arg = next( $argv );
626 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
628 $option = substr( $arg, 2 );
629 if ( array_key_exists( $option, $options ) ) {
630 $this->error( "\nERROR: $option parameter given twice\n" );
631 $this->maybeHelp( true );
633 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
634 $param = next( $argv );
635 if ( $param === false ) {
636 $this->error( "\nERROR: $option parameter needs a value after it\n" );
637 $this->maybeHelp( true );
639 $options[$option] = $param;
641 $bits = explode( '=', $option, 2 );
642 if ( count( $bits ) > 1 ) {
648 $options[$option] = $param;
650 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
652 $argLength = strlen( $arg );
653 for ( $p = 1; $p < $argLength; $p++
) {
655 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
656 $option = $this->mShortParamsMap
[$option];
658 if ( array_key_exists( $option, $options ) ) {
659 $this->error( "\nERROR: $option parameter given twice\n" );
660 $this->maybeHelp( true );
662 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
663 $param = next( $argv );
664 if ( $param === false ) {
665 $this->error( "\nERROR: $option parameter needs a value after it\n" );
666 $this->maybeHelp( true );
668 $options[$option] = $param;
670 $options[$option] = 1;
678 $this->mOptions
= $options;
679 $this->mArgs
= $args;
680 $this->loadSpecialVars();
681 $this->mInputLoaded
= true;
685 * Run some validation checks on the params, etc
687 protected function validateParamsAndArgs() {
689 # Check to make sure we've got all the required options
690 foreach ( $this->mParams
as $opt => $info ) {
691 if ( $info['require'] && !$this->hasOption( $opt ) ) {
692 $this->error( "Param $opt required!" );
697 foreach ( $this->mArgList
as $k => $info ) {
698 if ( $info['require'] && !$this->hasArg( $k ) ) {
699 $this->error( 'Argument <' . $info['name'] . '> required!' );
705 $this->maybeHelp( true );
710 * Handle the special variables that are global to all scripts
712 protected function loadSpecialVars() {
713 if ( $this->hasOption( 'dbuser' ) ) {
714 $this->mDbUser
= $this->getOption( 'dbuser' );
716 if ( $this->hasOption( 'dbpass' ) ) {
717 $this->mDbPass
= $this->getOption( 'dbpass' );
719 if ( $this->hasOption( 'quiet' ) ) {
720 $this->mQuiet
= true;
722 if ( $this->hasOption( 'batch-size' ) ) {
723 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
728 * Maybe show the help.
729 * @param bool $force Whether to force the help to show, default false
731 protected function maybeHelp( $force = false ) {
732 if ( !$force && !$this->hasOption( 'help' ) ) {
736 $screenWidth = 80; // TODO: Calculate this!
738 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
740 ksort( $this->mParams
);
741 $this->mQuiet
= false;
744 if ( $this->mDescription
) {
745 $this->output( "\n" . $this->mDescription
. "\n" );
747 $output = "\nUsage: php " . basename( $this->mSelf
);
749 // ... append parameters ...
750 if ( $this->mParams
) {
751 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
754 // ... and append arguments.
755 if ( $this->mArgList
) {
757 foreach ( $this->mArgList
as $k => $arg ) {
758 if ( $arg['require'] ) {
759 $output .= '<' . $arg['name'] . '>';
761 $output .= '[' . $arg['name'] . ']';
763 if ( $k < count( $this->mArgList
) - 1 ) {
768 $this->output( "$output\n\n" );
770 # TODO abstract some repetitive code below
772 // Generic parameters
773 $this->output( "Generic maintenance parameters:\n" );
774 foreach ( $this->mGenericParameters
as $par => $info ) {
775 if ( $info['shortName'] !== false ) {
776 $par .= " (-{$info['shortName']})";
779 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
780 "\n$tab$tab" ) . "\n"
783 $this->output( "\n" );
785 $scriptDependantParams = $this->mDependantParameters
;
786 if ( count( $scriptDependantParams ) > 0 ) {
787 $this->output( "Script dependant parameters:\n" );
788 // Parameters description
789 foreach ( $scriptDependantParams as $par => $info ) {
790 if ( $info['shortName'] !== false ) {
791 $par .= " (-{$info['shortName']})";
794 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
795 "\n$tab$tab" ) . "\n"
798 $this->output( "\n" );
801 // Script specific parameters not defined on construction by
802 // Maintenance::addDefaultParams()
803 $scriptSpecificParams = array_diff_key(
804 # all script parameters:
806 # remove the Maintenance default parameters:
807 $this->mGenericParameters
,
808 $this->mDependantParameters
810 if ( count( $scriptSpecificParams ) > 0 ) {
811 $this->output( "Script specific parameters:\n" );
812 // Parameters description
813 foreach ( $scriptSpecificParams as $par => $info ) {
814 if ( $info['shortName'] !== false ) {
815 $par .= " (-{$info['shortName']})";
818 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
819 "\n$tab$tab" ) . "\n"
822 $this->output( "\n" );
826 if ( count( $this->mArgList
) > 0 ) {
827 $this->output( "Arguments:\n" );
828 // Arguments description
829 foreach ( $this->mArgList
as $info ) {
830 $openChar = $info['require'] ?
'<' : '[';
831 $closeChar = $info['require'] ?
'>' : ']';
833 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
834 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
837 $this->output( "\n" );
844 * Handle some last-minute setup here.
846 public function finalSetup() {
847 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
848 global $wgDBadminuser, $wgDBadminpassword;
849 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
851 # Turn off output buffering again, it might have been turned on in the settings files
852 if ( ob_get_level() ) {
856 $wgCommandLineMode = true;
859 if ( $this->hasOption( 'server' ) ) {
860 $wgServer = $this->getOption( 'server', $wgServer );
863 # If these were passed, use them
864 if ( $this->mDbUser
) {
865 $wgDBadminuser = $this->mDbUser
;
867 if ( $this->mDbPass
) {
868 $wgDBadminpassword = $this->mDbPass
;
871 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
872 $wgDBuser = $wgDBadminuser;
873 $wgDBpassword = $wgDBadminpassword;
875 if ( $wgDBservers ) {
877 * @var $wgDBservers array
879 foreach ( $wgDBservers as $i => $server ) {
880 $wgDBservers[$i]['user'] = $wgDBuser;
881 $wgDBservers[$i]['password'] = $wgDBpassword;
884 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
885 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
886 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
888 LBFactory
::destroyInstance();
891 $this->afterFinalSetup();
893 $wgShowSQLErrors = true;
895 // @codingStandardsIgnoreStart Allow error supppression. wfSuppressWarnings()
897 @set_time_limit
( 0 );
898 // @codingStandardsIgnoreStart
900 $this->adjustMemoryLimit();
902 // Per-script profiling; useful for debugging
903 $forcedProfiler = $this->getOption( 'profiler' );
904 if ( $forcedProfiler === 'text' ) {
905 Profiler
::setInstance( new ProfilerSimpleText( array() ) );
906 Profiler
::instance()->setTemplated( true );
907 } elseif ( $forcedProfiler === 'trace' ) {
908 Profiler
::setInstance( new ProfilerSimpleTrace( array() ) );
909 Profiler
::instance()->setTemplated( true );
914 * Execute a callback function at the end of initialisation
916 protected function afterFinalSetup() {
917 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
918 call_user_func( MW_CMDLINE_CALLBACK
);
923 * Potentially debug globals. Originally a feature only
926 public function globals() {
927 if ( $this->hasOption( 'globals' ) ) {
933 * Generic setup for most installs. Returns the location of LocalSettings
936 public function loadSettings() {
937 global $wgCommandLineMode, $IP;
939 if ( isset( $this->mOptions
['conf'] ) ) {
940 $settingsFile = $this->mOptions
['conf'];
941 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
942 $settingsFile = MW_CONFIG_FILE
;
944 $settingsFile = "$IP/LocalSettings.php";
946 if ( isset( $this->mOptions
['wiki'] ) ) {
947 $bits = explode( '-', $this->mOptions
['wiki'] );
948 if ( count( $bits ) == 1 ) {
951 define( 'MW_DB', $bits[0] );
952 define( 'MW_PREFIX', $bits[1] );
955 if ( !is_readable( $settingsFile ) ) {
956 $this->error( "A copy of your installation's LocalSettings.php\n" .
957 "must exist and be readable in the source directory.\n" .
958 "Use --conf to specify it.", true );
960 $wgCommandLineMode = true;
962 return $settingsFile;
966 * Support function for cleaning up redundant text records
967 * @param bool $delete Whether or not to actually delete the records
968 * @author Rob Church <robchur@gmail.com>
970 public function purgeRedundantText( $delete = true ) {
971 # Data should come off the master, wrapped in a transaction
972 $dbw = $this->getDB( DB_MASTER
);
973 $dbw->begin( __METHOD__
);
975 # Get "active" text records from the revisions table
976 $this->output( 'Searching for active text records in revisions table...' );
977 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
978 foreach ( $res as $row ) {
979 $cur[] = $row->rev_text_id
;
981 $this->output( "done.\n" );
983 # Get "active" text records from the archive table
984 $this->output( 'Searching for active text records in archive table...' );
985 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
986 foreach ( $res as $row ) {
987 # old pre-MW 1.5 records can have null ar_text_id's.
988 if ( $row->ar_text_id
!== null ) {
989 $cur[] = $row->ar_text_id
;
992 $this->output( "done.\n" );
994 # Get the IDs of all text records not in these sets
995 $this->output( 'Searching for inactive text records...' );
996 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
997 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__
, array( 'DISTINCT' ) );
999 foreach ( $res as $row ) {
1000 $old[] = $row->old_id
;
1002 $this->output( "done.\n" );
1004 # Inform the user of what we're going to do
1005 $count = count( $old );
1006 $this->output( "$count inactive items found.\n" );
1008 # Delete as appropriate
1009 if ( $delete && $count ) {
1010 $this->output( 'Deleting...' );
1011 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__
);
1012 $this->output( "done.\n" );
1016 $dbw->commit( __METHOD__
);
1020 * Get the maintenance directory.
1023 protected function getDir() {
1028 * Returns a database to be used by current maintenance script. It can be set by setDB().
1029 * If not set, wfGetDB() will be used.
1030 * This function has the same parameters as wfGetDB()
1032 * @return DatabaseBase
1034 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1035 if ( is_null( $this->mDb
) ) {
1036 return wfGetDB( $db, $groups, $wiki );
1043 * Sets database object to be returned by getDB().
1045 * @param DatabaseBase $db Database object to be used
1047 public function setDB( &$db ) {
1052 * Lock the search index
1053 * @param DatabaseBase &$db
1055 private function lockSearchindex( &$db ) {
1056 $write = array( 'searchindex' );
1057 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1058 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1063 * @param DatabaseBase &$db
1065 private function unlockSearchindex( &$db ) {
1066 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1070 * Unlock and lock again
1071 * Since the lock is low-priority, queued reads will be able to complete
1072 * @param DatabaseBase &$db
1074 private function relockSearchindex( &$db ) {
1075 $this->unlockSearchindex( $db );
1076 $this->lockSearchindex( $db );
1080 * Perform a search index update with locking
1081 * @param int $maxLockTime The maximum time to keep the search index locked.
1082 * @param string $callback The function that will update the function.
1083 * @param DatabaseBase $dbw
1084 * @param array $results
1086 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1090 if ( $maxLockTime ) {
1091 $this->output( " --- Waiting for lock ---" );
1092 $this->lockSearchindex( $dbw );
1094 $this->output( "\n" );
1097 # Loop through the results and do a search update
1098 foreach ( $results as $row ) {
1099 # Allow reads to be processed
1100 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1101 $this->output( " --- Relocking ---" );
1102 $this->relockSearchindex( $dbw );
1104 $this->output( "\n" );
1106 call_user_func( $callback, $dbw, $row );
1109 # Unlock searchindex
1110 if ( $maxLockTime ) {
1111 $this->output( " --- Unlocking --" );
1112 $this->unlockSearchindex( $dbw );
1113 $this->output( "\n" );
1118 * Update the searchindex table for a given pageid
1119 * @param DatabaseBase $dbw A database write handle
1120 * @param int $pageId The page ID to update.
1121 * @return null|string
1123 public function updateSearchIndexForPage( $dbw, $pageId ) {
1124 // Get current revision
1125 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1128 $titleObj = $rev->getTitle();
1129 $title = $titleObj->getPrefixedDBkey();
1130 $this->output( "$title..." );
1131 # Update searchindex
1132 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1134 $this->output( "\n" );
1141 * Wrapper for posix_isatty()
1142 * We default as considering stdin a tty (for nice readline methods)
1143 * but treating stout as not a tty to avoid color codes
1145 * @param int $fd File descriptor
1148 public static function posix_isatty( $fd ) {
1149 if ( !function_exists( 'posix_isatty' ) ) {
1152 return posix_isatty( $fd );
1157 * Prompt the console for input
1158 * @param string $prompt What to begin the line with, like '> '
1159 * @return string Response
1161 public static function readconsole( $prompt = '> ' ) {
1162 static $isatty = null;
1163 if ( is_null( $isatty ) ) {
1164 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1167 if ( $isatty && function_exists( 'readline' ) ) {
1168 return readline( $prompt );
1171 $st = self
::readlineEmulation( $prompt );
1173 if ( feof( STDIN
) ) {
1176 $st = fgets( STDIN
, 1024 );
1179 if ( $st === false ) {
1182 $resp = trim( $st );
1189 * Emulate readline()
1190 * @param string $prompt What to begin the line with, like '> '
1193 private static function readlineEmulation( $prompt ) {
1194 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1195 if ( !wfIsWindows() && $bash ) {
1197 $encPrompt = wfEscapeShellArg( $prompt );
1198 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1199 $encCommand = wfEscapeShellArg( $command );
1200 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1202 if ( $retval == 0 ) {
1204 } elseif ( $retval == 127 ) {
1205 // Couldn't execute bash even though we thought we saw it.
1206 // Shell probably spit out an error message, sorry :(
1207 // Fall through to fgets()...
1214 // Fallback... we'll have no editing controls, EWWW
1215 if ( feof( STDIN
) ) {
1220 return fgets( STDIN
, 1024 );
1225 * Fake maintenance wrapper, mostly used for the web installer/updater
1227 class FakeMaintenance
extends Maintenance
{
1228 protected $mSelf = "FakeMaintenanceScript";
1230 public function execute() {
1236 * Class for scripts that perform database maintenance and want to log the
1237 * update in `updatelog` so we can later skip it
1239 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1240 public function __construct() {
1241 parent
::__construct();
1242 $this->addOption( 'force', 'Run the update even if it was completed already' );
1243 $this->setBatchSize( 200 );
1246 public function execute() {
1247 $db = $this->getDB( DB_MASTER
);
1248 $key = $this->getUpdateKey();
1250 if ( !$this->hasOption( 'force' )
1251 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
)
1253 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1258 if ( !$this->doDBUpdates() ) {
1262 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) ) {
1265 $this->output( $this->updatelogFailedMessage() . "\n" );
1272 * Message to show that the update was done already and was just skipped
1275 protected function updateSkippedMessage() {
1276 $key = $this->getUpdateKey();
1278 return "Update '{$key}' already logged as completed.";
1282 * Message to show the the update log was unable to log the completion of this update
1285 protected function updatelogFailedMessage() {
1286 $key = $this->getUpdateKey();
1288 return "Unable to log update '{$key}' as completed.";
1292 * Do the actual work. All child classes will need to implement this.
1293 * Return true to log the update as done or false (usually on failure).
1296 abstract protected function doDBUpdates();
1299 * Get the update key name to go in the update log table
1302 abstract protected function getUpdateKey();