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" .
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 * Remove an option. Useful for removing options that won't be used in your script.
163 * @param $name String: the option to remove.
165 protected function deleteOption( $name ) {
166 unset( $this->mParams
[$name] );
170 * Set the description text.
171 * @param $text String: the text of the description
173 protected function addDescription( $text ) {
174 $this->mDescription
= $text;
178 * Does a given argument exist?
179 * @param $argId Integer: the integer value (from zero) for the arg
182 protected function hasArg( $argId = 0 ) {
183 return isset( $this->mArgs
[$argId] );
188 * @param $argId Integer: the integer value (from zero) for the arg
189 * @param $default Mixed: the default if it doesn't exist
192 protected function getArg( $argId = 0, $default = null ) {
193 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
197 * Set the batch size.
198 * @param $s Integer: the number of operations to do in a batch
200 protected function setBatchSize( $s = 0 ) {
201 $this->mBatchSize
= $s;
205 * Get the script's name
208 public function getName() {
213 * Return input from stdin.
214 * @param $len Integer: the number of bytes to read. If null,
215 * just return the handle. Maintenance::STDIN_ALL returns
219 protected function getStdin( $len = null ) {
220 if ( $len == Maintenance
::STDIN_ALL
) {
221 return file_get_contents( 'php://stdin' );
223 $f = fopen( 'php://stdin', 'rt' );
227 $input = fgets( $f, $len );
229 return rtrim( $input );
232 public function isQuiet() {
233 return $this->mQuiet
;
237 * Throw some output to the user. Scripts can call this with no fears,
238 * as we handle all --quiet stuff here
239 * @param $out String: the text to show to the user
240 * @param $channel Mixed: unique identifier for the channel. See
241 * function outputChanneled.
243 protected function output( $out, $channel = null ) {
244 if ( $this->mQuiet
) {
247 if ( $channel === null ) {
248 $this->cleanupChanneled();
250 $f = fopen( 'php://stdout', 'w' );
255 $out = preg_replace( '/\n\z/', '', $out );
256 $this->outputChanneled( $out, $channel );
261 * Throw an error to the user. Doesn't respect --quiet, so don't use
262 * this for non-error output
263 * @param $err String: the error to display
264 * @param $die Boolean: If true, go ahead and die out.
266 protected function error( $err, $die = false ) {
267 $this->outputChanneled( false );
268 if ( php_sapi_name() == 'cli' ) {
269 fwrite( STDERR
, $err . "\n" );
271 $f = fopen( 'php://stderr', 'w' );
272 fwrite( $f, $err . "\n" );
280 private $atLineStart = true;
281 private $lastChannel = null;
284 * Clean up channeled output. Output a newline if necessary.
286 public function cleanupChanneled() {
287 if ( !$this->atLineStart
) {
288 $handle = fopen( 'php://stdout', 'w' );
289 fwrite( $handle, "\n" );
291 $this->atLineStart
= true;
296 * Message outputter with channeled message support. Messages on the
297 * same channel are concatenated, but any intervening messages in another
298 * channel start a new line.
299 * @param $msg String: the message without trailing newline
300 * @param $channel Channel identifier or null for no
301 * channel. Channel comparison uses ===.
303 public function outputChanneled( $msg, $channel = null ) {
304 if ( $msg === false ) {
305 $this->cleanupChanneled();
309 $handle = fopen( 'php://stdout', 'w' );
311 // End the current line if necessary
312 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
313 fwrite( $handle, "\n" );
316 fwrite( $handle, $msg );
318 $this->atLineStart
= false;
319 if ( $channel === null ) {
320 // For unchanneled messages, output trailing newline immediately
321 fwrite( $handle, "\n" );
322 $this->atLineStart
= true;
324 $this->lastChannel
= $channel;
331 * Does the script need different DB access? By default, we give Maintenance
332 * scripts normal rights to the DB. Sometimes, a script needs admin rights
333 * access for a reason and sometimes they want no access. Subclasses should
334 * override and return one of the following values, as needed:
335 * Maintenance::DB_NONE - For no DB access at all
336 * Maintenance::DB_STD - For normal DB access, default
337 * Maintenance::DB_ADMIN - For admin DB access
340 public function getDbType() {
341 return Maintenance
::DB_STD
;
345 * Add the default parameters to the scripts
347 protected function addDefaultParams() {
348 $this->addOption( 'help', 'Display this help message' );
349 $this->addOption( 'quiet', 'Whether to supress non-error output' );
350 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
351 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
352 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
353 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
354 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g.\n" .
355 "\t\thttp://en.wikipedia.org. This is sometimes necessary because\n" .
356 "\t\tserver name detection may fail in command line scripts.", false, true );
357 // If we support a DB, show the options
358 if ( $this->getDbType() > 0 ) {
359 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
360 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
362 // If we support $mBatchSize, show the option
363 if ( $this->mBatchSize
) {
364 $this->addOption( 'batch-size', 'Run this many operations ' .
365 'per batch, default: ' . $this->mBatchSize
, false, true );
370 * Run a child maintenance script. Pass all of the current arguments
372 * @param $maintClass String: a name of a child maintenance class
373 * @param $classFile String: full path of where the child is
374 * @return Maintenance child
376 public function runChild( $maintClass, $classFile = null ) {
377 // If we haven't already specified, kill setup procedures
378 // for child scripts, we've already got a sane environment
379 self
::disableSetup();
381 // Make sure the class is loaded first
382 if ( !class_exists( $maintClass ) ) {
384 require_once( $classFile );
386 if ( !class_exists( $maintClass ) ) {
387 $this->error( "Cannot spawn child: $maintClass" );
391 $child = new $maintClass();
392 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
397 * Disable Setup.php mostly
399 protected static function disableSetup() {
400 if ( !defined( 'MW_NO_SETUP' ) ) {
401 define( 'MW_NO_SETUP', true );
406 * Do some sanity checking and basic setup
408 public function setup() {
409 global $IP, $wgCommandLineMode, $wgRequestTime;
411 # Abort if called from a web server
412 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
413 $this->error( 'This script must be run from the command line', true );
416 # Make sure we can handle script parameters
417 if ( !ini_get( 'register_argc_argv' ) ) {
418 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
421 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
422 // Send PHP warnings and errors to stderr instead of stdout.
423 // This aids in diagnosing problems, while keeping messages
424 // out of redirected output.
425 if ( ini_get( 'display_errors' ) ) {
426 ini_set( 'display_errors', 'stderr' );
429 // Don't touch the setting on earlier versions of PHP,
430 // as setting it would disable output if you'd wanted it.
432 // Note that exceptions are also sent to stderr when
433 // command-line mode is on, regardless of PHP version.
436 $this->loadParamsAndArgs();
439 # Set the memory limit
440 # Note we need to set it again later in cache LocalSettings changed it
441 $this->adjustMemoryLimit();
443 # Set max execution time to 0 (no limit). PHP.net says that
444 # "When running PHP from the command line the default setting is 0."
445 # But sometimes this doesn't seem to be the case.
446 ini_set( 'max_execution_time', 0 );
448 $wgRequestTime = microtime( true );
450 # Define us as being in MediaWiki
451 define( 'MEDIAWIKI', true );
453 # Setup $IP, using MW_INSTALL_PATH if it exists
454 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
455 ?
getenv( 'MW_INSTALL_PATH' )
456 : realpath( dirname( __FILE__
) . '/..' );
458 $wgCommandLineMode = true;
459 # Turn off output buffering if it's on
462 $this->validateParamsAndArgs();
466 * Normally we disable the memory_limit when running admin scripts.
467 * Some scripts may wish to actually set a limit, however, to avoid
468 * blowing up unexpectedly. We also support a --memory-limit option,
469 * to allow sysadmins to explicitly set one if they'd prefer to override
470 * defaults (or for people using Suhosin which yells at you for trying
471 * to disable the limits)
473 public function memoryLimit() {
474 $limit = $this->getOption( 'memory-limit', 'max' );
475 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
480 * Adjusts PHP's memory limit to better suit our needs, if needed.
482 protected function adjustMemoryLimit() {
483 $limit = $this->memoryLimit();
484 if ( $limit == 'max' ) {
485 $limit = -1; // no memory limit
487 if ( $limit != 'default' ) {
488 ini_set( 'memory_limit', $limit );
493 * Clear all params and arguments.
495 public function clearParamsAndArgs() {
496 $this->mOptions
= array();
497 $this->mArgs
= array();
498 $this->mInputLoaded
= false;
502 * Process command line arguments
503 * $mOptions becomes an array with keys set to the option names
504 * $mArgs becomes a zero-based array containing the non-option arguments
506 * @param $self String The name of the script, if any
507 * @param $opts Array An array of options, in form of key=>value
508 * @param $args Array An array of command line arguments
510 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
511 # If we were given opts or args, set those and return early
513 $this->mSelf
= $self;
514 $this->mInputLoaded
= true;
517 $this->mOptions
= $opts;
518 $this->mInputLoaded
= true;
521 $this->mArgs
= $args;
522 $this->mInputLoaded
= true;
525 # If we've already loaded input (either by user values or from $argv)
526 # skip on loading it again. The array_shift() will corrupt values if
527 # it's run again and again
528 if ( $this->mInputLoaded
) {
529 $this->loadSpecialVars();
534 $this->mSelf
= array_shift( $argv );
540 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
541 if ( $arg == '--' ) {
542 # End of options, remainder should be considered arguments
543 $arg = next( $argv );
544 while ( $arg !== false ) {
546 $arg = next( $argv );
549 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
551 $option = substr( $arg, 2 );
552 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
553 $param = next( $argv );
554 if ( $param === false ) {
555 $this->error( "\nERROR: $option needs a value after it\n" );
556 $this->maybeHelp( true );
558 $options[$option] = $param;
560 $bits = explode( '=', $option, 2 );
561 if ( count( $bits ) > 1 ) {
567 $options[$option] = $param;
569 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
571 for ( $p = 1; $p < strlen( $arg ); $p++
) {
572 $option = $arg { $p } ;
573 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
574 $param = next( $argv );
575 if ( $param === false ) {
576 $this->error( "\nERROR: $option needs a value after it\n" );
577 $this->maybeHelp( true );
579 $options[$option] = $param;
581 $options[$option] = 1;
589 $this->mOptions
= $options;
590 $this->mArgs
= $args;
591 $this->loadSpecialVars();
592 $this->mInputLoaded
= true;
596 * Run some validation checks on the params, etc
598 protected function validateParamsAndArgs() {
600 # Check to make sure we've got all the required options
601 foreach ( $this->mParams
as $opt => $info ) {
602 if ( $info['require'] && !$this->hasOption( $opt ) ) {
603 $this->error( "Param $opt required!" );
608 foreach ( $this->mArgList
as $k => $info ) {
609 if ( $info['require'] && !$this->hasArg( $k ) ) {
610 $this->error( 'Argument <' . $info['name'] . '> required!' );
616 $this->maybeHelp( true );
621 * Handle the special variables that are global to all scripts
623 protected function loadSpecialVars() {
624 if ( $this->hasOption( 'dbuser' ) ) {
625 $this->mDbUser
= $this->getOption( 'dbuser' );
627 if ( $this->hasOption( 'dbpass' ) ) {
628 $this->mDbPass
= $this->getOption( 'dbpass' );
630 if ( $this->hasOption( 'quiet' ) ) {
631 $this->mQuiet
= true;
633 if ( $this->hasOption( 'batch-size' ) ) {
634 $this->mBatchSize
= $this->getOption( 'batch-size' );
639 * Maybe show the help.
640 * @param $force boolean Whether to force the help to show, default false
642 protected function maybeHelp( $force = false ) {
643 if( !$force && !$this->hasOption( 'help' ) ) {
647 $screenWidth = 80; // TODO: Caculate this!
649 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
651 ksort( $this->mParams
);
652 $this->mQuiet
= false;
655 if ( $this->mDescription
) {
656 $this->output( "\n" . $this->mDescription
. "\n" );
658 $output = "\nUsage: php " . basename( $this->mSelf
);
660 // ... append parameters ...
661 if ( $this->mParams
) {
662 $output .= " [--" . implode( array_keys( $this->mParams
), "|--" ) . "]";
665 // ... and append arguments.
666 if ( $this->mArgList
) {
668 foreach ( $this->mArgList
as $k => $arg ) {
669 $output .= $arg['name'] . ">";
670 if ( $k < count( $this->mArgList
) - 1 )
674 $this->output( "$output\n\n" );
676 // Parameters description
677 foreach ( $this->mParams
as $par => $info ) {
679 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
680 "\n$tab$tab" ) . "\n"
684 // Arguments description
685 foreach ( $this->mArgList
as $info ) {
687 wordwrap( "$tab<" . $info['name'] . ">: " .
688 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
696 * Handle some last-minute setup here.
698 public function finalSetup() {
699 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
700 global $wgProfiling, $wgDBadminuser, $wgDBadminpassword;
701 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
703 # Turn off output buffering again, it might have been turned on in the settings files
704 if ( ob_get_level() ) {
708 $wgCommandLineMode = true;
711 if( $this->hasOption( 'server') ) {
712 $wgServer = $this->getOption( 'server', $wgServer );
715 # If these were passed, use them
716 if ( $this->mDbUser
) {
717 $wgDBadminuser = $this->mDbUser
;
719 if ( $this->mDbPass
) {
720 $wgDBadminpassword = $this->mDbPass
;
723 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
724 $wgDBuser = $wgDBadminuser;
725 $wgDBpassword = $wgDBadminpassword;
727 if ( $wgDBservers ) {
728 foreach ( $wgDBservers as $i => $server ) {
729 $wgDBservers[$i]['user'] = $wgDBuser;
730 $wgDBservers[$i]['password'] = $wgDBpassword;
733 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
734 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
735 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
737 LBFactory
::destroyInstance();
740 $this->afterFinalSetup();
742 $wgShowSQLErrors = true;
743 @set_time_limit
( 0 );
744 $this->adjustMemoryLimit();
746 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
750 * Execute a callback function at the end of initialisation
752 protected function afterFinalSetup() {
753 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
754 call_user_func( MW_CMDLINE_CALLBACK
);
759 * Potentially debug globals. Originally a feature only
762 public function globals() {
763 if ( $this->hasOption( 'globals' ) ) {
769 * Do setup specific to WMF
771 public function loadWikimediaSettings() {
772 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
774 if ( empty( $wgNoDBParam ) ) {
775 # Check if we were passed a db name
776 if ( isset( $this->mOptions
['wiki'] ) ) {
777 $db = $this->mOptions
['wiki'];
779 $db = array_shift( $this->mArgs
);
781 list( $site, $lang ) = $wgConf->siteFromDB( $db );
783 # If not, work out the language and site the old way
784 if ( is_null( $site ) ||
is_null( $lang ) ) {
790 if ( isset( $this->mArgs
[0] ) ) {
791 $site = array_shift( $this->mArgs
);
801 # This is for the IRC scripts, which now run as the apache user
802 # The apache user doesn't have access to the wikiadmin_pass command
803 if ( $_ENV['USER'] == 'apache' ) {
804 # if ( posix_geteuid() == 48 ) {
805 $wgUseNormalUser = true;
808 putenv( 'wikilang=' . $lang );
810 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
812 if ( $lang == 'test' && $site == 'wikipedia' ) {
813 define( 'TESTWIKI', 1 );
818 * Generic setup for most installs. Returns the location of LocalSettings
821 public function loadSettings() {
822 global $wgWikiFarm, $wgCommandLineMode, $IP;
825 if ( isset( $this->mOptions
['conf'] ) ) {
826 $settingsFile = $this->mOptions
['conf'];
828 $settingsFile = "$IP/LocalSettings.php";
830 if ( isset( $this->mOptions
['wiki'] ) ) {
831 $bits = explode( '-', $this->mOptions
['wiki'] );
832 if ( count( $bits ) == 1 ) {
835 define( 'MW_DB', $bits[0] );
836 define( 'MW_PREFIX', $bits[1] );
839 if ( !is_readable( $settingsFile ) ) {
840 $this->error( "A copy of your installation's LocalSettings.php\n" .
841 "must exist and be readable in the source directory.\n" .
842 "Use --conf to specify it." , true );
844 $wgCommandLineMode = true;
845 return $settingsFile;
849 * Support function for cleaning up redundant text records
850 * @param $delete Boolean: whether or not to actually delete the records
851 * @author Rob Church <robchur@gmail.com>
853 public function purgeRedundantText( $delete = true ) {
854 # Data should come off the master, wrapped in a transaction
855 $dbw = wfGetDB( DB_MASTER
);
858 $tbl_arc = $dbw->tableName( 'archive' );
859 $tbl_rev = $dbw->tableName( 'revision' );
860 $tbl_txt = $dbw->tableName( 'text' );
862 # Get "active" text records from the revisions table
863 $this->output( 'Searching for active text records in revisions table...' );
864 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
865 foreach ( $res as $row ) {
866 $cur[] = $row->rev_text_id
;
868 $this->output( "done.\n" );
870 # Get "active" text records from the archive table
871 $this->output( 'Searching for active text records in archive table...' );
872 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
873 foreach ( $res as $row ) {
874 $cur[] = $row->ar_text_id
;
876 $this->output( "done.\n" );
878 # Get the IDs of all text records not in these sets
879 $this->output( 'Searching for inactive text records...' );
880 $set = implode( ', ', $cur );
881 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
883 foreach ( $res as $row ) {
884 $old[] = $row->old_id
;
886 $this->output( "done.\n" );
888 # Inform the user of what we're going to do
889 $count = count( $old );
890 $this->output( "$count inactive items found.\n" );
892 # Delete as appropriate
893 if ( $delete && $count ) {
894 $this->output( 'Deleting...' );
895 $set = implode( ', ', $old );
896 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
897 $this->output( "done.\n" );
905 * Get the maintenance directory.
907 protected function getDir() {
908 return dirname( __FILE__
);
912 * Get the list of available maintenance scripts. Note
913 * that if you call this _before_ calling doMaintenance
914 * you won't have any extensions in it yet
917 public static function getMaintenanceScripts() {
918 global $wgMaintenanceScripts;
919 return $wgMaintenanceScripts + self
::getCoreScripts();
923 * Return all of the core maintenance scripts
926 protected static function getCoreScripts() {
927 if ( !self
::$mCoreScripts ) {
928 self
::disableSetup();
931 dirname( __FILE__
) . '/gearman',
932 dirname( __FILE__
) . '/language',
933 dirname( __FILE__
) . '/storage',
935 self
::$mCoreScripts = array();
936 foreach ( $paths as $p ) {
937 $handle = opendir( $p );
938 while ( ( $file = readdir( $handle ) ) !== false ) {
939 if ( $file == 'Maintenance.php' ) {
942 $file = $p . '/' . $file;
943 if ( is_dir( $file ) ||
!strpos( $file, '.php' ) ||
944 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
948 $vars = get_defined_vars();
949 if ( array_key_exists( 'maintClass', $vars ) ) {
950 self
::$mCoreScripts[$vars['maintClass']] = $file;
956 return self
::$mCoreScripts;
960 * Lock the search index
961 * @param &$db Database object
963 private function lockSearchindex( &$db ) {
964 $write = array( 'searchindex' );
965 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
966 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
971 * @param &$db Database object
973 private function unlockSearchindex( &$db ) {
974 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
978 * Unlock and lock again
979 * Since the lock is low-priority, queued reads will be able to complete
980 * @param &$db Database object
982 private function relockSearchindex( &$db ) {
983 $this->unlockSearchindex( $db );
984 $this->lockSearchindex( $db );
988 * Perform a search index update with locking
989 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
990 * @param $callback callback String: the function that will update the function.
991 * @param $dbw Database object
994 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
998 if ( $maxLockTime ) {
999 $this->output( " --- Waiting for lock ---" );
1000 $this->lockSearchindex( $dbw );
1002 $this->output( "\n" );
1005 # Loop through the results and do a search update
1006 foreach ( $results as $row ) {
1007 # Allow reads to be processed
1008 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1009 $this->output( " --- Relocking ---" );
1010 $this->relockSearchindex( $dbw );
1012 $this->output( "\n" );
1014 call_user_func( $callback, $dbw, $row );
1017 # Unlock searchindex
1018 if ( $maxLockTime ) {
1019 $this->output( " --- Unlocking --" );
1020 $this->unlockSearchindex( $dbw );
1021 $this->output( "\n" );
1027 * Update the searchindex table for a given pageid
1028 * @param $dbw Database: a database write handle
1029 * @param $pageId Integer: the page ID to update.
1031 public function updateSearchIndexForPage( $dbw, $pageId ) {
1032 // Get current revision
1033 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1036 $titleObj = $rev->getTitle();
1037 $title = $titleObj->getPrefixedDBkey();
1038 $this->output( "$title..." );
1039 # Update searchindex
1040 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1042 $this->output( "\n" );
1049 class FakeMaintenance
extends Maintenance
{
1050 public function execute() {