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 $wgRequestTime = microtime( true );
532 # Define us as being in MediaWiki
533 define( 'MEDIAWIKI', true );
535 $wgCommandLineMode = true;
537 # Turn off output buffering if it's on
538 while ( ob_get_level() > 0 ) {
542 $this->validateParamsAndArgs();
546 * Normally we disable the memory_limit when running admin scripts.
547 * Some scripts may wish to actually set a limit, however, to avoid
548 * blowing up unexpectedly. We also support a --memory-limit option,
549 * to allow sysadmins to explicitly set one if they'd prefer to override
550 * defaults (or for people using Suhosin which yells at you for trying
551 * to disable the limits)
554 public function memoryLimit() {
555 $limit = $this->getOption( 'memory-limit', 'max' );
556 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
561 * Adjusts PHP's memory limit to better suit our needs, if needed.
563 protected function adjustMemoryLimit() {
564 $limit = $this->memoryLimit();
565 if ( $limit == 'max' ) {
566 $limit = -1; // no memory limit
568 if ( $limit != 'default' ) {
569 ini_set( 'memory_limit', $limit );
574 * Clear all params and arguments.
576 public function clearParamsAndArgs() {
577 $this->mOptions
= array();
578 $this->mArgs
= array();
579 $this->mInputLoaded
= false;
583 * Process command line arguments
584 * $mOptions becomes an array with keys set to the option names
585 * $mArgs becomes a zero-based array containing the non-option arguments
587 * @param string $self The name of the script, if any
588 * @param array $opts An array of options, in form of key=>value
589 * @param array $args An array of command line arguments
591 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
592 # If we were given opts or args, set those and return early
594 $this->mSelf
= $self;
595 $this->mInputLoaded
= true;
598 $this->mOptions
= $opts;
599 $this->mInputLoaded
= true;
602 $this->mArgs
= $args;
603 $this->mInputLoaded
= true;
606 # If we've already loaded input (either by user values or from $argv)
607 # skip on loading it again. The array_shift() will corrupt values if
608 # it's run again and again
609 if ( $this->mInputLoaded
) {
610 $this->loadSpecialVars();
616 $this->mSelf
= array_shift( $argv );
622 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
623 if ( $arg == '--' ) {
624 # End of options, remainder should be considered arguments
625 $arg = next( $argv );
626 while ( $arg !== false ) {
628 $arg = next( $argv );
631 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
633 $option = substr( $arg, 2 );
634 if ( array_key_exists( $option, $options ) ) {
635 $this->error( "\nERROR: $option parameter given twice\n" );
636 $this->maybeHelp( true );
638 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
639 $param = next( $argv );
640 if ( $param === false ) {
641 $this->error( "\nERROR: $option parameter needs a value after it\n" );
642 $this->maybeHelp( true );
644 $options[$option] = $param;
646 $bits = explode( '=', $option, 2 );
647 if ( count( $bits ) > 1 ) {
653 $options[$option] = $param;
655 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
657 $argLength = strlen( $arg );
658 for ( $p = 1; $p < $argLength; $p++
) {
660 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
661 $option = $this->mShortParamsMap
[$option];
663 if ( array_key_exists( $option, $options ) ) {
664 $this->error( "\nERROR: $option parameter given twice\n" );
665 $this->maybeHelp( true );
667 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
668 $param = next( $argv );
669 if ( $param === false ) {
670 $this->error( "\nERROR: $option parameter needs a value after it\n" );
671 $this->maybeHelp( true );
673 $options[$option] = $param;
675 $options[$option] = 1;
683 $this->mOptions
= $options;
684 $this->mArgs
= $args;
685 $this->loadSpecialVars();
686 $this->mInputLoaded
= true;
690 * Run some validation checks on the params, etc
692 protected function validateParamsAndArgs() {
694 # Check to make sure we've got all the required options
695 foreach ( $this->mParams
as $opt => $info ) {
696 if ( $info['require'] && !$this->hasOption( $opt ) ) {
697 $this->error( "Param $opt required!" );
702 foreach ( $this->mArgList
as $k => $info ) {
703 if ( $info['require'] && !$this->hasArg( $k ) ) {
704 $this->error( 'Argument <' . $info['name'] . '> required!' );
710 $this->maybeHelp( true );
715 * Handle the special variables that are global to all scripts
717 protected function loadSpecialVars() {
718 if ( $this->hasOption( 'dbuser' ) ) {
719 $this->mDbUser
= $this->getOption( 'dbuser' );
721 if ( $this->hasOption( 'dbpass' ) ) {
722 $this->mDbPass
= $this->getOption( 'dbpass' );
724 if ( $this->hasOption( 'quiet' ) ) {
725 $this->mQuiet
= true;
727 if ( $this->hasOption( 'batch-size' ) ) {
728 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
733 * Maybe show the help.
734 * @param bool $force Whether to force the help to show, default false
736 protected function maybeHelp( $force = false ) {
737 if ( !$force && !$this->hasOption( 'help' ) ) {
741 $screenWidth = 80; // TODO: Calculate this!
743 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
745 ksort( $this->mParams
);
746 $this->mQuiet
= false;
749 if ( $this->mDescription
) {
750 $this->output( "\n" . $this->mDescription
. "\n" );
752 $output = "\nUsage: php " . basename( $this->mSelf
);
754 // ... append parameters ...
755 if ( $this->mParams
) {
756 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
759 // ... and append arguments.
760 if ( $this->mArgList
) {
762 foreach ( $this->mArgList
as $k => $arg ) {
763 if ( $arg['require'] ) {
764 $output .= '<' . $arg['name'] . '>';
766 $output .= '[' . $arg['name'] . ']';
768 if ( $k < count( $this->mArgList
) - 1 ) {
773 $this->output( "$output\n\n" );
775 # TODO abstract some repetitive code below
777 // Generic parameters
778 $this->output( "Generic maintenance parameters:\n" );
779 foreach ( $this->mGenericParameters
as $par => $info ) {
780 if ( $info['shortName'] !== false ) {
781 $par .= " (-{$info['shortName']})";
784 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
785 "\n$tab$tab" ) . "\n"
788 $this->output( "\n" );
790 $scriptDependantParams = $this->mDependantParameters
;
791 if ( count( $scriptDependantParams ) > 0 ) {
792 $this->output( "Script dependant parameters:\n" );
793 // Parameters description
794 foreach ( $scriptDependantParams as $par => $info ) {
795 if ( $info['shortName'] !== false ) {
796 $par .= " (-{$info['shortName']})";
799 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
800 "\n$tab$tab" ) . "\n"
803 $this->output( "\n" );
806 // Script specific parameters not defined on construction by
807 // Maintenance::addDefaultParams()
808 $scriptSpecificParams = array_diff_key(
809 # all script parameters:
811 # remove the Maintenance default parameters:
812 $this->mGenericParameters
,
813 $this->mDependantParameters
815 if ( count( $scriptSpecificParams ) > 0 ) {
816 $this->output( "Script specific parameters:\n" );
817 // Parameters description
818 foreach ( $scriptSpecificParams as $par => $info ) {
819 if ( $info['shortName'] !== false ) {
820 $par .= " (-{$info['shortName']})";
823 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
824 "\n$tab$tab" ) . "\n"
827 $this->output( "\n" );
831 if ( count( $this->mArgList
) > 0 ) {
832 $this->output( "Arguments:\n" );
833 // Arguments description
834 foreach ( $this->mArgList
as $info ) {
835 $openChar = $info['require'] ?
'<' : '[';
836 $closeChar = $info['require'] ?
'>' : ']';
838 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
839 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
842 $this->output( "\n" );
849 * Handle some last-minute setup here.
851 public function finalSetup() {
852 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
853 global $wgDBadminuser, $wgDBadminpassword;
854 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
856 # Turn off output buffering again, it might have been turned on in the settings files
857 if ( ob_get_level() ) {
861 $wgCommandLineMode = true;
864 if ( $this->hasOption( 'server' ) ) {
865 $wgServer = $this->getOption( 'server', $wgServer );
868 # If these were passed, use them
869 if ( $this->mDbUser
) {
870 $wgDBadminuser = $this->mDbUser
;
872 if ( $this->mDbPass
) {
873 $wgDBadminpassword = $this->mDbPass
;
876 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
877 $wgDBuser = $wgDBadminuser;
878 $wgDBpassword = $wgDBadminpassword;
880 if ( $wgDBservers ) {
882 * @var $wgDBservers array
884 foreach ( $wgDBservers as $i => $server ) {
885 $wgDBservers[$i]['user'] = $wgDBuser;
886 $wgDBservers[$i]['password'] = $wgDBpassword;
889 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
890 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
891 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
893 LBFactory
::destroyInstance();
896 $this->afterFinalSetup();
898 $wgShowSQLErrors = true;
900 // @codingStandardsIgnoreStart Allow error supppression. wfSuppressWarnings()
902 @set_time_limit
( 0 );
903 // @codingStandardsIgnoreStart
905 $this->adjustMemoryLimit();
907 // Per-script profiling; useful for debugging
908 $forcedProfiler = $this->getOption( 'profiler' );
909 if ( $forcedProfiler === 'text' ) {
910 Profiler
::setInstance( new ProfilerSimpleText( array() ) );
911 Profiler
::instance()->setTemplated( true );
912 } elseif ( $forcedProfiler === 'trace' ) {
913 Profiler
::setInstance( new ProfilerSimpleTrace( array() ) );
914 Profiler
::instance()->setTemplated( true );
919 * Execute a callback function at the end of initialisation
921 protected function afterFinalSetup() {
922 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
923 call_user_func( MW_CMDLINE_CALLBACK
);
928 * Potentially debug globals. Originally a feature only
931 public function globals() {
932 if ( $this->hasOption( 'globals' ) ) {
938 * Generic setup for most installs. Returns the location of LocalSettings
941 public function loadSettings() {
942 global $wgCommandLineMode, $IP;
944 if ( isset( $this->mOptions
['conf'] ) ) {
945 $settingsFile = $this->mOptions
['conf'];
946 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
947 $settingsFile = MW_CONFIG_FILE
;
949 $settingsFile = "$IP/LocalSettings.php";
951 if ( isset( $this->mOptions
['wiki'] ) ) {
952 $bits = explode( '-', $this->mOptions
['wiki'] );
953 if ( count( $bits ) == 1 ) {
956 define( 'MW_DB', $bits[0] );
957 define( 'MW_PREFIX', $bits[1] );
960 if ( !is_readable( $settingsFile ) ) {
961 $this->error( "A copy of your installation's LocalSettings.php\n" .
962 "must exist and be readable in the source directory.\n" .
963 "Use --conf to specify it.", true );
965 $wgCommandLineMode = true;
967 return $settingsFile;
971 * Support function for cleaning up redundant text records
972 * @param bool $delete Whether or not to actually delete the records
973 * @author Rob Church <robchur@gmail.com>
975 public function purgeRedundantText( $delete = true ) {
976 # Data should come off the master, wrapped in a transaction
977 $dbw = $this->getDB( DB_MASTER
);
978 $dbw->begin( __METHOD__
);
980 # Get "active" text records from the revisions table
981 $this->output( 'Searching for active text records in revisions table...' );
982 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
983 foreach ( $res as $row ) {
984 $cur[] = $row->rev_text_id
;
986 $this->output( "done.\n" );
988 # Get "active" text records from the archive table
989 $this->output( 'Searching for active text records in archive table...' );
990 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
991 foreach ( $res as $row ) {
992 # old pre-MW 1.5 records can have null ar_text_id's.
993 if ( $row->ar_text_id
!== null ) {
994 $cur[] = $row->ar_text_id
;
997 $this->output( "done.\n" );
999 # Get the IDs of all text records not in these sets
1000 $this->output( 'Searching for inactive text records...' );
1001 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1002 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__
, array( 'DISTINCT' ) );
1004 foreach ( $res as $row ) {
1005 $old[] = $row->old_id
;
1007 $this->output( "done.\n" );
1009 # Inform the user of what we're going to do
1010 $count = count( $old );
1011 $this->output( "$count inactive items found.\n" );
1013 # Delete as appropriate
1014 if ( $delete && $count ) {
1015 $this->output( 'Deleting...' );
1016 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__
);
1017 $this->output( "done.\n" );
1021 $dbw->commit( __METHOD__
);
1025 * Get the maintenance directory.
1028 protected function getDir() {
1033 * Returns a database to be used by current maintenance script. It can be set by setDB().
1034 * If not set, wfGetDB() will be used.
1035 * This function has the same parameters as wfGetDB()
1037 * @return DatabaseBase
1039 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1040 if ( is_null( $this->mDb
) ) {
1041 return wfGetDB( $db, $groups, $wiki );
1048 * Sets database object to be returned by getDB().
1050 * @param DatabaseBase $db Database object to be used
1052 public function setDB( &$db ) {
1057 * Lock the search index
1058 * @param DatabaseBase &$db
1060 private function lockSearchindex( &$db ) {
1061 $write = array( 'searchindex' );
1062 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1063 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1068 * @param DatabaseBase &$db
1070 private function unlockSearchindex( &$db ) {
1071 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1075 * Unlock and lock again
1076 * Since the lock is low-priority, queued reads will be able to complete
1077 * @param DatabaseBase &$db
1079 private function relockSearchindex( &$db ) {
1080 $this->unlockSearchindex( $db );
1081 $this->lockSearchindex( $db );
1085 * Perform a search index update with locking
1086 * @param int $maxLockTime The maximum time to keep the search index locked.
1087 * @param string $callback The function that will update the function.
1088 * @param DatabaseBase $dbw
1089 * @param array $results
1091 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1095 if ( $maxLockTime ) {
1096 $this->output( " --- Waiting for lock ---" );
1097 $this->lockSearchindex( $dbw );
1099 $this->output( "\n" );
1102 # Loop through the results and do a search update
1103 foreach ( $results as $row ) {
1104 # Allow reads to be processed
1105 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1106 $this->output( " --- Relocking ---" );
1107 $this->relockSearchindex( $dbw );
1109 $this->output( "\n" );
1111 call_user_func( $callback, $dbw, $row );
1114 # Unlock searchindex
1115 if ( $maxLockTime ) {
1116 $this->output( " --- Unlocking --" );
1117 $this->unlockSearchindex( $dbw );
1118 $this->output( "\n" );
1123 * Update the searchindex table for a given pageid
1124 * @param DatabaseBase $dbw A database write handle
1125 * @param int $pageId The page ID to update.
1126 * @return null|string
1128 public function updateSearchIndexForPage( $dbw, $pageId ) {
1129 // Get current revision
1130 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1133 $titleObj = $rev->getTitle();
1134 $title = $titleObj->getPrefixedDBkey();
1135 $this->output( "$title..." );
1136 # Update searchindex
1137 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1139 $this->output( "\n" );
1146 * Wrapper for posix_isatty()
1147 * We default as considering stdin a tty (for nice readline methods)
1148 * but treating stout as not a tty to avoid color codes
1150 * @param int $fd File descriptor
1153 public static function posix_isatty( $fd ) {
1154 if ( !function_exists( 'posix_isatty' ) ) {
1157 return posix_isatty( $fd );
1162 * Prompt the console for input
1163 * @param string $prompt What to begin the line with, like '> '
1164 * @return string Response
1166 public static function readconsole( $prompt = '> ' ) {
1167 static $isatty = null;
1168 if ( is_null( $isatty ) ) {
1169 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1172 if ( $isatty && function_exists( 'readline' ) ) {
1173 return readline( $prompt );
1176 $st = self
::readlineEmulation( $prompt );
1178 if ( feof( STDIN
) ) {
1181 $st = fgets( STDIN
, 1024 );
1184 if ( $st === false ) {
1187 $resp = trim( $st );
1194 * Emulate readline()
1195 * @param string $prompt What to begin the line with, like '> '
1198 private static function readlineEmulation( $prompt ) {
1199 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1200 if ( !wfIsWindows() && $bash ) {
1202 $encPrompt = wfEscapeShellArg( $prompt );
1203 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1204 $encCommand = wfEscapeShellArg( $command );
1205 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1207 if ( $retval == 0 ) {
1209 } elseif ( $retval == 127 ) {
1210 // Couldn't execute bash even though we thought we saw it.
1211 // Shell probably spit out an error message, sorry :(
1212 // Fall through to fgets()...
1219 // Fallback... we'll have no editing controls, EWWW
1220 if ( feof( STDIN
) ) {
1225 return fgets( STDIN
, 1024 );
1230 * Fake maintenance wrapper, mostly used for the web installer/updater
1232 class FakeMaintenance
extends Maintenance
{
1233 protected $mSelf = "FakeMaintenanceScript";
1235 public function execute() {
1241 * Class for scripts that perform database maintenance and want to log the
1242 * update in `updatelog` so we can later skip it
1244 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1245 public function __construct() {
1246 parent
::__construct();
1247 $this->addOption( 'force', 'Run the update even if it was completed already' );
1248 $this->setBatchSize( 200 );
1251 public function execute() {
1252 $db = $this->getDB( DB_MASTER
);
1253 $key = $this->getUpdateKey();
1255 if ( !$this->hasOption( 'force' )
1256 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
)
1258 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1263 if ( !$this->doDBUpdates() ) {
1267 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) ) {
1270 $this->output( $this->updatelogFailedMessage() . "\n" );
1277 * Message to show that the update was done already and was just skipped
1280 protected function updateSkippedMessage() {
1281 $key = $this->getUpdateKey();
1283 return "Update '{$key}' already logged as completed.";
1287 * Message to show the the update log was unable to log the completion of this update
1290 protected function updatelogFailedMessage() {
1291 $key = $this->getUpdateKey();
1293 return "Unable to log update '{$key}' as completed.";
1297 * Do the actual work. All child classes will need to implement this.
1298 * Return true to log the update as done or false (usually on failure).
1301 abstract protected function doDBUpdates();
1304 * Get the update key name to go in the update log table
1307 abstract protected function getUpdateKey();