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 they were passed.
127 * Useful for option chaining (Ex. dumpBackup.php). It will
128 * be an empty array if the options are passed in through
129 * loadParamsAndArgs( $self, $opts, $args ).
131 * This is an array of arrays where
132 * 0 => the option and 1 => parameter value.
136 public $orderedOptions = array();
139 * Default constructor. Children should call this *first* if implementing
140 * their own constructors
142 public function __construct() {
143 // Setup $IP, using MW_INSTALL_PATH if it exists
145 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
146 ?
getenv( 'MW_INSTALL_PATH' )
147 : realpath( __DIR__
. '/..' );
149 $this->addDefaultParams();
150 register_shutdown_function( array( $this, 'outputChanneled' ), false );
154 * Should we execute the maintenance script, or just allow it to be included
155 * as a standalone class? It checks that the call stack only includes this
156 * function and "requires" (meaning was called from the file scope)
160 public static function shouldExecute() {
161 global $wgCommandLineMode;
163 if ( !function_exists( 'debug_backtrace' ) ) {
164 // If someone has a better idea...
165 return $wgCommandLineMode;
168 $bt = debug_backtrace();
169 $count = count( $bt );
171 return false; // sanity
173 if ( $bt[0]['class'] !== 'Maintenance' ||
$bt[0]['function'] !== 'shouldExecute' ) {
174 return false; // last call should be to this function
176 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
177 for ( $i = 1; $i < $count; $i++
) {
178 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
179 return false; // previous calls should all be "requires"
187 * Do the actual work. All child classes will need to implement this
189 abstract public function execute();
192 * Add a parameter to the script. Will be displayed on --help
193 * with the associated description
195 * @param string $name The name of the param (help, version, etc)
196 * @param string $description The description of the param to show on --help
197 * @param bool $required Is the param required?
198 * @param bool $withArg Is an argument required with this option?
199 * @param string $shortName Character to use as short name
200 * @param bool $multiOccurrence Can this option be passed multiple times?
202 protected function addOption( $name, $description, $required = false,
203 $withArg = false, $shortName = false, $multiOccurrence = false
205 $this->mParams
[$name] = array(
206 'desc' => $description,
207 'require' => $required,
208 'withArg' => $withArg,
209 'shortName' => $shortName,
210 'multiOccurrence' => $multiOccurrence
213 if ( $shortName !== false ) {
214 $this->mShortParamsMap
[$shortName] = $name;
219 * Checks to see if a particular param exists.
220 * @param string $name The name of the param
223 protected function hasOption( $name ) {
224 return isset( $this->mOptions
[$name] );
228 * Get an option, or return the default.
230 * If the option was added to support multiple occurrences,
231 * this will return an array.
233 * @param string $name The name of the param
234 * @param mixed $default Anything you want, default null
237 protected function getOption( $name, $default = null ) {
238 if ( $this->hasOption( $name ) ) {
239 return $this->mOptions
[$name];
241 // Set it so we don't have to provide the default again
242 $this->mOptions
[$name] = $default;
244 return $this->mOptions
[$name];
249 * Add some args that are needed
250 * @param string $arg Name of the arg, like 'start'
251 * @param string $description Short description of the arg
252 * @param bool $required Is this required?
254 protected function addArg( $arg, $description, $required = true ) {
255 $this->mArgList
[] = array(
257 'desc' => $description,
258 'require' => $required
263 * Remove an option. Useful for removing options that won't be used in your script.
264 * @param string $name The option to remove.
266 protected function deleteOption( $name ) {
267 unset( $this->mParams
[$name] );
271 * Set the description text.
272 * @param string $text The text of the description
274 protected function addDescription( $text ) {
275 $this->mDescription
= $text;
279 * Does a given argument exist?
280 * @param int $argId The integer value (from zero) for the arg
283 protected function hasArg( $argId = 0 ) {
284 return isset( $this->mArgs
[$argId] );
289 * @param int $argId The integer value (from zero) for the arg
290 * @param mixed $default The default if it doesn't exist
293 protected function getArg( $argId = 0, $default = null ) {
294 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
298 * Set the batch size.
299 * @param int $s The number of operations to do in a batch
301 protected function setBatchSize( $s = 0 ) {
302 $this->mBatchSize
= $s;
304 // If we support $mBatchSize, show the option.
305 // Used to be in addDefaultParams, but in order for that to
306 // work, subclasses would have to call this function in the constructor
307 // before they called parent::__construct which is just weird
308 // (and really wasn't done).
309 if ( $this->mBatchSize
) {
310 $this->addOption( 'batch-size', 'Run this many operations ' .
311 'per batch, default: ' . $this->mBatchSize
, false, true );
312 if ( isset( $this->mParams
['batch-size'] ) ) {
313 // This seems a little ugly...
314 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
320 * Get the script's name
323 public function getName() {
328 * Return input from stdin.
329 * @param int $len The number of bytes to read. If null, just return the handle.
330 * Maintenance::STDIN_ALL returns the full length
333 protected function getStdin( $len = null ) {
334 if ( $len == Maintenance
::STDIN_ALL
) {
335 return file_get_contents( 'php://stdin' );
337 $f = fopen( 'php://stdin', 'rt' );
341 $input = fgets( $f, $len );
344 return rtrim( $input );
350 public function isQuiet() {
351 return $this->mQuiet
;
355 * Throw some output to the user. Scripts can call this with no fears,
356 * as we handle all --quiet stuff here
357 * @param string $out The text to show to the user
358 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
360 protected function output( $out, $channel = null ) {
361 if ( $this->mQuiet
) {
364 if ( $channel === null ) {
365 $this->cleanupChanneled();
368 $out = preg_replace( '/\n\z/', '', $out );
369 $this->outputChanneled( $out, $channel );
374 * Throw an error to the user. Doesn't respect --quiet, so don't use
375 * this for non-error output
376 * @param string $err The error to display
377 * @param int $die If > 0, go ahead and die out using this int as the code
379 protected function error( $err, $die = 0 ) {
380 $this->outputChanneled( false );
381 if ( PHP_SAPI
== 'cli' ) {
382 fwrite( STDERR
, $err . "\n" );
386 $die = intval( $die );
392 private $atLineStart = true;
393 private $lastChannel = null;
396 * Clean up channeled output. Output a newline if necessary.
398 public function cleanupChanneled() {
399 if ( !$this->atLineStart
) {
401 $this->atLineStart
= true;
406 * Message outputter with channeled message support. Messages on the
407 * same channel are concatenated, but any intervening messages in another
408 * channel start a new line.
409 * @param string $msg The message without trailing newline
410 * @param string $channel Channel identifier or null for no
411 * channel. Channel comparison uses ===.
413 public function outputChanneled( $msg, $channel = null ) {
414 if ( $msg === false ) {
415 $this->cleanupChanneled();
420 // End the current line if necessary
421 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
427 $this->atLineStart
= false;
428 if ( $channel === null ) {
429 // For unchanneled messages, output trailing newline immediately
431 $this->atLineStart
= true;
433 $this->lastChannel
= $channel;
437 * Does the script need different DB access? By default, we give Maintenance
438 * scripts normal rights to the DB. Sometimes, a script needs admin rights
439 * access for a reason and sometimes they want no access. Subclasses should
440 * override and return one of the following values, as needed:
441 * Maintenance::DB_NONE - For no DB access at all
442 * Maintenance::DB_STD - For normal DB access, default
443 * Maintenance::DB_ADMIN - For admin DB access
446 public function getDbType() {
447 return Maintenance
::DB_STD
;
451 * Add the default parameters to the scripts
453 protected function addDefaultParams() {
455 # Generic (non script dependant) options:
457 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
458 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
459 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
460 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
461 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
464 'Set a specific memory limit for the script, '
465 . '"max" for no limit or "default" to avoid changing it'
467 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
468 "http://en.wikipedia.org. This is sometimes necessary because " .
469 "server name detection may fail in command line scripts.", false, true );
470 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
472 # Save generic options to display them separately in help
473 $this->mGenericParameters
= $this->mParams
;
475 # Script dependant options:
477 // If we support a DB, show the options
478 if ( $this->getDbType() > 0 ) {
479 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
480 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
483 # Save additional script dependant options to display
484 # Â them separately in help
485 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
492 public function getConfig() {
493 if ( $this->config
=== null ) {
494 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
497 return $this->config
;
502 * @param Config $config
504 public function setConfig( Config
$config ) {
505 $this->config
= $config;
509 * Run a child maintenance script. Pass all of the current arguments
511 * @param string $maintClass A name of a child maintenance class
512 * @param string $classFile Full path of where the child is
513 * @return Maintenance
515 public function runChild( $maintClass, $classFile = null ) {
516 // Make sure the class is loaded first
517 if ( !class_exists( $maintClass ) ) {
519 require_once $classFile;
521 if ( !class_exists( $maintClass ) ) {
522 $this->error( "Cannot spawn child: $maintClass" );
527 * @var $child Maintenance
529 $child = new $maintClass();
530 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
531 if ( !is_null( $this->mDb
) ) {
532 $child->setDB( $this->mDb
);
539 * Do some sanity checking and basic setup
541 public function setup() {
542 global $IP, $wgCommandLineMode, $wgRequestTime;
544 # Abort if called from a web server
545 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
546 $this->error( 'This script must be run from the command line', true );
549 if ( $IP === null ) {
550 $this->error( "\$IP not set, aborting!\n" .
551 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
554 # Make sure we can handle script parameters
555 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
556 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
559 // Send PHP warnings and errors to stderr instead of stdout.
560 // This aids in diagnosing problems, while keeping messages
561 // out of redirected output.
562 if ( ini_get( 'display_errors' ) ) {
563 ini_set( 'display_errors', 'stderr' );
566 $this->loadParamsAndArgs();
569 # Set the memory limit
570 # Note we need to set it again later in cache LocalSettings changed it
571 $this->adjustMemoryLimit();
573 # Set max execution time to 0 (no limit). PHP.net says that
574 # "When running PHP from the command line the default setting is 0."
575 # But sometimes this doesn't seem to be the case.
576 ini_set( 'max_execution_time', 0 );
578 $wgRequestTime = microtime( true );
580 # Define us as being in MediaWiki
581 define( 'MEDIAWIKI', true );
583 $wgCommandLineMode = true;
585 # Turn off output buffering if it's on
586 while ( ob_get_level() > 0 ) {
590 $this->validateParamsAndArgs();
594 * Normally we disable the memory_limit when running admin scripts.
595 * Some scripts may wish to actually set a limit, however, to avoid
596 * blowing up unexpectedly. We also support a --memory-limit option,
597 * to allow sysadmins to explicitly set one if they'd prefer to override
598 * defaults (or for people using Suhosin which yells at you for trying
599 * to disable the limits)
602 public function memoryLimit() {
603 $limit = $this->getOption( 'memory-limit', 'max' );
604 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
609 * Adjusts PHP's memory limit to better suit our needs, if needed.
611 protected function adjustMemoryLimit() {
612 $limit = $this->memoryLimit();
613 if ( $limit == 'max' ) {
614 $limit = -1; // no memory limit
616 if ( $limit != 'default' ) {
617 ini_set( 'memory_limit', $limit );
622 * Activate the profiler (assuming $wgProfiler is set)
624 protected function activateProfiler() {
625 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
627 $output = $this->getOption( 'profiler' );
632 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
633 $class = $wgProfiler['class'];
634 $profiler = new $class(
635 array( 'sampling' => 1, 'output' => array( $output ) )
637 +
array( 'threshold' => $wgProfileLimit )
639 $profiler->setTemplated( true );
640 Profiler
::replaceStubInstance( $profiler );
643 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
644 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
645 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
649 * Clear all params and arguments.
651 public function clearParamsAndArgs() {
652 $this->mOptions
= array();
653 $this->mArgs
= array();
654 $this->mInputLoaded
= false;
658 * Load params and arguments from a given array
659 * of command-line arguments
664 public function loadWithArgv( $argv ) {
667 $this->orderedOptions
= array();
670 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
671 if ( $arg == '--' ) {
672 # End of options, remainder should be considered arguments
673 $arg = next( $argv );
674 while ( $arg !== false ) {
676 $arg = next( $argv );
679 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
681 $option = substr( $arg, 2 );
682 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
683 $param = next( $argv );
684 if ( $param === false ) {
685 $this->error( "\nERROR: $option parameter needs a value after it\n" );
686 $this->maybeHelp( true );
689 $this->setParam( $options, $option, $param );
691 $bits = explode( '=', $option, 2 );
692 if ( count( $bits ) > 1 ) {
699 $this->setParam( $options, $option, $param );
701 } elseif ( $arg == '-' ) {
702 # Lonely "-", often used to indicate stdin or stdout.
704 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
706 $argLength = strlen( $arg );
707 for ( $p = 1; $p < $argLength; $p++
) {
709 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
710 $option = $this->mShortParamsMap
[$option];
713 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
714 $param = next( $argv );
715 if ( $param === false ) {
716 $this->error( "\nERROR: $option parameter needs a value after it\n" );
717 $this->maybeHelp( true );
719 $this->setParam( $options, $option, $param );
721 $this->setParam( $options, $option, 1 );
729 $this->mOptions
= $options;
730 $this->mArgs
= $args;
731 $this->loadSpecialVars();
732 $this->mInputLoaded
= true;
736 * Helper function used solely by loadParamsAndArgs
737 * to prevent code duplication
739 * This sets the param in the options array based on
740 * whether or not it can be specified multiple times.
743 * @param array $options
744 * @param string $option
745 * @param mixed $value
747 private function setParam( &$options, $option, $value ) {
748 $this->orderedOptions
[] = array( $option, $value );
750 if ( isset( $this->mParams
[$option] ) ) {
751 $multi = $this->mParams
[$option]['multiOccurrence'];
752 $exists = array_key_exists( $option, $options );
753 if ( $multi && $exists ) {
754 $options[$option][] = $value;
755 } elseif ( $multi ) {
756 $options[$option] = array( $value );
757 } elseif ( !$exists ) {
758 $options[$option] = $value;
760 $this->error( "\nERROR: $option parameter given twice\n" );
761 $this->maybeHelp( true );
767 * Process command line arguments
768 * $mOptions becomes an array with keys set to the option names
769 * $mArgs becomes a zero-based array containing the non-option arguments
771 * @param string $self The name of the script, if any
772 * @param array $opts An array of options, in form of key=>value
773 * @param array $args An array of command line arguments
775 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
776 # If we were given opts or args, set those and return early
778 $this->mSelf
= $self;
779 $this->mInputLoaded
= true;
782 $this->mOptions
= $opts;
783 $this->mInputLoaded
= true;
786 $this->mArgs
= $args;
787 $this->mInputLoaded
= true;
790 # If we've already loaded input (either by user values or from $argv)
791 # skip on loading it again. The array_shift() will corrupt values if
792 # it's run again and again
793 if ( $this->mInputLoaded
) {
794 $this->loadSpecialVars();
800 $this->mSelf
= $argv[0];
801 $this->loadWithArgv( array_slice( $argv, 1 ) );
805 * Run some validation checks on the params, etc
807 protected function validateParamsAndArgs() {
809 # Check to make sure we've got all the required options
810 foreach ( $this->mParams
as $opt => $info ) {
811 if ( $info['require'] && !$this->hasOption( $opt ) ) {
812 $this->error( "Param $opt required!" );
817 foreach ( $this->mArgList
as $k => $info ) {
818 if ( $info['require'] && !$this->hasArg( $k ) ) {
819 $this->error( 'Argument <' . $info['name'] . '> required!' );
825 $this->maybeHelp( true );
830 * Handle the special variables that are global to all scripts
832 protected function loadSpecialVars() {
833 if ( $this->hasOption( 'dbuser' ) ) {
834 $this->mDbUser
= $this->getOption( 'dbuser' );
836 if ( $this->hasOption( 'dbpass' ) ) {
837 $this->mDbPass
= $this->getOption( 'dbpass' );
839 if ( $this->hasOption( 'quiet' ) ) {
840 $this->mQuiet
= true;
842 if ( $this->hasOption( 'batch-size' ) ) {
843 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
848 * Maybe show the help.
849 * @param bool $force Whether to force the help to show, default false
851 protected function maybeHelp( $force = false ) {
852 if ( !$force && !$this->hasOption( 'help' ) ) {
856 $screenWidth = 80; // TODO: Calculate this!
858 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
860 ksort( $this->mParams
);
861 $this->mQuiet
= false;
864 if ( $this->mDescription
) {
865 $this->output( "\n" . $this->mDescription
. "\n" );
867 $output = "\nUsage: php " . basename( $this->mSelf
);
869 // ... append parameters ...
870 if ( $this->mParams
) {
871 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
874 // ... and append arguments.
875 if ( $this->mArgList
) {
877 foreach ( $this->mArgList
as $k => $arg ) {
878 if ( $arg['require'] ) {
879 $output .= '<' . $arg['name'] . '>';
881 $output .= '[' . $arg['name'] . ']';
883 if ( $k < count( $this->mArgList
) - 1 ) {
888 $this->output( "$output\n\n" );
890 # TODO abstract some repetitive code below
892 // Generic parameters
893 $this->output( "Generic maintenance parameters:\n" );
894 foreach ( $this->mGenericParameters
as $par => $info ) {
895 if ( $info['shortName'] !== false ) {
896 $par .= " (-{$info['shortName']})";
899 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
900 "\n$tab$tab" ) . "\n"
903 $this->output( "\n" );
905 $scriptDependantParams = $this->mDependantParameters
;
906 if ( count( $scriptDependantParams ) > 0 ) {
907 $this->output( "Script dependant parameters:\n" );
908 // Parameters description
909 foreach ( $scriptDependantParams as $par => $info ) {
910 if ( $info['shortName'] !== false ) {
911 $par .= " (-{$info['shortName']})";
914 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
915 "\n$tab$tab" ) . "\n"
918 $this->output( "\n" );
921 // Script specific parameters not defined on construction by
922 // Maintenance::addDefaultParams()
923 $scriptSpecificParams = array_diff_key(
924 # all script parameters:
926 # remove the Maintenance default parameters:
927 $this->mGenericParameters
,
928 $this->mDependantParameters
930 if ( count( $scriptSpecificParams ) > 0 ) {
931 $this->output( "Script specific parameters:\n" );
932 // Parameters description
933 foreach ( $scriptSpecificParams as $par => $info ) {
934 if ( $info['shortName'] !== false ) {
935 $par .= " (-{$info['shortName']})";
938 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
939 "\n$tab$tab" ) . "\n"
942 $this->output( "\n" );
946 if ( count( $this->mArgList
) > 0 ) {
947 $this->output( "Arguments:\n" );
948 // Arguments description
949 foreach ( $this->mArgList
as $info ) {
950 $openChar = $info['require'] ?
'<' : '[';
951 $closeChar = $info['require'] ?
'>' : ']';
953 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
954 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
957 $this->output( "\n" );
964 * Handle some last-minute setup here.
966 public function finalSetup() {
967 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
968 global $wgDBadminuser, $wgDBadminpassword;
969 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
971 # Turn off output buffering again, it might have been turned on in the settings files
972 if ( ob_get_level() ) {
976 $wgCommandLineMode = true;
979 if ( $this->hasOption( 'server' ) ) {
980 $wgServer = $this->getOption( 'server', $wgServer );
983 # If these were passed, use them
984 if ( $this->mDbUser
) {
985 $wgDBadminuser = $this->mDbUser
;
987 if ( $this->mDbPass
) {
988 $wgDBadminpassword = $this->mDbPass
;
991 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
992 $wgDBuser = $wgDBadminuser;
993 $wgDBpassword = $wgDBadminpassword;
995 if ( $wgDBservers ) {
997 * @var $wgDBservers array
999 foreach ( $wgDBservers as $i => $server ) {
1000 $wgDBservers[$i]['user'] = $wgDBuser;
1001 $wgDBservers[$i]['password'] = $wgDBpassword;
1004 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1005 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1006 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1008 LBFactory
::destroyInstance();
1011 // Per-script profiling; useful for debugging
1012 $this->activateProfiler();
1014 $this->afterFinalSetup();
1016 $wgShowSQLErrors = true;
1018 MediaWiki\
suppressWarnings();
1019 set_time_limit( 0 );
1020 MediaWiki\restoreWarnings
();
1022 $this->adjustMemoryLimit();
1026 * Execute a callback function at the end of initialisation
1028 protected function afterFinalSetup() {
1029 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1030 call_user_func( MW_CMDLINE_CALLBACK
);
1035 * Potentially debug globals. Originally a feature only
1038 public function globals() {
1039 if ( $this->hasOption( 'globals' ) ) {
1040 print_r( $GLOBALS );
1045 * Generic setup for most installs. Returns the location of LocalSettings
1048 public function loadSettings() {
1049 global $wgCommandLineMode, $IP;
1051 if ( isset( $this->mOptions
['conf'] ) ) {
1052 $settingsFile = $this->mOptions
['conf'];
1053 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1054 $settingsFile = MW_CONFIG_FILE
;
1056 $settingsFile = "$IP/LocalSettings.php";
1058 if ( isset( $this->mOptions
['wiki'] ) ) {
1059 $bits = explode( '-', $this->mOptions
['wiki'] );
1060 if ( count( $bits ) == 1 ) {
1063 define( 'MW_DB', $bits[0] );
1064 define( 'MW_PREFIX', $bits[1] );
1067 if ( !is_readable( $settingsFile ) ) {
1068 $this->error( "A copy of your installation's LocalSettings.php\n" .
1069 "must exist and be readable in the source directory.\n" .
1070 "Use --conf to specify it.", true );
1072 $wgCommandLineMode = true;
1074 return $settingsFile;
1078 * Support function for cleaning up redundant text records
1079 * @param bool $delete Whether or not to actually delete the records
1080 * @author Rob Church <robchur@gmail.com>
1082 public function purgeRedundantText( $delete = true ) {
1083 # Data should come off the master, wrapped in a transaction
1084 $dbw = $this->getDB( DB_MASTER
);
1085 $this->beginTransaction( $dbw, __METHOD__
);
1087 # Get "active" text records from the revisions table
1088 $this->output( 'Searching for active text records in revisions table...' );
1089 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
1090 foreach ( $res as $row ) {
1091 $cur[] = $row->rev_text_id
;
1093 $this->output( "done.\n" );
1095 # Get "active" text records from the archive table
1096 $this->output( 'Searching for active text records in archive table...' );
1097 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__
, array( 'DISTINCT' ) );
1098 foreach ( $res as $row ) {
1099 # old pre-MW 1.5 records can have null ar_text_id's.
1100 if ( $row->ar_text_id
!== null ) {
1101 $cur[] = $row->ar_text_id
;
1104 $this->output( "done.\n" );
1106 # Get the IDs of all text records not in these sets
1107 $this->output( 'Searching for inactive text records...' );
1108 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1109 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__
, array( 'DISTINCT' ) );
1111 foreach ( $res as $row ) {
1112 $old[] = $row->old_id
;
1114 $this->output( "done.\n" );
1116 # Inform the user of what we're going to do
1117 $count = count( $old );
1118 $this->output( "$count inactive items found.\n" );
1120 # Delete as appropriate
1121 if ( $delete && $count ) {
1122 $this->output( 'Deleting...' );
1123 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__
);
1124 $this->output( "done.\n" );
1128 $this->commitTransaction( $dbw, __METHOD__
);
1132 * Get the maintenance directory.
1135 protected function getDir() {
1140 * Returns a database to be used by current maintenance script. It can be set by setDB().
1141 * If not set, wfGetDB() will be used.
1142 * This function has the same parameters as wfGetDB()
1144 * @param integer $db DB index (DB_SLAVE/DB_MASTER)
1145 * @param array $groups; default: empty array
1146 * @param string|bool $wiki; default: current wiki
1149 protected function getDB( $db, $groups = array(), $wiki = false ) {
1150 if ( is_null( $this->mDb
) ) {
1151 return wfGetDB( $db, $groups, $wiki );
1158 * Sets database object to be returned by getDB().
1160 * @param IDatabase $db Database object to be used
1162 public function setDB( IDatabase
$db ) {
1167 * Begin a transcation on a DB
1169 * This method makes it clear that begin() is called from a maintenance script,
1170 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1172 * @param IDatabase $dbw
1173 * @param string $fname Caller name
1176 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1177 $dbw->begin( $fname );
1181 * Commit a transcation on a DB
1183 * This method makes it clear that commit() is called from a maintenance script,
1184 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1186 * @param IDatabase $dbw
1187 * @param string $fname Caller name
1190 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1191 $dbw->commit( $fname );
1195 * Rollback a transcation on a DB
1197 * This method makes it clear that rollback() is called from a maintenance script,
1198 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1200 * @param IDatabase $dbw
1201 * @param string $fname Caller name
1204 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1205 $dbw->rollback( $fname );
1209 * Lock the search index
1210 * @param DatabaseBase &$db
1212 private function lockSearchindex( $db ) {
1213 $write = array( 'searchindex' );
1223 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1228 * @param DatabaseBase &$db
1230 private function unlockSearchindex( $db ) {
1231 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1235 * Unlock and lock again
1236 * Since the lock is low-priority, queued reads will be able to complete
1237 * @param DatabaseBase &$db
1239 private function relockSearchindex( $db ) {
1240 $this->unlockSearchindex( $db );
1241 $this->lockSearchindex( $db );
1245 * Perform a search index update with locking
1246 * @param int $maxLockTime The maximum time to keep the search index locked.
1247 * @param string $callback The function that will update the function.
1248 * @param DatabaseBase $dbw
1249 * @param array $results
1251 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1255 if ( $maxLockTime ) {
1256 $this->output( " --- Waiting for lock ---" );
1257 $this->lockSearchindex( $dbw );
1259 $this->output( "\n" );
1262 # Loop through the results and do a search update
1263 foreach ( $results as $row ) {
1264 # Allow reads to be processed
1265 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1266 $this->output( " --- Relocking ---" );
1267 $this->relockSearchindex( $dbw );
1269 $this->output( "\n" );
1271 call_user_func( $callback, $dbw, $row );
1274 # Unlock searchindex
1275 if ( $maxLockTime ) {
1276 $this->output( " --- Unlocking --" );
1277 $this->unlockSearchindex( $dbw );
1278 $this->output( "\n" );
1283 * Update the searchindex table for a given pageid
1284 * @param DatabaseBase $dbw A database write handle
1285 * @param int $pageId The page ID to update.
1286 * @return null|string
1288 public function updateSearchIndexForPage( $dbw, $pageId ) {
1289 // Get current revision
1290 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1293 $titleObj = $rev->getTitle();
1294 $title = $titleObj->getPrefixedDBkey();
1295 $this->output( "$title..." );
1296 # Update searchindex
1297 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1299 $this->output( "\n" );
1306 * Wrapper for posix_isatty()
1307 * We default as considering stdin a tty (for nice readline methods)
1308 * but treating stout as not a tty to avoid color codes
1310 * @param mixed $fd File descriptor
1313 public static function posix_isatty( $fd ) {
1314 if ( !function_exists( 'posix_isatty' ) ) {
1317 return posix_isatty( $fd );
1322 * Prompt the console for input
1323 * @param string $prompt What to begin the line with, like '> '
1324 * @return string Response
1326 public static function readconsole( $prompt = '> ' ) {
1327 static $isatty = null;
1328 if ( is_null( $isatty ) ) {
1329 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1332 if ( $isatty && function_exists( 'readline' ) ) {
1333 $resp = readline( $prompt );
1334 if ( $resp === null ) {
1335 // Workaround for https://github.com/facebook/hhvm/issues/4776
1342 $st = self
::readlineEmulation( $prompt );
1344 if ( feof( STDIN
) ) {
1347 $st = fgets( STDIN
, 1024 );
1350 if ( $st === false ) {
1353 $resp = trim( $st );
1360 * Emulate readline()
1361 * @param string $prompt What to begin the line with, like '> '
1364 private static function readlineEmulation( $prompt ) {
1365 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1366 if ( !wfIsWindows() && $bash ) {
1368 $encPrompt = wfEscapeShellArg( $prompt );
1369 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1370 $encCommand = wfEscapeShellArg( $command );
1371 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1373 if ( $retval == 0 ) {
1375 } elseif ( $retval == 127 ) {
1376 // Couldn't execute bash even though we thought we saw it.
1377 // Shell probably spit out an error message, sorry :(
1378 // Fall through to fgets()...
1385 // Fallback... we'll have no editing controls, EWWW
1386 if ( feof( STDIN
) ) {
1391 return fgets( STDIN
, 1024 );
1396 * Fake maintenance wrapper, mostly used for the web installer/updater
1398 class FakeMaintenance
extends Maintenance
{
1399 protected $mSelf = "FakeMaintenanceScript";
1401 public function execute() {
1407 * Class for scripts that perform database maintenance and want to log the
1408 * update in `updatelog` so we can later skip it
1410 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1411 public function __construct() {
1412 parent
::__construct();
1413 $this->addOption( 'force', 'Run the update even if it was completed already' );
1414 $this->setBatchSize( 200 );
1417 public function execute() {
1418 $db = $this->getDB( DB_MASTER
);
1419 $key = $this->getUpdateKey();
1421 if ( !$this->hasOption( 'force' )
1422 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__
)
1424 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1429 if ( !$this->doDBUpdates() ) {
1433 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__
, 'IGNORE' ) ) {
1436 $this->output( $this->updatelogFailedMessage() . "\n" );
1443 * Message to show that the update was done already and was just skipped
1446 protected function updateSkippedMessage() {
1447 $key = $this->getUpdateKey();
1449 return "Update '{$key}' already logged as completed.";
1453 * Message to show that the update log was unable to log the completion of this update
1456 protected function updatelogFailedMessage() {
1457 $key = $this->getUpdateKey();
1459 return "Unable to log update '{$key}' as completed.";
1463 * Do the actual work. All child classes will need to implement this.
1464 * Return true to log the update as done or false (usually on failure).
1467 abstract protected function doDBUpdates();
1470 * Get the update key name to go in the update log table
1473 abstract protected function getUpdateKey();