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.1.0' ) < 0 ) {
14 die ( "Sorry! This version of MediaWiki requires PHP 5.1.x; you are running " .
15 PHP_VERSION
. ".\n\n" .
16 "If you are sure you already have PHP 5.1.x or higher installed, it may be\n" .
17 "installed in a different path from PHP " . PHP_VERSION
. ". Check with your system\n" .
21 // Wrapper for posix_isatty()
22 if ( !function_exists( 'posix_isatty' ) ) {
23 # We default as considering stdin a tty (for nice readline methods)
24 # but treating stout as not a tty to avoid color codes
25 function posix_isatty( $fd ) {
31 * Abstract maintenance class for quickly writing and churning out
32 * maintenance scripts with minimal effort. All that _must_ be defined
33 * is the execute() method. See docs/maintenance.txt for more info
34 * and a quick demo of how to use it.
36 * This program is free software; you can redistribute it and/or modify
37 * it under the terms of the GNU General Public License as published by
38 * the Free Software Foundation; either version 2 of the License, or
39 * (at your option) any later version.
41 * This program is distributed in the hope that it will be useful,
42 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 * GNU General Public License for more details.
46 * You should have received a copy of the GNU General Public License along
47 * with this program; if not, write to the Free Software Foundation, Inc.,
48 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
49 * http://www.gnu.org/copyleft/gpl.html
51 * @author Chad Horohoe <chad@anyonecanedit.org>
53 * @ingroup Maintenance
55 abstract class Maintenance
{
58 * Constants for DB access type
59 * @see Maintenance::getDbType()
65 // Const for getStdin()
66 const STDIN_ALL
= 'all';
68 // This is the desired params
69 protected $mParams = array();
71 // Array of desired args
72 protected $mArgList = array();
74 // This is the list of options that were actually passed
75 protected $mOptions = array();
77 // This is the list of arguments that were actually passed
78 protected $mArgs = array();
80 // Name of the script currently running
83 // Special vars for params that are always used
84 protected $mQuiet = false;
85 protected $mDbUser, $mDbPass;
87 // A description of the script, children should change this
88 protected $mDescription = '';
90 // Have we already loaded our user input?
91 protected $mInputLoaded = false;
93 // Batch size. If a script supports this, they should set
94 // a default with setBatchSize()
95 protected $mBatchSize = null;
98 * List of all the core maintenance scripts. This is added
99 * to scripts added by extensions in $wgMaintenanceScripts
100 * and returned by getMaintenanceScripts()
102 protected static $mCoreScripts = null;
105 * Default constructor. Children should call this if implementing
106 * their own constructors
108 public function __construct() {
109 $this->addDefaultParams();
110 register_shutdown_function( array( $this, 'outputChanneled' ), false );
114 * Do the actual work. All child classes will need to implement this
116 abstract public function execute();
119 * Add a parameter to the script. Will be displayed on --help
120 * with the associated description
122 * @param $name String: the name of the param (help, version, etc)
123 * @param $description String: the description of the param to show on --help
124 * @param $required Boolean: is the param required?
125 * @param $withArg Boolean: is an argument required with this option?
127 protected function addOption( $name, $description, $required = false, $withArg = false ) {
128 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg );
132 * Checks to see if a particular param exists.
133 * @param $name String: the name of the param
136 protected function hasOption( $name ) {
137 return isset( $this->mOptions
[$name] );
141 * Get an option, or return the default
142 * @param $name String: the name of the param
143 * @param $default Mixed: anything you want, default null
146 protected function getOption( $name, $default = null ) {
147 if ( $this->hasOption( $name ) ) {
148 return $this->mOptions
[$name];
150 // Set it so we don't have to provide the default again
151 $this->mOptions
[$name] = $default;
152 return $this->mOptions
[$name];
157 * Add some args that are needed
158 * @param $arg String: name of the arg, like 'start'
159 * @param $description String: short description of the arg
160 * @param $required Boolean: is this required?
162 protected function addArg( $arg, $description, $required = true ) {
163 $this->mArgList
[] = array(
165 'desc' => $description,
166 'require' => $required
171 * Remove an option. Useful for removing options that won't be used in your script.
172 * @param $name String: the option to remove.
174 protected function deleteOption( $name ) {
175 unset( $this->mParams
[$name] );
179 * Set the description text.
180 * @param $text String: the text of the description
182 protected function addDescription( $text ) {
183 $this->mDescription
= $text;
187 * Does a given argument exist?
188 * @param $argId Integer: the integer value (from zero) for the arg
191 protected function hasArg( $argId = 0 ) {
192 return isset( $this->mArgs
[$argId] );
197 * @param $argId Integer: the integer value (from zero) for the arg
198 * @param $default Mixed: the default if it doesn't exist
201 protected function getArg( $argId = 0, $default = null ) {
202 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
206 * Set the batch size.
207 * @param $s Integer: the number of operations to do in a batch
209 protected function setBatchSize( $s = 0 ) {
210 $this->mBatchSize
= $s;
214 * Get the script's name
217 public function getName() {
222 * Return input from stdin.
223 * @param $len Integer: the number of bytes to read. If null,
224 * just return the handle. Maintenance::STDIN_ALL returns
228 protected function getStdin( $len = null ) {
229 if ( $len == Maintenance
::STDIN_ALL
) {
230 return file_get_contents( 'php://stdin' );
232 $f = fopen( 'php://stdin', 'rt' );
236 $input = fgets( $f, $len );
238 return rtrim( $input );
241 public function isQuiet() {
242 return $this->mQuiet
;
246 * Throw some output to the user. Scripts can call this with no fears,
247 * as we handle all --quiet stuff here
248 * @param $out String: the text to show to the user
249 * @param $channel Mixed: unique identifier for the channel. See
250 * function outputChanneled.
252 protected function output( $out, $channel = null ) {
253 if ( $this->mQuiet
) {
256 if ( $channel === null ) {
257 $this->cleanupChanneled();
259 $f = fopen( 'php://stdout', 'w' );
264 $out = preg_replace( '/\n\z/', '', $out );
265 $this->outputChanneled( $out, $channel );
270 * Throw an error to the user. Doesn't respect --quiet, so don't use
271 * this for non-error output
272 * @param $err String: the error to display
273 * @param $die Boolean: If true, go ahead and die out.
275 protected function error( $err, $die = false ) {
276 $this->outputChanneled( false );
277 if ( php_sapi_name() == 'cli' ) {
278 fwrite( STDERR
, $err . "\n" );
280 $f = fopen( 'php://stderr', 'w' );
281 fwrite( $f, $err . "\n" );
289 private $atLineStart = true;
290 private $lastChannel = null;
293 * Clean up channeled output. Output a newline if necessary.
295 public function cleanupChanneled() {
296 if ( !$this->atLineStart
) {
297 $handle = fopen( 'php://stdout', 'w' );
298 fwrite( $handle, "\n" );
300 $this->atLineStart
= true;
305 * Message outputter with channeled message support. Messages on the
306 * same channel are concatenated, but any intervening messages in another
307 * channel start a new line.
308 * @param $msg String: the message without trailing newline
309 * @param $channel Channel identifier or null for no
310 * channel. Channel comparison uses ===.
312 public function outputChanneled( $msg, $channel = null ) {
313 if ( $msg === false ) {
314 $this->cleanupChanneled();
318 $handle = fopen( 'php://stdout', 'w' );
320 // End the current line if necessary
321 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
322 fwrite( $handle, "\n" );
325 fwrite( $handle, $msg );
327 $this->atLineStart
= false;
328 if ( $channel === null ) {
329 // For unchanneled messages, output trailing newline immediately
330 fwrite( $handle, "\n" );
331 $this->atLineStart
= true;
333 $this->lastChannel
= $channel;
340 * Does the script need different DB access? By default, we give Maintenance
341 * scripts normal rights to the DB. Sometimes, a script needs admin rights
342 * access for a reason and sometimes they want no access. Subclasses should
343 * override and return one of the following values, as needed:
344 * Maintenance::DB_NONE - For no DB access at all
345 * Maintenance::DB_STD - For normal DB access, default
346 * Maintenance::DB_ADMIN - For admin DB access
349 public function getDbType() {
350 return Maintenance
::DB_STD
;
354 * Add the default parameters to the scripts
356 protected function addDefaultParams() {
357 $this->addOption( 'help', 'Display this help message' );
358 $this->addOption( 'quiet', 'Whether to supress non-error output' );
359 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
360 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
361 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
362 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
363 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g.\n" .
364 "\t\thttp://en.wikipedia.org. This is sometimes necessary because\n" .
365 "\t\tserver name detection may fail in command line scripts.", false, true );
366 // If we support a DB, show the options
367 if ( $this->getDbType() > 0 ) {
368 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
369 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
371 // If we support $mBatchSize, show the option
372 if ( $this->mBatchSize
) {
373 $this->addOption( 'batch-size', 'Run this many operations ' .
374 'per batch, default: ' . $this->mBatchSize
, false, true );
379 * Run a child maintenance script. Pass all of the current arguments
381 * @param $maintClass String: a name of a child maintenance class
382 * @param $classFile String: full path of where the child is
383 * @return Maintenance child
385 public function runChild( $maintClass, $classFile = null ) {
386 // If we haven't already specified, kill setup procedures
387 // for child scripts, we've already got a sane environment
388 self
::disableSetup();
390 // Make sure the class is loaded first
391 if ( !class_exists( $maintClass ) ) {
393 require_once( $classFile );
395 if ( !class_exists( $maintClass ) ) {
396 $this->error( "Cannot spawn child: $maintClass" );
400 $child = new $maintClass();
401 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
406 * Disable Setup.php mostly
408 protected static function disableSetup() {
409 if ( !defined( 'MW_NO_SETUP' ) ) {
410 define( 'MW_NO_SETUP', true );
415 * Do some sanity checking and basic setup
417 public function setup() {
418 global $IP, $wgCommandLineMode, $wgRequestTime;
420 # Abort if called from a web server
421 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
422 $this->error( 'This script must be run from the command line', true );
425 # Make sure we can handle script parameters
426 if ( !ini_get( 'register_argc_argv' ) ) {
427 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
430 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
431 // Send PHP warnings and errors to stderr instead of stdout.
432 // This aids in diagnosing problems, while keeping messages
433 // out of redirected output.
434 if ( ini_get( 'display_errors' ) ) {
435 ini_set( 'display_errors', 'stderr' );
438 // Don't touch the setting on earlier versions of PHP,
439 // as setting it would disable output if you'd wanted it.
441 // Note that exceptions are also sent to stderr when
442 // command-line mode is on, regardless of PHP version.
445 $this->loadParamsAndArgs();
448 # Set the memory limit
449 # Note we need to set it again later in cache LocalSettings changed it
450 $this->adjustMemoryLimit();
452 # Set max execution time to 0 (no limit). PHP.net says that
453 # "When running PHP from the command line the default setting is 0."
454 # But sometimes this doesn't seem to be the case.
455 ini_set( 'max_execution_time', 0 );
457 $wgRequestTime = microtime( true );
459 # Define us as being in MediaWiki
460 define( 'MEDIAWIKI', true );
462 # Setup $IP, using MW_INSTALL_PATH if it exists
463 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
464 ?
getenv( 'MW_INSTALL_PATH' )
465 : realpath( dirname( __FILE__
) . '/..' );
467 $wgCommandLineMode = true;
468 # Turn off output buffering if it's on
471 $this->validateParamsAndArgs();
475 * Normally we disable the memory_limit when running admin scripts.
476 * Some scripts may wish to actually set a limit, however, to avoid
477 * blowing up unexpectedly. We also support a --memory-limit option,
478 * to allow sysadmins to explicitly set one if they'd prefer to override
479 * defaults (or for people using Suhosin which yells at you for trying
480 * to disable the limits)
482 public function memoryLimit() {
483 $limit = $this->getOption( 'memory-limit', 'max' );
484 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
489 * Adjusts PHP's memory limit to better suit our needs, if needed.
491 protected function adjustMemoryLimit() {
492 $limit = $this->memoryLimit();
493 if ( $limit == 'max' ) {
494 $limit = -1; // no memory limit
496 if ( $limit != 'default' ) {
497 ini_set( 'memory_limit', $limit );
502 * Clear all params and arguments.
504 public function clearParamsAndArgs() {
505 $this->mOptions
= array();
506 $this->mArgs
= array();
507 $this->mInputLoaded
= false;
511 * Process command line arguments
512 * $mOptions becomes an array with keys set to the option names
513 * $mArgs becomes a zero-based array containing the non-option arguments
515 * @param $self String The name of the script, if any
516 * @param $opts Array An array of options, in form of key=>value
517 * @param $args Array An array of command line arguments
519 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
520 # If we were given opts or args, set those and return early
522 $this->mSelf
= $self;
523 $this->mInputLoaded
= true;
526 $this->mOptions
= $opts;
527 $this->mInputLoaded
= true;
530 $this->mArgs
= $args;
531 $this->mInputLoaded
= true;
534 # If we've already loaded input (either by user values or from $argv)
535 # skip on loading it again. The array_shift() will corrupt values if
536 # it's run again and again
537 if ( $this->mInputLoaded
) {
538 $this->loadSpecialVars();
543 $this->mSelf
= array_shift( $argv );
549 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
550 if ( $arg == '--' ) {
551 # End of options, remainder should be considered arguments
552 $arg = next( $argv );
553 while ( $arg !== false ) {
555 $arg = next( $argv );
558 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
560 $option = substr( $arg, 2 );
561 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
562 $param = next( $argv );
563 if ( $param === false ) {
564 $this->error( "\nERROR: $option needs a value after it\n" );
565 $this->maybeHelp( true );
567 $options[$option] = $param;
569 $bits = explode( '=', $option, 2 );
570 if ( count( $bits ) > 1 ) {
576 $options[$option] = $param;
578 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
580 for ( $p = 1; $p < strlen( $arg ); $p++
) {
581 $option = $arg { $p } ;
582 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
583 $param = next( $argv );
584 if ( $param === false ) {
585 $this->error( "\nERROR: $option needs a value after it\n" );
586 $this->maybeHelp( true );
588 $options[$option] = $param;
590 $options[$option] = 1;
598 $this->mOptions
= $options;
599 $this->mArgs
= $args;
600 $this->loadSpecialVars();
601 $this->mInputLoaded
= true;
605 * Run some validation checks on the params, etc
607 protected function validateParamsAndArgs() {
609 # Check to make sure we've got all the required options
610 foreach ( $this->mParams
as $opt => $info ) {
611 if ( $info['require'] && !$this->hasOption( $opt ) ) {
612 $this->error( "Param $opt required!" );
617 foreach ( $this->mArgList
as $k => $info ) {
618 if ( $info['require'] && !$this->hasArg( $k ) ) {
619 $this->error( 'Argument <' . $info['name'] . '> required!' );
625 $this->maybeHelp( true );
630 * Handle the special variables that are global to all scripts
632 protected function loadSpecialVars() {
633 if ( $this->hasOption( 'dbuser' ) ) {
634 $this->mDbUser
= $this->getOption( 'dbuser' );
636 if ( $this->hasOption( 'dbpass' ) ) {
637 $this->mDbPass
= $this->getOption( 'dbpass' );
639 if ( $this->hasOption( 'quiet' ) ) {
640 $this->mQuiet
= true;
642 if ( $this->hasOption( 'batch-size' ) ) {
643 $this->mBatchSize
= $this->getOption( 'batch-size' );
648 * Maybe show the help.
649 * @param $force boolean Whether to force the help to show, default false
651 protected function maybeHelp( $force = false ) {
652 if( !$force && !$this->hasOption( 'help' ) ) {
656 $screenWidth = 80; // TODO: Caculate this!
658 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
660 ksort( $this->mParams
);
661 $this->mQuiet
= false;
664 if ( $this->mDescription
) {
665 $this->output( "\n" . $this->mDescription
. "\n" );
667 $output = "\nUsage: php " . basename( $this->mSelf
);
669 // ... append parameters ...
670 if ( $this->mParams
) {
671 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
674 // ... and append arguments.
675 if ( $this->mArgList
) {
677 foreach ( $this->mArgList
as $k => $arg ) {
678 $output .= $arg['name'] . ">";
679 if ( $k < count( $this->mArgList
) - 1 )
683 $this->output( "$output\n\n" );
685 // Parameters description
686 foreach ( $this->mParams
as $par => $info ) {
688 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
689 "\n$tab$tab" ) . "\n"
693 // Arguments description
694 foreach ( $this->mArgList
as $info ) {
696 wordwrap( "$tab<" . $info['name'] . ">: " .
697 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
705 * Handle some last-minute setup here.
707 public function finalSetup() {
708 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
709 global $wgProfiling, $wgDBadminuser, $wgDBadminpassword;
710 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
712 # Turn off output buffering again, it might have been turned on in the settings files
713 if ( ob_get_level() ) {
717 $wgCommandLineMode = true;
720 if( $this->hasOption( 'server') ) {
721 $wgServer = $this->getOption( 'server', $wgServer );
724 # If these were passed, use them
725 if ( $this->mDbUser
) {
726 $wgDBadminuser = $this->mDbUser
;
728 if ( $this->mDbPass
) {
729 $wgDBadminpassword = $this->mDbPass
;
732 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
733 $wgDBuser = $wgDBadminuser;
734 $wgDBpassword = $wgDBadminpassword;
736 if ( $wgDBservers ) {
737 foreach ( $wgDBservers as $i => $server ) {
738 $wgDBservers[$i]['user'] = $wgDBuser;
739 $wgDBservers[$i]['password'] = $wgDBpassword;
742 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
743 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
744 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
746 LBFactory
::destroyInstance();
749 $this->afterFinalSetup();
751 $wgShowSQLErrors = true;
752 @set_time_limit
( 0 );
753 $this->adjustMemoryLimit();
755 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
759 * Execute a callback function at the end of initialisation
761 protected function afterFinalSetup() {
762 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
763 call_user_func( MW_CMDLINE_CALLBACK
);
768 * Potentially debug globals. Originally a feature only
771 public function globals() {
772 if ( $this->hasOption( 'globals' ) ) {
778 * Do setup specific to WMF
780 public function loadWikimediaSettings() {
781 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
783 if ( empty( $wgNoDBParam ) ) {
784 # Check if we were passed a db name
785 if ( isset( $this->mOptions
['wiki'] ) ) {
786 $db = $this->mOptions
['wiki'];
788 $db = array_shift( $this->mArgs
);
790 list( $site, $lang ) = $wgConf->siteFromDB( $db );
792 # If not, work out the language and site the old way
793 if ( is_null( $site ) ||
is_null( $lang ) ) {
799 if ( isset( $this->mArgs
[0] ) ) {
800 $site = array_shift( $this->mArgs
);
810 # This is for the IRC scripts, which now run as the apache user
811 # The apache user doesn't have access to the wikiadmin_pass command
812 if ( $_ENV['USER'] == 'apache' ) {
813 # if ( posix_geteuid() == 48 ) {
814 $wgUseNormalUser = true;
817 putenv( 'wikilang=' . $lang );
819 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
821 if ( $lang == 'test' && $site == 'wikipedia' ) {
822 define( 'TESTWIKI', 1 );
827 * Generic setup for most installs. Returns the location of LocalSettings
830 public function loadSettings() {
831 global $wgWikiFarm, $wgCommandLineMode, $IP;
834 if ( isset( $this->mOptions
['conf'] ) ) {
835 $settingsFile = $this->mOptions
['conf'];
837 $settingsFile = "$IP/LocalSettings.php";
839 if ( isset( $this->mOptions
['wiki'] ) ) {
840 $bits = explode( '-', $this->mOptions
['wiki'] );
841 if ( count( $bits ) == 1 ) {
844 define( 'MW_DB', $bits[0] );
845 define( 'MW_PREFIX', $bits[1] );
848 if ( !is_readable( $settingsFile ) ) {
849 $this->error( "A copy of your installation's LocalSettings.php\n" .
850 "must exist and be readable in the source directory.\n" .
851 "Use --conf to specify it." , true );
853 $wgCommandLineMode = true;
854 return $settingsFile;
858 * Support function for cleaning up redundant text records
859 * @param $delete Boolean: whether or not to actually delete the records
860 * @author Rob Church <robchur@gmail.com>
862 public function purgeRedundantText( $delete = true ) {
863 # Data should come off the master, wrapped in a transaction
864 $dbw = wfGetDB( DB_MASTER
);
867 $tbl_arc = $dbw->tableName( 'archive' );
868 $tbl_rev = $dbw->tableName( 'revision' );
869 $tbl_txt = $dbw->tableName( 'text' );
871 # Get "active" text records from the revisions table
872 $this->output( 'Searching for active text records in revisions table...' );
873 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
874 foreach ( $res as $row ) {
875 $cur[] = $row->rev_text_id
;
877 $this->output( "done.\n" );
879 # Get "active" text records from the archive table
880 $this->output( 'Searching for active text records in archive table...' );
881 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
882 foreach ( $res as $row ) {
883 $cur[] = $row->ar_text_id
;
885 $this->output( "done.\n" );
887 # Get the IDs of all text records not in these sets
888 $this->output( 'Searching for inactive text records...' );
889 $set = implode( ', ', $cur );
890 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
892 foreach ( $res as $row ) {
893 $old[] = $row->old_id
;
895 $this->output( "done.\n" );
897 # Inform the user of what we're going to do
898 $count = count( $old );
899 $this->output( "$count inactive items found.\n" );
901 # Delete as appropriate
902 if ( $delete && $count ) {
903 $this->output( 'Deleting...' );
904 $set = implode( ', ', $old );
905 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
906 $this->output( "done.\n" );
914 * Get the maintenance directory.
916 protected function getDir() {
917 return dirname( __FILE__
);
921 * Get the list of available maintenance scripts. Note
922 * that if you call this _before_ calling doMaintenance
923 * you won't have any extensions in it yet
926 public static function getMaintenanceScripts() {
927 global $wgMaintenanceScripts;
928 return $wgMaintenanceScripts + self
::getCoreScripts();
932 * Return all of the core maintenance scripts
935 protected static function getCoreScripts() {
936 if ( !self
::$mCoreScripts ) {
937 self
::disableSetup();
940 dirname( __FILE__
) . '/gearman',
941 dirname( __FILE__
) . '/language',
942 dirname( __FILE__
) . '/storage',
944 self
::$mCoreScripts = array();
945 foreach ( $paths as $p ) {
946 $handle = opendir( $p );
947 while ( ( $file = readdir( $handle ) ) !== false ) {
948 if ( $file == 'Maintenance.php' ) {
951 $file = $p . '/' . $file;
952 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
953 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
957 $vars = get_defined_vars();
958 if ( array_key_exists( 'maintClass', $vars ) ) {
959 self
::$mCoreScripts[$vars['maintClass']] = $file;
965 return self
::$mCoreScripts;
969 * Lock the search index
970 * @param &$db Database object
972 private function lockSearchindex( &$db ) {
973 $write = array( 'searchindex' );
974 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
975 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
980 * @param &$db Database object
982 private function unlockSearchindex( &$db ) {
983 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
987 * Unlock and lock again
988 * Since the lock is low-priority, queued reads will be able to complete
989 * @param &$db Database object
991 private function relockSearchindex( &$db ) {
992 $this->unlockSearchindex( $db );
993 $this->lockSearchindex( $db );
997 * Perform a search index update with locking
998 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
999 * @param $callback callback String: the function that will update the function.
1000 * @param $dbw Database object
1003 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1007 if ( $maxLockTime ) {
1008 $this->output( " --- Waiting for lock ---" );
1009 $this->lockSearchindex( $dbw );
1011 $this->output( "\n" );
1014 # Loop through the results and do a search update
1015 foreach ( $results as $row ) {
1016 # Allow reads to be processed
1017 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1018 $this->output( " --- Relocking ---" );
1019 $this->relockSearchindex( $dbw );
1021 $this->output( "\n" );
1023 call_user_func( $callback, $dbw, $row );
1026 # Unlock searchindex
1027 if ( $maxLockTime ) {
1028 $this->output( " --- Unlocking --" );
1029 $this->unlockSearchindex( $dbw );
1030 $this->output( "\n" );
1036 * Update the searchindex table for a given pageid
1037 * @param $dbw Database: a database write handle
1038 * @param $pageId Integer: the page ID to update.
1040 public function updateSearchIndexForPage( $dbw, $pageId ) {
1041 // Get current revision
1042 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1045 $titleObj = $rev->getTitle();
1046 $title = $titleObj->getPrefixedDBkey();
1047 $this->output( "$title..." );
1048 # Update searchindex
1049 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1051 $this->output( "\n" );
1057 * Prompt the console for input
1058 * @param $prompt String what to begin the line with, like '> '
1059 * @return String response
1061 public static function readconsole( $prompt = '> ' ) {
1062 static $isatty = null;
1063 if ( is_null( $isatty ) ) {
1064 if ( posix_isatty( 0 /*STDIN*/ ) ) {
1071 if ( $isatty && function_exists( 'readline' ) ) {
1072 return readline( $prompt );
1075 $st = self
::readlineEmulation( $prompt );
1077 if ( feof( STDIN
) ) {
1080 $st = fgets( STDIN
, 1024 );
1083 if ( $st === false ) return false;
1084 $resp = trim( $st );
1090 * Emulate readline()
1091 * @param $prompt String what to begin the line with, like '> '
1094 private static function readlineEmulation( $prompt ) {
1095 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1096 if ( !wfIsWindows() && $bash ) {
1098 $encPrompt = wfEscapeShellArg( $prompt );
1099 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1100 $encCommand = wfEscapeShellArg( $command );
1101 $line = wfShellExec( "$bash -c $encCommand", $retval );
1103 if ( $retval == 0 ) {
1105 } elseif ( $retval == 127 ) {
1106 // Couldn't execute bash even though we thought we saw it.
1107 // Shell probably spit out an error message, sorry :(
1108 // Fall through to fgets()...
1115 // Fallback... we'll have no editing controls, EWWW
1116 if ( feof( STDIN
) ) {
1120 return fgets( STDIN
, 1024 );
1124 class FakeMaintenance
extends Maintenance
{
1125 public function execute() {