2 // Define this so scripts can easily find doMaintenance.php
3 define( 'DO_MAINTENANCE', dirname(__FILE__
) . '/doMaintenance.php' );
5 // Make sure we're on PHP5 or better
6 if( version_compare( PHP_VERSION
, '5.0.0' ) < 0 ) {
7 echo( "Sorry! This version of MediaWiki requires PHP 5; you are running " .
8 PHP_VERSION
. ".\n\n" .
9 "If you are sure you already have PHP 5 installed, it may be installed\n" .
10 "in a different path from PHP 4. Check with your system administrator.\n" );
15 * Abstract maintenance class for quickly writing and churning out
16 * maintenance scripts with minimal effort. All that _must_ be defined
17 * is the execute() method. See docs/maintenance.txt for more info
18 * and a quick demo of how to use it.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License along
31 * with this program; if not, write to the Free Software Foundation, Inc.,
32 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
33 * http://www.gnu.org/copyleft/gpl.html
35 * @author Chad Horohoe <chad@anyonecanedit.org>
37 * @ingroup Maintenance
39 abstract class Maintenance
{
42 * Constants for DB access type
43 * @see Maintenance::getDbType()
49 // Const for getStdin()
50 const STDIN_ALL
= 'all';
52 // This is the desired params
53 private $mParams = array();
55 // Array of desired args
56 private $mArgList = array();
58 // This is the list of options that were actually passed
59 private $mOptions = array();
61 // This is the list of arguments that were actually passed
62 protected $mArgs = array();
64 // Name of the script currently running
67 // Special vars for params that are always used
68 private $mQuiet = false;
69 private $mDbUser, $mDbPass;
71 // A description of the script, children should change this
72 protected $mDescription = '';
74 // Have we already loaded our user input?
75 private $mInputLoaded = false;
77 // Batch size. If a script supports this, they should set
78 // a default with setBatchSize()
79 protected $mBatchSize = null;
82 * List of all the core maintenance scripts. This is added
83 * to scripts added by extensions in $wgMaintenanceScripts
84 * and returned by getMaintenanceScripts()
86 protected static $mCoreScripts = null;
89 * Default constructor. Children should call this if implementing
90 * their own constructors
92 public function __construct() {
93 $this->addDefaultParams();
97 * Do the actual work. All child classes will need to implement this
99 abstract public function execute();
102 * Add a parameter to the script. Will be displayed on --help
103 * with the associated description
105 * @param $name String The name of the param (help, version, etc)
106 * @param $description String The description of the param to show on --help
107 * @param $required boolean Is the param required?
108 * @param $withArg Boolean Is an argument required with this option?
110 protected function addOption( $name, $description, $required = false, $withArg = false ) {
111 $this->mParams
[ $name ] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg );
115 * Checks to see if a particular param exists.
116 * @param $name String The name of the param
119 protected function hasOption( $name ) {
120 return isset( $this->mOptions
[ $name ] );
124 * Get an option, or return the default
125 * @param $name String The name of the param
126 * @param $default mixed Anything you want, default null
129 protected function getOption( $name, $default = null ) {
130 if( $this->hasOption($name) ) {
131 return $this->mOptions
[$name];
133 // Set it so we don't have to provide the default again
134 $this->mOptions
[$name] = $default;
135 return $this->mOptions
[$name];
140 * Add some args that are needed. Used in formatting help
142 protected function addArgs( $args ) {
143 $this->mArgList
= array_merge( $this->mArgList
, $args );
147 * Does a given argument exist?
148 * @param $argId int The integer value (from zero) for the arg
151 protected function hasArg( $argId = 0 ) {
152 return isset( $this->mArgs
[ $argId ] ) ;
157 * @param $argId int The integer value (from zero) for the arg
158 * @param $default mixed The default if it doesn't exist
161 protected function getArg( $argId = 0, $default = null ) {
162 return $this->hasArg($argId) ?
$this->mArgs
[$argId] : $default;
166 * Set the batch size.
167 * @param $s int The number of operations to do in a batch
169 protected function setBatchSize( $s = 0 ) {
170 $this->mBatchSize
= $s;
174 * Get the script's name
177 public function getName() {
182 * Return input from stdin.
183 * @param $length int The number of bytes to read. If null,
184 * just return the handle. Maintenance::STDIN_ALL returns
188 protected function getStdin( $len = null ) {
189 if ( $len == Maintenance
::STDIN_ALL
)
190 return file_get_contents( 'php://stdin' );
191 $f = fopen( 'php://stdin', 'rt' );
194 $input = fgets( $f, $len );
196 return rtrim( $input );
200 * Throw some output to the user. Scripts can call this with no fears,
201 * as we handle all --quiet stuff here
202 * @param $out String The text to show to the user
204 protected function output( $out ) {
205 if( $this->mQuiet
) {
208 $f = fopen( 'php://stdout', 'w' );
214 * Throw an error to the user. Doesn't respect --quiet, so don't use
215 * this for non-error output
216 * @param $err String The error to display
217 * @param $die boolean If true, go ahead and die out.
219 protected function error( $err, $die = false ) {
220 $f = fopen( 'php://stderr', 'w' );
221 fwrite( $f, $err . "\n" );
227 * Does the script need different DB access? By default, we give Maintenance
228 * scripts normal rights to the DB. Sometimes, a script needs admin rights
229 * access for a reason and sometimes they want no access. Subclasses should
230 * override and return one of the following values, as needed:
231 * Maintenance::DB_NONE - For no DB access at all
232 * Maintenance::DB_STD - For normal DB access, default
233 * Maintenance::DB_ADMIN - For admin DB access
236 protected function getDbType() {
237 return Maintenance
::DB_STD
;
241 * Add the default parameters to the scripts
243 private function addDefaultParams() {
244 $this->addOption( 'help', "Display this help message" );
245 $this->addOption( 'quiet', "Whether to supress non-error output" );
246 $this->addOption( 'conf', "Location of LocalSettings.php, if not default", false, true );
247 $this->addOption( 'wiki', "For specifying the wiki ID", false, true );
248 $this->addOption( 'globals', "Output globals at the end of processing for debugging" );
249 // If we support a DB, show the options
250 if( $this->getDbType() > 0 ) {
251 $this->addOption( 'dbuser', "The DB user to use for this script", false, true );
252 $this->addOption( 'dbpass', "The password to use for this script", false, true );
254 // If we support $mBatchSize, show the option
255 if( $this->mBatchSize
) {
256 $this->addOption( 'batch-size', 'Run this many operations ' .
257 'per batch, default: ' . $this->mBatchSize
, false, true );
262 * Spawn a child maintenance script. Pass all of the current arguments
264 * @param $maintClass String A name of a child maintenance class
265 * @param $classFile String Full path of where the child is
266 * @return Maintenance child
268 protected function spawnChild( $maintClass, $classFile = null ) {
269 // If we haven't already specified, kill setup procedures
270 // for child scripts, we've already got a sane environment
271 self
::disableSetup();
273 // Make sure the class is loaded first
274 if( !class_exists( $maintClass ) ) {
276 require_once( $classFile );
278 if( !class_exists( $maintClass ) ) {
279 $this->error( "Cannot spawn child: $maintClass" );
283 $child = new $maintClass();
284 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
289 * Disable Setup.php mostly
291 protected static function disableSetup() {
292 if( !defined( 'MW_NO_SETUP' ) )
293 define( 'MW_NO_SETUP', true );
297 * Do some sanity checking and basic setup
299 public function setup() {
300 global $IP, $wgCommandLineMode, $wgUseNormalUser, $wgRequestTime;
302 # Abort if called from a web server
303 if ( isset( $_SERVER ) && array_key_exists( 'REQUEST_METHOD', $_SERVER ) ) {
304 $this->error( "This script must be run from the command line", true );
307 # Make sure we can handle script parameters
308 if( !ini_get( 'register_argc_argv' ) ) {
309 $this->error( "Cannot get command line arguments, register_argc_argv is set to false", true );
312 if( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
313 // Send PHP warnings and errors to stderr instead of stdout.
314 // This aids in diagnosing problems, while keeping messages
315 // out of redirected output.
316 if( ini_get( 'display_errors' ) ) {
317 ini_set( 'display_errors', 'stderr' );
320 // Don't touch the setting on earlier versions of PHP,
321 // as setting it would disable output if you'd wanted it.
323 // Note that exceptions are also sent to stderr when
324 // command-line mode is on, regardless of PHP version.
327 # Set the memory limit
328 ini_set( 'memory_limit', -1 );
330 $wgRequestTime = microtime(true);
332 # Define us as being in Mediawiki
333 define( 'MEDIAWIKI', true );
335 # Setup $IP, using MW_INSTALL_PATH if it exists
336 $IP = strval( getenv('MW_INSTALL_PATH') ) !== ''
337 ?
getenv('MW_INSTALL_PATH')
338 : realpath( dirname( __FILE__
) . '/..' );
340 $wgCommandLineMode = true;
341 # Turn off output buffering if it's on
344 if (!isset( $wgUseNormalUser ) ) {
345 $wgUseNormalUser = false;
348 $this->loadParamsAndArgs();
350 $this->validateParamsAndArgs();
354 * Clear all params and arguments.
356 public function clearParamsAndArgs() {
357 $this->mOptions
= array();
358 $this->mArgs
= array();
359 $this->mInputLoaded
= false;
363 * Process command line arguments
364 * $mOptions becomes an array with keys set to the option names
365 * $mArgs becomes a zero-based array containing the non-option arguments
367 * @param $self String The name of the script, if any
368 * @param $opts Array An array of options, in form of key=>value
369 * @param $args Array An array of command line arguments
371 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
372 # If we were given opts or args, set those and return early
374 $this->mSelf
= $self;
375 $this->mInputLoaded
= true;
378 $this->mOptions
= $opts;
379 $this->mInputLoaded
= true;
382 $this->mArgs
= $args;
383 $this->mInputLoaded
= true;
386 # If we've already loaded input (either by user values or from $argv)
387 # skip on loading it again. The array_shift() will corrupt values if
388 # it's run again and again
389 if( $this->mInputLoaded
) {
390 $this->loadSpecialVars();
395 $this->mSelf
= array_shift( $argv );
401 for( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
402 if ( $arg == '--' ) {
403 # End of options, remainder should be considered arguments
404 $arg = next( $argv );
405 while( $arg !== false ) {
407 $arg = next( $argv );
410 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
412 $option = substr( $arg, 2 );
413 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
414 $param = next( $argv );
415 if ( $param === false ) {
416 $this->error( "\nERROR: $option needs a value after it\n" );
417 $this->maybeHelp( true );
419 $options[$option] = $param;
421 $bits = explode( '=', $option, 2 );
422 if( count( $bits ) > 1 ) {
428 $options[$option] = $param;
430 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
432 for ( $p=1; $p<strlen( $arg ); $p++
) {
434 if ( $this->mParams
[$option]['withArg'] ) {
435 $param = next( $argv );
436 if ( $param === false ) {
437 $this->error( "\nERROR: $option needs a value after it\n" );
438 $this->maybeHelp( true );
440 $options[$option] = $param;
442 $options[$option] = 1;
450 $this->mOptions
= $options;
451 $this->mArgs
= $args;
452 $this->loadSpecialVars();
453 $this->mInputLoaded
= true;
457 * Run some validation checks on the params, etc
459 private function validateParamsAndArgs() {
460 # Check to make sure we've got all the required ones
461 foreach( $this->mParams
as $opt => $info ) {
462 if( $info['require'] && !$this->hasOption($opt) ) {
463 $this->error( "Param $opt required.", true );
467 # Also make sure we've got enough arguments
468 if ( count( $this->mArgs
) < count( $this->mArgList
) ) {
469 $this->error( "Not enough arguments passed", true );
474 * Handle the special variables that are global to all scripts
476 private function loadSpecialVars() {
477 if( $this->hasOption( 'dbuser' ) )
478 $this->mDbUser
= $this->getOption( 'dbuser' );
479 if( $this->hasOption( 'dbpass' ) )
480 $this->mDbPass
= $this->getOption( 'dbpass' );
481 if( $this->hasOption( 'quiet' ) )
482 $this->mQuiet
= true;
483 if( $this->hasOption( 'batch-size' ) )
484 $this->mBatchSize
= $this->getOption( 'batch-size' );
488 * Maybe show the help.
489 * @param $force boolean Whether to force the help to show, default false
491 private function maybeHelp( $force = false ) {
492 ksort( $this->mParams
);
493 if( $this->hasOption('help') ||
in_array( 'help', $this->mArgs
) ||
$force ) {
494 $this->mQuiet
= false;
495 if( $this->mDescription
) {
496 $this->output( "\n" . $this->mDescription
. "\n" );
498 $this->output( "\nUsage: php " . $this->mSelf
);
499 if( $this->mParams
) {
500 $this->output( " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]" );
502 if( $this->mArgList
) {
503 $this->output( " <" . implode( $this->mArgList
, "> <" ) . ">" );
505 $this->output( "\n" );
506 foreach( $this->mParams
as $par => $info ) {
507 $this->output( "\t$par : " . $info['desc'] . "\n" );
514 * Handle some last-minute setup here.
516 private function finalSetup() {
517 global $wgCommandLineMode, $wgUseNormalUser, $wgShowSQLErrors;
518 global $wgTitle, $wgProfiling, $IP, $wgDBadminuser, $wgDBadminpassword;
519 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
521 # Turn off output buffering again, it might have been turned on in the settings files
522 if( ob_get_level() ) {
526 $wgCommandLineMode = true;
528 # If these were passed, use them
530 $wgDBadminuser = $this->mDbUser
;
532 $wgDBadminpass = $this->mDbPass
;
534 if ( empty( $wgUseNormalUser ) && isset( $wgDBadminuser ) ) {
535 $wgDBuser = $wgDBadminuser;
536 $wgDBpassword = $wgDBadminpassword;
539 foreach ( $wgDBservers as $i => $server ) {
540 $wgDBservers[$i]['user'] = $wgDBuser;
541 $wgDBservers[$i]['password'] = $wgDBpassword;
544 if( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
545 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
546 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
550 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
551 $fn = MW_CMDLINE_CALLBACK
;
555 $wgShowSQLErrors = true;
556 @set_time_limit
( 0 );
558 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
562 * Potentially debug globals. Originally a feature only
565 public function globals() {
566 if( $this->hasOption( 'globals' ) ) {
572 * Do setup specific to WMF
574 public function loadWikimediaSettings() {
575 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
577 if ( empty( $wgNoDBParam ) ) {
578 # Check if we were passed a db name
579 if ( isset( $this->mOptions
['wiki'] ) ) {
580 $db = $this->mOptions
['wiki'];
582 $db = array_shift( $this->mArgs
);
584 list( $site, $lang ) = $wgConf->siteFromDB( $db );
586 # If not, work out the language and site the old way
587 if ( is_null( $site ) ||
is_null( $lang ) ) {
593 if ( isset( $this->mArgs
[0] ) ) {
594 $site = array_shift( $this->mArgs
);
604 # This is for the IRC scripts, which now run as the apache user
605 # The apache user doesn't have access to the wikiadmin_pass command
606 if ( $_ENV['USER'] == 'apache' ) {
607 #if ( posix_geteuid() == 48 ) {
608 $wgUseNormalUser = true;
611 putenv( 'wikilang=' . $lang );
614 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
616 if ( $lang == 'test' && $site == 'wikipedia' ) {
617 define( 'TESTWIKI', 1 );
624 * Generic setup for most installs. Returns the location of LocalSettings
627 public function loadSettings() {
628 global $wgWikiFarm, $wgCommandLineMode, $IP, $DP;
631 if ( isset( $this->mOptions
['conf'] ) ) {
632 $settingsFile = $this->mOptions
['conf'];
634 $settingsFile = "$IP/LocalSettings.php";
636 if ( isset( $this->mOptions
['wiki'] ) ) {
637 $bits = explode( '-', $this->mOptions
['wiki'] );
638 if ( count( $bits ) == 1 ) {
641 define( 'MW_DB', $bits[0] );
642 define( 'MW_PREFIX', $bits[1] );
645 if ( ! is_readable( $settingsFile ) ) {
646 $this->error( "A copy of your installation's LocalSettings.php\n" .
647 "must exist and be readable in the source directory.", true );
649 $wgCommandLineMode = true;
652 return $settingsFile;
656 * Support function for cleaning up redundant text records
657 * @param $delete boolean Whether or not to actually delete the records
658 * @author Rob Church <robchur@gmail.com>
660 protected function purgeRedundantText( $delete = true ) {
661 # Data should come off the master, wrapped in a transaction
662 $dbw = wfGetDB( DB_MASTER
);
665 $tbl_arc = $dbw->tableName( 'archive' );
666 $tbl_rev = $dbw->tableName( 'revision' );
667 $tbl_txt = $dbw->tableName( 'text' );
669 # Get "active" text records from the revisions table
670 $this->output( "Searching for active text records in revisions table..." );
671 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
672 while( $row = $dbw->fetchObject( $res ) ) {
673 $cur[] = $row->rev_text_id
;
675 $this->output( "done.\n" );
677 # Get "active" text records from the archive table
678 $this->output( "Searching for active text records in archive table..." );
679 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
680 while( $row = $dbw->fetchObject( $res ) ) {
681 $cur[] = $row->ar_text_id
;
683 $this->output( "done.\n" );
685 # Get the IDs of all text records not in these sets
686 $this->output( "Searching for inactive text records..." );
687 $set = implode( ', ', $cur );
688 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
690 while( $row = $dbw->fetchObject( $res ) ) {
691 $old[] = $row->old_id
;
693 $this->output( "done.\n" );
695 # Inform the user of what we're going to do
696 $count = count( $old );
697 $this->output( "$count inactive items found.\n" );
699 # Delete as appropriate
700 if( $delete && $count ) {
701 $this->output( "Deleting..." );
702 $set = implode( ', ', $old );
703 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
704 $this->output( "done.\n" );
712 * Get the maintenance directory.
714 protected function getDir() {
715 return dirname( __FILE__
);
719 * Get the list of available maintenance scripts. Note
720 * that if you call this _before_ calling doMaintenance
721 * you won't have any extensions in it yet
724 public static function getMaintenanceScripts() {
725 global $wgMaintenanceScripts;
726 return $wgMaintenanceScripts + self
::getCoreScripts();
730 * Return all of the core maintenance scripts
733 private static function getCoreScripts() {
734 if( !self
::$mCoreScripts ) {
735 self
::disableSetup();
738 dirname( __FILE__
) . '/gearman',
739 dirname( __FILE__
) . '/language',
740 dirname( __FILE__
) . '/storage',
742 self
::$mCoreScripts = array();
743 foreach( $paths as $p ) {
744 $handle = opendir( $p );
745 while( ( $file = readdir( $handle ) ) !== false ) {
746 if( $file == 'Maintenance.php' )
748 $file = $p . '/' . $file;
749 if( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
750 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
754 $vars = get_defined_vars();
755 if( array_key_exists( 'maintClass', $vars ) ) {
756 self
::$mCoreScripts[$vars['maintClass']] = $file;
762 return self
::$mCoreScripts;