Merge "Change default of $wgResourceLoaderMaxQueryLength to 2000"
[mediawiki.git] / maintenance / Maintenance.php
bloba0ffcb2b155f7676fd2150e1ed655e466fb390ee
1 <?php
2 /**
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
18 * @file
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Make sure we're on PHP5.3.3 or better
24 if ( !function_exists( 'version_compare' ) || version_compare( PHP_VERSION, '5.3.3' ) < 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' );
30 /**
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
39 $maintClass = false;
41 /**
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>
48 * @since 1.16
49 * @ingroup Maintenance
51 abstract class Maintenance {
52 /**
53 * Constants for DB access type
54 * @see Maintenance::getDbType()
56 const DB_NONE = 0;
57 const DB_STD = 1;
58 const DB_ADMIN = 2;
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
79 protected $mSelf;
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;
91 /**
92 * Batch size. If a script supports this, they should set
93 * a default with setBatchSize()
95 * @var int
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 getDB() / setDB()
106 * @var DatabaseBase
108 private $mDb = null;
111 * Used when creating separate schema files.
112 * @var resource
114 public $fileHandle;
117 * Accessible via getConfig()
119 * @var Config
121 private $config;
124 * Default constructor. Children should call this *first* if implementing
125 * their own constructors
127 public function __construct() {
128 // Setup $IP, using MW_INSTALL_PATH if it exists
129 global $IP;
130 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
131 ? getenv( 'MW_INSTALL_PATH' )
132 : realpath( __DIR__ . '/..' );
134 $this->addDefaultParams();
135 register_shutdown_function( array( $this, 'outputChanneled' ), false );
139 * Should we execute the maintenance script, or just allow it to be included
140 * as a standalone class? It checks that the call stack only includes this
141 * function and "requires" (meaning was called from the file scope)
143 * @return bool
145 public static function shouldExecute() {
146 global $wgCommandLineMode;
148 if ( !function_exists( 'debug_backtrace' ) ) {
149 // If someone has a better idea...
150 return $wgCommandLineMode;
153 $bt = debug_backtrace();
154 $count = count( $bt );
155 if ( $count < 2 ) {
156 return false; // sanity
158 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
159 return false; // last call should be to this function
161 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
162 for ( $i = 1; $i < $count; $i++ ) {
163 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
164 return false; // previous calls should all be "requires"
168 return true;
172 * Do the actual work. All child classes will need to implement this
174 abstract public function execute();
177 * Add a parameter to the script. Will be displayed on --help
178 * with the associated description
180 * @param string $name The name of the param (help, version, etc)
181 * @param string $description The description of the param to show on --help
182 * @param bool $required Is the param required?
183 * @param bool $withArg Is an argument required with this option?
184 * @param string $shortName Character to use as short name
186 protected function addOption( $name, $description, $required = false,
187 $withArg = false, $shortName = false
189 $this->mParams[$name] = array(
190 'desc' => $description,
191 'require' => $required,
192 'withArg' => $withArg,
193 'shortName' => $shortName
196 if ( $shortName !== false ) {
197 $this->mShortParamsMap[$shortName] = $name;
202 * Checks to see if a particular param exists.
203 * @param string $name The name of the param
204 * @return bool
206 protected function hasOption( $name ) {
207 return isset( $this->mOptions[$name] );
211 * Get an option, or return the default
212 * @param string $name The name of the param
213 * @param mixed $default Anything you want, default null
214 * @return mixed
216 protected function getOption( $name, $default = null ) {
217 if ( $this->hasOption( $name ) ) {
218 return $this->mOptions[$name];
219 } else {
220 // Set it so we don't have to provide the default again
221 $this->mOptions[$name] = $default;
223 return $this->mOptions[$name];
228 * Add some args that are needed
229 * @param string $arg Name of the arg, like 'start'
230 * @param string $description Short description of the arg
231 * @param bool $required Is this required?
233 protected function addArg( $arg, $description, $required = true ) {
234 $this->mArgList[] = array(
235 'name' => $arg,
236 'desc' => $description,
237 'require' => $required
242 * Remove an option. Useful for removing options that won't be used in your script.
243 * @param string $name The option to remove.
245 protected function deleteOption( $name ) {
246 unset( $this->mParams[$name] );
250 * Set the description text.
251 * @param string $text The text of the description
253 protected function addDescription( $text ) {
254 $this->mDescription = $text;
258 * Does a given argument exist?
259 * @param int $argId The integer value (from zero) for the arg
260 * @return bool
262 protected function hasArg( $argId = 0 ) {
263 return isset( $this->mArgs[$argId] );
267 * Get an argument.
268 * @param int $argId The integer value (from zero) for the arg
269 * @param mixed $default The default if it doesn't exist
270 * @return mixed
272 protected function getArg( $argId = 0, $default = null ) {
273 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
277 * Set the batch size.
278 * @param int $s The number of operations to do in a batch
280 protected function setBatchSize( $s = 0 ) {
281 $this->mBatchSize = $s;
283 // If we support $mBatchSize, show the option.
284 // Used to be in addDefaultParams, but in order for that to
285 // work, subclasses would have to call this function in the constructor
286 // before they called parent::__construct which is just weird
287 // (and really wasn't done).
288 if ( $this->mBatchSize ) {
289 $this->addOption( 'batch-size', 'Run this many operations ' .
290 'per batch, default: ' . $this->mBatchSize, false, true );
291 if ( isset( $this->mParams['batch-size'] ) ) {
292 // This seems a little ugly...
293 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
299 * Get the script's name
300 * @return string
302 public function getName() {
303 return $this->mSelf;
307 * Return input from stdin.
308 * @param int $len The number of bytes to read. If null, just return the handle.
309 * Maintenance::STDIN_ALL returns the full length
310 * @return mixed
312 protected function getStdin( $len = null ) {
313 if ( $len == Maintenance::STDIN_ALL ) {
314 return file_get_contents( 'php://stdin' );
316 $f = fopen( 'php://stdin', 'rt' );
317 if ( !$len ) {
318 return $f;
320 $input = fgets( $f, $len );
321 fclose( $f );
323 return rtrim( $input );
327 * @return bool
329 public function isQuiet() {
330 return $this->mQuiet;
334 * Throw some output to the user. Scripts can call this with no fears,
335 * as we handle all --quiet stuff here
336 * @param string $out The text to show to the user
337 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
339 protected function output( $out, $channel = null ) {
340 if ( $this->mQuiet ) {
341 return;
343 if ( $channel === null ) {
344 $this->cleanupChanneled();
345 print $out;
346 } else {
347 $out = preg_replace( '/\n\z/', '', $out );
348 $this->outputChanneled( $out, $channel );
353 * Throw an error to the user. Doesn't respect --quiet, so don't use
354 * this for non-error output
355 * @param string $err The error to display
356 * @param int $die If > 0, go ahead and die out using this int as the code
358 protected function error( $err, $die = 0 ) {
359 $this->outputChanneled( false );
360 if ( PHP_SAPI == 'cli' ) {
361 fwrite( STDERR, $err . "\n" );
362 } else {
363 print $err;
365 $die = intval( $die );
366 if ( $die > 0 ) {
367 die( $die );
371 private $atLineStart = true;
372 private $lastChannel = null;
375 * Clean up channeled output. Output a newline if necessary.
377 public function cleanupChanneled() {
378 if ( !$this->atLineStart ) {
379 print "\n";
380 $this->atLineStart = true;
385 * Message outputter with channeled message support. Messages on the
386 * same channel are concatenated, but any intervening messages in another
387 * channel start a new line.
388 * @param string $msg The message without trailing newline
389 * @param string $channel Channel identifier or null for no
390 * channel. Channel comparison uses ===.
392 public function outputChanneled( $msg, $channel = null ) {
393 if ( $msg === false ) {
394 $this->cleanupChanneled();
396 return;
399 // End the current line if necessary
400 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
401 print "\n";
404 print $msg;
406 $this->atLineStart = false;
407 if ( $channel === null ) {
408 // For unchanneled messages, output trailing newline immediately
409 print "\n";
410 $this->atLineStart = true;
412 $this->lastChannel = $channel;
416 * Does the script need different DB access? By default, we give Maintenance
417 * scripts normal rights to the DB. Sometimes, a script needs admin rights
418 * access for a reason and sometimes they want no access. Subclasses should
419 * override and return one of the following values, as needed:
420 * Maintenance::DB_NONE - For no DB access at all
421 * Maintenance::DB_STD - For normal DB access, default
422 * Maintenance::DB_ADMIN - For admin DB access
423 * @return int
425 public function getDbType() {
426 return Maintenance::DB_STD;
430 * Add the default parameters to the scripts
432 protected function addDefaultParams() {
434 # Generic (non script dependant) options:
436 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
437 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
438 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
439 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
440 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
441 $this->addOption(
442 'memory-limit',
443 'Set a specific memory limit for the script, '
444 . '"max" for no limit or "default" to avoid changing it'
446 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
447 "http://en.wikipedia.org. This is sometimes necessary because " .
448 "server name detection may fail in command line scripts.", false, true );
449 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
451 # Save generic options to display them separately in help
452 $this->mGenericParameters = $this->mParams;
454 # Script dependant options:
456 // If we support a DB, show the options
457 if ( $this->getDbType() > 0 ) {
458 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
459 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
462 # Save additional script dependant options to display
463 # them separately in help
464 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
468 * @since 1.24
469 * @return Config
471 public function getConfig() {
472 if ( $this->config === null ) {
473 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
476 return $this->config;
480 * @since 1.24
481 * @param Config $config
483 public function setConfig( Config $config ) {
484 $this->config = $config;
488 * Run a child maintenance script. Pass all of the current arguments
489 * to it.
490 * @param string $maintClass A name of a child maintenance class
491 * @param string $classFile Full path of where the child is
492 * @return Maintenance
494 public function runChild( $maintClass, $classFile = null ) {
495 // Make sure the class is loaded first
496 if ( !class_exists( $maintClass ) ) {
497 if ( $classFile ) {
498 require_once $classFile;
500 if ( !class_exists( $maintClass ) ) {
501 $this->error( "Cannot spawn child: $maintClass" );
506 * @var $child Maintenance
508 $child = new $maintClass();
509 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
510 if ( !is_null( $this->mDb ) ) {
511 $child->setDB( $this->mDb );
514 return $child;
518 * Do some sanity checking and basic setup
520 public function setup() {
521 global $IP, $wgCommandLineMode, $wgRequestTime;
523 # Abort if called from a web server
524 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
525 $this->error( 'This script must be run from the command line', true );
528 if ( $IP === null ) {
529 $this->error( "\$IP not set, aborting!\n" .
530 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
533 # Make sure we can handle script parameters
534 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
535 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
538 // Send PHP warnings and errors to stderr instead of stdout.
539 // This aids in diagnosing problems, while keeping messages
540 // out of redirected output.
541 if ( ini_get( 'display_errors' ) ) {
542 ini_set( 'display_errors', 'stderr' );
545 $this->loadParamsAndArgs();
546 $this->maybeHelp();
548 # Set the memory limit
549 # Note we need to set it again later in cache LocalSettings changed it
550 $this->adjustMemoryLimit();
552 # Set max execution time to 0 (no limit). PHP.net says that
553 # "When running PHP from the command line the default setting is 0."
554 # But sometimes this doesn't seem to be the case.
555 ini_set( 'max_execution_time', 0 );
557 $wgRequestTime = microtime( true );
559 # Define us as being in MediaWiki
560 define( 'MEDIAWIKI', true );
562 $wgCommandLineMode = true;
564 # Turn off output buffering if it's on
565 while ( ob_get_level() > 0 ) {
566 ob_end_flush();
569 $this->validateParamsAndArgs();
573 * Normally we disable the memory_limit when running admin scripts.
574 * Some scripts may wish to actually set a limit, however, to avoid
575 * blowing up unexpectedly. We also support a --memory-limit option,
576 * to allow sysadmins to explicitly set one if they'd prefer to override
577 * defaults (or for people using Suhosin which yells at you for trying
578 * to disable the limits)
579 * @return string
581 public function memoryLimit() {
582 $limit = $this->getOption( 'memory-limit', 'max' );
583 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
584 return $limit;
588 * Adjusts PHP's memory limit to better suit our needs, if needed.
590 protected function adjustMemoryLimit() {
591 $limit = $this->memoryLimit();
592 if ( $limit == 'max' ) {
593 $limit = -1; // no memory limit
595 if ( $limit != 'default' ) {
596 ini_set( 'memory_limit', $limit );
601 * Activate the profiler (assuming $wgProfiler is set)
603 protected function activateProfiler() {
604 global $wgProfiler;
606 $output = $this->getOption( 'profiler' );
607 if ( $output && is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
608 $class = $wgProfiler['class'];
609 $profiler = new $class(
610 array( 'sampling' => 1, 'output' => $output ) + $wgProfiler
612 $profiler->setTemplated( true );
613 Profiler::replaceStubInstance( $profiler );
618 * Clear all params and arguments.
620 public function clearParamsAndArgs() {
621 $this->mOptions = array();
622 $this->mArgs = array();
623 $this->mInputLoaded = false;
627 * Process command line arguments
628 * $mOptions becomes an array with keys set to the option names
629 * $mArgs becomes a zero-based array containing the non-option arguments
631 * @param string $self The name of the script, if any
632 * @param array $opts An array of options, in form of key=>value
633 * @param array $args An array of command line arguments
635 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
636 # If we were given opts or args, set those and return early
637 if ( $self ) {
638 $this->mSelf = $self;
639 $this->mInputLoaded = true;
641 if ( $opts ) {
642 $this->mOptions = $opts;
643 $this->mInputLoaded = true;
645 if ( $args ) {
646 $this->mArgs = $args;
647 $this->mInputLoaded = true;
650 # If we've already loaded input (either by user values or from $argv)
651 # skip on loading it again. The array_shift() will corrupt values if
652 # it's run again and again
653 if ( $this->mInputLoaded ) {
654 $this->loadSpecialVars();
656 return;
659 global $argv;
660 $this->mSelf = array_shift( $argv );
662 $options = array();
663 $args = array();
665 # Parse arguments
666 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
667 if ( $arg == '--' ) {
668 # End of options, remainder should be considered arguments
669 $arg = next( $argv );
670 while ( $arg !== false ) {
671 $args[] = $arg;
672 $arg = next( $argv );
674 break;
675 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
676 # Long options
677 $option = substr( $arg, 2 );
678 if ( array_key_exists( $option, $options ) ) {
679 $this->error( "\nERROR: $option parameter given twice\n" );
680 $this->maybeHelp( true );
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 );
688 $options[$option] = $param;
689 } else {
690 $bits = explode( '=', $option, 2 );
691 if ( count( $bits ) > 1 ) {
692 $option = $bits[0];
693 $param = $bits[1];
694 } else {
695 $param = 1;
697 $options[$option] = $param;
699 } elseif ( $arg == '-' ) {
700 # Lonely "-", often used to indicate stdin or stdout.
701 $args[] = $arg;
702 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
703 # Short options
704 $argLength = strlen( $arg );
705 for ( $p = 1; $p < $argLength; $p++ ) {
706 $option = $arg[$p];
707 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
708 $option = $this->mShortParamsMap[$option];
710 if ( array_key_exists( $option, $options ) ) {
711 $this->error( "\nERROR: $option parameter given twice\n" );
712 $this->maybeHelp( true );
714 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
715 $param = next( $argv );
716 if ( $param === false ) {
717 $this->error( "\nERROR: $option parameter needs a value after it\n" );
718 $this->maybeHelp( true );
720 $options[$option] = $param;
721 } else {
722 $options[$option] = 1;
725 } else {
726 $args[] = $arg;
730 $this->mOptions = $options;
731 $this->mArgs = $args;
732 $this->loadSpecialVars();
733 $this->mInputLoaded = true;
737 * Run some validation checks on the params, etc
739 protected function validateParamsAndArgs() {
740 $die = false;
741 # Check to make sure we've got all the required options
742 foreach ( $this->mParams as $opt => $info ) {
743 if ( $info['require'] && !$this->hasOption( $opt ) ) {
744 $this->error( "Param $opt required!" );
745 $die = true;
748 # Check arg list too
749 foreach ( $this->mArgList as $k => $info ) {
750 if ( $info['require'] && !$this->hasArg( $k ) ) {
751 $this->error( 'Argument <' . $info['name'] . '> required!' );
752 $die = true;
756 if ( $die ) {
757 $this->maybeHelp( true );
762 * Handle the special variables that are global to all scripts
764 protected function loadSpecialVars() {
765 if ( $this->hasOption( 'dbuser' ) ) {
766 $this->mDbUser = $this->getOption( 'dbuser' );
768 if ( $this->hasOption( 'dbpass' ) ) {
769 $this->mDbPass = $this->getOption( 'dbpass' );
771 if ( $this->hasOption( 'quiet' ) ) {
772 $this->mQuiet = true;
774 if ( $this->hasOption( 'batch-size' ) ) {
775 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
780 * Maybe show the help.
781 * @param bool $force Whether to force the help to show, default false
783 protected function maybeHelp( $force = false ) {
784 if ( !$force && !$this->hasOption( 'help' ) ) {
785 return;
788 $screenWidth = 80; // TODO: Calculate this!
789 $tab = " ";
790 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
792 ksort( $this->mParams );
793 $this->mQuiet = false;
795 // Description ...
796 if ( $this->mDescription ) {
797 $this->output( "\n" . $this->mDescription . "\n" );
799 $output = "\nUsage: php " . basename( $this->mSelf );
801 // ... append parameters ...
802 if ( $this->mParams ) {
803 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
806 // ... and append arguments.
807 if ( $this->mArgList ) {
808 $output .= ' ';
809 foreach ( $this->mArgList as $k => $arg ) {
810 if ( $arg['require'] ) {
811 $output .= '<' . $arg['name'] . '>';
812 } else {
813 $output .= '[' . $arg['name'] . ']';
815 if ( $k < count( $this->mArgList ) - 1 ) {
816 $output .= ' ';
820 $this->output( "$output\n\n" );
822 # TODO abstract some repetitive code below
824 // Generic parameters
825 $this->output( "Generic maintenance parameters:\n" );
826 foreach ( $this->mGenericParameters as $par => $info ) {
827 if ( $info['shortName'] !== false ) {
828 $par .= " (-{$info['shortName']})";
830 $this->output(
831 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
832 "\n$tab$tab" ) . "\n"
835 $this->output( "\n" );
837 $scriptDependantParams = $this->mDependantParameters;
838 if ( count( $scriptDependantParams ) > 0 ) {
839 $this->output( "Script dependant parameters:\n" );
840 // Parameters description
841 foreach ( $scriptDependantParams as $par => $info ) {
842 if ( $info['shortName'] !== false ) {
843 $par .= " (-{$info['shortName']})";
845 $this->output(
846 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
847 "\n$tab$tab" ) . "\n"
850 $this->output( "\n" );
853 // Script specific parameters not defined on construction by
854 // Maintenance::addDefaultParams()
855 $scriptSpecificParams = array_diff_key(
856 # all script parameters:
857 $this->mParams,
858 # remove the Maintenance default parameters:
859 $this->mGenericParameters,
860 $this->mDependantParameters
862 if ( count( $scriptSpecificParams ) > 0 ) {
863 $this->output( "Script specific parameters:\n" );
864 // Parameters description
865 foreach ( $scriptSpecificParams as $par => $info ) {
866 if ( $info['shortName'] !== false ) {
867 $par .= " (-{$info['shortName']})";
869 $this->output(
870 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
871 "\n$tab$tab" ) . "\n"
874 $this->output( "\n" );
877 // Print arguments
878 if ( count( $this->mArgList ) > 0 ) {
879 $this->output( "Arguments:\n" );
880 // Arguments description
881 foreach ( $this->mArgList as $info ) {
882 $openChar = $info['require'] ? '<' : '[';
883 $closeChar = $info['require'] ? '>' : ']';
884 $this->output(
885 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
886 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
889 $this->output( "\n" );
892 die( 1 );
896 * Handle some last-minute setup here.
898 public function finalSetup() {
899 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
900 global $wgDBadminuser, $wgDBadminpassword;
901 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
903 # Turn off output buffering again, it might have been turned on in the settings files
904 if ( ob_get_level() ) {
905 ob_end_flush();
907 # Same with these
908 $wgCommandLineMode = true;
910 # Override $wgServer
911 if ( $this->hasOption( 'server' ) ) {
912 $wgServer = $this->getOption( 'server', $wgServer );
915 # If these were passed, use them
916 if ( $this->mDbUser ) {
917 $wgDBadminuser = $this->mDbUser;
919 if ( $this->mDbPass ) {
920 $wgDBadminpassword = $this->mDbPass;
923 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
924 $wgDBuser = $wgDBadminuser;
925 $wgDBpassword = $wgDBadminpassword;
927 if ( $wgDBservers ) {
929 * @var $wgDBservers array
931 foreach ( $wgDBservers as $i => $server ) {
932 $wgDBservers[$i]['user'] = $wgDBuser;
933 $wgDBservers[$i]['password'] = $wgDBpassword;
936 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
937 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
938 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
940 LBFactory::destroyInstance();
943 // Per-script profiling; useful for debugging
944 $this->activateProfiler();
946 $this->afterFinalSetup();
948 $wgShowSQLErrors = true;
950 // @codingStandardsIgnoreStart Allow error suppression. wfSuppressWarnings()
951 // is not available.
952 @set_time_limit( 0 );
953 // @codingStandardsIgnoreStart
955 $this->adjustMemoryLimit();
959 * Execute a callback function at the end of initialisation
961 protected function afterFinalSetup() {
962 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
963 call_user_func( MW_CMDLINE_CALLBACK );
968 * Potentially debug globals. Originally a feature only
969 * for refreshLinks
971 public function globals() {
972 if ( $this->hasOption( 'globals' ) ) {
973 print_r( $GLOBALS );
978 * Generic setup for most installs. Returns the location of LocalSettings
979 * @return string
981 public function loadSettings() {
982 global $wgCommandLineMode, $IP;
984 if ( isset( $this->mOptions['conf'] ) ) {
985 $settingsFile = $this->mOptions['conf'];
986 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
987 $settingsFile = MW_CONFIG_FILE;
988 } else {
989 $settingsFile = "$IP/LocalSettings.php";
991 if ( isset( $this->mOptions['wiki'] ) ) {
992 $bits = explode( '-', $this->mOptions['wiki'] );
993 if ( count( $bits ) == 1 ) {
994 $bits[] = '';
996 define( 'MW_DB', $bits[0] );
997 define( 'MW_PREFIX', $bits[1] );
1000 if ( !is_readable( $settingsFile ) ) {
1001 $this->error( "A copy of your installation's LocalSettings.php\n" .
1002 "must exist and be readable in the source directory.\n" .
1003 "Use --conf to specify it.", true );
1005 $wgCommandLineMode = true;
1007 return $settingsFile;
1011 * Support function for cleaning up redundant text records
1012 * @param bool $delete Whether or not to actually delete the records
1013 * @author Rob Church <robchur@gmail.com>
1015 public function purgeRedundantText( $delete = true ) {
1016 # Data should come off the master, wrapped in a transaction
1017 $dbw = $this->getDB( DB_MASTER );
1018 $dbw->begin( __METHOD__ );
1020 # Get "active" text records from the revisions table
1021 $this->output( 'Searching for active text records in revisions table...' );
1022 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
1023 foreach ( $res as $row ) {
1024 $cur[] = $row->rev_text_id;
1026 $this->output( "done.\n" );
1028 # Get "active" text records from the archive table
1029 $this->output( 'Searching for active text records in archive table...' );
1030 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
1031 foreach ( $res as $row ) {
1032 # old pre-MW 1.5 records can have null ar_text_id's.
1033 if ( $row->ar_text_id !== null ) {
1034 $cur[] = $row->ar_text_id;
1037 $this->output( "done.\n" );
1039 # Get the IDs of all text records not in these sets
1040 $this->output( 'Searching for inactive text records...' );
1041 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1042 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__, array( 'DISTINCT' ) );
1043 $old = array();
1044 foreach ( $res as $row ) {
1045 $old[] = $row->old_id;
1047 $this->output( "done.\n" );
1049 # Inform the user of what we're going to do
1050 $count = count( $old );
1051 $this->output( "$count inactive items found.\n" );
1053 # Delete as appropriate
1054 if ( $delete && $count ) {
1055 $this->output( 'Deleting...' );
1056 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__ );
1057 $this->output( "done.\n" );
1060 # Done
1061 $dbw->commit( __METHOD__ );
1065 * Get the maintenance directory.
1066 * @return string
1068 protected function getDir() {
1069 return __DIR__;
1073 * Returns a database to be used by current maintenance script. It can be set by setDB().
1074 * If not set, wfGetDB() will be used.
1075 * This function has the same parameters as wfGetDB()
1077 * @return DatabaseBase
1079 protected function getDB( $db, $groups = array(), $wiki = false ) {
1080 if ( is_null( $this->mDb ) ) {
1081 return wfGetDB( $db, $groups, $wiki );
1082 } else {
1083 return $this->mDb;
1088 * Sets database object to be returned by getDB().
1090 * @param DatabaseBase $db Database object to be used
1092 public function setDB( $db ) {
1093 $this->mDb = $db;
1097 * Lock the search index
1098 * @param DatabaseBase &$db
1100 private function lockSearchindex( $db ) {
1101 $write = array( 'searchindex' );
1102 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1103 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1107 * Unlock the tables
1108 * @param DatabaseBase &$db
1110 private function unlockSearchindex( $db ) {
1111 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1115 * Unlock and lock again
1116 * Since the lock is low-priority, queued reads will be able to complete
1117 * @param DatabaseBase &$db
1119 private function relockSearchindex( $db ) {
1120 $this->unlockSearchindex( $db );
1121 $this->lockSearchindex( $db );
1125 * Perform a search index update with locking
1126 * @param int $maxLockTime The maximum time to keep the search index locked.
1127 * @param string $callback The function that will update the function.
1128 * @param DatabaseBase $dbw
1129 * @param array $results
1131 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1132 $lockTime = time();
1134 # Lock searchindex
1135 if ( $maxLockTime ) {
1136 $this->output( " --- Waiting for lock ---" );
1137 $this->lockSearchindex( $dbw );
1138 $lockTime = time();
1139 $this->output( "\n" );
1142 # Loop through the results and do a search update
1143 foreach ( $results as $row ) {
1144 # Allow reads to be processed
1145 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1146 $this->output( " --- Relocking ---" );
1147 $this->relockSearchindex( $dbw );
1148 $lockTime = time();
1149 $this->output( "\n" );
1151 call_user_func( $callback, $dbw, $row );
1154 # Unlock searchindex
1155 if ( $maxLockTime ) {
1156 $this->output( " --- Unlocking --" );
1157 $this->unlockSearchindex( $dbw );
1158 $this->output( "\n" );
1163 * Update the searchindex table for a given pageid
1164 * @param DatabaseBase $dbw A database write handle
1165 * @param int $pageId The page ID to update.
1166 * @return null|string
1168 public function updateSearchIndexForPage( $dbw, $pageId ) {
1169 // Get current revision
1170 $rev = Revision::loadFromPageId( $dbw, $pageId );
1171 $title = null;
1172 if ( $rev ) {
1173 $titleObj = $rev->getTitle();
1174 $title = $titleObj->getPrefixedDBkey();
1175 $this->output( "$title..." );
1176 # Update searchindex
1177 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1178 $u->doUpdate();
1179 $this->output( "\n" );
1182 return $title;
1186 * Wrapper for posix_isatty()
1187 * We default as considering stdin a tty (for nice readline methods)
1188 * but treating stout as not a tty to avoid color codes
1190 * @param mixed $fd File descriptor
1191 * @return bool
1193 public static function posix_isatty( $fd ) {
1194 if ( !function_exists( 'posix_isatty' ) ) {
1195 return !$fd;
1196 } else {
1197 return posix_isatty( $fd );
1202 * Prompt the console for input
1203 * @param string $prompt What to begin the line with, like '> '
1204 * @return string Response
1206 public static function readconsole( $prompt = '> ' ) {
1207 static $isatty = null;
1208 if ( is_null( $isatty ) ) {
1209 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1212 if ( $isatty && function_exists( 'readline' ) ) {
1213 $resp = readline( $prompt );
1214 if ( $resp === null ) {
1215 // Workaround for https://github.com/facebook/hhvm/issues/4776
1216 return false;
1217 } else {
1218 return $resp;
1220 } else {
1221 if ( $isatty ) {
1222 $st = self::readlineEmulation( $prompt );
1223 } else {
1224 if ( feof( STDIN ) ) {
1225 $st = false;
1226 } else {
1227 $st = fgets( STDIN, 1024 );
1230 if ( $st === false ) {
1231 return false;
1233 $resp = trim( $st );
1235 return $resp;
1240 * Emulate readline()
1241 * @param string $prompt What to begin the line with, like '> '
1242 * @return string
1244 private static function readlineEmulation( $prompt ) {
1245 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1246 if ( !wfIsWindows() && $bash ) {
1247 $retval = false;
1248 $encPrompt = wfEscapeShellArg( $prompt );
1249 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1250 $encCommand = wfEscapeShellArg( $command );
1251 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1253 if ( $retval == 0 ) {
1254 return $line;
1255 } elseif ( $retval == 127 ) {
1256 // Couldn't execute bash even though we thought we saw it.
1257 // Shell probably spit out an error message, sorry :(
1258 // Fall through to fgets()...
1259 } else {
1260 // EOF/ctrl+D
1261 return false;
1265 // Fallback... we'll have no editing controls, EWWW
1266 if ( feof( STDIN ) ) {
1267 return false;
1269 print $prompt;
1271 return fgets( STDIN, 1024 );
1276 * Fake maintenance wrapper, mostly used for the web installer/updater
1278 class FakeMaintenance extends Maintenance {
1279 protected $mSelf = "FakeMaintenanceScript";
1281 public function execute() {
1282 return;
1287 * Class for scripts that perform database maintenance and want to log the
1288 * update in `updatelog` so we can later skip it
1290 abstract class LoggedUpdateMaintenance extends Maintenance {
1291 public function __construct() {
1292 parent::__construct();
1293 $this->addOption( 'force', 'Run the update even if it was completed already' );
1294 $this->setBatchSize( 200 );
1297 public function execute() {
1298 $db = $this->getDB( DB_MASTER );
1299 $key = $this->getUpdateKey();
1301 if ( !$this->hasOption( 'force' )
1302 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ )
1304 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1306 return true;
1309 if ( !$this->doDBUpdates() ) {
1310 return false;
1313 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) ) {
1314 return true;
1315 } else {
1316 $this->output( $this->updatelogFailedMessage() . "\n" );
1318 return false;
1323 * Message to show that the update was done already and was just skipped
1324 * @return string
1326 protected function updateSkippedMessage() {
1327 $key = $this->getUpdateKey();
1329 return "Update '{$key}' already logged as completed.";
1333 * Message to show that the update log was unable to log the completion of this update
1334 * @return string
1336 protected function updatelogFailedMessage() {
1337 $key = $this->getUpdateKey();
1339 return "Unable to log update '{$key}' as completed.";
1343 * Do the actual work. All child classes will need to implement this.
1344 * Return true to log the update as done or false (usually on failure).
1345 * @return bool
1347 abstract protected function doDBUpdates();
1350 * Get the update key name to go in the update log table
1351 * @return string
1353 abstract protected function getUpdateKey();