5 * @defgroup Maintenance Maintenance
8 // Define this so scripts can easily find doMaintenance.php
9 define( 'DO_MAINTENANCE', dirname( __FILE__ ) . '/doMaintenance.php' );
12 // Make sure we're on PHP5 or better
13 if( version_compare( PHP_VERSION, '5.0.0' ) < 0 ) {
14 echo( "Sorry! This version of MediaWiki requires PHP 5; you are running " .
15 PHP_VERSION . ".\n\n" .
16 "If you are sure you already have PHP 5 installed, it may be installed\n" .
17 "in a different path from PHP 4. Check with your system administrator.\n" );
22 * Abstract maintenance class for quickly writing and churning out
23 * maintenance scripts with minimal effort. All that _must_ be defined
24 * is the execute() method. See docs/maintenance.txt for more info
25 * and a quick demo of how to use it.
27 * This program is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation; either version 2 of the License, or
30 * (at your option) any later version.
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
37 * You should have received a copy of the GNU General Public License along
38 * with this program; if not, write to the Free Software Foundation, Inc.,
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
40 * http://www.gnu.org/copyleft/gpl.html
42 * @author Chad Horohoe <chad@anyonecanedit.org>
44 * @ingroup Maintenance
46 abstract class Maintenance {
49 * Constants for DB access type
50 * @see Maintenance::getDbType()
56 // Const for getStdin()
57 const STDIN_ALL = 'all';
59 // This is the desired params
60 protected $mParams = array();
62 // Array of desired args
63 protected $mArgList = array();
65 // This is the list of options that were actually passed
66 protected $mOptions = array();
68 // This is the list of arguments that were actually passed
69 protected $mArgs = array();
71 // Name of the script currently running
74 // Special vars for params that are always used
75 protected $mQuiet = false;
76 protected $mDbUser, $mDbPass;
78 // A description of the script, children should change this
79 protected $mDescription = '';
81 // Have we already loaded our user input?
82 protected $mInputLoaded = false;
84 // Batch size. If a script supports this, they should set
85 // a default with setBatchSize()
86 protected $mBatchSize = null;
89 * List of all the core maintenance scripts. This is added
90 * to scripts added by extensions in $wgMaintenanceScripts
91 * and returned by getMaintenanceScripts()
93 protected static $mCoreScripts = null;
96 * Default constructor. Children should call this if implementing
97 * their own constructors
99 public function __construct() {
100 $this->addDefaultParams();
101 register_shutdown_function( array( $this, 'outputChanneled' ), false );
105 * Do the actual work. All child classes will need to implement this
107 abstract public function execute();
110 * Add a parameter to the script. Will be displayed on --help
111 * with the associated description
113 * @param $name String The name of the param (help, version, etc)
114 * @param $description String The description of the param to show on --help
115 * @param $required boolean Is the param required?
116 * @param $withArg Boolean Is an argument required with this option?
118 protected function addOption( $name, $description, $required = false, $withArg = false ) {
119 $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg );
123 * Checks to see if a particular param exists.
124 * @param $name String The name of the param
127 protected function hasOption( $name ) {
128 return isset( $this->mOptions[$name] );
132 * Get an option, or return the default
133 * @param $name String The name of the param
134 * @param $default mixed Anything you want, default null
137 protected function getOption( $name, $default = null ) {
138 if( $this->hasOption( $name ) ) {
139 return $this->mOptions[$name];
141 // Set it so we don't have to provide the default again
142 $this->mOptions[$name] = $default;
143 return $this->mOptions[$name];
148 * Add some args that are needed
149 * @param $arg String Name of the arg, like 'start'
150 * @param $description String Short description of the arg
151 * @param $required Boolean Is this required?
153 protected function addArg( $arg, $description, $required = true ) {
154 $this->mArgList[] = array(
156 'desc' => $description,
157 'require' => $required
162 * Does a given argument exist?
163 * @param $argId int The integer value (from zero) for the arg
166 protected function hasArg( $argId = 0 ) {
167 return isset( $this->mArgs[$argId] );
172 * @param $argId int The integer value (from zero) for the arg
173 * @param $default mixed The default if it doesn't exist
176 protected function getArg( $argId = 0, $default = null ) {
177 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
181 * Set the batch size.
182 * @param $s int The number of operations to do in a batch
184 protected function setBatchSize( $s = 0 ) {
185 $this->mBatchSize = $s;
189 * Get the script's name
192 public function getName() {
197 * Return input from stdin.
198 * @param $length int The number of bytes to read. If null,
199 * just return the handle. Maintenance::STDIN_ALL returns
203 protected function getStdin( $len = null ) {
204 if ( $len == Maintenance::STDIN_ALL )
205 return file_get_contents( 'php://stdin' );
206 $f = fopen( 'php://stdin', 'rt' );
209 $input = fgets( $f, $len );
211 return rtrim( $input );
215 * Throw some output to the user. Scripts can call this with no fears,
216 * as we handle all --quiet stuff here
217 * @param $out String The text to show to the user
218 * @param $channel Mixed Unique identifier for the channel. See function outputChanneled.
220 protected function output( $out, $channel = null ) {
221 if( $this->mQuiet ) {
224 if ( $channel === null ) {
225 $f = fopen( 'php://stdout', 'w' );
230 $out = preg_replace( '/\n\z/', '', $out );
231 $this->outputChanneled( $out, $channel );
236 * Throw an error to the user. Doesn't respect --quiet, so don't use
237 * this for non-error output
238 * @param $err String The error to display
239 * @param $die boolean If true, go ahead and die out.
241 protected function error( $err, $die = false ) {
242 $this->outputChanneled( false );
243 if ( php_sapi_name() == 'cli' ) {
244 fwrite( STDERR, $err . "\n" );
246 $f = fopen( 'php://stderr', 'w' );
247 fwrite( $f, $err . "\n" );
253 private $atLineStart = true;
254 private $lastChannel = null;
257 * Message outputter with channeled message support. Messages on the
258 * same channel are concatenated, but any intervening messages in another
259 * channel start a new line.
260 * @param $msg String The message without trailing newline
261 * @param $channel Channel identifier or null for no channel. Channel comparison uses ===.
263 public function outputChanneled( $msg, $channel = null ) {
264 $handle = fopen( 'php://stdout', 'w' );
266 if ( $msg === false ) {
268 if ( !$this->atLineStart ) fwrite( $handle, "\n" );
273 // End the current line if necessary
274 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
275 fwrite( $handle, "\n" );
278 fwrite( $handle, $msg );
280 $this->atLineStart = false;
281 if ( $channel === null ) {
282 // For unchanneled messages, output trailing newline immediately
283 fwrite( $handle, "\n" );
284 $this->atLineStart = true;
286 $this->lastChannel = $channel;
293 * Does the script need different DB access? By default, we give Maintenance
294 * scripts normal rights to the DB. Sometimes, a script needs admin rights
295 * access for a reason and sometimes they want no access. Subclasses should
296 * override and return one of the following values, as needed:
297 * Maintenance::DB_NONE - For no DB access at all
298 * Maintenance::DB_STD - For normal DB access, default
299 * Maintenance::DB_ADMIN - For admin DB access
302 public function getDbType() {
303 return Maintenance::DB_STD;
307 * Add the default parameters to the scripts
309 protected function addDefaultParams() {
310 $this->addOption( 'help', "Display this help message" );
311 $this->addOption( 'quiet', "Whether to supress non-error output" );
312 $this->addOption( 'conf', "Location of LocalSettings.php, if not default", false, true );
313 $this->addOption( 'wiki', "For specifying the wiki ID", false, true );
314 $this->addOption( 'globals', "Output globals at the end of processing for debugging" );
315 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g.\n" .
316 "\t\thttp://en.wikipedia.org. This is sometimes necessary because\n" .
317 "\t\tserver name detection may fail in command line scripts.", false, true );
318 // If we support a DB, show the options
319 if( $this->getDbType() > 0 ) {
320 $this->addOption( 'dbuser', "The DB user to use for this script", false, true );
321 $this->addOption( 'dbpass', "The password to use for this script", false, true );
323 // If we support $mBatchSize, show the option
324 if( $this->mBatchSize ) {
325 $this->addOption( 'batch-size', 'Run this many operations ' .
326 'per batch, default: ' . $this->mBatchSize , false, true );
331 * Run a child maintenance script. Pass all of the current arguments
333 * @param $maintClass String A name of a child maintenance class
334 * @param $classFile String Full path of where the child is
335 * @return Maintenance child
337 protected function runChild( $maintClass, $classFile = null ) {
338 // If we haven't already specified, kill setup procedures
339 // for child scripts, we've already got a sane environment
340 self::disableSetup();
342 // Make sure the class is loaded first
343 if( !class_exists( $maintClass ) ) {
345 require_once( $classFile );
347 if( !class_exists( $maintClass ) ) {
348 $this->error( "Cannot spawn child: $maintClass" );
352 $child = new $maintClass();
353 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
358 * Disable Setup.php mostly
360 protected static function disableSetup() {
361 if( !defined( 'MW_NO_SETUP' ) )
362 define( 'MW_NO_SETUP', true );
366 * Do some sanity checking and basic setup
368 public function setup() {
369 global $IP, $wgCommandLineMode, $wgRequestTime;
371 # Abort if called from a web server
372 if ( isset( $_SERVER ) && array_key_exists( 'REQUEST_METHOD', $_SERVER ) ) {
373 $this->error( "This script must be run from the command line", true );
376 # Make sure we can handle script parameters
377 if( !ini_get( 'register_argc_argv' ) ) {
378 $this->error( "Cannot get command line arguments, register_argc_argv is set to false", true );
381 if( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
382 // Send PHP warnings and errors to stderr instead of stdout.
383 // This aids in diagnosing problems, while keeping messages
384 // out of redirected output.
385 if( ini_get( 'display_errors' ) ) {
386 ini_set( 'display_errors', 'stderr' );
389 // Don't touch the setting on earlier versions of PHP,
390 // as setting it would disable output if you'd wanted it.
392 // Note that exceptions are also sent to stderr when
393 // command-line mode is on, regardless of PHP version.
396 # Set the memory limit
397 # Note we need to set it again later in cache LocalSettings changed it
398 ini_set( 'memory_limit', $this->memoryLimit() );
400 # Set max execution time to 0 (no limit). PHP.net says that
401 # "When running PHP from the command line the default setting is 0."
402 # But sometimes this doesn't seem to be the case.
403 ini_set( 'max_execution_time', 0 );
405 $wgRequestTime = microtime( true );
407 # Define us as being in MediaWiki
408 define( 'MEDIAWIKI', true );
410 # Setup $IP, using MW_INSTALL_PATH if it exists
411 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
412 ? getenv( 'MW_INSTALL_PATH' )
413 : realpath( dirname( __FILE__ ) . '/..' );
415 $wgCommandLineMode = true;
416 # Turn off output buffering if it's on
419 $this->loadParamsAndArgs();
421 $this->validateParamsAndArgs();
425 * Normally we disable the memory_limit when running admin scripts.
426 * Some scripts may wish to actually set a limit, however, to avoid
427 * blowing up unexpectedly.
429 public function memoryLimit() {
434 * Clear all params and arguments.
436 public function clearParamsAndArgs() {
437 $this->mOptions = array();
438 $this->mArgs = array();
439 $this->mInputLoaded = false;
443 * Process command line arguments
444 * $mOptions becomes an array with keys set to the option names
445 * $mArgs becomes a zero-based array containing the non-option arguments
447 * @param $self String The name of the script, if any
448 * @param $opts Array An array of options, in form of key=>value
449 * @param $args Array An array of command line arguments
451 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
452 # If we were given opts or args, set those and return early
454 $this->mSelf = $self;
455 $this->mInputLoaded = true;
458 $this->mOptions = $opts;
459 $this->mInputLoaded = true;
462 $this->mArgs = $args;
463 $this->mInputLoaded = true;
466 # If we've already loaded input (either by user values or from $argv)
467 # skip on loading it again. The array_shift() will corrupt values if
468 # it's run again and again
469 if( $this->mInputLoaded ) {
470 $this->loadSpecialVars();
475 $this->mSelf = array_shift( $argv );
481 for( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
482 if ( $arg == '--' ) {
483 # End of options, remainder should be considered arguments
484 $arg = next( $argv );
485 while( $arg !== false ) {
487 $arg = next( $argv );
490 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
492 $option = substr( $arg, 2 );
493 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
494 $param = next( $argv );
495 if ( $param === false ) {
496 $this->error( "\nERROR: $option needs a value after it\n" );
497 $this->maybeHelp( true );
499 $options[$option] = $param;
501 $bits = explode( '=', $option, 2 );
502 if( count( $bits ) > 1 ) {
508 $options[$option] = $param;
510 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
512 for ( $p=1; $p<strlen( $arg ); $p++ ) {
514 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
515 $param = next( $argv );
516 if ( $param === false ) {
517 $this->error( "\nERROR: $option needs a value after it\n" );
518 $this->maybeHelp( true );
520 $options[$option] = $param;
522 $options[$option] = 1;
530 $this->mOptions = $options;
531 $this->mArgs = $args;
532 $this->loadSpecialVars();
533 $this->mInputLoaded = true;
537 * Run some validation checks on the params, etc
539 protected function validateParamsAndArgs() {
541 # Check to make sure we've got all the required options
542 foreach( $this->mParams as $opt => $info ) {
543 if( $info['require'] && !$this->hasOption( $opt ) ) {
544 $this->error( "Param $opt required!" );
549 foreach( $this->mArgList as $k => $info ) {
550 if( $info['require'] && !$this->hasArg($k) ) {
551 $this->error( "Argument <" . $info['name'] . "> required!" );
556 if( $die ) $this->maybeHelp( true );
560 * Handle the special variables that are global to all scripts
562 protected function loadSpecialVars() {
563 if( $this->hasOption( 'dbuser' ) )
564 $this->mDbUser = $this->getOption( 'dbuser' );
565 if( $this->hasOption( 'dbpass' ) )
566 $this->mDbPass = $this->getOption( 'dbpass' );
567 if( $this->hasOption( 'quiet' ) )
568 $this->mQuiet = true;
569 if( $this->hasOption( 'batch-size' ) )
570 $this->mBatchSize = $this->getOption( 'batch-size' );
574 * Maybe show the help.
575 * @param $force boolean Whether to force the help to show, default false
577 protected function maybeHelp( $force = false ) {
578 $screenWidth = 80; // TODO: Caculate this!
580 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
582 ksort( $this->mParams );
583 if( $this->hasOption( 'help' ) || $force ) {
584 $this->mQuiet = false;
586 if( $this->mDescription ) {
587 $this->output( "\n" . $this->mDescription . "\n" );
589 $output = "\nUsage: php " . basename( $this->mSelf );
590 if( $this->mParams ) {
591 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
593 if( $this->mArgList ) {
595 foreach( $this->mArgList as $k => $arg ) {
596 $output .= $arg['name'] . ">";
597 if( $k < count( $this->mArgList ) - 1 )
601 $this->output( "$output\n" );
602 foreach( $this->mParams as $par => $info ) {
603 $this->output( wordwrap( "$tab$par : " . $info['desc'], $descWidth,
604 "\n$tab$tab" ) . "\n" );
606 foreach( $this->mArgList as $info ) {
607 $this->output( wordwrap( "$tab<" . $info['name'] . "> : " .
608 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n" );
615 * Handle some last-minute setup here.
617 public function finalSetup() {
618 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
619 global $wgTitle, $wgProfiling, $IP, $wgDBadminuser, $wgDBadminpassword;
620 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
622 # Turn off output buffering again, it might have been turned on in the settings files
623 if( ob_get_level() ) {
627 $wgCommandLineMode = true;
630 if( $this->hasOption( 'server') ) {
631 $wgServer = $this->getOption( 'server', $wgServer );
634 # If these were passed, use them
636 $wgDBadminuser = $this->mDbUser;
638 $wgDBadminpassword = $this->mDbPass;
640 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
641 $wgDBuser = $wgDBadminuser;
642 $wgDBpassword = $wgDBadminpassword;
645 foreach ( $wgDBservers as $i => $server ) {
646 $wgDBservers[$i]['user'] = $wgDBuser;
647 $wgDBservers[$i]['password'] = $wgDBpassword;
650 if( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
651 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
652 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
656 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
657 $fn = MW_CMDLINE_CALLBACK;
661 $wgShowSQLErrors = true;
662 @set_time_limit( 0 );
663 ini_set( 'memory_limit', $this->memoryLimit() );
665 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
669 * Potentially debug globals. Originally a feature only
672 public function globals() {
673 if( $this->hasOption( 'globals' ) ) {
679 * Do setup specific to WMF
681 public function loadWikimediaSettings() {
682 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
684 if ( empty( $wgNoDBParam ) ) {
685 # Check if we were passed a db name
686 if ( isset( $this->mOptions['wiki'] ) ) {
687 $db = $this->mOptions['wiki'];
689 $db = array_shift( $this->mArgs );
691 list( $site, $lang ) = $wgConf->siteFromDB( $db );
693 # If not, work out the language and site the old way
694 if ( is_null( $site ) || is_null( $lang ) ) {
700 if ( isset( $this->mArgs[0] ) ) {
701 $site = array_shift( $this->mArgs );
711 # This is for the IRC scripts, which now run as the apache user
712 # The apache user doesn't have access to the wikiadmin_pass command
713 if ( $_ENV['USER'] == 'apache' ) {
714 #if ( posix_geteuid() == 48 ) {
715 $wgUseNormalUser = true;
718 putenv( 'wikilang=' . $lang );
721 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
723 if ( $lang == 'test' && $site == 'wikipedia' ) {
724 define( 'TESTWIKI', 1 );
729 * Generic setup for most installs. Returns the location of LocalSettings
732 public function loadSettings() {
733 global $wgWikiFarm, $wgCommandLineMode, $IP, $DP;
736 if ( isset( $this->mOptions['conf'] ) ) {
737 $settingsFile = $this->mOptions['conf'];
739 $settingsFile = "$IP/LocalSettings.php";
741 if ( isset( $this->mOptions['wiki'] ) ) {
742 $bits = explode( '-', $this->mOptions['wiki'] );
743 if ( count( $bits ) == 1 ) {
746 define( 'MW_DB', $bits[0] );
747 define( 'MW_PREFIX', $bits[1] );
750 if ( !is_readable( $settingsFile ) ) {
751 $this->error( "A copy of your installation's LocalSettings.php\n" .
752 "must exist and be readable in the source directory.", true );
754 $wgCommandLineMode = true;
756 return $settingsFile;
760 * Support function for cleaning up redundant text records
761 * @param $delete boolean Whether or not to actually delete the records
762 * @author Rob Church <robchur@gmail.com>
764 protected function purgeRedundantText( $delete = true ) {
765 # Data should come off the master, wrapped in a transaction
766 $dbw = wfGetDB( DB_MASTER );
769 $tbl_arc = $dbw->tableName( 'archive' );
770 $tbl_rev = $dbw->tableName( 'revision' );
771 $tbl_txt = $dbw->tableName( 'text' );
773 # Get "active" text records from the revisions table
774 $this->output( "Searching for active text records in revisions table..." );
775 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
776 foreach( $res as $row ) {
777 $cur[] = $row->rev_text_id;
779 $this->output( "done.\n" );
781 # Get "active" text records from the archive table
782 $this->output( "Searching for active text records in archive table..." );
783 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
784 foreach( $res as $row ) {
785 $cur[] = $row->ar_text_id;
787 $this->output( "done.\n" );
789 # Get the IDs of all text records not in these sets
790 $this->output( "Searching for inactive text records..." );
791 $set = implode( ', ', $cur );
792 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
794 foreach( $res as $row ) {
795 $old[] = $row->old_id;
797 $this->output( "done.\n" );
799 # Inform the user of what we're going to do
800 $count = count( $old );
801 $this->output( "$count inactive items found.\n" );
803 # Delete as appropriate
804 if( $delete && $count ) {
805 $this->output( "Deleting..." );
806 $set = implode( ', ', $old );
807 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
808 $this->output( "done.\n" );
816 * Get the maintenance directory.
818 protected function getDir() {
819 return dirname( __FILE__ );
823 * Get the list of available maintenance scripts. Note
824 * that if you call this _before_ calling doMaintenance
825 * you won't have any extensions in it yet
828 public static function getMaintenanceScripts() {
829 global $wgMaintenanceScripts;
830 return $wgMaintenanceScripts + self::getCoreScripts();
834 * Return all of the core maintenance scripts
837 protected static function getCoreScripts() {
838 if( !self::$mCoreScripts ) {
839 self::disableSetup();
842 dirname( __FILE__ ) . '/gearman',
843 dirname( __FILE__ ) . '/language',
844 dirname( __FILE__ ) . '/storage',
846 self::$mCoreScripts = array();
847 foreach( $paths as $p ) {
848 $handle = opendir( $p );
849 while( ( $file = readdir( $handle ) ) !== false ) {
850 if( $file == 'Maintenance.php' )
852 $file = $p . '/' . $file;
853 if( is_dir( $file ) || !strpos( $file, '.php' ) ||
854 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
858 $vars = get_defined_vars();
859 if( array_key_exists( 'maintClass', $vars ) ) {
860 self::$mCoreScripts[$vars['maintClass']] = $file;
866 return self::$mCoreScripts;