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 // Include global constants, including MW_VERSION and MW_MIN_PHP_VERSION
24 require_once( dirname( dirname( __FILE__
) ) . '/includes/Defines.php' );
26 // Define this so scripts can easily find doMaintenance.php
27 define( 'RUN_MAINTENANCE_IF_MAIN', dirname( __FILE__
) . '/doMaintenance.php' );
28 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
32 // Make sure we're on PHP5 or better
33 if ( version_compare( PHP_VERSION
, MW_MIN_PHP_VERSION
) < 0 ) {
34 die ( "Sorry! This version of MediaWiki requires PHP " . MW_MIN_PHP_VERSION
. "; you are running " .
35 PHP_VERSION
. ".\n\n" .
36 "If you are sure you already have PHP " . MW_MIN_PHP_VERSION
. " or higher installed, it may be\n" .
37 "installed in a different path from PHP " . PHP_VERSION
. ". Check with your system\n" .
41 // Wrapper for posix_isatty()
42 if ( !function_exists( 'posix_isatty' ) ) {
43 # We default as considering stdin a tty (for nice readline methods)
44 # but treating stout as not a tty to avoid color codes
45 function posix_isatty( $fd ) {
51 * Abstract maintenance class for quickly writing and churning out
52 * maintenance scripts with minimal effort. All that _must_ be defined
53 * is the execute() method. See docs/maintenance.txt for more info
54 * and a quick demo of how to use it.
56 * @author Chad Horohoe <chad@anyonecanedit.org>
58 * @ingroup Maintenance
60 abstract class Maintenance
{
63 * Constants for DB access type
64 * @see Maintenance::getDbType()
70 // Const for getStdin()
71 const STDIN_ALL
= 'all';
73 // This is the desired params
74 protected $mParams = array();
76 // Array of mapping short parameters to long ones
77 protected $mShortParamsMap = array();
79 // Array of desired args
80 protected $mArgList = array();
82 // This is the list of options that were actually passed
83 protected $mOptions = array();
85 // This is the list of arguments that were actually passed
86 protected $mArgs = array();
88 // Name of the script currently running
91 // Special vars for params that are always used
92 protected $mQuiet = false;
93 protected $mDbUser, $mDbPass;
95 // A description of the script, children should change this
96 protected $mDescription = '';
98 // Have we already loaded our user input?
99 protected $mInputLoaded = false;
102 * Batch size. If a script supports this, they should set
103 * a default with setBatchSize()
107 protected $mBatchSize = null;
109 // Generic options added by addDefaultParams()
110 private $mGenericParameters = array();
111 // Generic options which might or not be supported by the script
112 private $mDependantParameters = array();
115 * List of all the core maintenance scripts. This is added
116 * to scripts added by extensions in $wgMaintenanceScripts
117 * and returned by getMaintenanceScripts()
119 protected static $mCoreScripts = null;
122 * Default constructor. Children should call this *first* if implementing
123 * their own constructors
125 public function __construct() {
126 // Setup $IP, using MW_INSTALL_PATH if it exists
128 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
129 ?
getenv( 'MW_INSTALL_PATH' )
130 : realpath( dirname( __FILE__
) . '/..' );
132 $this->addDefaultParams();
133 register_shutdown_function( array( $this, 'outputChanneled' ), false );
137 * Should we execute the maintenance script, or just allow it to be included
138 * as a standalone class? It checks that the call stack only includes this
139 * function and a require (meaning was called from the file scope)
143 public static function shouldExecute() {
144 $bt = debug_backtrace();
145 if( count( $bt ) !== 2 ) {
148 return in_array( $bt[1]['function'], array( 'require_once', 'require', 'include' ) ) &&
149 $bt[0]['class'] == 'Maintenance' &&
150 $bt[0]['function'] == 'shouldExecute';
154 * Do the actual work. All child classes will need to implement this
156 abstract public function execute();
159 * Add a parameter to the script. Will be displayed on --help
160 * with the associated description
162 * @param $name String: the name of the param (help, version, etc)
163 * @param $description String: the description of the param to show on --help
164 * @param $required Boolean: is the param required?
165 * @param $withArg Boolean: is an argument required with this option?
166 * @param $shortName String: character to use as short name
168 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
169 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
170 if ( $shortName !== false ) {
171 $this->mShortParamsMap
[$shortName] = $name;
176 * Checks to see if a particular param exists.
177 * @param $name String: the name of the param
180 protected function hasOption( $name ) {
181 return isset( $this->mOptions
[$name] );
185 * Get an option, or return the default
186 * @param $name String: the name of the param
187 * @param $default Mixed: anything you want, default null
190 protected function getOption( $name, $default = null ) {
191 if ( $this->hasOption( $name ) ) {
192 return $this->mOptions
[$name];
194 // Set it so we don't have to provide the default again
195 $this->mOptions
[$name] = $default;
196 return $this->mOptions
[$name];
201 * Add some args that are needed
202 * @param $arg String: name of the arg, like 'start'
203 * @param $description String: short description of the arg
204 * @param $required Boolean: is this required?
206 protected function addArg( $arg, $description, $required = true ) {
207 $this->mArgList
[] = array(
209 'desc' => $description,
210 'require' => $required
215 * Remove an option. Useful for removing options that won't be used in your script.
216 * @param $name String: the option to remove.
218 protected function deleteOption( $name ) {
219 unset( $this->mParams
[$name] );
223 * Set the description text.
224 * @param $text String: the text of the description
226 protected function addDescription( $text ) {
227 $this->mDescription
= $text;
231 * Does a given argument exist?
232 * @param $argId Integer: the integer value (from zero) for the arg
235 protected function hasArg( $argId = 0 ) {
236 return isset( $this->mArgs
[$argId] );
241 * @param $argId Integer: the integer value (from zero) for the arg
242 * @param $default Mixed: the default if it doesn't exist
245 protected function getArg( $argId = 0, $default = null ) {
246 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
250 * Set the batch size.
251 * @param $s Integer: the number of operations to do in a batch
253 protected function setBatchSize( $s = 0 ) {
254 $this->mBatchSize
= $s;
258 * Get the script's name
261 public function getName() {
266 * Return input from stdin.
267 * @param $len Integer: the number of bytes to read. If null,
268 * just return the handle. Maintenance::STDIN_ALL returns
272 protected function getStdin( $len = null ) {
273 if ( $len == Maintenance
::STDIN_ALL
) {
274 return file_get_contents( 'php://stdin' );
276 $f = fopen( 'php://stdin', 'rt' );
280 $input = fgets( $f, $len );
282 return rtrim( $input );
285 public function isQuiet() {
286 return $this->mQuiet
;
290 * Throw some output to the user. Scripts can call this with no fears,
291 * as we handle all --quiet stuff here
292 * @param $out String: the text to show to the user
293 * @param $channel Mixed: unique identifier for the channel. See
294 * function outputChanneled.
296 protected function output( $out, $channel = null ) {
297 if ( $this->mQuiet
) {
300 if ( $channel === null ) {
301 $this->cleanupChanneled();
303 $f = fopen( 'php://stdout', 'w' );
308 $out = preg_replace( '/\n\z/', '', $out );
309 $this->outputChanneled( $out, $channel );
314 * Throw an error to the user. Doesn't respect --quiet, so don't use
315 * this for non-error output
316 * @param $err String: the error to display
317 * @param $die Boolean: If true, go ahead and die out.
319 protected function error( $err, $die = false ) {
320 $this->outputChanneled( false );
321 if ( php_sapi_name() == 'cli' ) {
322 fwrite( STDERR
, $err . "\n" );
324 $f = fopen( 'php://stderr', 'w' );
325 fwrite( $f, $err . "\n" );
333 private $atLineStart = true;
334 private $lastChannel = null;
337 * Clean up channeled output. Output a newline if necessary.
339 public function cleanupChanneled() {
340 if ( !$this->atLineStart
) {
341 $handle = fopen( 'php://stdout', 'w' );
342 fwrite( $handle, "\n" );
344 $this->atLineStart
= true;
349 * Message outputter with channeled message support. Messages on the
350 * same channel are concatenated, but any intervening messages in another
351 * channel start a new line.
352 * @param $msg String: the message without trailing newline
353 * @param $channel Channel identifier or null for no
354 * channel. Channel comparison uses ===.
356 public function outputChanneled( $msg, $channel = null ) {
357 if ( $msg === false ) {
358 $this->cleanupChanneled();
362 $handle = fopen( 'php://stdout', 'w' );
364 // End the current line if necessary
365 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
366 fwrite( $handle, "\n" );
369 fwrite( $handle, $msg );
371 $this->atLineStart
= false;
372 if ( $channel === null ) {
373 // For unchanneled messages, output trailing newline immediately
374 fwrite( $handle, "\n" );
375 $this->atLineStart
= true;
377 $this->lastChannel
= $channel;
384 * Does the script need different DB access? By default, we give Maintenance
385 * scripts normal rights to the DB. Sometimes, a script needs admin rights
386 * access for a reason and sometimes they want no access. Subclasses should
387 * override and return one of the following values, as needed:
388 * Maintenance::DB_NONE - For no DB access at all
389 * Maintenance::DB_STD - For normal DB access, default
390 * Maintenance::DB_ADMIN - For admin DB access
393 public function getDbType() {
394 return Maintenance
::DB_STD
;
398 * Add the default parameters to the scripts
400 protected function addDefaultParams() {
402 # Generic (non script dependant) options:
404 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
405 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
406 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
407 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
408 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
409 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
410 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
411 "http://en.wikipedia.org. This is sometimes necessary because " .
412 "server name detection may fail in command line scripts.", false, true );
414 # Save generic options to display them separately in help
415 $this->mGenericParameters
= $this->mParams
;
417 # Script dependant options:
419 // If we support a DB, show the options
420 if ( $this->getDbType() > 0 ) {
421 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
422 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
424 // If we support $mBatchSize, show the option
425 if ( $this->mBatchSize
) {
426 $this->addOption( 'batch-size', 'Run this many operations ' .
427 'per batch, default: ' . $this->mBatchSize
, false, true );
429 # Save additional script dependant options to display
430 #Â them separately in help
431 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
435 * Run a child maintenance script. Pass all of the current arguments
437 * @param $maintClass String: a name of a child maintenance class
438 * @param $classFile String: full path of where the child is
439 * @return Maintenance child
441 public function runChild( $maintClass, $classFile = null ) {
442 // Make sure the class is loaded first
443 if ( !MWInit
::classExists( $maintClass ) ) {
445 require_once( $classFile );
447 if ( !MWInit
::classExists( $maintClass ) ) {
448 $this->error( "Cannot spawn child: $maintClass" );
452 $child = new $maintClass();
453 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
458 * Do some sanity checking and basic setup
460 public function setup() {
461 global $wgCommandLineMode, $wgRequestTime;
463 # Abort if called from a web server
464 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
465 $this->error( 'This script must be run from the command line', true );
468 # Make sure we can handle script parameters
469 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
470 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
473 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
474 // Send PHP warnings and errors to stderr instead of stdout.
475 // This aids in diagnosing problems, while keeping messages
476 // out of redirected output.
477 if ( ini_get( 'display_errors' ) ) {
478 ini_set( 'display_errors', 'stderr' );
481 // Don't touch the setting on earlier versions of PHP,
482 // as setting it would disable output if you'd wanted it.
484 // Note that exceptions are also sent to stderr when
485 // command-line mode is on, regardless of PHP version.
488 $this->loadParamsAndArgs();
491 # Set the memory limit
492 # Note we need to set it again later in cache LocalSettings changed it
493 $this->adjustMemoryLimit();
495 # Set max execution time to 0 (no limit). PHP.net says that
496 # "When running PHP from the command line the default setting is 0."
497 # But sometimes this doesn't seem to be the case.
498 ini_set( 'max_execution_time', 0 );
500 $wgRequestTime = microtime( true );
502 # Define us as being in MediaWiki
503 define( 'MEDIAWIKI', true );
505 $wgCommandLineMode = true;
506 # Turn off output buffering if it's on
509 $this->validateParamsAndArgs();
513 * Normally we disable the memory_limit when running admin scripts.
514 * Some scripts may wish to actually set a limit, however, to avoid
515 * blowing up unexpectedly. We also support a --memory-limit option,
516 * to allow sysadmins to explicitly set one if they'd prefer to override
517 * defaults (or for people using Suhosin which yells at you for trying
518 * to disable the limits)
520 public function memoryLimit() {
521 $limit = $this->getOption( 'memory-limit', 'max' );
522 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
527 * Adjusts PHP's memory limit to better suit our needs, if needed.
529 protected function adjustMemoryLimit() {
530 $limit = $this->memoryLimit();
531 if ( $limit == 'max' ) {
532 $limit = -1; // no memory limit
534 if ( $limit != 'default' ) {
535 ini_set( 'memory_limit', $limit );
540 * Clear all params and arguments.
542 public function clearParamsAndArgs() {
543 $this->mOptions
= array();
544 $this->mArgs
= array();
545 $this->mInputLoaded
= false;
549 * Process command line arguments
550 * $mOptions becomes an array with keys set to the option names
551 * $mArgs becomes a zero-based array containing the non-option arguments
553 * @param $self String The name of the script, if any
554 * @param $opts Array An array of options, in form of key=>value
555 * @param $args Array An array of command line arguments
557 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
558 # If we were given opts or args, set those and return early
560 $this->mSelf
= $self;
561 $this->mInputLoaded
= true;
564 $this->mOptions
= $opts;
565 $this->mInputLoaded
= true;
568 $this->mArgs
= $args;
569 $this->mInputLoaded
= true;
572 # If we've already loaded input (either by user values or from $argv)
573 # skip on loading it again. The array_shift() will corrupt values if
574 # it's run again and again
575 if ( $this->mInputLoaded
) {
576 $this->loadSpecialVars();
581 $this->mSelf
= array_shift( $argv );
587 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
588 if ( $arg == '--' ) {
589 # End of options, remainder should be considered arguments
590 $arg = next( $argv );
591 while ( $arg !== false ) {
593 $arg = next( $argv );
596 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
598 $option = substr( $arg, 2 );
599 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
600 $param = next( $argv );
601 if ( $param === false ) {
602 $this->error( "\nERROR: $option needs a value after it\n" );
603 $this->maybeHelp( true );
605 $options[$option] = $param;
607 $bits = explode( '=', $option, 2 );
608 if ( count( $bits ) > 1 ) {
614 $options[$option] = $param;
616 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
618 for ( $p = 1; $p < strlen( $arg ); $p++
) {
619 $option = $arg { $p } ;
620 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
621 $option = $this->mShortParamsMap
[$option];
623 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
624 $param = next( $argv );
625 if ( $param === false ) {
626 $this->error( "\nERROR: $option needs a value after it\n" );
627 $this->maybeHelp( true );
629 $options[$option] = $param;
631 $options[$option] = 1;
639 $this->mOptions
= $options;
640 $this->mArgs
= $args;
641 $this->loadSpecialVars();
642 $this->mInputLoaded
= true;
646 * Run some validation checks on the params, etc
648 protected function validateParamsAndArgs() {
650 # Check to make sure we've got all the required options
651 foreach ( $this->mParams
as $opt => $info ) {
652 if ( $info['require'] && !$this->hasOption( $opt ) ) {
653 $this->error( "Param $opt required!" );
658 foreach ( $this->mArgList
as $k => $info ) {
659 if ( $info['require'] && !$this->hasArg( $k ) ) {
660 $this->error( 'Argument <' . $info['name'] . '> required!' );
666 $this->maybeHelp( true );
671 * Handle the special variables that are global to all scripts
673 protected function loadSpecialVars() {
674 if ( $this->hasOption( 'dbuser' ) ) {
675 $this->mDbUser
= $this->getOption( 'dbuser' );
677 if ( $this->hasOption( 'dbpass' ) ) {
678 $this->mDbPass
= $this->getOption( 'dbpass' );
680 if ( $this->hasOption( 'quiet' ) ) {
681 $this->mQuiet
= true;
683 if ( $this->hasOption( 'batch-size' ) ) {
684 $this->mBatchSize
= $this->getOption( 'batch-size' );
689 * Maybe show the help.
690 * @param $force boolean Whether to force the help to show, default false
692 protected function maybeHelp( $force = false ) {
693 if( !$force && !$this->hasOption( 'help' ) ) {
697 $screenWidth = 80; // TODO: Caculate this!
699 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
701 ksort( $this->mParams
);
702 $this->mQuiet
= false;
705 if ( $this->mDescription
) {
706 $this->output( "\n" . $this->mDescription
. "\n" );
708 $output = "\nUsage: php " . basename( $this->mSelf
);
710 // ... append parameters ...
711 if ( $this->mParams
) {
712 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
715 // ... and append arguments.
716 if ( $this->mArgList
) {
718 foreach ( $this->mArgList
as $k => $arg ) {
719 if ( $arg['require'] ) {
720 $output .= '<' . $arg['name'] . '>';
722 $output .= '[' . $arg['name'] . ']';
724 if ( $k < count( $this->mArgList
) - 1 )
728 $this->output( "$output\n\n" );
730 # TODO abstract some repetitive code below
732 // Generic parameters
733 $this->output( "Generic maintenance parameters:\n" );
734 foreach ( $this->mGenericParameters
as $par => $info ) {
735 if ( $info['shortName'] !== false ) {
736 $par .= " (-{$info['shortName']})";
739 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
740 "\n$tab$tab" ) . "\n"
743 $this->output( "\n" );
745 $scriptDependantParams = $this->mDependantParameters
;
746 if( count($scriptDependantParams) > 0 ) {
747 $this->output( "Script dependant parameters:\n" );
748 // Parameters description
749 foreach ( $scriptDependantParams as $par => $info ) {
750 if ( $info['shortName'] !== false ) {
751 $par .= " (-{$info['shortName']})";
754 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
755 "\n$tab$tab" ) . "\n"
758 $this->output( "\n" );
762 // Script specific parameters not defined on construction by
763 // Maintenance::addDefaultParams()
764 $scriptSpecificParams = array_diff_key(
765 # all script parameters:
767 # remove the Maintenance default parameters:
768 $this->mGenericParameters
,
769 $this->mDependantParameters
771 if( count($scriptSpecificParams) > 0 ) {
772 $this->output( "Script specific parameters:\n" );
773 // Parameters description
774 foreach ( $scriptSpecificParams as $par => $info ) {
775 if ( $info['shortName'] !== false ) {
776 $par .= " (-{$info['shortName']})";
779 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
780 "\n$tab$tab" ) . "\n"
783 $this->output( "\n" );
787 if( count( $this->mArgList
) > 0 ) {
788 $this->output( "Arguments:\n" );
789 // Arguments description
790 foreach ( $this->mArgList
as $info ) {
791 $openChar = $info['require'] ?
'<' : '[';
792 $closeChar = $info['require'] ?
'>' : ']';
794 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
795 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
798 $this->output( "\n" );
805 * Handle some last-minute setup here.
807 public function finalSetup() {
808 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
809 global $wgDBadminuser, $wgDBadminpassword;
810 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
812 # Turn off output buffering again, it might have been turned on in the settings files
813 if ( ob_get_level() ) {
817 $wgCommandLineMode = true;
820 if( $this->hasOption( 'server') ) {
821 $wgServer = $this->getOption( 'server', $wgServer );
824 # If these were passed, use them
825 if ( $this->mDbUser
) {
826 $wgDBadminuser = $this->mDbUser
;
828 if ( $this->mDbPass
) {
829 $wgDBadminpassword = $this->mDbPass
;
832 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
833 $wgDBuser = $wgDBadminuser;
834 $wgDBpassword = $wgDBadminpassword;
836 if ( $wgDBservers ) {
837 foreach ( $wgDBservers as $i => $server ) {
838 $wgDBservers[$i]['user'] = $wgDBuser;
839 $wgDBservers[$i]['password'] = $wgDBpassword;
842 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
843 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
844 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
846 LBFactory
::destroyInstance();
849 $this->afterFinalSetup();
851 $wgShowSQLErrors = true;
852 @set_time_limit
( 0 );
853 $this->adjustMemoryLimit();
857 * Execute a callback function at the end of initialisation
859 protected function afterFinalSetup() {
860 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
861 call_user_func( MW_CMDLINE_CALLBACK
);
866 * Potentially debug globals. Originally a feature only
869 public function globals() {
870 if ( $this->hasOption( 'globals' ) ) {
876 * Do setup specific to WMF
878 public function loadWikimediaSettings() {
879 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
881 if ( empty( $wgNoDBParam ) ) {
882 # Check if we were passed a db name
883 if ( isset( $this->mOptions
['wiki'] ) ) {
884 $db = $this->mOptions
['wiki'];
886 $db = array_shift( $this->mArgs
);
888 list( $site, $lang ) = $wgConf->siteFromDB( $db );
890 # If not, work out the language and site the old way
891 if ( is_null( $site ) ||
is_null( $lang ) ) {
897 if ( isset( $this->mArgs
[0] ) ) {
898 $site = array_shift( $this->mArgs
);
908 # This is for the IRC scripts, which now run as the apache user
909 # The apache user doesn't have access to the wikiadmin_pass command
910 if ( $_ENV['USER'] == 'apache' ) {
911 # if ( posix_geteuid() == 48 ) {
912 $wgUseNormalUser = true;
915 putenv( 'wikilang=' . $lang );
917 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
919 if ( $lang == 'test' && $site == 'wikipedia' ) {
920 define( 'TESTWIKI', 1 );
925 * Generic setup for most installs. Returns the location of LocalSettings
928 public function loadSettings() {
929 global $wgWikiFarm, $wgCommandLineMode, $IP;
932 if ( isset( $this->mOptions
['conf'] ) ) {
933 $settingsFile = $this->mOptions
['conf'];
934 } else if ( defined("MW_CONFIG_FILE") ) {
935 $settingsFile = MW_CONFIG_FILE
;
937 $settingsFile = "$IP/LocalSettings.php";
939 if ( isset( $this->mOptions
['wiki'] ) ) {
940 $bits = explode( '-', $this->mOptions
['wiki'] );
941 if ( count( $bits ) == 1 ) {
944 define( 'MW_DB', $bits[0] );
945 define( 'MW_PREFIX', $bits[1] );
948 if ( !is_readable( $settingsFile ) ) {
949 $this->error( "A copy of your installation's LocalSettings.php\n" .
950 "must exist and be readable in the source directory.\n" .
951 "Use --conf to specify it." , true );
953 $wgCommandLineMode = true;
954 return $settingsFile;
958 * Support function for cleaning up redundant text records
959 * @param $delete Boolean: whether or not to actually delete the records
960 * @author Rob Church <robchur@gmail.com>
962 public function purgeRedundantText( $delete = true ) {
963 # Data should come off the master, wrapped in a transaction
964 $dbw = wfGetDB( DB_MASTER
);
967 $tbl_arc = $dbw->tableName( 'archive' );
968 $tbl_rev = $dbw->tableName( 'revision' );
969 $tbl_txt = $dbw->tableName( 'text' );
971 # Get "active" text records from the revisions table
972 $this->output( 'Searching for active text records in revisions table...' );
973 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
974 foreach ( $res as $row ) {
975 $cur[] = $row->rev_text_id
;
977 $this->output( "done.\n" );
979 # Get "active" text records from the archive table
980 $this->output( 'Searching for active text records in archive table...' );
981 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
982 foreach ( $res as $row ) {
983 $cur[] = $row->ar_text_id
;
985 $this->output( "done.\n" );
987 # Get the IDs of all text records not in these sets
988 $this->output( 'Searching for inactive text records...' );
989 $set = implode( ', ', $cur );
990 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
992 foreach ( $res as $row ) {
993 $old[] = $row->old_id
;
995 $this->output( "done.\n" );
997 # Inform the user of what we're going to do
998 $count = count( $old );
999 $this->output( "$count inactive items found.\n" );
1001 # Delete as appropriate
1002 if ( $delete && $count ) {
1003 $this->output( 'Deleting...' );
1004 $set = implode( ', ', $old );
1005 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
1006 $this->output( "done.\n" );
1014 * Get the maintenance directory.
1016 protected function getDir() {
1017 return dirname( __FILE__
);
1021 * Get the list of available maintenance scripts. Note
1022 * that if you call this _before_ calling doMaintenance
1023 * you won't have any extensions in it yet
1026 public static function getMaintenanceScripts() {
1027 global $wgMaintenanceScripts;
1028 return $wgMaintenanceScripts + self
::getCoreScripts();
1032 * Return all of the core maintenance scripts
1035 protected static function getCoreScripts() {
1036 if ( !self
::$mCoreScripts ) {
1038 dirname( __FILE__
),
1039 dirname( __FILE__
) . '/gearman',
1040 dirname( __FILE__
) . '/language',
1041 dirname( __FILE__
) . '/storage',
1043 self
::$mCoreScripts = array();
1044 foreach ( $paths as $p ) {
1045 $handle = opendir( $p );
1046 while ( ( $file = readdir( $handle ) ) !== false ) {
1047 if ( $file == 'Maintenance.php' ) {
1050 $file = $p . '/' . $file;
1051 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
1052 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1056 $vars = get_defined_vars();
1057 if ( array_key_exists( 'maintClass', $vars ) ) {
1058 self
::$mCoreScripts[$vars['maintClass']] = $file;
1061 closedir( $handle );
1064 return self
::$mCoreScripts;
1068 * Lock the search index
1069 * @param &$db Database object
1071 private function lockSearchindex( &$db ) {
1072 $write = array( 'searchindex' );
1073 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1074 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1079 * @param &$db Database object
1081 private function unlockSearchindex( &$db ) {
1082 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1086 * Unlock and lock again
1087 * Since the lock is low-priority, queued reads will be able to complete
1088 * @param &$db Database object
1090 private function relockSearchindex( &$db ) {
1091 $this->unlockSearchindex( $db );
1092 $this->lockSearchindex( $db );
1096 * Perform a search index update with locking
1097 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1098 * @param $callback callback String: the function that will update the function.
1099 * @param $dbw DatabaseBase object
1102 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1106 if ( $maxLockTime ) {
1107 $this->output( " --- Waiting for lock ---" );
1108 $this->lockSearchindex( $dbw );
1110 $this->output( "\n" );
1113 # Loop through the results and do a search update
1114 foreach ( $results as $row ) {
1115 # Allow reads to be processed
1116 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1117 $this->output( " --- Relocking ---" );
1118 $this->relockSearchindex( $dbw );
1120 $this->output( "\n" );
1122 call_user_func( $callback, $dbw, $row );
1125 # Unlock searchindex
1126 if ( $maxLockTime ) {
1127 $this->output( " --- Unlocking --" );
1128 $this->unlockSearchindex( $dbw );
1129 $this->output( "\n" );
1135 * Update the searchindex table for a given pageid
1136 * @param $dbw Database: a database write handle
1137 * @param $pageId Integer: the page ID to update.
1139 public function updateSearchIndexForPage( $dbw, $pageId ) {
1140 // Get current revision
1141 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1144 $titleObj = $rev->getTitle();
1145 $title = $titleObj->getPrefixedDBkey();
1146 $this->output( "$title..." );
1147 # Update searchindex
1148 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1150 $this->output( "\n" );
1156 * Prompt the console for input
1157 * @param $prompt String what to begin the line with, like '> '
1158 * @return String response
1160 public static function readconsole( $prompt = '> ' ) {
1161 static $isatty = null;
1162 if ( is_null( $isatty ) ) {
1163 $isatty = posix_isatty( 0 /*STDIN*/ );
1166 if ( $isatty && function_exists( 'readline' ) ) {
1167 return readline( $prompt );
1170 $st = self
::readlineEmulation( $prompt );
1172 if ( feof( STDIN
) ) {
1175 $st = fgets( STDIN
, 1024 );
1178 if ( $st === false ) return false;
1179 $resp = trim( $st );
1185 * Emulate readline()
1186 * @param $prompt String what to begin the line with, like '> '
1189 private static function readlineEmulation( $prompt ) {
1190 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1191 if ( !wfIsWindows() && $bash ) {
1193 $encPrompt = wfEscapeShellArg( $prompt );
1194 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1195 $encCommand = wfEscapeShellArg( $command );
1196 $line = wfShellExec( "$bash -c $encCommand", $retval );
1198 if ( $retval == 0 ) {
1200 } elseif ( $retval == 127 ) {
1201 // Couldn't execute bash even though we thought we saw it.
1202 // Shell probably spit out an error message, sorry :(
1203 // Fall through to fgets()...
1210 // Fallback... we'll have no editing controls, EWWW
1211 if ( feof( STDIN
) ) {
1215 return fgets( STDIN
, 1024 );
1219 class FakeMaintenance
extends Maintenance
{
1220 protected $mSelf = "FakeMaintenanceScript";
1221 public function execute() {