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 // Define this so scripts can easily find doMaintenance.php
24 define( 'RUN_MAINTENANCE_IF_MAIN', dirname( __FILE__
) . '/doMaintenance.php' );
25 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
29 // Make sure we're on PHP5 or better
30 if ( !function_exists( 'version_compare' ) ||
version_compare( PHP_VERSION
, '5.2.3' ) < 0 ) {
31 require_once( dirname( __FILE__
) . '/../includes/PHPVersionError.php' );
32 wfPHPVersionError( 'cli' );
35 // Wrapper for posix_isatty()
36 if ( !function_exists( 'posix_isatty' ) ) {
37 # We default as considering stdin a tty (for nice readline methods)
38 # but treating stout as not a tty to avoid color codes
39 function posix_isatty( $fd ) {
45 * Abstract maintenance class for quickly writing and churning out
46 * maintenance scripts with minimal effort. All that _must_ be defined
47 * is the execute() method. See docs/maintenance.txt for more info
48 * and a quick demo of how to use it.
50 * @author Chad Horohoe <chad@anyonecanedit.org>
52 * @ingroup Maintenance
54 abstract class Maintenance
{
57 * Constants for DB access type
58 * @see Maintenance::getDbType()
64 // Const for getStdin()
65 const STDIN_ALL
= 'all';
67 // This is the desired params
68 protected $mParams = array();
70 // Array of mapping short parameters to long ones
71 protected $mShortParamsMap = array();
73 // Array of desired args
74 protected $mArgList = array();
76 // This is the list of options that were actually passed
77 protected $mOptions = array();
79 // This is the list of arguments that were actually passed
80 protected $mArgs = array();
82 // Name of the script currently running
85 // Special vars for params that are always used
86 protected $mQuiet = false;
87 protected $mDbUser, $mDbPass;
89 // A description of the script, children should change this
90 protected $mDescription = '';
92 // Have we already loaded our user input?
93 protected $mInputLoaded = false;
96 * Batch size. If a script supports this, they should set
97 * a default with setBatchSize()
101 protected $mBatchSize = null;
103 // Generic options added by addDefaultParams()
104 private $mGenericParameters = array();
105 // Generic options which might or not be supported by the script
106 private $mDependantParameters = array();
108 // Used by getDD() / setDB()
112 * List of all the core maintenance scripts. This is added
113 * to scripts added by extensions in $wgMaintenanceScripts
114 * and returned by getMaintenanceScripts()
116 protected static $mCoreScripts = null;
119 * Default constructor. Children should call this *first* if implementing
120 * their own constructors
122 public function __construct() {
123 // Setup $IP, using MW_INSTALL_PATH if it exists
125 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
126 ?
getenv( 'MW_INSTALL_PATH' )
127 : realpath( dirname( __FILE__
) . '/..' );
129 $this->addDefaultParams();
130 register_shutdown_function( array( $this, 'outputChanneled' ), false );
134 * Should we execute the maintenance script, or just allow it to be included
135 * as a standalone class? It checks that the call stack only includes this
136 * function and a require (meaning was called from the file scope)
140 public static function shouldExecute() {
141 $bt = debug_backtrace();
142 if( count( $bt ) !== 2 ) {
145 return in_array( $bt[1]['function'], array( 'require_once', 'require', 'include' ) ) &&
146 $bt[0]['class'] == 'Maintenance' &&
147 $bt[0]['function'] == 'shouldExecute';
151 * Do the actual work. All child classes will need to implement this
153 abstract public function execute();
156 * Add a parameter to the script. Will be displayed on --help
157 * with the associated description
159 * @param $name String: the name of the param (help, version, etc)
160 * @param $description String: the description of the param to show on --help
161 * @param $required Boolean: is the param required?
162 * @param $withArg Boolean: is an argument required with this option?
163 * @param $shortName String: character to use as short name
165 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
166 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
167 if ( $shortName !== false ) {
168 $this->mShortParamsMap
[$shortName] = $name;
173 * Checks to see if a particular param exists.
174 * @param $name String: the name of the param
177 protected function hasOption( $name ) {
178 return isset( $this->mOptions
[$name] );
182 * Get an option, or return the default
183 * @param $name String: the name of the param
184 * @param $default Mixed: anything you want, default null
187 protected function getOption( $name, $default = null ) {
188 if ( $this->hasOption( $name ) ) {
189 return $this->mOptions
[$name];
191 // Set it so we don't have to provide the default again
192 $this->mOptions
[$name] = $default;
193 return $this->mOptions
[$name];
198 * Add some args that are needed
199 * @param $arg String: name of the arg, like 'start'
200 * @param $description String: short description of the arg
201 * @param $required Boolean: is this required?
203 protected function addArg( $arg, $description, $required = true ) {
204 $this->mArgList
[] = array(
206 'desc' => $description,
207 'require' => $required
212 * Remove an option. Useful for removing options that won't be used in your script.
213 * @param $name String: the option to remove.
215 protected function deleteOption( $name ) {
216 unset( $this->mParams
[$name] );
220 * Set the description text.
221 * @param $text String: the text of the description
223 protected function addDescription( $text ) {
224 $this->mDescription
= $text;
228 * Does a given argument exist?
229 * @param $argId Integer: the integer value (from zero) for the arg
232 protected function hasArg( $argId = 0 ) {
233 return isset( $this->mArgs
[$argId] );
238 * @param $argId Integer: the integer value (from zero) for the arg
239 * @param $default Mixed: the default if it doesn't exist
242 protected function getArg( $argId = 0, $default = null ) {
243 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
247 * Set the batch size.
248 * @param $s Integer: the number of operations to do in a batch
250 protected function setBatchSize( $s = 0 ) {
251 $this->mBatchSize
= $s;
255 * Get the script's name
258 public function getName() {
263 * Return input from stdin.
264 * @param $len Integer: the number of bytes to read. If null,
265 * just return the handle. Maintenance::STDIN_ALL returns
269 protected function getStdin( $len = null ) {
270 if ( $len == Maintenance
::STDIN_ALL
) {
271 return file_get_contents( 'php://stdin' );
273 $f = fopen( 'php://stdin', 'rt' );
277 $input = fgets( $f, $len );
279 return rtrim( $input );
282 public function isQuiet() {
283 return $this->mQuiet
;
287 * Throw some output to the user. Scripts can call this with no fears,
288 * as we handle all --quiet stuff here
289 * @param $out String: the text to show to the user
290 * @param $channel Mixed: unique identifier for the channel. See
291 * function outputChanneled.
293 protected function output( $out, $channel = null ) {
294 if ( $this->mQuiet
) {
297 if ( $channel === null ) {
298 $this->cleanupChanneled();
300 $f = fopen( 'php://stdout', 'w' );
305 $out = preg_replace( '/\n\z/', '', $out );
306 $this->outputChanneled( $out, $channel );
311 * Throw an error to the user. Doesn't respect --quiet, so don't use
312 * this for non-error output
313 * @param $err String: the error to display
314 * @param $die Int: if > 0, go ahead and die out using this int as the code
316 protected function error( $err, $die = 0 ) {
317 $this->outputChanneled( false );
318 if ( php_sapi_name() == 'cli' ) {
319 fwrite( STDERR
, $err . "\n" );
321 $f = fopen( 'php://stderr', 'w' );
322 fwrite( $f, $err . "\n" );
325 $die = intval( $die );
331 private $atLineStart = true;
332 private $lastChannel = null;
335 * Clean up channeled output. Output a newline if necessary.
337 public function cleanupChanneled() {
338 if ( !$this->atLineStart
) {
339 $handle = fopen( 'php://stdout', 'w' );
340 fwrite( $handle, "\n" );
342 $this->atLineStart
= true;
347 * Message outputter with channeled message support. Messages on the
348 * same channel are concatenated, but any intervening messages in another
349 * channel start a new line.
350 * @param $msg String: the message without trailing newline
351 * @param $channel Channel identifier or null for no
352 * channel. Channel comparison uses ===.
354 public function outputChanneled( $msg, $channel = null ) {
355 if ( $msg === false ) {
356 $this->cleanupChanneled();
360 $handle = fopen( 'php://stdout', 'w' );
362 // End the current line if necessary
363 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
364 fwrite( $handle, "\n" );
367 fwrite( $handle, $msg );
369 $this->atLineStart
= false;
370 if ( $channel === null ) {
371 // For unchanneled messages, output trailing newline immediately
372 fwrite( $handle, "\n" );
373 $this->atLineStart
= true;
375 $this->lastChannel
= $channel;
382 * Does the script need different DB access? By default, we give Maintenance
383 * scripts normal rights to the DB. Sometimes, a script needs admin rights
384 * access for a reason and sometimes they want no access. Subclasses should
385 * override and return one of the following values, as needed:
386 * Maintenance::DB_NONE - For no DB access at all
387 * Maintenance::DB_STD - For normal DB access, default
388 * Maintenance::DB_ADMIN - For admin DB access
391 public function getDbType() {
392 return Maintenance
::DB_STD
;
396 * Add the default parameters to the scripts
398 protected function addDefaultParams() {
400 # Generic (non script dependant) options:
402 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
403 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
404 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
405 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
406 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
407 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
408 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
409 "http://en.wikipedia.org. This is sometimes necessary because " .
410 "server name detection may fail in command line scripts.", false, true );
412 # Save generic options to display them separately in help
413 $this->mGenericParameters
= $this->mParams
;
415 # Script dependant options:
417 // If we support a DB, show the options
418 if ( $this->getDbType() > 0 ) {
419 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
420 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
422 // If we support $mBatchSize, show the option
423 if ( $this->mBatchSize
) {
424 $this->addOption( 'batch-size', 'Run this many operations ' .
425 'per batch, default: ' . $this->mBatchSize
, false, true );
427 # Save additional script dependant options to display
428 #Â them separately in help
429 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
433 * Run a child maintenance script. Pass all of the current arguments
435 * @param $maintClass String: a name of a child maintenance class
436 * @param $classFile String: full path of where the child is
437 * @return Maintenance child
439 public function runChild( $maintClass, $classFile = null ) {
440 // Make sure the class is loaded first
441 if ( !MWInit
::classExists( $maintClass ) ) {
443 require_once( $classFile );
445 if ( !MWInit
::classExists( $maintClass ) ) {
446 $this->error( "Cannot spawn child: $maintClass" );
450 $child = new $maintClass();
451 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
452 if ( !is_null( $this->mDb
) ) {
453 $child->setDB( $this->mDb
);
459 * Do some sanity checking and basic setup
461 public function setup() {
462 global $wgCommandLineMode, $wgRequestTime;
464 # Abort if called from a web server
465 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
466 $this->error( 'This script must be run from the command line', true );
469 # Make sure we can handle script parameters
470 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
471 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
474 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
475 // Send PHP warnings and errors to stderr instead of stdout.
476 // This aids in diagnosing problems, while keeping messages
477 // out of redirected output.
478 if ( ini_get( 'display_errors' ) ) {
479 ini_set( 'display_errors', 'stderr' );
482 // Don't touch the setting on earlier versions of PHP,
483 // as setting it would disable output if you'd wanted it.
485 // Note that exceptions are also sent to stderr when
486 // command-line mode is on, regardless of PHP version.
489 $this->loadParamsAndArgs();
492 # Set the memory limit
493 # Note we need to set it again later in cache LocalSettings changed it
494 $this->adjustMemoryLimit();
496 # Set max execution time to 0 (no limit). PHP.net says that
497 # "When running PHP from the command line the default setting is 0."
498 # But sometimes this doesn't seem to be the case.
499 ini_set( 'max_execution_time', 0 );
501 $wgRequestTime = microtime( true );
503 # Define us as being in MediaWiki
504 define( 'MEDIAWIKI', true );
506 $wgCommandLineMode = true;
507 # Turn off output buffering if it's on
510 $this->validateParamsAndArgs();
514 * Normally we disable the memory_limit when running admin scripts.
515 * Some scripts may wish to actually set a limit, however, to avoid
516 * blowing up unexpectedly. We also support a --memory-limit option,
517 * to allow sysadmins to explicitly set one if they'd prefer to override
518 * defaults (or for people using Suhosin which yells at you for trying
519 * to disable the limits)
521 public function memoryLimit() {
522 $limit = $this->getOption( 'memory-limit', 'max' );
523 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
528 * Adjusts PHP's memory limit to better suit our needs, if needed.
530 protected function adjustMemoryLimit() {
531 $limit = $this->memoryLimit();
532 if ( $limit == 'max' ) {
533 $limit = -1; // no memory limit
535 if ( $limit != 'default' ) {
536 ini_set( 'memory_limit', $limit );
541 * Clear all params and arguments.
543 public function clearParamsAndArgs() {
544 $this->mOptions
= array();
545 $this->mArgs
= array();
546 $this->mInputLoaded
= false;
550 * Process command line arguments
551 * $mOptions becomes an array with keys set to the option names
552 * $mArgs becomes a zero-based array containing the non-option arguments
554 * @param $self String The name of the script, if any
555 * @param $opts Array An array of options, in form of key=>value
556 * @param $args Array An array of command line arguments
558 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
559 # If we were given opts or args, set those and return early
561 $this->mSelf
= $self;
562 $this->mInputLoaded
= true;
565 $this->mOptions
= $opts;
566 $this->mInputLoaded
= true;
569 $this->mArgs
= $args;
570 $this->mInputLoaded
= true;
573 # If we've already loaded input (either by user values or from $argv)
574 # skip on loading it again. The array_shift() will corrupt values if
575 # it's run again and again
576 if ( $this->mInputLoaded
) {
577 $this->loadSpecialVars();
582 $this->mSelf
= array_shift( $argv );
588 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
589 if ( $arg == '--' ) {
590 # End of options, remainder should be considered arguments
591 $arg = next( $argv );
592 while ( $arg !== false ) {
594 $arg = next( $argv );
597 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
599 $option = substr( $arg, 2 );
600 if ( array_key_exists( $option, $options ) ) {
601 $this->error( "\nERROR: $option parameter given twice\n" );
602 $this->maybeHelp( true );
604 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
605 $param = next( $argv );
606 if ( $param === false ) {
607 $this->error( "\nERROR: $option parameter needs a value after it\n" );
608 $this->maybeHelp( true );
610 $options[$option] = $param;
612 $bits = explode( '=', $option, 2 );
613 if ( count( $bits ) > 1 ) {
619 $options[$option] = $param;
621 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
623 for ( $p = 1; $p < strlen( $arg ); $p++
) {
624 $option = $arg { $p } ;
625 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
626 $option = $this->mShortParamsMap
[$option];
628 if ( array_key_exists( $option, $options ) ) {
629 $this->error( "\nERROR: $option parameter given twice\n" );
630 $this->maybeHelp( true );
632 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
633 $param = next( $argv );
634 if ( $param === false ) {
635 $this->error( "\nERROR: $option parameter needs a value after it\n" );
636 $this->maybeHelp( true );
638 $options[$option] = $param;
640 $options[$option] = 1;
648 $this->mOptions
= $options;
649 $this->mArgs
= $args;
650 $this->loadSpecialVars();
651 $this->mInputLoaded
= true;
655 * Run some validation checks on the params, etc
657 protected function validateParamsAndArgs() {
659 # Check to make sure we've got all the required options
660 foreach ( $this->mParams
as $opt => $info ) {
661 if ( $info['require'] && !$this->hasOption( $opt ) ) {
662 $this->error( "Param $opt required!" );
667 foreach ( $this->mArgList
as $k => $info ) {
668 if ( $info['require'] && !$this->hasArg( $k ) ) {
669 $this->error( 'Argument <' . $info['name'] . '> required!' );
675 $this->maybeHelp( true );
680 * Handle the special variables that are global to all scripts
682 protected function loadSpecialVars() {
683 if ( $this->hasOption( 'dbuser' ) ) {
684 $this->mDbUser
= $this->getOption( 'dbuser' );
686 if ( $this->hasOption( 'dbpass' ) ) {
687 $this->mDbPass
= $this->getOption( 'dbpass' );
689 if ( $this->hasOption( 'quiet' ) ) {
690 $this->mQuiet
= true;
692 if ( $this->hasOption( 'batch-size' ) ) {
693 $this->mBatchSize
= $this->getOption( 'batch-size' );
698 * Maybe show the help.
699 * @param $force boolean Whether to force the help to show, default false
701 protected function maybeHelp( $force = false ) {
702 if( !$force && !$this->hasOption( 'help' ) ) {
706 $screenWidth = 80; // TODO: Caculate this!
708 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
710 ksort( $this->mParams
);
711 $this->mQuiet
= false;
714 if ( $this->mDescription
) {
715 $this->output( "\n" . $this->mDescription
. "\n" );
717 $output = "\nUsage: php " . basename( $this->mSelf
);
719 // ... append parameters ...
720 if ( $this->mParams
) {
721 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
724 // ... and append arguments.
725 if ( $this->mArgList
) {
727 foreach ( $this->mArgList
as $k => $arg ) {
728 if ( $arg['require'] ) {
729 $output .= '<' . $arg['name'] . '>';
731 $output .= '[' . $arg['name'] . ']';
733 if ( $k < count( $this->mArgList
) - 1 )
737 $this->output( "$output\n\n" );
739 # TODO abstract some repetitive code below
741 // Generic parameters
742 $this->output( "Generic maintenance parameters:\n" );
743 foreach ( $this->mGenericParameters
as $par => $info ) {
744 if ( $info['shortName'] !== false ) {
745 $par .= " (-{$info['shortName']})";
748 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
749 "\n$tab$tab" ) . "\n"
752 $this->output( "\n" );
754 $scriptDependantParams = $this->mDependantParameters
;
755 if( count($scriptDependantParams) > 0 ) {
756 $this->output( "Script dependant parameters:\n" );
757 // Parameters description
758 foreach ( $scriptDependantParams as $par => $info ) {
759 if ( $info['shortName'] !== false ) {
760 $par .= " (-{$info['shortName']})";
763 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
764 "\n$tab$tab" ) . "\n"
767 $this->output( "\n" );
771 // Script specific parameters not defined on construction by
772 // Maintenance::addDefaultParams()
773 $scriptSpecificParams = array_diff_key(
774 # all script parameters:
776 # remove the Maintenance default parameters:
777 $this->mGenericParameters
,
778 $this->mDependantParameters
780 if( count($scriptSpecificParams) > 0 ) {
781 $this->output( "Script specific parameters:\n" );
782 // Parameters description
783 foreach ( $scriptSpecificParams as $par => $info ) {
784 if ( $info['shortName'] !== false ) {
785 $par .= " (-{$info['shortName']})";
788 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
789 "\n$tab$tab" ) . "\n"
792 $this->output( "\n" );
796 if( count( $this->mArgList
) > 0 ) {
797 $this->output( "Arguments:\n" );
798 // Arguments description
799 foreach ( $this->mArgList
as $info ) {
800 $openChar = $info['require'] ?
'<' : '[';
801 $closeChar = $info['require'] ?
'>' : ']';
803 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
804 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
807 $this->output( "\n" );
814 * Handle some last-minute setup here.
816 public function finalSetup() {
817 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
818 global $wgDBadminuser, $wgDBadminpassword;
819 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
821 # Turn off output buffering again, it might have been turned on in the settings files
822 if ( ob_get_level() ) {
826 $wgCommandLineMode = true;
829 if( $this->hasOption( 'server') ) {
830 $wgServer = $this->getOption( 'server', $wgServer );
833 # If these were passed, use them
834 if ( $this->mDbUser
) {
835 $wgDBadminuser = $this->mDbUser
;
837 if ( $this->mDbPass
) {
838 $wgDBadminpassword = $this->mDbPass
;
841 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
842 $wgDBuser = $wgDBadminuser;
843 $wgDBpassword = $wgDBadminpassword;
845 if ( $wgDBservers ) {
846 foreach ( $wgDBservers as $i => $server ) {
847 $wgDBservers[$i]['user'] = $wgDBuser;
848 $wgDBservers[$i]['password'] = $wgDBpassword;
851 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
852 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
853 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
855 LBFactory
::destroyInstance();
858 $this->afterFinalSetup();
860 $wgShowSQLErrors = true;
861 @set_time_limit
( 0 );
862 $this->adjustMemoryLimit();
866 * Execute a callback function at the end of initialisation
868 protected function afterFinalSetup() {
869 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
870 call_user_func( MW_CMDLINE_CALLBACK
);
875 * Potentially debug globals. Originally a feature only
878 public function globals() {
879 if ( $this->hasOption( 'globals' ) ) {
885 * Do setup specific to WMF
887 public function loadWikimediaSettings() {
888 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
890 if ( empty( $wgNoDBParam ) ) {
891 # Check if we were passed a db name
892 if ( isset( $this->mOptions
['wiki'] ) ) {
893 $db = $this->mOptions
['wiki'];
895 $db = array_shift( $this->mArgs
);
897 list( $site, $lang ) = $wgConf->siteFromDB( $db );
899 # If not, work out the language and site the old way
900 if ( is_null( $site ) ||
is_null( $lang ) ) {
906 if ( isset( $this->mArgs
[0] ) ) {
907 $site = array_shift( $this->mArgs
);
917 # This is for the IRC scripts, which now run as the apache user
918 # The apache user doesn't have access to the wikiadmin_pass command
919 if ( $_ENV['USER'] == 'apache' ) {
920 # if ( posix_geteuid() == 48 ) {
921 $wgUseNormalUser = true;
924 putenv( 'wikilang=' . $lang );
926 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
928 if ( $lang == 'test' && $site == 'wikipedia' ) {
929 define( 'TESTWIKI', 1 );
934 * Generic setup for most installs. Returns the location of LocalSettings
937 public function loadSettings() {
938 global $wgCommandLineMode, $IP;
940 if ( isset( $this->mOptions
['conf'] ) ) {
941 $settingsFile = $this->mOptions
['conf'];
942 } elseif ( defined("MW_CONFIG_FILE") ) {
943 $settingsFile = MW_CONFIG_FILE
;
945 $settingsFile = "$IP/LocalSettings.php";
947 if ( isset( $this->mOptions
['wiki'] ) ) {
948 $bits = explode( '-', $this->mOptions
['wiki'] );
949 if ( count( $bits ) == 1 ) {
952 define( 'MW_DB', $bits[0] );
953 define( 'MW_PREFIX', $bits[1] );
956 if ( !is_readable( $settingsFile ) ) {
957 $this->error( "A copy of your installation's LocalSettings.php\n" .
958 "must exist and be readable in the source directory.\n" .
959 "Use --conf to specify it." , true );
961 $wgCommandLineMode = true;
962 return $settingsFile;
966 * Support function for cleaning up redundant text records
967 * @param $delete Boolean: whether or not to actually delete the records
968 * @author Rob Church <robchur@gmail.com>
970 public function purgeRedundantText( $delete = true ) {
971 # Data should come off the master, wrapped in a transaction
972 $dbw = $this->getDB( DB_MASTER
);
975 $tbl_arc = $dbw->tableName( 'archive' );
976 $tbl_rev = $dbw->tableName( 'revision' );
977 $tbl_txt = $dbw->tableName( 'text' );
979 # Get "active" text records from the revisions table
980 $this->output( 'Searching for active text records in revisions table...' );
981 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
982 foreach ( $res as $row ) {
983 $cur[] = $row->rev_text_id
;
985 $this->output( "done.\n" );
987 # Get "active" text records from the archive table
988 $this->output( 'Searching for active text records in archive table...' );
989 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
990 foreach ( $res as $row ) {
991 $cur[] = $row->ar_text_id
;
993 $this->output( "done.\n" );
995 # Get the IDs of all text records not in these sets
996 $this->output( 'Searching for inactive text records...' );
997 $set = implode( ', ', $cur );
998 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
1000 foreach ( $res as $row ) {
1001 $old[] = $row->old_id
;
1003 $this->output( "done.\n" );
1005 # Inform the user of what we're going to do
1006 $count = count( $old );
1007 $this->output( "$count inactive items found.\n" );
1009 # Delete as appropriate
1010 if ( $delete && $count ) {
1011 $this->output( 'Deleting...' );
1012 $set = implode( ', ', $old );
1013 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
1014 $this->output( "done.\n" );
1022 * Get the maintenance directory.
1024 protected function getDir() {
1025 return dirname( __FILE__
);
1029 * Get the list of available maintenance scripts. Note
1030 * that if you call this _before_ calling doMaintenance
1031 * you won't have any extensions in it yet
1034 public static function getMaintenanceScripts() {
1035 global $wgMaintenanceScripts;
1036 return $wgMaintenanceScripts + self
::getCoreScripts();
1040 * Return all of the core maintenance scripts
1043 protected static function getCoreScripts() {
1044 if ( !self
::$mCoreScripts ) {
1046 dirname( __FILE__
),
1047 dirname( __FILE__
) . '/gearman',
1048 dirname( __FILE__
) . '/language',
1049 dirname( __FILE__
) . '/storage',
1051 self
::$mCoreScripts = array();
1052 foreach ( $paths as $p ) {
1053 $handle = opendir( $p );
1054 while ( ( $file = readdir( $handle ) ) !== false ) {
1055 if ( $file == 'Maintenance.php' ) {
1058 $file = $p . '/' . $file;
1059 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
1060 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1064 $vars = get_defined_vars();
1065 if ( array_key_exists( 'maintClass', $vars ) ) {
1066 self
::$mCoreScripts[$vars['maintClass']] = $file;
1069 closedir( $handle );
1072 return self
::$mCoreScripts;
1076 * Returns a database to be used by current maintenance script. It can be set by setDB().
1077 * If not set, wfGetDB() will be used.
1078 * This function has the same parameters as wfGetDB()
1080 * @return DatabaseBase
1082 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1083 if ( is_null( $this->mDb
) ) {
1084 return wfGetDB( $db, $groups, $wiki );
1091 * Sets database object to be returned by getDB().
1093 * @param $db DatabaseBase: Database object to be used
1095 public function setDB( &$db ) {
1100 * Lock the search index
1101 * @param &$db Database object
1103 private function lockSearchindex( &$db ) {
1104 $write = array( 'searchindex' );
1105 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1106 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1111 * @param &$db Database object
1113 private function unlockSearchindex( &$db ) {
1114 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1118 * Unlock and lock again
1119 * Since the lock is low-priority, queued reads will be able to complete
1120 * @param &$db Database object
1122 private function relockSearchindex( &$db ) {
1123 $this->unlockSearchindex( $db );
1124 $this->lockSearchindex( $db );
1128 * Perform a search index update with locking
1129 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1130 * @param $callback callback String: the function that will update the function.
1131 * @param $dbw DatabaseBase object
1134 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1138 if ( $maxLockTime ) {
1139 $this->output( " --- Waiting for lock ---" );
1140 $this->lockSearchindex( $dbw );
1142 $this->output( "\n" );
1145 # Loop through the results and do a search update
1146 foreach ( $results as $row ) {
1147 # Allow reads to be processed
1148 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1149 $this->output( " --- Relocking ---" );
1150 $this->relockSearchindex( $dbw );
1152 $this->output( "\n" );
1154 call_user_func( $callback, $dbw, $row );
1157 # Unlock searchindex
1158 if ( $maxLockTime ) {
1159 $this->output( " --- Unlocking --" );
1160 $this->unlockSearchindex( $dbw );
1161 $this->output( "\n" );
1167 * Update the searchindex table for a given pageid
1168 * @param $dbw Database: a database write handle
1169 * @param $pageId Integer: the page ID to update.
1171 public function updateSearchIndexForPage( $dbw, $pageId ) {
1172 // Get current revision
1173 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1176 $titleObj = $rev->getTitle();
1177 $title = $titleObj->getPrefixedDBkey();
1178 $this->output( "$title..." );
1179 # Update searchindex
1180 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1182 $this->output( "\n" );
1188 * Prompt the console for input
1189 * @param $prompt String what to begin the line with, like '> '
1190 * @return String response
1192 public static function readconsole( $prompt = '> ' ) {
1193 static $isatty = null;
1194 if ( is_null( $isatty ) ) {
1195 $isatty = posix_isatty( 0 /*STDIN*/ );
1198 if ( $isatty && function_exists( 'readline' ) ) {
1199 return readline( $prompt );
1202 $st = self
::readlineEmulation( $prompt );
1204 if ( feof( STDIN
) ) {
1207 $st = fgets( STDIN
, 1024 );
1210 if ( $st === false ) return false;
1211 $resp = trim( $st );
1217 * Emulate readline()
1218 * @param $prompt String what to begin the line with, like '> '
1221 private static function readlineEmulation( $prompt ) {
1222 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1223 if ( !wfIsWindows() && $bash ) {
1225 $encPrompt = wfEscapeShellArg( $prompt );
1226 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1227 $encCommand = wfEscapeShellArg( $command );
1228 $line = wfShellExec( "$bash -c $encCommand", $retval );
1230 if ( $retval == 0 ) {
1232 } elseif ( $retval == 127 ) {
1233 // Couldn't execute bash even though we thought we saw it.
1234 // Shell probably spit out an error message, sorry :(
1235 // Fall through to fgets()...
1242 // Fallback... we'll have no editing controls, EWWW
1243 if ( feof( STDIN
) ) {
1247 return fgets( STDIN
, 1024 );
1251 class FakeMaintenance
extends Maintenance
{
1252 protected $mSelf = "FakeMaintenanceScript";
1253 public function execute() {