RELEASE-NOTES typo
[mediawiki.git] / maintenance / Maintenance.php
blob394b0a41bb55c7bebc66f71b084acc3f895f1ab2
1 <?php
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" );
11 die();
14 /**
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>
36 * @since 1.16
37 * @ingroup Maintenance
39 abstract class Maintenance {
41 /**
42 * Constants for DB access type
43 * @see Maintenance::getDbType()
45 const DB_NONE = 0;
46 const DB_STD = 1;
47 const DB_ADMIN = 2;
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
65 protected $mSelf;
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;
81 /**
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;
88 /**
89 * Default constructor. Children should call this if implementing
90 * their own constructors
92 public function __construct() {
93 $this->addDefaultParams();
96 /**
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
117 * @return boolean
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
127 * @return mixed
129 protected function getOption( $name, $default = null ) {
130 if( $this->hasOption( $name ) ) {
131 return $this->mOptions[$name];
132 } else {
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
141 * @param $arg String Name of the arg, like 'start'
142 * @param $description String Short description of the arg
143 * @param $required Boolean Is this required?
145 protected function addArg( $arg, $description, $required = true ) {
146 $this->mArgList[] = array(
147 'name' => $arg,
148 'desc' => $description,
149 'require' => $required
154 * Does a given argument exist?
155 * @param $argId int The integer value (from zero) for the arg
156 * @return boolean
158 protected function hasArg( $argId = 0 ) {
159 return isset( $this->mArgs[$argId] );
163 * Get an argument.
164 * @param $argId int The integer value (from zero) for the arg
165 * @param $default mixed The default if it doesn't exist
166 * @return mixed
168 protected function getArg( $argId = 0, $default = null ) {
169 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
173 * Set the batch size.
174 * @param $s int The number of operations to do in a batch
176 protected function setBatchSize( $s = 0 ) {
177 $this->mBatchSize = $s;
181 * Get the script's name
182 * @return String
184 public function getName() {
185 return $this->mSelf;
189 * Return input from stdin.
190 * @param $length int The number of bytes to read. If null,
191 * just return the handle. Maintenance::STDIN_ALL returns
192 * the full length
193 * @return mixed
195 protected function getStdin( $len = null ) {
196 if ( $len == Maintenance::STDIN_ALL )
197 return file_get_contents( 'php://stdin' );
198 $f = fopen( 'php://stdin', 'rt' );
199 if( !$len )
200 return $f;
201 $input = fgets( $f, $len );
202 fclose( $f );
203 return rtrim( $input );
207 * Throw some output to the user. Scripts can call this with no fears,
208 * as we handle all --quiet stuff here
209 * @param $out String The text to show to the user
211 protected function output( $out ) {
212 if( $this->mQuiet ) {
213 return;
215 $f = fopen( 'php://stdout', 'w' );
216 fwrite( $f, $out );
217 fclose( $f );
221 * Throw an error to the user. Doesn't respect --quiet, so don't use
222 * this for non-error output
223 * @param $err String The error to display
224 * @param $die boolean If true, go ahead and die out.
226 protected function error( $err, $die = false ) {
227 $f = fopen( 'php://stderr', 'w' );
228 fwrite( $f, $err . "\n" );
229 fclose( $f );
230 if( $die ) die();
234 * Does the script need different DB access? By default, we give Maintenance
235 * scripts normal rights to the DB. Sometimes, a script needs admin rights
236 * access for a reason and sometimes they want no access. Subclasses should
237 * override and return one of the following values, as needed:
238 * Maintenance::DB_NONE - For no DB access at all
239 * Maintenance::DB_STD - For normal DB access, default
240 * Maintenance::DB_ADMIN - For admin DB access
241 * @return int
243 protected function getDbType() {
244 return Maintenance::DB_STD;
248 * Add the default parameters to the scripts
250 private function addDefaultParams() {
251 $this->addOption( 'help', "Display this help message" );
252 $this->addOption( 'quiet', "Whether to supress non-error output" );
253 $this->addOption( 'conf', "Location of LocalSettings.php, if not default", false, true );
254 $this->addOption( 'wiki', "For specifying the wiki ID", false, true );
255 $this->addOption( 'globals', "Output globals at the end of processing for debugging" );
256 // If we support a DB, show the options
257 if( $this->getDbType() > 0 ) {
258 $this->addOption( 'dbuser', "The DB user to use for this script", false, true );
259 $this->addOption( 'dbpass', "The password to use for this script", false, true );
261 // If we support $mBatchSize, show the option
262 if( $this->mBatchSize ) {
263 $this->addOption( 'batch-size', 'Run this many operations ' .
264 'per batch, default: ' . $this->mBatchSize , false, true );
269 * Spawn a child maintenance script. Pass all of the current arguments
270 * to it.
271 * @param $maintClass String A name of a child maintenance class
272 * @param $classFile String Full path of where the child is
273 * @return Maintenance child
275 protected function spawnChild( $maintClass, $classFile = null ) {
276 // If we haven't already specified, kill setup procedures
277 // for child scripts, we've already got a sane environment
278 self::disableSetup();
280 // Make sure the class is loaded first
281 if( !class_exists( $maintClass ) ) {
282 if( $classFile ) {
283 require_once( $classFile );
285 if( !class_exists( $maintClass ) ) {
286 $this->error( "Cannot spawn child: $maintClass" );
290 $child = new $maintClass();
291 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
292 return $child;
296 * Disable Setup.php mostly
298 protected static function disableSetup() {
299 if( !defined( 'MW_NO_SETUP' ) )
300 define( 'MW_NO_SETUP', true );
304 * Do some sanity checking and basic setup
306 public function setup() {
307 global $IP, $wgCommandLineMode, $wgUseNormalUser, $wgRequestTime;
309 # Abort if called from a web server
310 if ( isset( $_SERVER ) && array_key_exists( 'REQUEST_METHOD', $_SERVER ) ) {
311 $this->error( "This script must be run from the command line", true );
314 # Make sure we can handle script parameters
315 if( !ini_get( 'register_argc_argv' ) ) {
316 $this->error( "Cannot get command line arguments, register_argc_argv is set to false", true );
319 if( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
320 // Send PHP warnings and errors to stderr instead of stdout.
321 // This aids in diagnosing problems, while keeping messages
322 // out of redirected output.
323 if( ini_get( 'display_errors' ) ) {
324 ini_set( 'display_errors', 'stderr' );
327 // Don't touch the setting on earlier versions of PHP,
328 // as setting it would disable output if you'd wanted it.
330 // Note that exceptions are also sent to stderr when
331 // command-line mode is on, regardless of PHP version.
334 # Set the memory limit
335 ini_set( 'memory_limit', -1 );
337 # Set max execution time to 0 (no limit). PHP.net says that
338 # "When running PHP from the command line the default setting is 0."
339 # But sometimes this doesn't seem to be the case.
340 ini_set( 'max_execution_time', 0 );
342 $wgRequestTime = microtime( true );
344 # Define us as being in MediaWiki
345 define( 'MEDIAWIKI', true );
347 # Setup $IP, using MW_INSTALL_PATH if it exists
348 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
349 ? getenv( 'MW_INSTALL_PATH' )
350 : realpath( dirname( __FILE__ ) . '/..' );
352 $wgCommandLineMode = true;
353 # Turn off output buffering if it's on
354 @ob_end_flush();
356 if ( !isset( $wgUseNormalUser ) ) {
357 $wgUseNormalUser = false;
360 $this->loadParamsAndArgs();
361 $this->maybeHelp();
362 $this->validateParamsAndArgs();
366 * Clear all params and arguments.
368 public function clearParamsAndArgs() {
369 $this->mOptions = array();
370 $this->mArgs = array();
371 $this->mInputLoaded = false;
375 * Process command line arguments
376 * $mOptions becomes an array with keys set to the option names
377 * $mArgs becomes a zero-based array containing the non-option arguments
379 * @param $self String The name of the script, if any
380 * @param $opts Array An array of options, in form of key=>value
381 * @param $args Array An array of command line arguments
383 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
384 # If we were given opts or args, set those and return early
385 if( $self ) {
386 $this->mSelf = $self;
387 $this->mInputLoaded = true;
389 if( $opts ) {
390 $this->mOptions = $opts;
391 $this->mInputLoaded = true;
393 if( $args ) {
394 $this->mArgs = $args;
395 $this->mInputLoaded = true;
398 # If we've already loaded input (either by user values or from $argv)
399 # skip on loading it again. The array_shift() will corrupt values if
400 # it's run again and again
401 if( $this->mInputLoaded ) {
402 $this->loadSpecialVars();
403 return;
406 global $argv;
407 $this->mSelf = array_shift( $argv );
409 $options = array();
410 $args = array();
412 # Parse arguments
413 for( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
414 if ( $arg == '--' ) {
415 # End of options, remainder should be considered arguments
416 $arg = next( $argv );
417 while( $arg !== false ) {
418 $args[] = $arg;
419 $arg = next( $argv );
421 break;
422 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
423 # Long options
424 $option = substr( $arg, 2 );
425 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
426 $param = next( $argv );
427 if ( $param === false ) {
428 $this->error( "\nERROR: $option needs a value after it\n" );
429 $this->maybeHelp( true );
431 $options[$option] = $param;
432 } else {
433 $bits = explode( '=', $option, 2 );
434 if( count( $bits ) > 1 ) {
435 $option = $bits[0];
436 $param = $bits[1];
437 } else {
438 $param = 1;
440 $options[$option] = $param;
442 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
443 # Short options
444 for ( $p=1; $p<strlen( $arg ); $p++ ) {
445 $option = $arg{$p};
446 if ( $this->mParams[$option]['withArg'] ) {
447 $param = next( $argv );
448 if ( $param === false ) {
449 $this->error( "\nERROR: $option needs a value after it\n" );
450 $this->maybeHelp( true );
452 $options[$option] = $param;
453 } else {
454 $options[$option] = 1;
457 } else {
458 $args[] = $arg;
462 $this->mOptions = $options;
463 $this->mArgs = $args;
464 $this->loadSpecialVars();
465 $this->mInputLoaded = true;
469 * Run some validation checks on the params, etc
471 private function validateParamsAndArgs() {
472 $die = false;
473 # Check to make sure we've got all the required options
474 foreach( $this->mParams as $opt => $info ) {
475 if( $info['require'] && !$this->hasOption( $opt ) ) {
476 $this->error( "Param $opt required!" );
477 $die = true;
480 # Check arg list too
481 foreach( $this->mArgList as $k => $info ) {
482 if( $info['require'] && !$this->hasArg($k) ) {
483 $this->error( "Argument <" . $info['name'] . "> required!" );
484 $die = true;
488 if( $die ) $this->maybeHelp( true );
492 * Handle the special variables that are global to all scripts
494 private function loadSpecialVars() {
495 if( $this->hasOption( 'dbuser' ) )
496 $this->mDbUser = $this->getOption( 'dbuser' );
497 if( $this->hasOption( 'dbpass' ) )
498 $this->mDbPass = $this->getOption( 'dbpass' );
499 if( $this->hasOption( 'quiet' ) )
500 $this->mQuiet = true;
501 if( $this->hasOption( 'batch-size' ) )
502 $this->mBatchSize = $this->getOption( 'batch-size' );
506 * Maybe show the help.
507 * @param $force boolean Whether to force the help to show, default false
509 private function maybeHelp( $force = false ) {
510 ksort( $this->mParams );
511 if( $this->hasOption( 'help' ) || in_array( 'help', $this->mArgs ) || $force ) {
512 $this->mQuiet = false;
513 if( $this->mDescription ) {
514 $this->output( "\n" . $this->mDescription . "\n" );
516 $this->output( "\nUsage: php " . $this->mSelf );
517 if( $this->mParams ) {
518 $this->output( " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]" );
520 if( $this->mArgList ) {
521 $this->output( " <" );
522 foreach( $this->mArgList as $k => $arg ) {
523 $this->output( $arg['name'] . ">" );
524 if( $k < count( $this->mArgList ) - 1 )
525 $this->output( " <" );
528 $this->output( "\n" );
529 foreach( $this->mParams as $par => $info ) {
530 $this->output( "\t$par : " . $info['desc'] . "\n" );
532 foreach( $this->mArgList as $info ) {
533 $this->output( "\t<" . $info['name'] . "> : " . $info['desc'] . "\n" );
535 die( 1 );
540 * Handle some last-minute setup here.
542 public function finalSetup() {
543 global $wgCommandLineMode, $wgUseNormalUser, $wgShowSQLErrors;
544 global $wgTitle, $wgProfiling, $IP, $wgDBadminuser, $wgDBadminpassword;
545 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
547 # Turn off output buffering again, it might have been turned on in the settings files
548 if( ob_get_level() ) {
549 ob_end_flush();
551 # Same with these
552 $wgCommandLineMode = true;
554 # If these were passed, use them
555 if( $this->mDbUser )
556 $wgDBadminuser = $this->mDbUser;
557 if( $this->mDbPass )
558 $wgDBadminpassword = $this->mDbPass;
560 if ( empty( $wgUseNormalUser ) && isset( $wgDBadminuser ) ) {
561 $wgDBuser = $wgDBadminuser;
562 $wgDBpassword = $wgDBadminpassword;
564 if( $wgDBservers ) {
565 foreach ( $wgDBservers as $i => $server ) {
566 $wgDBservers[$i]['user'] = $wgDBuser;
567 $wgDBservers[$i]['password'] = $wgDBpassword;
570 if( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
571 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
572 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
576 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
577 $fn = MW_CMDLINE_CALLBACK;
578 $fn();
581 $wgShowSQLErrors = true;
582 @set_time_limit( 0 );
584 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
588 * Potentially debug globals. Originally a feature only
589 * for refreshLinks
591 public function globals() {
592 if( $this->hasOption( 'globals' ) ) {
593 print_r( $GLOBALS );
598 * Do setup specific to WMF
600 public function loadWikimediaSettings() {
601 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
603 if ( empty( $wgNoDBParam ) ) {
604 # Check if we were passed a db name
605 if ( isset( $this->mOptions['wiki'] ) ) {
606 $db = $this->mOptions['wiki'];
607 } else {
608 $db = array_shift( $this->mArgs );
610 list( $site, $lang ) = $wgConf->siteFromDB( $db );
612 # If not, work out the language and site the old way
613 if ( is_null( $site ) || is_null( $lang ) ) {
614 if ( !$db ) {
615 $lang = 'aa';
616 } else {
617 $lang = $db;
619 if ( isset( $this->mArgs[0] ) ) {
620 $site = array_shift( $this->mArgs );
621 } else {
622 $site = 'wikipedia';
625 } else {
626 $lang = 'aa';
627 $site = 'wikipedia';
630 # This is for the IRC scripts, which now run as the apache user
631 # The apache user doesn't have access to the wikiadmin_pass command
632 if ( $_ENV['USER'] == 'apache' ) {
633 #if ( posix_geteuid() == 48 ) {
634 $wgUseNormalUser = true;
637 putenv( 'wikilang=' . $lang );
639 $DP = $IP;
640 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
642 if ( $lang == 'test' && $site == 'wikipedia' ) {
643 define( 'TESTWIKI', 1 );
648 * Generic setup for most installs. Returns the location of LocalSettings
649 * @return String
651 public function loadSettings() {
652 global $wgWikiFarm, $wgCommandLineMode, $IP, $DP;
654 $wgWikiFarm = false;
655 if ( isset( $this->mOptions['conf'] ) ) {
656 $settingsFile = $this->mOptions['conf'];
657 } else {
658 $settingsFile = "$IP/LocalSettings.php";
660 if ( isset( $this->mOptions['wiki'] ) ) {
661 $bits = explode( '-', $this->mOptions['wiki'] );
662 if ( count( $bits ) == 1 ) {
663 $bits[] = '';
665 define( 'MW_DB', $bits[0] );
666 define( 'MW_PREFIX', $bits[1] );
669 if ( !is_readable( $settingsFile ) ) {
670 $this->error( "A copy of your installation's LocalSettings.php\n" .
671 "must exist and be readable in the source directory.", true );
673 $wgCommandLineMode = true;
674 $DP = $IP;
675 return $settingsFile;
679 * Support function for cleaning up redundant text records
680 * @param $delete boolean Whether or not to actually delete the records
681 * @author Rob Church <robchur@gmail.com>
683 protected function purgeRedundantText( $delete = true ) {
684 # Data should come off the master, wrapped in a transaction
685 $dbw = wfGetDB( DB_MASTER );
686 $dbw->begin();
688 $tbl_arc = $dbw->tableName( 'archive' );
689 $tbl_rev = $dbw->tableName( 'revision' );
690 $tbl_txt = $dbw->tableName( 'text' );
692 # Get "active" text records from the revisions table
693 $this->output( "Searching for active text records in revisions table..." );
694 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
695 foreach( $res as $row ) {
696 $cur[] = $row->rev_text_id;
698 $this->output( "done.\n" );
700 # Get "active" text records from the archive table
701 $this->output( "Searching for active text records in archive table..." );
702 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
703 foreach( $res as $row ) {
704 $cur[] = $row->ar_text_id;
706 $this->output( "done.\n" );
708 # Get the IDs of all text records not in these sets
709 $this->output( "Searching for inactive text records..." );
710 $set = implode( ', ', $cur );
711 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
712 $old = array();
713 foreach( $res as $row ) {
714 $old[] = $row->old_id;
716 $this->output( "done.\n" );
718 # Inform the user of what we're going to do
719 $count = count( $old );
720 $this->output( "$count inactive items found.\n" );
722 # Delete as appropriate
723 if( $delete && $count ) {
724 $this->output( "Deleting..." );
725 $set = implode( ', ', $old );
726 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
727 $this->output( "done.\n" );
730 # Done
731 $dbw->commit();
735 * Get the maintenance directory.
737 protected function getDir() {
738 return dirname( __FILE__ );
742 * Get the list of available maintenance scripts. Note
743 * that if you call this _before_ calling doMaintenance
744 * you won't have any extensions in it yet
745 * @return array
747 public static function getMaintenanceScripts() {
748 global $wgMaintenanceScripts;
749 return $wgMaintenanceScripts + self::getCoreScripts();
753 * Return all of the core maintenance scripts
754 * @return array
756 private static function getCoreScripts() {
757 if( !self::$mCoreScripts ) {
758 self::disableSetup();
759 $paths = array(
760 dirname( __FILE__ ),
761 dirname( __FILE__ ) . '/gearman',
762 dirname( __FILE__ ) . '/language',
763 dirname( __FILE__ ) . '/storage',
765 self::$mCoreScripts = array();
766 foreach( $paths as $p ) {
767 $handle = opendir( $p );
768 while( ( $file = readdir( $handle ) ) !== false ) {
769 if( $file == 'Maintenance.php' )
770 continue;
771 $file = $p . '/' . $file;
772 if( is_dir( $file ) || !strpos( $file, '.php' ) ||
773 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
774 continue;
776 require( $file );
777 $vars = get_defined_vars();
778 if( array_key_exists( 'maintClass', $vars ) ) {
779 self::$mCoreScripts[$vars['maintClass']] = $file;
782 closedir( $handle );
785 return self::$mCoreScripts;