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 // Bail on old versions of PHP, or if composer has not been run yet to install
24 // dependencies. Using dirname( __FILE__ ) here because __DIR__ is PHP5.3+.
25 // @codingStandardsIgnoreStart MediaWiki.Usage.DirUsage.FunctionFound
26 require_once dirname( __FILE__
) . '/../includes/PHPVersionCheck.php';
27 // @codingStandardsIgnoreEnd
28 wfEntryPointCheck( '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
41 use MediaWiki\Logger\LoggerFactory
;
44 * Abstract maintenance class for quickly writing and churning out
45 * maintenance scripts with minimal effort. All that _must_ be defined
46 * is the execute() method. See docs/maintenance.txt for more info
47 * and a quick demo of how to use it.
49 * @author Chad Horohoe <chad@anyonecanedit.org>
51 * @ingroup Maintenance
53 abstract class Maintenance
{
55 * Constants for DB access type
56 * @see Maintenance::getDbType()
62 // Const for getStdin()
63 const STDIN_ALL
= 'all';
65 // This is the desired params
66 protected $mParams = array();
68 // Array of mapping short parameters to long ones
69 protected $mShortParamsMap = array();
71 // Array of desired args
72 protected $mArgList = array();
74 // This is the list of options that were actually passed
75 protected $mOptions = array();
77 // This is the list of arguments that were actually passed
78 protected $mArgs = array();
80 // Name of the script currently running
83 // Special vars for params that are always used
84 protected $mQuiet = false;
85 protected $mDbUser, $mDbPass;
87 // A description of the script, children should change this
88 protected $mDescription = '';
90 // Have we already loaded our user input?
91 protected $mInputLoaded = false;
94 * Batch size. If a script supports this, they should set
95 * a default with setBatchSize()
99 protected $mBatchSize = null;
101 // Generic options added by addDefaultParams()
102 private $mGenericParameters = array();
103 // Generic options which might or not be supported by the script
104 private $mDependantParameters = array();
107 * Used by getDB() / setDB()
113 * Used when creating separate schema files.
119 * Accessible via getConfig()
126 * Used to read the options in the order
127 * they were passed. Useful for option
128 * chaining. (Ex. dumpBackup.php)
130 * This is an array of arrays where
131 * 0 => the option and 1 => parameter value
135 public $orderedOptions = array();
138 * Default constructor. Children should call this *first* if implementing
139 * their own constructors
141 public function __construct() {
142 // Setup $IP, using MW_INSTALL_PATH if it exists
144 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
145 ?
getenv( 'MW_INSTALL_PATH' )
146 : realpath( __DIR__
. '/..' );
148 $this->addDefaultParams();
149 register_shutdown_function( array( $this, 'outputChanneled' ), false );
153 * Should we execute the maintenance script, or just allow it to be included
154 * as a standalone class? It checks that the call stack only includes this
155 * function and "requires" (meaning was called from the file scope)
159 public static function shouldExecute() {
160 global $wgCommandLineMode;
162 if ( !function_exists( 'debug_backtrace' ) ) {
163 // If someone has a better idea...
164 return $wgCommandLineMode;
167 $bt = debug_backtrace();
168 $count = count( $bt );
170 return false; // sanity
172 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
173 return false; // last call should be to this function
175 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
176 for ( $i = 1; $i < $count; $i++
) {
177 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
178 return false; // previous calls should all be "requires"
186 * Do the actual work. All child classes will need to implement this
188 abstract public function execute();
191 * Add a parameter to the script. Will be displayed on --help
192 * with the associated description
194 * @param string $name The name of the param (help, version, etc)
195 * @param string $description The description of the param to show on --help
196 * @param bool $required Is the param required?
197 * @param bool $withArg Is an argument required with this option?
198 * @param string $shortName Character to use as short name
199 * @param bool $multiOccurrence Can this option be passed multiple times?
201 protected function addOption( $name, $description, $required = false,
202 $withArg = false, $shortName = false, $multiOccurrence = false
204 $this->mParams
[$name] = array(
205 'desc' => $description,
206 'require' => $required,
207 'withArg' => $withArg,
208 'shortName' => $shortName,
209 'multiOccurrence' => $multiOccurrence
212 if ( $shortName !== false ) {
213 $this->mShortParamsMap
[$shortName] = $name;
218 * Checks to see if a particular param exists.
219 * @param string $name The name of the param
222 protected function hasOption( $name ) {
223 return isset( $this->mOptions
[$name] );
227 * Get an option, or return the default.
229 * If the option was added to support multiple occurrences,
230 * this will return an array.
232 * @param string $name The name of the param
233 * @param mixed $default Anything you want, default null
236 protected function getOption( $name, $default = null ) {
237 if ( $this->hasOption( $name ) ) {
238 return $this->mOptions
[$name];
240 // Set it so we don't have to provide the default again
241 $this->mOptions
[$name] = $default;
243 return $this->mOptions
[$name];
248 * Add some args that are needed
249 * @param string $arg Name of the arg, like 'start'
250 * @param string $description Short description of the arg
251 * @param bool $required Is this required?
253 protected function addArg( $arg, $description, $required = true ) {
254 $this->mArgList
[] = array(
256 'desc' => $description,
257 'require' => $required
262 * Remove an option. Useful for removing options that won't be used in your script.
263 * @param string $name The option to remove.
265 protected function deleteOption( $name ) {
266 unset( $this->mParams
[$name] );
270 * Set the description text.
271 * @param string $text The text of the description
273 protected function addDescription( $text ) {
274 $this->mDescription
= $text;
278 * Does a given argument exist?
279 * @param int $argId The integer value (from zero) for the arg
282 protected function hasArg( $argId = 0 ) {
283 return isset( $this->mArgs
[$argId] );
288 * @param int $argId The integer value (from zero) for the arg
289 * @param mixed $default The default if it doesn't exist
292 protected function getArg( $argId = 0, $default = null ) {
293 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
297 * Set the batch size.
298 * @param int $s The number of operations to do in a batch
300 protected function setBatchSize( $s = 0 ) {
301 $this->mBatchSize
= $s;
303 // If we support $mBatchSize, show the option.
304 // Used to be in addDefaultParams, but in order for that to
305 // work, subclasses would have to call this function in the constructor
306 // before they called parent::__construct which is just weird
307 // (and really wasn't done).
308 if ( $this->mBatchSize
) {
309 $this->addOption( 'batch-size', 'Run this many operations ' .
310 'per batch, default: ' . $this->mBatchSize
, false, true );
311 if ( isset( $this->mParams
['batch-size'] ) ) {
312 // This seems a little ugly...
313 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
319 * Get the script's name
322 public function getName() {
327 * Return input from stdin.
328 * @param int $len The number of bytes to read. If null, just return the handle.
329 * Maintenance::STDIN_ALL returns the full length
332 protected function getStdin( $len = null ) {
333 if ( $len == Maintenance
::STDIN_ALL
) {
334 return file_get_contents( 'php://stdin' );
336 $f = fopen( 'php://stdin', 'rt' );
340 $input = fgets( $f, $len );
343 return rtrim( $input );
349 public function isQuiet() {
350 return $this->mQuiet
;
354 * Throw some output to the user. Scripts can call this with no fears,
355 * as we handle all --quiet stuff here
356 * @param string $out The text to show to the user
357 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
359 protected function output( $out, $channel = null ) {
360 if ( $this->mQuiet
) {
363 if ( $channel === null ) {
364 $this->cleanupChanneled();
367 $out = preg_replace( '/\n\z/', '', $out );
368 $this->outputChanneled( $out, $channel );
373 * Throw an error to the user. Doesn't respect --quiet, so don't use
374 * this for non-error output
375 * @param string $err The error to display
376 * @param int $die If > 0, go ahead and die out using this int as the code
378 protected function error( $err, $die = 0 ) {
379 $this->outputChanneled( false );
380 if ( PHP_SAPI
== 'cli' ) {
381 fwrite( STDERR
, $err . "\n" );
385 $die = intval( $die );
391 private $atLineStart = true;
392 private $lastChannel = null;
395 * Clean up channeled output. Output a newline if necessary.
397 public function cleanupChanneled() {
398 if ( !$this->atLineStart
) {
400 $this->atLineStart
= true;
405 * Message outputter with channeled message support. Messages on the
406 * same channel are concatenated, but any intervening messages in another
407 * channel start a new line.
408 * @param string $msg The message without trailing newline
409 * @param string $channel Channel identifier or null for no
410 * channel. Channel comparison uses ===.
412 public function outputChanneled( $msg, $channel = null ) {
413 if ( $msg === false ) {
414 $this->cleanupChanneled();
419 // End the current line if necessary
420 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
426 $this->atLineStart
= false;
427 if ( $channel === null ) {
428 // For unchanneled messages, output trailing newline immediately
430 $this->atLineStart
= true;
432 $this->lastChannel
= $channel;
436 * Does the script need different DB access? By default, we give Maintenance
437 * scripts normal rights to the DB. Sometimes, a script needs admin rights
438 * access for a reason and sometimes they want no access. Subclasses should
439 * override and return one of the following values, as needed:
440 * Maintenance::DB_NONE - For no DB access at all
441 * Maintenance::DB_STD - For normal DB access, default
442 * Maintenance::DB_ADMIN - For admin DB access
445 public function getDbType() {
446 return Maintenance
::DB_STD
;
450 * Add the default parameters to the scripts
452 protected function addDefaultParams() {
454 # Generic (non script dependant) options:
456 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
457 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
458 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
459 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
460 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
463 'Set a specific memory limit for the script, '
464 . '"max" for no limit or "default" to avoid changing it'
466 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
467 "http://en.wikipedia.org. This is sometimes necessary because " .
468 "server name detection may fail in command line scripts.", false, true );
469 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
471 # Save generic options to display them separately in help
472 $this->mGenericParameters
= $this->mParams
;
474 # Script dependant options:
476 // If we support a DB, show the options
477 if ( $this->getDbType() > 0 ) {
478 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
479 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
482 # Save additional script dependant options to display
483 # Â them separately in help
484 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
491 public function getConfig() {
492 if ( $this->config
=== null ) {
493 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
496 return $this->config
;
501 * @param Config $config
503 public function setConfig( Config
$config ) {
504 $this->config
= $config;
508 * Run a child maintenance script. Pass all of the current arguments
510 * @param string $maintClass A name of a child maintenance class
511 * @param string $classFile Full path of where the child is
512 * @return Maintenance
514 public function runChild( $maintClass, $classFile = null ) {
515 // Make sure the class is loaded first
516 if ( !class_exists( $maintClass ) ) {
518 require_once $classFile;
520 if ( !class_exists( $maintClass ) ) {
521 $this->error( "Cannot spawn child: $maintClass" );
526 * @var $child Maintenance
528 $child = new $maintClass();
529 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
530 if ( !is_null( $this->mDb
) ) {
531 $child->setDB( $this->mDb
);
538 * Do some sanity checking and basic setup
540 public function setup() {
541 global $IP, $wgCommandLineMode, $wgRequestTime;
543 # Abort if called from a web server
544 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
545 $this->error( 'This script must be run from the command line', true );
548 if ( $IP === null ) {
549 $this->error( "\$IP not set, aborting!\n" .
550 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
553 # Make sure we can handle script parameters
554 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
555 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
558 // Send PHP warnings and errors to stderr instead of stdout.
559 // This aids in diagnosing problems, while keeping messages
560 // out of redirected output.
561 if ( ini_get( 'display_errors' ) ) {
562 ini_set( 'display_errors', 'stderr' );
565 $this->loadParamsAndArgs();
568 # Set the memory limit
569 # Note we need to set it again later in cache LocalSettings changed it
570 $this->adjustMemoryLimit();
572 # Set max execution time to 0 (no limit). PHP.net says that
573 # "When running PHP from the command line the default setting is 0."
574 # But sometimes this doesn't seem to be the case.
575 ini_set( 'max_execution_time', 0 );
577 $wgRequestTime = microtime( true );
579 # Define us as being in MediaWiki
580 define( 'MEDIAWIKI', true );
582 $wgCommandLineMode = true;
584 # Turn off output buffering if it's on
585 while ( ob_get_level() > 0 ) {
589 $this->validateParamsAndArgs();
593 * Normally we disable the memory_limit when running admin scripts.
594 * Some scripts may wish to actually set a limit, however, to avoid
595 * blowing up unexpectedly. We also support a --memory-limit option,
596 * to allow sysadmins to explicitly set one if they'd prefer to override
597 * defaults (or for people using Suhosin which yells at you for trying
598 * to disable the limits)
601 public function memoryLimit() {
602 $limit = $this->getOption( 'memory-limit', 'max' );
603 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
608 * Adjusts PHP's memory limit to better suit our needs, if needed.
610 protected function adjustMemoryLimit() {
611 $limit = $this->memoryLimit();
612 if ( $limit == 'max' ) {
613 $limit = -1; // no memory limit
615 if ( $limit != 'default' ) {
616 ini_set( 'memory_limit', $limit );
621 * Activate the profiler (assuming $wgProfiler is set)
623 protected function activateProfiler() {
624 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
626 $output = $this->getOption( 'profiler' );
631 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
632 $class = $wgProfiler['class'];
633 $profiler = new $class(
634 array( 'sampling' => 1, 'output' => array( $output ) )
636 +
array( 'threshold' => $wgProfileLimit )
638 $profiler->setTemplated( true );
639 Profiler
::replaceStubInstance( $profiler );
642 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
643 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
644 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
648 * Clear all params and arguments.
650 public function clearParamsAndArgs() {
651 $this->mOptions
= array();
652 $this->mArgs
= array();
653 $this->mInputLoaded
= false;
657 * Process command line arguments
658 * $mOptions becomes an array with keys set to the option names
659 * $mArgs becomes a zero-based array containing the non-option arguments
661 * @param string $self The name of the script, if any
662 * @param array $opts An array of options, in form of key=>value
663 * @param array $args An array of command line arguments
665 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
666 # If we were given opts or args, set those and return early
668 $this->mSelf
= $self;
669 $this->mInputLoaded
= true;
672 $this->mOptions
= $opts;
673 $this->mInputLoaded
= true;
676 $this->mArgs
= $args;
677 $this->mInputLoaded
= true;
680 # If we've already loaded input (either by user values or from $argv)
681 # skip on loading it again. The array_shift() will corrupt values if
682 # it's run again and again
683 if ( $this->mInputLoaded
) {
684 $this->loadSpecialVars();
690 $this->mSelf
= array_shift( $argv );
694 $this->orderedOptions
= array();
697 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
698 if ( $arg == '--' ) {
699 # End of options, remainder should be considered arguments
700 $arg = next( $argv );
701 while ( $arg !== false ) {
703 $arg = next( $argv );
706 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
708 $option = substr( $arg, 2 );
709 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
710 $param = next( $argv );
711 if ( $param === false ) {
712 $this->error( "\nERROR: $option parameter needs a value after it\n" );
713 $this->maybeHelp( true );
716 $this->setParam( $options, $option, $param );
718 $bits = explode( '=', $option, 2 );
719 if ( count( $bits ) > 1 ) {
726 $this->setParam( $options, $option, $param );
728 } elseif ( $arg == '-' ) {
729 # Lonely "-", often used to indicate stdin or stdout.
731 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
733 $argLength = strlen( $arg );
734 for ( $p = 1; $p < $argLength; $p++
) {
736 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
737 $option = $this->mShortParamsMap
[$option];
740 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
741 $param = next( $argv );
742 if ( $param === false ) {
743 $this->error( "\nERROR: $option parameter needs a value after it\n" );
744 $this->maybeHelp( true );
746 $this->setParam( $options, $option, $param );
748 $this->setParam( $options, $option, 1 );
756 $this->mOptions
= $options;
757 $this->mArgs
= $args;
758 $this->loadSpecialVars();
759 $this->mInputLoaded
= true;
763 * Helper function used solely by loadParamsAndArgs
764 * to prevent code duplication
766 * This sets the param in the options array based on
767 * whether or not it can be specified multiple times.
770 * @param array $options
771 * @param string $option
772 * @param mixed $value
774 private function setParam( &$options, $option, $value ) {
775 $this->orderedOptions
[] = array( $option, $value );
777 if ( isset( $this->mParams
[$option] ) ) {
778 $multi = $this->mParams
[$option]['multiOccurrence'];
779 $exists = array_key_exists( $option, $options );
780 if ( $multi && $exists ) {
781 $options[$option][] = $value;
782 } elseif ( $multi ) {
783 $options[$option] = array( $value );
784 } elseif ( !$exists ) {
785 $options[$option] = $value;
787 $this->error( "\nERROR: $option parameter given twice\n" );
788 $this->maybeHelp( true );
794 * Run some validation checks on the params, etc
796 protected function validateParamsAndArgs() {
798 # Check to make sure we've got all the required options
799 foreach ( $this->mParams
as $opt => $info ) {
800 if ( $info['require'] && !$this->hasOption( $opt ) ) {
801 $this->error( "Param $opt required!" );
806 foreach ( $this->mArgList
as $k => $info ) {
807 if ( $info['require'] && !$this->hasArg( $k ) ) {
808 $this->error( 'Argument <' . $info['name'] . '> required!' );
814 $this->maybeHelp( true );
819 * Handle the special variables that are global to all scripts
821 protected function loadSpecialVars() {
822 if ( $this->hasOption( 'dbuser' ) ) {
823 $this->mDbUser
= $this->getOption( 'dbuser' );
825 if ( $this->hasOption( 'dbpass' ) ) {
826 $this->mDbPass
= $this->getOption( 'dbpass' );
828 if ( $this->hasOption( 'quiet' ) ) {
829 $this->mQuiet
= true;
831 if ( $this->hasOption( 'batch-size' ) ) {
832 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
837 * Maybe show the help.
838 * @param bool $force Whether to force the help to show, default false
840 protected function maybeHelp( $force = false ) {
841 if ( !$force && !$this->hasOption( 'help' ) ) {
845 $screenWidth = 80; // TODO: Calculate this!
847 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
849 ksort( $this->mParams
);
850 $this->mQuiet
= false;
853 if ( $this->mDescription
) {
854 $this->output( "\n" . $this->mDescription
. "\n" );
856 $output = "\nUsage: php " . basename( $this->mSelf
);
858 // ... append parameters ...
859 if ( $this->mParams
) {
860 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
863 // ... and append arguments.
864 if ( $this->mArgList
) {
866 foreach ( $this->mArgList
as $k => $arg ) {
867 if ( $arg['require'] ) {
868 $output .= '<' . $arg['name'] . '>';
870 $output .= '[' . $arg['name'] . ']';
872 if ( $k < count( $this->mArgList
) - 1 ) {
877 $this->output( "$output\n\n" );
879 # TODO abstract some repetitive code below
881 // Generic parameters
882 $this->output( "Generic maintenance parameters:\n" );
883 foreach ( $this->mGenericParameters
as $par => $info ) {
884 if ( $info['shortName'] !== false ) {
885 $par .= " (-{$info['shortName']})";
888 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
889 "\n$tab$tab" ) . "\n"
892 $this->output( "\n" );
894 $scriptDependantParams = $this->mDependantParameters
;
895 if ( count( $scriptDependantParams ) > 0 ) {
896 $this->output( "Script dependant parameters:\n" );
897 // Parameters description
898 foreach ( $scriptDependantParams as $par => $info ) {
899 if ( $info['shortName'] !== false ) {
900 $par .= " (-{$info['shortName']})";
903 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
904 "\n$tab$tab" ) . "\n"
907 $this->output( "\n" );
910 // Script specific parameters not defined on construction by
911 // Maintenance::addDefaultParams()
912 $scriptSpecificParams = array_diff_key(
913 # all script parameters:
915 # remove the Maintenance default parameters:
916 $this->mGenericParameters
,
917 $this->mDependantParameters
919 if ( count( $scriptSpecificParams ) > 0 ) {
920 $this->output( "Script specific parameters:\n" );
921 // Parameters description
922 foreach ( $scriptSpecificParams as $par => $info ) {
923 if ( $info['shortName'] !== false ) {
924 $par .= " (-{$info['shortName']})";
927 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
928 "\n$tab$tab" ) . "\n"
931 $this->output( "\n" );
935 if ( count( $this->mArgList
) > 0 ) {
936 $this->output( "Arguments:\n" );
937 // Arguments description
938 foreach ( $this->mArgList
as $info ) {
939 $openChar = $info['require'] ?
'<' : '[';
940 $closeChar = $info['require'] ?
'>' : ']';
942 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
943 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
946 $this->output( "\n" );
953 * Handle some last-minute setup here.
955 public function finalSetup() {
956 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
957 global $wgDBadminuser, $wgDBadminpassword;
958 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
960 # Turn off output buffering again, it might have been turned on in the settings files
961 if ( ob_get_level() ) {
965 $wgCommandLineMode = true;
968 if ( $this->hasOption( 'server' ) ) {
969 $wgServer = $this->getOption( 'server', $wgServer );
972 # If these were passed, use them
973 if ( $this->mDbUser
) {
974 $wgDBadminuser = $this->mDbUser
;
976 if ( $this->mDbPass
) {
977 $wgDBadminpassword = $this->mDbPass
;
980 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
981 $wgDBuser = $wgDBadminuser;
982 $wgDBpassword = $wgDBadminpassword;
984 if ( $wgDBservers ) {
986 * @var $wgDBservers array
988 foreach ( $wgDBservers as $i => $server ) {
989 $wgDBservers[$i]['user'] = $wgDBuser;
990 $wgDBservers[$i]['password'] = $wgDBpassword;
993 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
994 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
995 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
997 LBFactory
::destroyInstance();
1000 // Per-script profiling; useful for debugging
1001 $this->activateProfiler();
1003 $this->afterFinalSetup();
1005 $wgShowSQLErrors = true;
1007 MediaWiki\
suppressWarnings();
1008 set_time_limit( 0 );
1009 MediaWiki\restoreWarnings
();
1011 $this->adjustMemoryLimit();
1015 * Execute a callback function at the end of initialisation
1017 protected function afterFinalSetup() {
1018 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1019 call_user_func( MW_CMDLINE_CALLBACK
);
1024 * Potentially debug globals. Originally a feature only
1027 public function globals() {
1028 if ( $this->hasOption( 'globals' ) ) {
1029 print_r( $GLOBALS );
1034 * Generic setup for most installs. Returns the location of LocalSettings
1037 public function loadSettings() {
1038 global $wgCommandLineMode, $IP;
1040 if ( isset( $this->mOptions
['conf'] ) ) {
1041 $settingsFile = $this->mOptions
['conf'];
1042 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1043 $settingsFile = MW_CONFIG_FILE
;
1045 $settingsFile = "$IP/LocalSettings.php";
1047 if ( isset( $this->mOptions
['wiki'] ) ) {
1048 $bits = explode( '-', $this->mOptions
['wiki'] );
1049 if ( count( $bits ) == 1 ) {
1052 define( 'MW_DB', $bits[0] );
1053 define( 'MW_PREFIX', $bits[1] );
1056 if ( !is_readable( $settingsFile ) ) {
1057 $this->error( "A copy of your installation's LocalSettings.php\n" .
1058 "must exist and be readable in the source directory.\n" .
1059 "Use --conf to specify it.", true );
1061 $wgCommandLineMode = true;
1063 return $settingsFile;
1067 * Support function for cleaning up redundant text records
1068 * @param bool $delete Whether or not to actually delete the records
1069 * @author Rob Church <robchur@gmail.com>
1071 public function purgeRedundantText( $delete = true ) {
1072 # Data should come off the master, wrapped in a transaction
1073 $dbw = $this->getDB( DB_MASTER
);
1074 $dbw->begin( __METHOD__
);
1076 # Get "active" text records from the revisions table
1077 $this->output( 'Searching for active text records in revisions table...' );
1078 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
1079 foreach ( $res as $row ) {
1080 $cur[] = $row->rev_text_id
;
1082 $this->output( "done.\n" );
1084 # Get "active" text records from the archive table
1085 $this->output( 'Searching for active text records in archive table...' );
1086 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
1087 foreach ( $res as $row ) {
1088 # old pre-MW 1.5 records can have null ar_text_id's.
1089 if ( $row->ar_text_id
!== null ) {
1090 $cur[] = $row->ar_text_id
;
1093 $this->output( "done.\n" );
1095 # Get the IDs of all text records not in these sets
1096 $this->output( 'Searching for inactive text records...' );
1097 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1098 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__
, array( 'DISTINCT' ) );
1100 foreach ( $res as $row ) {
1101 $old[] = $row->old_id
;
1103 $this->output( "done.\n" );
1105 # Inform the user of what we're going to do
1106 $count = count( $old );
1107 $this->output( "$count inactive items found.\n" );
1109 # Delete as appropriate
1110 if ( $delete && $count ) {
1111 $this->output( 'Deleting...' );
1112 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__
);
1113 $this->output( "done.\n" );
1117 $dbw->commit( __METHOD__
);
1121 * Get the maintenance directory.
1124 protected function getDir() {
1129 * Returns a database to be used by current maintenance script. It can be set by setDB().
1130 * If not set, wfGetDB() will be used.
1131 * This function has the same parameters as wfGetDB()
1133 * @return DatabaseBase
1135 protected function getDB( $db, $groups = array(), $wiki = false ) {
1136 if ( is_null( $this->mDb
) ) {
1137 return wfGetDB( $db, $groups, $wiki );
1144 * Sets database object to be returned by getDB().
1146 * @param DatabaseBase $db Database object to be used
1148 public function setDB( $db ) {
1153 * Lock the search index
1154 * @param DatabaseBase &$db
1156 private function lockSearchindex( $db ) {
1157 $write = array( 'searchindex' );
1167 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1172 * @param DatabaseBase &$db
1174 private function unlockSearchindex( $db ) {
1175 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1179 * Unlock and lock again
1180 * Since the lock is low-priority, queued reads will be able to complete
1181 * @param DatabaseBase &$db
1183 private function relockSearchindex( $db ) {
1184 $this->unlockSearchindex( $db );
1185 $this->lockSearchindex( $db );
1189 * Perform a search index update with locking
1190 * @param int $maxLockTime The maximum time to keep the search index locked.
1191 * @param string $callback The function that will update the function.
1192 * @param DatabaseBase $dbw
1193 * @param array $results
1195 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1199 if ( $maxLockTime ) {
1200 $this->output( " --- Waiting for lock ---" );
1201 $this->lockSearchindex( $dbw );
1203 $this->output( "\n" );
1206 # Loop through the results and do a search update
1207 foreach ( $results as $row ) {
1208 # Allow reads to be processed
1209 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1210 $this->output( " --- Relocking ---" );
1211 $this->relockSearchindex( $dbw );
1213 $this->output( "\n" );
1215 call_user_func( $callback, $dbw, $row );
1218 # Unlock searchindex
1219 if ( $maxLockTime ) {
1220 $this->output( " --- Unlocking --" );
1221 $this->unlockSearchindex( $dbw );
1222 $this->output( "\n" );
1227 * Update the searchindex table for a given pageid
1228 * @param DatabaseBase $dbw A database write handle
1229 * @param int $pageId The page ID to update.
1230 * @return null|string
1232 public function updateSearchIndexForPage( $dbw, $pageId ) {
1233 // Get current revision
1234 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1237 $titleObj = $rev->getTitle();
1238 $title = $titleObj->getPrefixedDBkey();
1239 $this->output( "$title..." );
1240 # Update searchindex
1241 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1243 $this->output( "\n" );
1250 * Wrapper for posix_isatty()
1251 * We default as considering stdin a tty (for nice readline methods)
1252 * but treating stout as not a tty to avoid color codes
1254 * @param mixed $fd File descriptor
1257 public static function posix_isatty( $fd ) {
1258 if ( !function_exists( 'posix_isatty' ) ) {
1261 return posix_isatty( $fd );
1266 * Prompt the console for input
1267 * @param string $prompt What to begin the line with, like '> '
1268 * @return string Response
1270 public static function readconsole( $prompt = '> ' ) {
1271 static $isatty = null;
1272 if ( is_null( $isatty ) ) {
1273 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1276 if ( $isatty && function_exists( 'readline' ) ) {
1277 $resp = readline( $prompt );
1278 if ( $resp === null ) {
1279 // Workaround for https://github.com/facebook/hhvm/issues/4776
1286 $st = self
::readlineEmulation( $prompt );
1288 if ( feof( STDIN
) ) {
1291 $st = fgets( STDIN
, 1024 );
1294 if ( $st === false ) {
1297 $resp = trim( $st );
1304 * Emulate readline()
1305 * @param string $prompt What to begin the line with, like '> '
1308 private static function readlineEmulation( $prompt ) {
1309 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1310 if ( !wfIsWindows() && $bash ) {
1312 $encPrompt = wfEscapeShellArg( $prompt );
1313 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1314 $encCommand = wfEscapeShellArg( $command );
1315 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1317 if ( $retval == 0 ) {
1319 } elseif ( $retval == 127 ) {
1320 // Couldn't execute bash even though we thought we saw it.
1321 // Shell probably spit out an error message, sorry :(
1322 // Fall through to fgets()...
1329 // Fallback... we'll have no editing controls, EWWW
1330 if ( feof( STDIN
) ) {
1335 return fgets( STDIN
, 1024 );
1340 * Fake maintenance wrapper, mostly used for the web installer/updater
1342 class FakeMaintenance
extends Maintenance
{
1343 protected $mSelf = "FakeMaintenanceScript";
1345 public function execute() {
1351 * Class for scripts that perform database maintenance and want to log the
1352 * update in `updatelog` so we can later skip it
1354 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1355 public function __construct() {
1356 parent
::__construct();
1357 $this->addOption( 'force', 'Run the update even if it was completed already' );
1358 $this->setBatchSize( 200 );
1361 public function execute() {
1362 $db = $this->getDB( DB_MASTER
);
1363 $key = $this->getUpdateKey();
1365 if ( !$this->hasOption( 'force' )
1366 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
)
1368 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1373 if ( !$this->doDBUpdates() ) {
1377 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) ) {
1380 $this->output( $this->updatelogFailedMessage() . "\n" );
1387 * Message to show that the update was done already and was just skipped
1390 protected function updateSkippedMessage() {
1391 $key = $this->getUpdateKey();
1393 return "Update '{$key}' already logged as completed.";
1397 * Message to show that the update log was unable to log the completion of this update
1400 protected function updatelogFailedMessage() {
1401 $key = $this->getUpdateKey();
1403 return "Unable to log update '{$key}' as completed.";
1407 * Do the actual work. All child classes will need to implement this.
1408 * Return true to log the update as done or false (usually on failure).
1411 abstract protected function doDBUpdates();
1414 * Get the update key name to go in the update log table
1417 abstract protected function getUpdateKey();