3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Define this so scripts can easily find doMaintenance.php
24 define( 'DO_MAINTENANCE', dirname( __FILE__
) . '/doMaintenance.php' );
27 // Make sure we're on PHP5 or better
28 if ( version_compare( PHP_VERSION
, '5.1.0' ) < 0 ) {
29 die ( "Sorry! This version of MediaWiki requires PHP 5.1.x; you are running " .
30 PHP_VERSION
. ".\n\n" .
31 "If you are sure you already have PHP 5.1.x or higher installed, it may be\n" .
32 "installed in a different path from PHP " . PHP_VERSION
. ". Check with your system\n" .
36 // Wrapper for posix_isatty()
37 if ( !function_exists( 'posix_isatty' ) ) {
38 # We default as considering stdin a tty (for nice readline methods)
39 # but treating stout as not a tty to avoid color codes
40 function posix_isatty( $fd ) {
46 * Abstract maintenance class for quickly writing and churning out
47 * maintenance scripts with minimal effort. All that _must_ be defined
48 * is the execute() method. See docs/maintenance.txt for more info
49 * and a quick demo of how to use it.
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 *first* if implementing
106 * their own constructors
108 public function __construct() {
109 // Setup $IP, using MW_INSTALL_PATH if it exists
111 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
112 ?
getenv( 'MW_INSTALL_PATH' )
113 : realpath( dirname( __FILE__
) . '/..' );
115 $this->addDefaultParams();
116 register_shutdown_function( array( $this, 'outputChanneled' ), false );
120 * Do the actual work. All child classes will need to implement this
122 abstract public function execute();
125 * Add a parameter to the script. Will be displayed on --help
126 * with the associated description
128 * @param $name String: the name of the param (help, version, etc)
129 * @param $description String: the description of the param to show on --help
130 * @param $required Boolean: is the param required?
131 * @param $withArg Boolean: is an argument required with this option?
133 protected function addOption( $name, $description, $required = false, $withArg = false ) {
134 $this->mParams
[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg );
138 * Checks to see if a particular param exists.
139 * @param $name String: the name of the param
142 protected function hasOption( $name ) {
143 return isset( $this->mOptions
[$name] );
147 * Get an option, or return the default
148 * @param $name String: the name of the param
149 * @param $default Mixed: anything you want, default null
152 protected function getOption( $name, $default = null ) {
153 if ( $this->hasOption( $name ) ) {
154 return $this->mOptions
[$name];
156 // Set it so we don't have to provide the default again
157 $this->mOptions
[$name] = $default;
158 return $this->mOptions
[$name];
163 * Add some args that are needed
164 * @param $arg String: name of the arg, like 'start'
165 * @param $description String: short description of the arg
166 * @param $required Boolean: is this required?
168 protected function addArg( $arg, $description, $required = true ) {
169 $this->mArgList
[] = array(
171 'desc' => $description,
172 'require' => $required
177 * Remove an option. Useful for removing options that won't be used in your script.
178 * @param $name String: the option to remove.
180 protected function deleteOption( $name ) {
181 unset( $this->mParams
[$name] );
185 * Set the description text.
186 * @param $text String: the text of the description
188 protected function addDescription( $text ) {
189 $this->mDescription
= $text;
193 * Does a given argument exist?
194 * @param $argId Integer: the integer value (from zero) for the arg
197 protected function hasArg( $argId = 0 ) {
198 return isset( $this->mArgs
[$argId] );
203 * @param $argId Integer: the integer value (from zero) for the arg
204 * @param $default Mixed: the default if it doesn't exist
207 protected function getArg( $argId = 0, $default = null ) {
208 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
212 * Set the batch size.
213 * @param $s Integer: the number of operations to do in a batch
215 protected function setBatchSize( $s = 0 ) {
216 $this->mBatchSize
= $s;
220 * Get the script's name
223 public function getName() {
228 * Return input from stdin.
229 * @param $len Integer: the number of bytes to read. If null,
230 * just return the handle. Maintenance::STDIN_ALL returns
234 protected function getStdin( $len = null ) {
235 if ( $len == Maintenance
::STDIN_ALL
) {
236 return file_get_contents( 'php://stdin' );
238 $f = fopen( 'php://stdin', 'rt' );
242 $input = fgets( $f, $len );
244 return rtrim( $input );
247 public function isQuiet() {
248 return $this->mQuiet
;
252 * Throw some output to the user. Scripts can call this with no fears,
253 * as we handle all --quiet stuff here
254 * @param $out String: the text to show to the user
255 * @param $channel Mixed: unique identifier for the channel. See
256 * function outputChanneled.
258 protected function output( $out, $channel = null ) {
259 if ( $this->mQuiet
) {
262 if ( $channel === null ) {
263 $this->cleanupChanneled();
265 $f = fopen( 'php://stdout', 'w' );
270 $out = preg_replace( '/\n\z/', '', $out );
271 $this->outputChanneled( $out, $channel );
276 * Throw an error to the user. Doesn't respect --quiet, so don't use
277 * this for non-error output
278 * @param $err String: the error to display
279 * @param $die Boolean: If true, go ahead and die out.
281 protected function error( $err, $die = false ) {
282 $this->outputChanneled( false );
283 if ( php_sapi_name() == 'cli' ) {
284 fwrite( STDERR
, $err . "\n" );
286 $f = fopen( 'php://stderr', 'w' );
287 fwrite( $f, $err . "\n" );
295 private $atLineStart = true;
296 private $lastChannel = null;
299 * Clean up channeled output. Output a newline if necessary.
301 public function cleanupChanneled() {
302 if ( !$this->atLineStart
) {
303 $handle = fopen( 'php://stdout', 'w' );
304 fwrite( $handle, "\n" );
306 $this->atLineStart
= true;
311 * Message outputter with channeled message support. Messages on the
312 * same channel are concatenated, but any intervening messages in another
313 * channel start a new line.
314 * @param $msg String: the message without trailing newline
315 * @param $channel Channel identifier or null for no
316 * channel. Channel comparison uses ===.
318 public function outputChanneled( $msg, $channel = null ) {
319 if ( $msg === false ) {
320 $this->cleanupChanneled();
324 $handle = fopen( 'php://stdout', 'w' );
326 // End the current line if necessary
327 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
328 fwrite( $handle, "\n" );
331 fwrite( $handle, $msg );
333 $this->atLineStart
= false;
334 if ( $channel === null ) {
335 // For unchanneled messages, output trailing newline immediately
336 fwrite( $handle, "\n" );
337 $this->atLineStart
= true;
339 $this->lastChannel
= $channel;
346 * Does the script need different DB access? By default, we give Maintenance
347 * scripts normal rights to the DB. Sometimes, a script needs admin rights
348 * access for a reason and sometimes they want no access. Subclasses should
349 * override and return one of the following values, as needed:
350 * Maintenance::DB_NONE - For no DB access at all
351 * Maintenance::DB_STD - For normal DB access, default
352 * Maintenance::DB_ADMIN - For admin DB access
355 public function getDbType() {
356 return Maintenance
::DB_STD
;
360 * Add the default parameters to the scripts
362 protected function addDefaultParams() {
363 $this->addOption( 'help', 'Display this help message' );
364 $this->addOption( 'quiet', 'Whether to supress non-error output' );
365 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
366 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
367 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
368 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
369 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
370 "http://en.wikipedia.org. This is sometimes necessary because " .
371 "server name detection may fail in command line scripts.", false, true );
372 // If we support a DB, show the options
373 if ( $this->getDbType() > 0 ) {
374 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
375 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
377 // If we support $mBatchSize, show the option
378 if ( $this->mBatchSize
) {
379 $this->addOption( 'batch-size', 'Run this many operations ' .
380 'per batch, default: ' . $this->mBatchSize
, false, true );
385 * Run a child maintenance script. Pass all of the current arguments
387 * @param $maintClass String: a name of a child maintenance class
388 * @param $classFile String: full path of where the child is
389 * @return Maintenance child
391 public function runChild( $maintClass, $classFile = null ) {
392 // If we haven't already specified, kill setup procedures
393 // for child scripts, we've already got a sane environment
394 self
::disableSetup();
396 // Make sure the class is loaded first
397 if ( !class_exists( $maintClass ) ) {
399 require_once( $classFile );
401 if ( !class_exists( $maintClass ) ) {
402 $this->error( "Cannot spawn child: $maintClass" );
406 $child = new $maintClass();
407 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
412 * Disable Setup.php mostly
414 protected static function disableSetup() {
415 if ( !defined( 'MW_NO_SETUP' ) ) {
416 define( 'MW_NO_SETUP', true );
421 * Do some sanity checking and basic setup
423 public function setup() {
424 global $wgCommandLineMode, $wgRequestTime;
426 # Abort if called from a web server
427 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
428 $this->error( 'This script must be run from the command line', true );
431 # Make sure we can handle script parameters
432 if ( !ini_get( 'register_argc_argv' ) ) {
433 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
436 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
437 // Send PHP warnings and errors to stderr instead of stdout.
438 // This aids in diagnosing problems, while keeping messages
439 // out of redirected output.
440 if ( ini_get( 'display_errors' ) ) {
441 ini_set( 'display_errors', 'stderr' );
444 // Don't touch the setting on earlier versions of PHP,
445 // as setting it would disable output if you'd wanted it.
447 // Note that exceptions are also sent to stderr when
448 // command-line mode is on, regardless of PHP version.
451 $this->loadParamsAndArgs();
454 # Set the memory limit
455 # Note we need to set it again later in cache LocalSettings changed it
456 $this->adjustMemoryLimit();
458 # Set max execution time to 0 (no limit). PHP.net says that
459 # "When running PHP from the command line the default setting is 0."
460 # But sometimes this doesn't seem to be the case.
461 ini_set( 'max_execution_time', 0 );
463 $wgRequestTime = microtime( true );
465 # Define us as being in MediaWiki
466 define( 'MEDIAWIKI', true );
468 $wgCommandLineMode = true;
469 # Turn off output buffering if it's on
472 $this->validateParamsAndArgs();
476 * Normally we disable the memory_limit when running admin scripts.
477 * Some scripts may wish to actually set a limit, however, to avoid
478 * blowing up unexpectedly. We also support a --memory-limit option,
479 * to allow sysadmins to explicitly set one if they'd prefer to override
480 * defaults (or for people using Suhosin which yells at you for trying
481 * to disable the limits)
483 public function memoryLimit() {
484 $limit = $this->getOption( 'memory-limit', 'max' );
485 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
490 * Adjusts PHP's memory limit to better suit our needs, if needed.
492 protected function adjustMemoryLimit() {
493 $limit = $this->memoryLimit();
494 if ( $limit == 'max' ) {
495 $limit = -1; // no memory limit
497 if ( $limit != 'default' ) {
498 ini_set( 'memory_limit', $limit );
503 * Clear all params and arguments.
505 public function clearParamsAndArgs() {
506 $this->mOptions
= array();
507 $this->mArgs
= array();
508 $this->mInputLoaded
= false;
512 * Process command line arguments
513 * $mOptions becomes an array with keys set to the option names
514 * $mArgs becomes a zero-based array containing the non-option arguments
516 * @param $self String The name of the script, if any
517 * @param $opts Array An array of options, in form of key=>value
518 * @param $args Array An array of command line arguments
520 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
521 # If we were given opts or args, set those and return early
523 $this->mSelf
= $self;
524 $this->mInputLoaded
= true;
527 $this->mOptions
= $opts;
528 $this->mInputLoaded
= true;
531 $this->mArgs
= $args;
532 $this->mInputLoaded
= true;
535 # If we've already loaded input (either by user values or from $argv)
536 # skip on loading it again. The array_shift() will corrupt values if
537 # it's run again and again
538 if ( $this->mInputLoaded
) {
539 $this->loadSpecialVars();
544 $this->mSelf
= array_shift( $argv );
550 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
551 if ( $arg == '--' ) {
552 # End of options, remainder should be considered arguments
553 $arg = next( $argv );
554 while ( $arg !== false ) {
556 $arg = next( $argv );
559 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
561 $option = substr( $arg, 2 );
562 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
563 $param = next( $argv );
564 if ( $param === false ) {
565 $this->error( "\nERROR: $option needs a value after it\n" );
566 $this->maybeHelp( true );
568 $options[$option] = $param;
570 $bits = explode( '=', $option, 2 );
571 if ( count( $bits ) > 1 ) {
577 $options[$option] = $param;
579 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
581 for ( $p = 1; $p < strlen( $arg ); $p++
) {
582 $option = $arg { $p } ;
583 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
584 $param = next( $argv );
585 if ( $param === false ) {
586 $this->error( "\nERROR: $option needs a value after it\n" );
587 $this->maybeHelp( true );
589 $options[$option] = $param;
591 $options[$option] = 1;
599 $this->mOptions
= $options;
600 $this->mArgs
= $args;
601 $this->loadSpecialVars();
602 $this->mInputLoaded
= true;
606 * Run some validation checks on the params, etc
608 protected function validateParamsAndArgs() {
610 # Check to make sure we've got all the required options
611 foreach ( $this->mParams
as $opt => $info ) {
612 if ( $info['require'] && !$this->hasOption( $opt ) ) {
613 $this->error( "Param $opt required!" );
618 foreach ( $this->mArgList
as $k => $info ) {
619 if ( $info['require'] && !$this->hasArg( $k ) ) {
620 $this->error( 'Argument <' . $info['name'] . '> required!' );
626 $this->maybeHelp( true );
631 * Handle the special variables that are global to all scripts
633 protected function loadSpecialVars() {
634 if ( $this->hasOption( 'dbuser' ) ) {
635 $this->mDbUser
= $this->getOption( 'dbuser' );
637 if ( $this->hasOption( 'dbpass' ) ) {
638 $this->mDbPass
= $this->getOption( 'dbpass' );
640 if ( $this->hasOption( 'quiet' ) ) {
641 $this->mQuiet
= true;
643 if ( $this->hasOption( 'batch-size' ) ) {
644 $this->mBatchSize
= $this->getOption( 'batch-size' );
649 * Maybe show the help.
650 * @param $force boolean Whether to force the help to show, default false
652 protected function maybeHelp( $force = false ) {
653 if( !$force && !$this->hasOption( 'help' ) ) {
657 $screenWidth = 80; // TODO: Caculate this!
659 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
661 ksort( $this->mParams
);
662 $this->mQuiet
= false;
665 if ( $this->mDescription
) {
666 $this->output( "\n" . $this->mDescription
. "\n" );
668 $output = "\nUsage: php " . basename( $this->mSelf
);
670 // ... append parameters ...
671 if ( $this->mParams
) {
672 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
675 // ... and append arguments.
676 if ( $this->mArgList
) {
678 foreach ( $this->mArgList
as $k => $arg ) {
679 if ( $arg['require'] ) {
680 $output .= '<' . $arg['name'] . '>';
682 $output .= '[' . $arg['name'] . ']';
684 if ( $k < count( $this->mArgList
) - 1 )
688 $this->output( "$output\n\n" );
690 // Parameters description
691 foreach ( $this->mParams
as $par => $info ) {
693 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
694 "\n$tab$tab" ) . "\n"
698 // Arguments description
699 foreach ( $this->mArgList
as $info ) {
700 $openChar = $info['require'] ?
'<' : '[';
701 $closeChar = $info['require'] ?
'>' : ']';
703 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
704 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
712 * Handle some last-minute setup here.
714 public function finalSetup() {
715 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
716 global $wgProfiling, $wgDBadminuser, $wgDBadminpassword;
717 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
719 # Turn off output buffering again, it might have been turned on in the settings files
720 if ( ob_get_level() ) {
724 $wgCommandLineMode = true;
727 if( $this->hasOption( 'server') ) {
728 $wgServer = $this->getOption( 'server', $wgServer );
731 # If these were passed, use them
732 if ( $this->mDbUser
) {
733 $wgDBadminuser = $this->mDbUser
;
735 if ( $this->mDbPass
) {
736 $wgDBadminpassword = $this->mDbPass
;
739 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
740 $wgDBuser = $wgDBadminuser;
741 $wgDBpassword = $wgDBadminpassword;
743 if ( $wgDBservers ) {
744 foreach ( $wgDBservers as $i => $server ) {
745 $wgDBservers[$i]['user'] = $wgDBuser;
746 $wgDBservers[$i]['password'] = $wgDBpassword;
749 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
750 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
751 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
753 LBFactory
::destroyInstance();
756 $this->afterFinalSetup();
758 $wgShowSQLErrors = true;
759 @set_time_limit
( 0 );
760 $this->adjustMemoryLimit();
762 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
766 * Execute a callback function at the end of initialisation
768 protected function afterFinalSetup() {
769 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
770 call_user_func( MW_CMDLINE_CALLBACK
);
775 * Potentially debug globals. Originally a feature only
778 public function globals() {
779 if ( $this->hasOption( 'globals' ) ) {
785 * Do setup specific to WMF
787 public function loadWikimediaSettings() {
788 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
790 if ( empty( $wgNoDBParam ) ) {
791 # Check if we were passed a db name
792 if ( isset( $this->mOptions
['wiki'] ) ) {
793 $db = $this->mOptions
['wiki'];
795 $db = array_shift( $this->mArgs
);
797 list( $site, $lang ) = $wgConf->siteFromDB( $db );
799 # If not, work out the language and site the old way
800 if ( is_null( $site ) ||
is_null( $lang ) ) {
806 if ( isset( $this->mArgs
[0] ) ) {
807 $site = array_shift( $this->mArgs
);
817 # This is for the IRC scripts, which now run as the apache user
818 # The apache user doesn't have access to the wikiadmin_pass command
819 if ( $_ENV['USER'] == 'apache' ) {
820 # if ( posix_geteuid() == 48 ) {
821 $wgUseNormalUser = true;
824 putenv( 'wikilang=' . $lang );
826 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
828 if ( $lang == 'test' && $site == 'wikipedia' ) {
829 define( 'TESTWIKI', 1 );
834 * Generic setup for most installs. Returns the location of LocalSettings
837 public function loadSettings() {
838 global $wgWikiFarm, $wgCommandLineMode, $IP;
841 if ( isset( $this->mOptions
['conf'] ) ) {
842 $settingsFile = $this->mOptions
['conf'];
843 } else if ( defined("MW_CONFIG_FILE") ) {
844 $settingsFile = MW_CONFIG_FILE
;
846 $settingsFile = "$IP/LocalSettings.php";
848 if ( isset( $this->mOptions
['wiki'] ) ) {
849 $bits = explode( '-', $this->mOptions
['wiki'] );
850 if ( count( $bits ) == 1 ) {
853 define( 'MW_DB', $bits[0] );
854 define( 'MW_PREFIX', $bits[1] );
857 if ( !is_readable( $settingsFile ) ) {
858 $this->error( "A copy of your installation's LocalSettings.php\n" .
859 "must exist and be readable in the source directory.\n" .
860 "Use --conf to specify it." , true );
862 $wgCommandLineMode = true;
863 return $settingsFile;
867 * Support function for cleaning up redundant text records
868 * @param $delete Boolean: whether or not to actually delete the records
869 * @author Rob Church <robchur@gmail.com>
871 public function purgeRedundantText( $delete = true ) {
872 # Data should come off the master, wrapped in a transaction
873 $dbw = wfGetDB( DB_MASTER
);
876 $tbl_arc = $dbw->tableName( 'archive' );
877 $tbl_rev = $dbw->tableName( 'revision' );
878 $tbl_txt = $dbw->tableName( 'text' );
880 # Get "active" text records from the revisions table
881 $this->output( 'Searching for active text records in revisions table...' );
882 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
883 foreach ( $res as $row ) {
884 $cur[] = $row->rev_text_id
;
886 $this->output( "done.\n" );
888 # Get "active" text records from the archive table
889 $this->output( 'Searching for active text records in archive table...' );
890 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
891 foreach ( $res as $row ) {
892 $cur[] = $row->ar_text_id
;
894 $this->output( "done.\n" );
896 # Get the IDs of all text records not in these sets
897 $this->output( 'Searching for inactive text records...' );
898 $set = implode( ', ', $cur );
899 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
901 foreach ( $res as $row ) {
902 $old[] = $row->old_id
;
904 $this->output( "done.\n" );
906 # Inform the user of what we're going to do
907 $count = count( $old );
908 $this->output( "$count inactive items found.\n" );
910 # Delete as appropriate
911 if ( $delete && $count ) {
912 $this->output( 'Deleting...' );
913 $set = implode( ', ', $old );
914 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
915 $this->output( "done.\n" );
923 * Get the maintenance directory.
925 protected function getDir() {
926 return dirname( __FILE__
);
930 * Get the list of available maintenance scripts. Note
931 * that if you call this _before_ calling doMaintenance
932 * you won't have any extensions in it yet
935 public static function getMaintenanceScripts() {
936 global $wgMaintenanceScripts;
937 return $wgMaintenanceScripts + self
::getCoreScripts();
941 * Return all of the core maintenance scripts
944 protected static function getCoreScripts() {
945 if ( !self
::$mCoreScripts ) {
946 self
::disableSetup();
949 dirname( __FILE__
) . '/gearman',
950 dirname( __FILE__
) . '/language',
951 dirname( __FILE__
) . '/storage',
953 self
::$mCoreScripts = array();
954 foreach ( $paths as $p ) {
955 $handle = opendir( $p );
956 while ( ( $file = readdir( $handle ) ) !== false ) {
957 if ( $file == 'Maintenance.php' ) {
960 $file = $p . '/' . $file;
961 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
962 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
966 $vars = get_defined_vars();
967 if ( array_key_exists( 'maintClass', $vars ) ) {
968 self
::$mCoreScripts[$vars['maintClass']] = $file;
974 return self
::$mCoreScripts;
978 * Lock the search index
979 * @param &$db Database object
981 private function lockSearchindex( &$db ) {
982 $write = array( 'searchindex' );
983 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
984 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
989 * @param &$db Database object
991 private function unlockSearchindex( &$db ) {
992 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
996 * Unlock and lock again
997 * Since the lock is low-priority, queued reads will be able to complete
998 * @param &$db Database object
1000 private function relockSearchindex( &$db ) {
1001 $this->unlockSearchindex( $db );
1002 $this->lockSearchindex( $db );
1006 * Perform a search index update with locking
1007 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1008 * @param $callback callback String: the function that will update the function.
1009 * @param $dbw Database object
1012 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1016 if ( $maxLockTime ) {
1017 $this->output( " --- Waiting for lock ---" );
1018 $this->lockSearchindex( $dbw );
1020 $this->output( "\n" );
1023 # Loop through the results and do a search update
1024 foreach ( $results as $row ) {
1025 # Allow reads to be processed
1026 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1027 $this->output( " --- Relocking ---" );
1028 $this->relockSearchindex( $dbw );
1030 $this->output( "\n" );
1032 call_user_func( $callback, $dbw, $row );
1035 # Unlock searchindex
1036 if ( $maxLockTime ) {
1037 $this->output( " --- Unlocking --" );
1038 $this->unlockSearchindex( $dbw );
1039 $this->output( "\n" );
1045 * Update the searchindex table for a given pageid
1046 * @param $dbw Database: a database write handle
1047 * @param $pageId Integer: the page ID to update.
1049 public function updateSearchIndexForPage( $dbw, $pageId ) {
1050 // Get current revision
1051 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1054 $titleObj = $rev->getTitle();
1055 $title = $titleObj->getPrefixedDBkey();
1056 $this->output( "$title..." );
1057 # Update searchindex
1058 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1060 $this->output( "\n" );
1066 * Prompt the console for input
1067 * @param $prompt String what to begin the line with, like '> '
1068 * @return String response
1070 public static function readconsole( $prompt = '> ' ) {
1071 static $isatty = null;
1072 if ( is_null( $isatty ) ) {
1073 $isatty = posix_isatty( 0 /*STDIN*/ );
1076 if ( $isatty && function_exists( 'readline' ) ) {
1077 return readline( $prompt );
1080 $st = self
::readlineEmulation( $prompt );
1082 if ( feof( STDIN
) ) {
1085 $st = fgets( STDIN
, 1024 );
1088 if ( $st === false ) return false;
1089 $resp = trim( $st );
1095 * Emulate readline()
1096 * @param $prompt String what to begin the line with, like '> '
1099 private static function readlineEmulation( $prompt ) {
1100 $bash = Installer
::locateExecutableInDefaultPaths( array( 'bash' ) );
1101 if ( !wfIsWindows() && $bash ) {
1103 $encPrompt = wfEscapeShellArg( $prompt );
1104 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1105 $encCommand = wfEscapeShellArg( $command );
1106 $line = wfShellExec( "$bash -c $encCommand", $retval );
1108 if ( $retval == 0 ) {
1110 } elseif ( $retval == 127 ) {
1111 // Couldn't execute bash even though we thought we saw it.
1112 // Shell probably spit out an error message, sorry :(
1113 // Fall through to fgets()...
1120 // Fallback... we'll have no editing controls, EWWW
1121 if ( feof( STDIN
) ) {
1125 return fgets( STDIN
, 1024 );
1129 class FakeMaintenance
extends Maintenance
{
1130 protected $mSelf = "FakeMaintenanceScript";
1131 public function execute() {