Merge "Whitelist the <wbr> element."
[mediawiki.git] / maintenance / Maintenance.php
blobe29ffd992b4de2d45f2b0d927561558be790c3b9
1 <?php
2 /**
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
18 * @file
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Make sure we're on PHP5.3.2 or better
24 if ( !function_exists( 'version_compare' ) || version_compare( PHP_VERSION, '5.3.2' ) < 0 ) {
25 // We need to use dirname( __FILE__ ) here cause __DIR__ is PHP5.3+
26 require_once dirname( __FILE__ ) . '/../includes/PHPVersionError.php';
27 wfPHPVersionError( 'cli' );
30 /**
31 * @defgroup MaintenanceArchive Maintenance archives
32 * @ingroup Maintenance
35 // Define this so scripts can easily find doMaintenance.php
36 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' );
37 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
39 $maintClass = false;
41 /**
42 * Abstract maintenance class for quickly writing and churning out
43 * maintenance scripts with minimal effort. All that _must_ be defined
44 * is the execute() method. See docs/maintenance.txt for more info
45 * and a quick demo of how to use it.
47 * @author Chad Horohoe <chad@anyonecanedit.org>
48 * @since 1.16
49 * @ingroup Maintenance
51 abstract class Maintenance {
53 /**
54 * Constants for DB access type
55 * @see Maintenance::getDbType()
57 const DB_NONE = 0;
58 const DB_STD = 1;
59 const DB_ADMIN = 2;
61 // Const for getStdin()
62 const STDIN_ALL = 'all';
64 // This is the desired params
65 protected $mParams = array();
67 // Array of mapping short parameters to long ones
68 protected $mShortParamsMap = array();
70 // Array of desired args
71 protected $mArgList = array();
73 // This is the list of options that were actually passed
74 protected $mOptions = array();
76 // This is the list of arguments that were actually passed
77 protected $mArgs = array();
79 // Name of the script currently running
80 protected $mSelf;
82 // Special vars for params that are always used
83 protected $mQuiet = false;
84 protected $mDbUser, $mDbPass;
86 // A description of the script, children should change this
87 protected $mDescription = '';
89 // Have we already loaded our user input?
90 protected $mInputLoaded = false;
92 /**
93 * Batch size. If a script supports this, they should set
94 * a default with setBatchSize()
96 * @var int
98 protected $mBatchSize = null;
100 // Generic options added by addDefaultParams()
101 private $mGenericParameters = array();
102 // Generic options which might or not be supported by the script
103 private $mDependantParameters = array();
106 * Used by getDD() / setDB()
107 * @var DatabaseBase
109 private $mDb = null;
112 * Used when creating separate schema files.
113 * @var resource
115 public $fileHandle;
118 * List of all the core maintenance scripts. This is added
119 * to scripts added by extensions in $wgMaintenanceScripts
120 * and returned by getMaintenanceScripts()
122 protected static $mCoreScripts = null;
125 * Default constructor. Children should call this *first* if implementing
126 * their own constructors
128 public function __construct() {
129 // Setup $IP, using MW_INSTALL_PATH if it exists
130 global $IP;
131 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
132 ? getenv( 'MW_INSTALL_PATH' )
133 : realpath( __DIR__ . '/..' );
135 $this->addDefaultParams();
136 register_shutdown_function( array( $this, 'outputChanneled' ), false );
140 * Should we execute the maintenance script, or just allow it to be included
141 * as a standalone class? It checks that the call stack only includes this
142 * function and "requires" (meaning was called from the file scope)
144 * @return Boolean
146 public static function shouldExecute() {
147 $bt = debug_backtrace();
148 $count = count( $bt );
149 if ( $count < 2 ) {
150 return false; // sanity
152 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
153 return false; // last call should be to this function
155 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
156 for ( $i = 1; $i < $count; $i++ ) {
157 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
158 return false; // previous calls should all be "requires"
161 return true;
165 * Do the actual work. All child classes will need to implement this
167 abstract public function execute();
170 * Add a parameter to the script. Will be displayed on --help
171 * with the associated description
173 * @param $name String: the name of the param (help, version, etc)
174 * @param $description String: the description of the param to show on --help
175 * @param $required Boolean: is the param required?
176 * @param $withArg Boolean: is an argument required with this option?
177 * @param $shortName String: character to use as short name
179 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
180 $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
181 if ( $shortName !== false ) {
182 $this->mShortParamsMap[$shortName] = $name;
187 * Checks to see if a particular param exists.
188 * @param $name String: the name of the param
189 * @return Boolean
191 protected function hasOption( $name ) {
192 return isset( $this->mOptions[$name] );
196 * Get an option, or return the default
197 * @param $name String: the name of the param
198 * @param $default Mixed: anything you want, default null
199 * @return Mixed
201 protected function getOption( $name, $default = null ) {
202 if ( $this->hasOption( $name ) ) {
203 return $this->mOptions[$name];
204 } else {
205 // Set it so we don't have to provide the default again
206 $this->mOptions[$name] = $default;
207 return $this->mOptions[$name];
212 * Add some args that are needed
213 * @param $arg String: name of the arg, like 'start'
214 * @param $description String: short description of the arg
215 * @param $required Boolean: is this required?
217 protected function addArg( $arg, $description, $required = true ) {
218 $this->mArgList[] = array(
219 'name' => $arg,
220 'desc' => $description,
221 'require' => $required
226 * Remove an option. Useful for removing options that won't be used in your script.
227 * @param $name String: the option to remove.
229 protected function deleteOption( $name ) {
230 unset( $this->mParams[$name] );
234 * Set the description text.
235 * @param $text String: the text of the description
237 protected function addDescription( $text ) {
238 $this->mDescription = $text;
242 * Does a given argument exist?
243 * @param $argId Integer: the integer value (from zero) for the arg
244 * @return Boolean
246 protected function hasArg( $argId = 0 ) {
247 return isset( $this->mArgs[$argId] );
251 * Get an argument.
252 * @param $argId Integer: the integer value (from zero) for the arg
253 * @param $default Mixed: the default if it doesn't exist
254 * @return mixed
256 protected function getArg( $argId = 0, $default = null ) {
257 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
261 * Set the batch size.
262 * @param $s Integer: the number of operations to do in a batch
264 protected function setBatchSize( $s = 0 ) {
265 $this->mBatchSize = $s;
267 // If we support $mBatchSize, show the option.
268 // Used to be in addDefaultParams, but in order for that to
269 // work, subclasses would have to call this function in the constructor
270 // before they called parent::__construct which is just weird
271 // (and really wasn't done).
272 if ( $this->mBatchSize ) {
273 $this->addOption( 'batch-size', 'Run this many operations ' .
274 'per batch, default: ' . $this->mBatchSize, false, true );
275 if ( isset( $this->mParams['batch-size'] ) ) {
276 // This seems a little ugly...
277 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
283 * Get the script's name
284 * @return String
286 public function getName() {
287 return $this->mSelf;
291 * Return input from stdin.
292 * @param $len Integer: the number of bytes to read. If null,
293 * just return the handle. Maintenance::STDIN_ALL returns
294 * the full length
295 * @return Mixed
297 protected function getStdin( $len = null ) {
298 if ( $len == Maintenance::STDIN_ALL ) {
299 return file_get_contents( 'php://stdin' );
301 $f = fopen( 'php://stdin', 'rt' );
302 if ( !$len ) {
303 return $f;
305 $input = fgets( $f, $len );
306 fclose( $f );
307 return rtrim( $input );
311 * @return bool
313 public function isQuiet() {
314 return $this->mQuiet;
318 * Throw some output to the user. Scripts can call this with no fears,
319 * as we handle all --quiet stuff here
320 * @param $out String: the text to show to the user
321 * @param $channel Mixed: unique identifier for the channel. See
322 * function outputChanneled.
324 protected function output( $out, $channel = null ) {
325 if ( $this->mQuiet ) {
326 return;
328 if ( $channel === null ) {
329 $this->cleanupChanneled();
330 print $out;
331 } else {
332 $out = preg_replace( '/\n\z/', '', $out );
333 $this->outputChanneled( $out, $channel );
338 * Throw an error to the user. Doesn't respect --quiet, so don't use
339 * this for non-error output
340 * @param $err String: the error to display
341 * @param $die Int: if > 0, go ahead and die out using this int as the code
343 protected function error( $err, $die = 0 ) {
344 $this->outputChanneled( false );
345 if ( PHP_SAPI == 'cli' ) {
346 fwrite( STDERR, $err . "\n" );
347 } else {
348 print $err;
350 $die = intval( $die );
351 if ( $die > 0 ) {
352 die( $die );
356 private $atLineStart = true;
357 private $lastChannel = null;
360 * Clean up channeled output. Output a newline if necessary.
362 public function cleanupChanneled() {
363 if ( !$this->atLineStart ) {
364 print "\n";
365 $this->atLineStart = true;
370 * Message outputter with channeled message support. Messages on the
371 * same channel are concatenated, but any intervening messages in another
372 * channel start a new line.
373 * @param $msg String: the message without trailing newline
374 * @param $channel string Channel identifier or null for no
375 * channel. Channel comparison uses ===.
377 public function outputChanneled( $msg, $channel = null ) {
378 if ( $msg === false ) {
379 $this->cleanupChanneled();
380 return;
383 // End the current line if necessary
384 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
385 print "\n";
388 print $msg;
390 $this->atLineStart = false;
391 if ( $channel === null ) {
392 // For unchanneled messages, output trailing newline immediately
393 print "\n";
394 $this->atLineStart = true;
396 $this->lastChannel = $channel;
400 * Does the script need different DB access? By default, we give Maintenance
401 * scripts normal rights to the DB. Sometimes, a script needs admin rights
402 * access for a reason and sometimes they want no access. Subclasses should
403 * override and return one of the following values, as needed:
404 * Maintenance::DB_NONE - For no DB access at all
405 * Maintenance::DB_STD - For normal DB access, default
406 * Maintenance::DB_ADMIN - For admin DB access
407 * @return Integer
409 public function getDbType() {
410 return Maintenance::DB_STD;
414 * Add the default parameters to the scripts
416 protected function addDefaultParams() {
418 # Generic (non script dependant) options:
420 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
421 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
422 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
423 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
424 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
425 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
426 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
427 "http://en.wikipedia.org. This is sometimes necessary because " .
428 "server name detection may fail in command line scripts.", false, true );
429 $this->addOption( 'profiler', 'Set to "text" or "trace" to show profiling output', false, true );
431 # Save generic options to display them separately in help
432 $this->mGenericParameters = $this->mParams;
434 # Script dependant options:
436 // If we support a DB, show the options
437 if ( $this->getDbType() > 0 ) {
438 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
439 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
442 # Save additional script dependant options to display
443 # them separately in help
444 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
448 * Run a child maintenance script. Pass all of the current arguments
449 * to it.
450 * @param $maintClass String: a name of a child maintenance class
451 * @param $classFile String: full path of where the child is
452 * @return Maintenance child
454 public function runChild( $maintClass, $classFile = null ) {
455 // Make sure the class is loaded first
456 if ( !MWInit::classExists( $maintClass ) ) {
457 if ( $classFile ) {
458 require_once $classFile;
460 if ( !MWInit::classExists( $maintClass ) ) {
461 $this->error( "Cannot spawn child: $maintClass" );
466 * @var $child Maintenance
468 $child = new $maintClass();
469 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
470 if ( !is_null( $this->mDb ) ) {
471 $child->setDB( $this->mDb );
473 return $child;
477 * Do some sanity checking and basic setup
479 public function setup() {
480 global $wgCommandLineMode, $wgRequestTime;
482 # Abort if called from a web server
483 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
484 $this->error( 'This script must be run from the command line', true );
487 # Make sure we can handle script parameters
488 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
489 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
492 // Send PHP warnings and errors to stderr instead of stdout.
493 // This aids in diagnosing problems, while keeping messages
494 // out of redirected output.
495 if ( ini_get( 'display_errors' ) ) {
496 ini_set( 'display_errors', 'stderr' );
499 $this->loadParamsAndArgs();
500 $this->maybeHelp();
502 # Set the memory limit
503 # Note we need to set it again later in cache LocalSettings changed it
504 $this->adjustMemoryLimit();
506 # Set max execution time to 0 (no limit). PHP.net says that
507 # "When running PHP from the command line the default setting is 0."
508 # But sometimes this doesn't seem to be the case.
509 ini_set( 'max_execution_time', 0 );
511 $wgRequestTime = microtime( true );
513 # Define us as being in MediaWiki
514 define( 'MEDIAWIKI', true );
516 $wgCommandLineMode = true;
518 # Turn off output buffering if it's on
519 while ( ob_get_level() > 0 ) {
520 ob_end_flush();
523 $this->validateParamsAndArgs();
527 * Normally we disable the memory_limit when running admin scripts.
528 * Some scripts may wish to actually set a limit, however, to avoid
529 * blowing up unexpectedly. We also support a --memory-limit option,
530 * to allow sysadmins to explicitly set one if they'd prefer to override
531 * defaults (or for people using Suhosin which yells at you for trying
532 * to disable the limits)
533 * @return string
535 public function memoryLimit() {
536 $limit = $this->getOption( 'memory-limit', 'max' );
537 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
538 return $limit;
542 * Adjusts PHP's memory limit to better suit our needs, if needed.
544 protected function adjustMemoryLimit() {
545 $limit = $this->memoryLimit();
546 if ( $limit == 'max' ) {
547 $limit = -1; // no memory limit
549 if ( $limit != 'default' ) {
550 ini_set( 'memory_limit', $limit );
555 * Clear all params and arguments.
557 public function clearParamsAndArgs() {
558 $this->mOptions = array();
559 $this->mArgs = array();
560 $this->mInputLoaded = false;
564 * Process command line arguments
565 * $mOptions becomes an array with keys set to the option names
566 * $mArgs becomes a zero-based array containing the non-option arguments
568 * @param $self String The name of the script, if any
569 * @param $opts Array An array of options, in form of key=>value
570 * @param $args Array An array of command line arguments
572 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
573 # If we were given opts or args, set those and return early
574 if ( $self ) {
575 $this->mSelf = $self;
576 $this->mInputLoaded = true;
578 if ( $opts ) {
579 $this->mOptions = $opts;
580 $this->mInputLoaded = true;
582 if ( $args ) {
583 $this->mArgs = $args;
584 $this->mInputLoaded = true;
587 # If we've already loaded input (either by user values or from $argv)
588 # skip on loading it again. The array_shift() will corrupt values if
589 # it's run again and again
590 if ( $this->mInputLoaded ) {
591 $this->loadSpecialVars();
592 return;
595 global $argv;
596 $this->mSelf = array_shift( $argv );
598 $options = array();
599 $args = array();
601 # Parse arguments
602 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
603 if ( $arg == '--' ) {
604 # End of options, remainder should be considered arguments
605 $arg = next( $argv );
606 while ( $arg !== false ) {
607 $args[] = $arg;
608 $arg = next( $argv );
610 break;
611 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
612 # Long options
613 $option = substr( $arg, 2 );
614 if ( array_key_exists( $option, $options ) ) {
615 $this->error( "\nERROR: $option parameter given twice\n" );
616 $this->maybeHelp( true );
618 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
619 $param = next( $argv );
620 if ( $param === false ) {
621 $this->error( "\nERROR: $option parameter needs a value after it\n" );
622 $this->maybeHelp( true );
624 $options[$option] = $param;
625 } else {
626 $bits = explode( '=', $option, 2 );
627 if ( count( $bits ) > 1 ) {
628 $option = $bits[0];
629 $param = $bits[1];
630 } else {
631 $param = 1;
633 $options[$option] = $param;
635 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
636 # Short options
637 for ( $p = 1; $p < strlen( $arg ); $p++ ) {
638 $option = $arg { $p };
639 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
640 $option = $this->mShortParamsMap[$option];
642 if ( array_key_exists( $option, $options ) ) {
643 $this->error( "\nERROR: $option parameter given twice\n" );
644 $this->maybeHelp( true );
646 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
647 $param = next( $argv );
648 if ( $param === false ) {
649 $this->error( "\nERROR: $option parameter needs a value after it\n" );
650 $this->maybeHelp( true );
652 $options[$option] = $param;
653 } else {
654 $options[$option] = 1;
657 } else {
658 $args[] = $arg;
662 $this->mOptions = $options;
663 $this->mArgs = $args;
664 $this->loadSpecialVars();
665 $this->mInputLoaded = true;
669 * Run some validation checks on the params, etc
671 protected function validateParamsAndArgs() {
672 $die = false;
673 # Check to make sure we've got all the required options
674 foreach ( $this->mParams as $opt => $info ) {
675 if ( $info['require'] && !$this->hasOption( $opt ) ) {
676 $this->error( "Param $opt required!" );
677 $die = true;
680 # Check arg list too
681 foreach ( $this->mArgList as $k => $info ) {
682 if ( $info['require'] && !$this->hasArg( $k ) ) {
683 $this->error( 'Argument <' . $info['name'] . '> required!' );
684 $die = true;
688 if ( $die ) {
689 $this->maybeHelp( true );
694 * Handle the special variables that are global to all scripts
696 protected function loadSpecialVars() {
697 if ( $this->hasOption( 'dbuser' ) ) {
698 $this->mDbUser = $this->getOption( 'dbuser' );
700 if ( $this->hasOption( 'dbpass' ) ) {
701 $this->mDbPass = $this->getOption( 'dbpass' );
703 if ( $this->hasOption( 'quiet' ) ) {
704 $this->mQuiet = true;
706 if ( $this->hasOption( 'batch-size' ) ) {
707 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
712 * Maybe show the help.
713 * @param $force boolean Whether to force the help to show, default false
715 protected function maybeHelp( $force = false ) {
716 if ( !$force && !$this->hasOption( 'help' ) ) {
717 return;
720 $screenWidth = 80; // TODO: Caculate this!
721 $tab = " ";
722 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
724 ksort( $this->mParams );
725 $this->mQuiet = false;
727 // Description ...
728 if ( $this->mDescription ) {
729 $this->output( "\n" . $this->mDescription . "\n" );
731 $output = "\nUsage: php " . basename( $this->mSelf );
733 // ... append parameters ...
734 if ( $this->mParams ) {
735 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
738 // ... and append arguments.
739 if ( $this->mArgList ) {
740 $output .= ' ';
741 foreach ( $this->mArgList as $k => $arg ) {
742 if ( $arg['require'] ) {
743 $output .= '<' . $arg['name'] . '>';
744 } else {
745 $output .= '[' . $arg['name'] . ']';
747 if ( $k < count( $this->mArgList ) - 1 ) {
748 $output .= ' ';
752 $this->output( "$output\n\n" );
754 # TODO abstract some repetitive code below
756 // Generic parameters
757 $this->output( "Generic maintenance parameters:\n" );
758 foreach ( $this->mGenericParameters as $par => $info ) {
759 if ( $info['shortName'] !== false ) {
760 $par .= " (-{$info['shortName']})";
762 $this->output(
763 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
764 "\n$tab$tab" ) . "\n"
767 $this->output( "\n" );
769 $scriptDependantParams = $this->mDependantParameters;
770 if ( count( $scriptDependantParams ) > 0 ) {
771 $this->output( "Script dependant parameters:\n" );
772 // Parameters description
773 foreach ( $scriptDependantParams as $par => $info ) {
774 if ( $info['shortName'] !== false ) {
775 $par .= " (-{$info['shortName']})";
777 $this->output(
778 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
779 "\n$tab$tab" ) . "\n"
782 $this->output( "\n" );
786 // Script specific parameters not defined on construction by
787 // Maintenance::addDefaultParams()
788 $scriptSpecificParams = array_diff_key(
789 # all script parameters:
790 $this->mParams,
791 # remove the Maintenance default parameters:
792 $this->mGenericParameters,
793 $this->mDependantParameters
795 if ( count( $scriptSpecificParams ) > 0 ) {
796 $this->output( "Script specific parameters:\n" );
797 // Parameters description
798 foreach ( $scriptSpecificParams as $par => $info ) {
799 if ( $info['shortName'] !== false ) {
800 $par .= " (-{$info['shortName']})";
802 $this->output(
803 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
804 "\n$tab$tab" ) . "\n"
807 $this->output( "\n" );
810 // Print arguments
811 if ( count( $this->mArgList ) > 0 ) {
812 $this->output( "Arguments:\n" );
813 // Arguments description
814 foreach ( $this->mArgList as $info ) {
815 $openChar = $info['require'] ? '<' : '[';
816 $closeChar = $info['require'] ? '>' : ']';
817 $this->output(
818 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
819 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
822 $this->output( "\n" );
825 die( 1 );
829 * Handle some last-minute setup here.
831 public function finalSetup() {
832 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
833 global $wgDBadminuser, $wgDBadminpassword;
834 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
836 # Turn off output buffering again, it might have been turned on in the settings files
837 if ( ob_get_level() ) {
838 ob_end_flush();
840 # Same with these
841 $wgCommandLineMode = true;
843 # Override $wgServer
844 if ( $this->hasOption( 'server' ) ) {
845 $wgServer = $this->getOption( 'server', $wgServer );
848 # If these were passed, use them
849 if ( $this->mDbUser ) {
850 $wgDBadminuser = $this->mDbUser;
852 if ( $this->mDbPass ) {
853 $wgDBadminpassword = $this->mDbPass;
856 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
857 $wgDBuser = $wgDBadminuser;
858 $wgDBpassword = $wgDBadminpassword;
860 if ( $wgDBservers ) {
862 * @var $wgDBservers array
864 foreach ( $wgDBservers as $i => $server ) {
865 $wgDBservers[$i]['user'] = $wgDBuser;
866 $wgDBservers[$i]['password'] = $wgDBpassword;
869 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
870 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
871 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
873 LBFactory::destroyInstance();
876 $this->afterFinalSetup();
878 $wgShowSQLErrors = true;
879 @set_time_limit( 0 );
880 $this->adjustMemoryLimit();
882 // Per-script profiling; useful for debugging
883 $forcedProfiler = $this->getOption( 'profiler' );
884 if ( $forcedProfiler === 'text' ) {
885 Profiler::setInstance( new ProfilerSimpleText( array() ) );
886 Profiler::instance()->setTemplated( true );
887 } elseif ( $forcedProfiler === 'trace' ) {
888 Profiler::setInstance( new ProfilerSimpleTrace( array() ) );
889 Profiler::instance()->setTemplated( true );
894 * Execute a callback function at the end of initialisation
896 protected function afterFinalSetup() {
897 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
898 call_user_func( MW_CMDLINE_CALLBACK );
903 * Potentially debug globals. Originally a feature only
904 * for refreshLinks
906 public function globals() {
907 if ( $this->hasOption( 'globals' ) ) {
908 print_r( $GLOBALS );
913 * Generic setup for most installs. Returns the location of LocalSettings
914 * @return String
916 public function loadSettings() {
917 global $wgCommandLineMode, $IP;
919 if ( isset( $this->mOptions['conf'] ) ) {
920 $settingsFile = $this->mOptions['conf'];
921 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
922 $settingsFile = MW_CONFIG_FILE;
923 } else {
924 $settingsFile = "$IP/LocalSettings.php";
926 if ( isset( $this->mOptions['wiki'] ) ) {
927 $bits = explode( '-', $this->mOptions['wiki'] );
928 if ( count( $bits ) == 1 ) {
929 $bits[] = '';
931 define( 'MW_DB', $bits[0] );
932 define( 'MW_PREFIX', $bits[1] );
935 if ( !is_readable( $settingsFile ) ) {
936 $this->error( "A copy of your installation's LocalSettings.php\n" .
937 "must exist and be readable in the source directory.\n" .
938 "Use --conf to specify it.", true );
940 $wgCommandLineMode = true;
941 return $settingsFile;
945 * Support function for cleaning up redundant text records
946 * @param $delete Boolean: whether or not to actually delete the records
947 * @author Rob Church <robchur@gmail.com>
949 public function purgeRedundantText( $delete = true ) {
950 # Data should come off the master, wrapped in a transaction
951 $dbw = $this->getDB( DB_MASTER );
952 $dbw->begin( __METHOD__ );
954 # Get "active" text records from the revisions table
955 $this->output( 'Searching for active text records in revisions table...' );
956 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
957 foreach ( $res as $row ) {
958 $cur[] = $row->rev_text_id;
960 $this->output( "done.\n" );
962 # Get "active" text records from the archive table
963 $this->output( 'Searching for active text records in archive table...' );
964 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
965 foreach ( $res as $row ) {
966 # old pre-MW 1.5 records can have null ar_text_id's.
967 if ( $row->ar_text_id !== null ) {
968 $cur[] = $row->ar_text_id;
971 $this->output( "done.\n" );
973 # Get the IDs of all text records not in these sets
974 $this->output( 'Searching for inactive text records...' );
975 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
976 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__, array( 'DISTINCT' ) );
977 $old = array();
978 foreach ( $res as $row ) {
979 $old[] = $row->old_id;
981 $this->output( "done.\n" );
983 # Inform the user of what we're going to do
984 $count = count( $old );
985 $this->output( "$count inactive items found.\n" );
987 # Delete as appropriate
988 if ( $delete && $count ) {
989 $this->output( 'Deleting...' );
990 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__ );
991 $this->output( "done.\n" );
994 # Done
995 $dbw->commit( __METHOD__ );
999 * Get the maintenance directory.
1000 * @return string
1002 protected function getDir() {
1003 return __DIR__;
1007 * Get the list of available maintenance scripts. Note
1008 * that if you call this _before_ calling doMaintenance
1009 * you won't have any extensions in it yet
1010 * @return Array
1012 public static function getMaintenanceScripts() {
1013 global $wgMaintenanceScripts;
1014 return $wgMaintenanceScripts + self::getCoreScripts();
1018 * Return all of the core maintenance scripts
1019 * @return array
1021 protected static function getCoreScripts() {
1022 if ( !self::$mCoreScripts ) {
1023 $paths = array(
1024 __DIR__,
1025 __DIR__ . '/language',
1026 __DIR__ . '/storage',
1028 self::$mCoreScripts = array();
1029 foreach ( $paths as $p ) {
1030 $handle = opendir( $p );
1031 while ( ( $file = readdir( $handle ) ) !== false ) {
1032 if ( $file == 'Maintenance.php' ) {
1033 continue;
1035 $file = $p . '/' . $file;
1036 if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
1037 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1038 continue;
1040 require $file;
1041 $vars = get_defined_vars();
1042 if ( array_key_exists( 'maintClass', $vars ) ) {
1043 self::$mCoreScripts[$vars['maintClass']] = $file;
1046 closedir( $handle );
1049 return self::$mCoreScripts;
1053 * Returns a database to be used by current maintenance script. It can be set by setDB().
1054 * If not set, wfGetDB() will be used.
1055 * This function has the same parameters as wfGetDB()
1057 * @return DatabaseBase
1059 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1060 if ( is_null( $this->mDb ) ) {
1061 return wfGetDB( $db, $groups, $wiki );
1062 } else {
1063 return $this->mDb;
1068 * Sets database object to be returned by getDB().
1070 * @param $db DatabaseBase: Database object to be used
1072 public function setDB( &$db ) {
1073 $this->mDb = $db;
1077 * Lock the search index
1078 * @param &$db DatabaseBase object
1080 private function lockSearchindex( &$db ) {
1081 $write = array( 'searchindex' );
1082 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1083 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1087 * Unlock the tables
1088 * @param &$db DatabaseBase object
1090 private function unlockSearchindex( &$db ) {
1091 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1095 * Unlock and lock again
1096 * Since the lock is low-priority, queued reads will be able to complete
1097 * @param &$db DatabaseBase object
1099 private function relockSearchindex( &$db ) {
1100 $this->unlockSearchindex( $db );
1101 $this->lockSearchindex( $db );
1105 * Perform a search index update with locking
1106 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1107 * @param $callback callback String: the function that will update the function.
1108 * @param $dbw DatabaseBase object
1109 * @param $results
1111 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1112 $lockTime = time();
1114 # Lock searchindex
1115 if ( $maxLockTime ) {
1116 $this->output( " --- Waiting for lock ---" );
1117 $this->lockSearchindex( $dbw );
1118 $lockTime = time();
1119 $this->output( "\n" );
1122 # Loop through the results and do a search update
1123 foreach ( $results as $row ) {
1124 # Allow reads to be processed
1125 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1126 $this->output( " --- Relocking ---" );
1127 $this->relockSearchindex( $dbw );
1128 $lockTime = time();
1129 $this->output( "\n" );
1131 call_user_func( $callback, $dbw, $row );
1134 # Unlock searchindex
1135 if ( $maxLockTime ) {
1136 $this->output( " --- Unlocking --" );
1137 $this->unlockSearchindex( $dbw );
1138 $this->output( "\n" );
1144 * Update the searchindex table for a given pageid
1145 * @param $dbw DatabaseBase a database write handle
1146 * @param $pageId Integer: the page ID to update.
1147 * @return null|string
1149 public function updateSearchIndexForPage( $dbw, $pageId ) {
1150 // Get current revision
1151 $rev = Revision::loadFromPageId( $dbw, $pageId );
1152 $title = null;
1153 if ( $rev ) {
1154 $titleObj = $rev->getTitle();
1155 $title = $titleObj->getPrefixedDBkey();
1156 $this->output( "$title..." );
1157 # Update searchindex
1158 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1159 $u->doUpdate();
1160 $this->output( "\n" );
1162 return $title;
1166 * Wrapper for posix_isatty()
1167 * We default as considering stdin a tty (for nice readline methods)
1168 * but treating stout as not a tty to avoid color codes
1170 * @param $fd int File descriptor
1171 * @return bool
1173 public static function posix_isatty( $fd ) {
1174 if ( !MWInit::functionExists( 'posix_isatty' ) ) {
1175 return !$fd;
1176 } else {
1177 return posix_isatty( $fd );
1182 * Prompt the console for input
1183 * @param $prompt String what to begin the line with, like '> '
1184 * @return String response
1186 public static function readconsole( $prompt = '> ' ) {
1187 static $isatty = null;
1188 if ( is_null( $isatty ) ) {
1189 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1192 if ( $isatty && function_exists( 'readline' ) ) {
1193 return readline( $prompt );
1194 } else {
1195 if ( $isatty ) {
1196 $st = self::readlineEmulation( $prompt );
1197 } else {
1198 if ( feof( STDIN ) ) {
1199 $st = false;
1200 } else {
1201 $st = fgets( STDIN, 1024 );
1204 if ( $st === false ) {
1205 return false;
1207 $resp = trim( $st );
1208 return $resp;
1213 * Emulate readline()
1214 * @param $prompt String what to begin the line with, like '> '
1215 * @return String
1217 private static function readlineEmulation( $prompt ) {
1218 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1219 if ( !wfIsWindows() && $bash ) {
1220 $retval = false;
1221 $encPrompt = wfEscapeShellArg( $prompt );
1222 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1223 $encCommand = wfEscapeShellArg( $command );
1224 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1226 if ( $retval == 0 ) {
1227 return $line;
1228 } elseif ( $retval == 127 ) {
1229 // Couldn't execute bash even though we thought we saw it.
1230 // Shell probably spit out an error message, sorry :(
1231 // Fall through to fgets()...
1232 } else {
1233 // EOF/ctrl+D
1234 return false;
1238 // Fallback... we'll have no editing controls, EWWW
1239 if ( feof( STDIN ) ) {
1240 return false;
1242 print $prompt;
1243 return fgets( STDIN, 1024 );
1248 * Fake maintenance wrapper, mostly used for the web installer/updater
1250 class FakeMaintenance extends Maintenance {
1251 protected $mSelf = "FakeMaintenanceScript";
1252 public function execute() {
1253 return;
1258 * Class for scripts that perform database maintenance and want to log the
1259 * update in `updatelog` so we can later skip it
1261 abstract class LoggedUpdateMaintenance extends Maintenance {
1262 public function __construct() {
1263 parent::__construct();
1264 $this->addOption( 'force', 'Run the update even if it was completed already' );
1265 $this->setBatchSize( 200 );
1268 public function execute() {
1269 $db = $this->getDB( DB_MASTER );
1270 $key = $this->getUpdateKey();
1272 if ( !$this->hasOption( 'force' ) &&
1273 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ ) )
1275 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1276 return true;
1279 if ( !$this->doDBUpdates() ) {
1280 return false;
1283 if (
1284 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) )
1286 return true;
1287 } else {
1288 $this->output( $this->updatelogFailedMessage() . "\n" );
1289 return false;
1294 * Message to show that the update was done already and was just skipped
1295 * @return String
1297 protected function updateSkippedMessage() {
1298 $key = $this->getUpdateKey();
1299 return "Update '{$key}' already logged as completed.";
1303 * Message to show the the update log was unable to log the completion of this update
1304 * @return String
1306 protected function updatelogFailedMessage() {
1307 $key = $this->getUpdateKey();
1308 return "Unable to log update '{$key}' as completed.";
1312 * Do the actual work. All child classes will need to implement this.
1313 * Return true to log the update as done or false (usually on failure).
1314 * @return Bool
1316 abstract protected function doDBUpdates();
1319 * Get the update key name to go in the update log table
1320 * @return String
1322 abstract protected function getUpdateKey();