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 ( version_compare( PHP_VERSION
, '5.2.3' ) < 0 ) {
31 die ( "Sorry! This version of MediaWiki requires PHP 5.2.3; you are running " .
32 PHP_VERSION
. ".\n\n" .
33 "If you are sure you already have PHP 5.2.3 or higher installed, it may be\n" .
34 "installed in a different path from PHP " . PHP_VERSION
. ". Check with your system\n" .
38 // Wrapper for posix_isatty()
39 if ( !function_exists( 'posix_isatty' ) ) {
40 # We default as considering stdin a tty (for nice readline methods)
41 # but treating stout as not a tty to avoid color codes
42 function posix_isatty( $fd ) {
48 * Abstract maintenance class for quickly writing and churning out
49 * maintenance scripts with minimal effort. All that _must_ be defined
50 * is the execute() method. See docs/maintenance.txt for more info
51 * and a quick demo of how to use it.
53 * @author Chad Horohoe <chad@anyonecanedit.org>
55 * @ingroup Maintenance
57 abstract class Maintenance
{
60 * Constants for DB access type
61 * @see Maintenance::getDbType()
67 // Const for getStdin()
68 const STDIN_ALL
= 'all';
70 // This is the desired params
71 protected $mParams = array();
73 // Array of mapping short parameters to long ones
74 protected $mShortParamsMap = array();
76 // Array of desired args
77 protected $mArgList = array();
79 // This is the list of options that were actually passed
80 protected $mOptions = array();
82 // This is the list of arguments that were actually passed
83 protected $mArgs = array();
85 // Name of the script currently running
88 // Special vars for params that are always used
89 protected $mQuiet = false;
90 protected $mDbUser, $mDbPass;
92 // A description of the script, children should change this
93 protected $mDescription = '';
95 // Have we already loaded our user input?
96 protected $mInputLoaded = false;
99 * Batch size. If a script supports this, they should set
100 * a default with setBatchSize()
104 protected $mBatchSize = null;
106 // Generic options added by addDefaultParams()
107 private $mGenericParameters = array();
108 // Generic options which might or not be supported by the script
109 private $mDependantParameters = array();
111 // Used by getDD() / setDB()
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
);
454 if ( !is_null( $this->mDb
) ) {
455 $child->setDB( $this->mDb
);
461 * Do some sanity checking and basic setup
463 public function setup() {
464 global $wgCommandLineMode, $wgRequestTime;
466 # Abort if called from a web server
467 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
468 $this->error( 'This script must be run from the command line', true );
471 # Make sure we can handle script parameters
472 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
473 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
476 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
477 // Send PHP warnings and errors to stderr instead of stdout.
478 // This aids in diagnosing problems, while keeping messages
479 // out of redirected output.
480 if ( ini_get( 'display_errors' ) ) {
481 ini_set( 'display_errors', 'stderr' );
484 // Don't touch the setting on earlier versions of PHP,
485 // as setting it would disable output if you'd wanted it.
487 // Note that exceptions are also sent to stderr when
488 // command-line mode is on, regardless of PHP version.
491 $this->loadParamsAndArgs();
494 # Set the memory limit
495 # Note we need to set it again later in cache LocalSettings changed it
496 $this->adjustMemoryLimit();
498 # Set max execution time to 0 (no limit). PHP.net says that
499 # "When running PHP from the command line the default setting is 0."
500 # But sometimes this doesn't seem to be the case.
501 ini_set( 'max_execution_time', 0 );
503 $wgRequestTime = microtime( true );
505 # Define us as being in MediaWiki
506 define( 'MEDIAWIKI', true );
508 $wgCommandLineMode = true;
509 # Turn off output buffering if it's on
512 $this->validateParamsAndArgs();
516 * Normally we disable the memory_limit when running admin scripts.
517 * Some scripts may wish to actually set a limit, however, to avoid
518 * blowing up unexpectedly. We also support a --memory-limit option,
519 * to allow sysadmins to explicitly set one if they'd prefer to override
520 * defaults (or for people using Suhosin which yells at you for trying
521 * to disable the limits)
523 public function memoryLimit() {
524 $limit = $this->getOption( 'memory-limit', 'max' );
525 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
530 * Adjusts PHP's memory limit to better suit our needs, if needed.
532 protected function adjustMemoryLimit() {
533 $limit = $this->memoryLimit();
534 if ( $limit == 'max' ) {
535 $limit = -1; // no memory limit
537 if ( $limit != 'default' ) {
538 ini_set( 'memory_limit', $limit );
543 * Clear all params and arguments.
545 public function clearParamsAndArgs() {
546 $this->mOptions
= array();
547 $this->mArgs
= array();
548 $this->mInputLoaded
= false;
552 * Process command line arguments
553 * $mOptions becomes an array with keys set to the option names
554 * $mArgs becomes a zero-based array containing the non-option arguments
556 * @param $self String The name of the script, if any
557 * @param $opts Array An array of options, in form of key=>value
558 * @param $args Array An array of command line arguments
560 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
561 # If we were given opts or args, set those and return early
563 $this->mSelf
= $self;
564 $this->mInputLoaded
= true;
567 $this->mOptions
= $opts;
568 $this->mInputLoaded
= true;
571 $this->mArgs
= $args;
572 $this->mInputLoaded
= true;
575 # If we've already loaded input (either by user values or from $argv)
576 # skip on loading it again. The array_shift() will corrupt values if
577 # it's run again and again
578 if ( $this->mInputLoaded
) {
579 $this->loadSpecialVars();
584 $this->mSelf
= array_shift( $argv );
590 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
591 if ( $arg == '--' ) {
592 # End of options, remainder should be considered arguments
593 $arg = next( $argv );
594 while ( $arg !== false ) {
596 $arg = next( $argv );
599 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
601 $option = substr( $arg, 2 );
602 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
603 $param = next( $argv );
604 if ( $param === false ) {
605 $this->error( "\nERROR: $option needs a value after it\n" );
606 $this->maybeHelp( true );
608 $options[$option] = $param;
610 $bits = explode( '=', $option, 2 );
611 if ( count( $bits ) > 1 ) {
617 $options[$option] = $param;
619 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
621 for ( $p = 1; $p < strlen( $arg ); $p++
) {
622 $option = $arg { $p } ;
623 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
624 $option = $this->mShortParamsMap
[$option];
626 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
627 $param = next( $argv );
628 if ( $param === false ) {
629 $this->error( "\nERROR: $option needs a value after it\n" );
630 $this->maybeHelp( true );
632 $options[$option] = $param;
634 $options[$option] = 1;
642 $this->mOptions
= $options;
643 $this->mArgs
= $args;
644 $this->loadSpecialVars();
645 $this->mInputLoaded
= true;
649 * Run some validation checks on the params, etc
651 protected function validateParamsAndArgs() {
653 # Check to make sure we've got all the required options
654 foreach ( $this->mParams
as $opt => $info ) {
655 if ( $info['require'] && !$this->hasOption( $opt ) ) {
656 $this->error( "Param $opt required!" );
661 foreach ( $this->mArgList
as $k => $info ) {
662 if ( $info['require'] && !$this->hasArg( $k ) ) {
663 $this->error( 'Argument <' . $info['name'] . '> required!' );
669 $this->maybeHelp( true );
674 * Handle the special variables that are global to all scripts
676 protected function loadSpecialVars() {
677 if ( $this->hasOption( 'dbuser' ) ) {
678 $this->mDbUser
= $this->getOption( 'dbuser' );
680 if ( $this->hasOption( 'dbpass' ) ) {
681 $this->mDbPass
= $this->getOption( 'dbpass' );
683 if ( $this->hasOption( 'quiet' ) ) {
684 $this->mQuiet
= true;
686 if ( $this->hasOption( 'batch-size' ) ) {
687 $this->mBatchSize
= $this->getOption( 'batch-size' );
692 * Maybe show the help.
693 * @param $force boolean Whether to force the help to show, default false
695 protected function maybeHelp( $force = false ) {
696 if( !$force && !$this->hasOption( 'help' ) ) {
700 $screenWidth = 80; // TODO: Caculate this!
702 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
704 ksort( $this->mParams
);
705 $this->mQuiet
= false;
708 if ( $this->mDescription
) {
709 $this->output( "\n" . $this->mDescription
. "\n" );
711 $output = "\nUsage: php " . basename( $this->mSelf
);
713 // ... append parameters ...
714 if ( $this->mParams
) {
715 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
718 // ... and append arguments.
719 if ( $this->mArgList
) {
721 foreach ( $this->mArgList
as $k => $arg ) {
722 if ( $arg['require'] ) {
723 $output .= '<' . $arg['name'] . '>';
725 $output .= '[' . $arg['name'] . ']';
727 if ( $k < count( $this->mArgList
) - 1 )
731 $this->output( "$output\n\n" );
733 # TODO abstract some repetitive code below
735 // Generic parameters
736 $this->output( "Generic maintenance parameters:\n" );
737 foreach ( $this->mGenericParameters
as $par => $info ) {
738 if ( $info['shortName'] !== false ) {
739 $par .= " (-{$info['shortName']})";
742 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
743 "\n$tab$tab" ) . "\n"
746 $this->output( "\n" );
748 $scriptDependantParams = $this->mDependantParameters
;
749 if( count($scriptDependantParams) > 0 ) {
750 $this->output( "Script dependant parameters:\n" );
751 // Parameters description
752 foreach ( $scriptDependantParams as $par => $info ) {
753 if ( $info['shortName'] !== false ) {
754 $par .= " (-{$info['shortName']})";
757 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
758 "\n$tab$tab" ) . "\n"
761 $this->output( "\n" );
765 // Script specific parameters not defined on construction by
766 // Maintenance::addDefaultParams()
767 $scriptSpecificParams = array_diff_key(
768 # all script parameters:
770 # remove the Maintenance default parameters:
771 $this->mGenericParameters
,
772 $this->mDependantParameters
774 if( count($scriptSpecificParams) > 0 ) {
775 $this->output( "Script specific parameters:\n" );
776 // Parameters description
777 foreach ( $scriptSpecificParams as $par => $info ) {
778 if ( $info['shortName'] !== false ) {
779 $par .= " (-{$info['shortName']})";
782 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
783 "\n$tab$tab" ) . "\n"
786 $this->output( "\n" );
790 if( count( $this->mArgList
) > 0 ) {
791 $this->output( "Arguments:\n" );
792 // Arguments description
793 foreach ( $this->mArgList
as $info ) {
794 $openChar = $info['require'] ?
'<' : '[';
795 $closeChar = $info['require'] ?
'>' : ']';
797 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
798 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
801 $this->output( "\n" );
808 * Handle some last-minute setup here.
810 public function finalSetup() {
811 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
812 global $wgDBadminuser, $wgDBadminpassword;
813 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
815 # Turn off output buffering again, it might have been turned on in the settings files
816 if ( ob_get_level() ) {
820 $wgCommandLineMode = true;
823 if( $this->hasOption( 'server') ) {
824 $wgServer = $this->getOption( 'server', $wgServer );
827 # If these were passed, use them
828 if ( $this->mDbUser
) {
829 $wgDBadminuser = $this->mDbUser
;
831 if ( $this->mDbPass
) {
832 $wgDBadminpassword = $this->mDbPass
;
835 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
836 $wgDBuser = $wgDBadminuser;
837 $wgDBpassword = $wgDBadminpassword;
839 if ( $wgDBservers ) {
840 foreach ( $wgDBservers as $i => $server ) {
841 $wgDBservers[$i]['user'] = $wgDBuser;
842 $wgDBservers[$i]['password'] = $wgDBpassword;
845 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
846 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
847 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
849 LBFactory
::destroyInstance();
852 $this->afterFinalSetup();
854 $wgShowSQLErrors = true;
855 @set_time_limit
( 0 );
856 $this->adjustMemoryLimit();
860 * Execute a callback function at the end of initialisation
862 protected function afterFinalSetup() {
863 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
864 call_user_func( MW_CMDLINE_CALLBACK
);
869 * Potentially debug globals. Originally a feature only
872 public function globals() {
873 if ( $this->hasOption( 'globals' ) ) {
879 * Do setup specific to WMF
881 public function loadWikimediaSettings() {
882 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
884 if ( empty( $wgNoDBParam ) ) {
885 # Check if we were passed a db name
886 if ( isset( $this->mOptions
['wiki'] ) ) {
887 $db = $this->mOptions
['wiki'];
889 $db = array_shift( $this->mArgs
);
891 list( $site, $lang ) = $wgConf->siteFromDB( $db );
893 # If not, work out the language and site the old way
894 if ( is_null( $site ) ||
is_null( $lang ) ) {
900 if ( isset( $this->mArgs
[0] ) ) {
901 $site = array_shift( $this->mArgs
);
911 # This is for the IRC scripts, which now run as the apache user
912 # The apache user doesn't have access to the wikiadmin_pass command
913 if ( $_ENV['USER'] == 'apache' ) {
914 # if ( posix_geteuid() == 48 ) {
915 $wgUseNormalUser = true;
918 putenv( 'wikilang=' . $lang );
920 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
922 if ( $lang == 'test' && $site == 'wikipedia' ) {
923 define( 'TESTWIKI', 1 );
928 * Generic setup for most installs. Returns the location of LocalSettings
931 public function loadSettings() {
932 global $wgCommandLineMode, $IP;
934 if ( isset( $this->mOptions
['conf'] ) ) {
935 $settingsFile = $this->mOptions
['conf'];
936 } elseif ( defined("MW_CONFIG_FILE") ) {
937 $settingsFile = MW_CONFIG_FILE
;
939 $settingsFile = "$IP/LocalSettings.php";
941 if ( isset( $this->mOptions
['wiki'] ) ) {
942 $bits = explode( '-', $this->mOptions
['wiki'] );
943 if ( count( $bits ) == 1 ) {
946 define( 'MW_DB', $bits[0] );
947 define( 'MW_PREFIX', $bits[1] );
950 if ( !is_readable( $settingsFile ) ) {
951 $this->error( "A copy of your installation's LocalSettings.php\n" .
952 "must exist and be readable in the source directory.\n" .
953 "Use --conf to specify it." , true );
955 $wgCommandLineMode = true;
956 return $settingsFile;
960 * Support function for cleaning up redundant text records
961 * @param $delete Boolean: whether or not to actually delete the records
962 * @author Rob Church <robchur@gmail.com>
964 public function purgeRedundantText( $delete = true ) {
965 # Data should come off the master, wrapped in a transaction
966 $dbw = $this->getDB( DB_MASTER
);
969 $tbl_arc = $dbw->tableName( 'archive' );
970 $tbl_rev = $dbw->tableName( 'revision' );
971 $tbl_txt = $dbw->tableName( 'text' );
973 # Get "active" text records from the revisions table
974 $this->output( 'Searching for active text records in revisions table...' );
975 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
976 foreach ( $res as $row ) {
977 $cur[] = $row->rev_text_id
;
979 $this->output( "done.\n" );
981 # Get "active" text records from the archive table
982 $this->output( 'Searching for active text records in archive table...' );
983 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
984 foreach ( $res as $row ) {
985 $cur[] = $row->ar_text_id
;
987 $this->output( "done.\n" );
989 # Get the IDs of all text records not in these sets
990 $this->output( 'Searching for inactive text records...' );
991 $set = implode( ', ', $cur );
992 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
994 foreach ( $res as $row ) {
995 $old[] = $row->old_id
;
997 $this->output( "done.\n" );
999 # Inform the user of what we're going to do
1000 $count = count( $old );
1001 $this->output( "$count inactive items found.\n" );
1003 # Delete as appropriate
1004 if ( $delete && $count ) {
1005 $this->output( 'Deleting...' );
1006 $set = implode( ', ', $old );
1007 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
1008 $this->output( "done.\n" );
1016 * Get the maintenance directory.
1018 protected function getDir() {
1019 return dirname( __FILE__
);
1023 * Get the list of available maintenance scripts. Note
1024 * that if you call this _before_ calling doMaintenance
1025 * you won't have any extensions in it yet
1028 public static function getMaintenanceScripts() {
1029 global $wgMaintenanceScripts;
1030 return $wgMaintenanceScripts + self
::getCoreScripts();
1034 * Return all of the core maintenance scripts
1037 protected static function getCoreScripts() {
1038 if ( !self
::$mCoreScripts ) {
1040 dirname( __FILE__
),
1041 dirname( __FILE__
) . '/gearman',
1042 dirname( __FILE__
) . '/language',
1043 dirname( __FILE__
) . '/storage',
1045 self
::$mCoreScripts = array();
1046 foreach ( $paths as $p ) {
1047 $handle = opendir( $p );
1048 while ( ( $file = readdir( $handle ) ) !== false ) {
1049 if ( $file == 'Maintenance.php' ) {
1052 $file = $p . '/' . $file;
1053 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
1054 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1058 $vars = get_defined_vars();
1059 if ( array_key_exists( 'maintClass', $vars ) ) {
1060 self
::$mCoreScripts[$vars['maintClass']] = $file;
1063 closedir( $handle );
1066 return self
::$mCoreScripts;
1070 * Returns a database to be used by current maintenance script. It can be set by setDB().
1071 * If not set, wfGetDB() will be used.
1072 * This function has the same parameters as wfGetDB()
1074 * @return DatabaseBase
1076 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1077 if ( is_null( $this->mDb
) ) {
1078 return wfGetDB( $db, $groups, $wiki );
1085 * Sets database object to be returned by getDB().
1087 * @param $db DatabaseBase: Database object to be used
1089 public function setDB( &$db ) {
1094 * Lock the search index
1095 * @param &$db Database object
1097 private function lockSearchindex( &$db ) {
1098 $write = array( 'searchindex' );
1099 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1100 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1105 * @param &$db Database object
1107 private function unlockSearchindex( &$db ) {
1108 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1112 * Unlock and lock again
1113 * Since the lock is low-priority, queued reads will be able to complete
1114 * @param &$db Database object
1116 private function relockSearchindex( &$db ) {
1117 $this->unlockSearchindex( $db );
1118 $this->lockSearchindex( $db );
1122 * Perform a search index update with locking
1123 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1124 * @param $callback callback String: the function that will update the function.
1125 * @param $dbw DatabaseBase object
1128 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1132 if ( $maxLockTime ) {
1133 $this->output( " --- Waiting for lock ---" );
1134 $this->lockSearchindex( $dbw );
1136 $this->output( "\n" );
1139 # Loop through the results and do a search update
1140 foreach ( $results as $row ) {
1141 # Allow reads to be processed
1142 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1143 $this->output( " --- Relocking ---" );
1144 $this->relockSearchindex( $dbw );
1146 $this->output( "\n" );
1148 call_user_func( $callback, $dbw, $row );
1151 # Unlock searchindex
1152 if ( $maxLockTime ) {
1153 $this->output( " --- Unlocking --" );
1154 $this->unlockSearchindex( $dbw );
1155 $this->output( "\n" );
1161 * Update the searchindex table for a given pageid
1162 * @param $dbw Database: a database write handle
1163 * @param $pageId Integer: the page ID to update.
1165 public function updateSearchIndexForPage( $dbw, $pageId ) {
1166 // Get current revision
1167 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1170 $titleObj = $rev->getTitle();
1171 $title = $titleObj->getPrefixedDBkey();
1172 $this->output( "$title..." );
1173 # Update searchindex
1174 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1176 $this->output( "\n" );
1182 * Prompt the console for input
1183 * @param $prompt String what to begin the line with, like '> '
1184 * @return String response
1186 public static function readconsole( $prompt = '> ' ) {
1187 static $isatty = null;
1188 if ( is_null( $isatty ) ) {
1189 $isatty = posix_isatty( 0 /*STDIN*/ );
1192 if ( $isatty && function_exists( 'readline' ) ) {
1193 return readline( $prompt );
1196 $st = self
::readlineEmulation( $prompt );
1198 if ( feof( STDIN
) ) {
1201 $st = fgets( STDIN
, 1024 );
1204 if ( $st === false ) return false;
1205 $resp = trim( $st );
1211 * Emulate readline()
1212 * @param $prompt String what to begin the line with, like '> '
1215 private static function readlineEmulation( $prompt ) {
1216 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1217 if ( !wfIsWindows() && $bash ) {
1219 $encPrompt = wfEscapeShellArg( $prompt );
1220 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1221 $encCommand = wfEscapeShellArg( $command );
1222 $line = wfShellExec( "$bash -c $encCommand", $retval );
1224 if ( $retval == 0 ) {
1226 } elseif ( $retval == 127 ) {
1227 // Couldn't execute bash even though we thought we saw it.
1228 // Shell probably spit out an error message, sorry :(
1229 // Fall through to fgets()...
1236 // Fallback... we'll have no editing controls, EWWW
1237 if ( feof( STDIN
) ) {
1241 return fgets( STDIN
, 1024 );
1245 class FakeMaintenance
extends Maintenance
{
1246 protected $mSelf = "FakeMaintenanceScript";
1247 public function execute() {