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. " .
364 "http://en.wikipedia.org. This is sometimes necessary because " .
365 "server 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 if ( $arg['require'] ) {
679 $output .= '<' . $arg['name'] . '>';
681 $output .= '[' . $arg['name'] . ']';
683 if ( $k < count( $this->mArgList
) - 1 )
687 $this->output( "$output\n\n" );
689 // Parameters description
690 foreach ( $this->mParams
as $par => $info ) {
692 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
693 "\n$tab$tab" ) . "\n"
697 // Arguments description
698 foreach ( $this->mArgList
as $info ) {
699 $openChar = $info['require'] ?
'<' : '[';
700 $closeChar = $info['require'] ?
'>' : ']';
702 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
703 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
711 * Handle some last-minute setup here.
713 public function finalSetup() {
714 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
715 global $wgProfiling, $wgDBadminuser, $wgDBadminpassword;
716 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
718 # Turn off output buffering again, it might have been turned on in the settings files
719 if ( ob_get_level() ) {
723 $wgCommandLineMode = true;
726 if( $this->hasOption( 'server') ) {
727 $wgServer = $this->getOption( 'server', $wgServer );
730 # If these were passed, use them
731 if ( $this->mDbUser
) {
732 $wgDBadminuser = $this->mDbUser
;
734 if ( $this->mDbPass
) {
735 $wgDBadminpassword = $this->mDbPass
;
738 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
739 $wgDBuser = $wgDBadminuser;
740 $wgDBpassword = $wgDBadminpassword;
742 if ( $wgDBservers ) {
743 foreach ( $wgDBservers as $i => $server ) {
744 $wgDBservers[$i]['user'] = $wgDBuser;
745 $wgDBservers[$i]['password'] = $wgDBpassword;
748 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
749 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
750 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
752 LBFactory
::destroyInstance();
755 $this->afterFinalSetup();
757 $wgShowSQLErrors = true;
758 @set_time_limit
( 0 );
759 $this->adjustMemoryLimit();
761 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
765 * Execute a callback function at the end of initialisation
767 protected function afterFinalSetup() {
768 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
769 call_user_func( MW_CMDLINE_CALLBACK
);
774 * Potentially debug globals. Originally a feature only
777 public function globals() {
778 if ( $this->hasOption( 'globals' ) ) {
784 * Do setup specific to WMF
786 public function loadWikimediaSettings() {
787 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
789 if ( empty( $wgNoDBParam ) ) {
790 # Check if we were passed a db name
791 if ( isset( $this->mOptions
['wiki'] ) ) {
792 $db = $this->mOptions
['wiki'];
794 $db = array_shift( $this->mArgs
);
796 list( $site, $lang ) = $wgConf->siteFromDB( $db );
798 # If not, work out the language and site the old way
799 if ( is_null( $site ) ||
is_null( $lang ) ) {
805 if ( isset( $this->mArgs
[0] ) ) {
806 $site = array_shift( $this->mArgs
);
816 # This is for the IRC scripts, which now run as the apache user
817 # The apache user doesn't have access to the wikiadmin_pass command
818 if ( $_ENV['USER'] == 'apache' ) {
819 # if ( posix_geteuid() == 48 ) {
820 $wgUseNormalUser = true;
823 putenv( 'wikilang=' . $lang );
825 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
827 if ( $lang == 'test' && $site == 'wikipedia' ) {
828 define( 'TESTWIKI', 1 );
833 * Generic setup for most installs. Returns the location of LocalSettings
836 public function loadSettings() {
837 global $wgWikiFarm, $wgCommandLineMode, $IP;
840 if ( isset( $this->mOptions
['conf'] ) ) {
841 $settingsFile = $this->mOptions
['conf'];
843 $settingsFile = "$IP/LocalSettings.php";
845 if ( isset( $this->mOptions
['wiki'] ) ) {
846 $bits = explode( '-', $this->mOptions
['wiki'] );
847 if ( count( $bits ) == 1 ) {
850 define( 'MW_DB', $bits[0] );
851 define( 'MW_PREFIX', $bits[1] );
854 if ( !is_readable( $settingsFile ) ) {
855 $this->error( "A copy of your installation's LocalSettings.php\n" .
856 "must exist and be readable in the source directory.\n" .
857 "Use --conf to specify it." , true );
859 $wgCommandLineMode = true;
860 return $settingsFile;
864 * Support function for cleaning up redundant text records
865 * @param $delete Boolean: whether or not to actually delete the records
866 * @author Rob Church <robchur@gmail.com>
868 public function purgeRedundantText( $delete = true ) {
869 # Data should come off the master, wrapped in a transaction
870 $dbw = wfGetDB( DB_MASTER
);
873 $tbl_arc = $dbw->tableName( 'archive' );
874 $tbl_rev = $dbw->tableName( 'revision' );
875 $tbl_txt = $dbw->tableName( 'text' );
877 # Get "active" text records from the revisions table
878 $this->output( 'Searching for active text records in revisions table...' );
879 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
880 foreach ( $res as $row ) {
881 $cur[] = $row->rev_text_id
;
883 $this->output( "done.\n" );
885 # Get "active" text records from the archive table
886 $this->output( 'Searching for active text records in archive table...' );
887 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
888 foreach ( $res as $row ) {
889 $cur[] = $row->ar_text_id
;
891 $this->output( "done.\n" );
893 # Get the IDs of all text records not in these sets
894 $this->output( 'Searching for inactive text records...' );
895 $set = implode( ', ', $cur );
896 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
898 foreach ( $res as $row ) {
899 $old[] = $row->old_id
;
901 $this->output( "done.\n" );
903 # Inform the user of what we're going to do
904 $count = count( $old );
905 $this->output( "$count inactive items found.\n" );
907 # Delete as appropriate
908 if ( $delete && $count ) {
909 $this->output( 'Deleting...' );
910 $set = implode( ', ', $old );
911 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
912 $this->output( "done.\n" );
920 * Get the maintenance directory.
922 protected function getDir() {
923 return dirname( __FILE__
);
927 * Get the list of available maintenance scripts. Note
928 * that if you call this _before_ calling doMaintenance
929 * you won't have any extensions in it yet
932 public static function getMaintenanceScripts() {
933 global $wgMaintenanceScripts;
934 return $wgMaintenanceScripts + self
::getCoreScripts();
938 * Return all of the core maintenance scripts
941 protected static function getCoreScripts() {
942 if ( !self
::$mCoreScripts ) {
943 self
::disableSetup();
946 dirname( __FILE__
) . '/gearman',
947 dirname( __FILE__
) . '/language',
948 dirname( __FILE__
) . '/storage',
950 self
::$mCoreScripts = array();
951 foreach ( $paths as $p ) {
952 $handle = opendir( $p );
953 while ( ( $file = readdir( $handle ) ) !== false ) {
954 if ( $file == 'Maintenance.php' ) {
957 $file = $p . '/' . $file;
958 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
959 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
963 $vars = get_defined_vars();
964 if ( array_key_exists( 'maintClass', $vars ) ) {
965 self
::$mCoreScripts[$vars['maintClass']] = $file;
971 return self
::$mCoreScripts;
975 * Lock the search index
976 * @param &$db Database object
978 private function lockSearchindex( &$db ) {
979 $write = array( 'searchindex' );
980 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
981 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
986 * @param &$db Database object
988 private function unlockSearchindex( &$db ) {
989 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
993 * Unlock and lock again
994 * Since the lock is low-priority, queued reads will be able to complete
995 * @param &$db Database object
997 private function relockSearchindex( &$db ) {
998 $this->unlockSearchindex( $db );
999 $this->lockSearchindex( $db );
1003 * Perform a search index update with locking
1004 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1005 * @param $callback callback String: the function that will update the function.
1006 * @param $dbw Database object
1009 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1013 if ( $maxLockTime ) {
1014 $this->output( " --- Waiting for lock ---" );
1015 $this->lockSearchindex( $dbw );
1017 $this->output( "\n" );
1020 # Loop through the results and do a search update
1021 foreach ( $results as $row ) {
1022 # Allow reads to be processed
1023 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1024 $this->output( " --- Relocking ---" );
1025 $this->relockSearchindex( $dbw );
1027 $this->output( "\n" );
1029 call_user_func( $callback, $dbw, $row );
1032 # Unlock searchindex
1033 if ( $maxLockTime ) {
1034 $this->output( " --- Unlocking --" );
1035 $this->unlockSearchindex( $dbw );
1036 $this->output( "\n" );
1042 * Update the searchindex table for a given pageid
1043 * @param $dbw Database: a database write handle
1044 * @param $pageId Integer: the page ID to update.
1046 public function updateSearchIndexForPage( $dbw, $pageId ) {
1047 // Get current revision
1048 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1051 $titleObj = $rev->getTitle();
1052 $title = $titleObj->getPrefixedDBkey();
1053 $this->output( "$title..." );
1054 # Update searchindex
1055 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1057 $this->output( "\n" );
1063 * Prompt the console for input
1064 * @param $prompt String what to begin the line with, like '> '
1065 * @return String response
1067 public static function readconsole( $prompt = '> ' ) {
1068 static $isatty = null;
1069 if ( is_null( $isatty ) ) {
1070 if ( posix_isatty( 0 /*STDIN*/ ) ) {
1077 if ( $isatty && function_exists( 'readline' ) ) {
1078 return readline( $prompt );
1081 $st = self
::readlineEmulation( $prompt );
1083 if ( feof( STDIN
) ) {
1086 $st = fgets( STDIN
, 1024 );
1089 if ( $st === false ) return false;
1090 $resp = trim( $st );
1096 * Emulate readline()
1097 * @param $prompt String what to begin the line with, like '> '
1100 private static function readlineEmulation( $prompt ) {
1101 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1102 if ( !wfIsWindows() && $bash ) {
1104 $encPrompt = wfEscapeShellArg( $prompt );
1105 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1106 $encCommand = wfEscapeShellArg( $command );
1107 $line = wfShellExec( "$bash -c $encCommand", $retval );
1109 if ( $retval == 0 ) {
1111 } elseif ( $retval == 127 ) {
1112 // Couldn't execute bash even though we thought we saw it.
1113 // Shell probably spit out an error message, sorry :(
1114 // Fall through to fgets()...
1121 // Fallback... we'll have no editing controls, EWWW
1122 if ( feof( STDIN
) ) {
1126 return fgets( STDIN
, 1024 );
1130 class FakeMaintenance
extends Maintenance
{
1131 public function execute() {