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