Merge "Fix how QUnit.newMwEnvironment merges live and custom settings"
[lhc/web/wiklou.git] / maintenance / Maintenance.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
21 */
22
23 if( PHP_SAPI != 'cli' ) {
24 die( "Run me from the command line please.\n" );
25 }
26
27 // Make sure we're on PHP5.3.2 or better
28 if ( !function_exists( 'version_compare' ) || version_compare( PHP_VERSION, '5.3.2' ) < 0 ) {
29 // We need to use dirname( __FILE__ ) here cause __DIR__ is PHP5.3+
30 require_once( dirname( __FILE__ ) . '/../includes/PHPVersionError.php' );
31 wfPHPVersionError( 'cli' );
32 }
33
34 /**
35 * @defgroup MaintenanceArchive Maintenance archives
36 * @ingroup Maintenance
37 */
38
39 // Define this so scripts can easily find doMaintenance.php
40 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' );
41 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
42
43 $maintClass = false;
44
45 /**
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.
50 *
51 * @author Chad Horohoe <chad@anyonecanedit.org>
52 * @since 1.16
53 * @ingroup Maintenance
54 */
55 abstract class Maintenance {
56
57 /**
58 * Constants for DB access type
59 * @see Maintenance::getDbType()
60 */
61 const DB_NONE = 0;
62 const DB_STD = 1;
63 const DB_ADMIN = 2;
64
65 // Const for getStdin()
66 const STDIN_ALL = 'all';
67
68 // This is the desired params
69 protected $mParams = array();
70
71 // Array of mapping short parameters to long ones
72 protected $mShortParamsMap = array();
73
74 // Array of desired args
75 protected $mArgList = array();
76
77 // This is the list of options that were actually passed
78 protected $mOptions = array();
79
80 // This is the list of arguments that were actually passed
81 protected $mArgs = array();
82
83 // Name of the script currently running
84 protected $mSelf;
85
86 // Special vars for params that are always used
87 protected $mQuiet = false;
88 protected $mDbUser, $mDbPass;
89
90 // A description of the script, children should change this
91 protected $mDescription = '';
92
93 // Have we already loaded our user input?
94 protected $mInputLoaded = false;
95
96 /**
97 * Batch size. If a script supports this, they should set
98 * a default with setBatchSize()
99 *
100 * @var int
101 */
102 protected $mBatchSize = null;
103
104 // Generic options added by addDefaultParams()
105 private $mGenericParameters = array();
106 // Generic options which might or not be supported by the script
107 private $mDependantParameters = array();
108
109 /**
110 * Used by getDD() / setDB()
111 * @var DatabaseBase
112 */
113 private $mDb = null;
114
115 /**
116 * Used when creating separate schema files.
117 * @var resource
118 */
119 public $fileHandle;
120
121 /**
122 * List of all the core maintenance scripts. This is added
123 * to scripts added by extensions in $wgMaintenanceScripts
124 * and returned by getMaintenanceScripts()
125 */
126 protected static $mCoreScripts = null;
127
128 /**
129 * Default constructor. Children should call this *first* if implementing
130 * their own constructors
131 */
132 public function __construct() {
133 // Setup $IP, using MW_INSTALL_PATH if it exists
134 global $IP;
135 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
136 ? getenv( 'MW_INSTALL_PATH' )
137 : realpath( __DIR__ . '/..' );
138
139 $this->addDefaultParams();
140 register_shutdown_function( array( $this, 'outputChanneled' ), false );
141 }
142
143 /**
144 * Should we execute the maintenance script, or just allow it to be included
145 * as a standalone class? It checks that the call stack only includes this
146 * function and "requires" (meaning was called from the file scope)
147 *
148 * @return Boolean
149 */
150 public static function shouldExecute() {
151 $bt = debug_backtrace();
152 $count = count( $bt );
153 if ( $count < 2 ) {
154 return false; // sanity
155 }
156 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
157 return false; // last call should be to this function
158 }
159 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
160 for( $i=1; $i < $count; $i++ ) {
161 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
162 return false; // previous calls should all be "requires"
163 }
164 }
165 return true;
166 }
167
168 /**
169 * Do the actual work. All child classes will need to implement this
170 */
171 abstract public function execute();
172
173 /**
174 * Add a parameter to the script. Will be displayed on --help
175 * with the associated description
176 *
177 * @param $name String: the name of the param (help, version, etc)
178 * @param $description String: the description of the param to show on --help
179 * @param $required Boolean: is the param required?
180 * @param $withArg Boolean: is an argument required with this option?
181 * @param $shortName String: character to use as short name
182 */
183 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
184 $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
185 if ( $shortName !== false ) {
186 $this->mShortParamsMap[$shortName] = $name;
187 }
188 }
189
190 /**
191 * Checks to see if a particular param exists.
192 * @param $name String: the name of the param
193 * @return Boolean
194 */
195 protected function hasOption( $name ) {
196 return isset( $this->mOptions[$name] );
197 }
198
199 /**
200 * Get an option, or return the default
201 * @param $name String: the name of the param
202 * @param $default Mixed: anything you want, default null
203 * @return Mixed
204 */
205 protected function getOption( $name, $default = null ) {
206 if ( $this->hasOption( $name ) ) {
207 return $this->mOptions[$name];
208 } else {
209 // Set it so we don't have to provide the default again
210 $this->mOptions[$name] = $default;
211 return $this->mOptions[$name];
212 }
213 }
214
215 /**
216 * Add some args that are needed
217 * @param $arg String: name of the arg, like 'start'
218 * @param $description String: short description of the arg
219 * @param $required Boolean: is this required?
220 */
221 protected function addArg( $arg, $description, $required = true ) {
222 $this->mArgList[] = array(
223 'name' => $arg,
224 'desc' => $description,
225 'require' => $required
226 );
227 }
228
229 /**
230 * Remove an option. Useful for removing options that won't be used in your script.
231 * @param $name String: the option to remove.
232 */
233 protected function deleteOption( $name ) {
234 unset( $this->mParams[$name] );
235 }
236
237 /**
238 * Set the description text.
239 * @param $text String: the text of the description
240 */
241 protected function addDescription( $text ) {
242 $this->mDescription = $text;
243 }
244
245 /**
246 * Does a given argument exist?
247 * @param $argId Integer: the integer value (from zero) for the arg
248 * @return Boolean
249 */
250 protected function hasArg( $argId = 0 ) {
251 return isset( $this->mArgs[$argId] );
252 }
253
254 /**
255 * Get an argument.
256 * @param $argId Integer: the integer value (from zero) for the arg
257 * @param $default Mixed: the default if it doesn't exist
258 * @return mixed
259 */
260 protected function getArg( $argId = 0, $default = null ) {
261 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
262 }
263
264 /**
265 * Set the batch size.
266 * @param $s Integer: the number of operations to do in a batch
267 */
268 protected function setBatchSize( $s = 0 ) {
269 $this->mBatchSize = $s;
270
271 // If we support $mBatchSize, show the option.
272 // Used to be in addDefaultParams, but in order for that to
273 // work, subclasses would have to call this function in the constructor
274 // before they called parent::__construct which is just weird
275 // (and really wasn't done).
276 if ( $this->mBatchSize ) {
277 $this->addOption( 'batch-size', 'Run this many operations ' .
278 'per batch, default: ' . $this->mBatchSize, false, true );
279 if ( isset( $this->mParams['batch-size'] ) ) {
280 // This seems a little ugly...
281 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
282 }
283 }
284 }
285
286 /**
287 * Get the script's name
288 * @return String
289 */
290 public function getName() {
291 return $this->mSelf;
292 }
293
294 /**
295 * Return input from stdin.
296 * @param $len Integer: the number of bytes to read. If null,
297 * just return the handle. Maintenance::STDIN_ALL returns
298 * the full length
299 * @return Mixed
300 */
301 protected function getStdin( $len = null ) {
302 if ( $len == Maintenance::STDIN_ALL ) {
303 return file_get_contents( 'php://stdin' );
304 }
305 $f = fopen( 'php://stdin', 'rt' );
306 if ( !$len ) {
307 return $f;
308 }
309 $input = fgets( $f, $len );
310 fclose( $f );
311 return rtrim( $input );
312 }
313
314 /**
315 * @return bool
316 */
317 public function isQuiet() {
318 return $this->mQuiet;
319 }
320
321 /**
322 * Throw some output to the user. Scripts can call this with no fears,
323 * as we handle all --quiet stuff here
324 * @param $out String: the text to show to the user
325 * @param $channel Mixed: unique identifier for the channel. See
326 * function outputChanneled.
327 */
328 protected function output( $out, $channel = null ) {
329 if ( $this->mQuiet ) {
330 return;
331 }
332 if ( $channel === null ) {
333 $this->cleanupChanneled();
334 print( $out );
335 } else {
336 $out = preg_replace( '/\n\z/', '', $out );
337 $this->outputChanneled( $out, $channel );
338 }
339 }
340
341 /**
342 * Throw an error to the user. Doesn't respect --quiet, so don't use
343 * this for non-error output
344 * @param $err String: the error to display
345 * @param $die Int: if > 0, go ahead and die out using this int as the code
346 */
347 protected function error( $err, $die = 0 ) {
348 $this->outputChanneled( false );
349 if ( PHP_SAPI == 'cli' ) {
350 fwrite( STDERR, $err . "\n" );
351 } else {
352 print $err;
353 }
354 $die = intval( $die );
355 if ( $die > 0 ) {
356 die( $die );
357 }
358 }
359
360 private $atLineStart = true;
361 private $lastChannel = null;
362
363 /**
364 * Clean up channeled output. Output a newline if necessary.
365 */
366 public function cleanupChanneled() {
367 if ( !$this->atLineStart ) {
368 print "\n";
369 $this->atLineStart = true;
370 }
371 }
372
373 /**
374 * Message outputter with channeled message support. Messages on the
375 * same channel are concatenated, but any intervening messages in another
376 * channel start a new line.
377 * @param $msg String: the message without trailing newline
378 * @param $channel string Channel identifier or null for no
379 * channel. Channel comparison uses ===.
380 */
381 public function outputChanneled( $msg, $channel = null ) {
382 if ( $msg === false ) {
383 $this->cleanupChanneled();
384 return;
385 }
386
387 // End the current line if necessary
388 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
389 print "\n";
390 }
391
392 print $msg;
393
394 $this->atLineStart = false;
395 if ( $channel === null ) {
396 // For unchanneled messages, output trailing newline immediately
397 print "\n";
398 $this->atLineStart = true;
399 }
400 $this->lastChannel = $channel;
401 }
402
403 /**
404 * Does the script need different DB access? By default, we give Maintenance
405 * scripts normal rights to the DB. Sometimes, a script needs admin rights
406 * access for a reason and sometimes they want no access. Subclasses should
407 * override and return one of the following values, as needed:
408 * Maintenance::DB_NONE - For no DB access at all
409 * Maintenance::DB_STD - For normal DB access, default
410 * Maintenance::DB_ADMIN - For admin DB access
411 * @return Integer
412 */
413 public function getDbType() {
414 return Maintenance::DB_STD;
415 }
416
417 /**
418 * Add the default parameters to the scripts
419 */
420 protected function addDefaultParams() {
421
422 # Generic (non script dependant) options:
423
424 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
425 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
426 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
427 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
428 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
429 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
430 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
431 "http://en.wikipedia.org. This is sometimes necessary because " .
432 "server name detection may fail in command line scripts.", false, true );
433
434 # Save generic options to display them separately in help
435 $this->mGenericParameters = $this->mParams ;
436
437 # Script dependant options:
438
439 // If we support a DB, show the options
440 if ( $this->getDbType() > 0 ) {
441 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
442 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
443 }
444
445 # Save additional script dependant options to display
446 # them separately in help
447 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
448 }
449
450 /**
451 * Run a child maintenance script. Pass all of the current arguments
452 * to it.
453 * @param $maintClass String: a name of a child maintenance class
454 * @param $classFile String: full path of where the child is
455 * @return Maintenance child
456 */
457 public function runChild( $maintClass, $classFile = null ) {
458 // Make sure the class is loaded first
459 if ( !MWInit::classExists( $maintClass ) ) {
460 if ( $classFile ) {
461 require_once( $classFile );
462 }
463 if ( !MWInit::classExists( $maintClass ) ) {
464 $this->error( "Cannot spawn child: $maintClass" );
465 }
466 }
467
468 /**
469 * @var $child Maintenance
470 */
471 $child = new $maintClass();
472 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
473 if ( !is_null( $this->mDb ) ) {
474 $child->setDB( $this->mDb );
475 }
476 return $child;
477 }
478
479 /**
480 * Do some sanity checking and basic setup
481 */
482 public function setup() {
483 global $wgCommandLineMode, $wgRequestTime;
484
485 # Abort if called from a web server
486 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
487 $this->error( 'This script must be run from the command line', true );
488 }
489
490 # Make sure we can handle script parameters
491 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
492 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
493 }
494
495 // Send PHP warnings and errors to stderr instead of stdout.
496 // This aids in diagnosing problems, while keeping messages
497 // out of redirected output.
498 if ( ini_get( 'display_errors' ) ) {
499 ini_set( 'display_errors', 'stderr' );
500 }
501
502 $this->loadParamsAndArgs();
503 $this->maybeHelp();
504
505 # Set the memory limit
506 # Note we need to set it again later in cache LocalSettings changed it
507 $this->adjustMemoryLimit();
508
509 # Set max execution time to 0 (no limit). PHP.net says that
510 # "When running PHP from the command line the default setting is 0."
511 # But sometimes this doesn't seem to be the case.
512 ini_set( 'max_execution_time', 0 );
513
514 $wgRequestTime = microtime( true );
515
516 # Define us as being in MediaWiki
517 define( 'MEDIAWIKI', true );
518
519 $wgCommandLineMode = true;
520 # Turn off output buffering if it's on
521 @ob_end_flush();
522
523 $this->validateParamsAndArgs();
524 }
525
526 /**
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
534 */
535 public function memoryLimit() {
536 $limit = $this->getOption( 'memory-limit', 'max' );
537 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
538 return $limit;
539 }
540
541 /**
542 * Adjusts PHP's memory limit to better suit our needs, if needed.
543 */
544 protected function adjustMemoryLimit() {
545 $limit = $this->memoryLimit();
546 if ( $limit == 'max' ) {
547 $limit = -1; // no memory limit
548 }
549 if ( $limit != 'default' ) {
550 ini_set( 'memory_limit', $limit );
551 }
552 }
553
554 /**
555 * Clear all params and arguments.
556 */
557 public function clearParamsAndArgs() {
558 $this->mOptions = array();
559 $this->mArgs = array();
560 $this->mInputLoaded = false;
561 }
562
563 /**
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
567 *
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
571 */
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;
577 }
578 if ( $opts ) {
579 $this->mOptions = $opts;
580 $this->mInputLoaded = true;
581 }
582 if ( $args ) {
583 $this->mArgs = $args;
584 $this->mInputLoaded = true;
585 }
586
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;
593 }
594
595 global $argv;
596 $this->mSelf = array_shift( $argv );
597
598 $options = array();
599 $args = array();
600
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 );
609 }
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 );
617 }
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 );
623 }
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;
632 }
633 $options[$option] = $param;
634 }
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];
641 }
642 if ( array_key_exists( $option, $options ) ) {
643 $this->error( "\nERROR: $option parameter given twice\n" );
644 $this->maybeHelp( true );
645 }
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 );
651 }
652 $options[$option] = $param;
653 } else {
654 $options[$option] = 1;
655 }
656 }
657 } else {
658 $args[] = $arg;
659 }
660 }
661
662 $this->mOptions = $options;
663 $this->mArgs = $args;
664 $this->loadSpecialVars();
665 $this->mInputLoaded = true;
666 }
667
668 /**
669 * Run some validation checks on the params, etc
670 */
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;
678 }
679 }
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;
685 }
686 }
687
688 if ( $die ) {
689 $this->maybeHelp( true );
690 }
691 }
692
693 /**
694 * Handle the special variables that are global to all scripts
695 */
696 protected function loadSpecialVars() {
697 if ( $this->hasOption( 'dbuser' ) ) {
698 $this->mDbUser = $this->getOption( 'dbuser' );
699 }
700 if ( $this->hasOption( 'dbpass' ) ) {
701 $this->mDbPass = $this->getOption( 'dbpass' );
702 }
703 if ( $this->hasOption( 'quiet' ) ) {
704 $this->mQuiet = true;
705 }
706 if ( $this->hasOption( 'batch-size' ) ) {
707 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
708 }
709 }
710
711 /**
712 * Maybe show the help.
713 * @param $force boolean Whether to force the help to show, default false
714 */
715 protected function maybeHelp( $force = false ) {
716 if( !$force && !$this->hasOption( 'help' ) ) {
717 return;
718 }
719
720 $screenWidth = 80; // TODO: Caculate this!
721 $tab = " ";
722 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
723
724 ksort( $this->mParams );
725 $this->mQuiet = false;
726
727 // Description ...
728 if ( $this->mDescription ) {
729 $this->output( "\n" . $this->mDescription . "\n" );
730 }
731 $output = "\nUsage: php " . basename( $this->mSelf );
732
733 // ... append parameters ...
734 if ( $this->mParams ) {
735 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
736 }
737
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'] . ']';
746 }
747 if ( $k < count( $this->mArgList ) - 1 )
748 $output .= ' ';
749 }
750 }
751 $this->output( "$output\n\n" );
752
753 # TODO abstract some repetitive code below
754
755 // Generic parameters
756 $this->output( "Generic maintenance parameters:\n" );
757 foreach ( $this->mGenericParameters as $par => $info ) {
758 if ( $info['shortName'] !== false ) {
759 $par .= " (-{$info['shortName']})";
760 }
761 $this->output(
762 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
763 "\n$tab$tab" ) . "\n"
764 );
765 }
766 $this->output( "\n" );
767
768 $scriptDependantParams = $this->mDependantParameters;
769 if( count($scriptDependantParams) > 0 ) {
770 $this->output( "Script dependant parameters:\n" );
771 // Parameters description
772 foreach ( $scriptDependantParams as $par => $info ) {
773 if ( $info['shortName'] !== false ) {
774 $par .= " (-{$info['shortName']})";
775 }
776 $this->output(
777 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
778 "\n$tab$tab" ) . "\n"
779 );
780 }
781 $this->output( "\n" );
782 }
783
784
785 // Script specific parameters not defined on construction by
786 // Maintenance::addDefaultParams()
787 $scriptSpecificParams = array_diff_key(
788 # all script parameters:
789 $this->mParams,
790 # remove the Maintenance default parameters:
791 $this->mGenericParameters,
792 $this->mDependantParameters
793 );
794 if( count($scriptSpecificParams) > 0 ) {
795 $this->output( "Script specific parameters:\n" );
796 // Parameters description
797 foreach ( $scriptSpecificParams as $par => $info ) {
798 if ( $info['shortName'] !== false ) {
799 $par .= " (-{$info['shortName']})";
800 }
801 $this->output(
802 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
803 "\n$tab$tab" ) . "\n"
804 );
805 }
806 $this->output( "\n" );
807 }
808
809 // Print arguments
810 if( count( $this->mArgList ) > 0 ) {
811 $this->output( "Arguments:\n" );
812 // Arguments description
813 foreach ( $this->mArgList as $info ) {
814 $openChar = $info['require'] ? '<' : '[';
815 $closeChar = $info['require'] ? '>' : ']';
816 $this->output(
817 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
818 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
819 );
820 }
821 $this->output( "\n" );
822 }
823
824 die( 1 );
825 }
826
827 /**
828 * Handle some last-minute setup here.
829 */
830 public function finalSetup() {
831 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
832 global $wgDBadminuser, $wgDBadminpassword;
833 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
834
835 # Turn off output buffering again, it might have been turned on in the settings files
836 if ( ob_get_level() ) {
837 ob_end_flush();
838 }
839 # Same with these
840 $wgCommandLineMode = true;
841
842 # Override $wgServer
843 if( $this->hasOption( 'server') ) {
844 $wgServer = $this->getOption( 'server', $wgServer );
845 }
846
847 # If these were passed, use them
848 if ( $this->mDbUser ) {
849 $wgDBadminuser = $this->mDbUser;
850 }
851 if ( $this->mDbPass ) {
852 $wgDBadminpassword = $this->mDbPass;
853 }
854
855 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
856 $wgDBuser = $wgDBadminuser;
857 $wgDBpassword = $wgDBadminpassword;
858
859 if ( $wgDBservers ) {
860 /**
861 * @var $wgDBservers array
862 */
863 foreach ( $wgDBservers as $i => $server ) {
864 $wgDBservers[$i]['user'] = $wgDBuser;
865 $wgDBservers[$i]['password'] = $wgDBpassword;
866 }
867 }
868 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
869 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
870 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
871 }
872 LBFactory::destroyInstance();
873 }
874
875 $this->afterFinalSetup();
876
877 $wgShowSQLErrors = true;
878 @set_time_limit( 0 );
879 $this->adjustMemoryLimit();
880 }
881
882 /**
883 * Execute a callback function at the end of initialisation
884 */
885 protected function afterFinalSetup() {
886 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
887 call_user_func( MW_CMDLINE_CALLBACK );
888 }
889 }
890
891 /**
892 * Potentially debug globals. Originally a feature only
893 * for refreshLinks
894 */
895 public function globals() {
896 if ( $this->hasOption( 'globals' ) ) {
897 print_r( $GLOBALS );
898 }
899 }
900
901 /**
902 * Generic setup for most installs. Returns the location of LocalSettings
903 * @return String
904 */
905 public function loadSettings() {
906 global $wgCommandLineMode, $IP;
907
908 if ( isset( $this->mOptions['conf'] ) ) {
909 $settingsFile = $this->mOptions['conf'];
910 } elseif ( defined("MW_CONFIG_FILE") ) {
911 $settingsFile = MW_CONFIG_FILE;
912 } else {
913 $settingsFile = "$IP/LocalSettings.php";
914 }
915 if ( isset( $this->mOptions['wiki'] ) ) {
916 $bits = explode( '-', $this->mOptions['wiki'] );
917 if ( count( $bits ) == 1 ) {
918 $bits[] = '';
919 }
920 define( 'MW_DB', $bits[0] );
921 define( 'MW_PREFIX', $bits[1] );
922 }
923
924 if ( !is_readable( $settingsFile ) ) {
925 $this->error( "A copy of your installation's LocalSettings.php\n" .
926 "must exist and be readable in the source directory.\n" .
927 "Use --conf to specify it.", true );
928 }
929 $wgCommandLineMode = true;
930 return $settingsFile;
931 }
932
933 /**
934 * Support function for cleaning up redundant text records
935 * @param $delete Boolean: whether or not to actually delete the records
936 * @author Rob Church <robchur@gmail.com>
937 */
938 public function purgeRedundantText( $delete = true ) {
939 # Data should come off the master, wrapped in a transaction
940 $dbw = $this->getDB( DB_MASTER );
941 $dbw->begin( __METHOD__ );
942
943 # Get "active" text records from the revisions table
944 $this->output( 'Searching for active text records in revisions table...' );
945 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
946 foreach ( $res as $row ) {
947 $cur[] = $row->rev_text_id;
948 }
949 $this->output( "done.\n" );
950
951 # Get "active" text records from the archive table
952 $this->output( 'Searching for active text records in archive table...' );
953 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
954 foreach ( $res as $row ) {
955 # old pre-MW 1.5 records can have null ar_text_id's.
956 if ( $row->ar_text_id !== null ) {
957 $cur[] = $row->ar_text_id;
958 }
959 }
960 $this->output( "done.\n" );
961
962 # Get the IDs of all text records not in these sets
963 $this->output( 'Searching for inactive text records...' );
964 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
965 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__, array( 'DISTINCT' ) );
966 $old = array();
967 foreach ( $res as $row ) {
968 $old[] = $row->old_id;
969 }
970 $this->output( "done.\n" );
971
972 # Inform the user of what we're going to do
973 $count = count( $old );
974 $this->output( "$count inactive items found.\n" );
975
976 # Delete as appropriate
977 if ( $delete && $count ) {
978 $this->output( 'Deleting...' );
979 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__ );
980 $this->output( "done.\n" );
981 }
982
983 # Done
984 $dbw->commit( __METHOD__ );
985 }
986
987 /**
988 * Get the maintenance directory.
989 * @return string
990 */
991 protected function getDir() {
992 return __DIR__;
993 }
994
995 /**
996 * Get the list of available maintenance scripts. Note
997 * that if you call this _before_ calling doMaintenance
998 * you won't have any extensions in it yet
999 * @return Array
1000 */
1001 public static function getMaintenanceScripts() {
1002 global $wgMaintenanceScripts;
1003 return $wgMaintenanceScripts + self::getCoreScripts();
1004 }
1005
1006 /**
1007 * Return all of the core maintenance scripts
1008 * @return array
1009 */
1010 protected static function getCoreScripts() {
1011 if ( !self::$mCoreScripts ) {
1012 $paths = array(
1013 __DIR__,
1014 __DIR__ . '/language',
1015 __DIR__ . '/storage',
1016 );
1017 self::$mCoreScripts = array();
1018 foreach ( $paths as $p ) {
1019 $handle = opendir( $p );
1020 while ( ( $file = readdir( $handle ) ) !== false ) {
1021 if ( $file == 'Maintenance.php' ) {
1022 continue;
1023 }
1024 $file = $p . '/' . $file;
1025 if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
1026 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1027 continue;
1028 }
1029 require( $file );
1030 $vars = get_defined_vars();
1031 if ( array_key_exists( 'maintClass', $vars ) ) {
1032 self::$mCoreScripts[$vars['maintClass']] = $file;
1033 }
1034 }
1035 closedir( $handle );
1036 }
1037 }
1038 return self::$mCoreScripts;
1039 }
1040
1041 /**
1042 * Returns a database to be used by current maintenance script. It can be set by setDB().
1043 * If not set, wfGetDB() will be used.
1044 * This function has the same parameters as wfGetDB()
1045 *
1046 * @return DatabaseBase
1047 */
1048 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1049 if ( is_null( $this->mDb ) ) {
1050 return wfGetDB( $db, $groups, $wiki );
1051 } else {
1052 return $this->mDb;
1053 }
1054 }
1055
1056 /**
1057 * Sets database object to be returned by getDB().
1058 *
1059 * @param $db DatabaseBase: Database object to be used
1060 */
1061 public function setDB( &$db ) {
1062 $this->mDb = $db;
1063 }
1064
1065 /**
1066 * Lock the search index
1067 * @param &$db DatabaseBase object
1068 */
1069 private function lockSearchindex( &$db ) {
1070 $write = array( 'searchindex' );
1071 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1072 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1073 }
1074
1075 /**
1076 * Unlock the tables
1077 * @param &$db DatabaseBase object
1078 */
1079 private function unlockSearchindex( &$db ) {
1080 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1081 }
1082
1083 /**
1084 * Unlock and lock again
1085 * Since the lock is low-priority, queued reads will be able to complete
1086 * @param &$db DatabaseBase object
1087 */
1088 private function relockSearchindex( &$db ) {
1089 $this->unlockSearchindex( $db );
1090 $this->lockSearchindex( $db );
1091 }
1092
1093 /**
1094 * Perform a search index update with locking
1095 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1096 * @param $callback callback String: the function that will update the function.
1097 * @param $dbw DatabaseBase object
1098 * @param $results
1099 */
1100 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1101 $lockTime = time();
1102
1103 # Lock searchindex
1104 if ( $maxLockTime ) {
1105 $this->output( " --- Waiting for lock ---" );
1106 $this->lockSearchindex( $dbw );
1107 $lockTime = time();
1108 $this->output( "\n" );
1109 }
1110
1111 # Loop through the results and do a search update
1112 foreach ( $results as $row ) {
1113 # Allow reads to be processed
1114 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1115 $this->output( " --- Relocking ---" );
1116 $this->relockSearchindex( $dbw );
1117 $lockTime = time();
1118 $this->output( "\n" );
1119 }
1120 call_user_func( $callback, $dbw, $row );
1121 }
1122
1123 # Unlock searchindex
1124 if ( $maxLockTime ) {
1125 $this->output( " --- Unlocking --" );
1126 $this->unlockSearchindex( $dbw );
1127 $this->output( "\n" );
1128 }
1129
1130 }
1131
1132 /**
1133 * Update the searchindex table for a given pageid
1134 * @param $dbw DatabaseBase a database write handle
1135 * @param $pageId Integer: the page ID to update.
1136 * @return null|string
1137 */
1138 public function updateSearchIndexForPage( $dbw, $pageId ) {
1139 // Get current revision
1140 $rev = Revision::loadFromPageId( $dbw, $pageId );
1141 $title = null;
1142 if ( $rev ) {
1143 $titleObj = $rev->getTitle();
1144 $title = $titleObj->getPrefixedDBkey();
1145 $this->output( "$title..." );
1146 # Update searchindex
1147 # TODO: pass the Content object to SearchUpdate, let the search engine decide how to deal with it.
1148 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent()->getTextForSearchIndex() );
1149 $u->doUpdate();
1150 $this->output( "\n" );
1151 }
1152 return $title;
1153 }
1154
1155 /**
1156 * Wrapper for posix_isatty()
1157 * We default as considering stdin a tty (for nice readline methods)
1158 * but treating stout as not a tty to avoid color codes
1159 *
1160 * @param $fd int File descriptor
1161 * @return bool
1162 */
1163 public static function posix_isatty( $fd ) {
1164 if ( !MWInit::functionExists( 'posix_isatty' ) ) {
1165 return !$fd;
1166 } else {
1167 return posix_isatty( $fd );
1168 }
1169 }
1170
1171 /**
1172 * Prompt the console for input
1173 * @param $prompt String what to begin the line with, like '> '
1174 * @return String response
1175 */
1176 public static function readconsole( $prompt = '> ' ) {
1177 static $isatty = null;
1178 if ( is_null( $isatty ) ) {
1179 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1180 }
1181
1182 if ( $isatty && function_exists( 'readline' ) ) {
1183 return readline( $prompt );
1184 } else {
1185 if ( $isatty ) {
1186 $st = self::readlineEmulation( $prompt );
1187 } else {
1188 if ( feof( STDIN ) ) {
1189 $st = false;
1190 } else {
1191 $st = fgets( STDIN, 1024 );
1192 }
1193 }
1194 if ( $st === false ) return false;
1195 $resp = trim( $st );
1196 return $resp;
1197 }
1198 }
1199
1200 /**
1201 * Emulate readline()
1202 * @param $prompt String what to begin the line with, like '> '
1203 * @return String
1204 */
1205 private static function readlineEmulation( $prompt ) {
1206 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1207 if ( !wfIsWindows() && $bash ) {
1208 $retval = false;
1209 $encPrompt = wfEscapeShellArg( $prompt );
1210 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1211 $encCommand = wfEscapeShellArg( $command );
1212 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1213
1214 if ( $retval == 0 ) {
1215 return $line;
1216 } elseif ( $retval == 127 ) {
1217 // Couldn't execute bash even though we thought we saw it.
1218 // Shell probably spit out an error message, sorry :(
1219 // Fall through to fgets()...
1220 } else {
1221 // EOF/ctrl+D
1222 return false;
1223 }
1224 }
1225
1226 // Fallback... we'll have no editing controls, EWWW
1227 if ( feof( STDIN ) ) {
1228 return false;
1229 }
1230 print $prompt;
1231 return fgets( STDIN, 1024 );
1232 }
1233 }
1234
1235 /**
1236 * Fake maintenance wrapper, mostly used for the web installer/updater
1237 */
1238 class FakeMaintenance extends Maintenance {
1239 protected $mSelf = "FakeMaintenanceScript";
1240 public function execute() {
1241 return;
1242 }
1243 }
1244
1245 /**
1246 * Class for scripts that perform database maintenance and want to log the
1247 * update in `updatelog` so we can later skip it
1248 */
1249 abstract class LoggedUpdateMaintenance extends Maintenance {
1250 public function __construct() {
1251 parent::__construct();
1252 $this->addOption( 'force', 'Run the update even if it was completed already' );
1253 $this->setBatchSize( 200 );
1254 }
1255
1256 public function execute() {
1257 $db = $this->getDB( DB_MASTER );
1258 $key = $this->getUpdateKey();
1259
1260 if ( !$this->hasOption( 'force' ) &&
1261 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ ) )
1262 {
1263 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1264 return true;
1265 }
1266
1267 if ( !$this->doDBUpdates() ) {
1268 return false;
1269 }
1270
1271 if (
1272 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) )
1273 {
1274 return true;
1275 } else {
1276 $this->output( $this->updatelogFailedMessage() . "\n" );
1277 return false;
1278 }
1279 }
1280
1281 /**
1282 * Message to show that the update was done already and was just skipped
1283 * @return String
1284 */
1285 protected function updateSkippedMessage() {
1286 $key = $this->getUpdateKey();
1287 return "Update '{$key}' already logged as completed.";
1288 }
1289
1290 /**
1291 * Message to show the the update log was unable to log the completion of this update
1292 * @return String
1293 */
1294 protected function updatelogFailedMessage() {
1295 $key = $this->getUpdateKey();
1296 return "Unable to log update '{$key}' as completed.";
1297 }
1298
1299 /**
1300 * Do the actual work. All child classes will need to implement this.
1301 * Return true to log the update as done or false (usually on failure).
1302 * @return Bool
1303 */
1304 abstract protected function doDBUpdates();
1305
1306 /**
1307 * Get the update key name to go in the update log table
1308 * @return String
1309 */
1310 abstract protected function getUpdateKey();
1311 }