2 // Define this so scripts can easily find doMaintenance.php
3 define( 'DO_MAINTENANCE', dirname( __FILE__
) . '/doMaintenance.php' );
6 // Make sure we're on PHP5 or better
7 if( version_compare( PHP_VERSION
, '5.0.0' ) < 0 ) {
8 echo( "Sorry! This version of MediaWiki requires PHP 5; you are running " .
9 PHP_VERSION
. ".\n\n" .
10 "If you are sure you already have PHP 5 installed, it may be installed\n" .
11 "in a different path from PHP 4. Check with your system administrator.\n" );
16 * Abstract maintenance class for quickly writing and churning out
17 * maintenance scripts with minimal effort. All that _must_ be defined
18 * is the execute() method. See docs/maintenance.txt for more info
19 * and a quick demo of how to use it.
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 2 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License along
32 * with this program; if not, write to the Free Software Foundation, Inc.,
33 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
34 * http://www.gnu.org/copyleft/gpl.html
36 * @author Chad Horohoe <chad@anyonecanedit.org>
38 * @ingroup Maintenance
40 abstract class Maintenance
{
43 * Constants for DB access type
44 * @see Maintenance::getDbType()
50 // Const for getStdin()
51 const STDIN_ALL
= 'all';
53 // This is the desired params
54 protected $mParams = array();
56 // Array of desired args
57 protected $mArgList = array();
59 // This is the list of options that were actually passed
60 protected $mOptions = array();
62 // This is the list of arguments that were actually passed
63 protected $mArgs = array();
65 // Name of the script currently running
68 // Special vars for params that are always used
69 protected $mQuiet = false;
70 protected $mDbUser, $mDbPass;
72 // A description of the script, children should change this
73 protected $mDescription = '';
75 // Have we already loaded our user input?
76 protected $mInputLoaded = false;
78 // Batch size. If a script supports this, they should set
79 // a default with setBatchSize()
80 protected $mBatchSize = null;
83 * List of all the core maintenance scripts. This is added
84 * to scripts added by extensions in $wgMaintenanceScripts
85 * and returned by getMaintenanceScripts()
87 protected static $mCoreScripts = null;
90 * Default constructor. Children should call this if implementing
91 * their own constructors
93 public function __construct() {
94 $this->addDefaultParams();
98 * Do the actual work. All child classes will need to implement this
100 abstract public function execute();
103 * Add a parameter to the script. Will be displayed on --help
104 * with the associated description
106 * @param $name String The name of the param (help, version, etc)
107 * @param $description String The description of the param to show on --help
108 * @param $required boolean Is the param required?
109 * @param $withArg Boolean Is an argument required with this option?
111 protected function addOption( $name, $description, $required = false, $withArg = false ) {
112 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg );
116 * Checks to see if a particular param exists.
117 * @param $name String The name of the param
120 protected function hasOption( $name ) {
121 return isset( $this->mOptions
[$name] );
125 * Get an option, or return the default
126 * @param $name String The name of the param
127 * @param $default mixed Anything you want, default null
130 protected function getOption( $name, $default = null ) {
131 if( $this->hasOption( $name ) ) {
132 return $this->mOptions
[$name];
134 // Set it so we don't have to provide the default again
135 $this->mOptions
[$name] = $default;
136 return $this->mOptions
[$name];
141 * Add some args that are needed
142 * @param $arg String Name of the arg, like 'start'
143 * @param $description String Short description of the arg
144 * @param $required Boolean Is this required?
146 protected function addArg( $arg, $description, $required = true ) {
147 $this->mArgList
[] = array(
149 'desc' => $description,
150 'require' => $required
155 * Does a given argument exist?
156 * @param $argId int The integer value (from zero) for the arg
159 protected function hasArg( $argId = 0 ) {
160 return isset( $this->mArgs
[$argId] );
165 * @param $argId int The integer value (from zero) for the arg
166 * @param $default mixed The default if it doesn't exist
169 protected function getArg( $argId = 0, $default = null ) {
170 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
174 * Set the batch size.
175 * @param $s int The number of operations to do in a batch
177 protected function setBatchSize( $s = 0 ) {
178 $this->mBatchSize
= $s;
182 * Get the script's name
185 public function getName() {
190 * Return input from stdin.
191 * @param $length int The number of bytes to read. If null,
192 * just return the handle. Maintenance::STDIN_ALL returns
196 protected function getStdin( $len = null ) {
197 if ( $len == Maintenance
::STDIN_ALL
)
198 return file_get_contents( 'php://stdin' );
199 $f = fopen( 'php://stdin', 'rt' );
202 $input = fgets( $f, $len );
204 return rtrim( $input );
208 * Throw some output to the user. Scripts can call this with no fears,
209 * as we handle all --quiet stuff here
210 * @param $out String The text to show to the user
212 protected function output( $out ) {
213 if( $this->mQuiet
) {
216 $f = fopen( 'php://stdout', 'w' );
222 * Throw an error to the user. Doesn't respect --quiet, so don't use
223 * this for non-error output
224 * @param $err String The error to display
225 * @param $die boolean If true, go ahead and die out.
227 protected function error( $err, $die = false ) {
228 $f = fopen( 'php://stderr', 'w' );
229 fwrite( $f, $err . "\n" );
235 * Does the script need different DB access? By default, we give Maintenance
236 * scripts normal rights to the DB. Sometimes, a script needs admin rights
237 * access for a reason and sometimes they want no access. Subclasses should
238 * override and return one of the following values, as needed:
239 * Maintenance::DB_NONE - For no DB access at all
240 * Maintenance::DB_STD - For normal DB access, default
241 * Maintenance::DB_ADMIN - For admin DB access
244 protected function getDbType() {
245 return Maintenance
::DB_STD
;
249 * Add the default parameters to the scripts
251 protected function addDefaultParams() {
252 $this->addOption( 'help', "Display this help message" );
253 $this->addOption( 'quiet', "Whether to supress non-error output" );
254 $this->addOption( 'conf', "Location of LocalSettings.php, if not default", false, true );
255 $this->addOption( 'wiki', "For specifying the wiki ID", false, true );
256 $this->addOption( 'globals', "Output globals at the end of processing for debugging" );
257 // If we support a DB, show the options
258 if( $this->getDbType() > 0 ) {
259 $this->addOption( 'dbuser', "The DB user to use for this script", false, true );
260 $this->addOption( 'dbpass', "The password to use for this script", false, true );
262 // If we support $mBatchSize, show the option
263 if( $this->mBatchSize
) {
264 $this->addOption( 'batch-size', 'Run this many operations ' .
265 'per batch, default: ' . $this->mBatchSize
, false, true );
270 * Run a child maintenance script. Pass all of the current arguments
272 * @param $maintClass String A name of a child maintenance class
273 * @param $classFile String Full path of where the child is
274 * @return Maintenance child
276 protected function runChild( $maintClass, $classFile = null ) {
277 // If we haven't already specified, kill setup procedures
278 // for child scripts, we've already got a sane environment
279 self
::disableSetup();
281 // Make sure the class is loaded first
282 if( !class_exists( $maintClass ) ) {
284 require_once( $classFile );
286 if( !class_exists( $maintClass ) ) {
287 $this->error( "Cannot spawn child: $maintClass" );
291 $child = new $maintClass();
292 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
297 * Disable Setup.php mostly
299 protected static function disableSetup() {
300 if( !defined( 'MW_NO_SETUP' ) )
301 define( 'MW_NO_SETUP', true );
305 * Do some sanity checking and basic setup
307 public function setup() {
308 global $IP, $wgCommandLineMode, $wgUseNormalUser, $wgRequestTime;
310 # Abort if called from a web server
311 if ( isset( $_SERVER ) && array_key_exists( 'REQUEST_METHOD', $_SERVER ) ) {
312 $this->error( "This script must be run from the command line", true );
315 # Make sure we can handle script parameters
316 if( !ini_get( 'register_argc_argv' ) ) {
317 $this->error( "Cannot get command line arguments, register_argc_argv is set to false", true );
320 if( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
321 // Send PHP warnings and errors to stderr instead of stdout.
322 // This aids in diagnosing problems, while keeping messages
323 // out of redirected output.
324 if( ini_get( 'display_errors' ) ) {
325 ini_set( 'display_errors', 'stderr' );
328 // Don't touch the setting on earlier versions of PHP,
329 // as setting it would disable output if you'd wanted it.
331 // Note that exceptions are also sent to stderr when
332 // command-line mode is on, regardless of PHP version.
335 # Set the memory limit
336 ini_set( 'memory_limit', -1 );
338 # Set max execution time to 0 (no limit). PHP.net says that
339 # "When running PHP from the command line the default setting is 0."
340 # But sometimes this doesn't seem to be the case.
341 ini_set( 'max_execution_time', 0 );
343 $wgRequestTime = microtime( true );
345 # Define us as being in MediaWiki
346 define( 'MEDIAWIKI', true );
348 # Setup $IP, using MW_INSTALL_PATH if it exists
349 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
350 ?
getenv( 'MW_INSTALL_PATH' )
351 : realpath( dirname( __FILE__
) . '/..' );
353 $wgCommandLineMode = true;
354 # Turn off output buffering if it's on
357 if ( !isset( $wgUseNormalUser ) ) {
358 $wgUseNormalUser = false;
361 $this->loadParamsAndArgs();
363 $this->validateParamsAndArgs();
367 * Clear all params and arguments.
369 public function clearParamsAndArgs() {
370 $this->mOptions
= array();
371 $this->mArgs
= array();
372 $this->mInputLoaded
= false;
376 * Process command line arguments
377 * $mOptions becomes an array with keys set to the option names
378 * $mArgs becomes a zero-based array containing the non-option arguments
380 * @param $self String The name of the script, if any
381 * @param $opts Array An array of options, in form of key=>value
382 * @param $args Array An array of command line arguments
384 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
385 # If we were given opts or args, set those and return early
387 $this->mSelf
= $self;
388 $this->mInputLoaded
= true;
391 $this->mOptions
= $opts;
392 $this->mInputLoaded
= true;
395 $this->mArgs
= $args;
396 $this->mInputLoaded
= true;
399 # If we've already loaded input (either by user values or from $argv)
400 # skip on loading it again. The array_shift() will corrupt values if
401 # it's run again and again
402 if( $this->mInputLoaded
) {
403 $this->loadSpecialVars();
408 $this->mSelf
= array_shift( $argv );
414 for( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
415 if ( $arg == '--' ) {
416 # End of options, remainder should be considered arguments
417 $arg = next( $argv );
418 while( $arg !== false ) {
420 $arg = next( $argv );
423 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
425 $option = substr( $arg, 2 );
426 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
427 $param = next( $argv );
428 if ( $param === false ) {
429 $this->error( "\nERROR: $option needs a value after it\n" );
430 $this->maybeHelp( true );
432 $options[$option] = $param;
434 $bits = explode( '=', $option, 2 );
435 if( count( $bits ) > 1 ) {
441 $options[$option] = $param;
443 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
445 for ( $p=1; $p<strlen( $arg ); $p++
) {
447 if ( $this->mParams
[$option]['withArg'] ) {
448 $param = next( $argv );
449 if ( $param === false ) {
450 $this->error( "\nERROR: $option needs a value after it\n" );
451 $this->maybeHelp( true );
453 $options[$option] = $param;
455 $options[$option] = 1;
463 $this->mOptions
= $options;
464 $this->mArgs
= $args;
465 $this->loadSpecialVars();
466 $this->mInputLoaded
= true;
470 * Run some validation checks on the params, etc
472 protected function validateParamsAndArgs() {
474 # Check to make sure we've got all the required options
475 foreach( $this->mParams
as $opt => $info ) {
476 if( $info['require'] && !$this->hasOption( $opt ) ) {
477 $this->error( "Param $opt required!" );
482 foreach( $this->mArgList
as $k => $info ) {
483 if( $info['require'] && !$this->hasArg($k) ) {
484 $this->error( "Argument <" . $info['name'] . "> required!" );
489 if( $die ) $this->maybeHelp( true );
493 * Handle the special variables that are global to all scripts
495 protected function loadSpecialVars() {
496 if( $this->hasOption( 'dbuser' ) )
497 $this->mDbUser
= $this->getOption( 'dbuser' );
498 if( $this->hasOption( 'dbpass' ) )
499 $this->mDbPass
= $this->getOption( 'dbpass' );
500 if( $this->hasOption( 'quiet' ) )
501 $this->mQuiet
= true;
502 if( $this->hasOption( 'batch-size' ) )
503 $this->mBatchSize
= $this->getOption( 'batch-size' );
507 * Maybe show the help.
508 * @param $force boolean Whether to force the help to show, default false
510 protected function maybeHelp( $force = false ) {
511 ksort( $this->mParams
);
512 if( $this->hasOption( 'help' ) ||
$force ) {
513 $this->mQuiet
= false;
514 if( $this->mDescription
) {
515 $this->output( "\n" . $this->mDescription
. "\n" );
517 $this->output( "\nUsage: php " . $this->mSelf
);
518 if( $this->mParams
) {
519 $this->output( " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]" );
521 if( $this->mArgList
) {
522 $this->output( " <" );
523 foreach( $this->mArgList
as $k => $arg ) {
524 $this->output( $arg['name'] . ">" );
525 if( $k < count( $this->mArgList
) - 1 )
526 $this->output( " <" );
529 $this->output( "\n" );
530 foreach( $this->mParams
as $par => $info ) {
531 $this->output( "\t$par : " . $info['desc'] . "\n" );
533 foreach( $this->mArgList
as $info ) {
534 $this->output( "\t<" . $info['name'] . "> : " . $info['desc'] . "\n" );
541 * Handle some last-minute setup here.
543 public function finalSetup() {
544 global $wgCommandLineMode, $wgUseNormalUser, $wgShowSQLErrors;
545 global $wgTitle, $wgProfiling, $IP, $wgDBadminuser, $wgDBadminpassword;
546 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
548 # Turn off output buffering again, it might have been turned on in the settings files
549 if( ob_get_level() ) {
553 $wgCommandLineMode = true;
555 # If these were passed, use them
557 $wgDBadminuser = $this->mDbUser
;
559 $wgDBadminpassword = $this->mDbPass
;
561 if ( empty( $wgUseNormalUser ) && isset( $wgDBadminuser ) ) {
562 $wgDBuser = $wgDBadminuser;
563 $wgDBpassword = $wgDBadminpassword;
566 foreach ( $wgDBservers as $i => $server ) {
567 $wgDBservers[$i]['user'] = $wgDBuser;
568 $wgDBservers[$i]['password'] = $wgDBpassword;
571 if( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
572 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
573 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
577 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
578 $fn = MW_CMDLINE_CALLBACK
;
582 $wgShowSQLErrors = true;
583 @set_time_limit
( 0 );
585 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
589 * Potentially debug globals. Originally a feature only
592 public function globals() {
593 if( $this->hasOption( 'globals' ) ) {
599 * Do setup specific to WMF
601 public function loadWikimediaSettings() {
602 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
604 if ( empty( $wgNoDBParam ) ) {
605 # Check if we were passed a db name
606 if ( isset( $this->mOptions
['wiki'] ) ) {
607 $db = $this->mOptions
['wiki'];
609 $db = array_shift( $this->mArgs
);
611 list( $site, $lang ) = $wgConf->siteFromDB( $db );
613 # If not, work out the language and site the old way
614 if ( is_null( $site ) ||
is_null( $lang ) ) {
620 if ( isset( $this->mArgs
[0] ) ) {
621 $site = array_shift( $this->mArgs
);
631 # This is for the IRC scripts, which now run as the apache user
632 # The apache user doesn't have access to the wikiadmin_pass command
633 if ( $_ENV['USER'] == 'apache' ) {
634 #if ( posix_geteuid() == 48 ) {
635 $wgUseNormalUser = true;
638 putenv( 'wikilang=' . $lang );
641 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
643 if ( $lang == 'test' && $site == 'wikipedia' ) {
644 define( 'TESTWIKI', 1 );
649 * Generic setup for most installs. Returns the location of LocalSettings
652 public function loadSettings() {
653 global $wgWikiFarm, $wgCommandLineMode, $IP, $DP;
656 if ( isset( $this->mOptions
['conf'] ) ) {
657 $settingsFile = $this->mOptions
['conf'];
659 $settingsFile = "$IP/LocalSettings.php";
661 if ( isset( $this->mOptions
['wiki'] ) ) {
662 $bits = explode( '-', $this->mOptions
['wiki'] );
663 if ( count( $bits ) == 1 ) {
666 define( 'MW_DB', $bits[0] );
667 define( 'MW_PREFIX', $bits[1] );
670 if ( !is_readable( $settingsFile ) ) {
671 $this->error( "A copy of your installation's LocalSettings.php\n" .
672 "must exist and be readable in the source directory.", true );
674 $wgCommandLineMode = true;
676 return $settingsFile;
680 * Support function for cleaning up redundant text records
681 * @param $delete boolean Whether or not to actually delete the records
682 * @author Rob Church <robchur@gmail.com>
684 protected function purgeRedundantText( $delete = true ) {
685 # Data should come off the master, wrapped in a transaction
686 $dbw = wfGetDB( DB_MASTER
);
689 $tbl_arc = $dbw->tableName( 'archive' );
690 $tbl_rev = $dbw->tableName( 'revision' );
691 $tbl_txt = $dbw->tableName( 'text' );
693 # Get "active" text records from the revisions table
694 $this->output( "Searching for active text records in revisions table..." );
695 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
696 foreach( $res as $row ) {
697 $cur[] = $row->rev_text_id
;
699 $this->output( "done.\n" );
701 # Get "active" text records from the archive table
702 $this->output( "Searching for active text records in archive table..." );
703 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
704 foreach( $res as $row ) {
705 $cur[] = $row->ar_text_id
;
707 $this->output( "done.\n" );
709 # Get the IDs of all text records not in these sets
710 $this->output( "Searching for inactive text records..." );
711 $set = implode( ', ', $cur );
712 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
714 foreach( $res as $row ) {
715 $old[] = $row->old_id
;
717 $this->output( "done.\n" );
719 # Inform the user of what we're going to do
720 $count = count( $old );
721 $this->output( "$count inactive items found.\n" );
723 # Delete as appropriate
724 if( $delete && $count ) {
725 $this->output( "Deleting..." );
726 $set = implode( ', ', $old );
727 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
728 $this->output( "done.\n" );
736 * Get the maintenance directory.
738 protected function getDir() {
739 return dirname( __FILE__
);
743 * Get the list of available maintenance scripts. Note
744 * that if you call this _before_ calling doMaintenance
745 * you won't have any extensions in it yet
748 public static function getMaintenanceScripts() {
749 global $wgMaintenanceScripts;
750 return $wgMaintenanceScripts + self
::getCoreScripts();
754 * Return all of the core maintenance scripts
757 protected static function getCoreScripts() {
758 if( !self
::$mCoreScripts ) {
759 self
::disableSetup();
762 dirname( __FILE__
) . '/gearman',
763 dirname( __FILE__
) . '/language',
764 dirname( __FILE__
) . '/storage',
766 self
::$mCoreScripts = array();
767 foreach( $paths as $p ) {
768 $handle = opendir( $p );
769 while( ( $file = readdir( $handle ) ) !== false ) {
770 if( $file == 'Maintenance.php' )
772 $file = $p . '/' . $file;
773 if( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
774 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
778 $vars = get_defined_vars();
779 if( array_key_exists( 'maintClass', $vars ) ) {
780 self
::$mCoreScripts[$vars['maintClass']] = $file;
786 return self
::$mCoreScripts;