Move the check for if a Maintenance script supports --batch-size away from addDefault...
[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
313 $f = fopen( 'php://stdout', 'w' );
314 fwrite( $f, $out );
315 fclose( $f );
316 }
317 else {
318 $out = preg_replace( '/\n\z/', '', $out );
319 $this->outputChanneled( $out, $channel );
320 }
321 }
322
323 /**
324 * Throw an error to the user. Doesn't respect --quiet, so don't use
325 * this for non-error output
326 * @param $err String: the error to display
327 * @param $die Int: if > 0, go ahead and die out using this int as the code
328 */
329 protected function error( $err, $die = 0 ) {
330 $this->outputChanneled( false );
331 if ( php_sapi_name() == 'cli' ) {
332 fwrite( STDERR, $err . "\n" );
333 } else {
334 $f = fopen( 'php://stderr', 'w' );
335 fwrite( $f, $err . "\n" );
336 fclose( $f );
337 }
338 $die = intval( $die );
339 if ( $die > 0 ) {
340 die( $die );
341 }
342 }
343
344 private $atLineStart = true;
345 private $lastChannel = null;
346
347 /**
348 * Clean up channeled output. Output a newline if necessary.
349 */
350 public function cleanupChanneled() {
351 if ( !$this->atLineStart ) {
352 $handle = fopen( 'php://stdout', 'w' );
353 fwrite( $handle, "\n" );
354 fclose( $handle );
355 $this->atLineStart = true;
356 }
357 }
358
359 /**
360 * Message outputter with channeled message support. Messages on the
361 * same channel are concatenated, but any intervening messages in another
362 * channel start a new line.
363 * @param $msg String: the message without trailing newline
364 * @param $channel Channel identifier or null for no
365 * channel. Channel comparison uses ===.
366 */
367 public function outputChanneled( $msg, $channel = null ) {
368 if ( $msg === false ) {
369 $this->cleanupChanneled();
370 return;
371 }
372
373 $handle = fopen( 'php://stdout', 'w' );
374
375 // End the current line if necessary
376 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
377 fwrite( $handle, "\n" );
378 }
379
380 fwrite( $handle, $msg );
381
382 $this->atLineStart = false;
383 if ( $channel === null ) {
384 // For unchanneled messages, output trailing newline immediately
385 fwrite( $handle, "\n" );
386 $this->atLineStart = true;
387 }
388 $this->lastChannel = $channel;
389
390 // Cleanup handle
391 fclose( $handle );
392 }
393
394 /**
395 * Does the script need different DB access? By default, we give Maintenance
396 * scripts normal rights to the DB. Sometimes, a script needs admin rights
397 * access for a reason and sometimes they want no access. Subclasses should
398 * override and return one of the following values, as needed:
399 * Maintenance::DB_NONE - For no DB access at all
400 * Maintenance::DB_STD - For normal DB access, default
401 * Maintenance::DB_ADMIN - For admin DB access
402 * @return Integer
403 */
404 public function getDbType() {
405 return Maintenance::DB_STD;
406 }
407
408 /**
409 * Add the default parameters to the scripts
410 */
411 protected function addDefaultParams() {
412
413 # Generic (non script dependant) options:
414
415 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
416 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
417 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
418 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
419 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
420 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
421 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
422 "http://en.wikipedia.org. This is sometimes necessary because " .
423 "server name detection may fail in command line scripts.", false, true );
424
425 # Save generic options to display them separately in help
426 $this->mGenericParameters = $this->mParams ;
427
428 # Script dependant options:
429
430 // If we support a DB, show the options
431 if ( $this->getDbType() > 0 ) {
432 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
433 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
434 }
435
436 # Save additional script dependant options to display
437 # them separately in help
438 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
439 }
440
441 /**
442 * Run a child maintenance script. Pass all of the current arguments
443 * to it.
444 * @param $maintClass String: a name of a child maintenance class
445 * @param $classFile String: full path of where the child is
446 * @return Maintenance child
447 */
448 public function runChild( $maintClass, $classFile = null ) {
449 // Make sure the class is loaded first
450 if ( !MWInit::classExists( $maintClass ) ) {
451 if ( $classFile ) {
452 require_once( $classFile );
453 }
454 if ( !MWInit::classExists( $maintClass ) ) {
455 $this->error( "Cannot spawn child: $maintClass" );
456 }
457 }
458
459 $child = new $maintClass();
460 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
461 if ( !is_null( $this->mDb ) ) {
462 $child->setDB( $this->mDb );
463 }
464 return $child;
465 }
466
467 /**
468 * Do some sanity checking and basic setup
469 */
470 public function setup() {
471 global $wgCommandLineMode, $wgRequestTime;
472
473 # Abort if called from a web server
474 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
475 $this->error( 'This script must be run from the command line', true );
476 }
477
478 # Make sure we can handle script parameters
479 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
480 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
481 }
482
483 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
484 // Send PHP warnings and errors to stderr instead of stdout.
485 // This aids in diagnosing problems, while keeping messages
486 // out of redirected output.
487 if ( ini_get( 'display_errors' ) ) {
488 ini_set( 'display_errors', 'stderr' );
489 }
490
491 // Don't touch the setting on earlier versions of PHP,
492 // as setting it would disable output if you'd wanted it.
493
494 // Note that exceptions are also sent to stderr when
495 // command-line mode is on, regardless of PHP version.
496 }
497
498 $this->loadParamsAndArgs();
499 $this->maybeHelp();
500
501 # Set the memory limit
502 # Note we need to set it again later in cache LocalSettings changed it
503 $this->adjustMemoryLimit();
504
505 # Set max execution time to 0 (no limit). PHP.net says that
506 # "When running PHP from the command line the default setting is 0."
507 # But sometimes this doesn't seem to be the case.
508 ini_set( 'max_execution_time', 0 );
509
510 $wgRequestTime = microtime( true );
511
512 # Define us as being in MediaWiki
513 define( 'MEDIAWIKI', true );
514
515 $wgCommandLineMode = true;
516 # Turn off output buffering if it's on
517 @ob_end_flush();
518
519 $this->validateParamsAndArgs();
520 }
521
522 /**
523 * Normally we disable the memory_limit when running admin scripts.
524 * Some scripts may wish to actually set a limit, however, to avoid
525 * blowing up unexpectedly. We also support a --memory-limit option,
526 * to allow sysadmins to explicitly set one if they'd prefer to override
527 * defaults (or for people using Suhosin which yells at you for trying
528 * to disable the limits)
529 */
530 public function memoryLimit() {
531 $limit = $this->getOption( 'memory-limit', 'max' );
532 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
533 return $limit;
534 }
535
536 /**
537 * Adjusts PHP's memory limit to better suit our needs, if needed.
538 */
539 protected function adjustMemoryLimit() {
540 $limit = $this->memoryLimit();
541 if ( $limit == 'max' ) {
542 $limit = -1; // no memory limit
543 }
544 if ( $limit != 'default' ) {
545 ini_set( 'memory_limit', $limit );
546 }
547 }
548
549 /**
550 * Clear all params and arguments.
551 */
552 public function clearParamsAndArgs() {
553 $this->mOptions = array();
554 $this->mArgs = array();
555 $this->mInputLoaded = false;
556 }
557
558 /**
559 * Process command line arguments
560 * $mOptions becomes an array with keys set to the option names
561 * $mArgs becomes a zero-based array containing the non-option arguments
562 *
563 * @param $self String The name of the script, if any
564 * @param $opts Array An array of options, in form of key=>value
565 * @param $args Array An array of command line arguments
566 */
567 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
568 # If we were given opts or args, set those and return early
569 if ( $self ) {
570 $this->mSelf = $self;
571 $this->mInputLoaded = true;
572 }
573 if ( $opts ) {
574 $this->mOptions = $opts;
575 $this->mInputLoaded = true;
576 }
577 if ( $args ) {
578 $this->mArgs = $args;
579 $this->mInputLoaded = true;
580 }
581
582 # If we've already loaded input (either by user values or from $argv)
583 # skip on loading it again. The array_shift() will corrupt values if
584 # it's run again and again
585 if ( $this->mInputLoaded ) {
586 $this->loadSpecialVars();
587 return;
588 }
589
590 global $argv;
591 $this->mSelf = array_shift( $argv );
592
593 $options = array();
594 $args = array();
595
596 # Parse arguments
597 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
598 if ( $arg == '--' ) {
599 # End of options, remainder should be considered arguments
600 $arg = next( $argv );
601 while ( $arg !== false ) {
602 $args[] = $arg;
603 $arg = next( $argv );
604 }
605 break;
606 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
607 # Long options
608 $option = substr( $arg, 2 );
609 if ( array_key_exists( $option, $options ) ) {
610 $this->error( "\nERROR: $option parameter given twice\n" );
611 $this->maybeHelp( true );
612 }
613 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
614 $param = next( $argv );
615 if ( $param === false ) {
616 $this->error( "\nERROR: $option parameter needs a value after it\n" );
617 $this->maybeHelp( true );
618 }
619 $options[$option] = $param;
620 } else {
621 $bits = explode( '=', $option, 2 );
622 if ( count( $bits ) > 1 ) {
623 $option = $bits[0];
624 $param = $bits[1];
625 } else {
626 $param = 1;
627 }
628 $options[$option] = $param;
629 }
630 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
631 # Short options
632 for ( $p = 1; $p < strlen( $arg ); $p++ ) {
633 $option = $arg { $p } ;
634 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
635 $option = $this->mShortParamsMap[$option];
636 }
637 if ( array_key_exists( $option, $options ) ) {
638 $this->error( "\nERROR: $option parameter given twice\n" );
639 $this->maybeHelp( true );
640 }
641 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
642 $param = next( $argv );
643 if ( $param === false ) {
644 $this->error( "\nERROR: $option parameter needs a value after it\n" );
645 $this->maybeHelp( true );
646 }
647 $options[$option] = $param;
648 } else {
649 $options[$option] = 1;
650 }
651 }
652 } else {
653 $args[] = $arg;
654 }
655 }
656
657 $this->mOptions = $options;
658 $this->mArgs = $args;
659 $this->loadSpecialVars();
660 $this->mInputLoaded = true;
661 }
662
663 /**
664 * Run some validation checks on the params, etc
665 */
666 protected function validateParamsAndArgs() {
667 $die = false;
668 # Check to make sure we've got all the required options
669 foreach ( $this->mParams as $opt => $info ) {
670 if ( $info['require'] && !$this->hasOption( $opt ) ) {
671 $this->error( "Param $opt required!" );
672 $die = true;
673 }
674 }
675 # Check arg list too
676 foreach ( $this->mArgList as $k => $info ) {
677 if ( $info['require'] && !$this->hasArg( $k ) ) {
678 $this->error( 'Argument <' . $info['name'] . '> required!' );
679 $die = true;
680 }
681 }
682
683 if ( $die ) {
684 $this->maybeHelp( true );
685 }
686 }
687
688 /**
689 * Handle the special variables that are global to all scripts
690 */
691 protected function loadSpecialVars() {
692 if ( $this->hasOption( 'dbuser' ) ) {
693 $this->mDbUser = $this->getOption( 'dbuser' );
694 }
695 if ( $this->hasOption( 'dbpass' ) ) {
696 $this->mDbPass = $this->getOption( 'dbpass' );
697 }
698 if ( $this->hasOption( 'quiet' ) ) {
699 $this->mQuiet = true;
700 }
701 if ( $this->hasOption( 'batch-size' ) ) {
702 $this->mBatchSize = $this->getOption( 'batch-size' );
703 }
704 }
705
706 /**
707 * Maybe show the help.
708 * @param $force boolean Whether to force the help to show, default false
709 */
710 protected function maybeHelp( $force = false ) {
711 if( !$force && !$this->hasOption( 'help' ) ) {
712 return;
713 }
714
715 $screenWidth = 80; // TODO: Caculate this!
716 $tab = " ";
717 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
718
719 ksort( $this->mParams );
720 $this->mQuiet = false;
721
722 // Description ...
723 if ( $this->mDescription ) {
724 $this->output( "\n" . $this->mDescription . "\n" );
725 }
726 $output = "\nUsage: php " . basename( $this->mSelf );
727
728 // ... append parameters ...
729 if ( $this->mParams ) {
730 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
731 }
732
733 // ... and append arguments.
734 if ( $this->mArgList ) {
735 $output .= ' ';
736 foreach ( $this->mArgList as $k => $arg ) {
737 if ( $arg['require'] ) {
738 $output .= '<' . $arg['name'] . '>';
739 } else {
740 $output .= '[' . $arg['name'] . ']';
741 }
742 if ( $k < count( $this->mArgList ) - 1 )
743 $output .= ' ';
744 }
745 }
746 $this->output( "$output\n\n" );
747
748 # TODO abstract some repetitive code below
749
750 // Generic parameters
751 $this->output( "Generic maintenance parameters:\n" );
752 foreach ( $this->mGenericParameters as $par => $info ) {
753 if ( $info['shortName'] !== false ) {
754 $par .= " (-{$info['shortName']})";
755 }
756 $this->output(
757 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
758 "\n$tab$tab" ) . "\n"
759 );
760 }
761 $this->output( "\n" );
762
763 $scriptDependantParams = $this->mDependantParameters;
764 if( count($scriptDependantParams) > 0 ) {
765 $this->output( "Script dependant parameters:\n" );
766 // Parameters description
767 foreach ( $scriptDependantParams as $par => $info ) {
768 if ( $info['shortName'] !== false ) {
769 $par .= " (-{$info['shortName']})";
770 }
771 $this->output(
772 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
773 "\n$tab$tab" ) . "\n"
774 );
775 }
776 $this->output( "\n" );
777 }
778
779
780 // Script specific parameters not defined on construction by
781 // Maintenance::addDefaultParams()
782 $scriptSpecificParams = array_diff_key(
783 # all script parameters:
784 $this->mParams,
785 # remove the Maintenance default parameters:
786 $this->mGenericParameters,
787 $this->mDependantParameters
788 );
789 if( count($scriptSpecificParams) > 0 ) {
790 $this->output( "Script specific parameters:\n" );
791 // Parameters description
792 foreach ( $scriptSpecificParams as $par => $info ) {
793 if ( $info['shortName'] !== false ) {
794 $par .= " (-{$info['shortName']})";
795 }
796 $this->output(
797 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
798 "\n$tab$tab" ) . "\n"
799 );
800 }
801 $this->output( "\n" );
802 }
803
804 // Print arguments
805 if( count( $this->mArgList ) > 0 ) {
806 $this->output( "Arguments:\n" );
807 // Arguments description
808 foreach ( $this->mArgList as $info ) {
809 $openChar = $info['require'] ? '<' : '[';
810 $closeChar = $info['require'] ? '>' : ']';
811 $this->output(
812 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
813 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
814 );
815 }
816 $this->output( "\n" );
817 }
818
819 die( 1 );
820 }
821
822 /**
823 * Handle some last-minute setup here.
824 */
825 public function finalSetup() {
826 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
827 global $wgDBadminuser, $wgDBadminpassword;
828 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
829
830 # Turn off output buffering again, it might have been turned on in the settings files
831 if ( ob_get_level() ) {
832 ob_end_flush();
833 }
834 # Same with these
835 $wgCommandLineMode = true;
836
837 # Override $wgServer
838 if( $this->hasOption( 'server') ) {
839 $wgServer = $this->getOption( 'server', $wgServer );
840 }
841
842 # If these were passed, use them
843 if ( $this->mDbUser ) {
844 $wgDBadminuser = $this->mDbUser;
845 }
846 if ( $this->mDbPass ) {
847 $wgDBadminpassword = $this->mDbPass;
848 }
849
850 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
851 $wgDBuser = $wgDBadminuser;
852 $wgDBpassword = $wgDBadminpassword;
853
854 if ( $wgDBservers ) {
855 foreach ( $wgDBservers as $i => $server ) {
856 $wgDBservers[$i]['user'] = $wgDBuser;
857 $wgDBservers[$i]['password'] = $wgDBpassword;
858 }
859 }
860 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
861 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
862 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
863 }
864 LBFactory::destroyInstance();
865 }
866
867 $this->afterFinalSetup();
868
869 $wgShowSQLErrors = true;
870 @set_time_limit( 0 );
871 $this->adjustMemoryLimit();
872 }
873
874 /**
875 * Execute a callback function at the end of initialisation
876 */
877 protected function afterFinalSetup() {
878 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
879 call_user_func( MW_CMDLINE_CALLBACK );
880 }
881 }
882
883 /**
884 * Potentially debug globals. Originally a feature only
885 * for refreshLinks
886 */
887 public function globals() {
888 if ( $this->hasOption( 'globals' ) ) {
889 print_r( $GLOBALS );
890 }
891 }
892
893 /**
894 * Do setup specific to WMF
895 */
896 public function loadWikimediaSettings() {
897 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
898
899 if ( empty( $wgNoDBParam ) ) {
900 # Check if we were passed a db name
901 if ( isset( $this->mOptions['wiki'] ) ) {
902 $db = $this->mOptions['wiki'];
903 } else {
904 $db = array_shift( $this->mArgs );
905 }
906 list( $site, $lang ) = $wgConf->siteFromDB( $db );
907
908 # If not, work out the language and site the old way
909 if ( is_null( $site ) || is_null( $lang ) ) {
910 if ( !$db ) {
911 $lang = 'aa';
912 } else {
913 $lang = $db;
914 }
915 if ( isset( $this->mArgs[0] ) ) {
916 $site = array_shift( $this->mArgs );
917 } else {
918 $site = 'wikipedia';
919 }
920 }
921 } else {
922 $lang = 'aa';
923 $site = 'wikipedia';
924 }
925
926 # This is for the IRC scripts, which now run as the apache user
927 # The apache user doesn't have access to the wikiadmin_pass command
928 if ( $_ENV['USER'] == 'apache' ) {
929 # if ( posix_geteuid() == 48 ) {
930 $wgUseNormalUser = true;
931 }
932
933 putenv( 'wikilang=' . $lang );
934
935 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
936
937 if ( $lang == 'test' && $site == 'wikipedia' ) {
938 if ( !defined( 'TESTWIKI' ) ) {
939 define( 'TESTWIKI', 1 );
940 }
941 }
942 }
943
944 /**
945 * Generic setup for most installs. Returns the location of LocalSettings
946 * @return String
947 */
948 public function loadSettings() {
949 global $wgCommandLineMode, $IP;
950
951 if ( isset( $this->mOptions['conf'] ) ) {
952 $settingsFile = $this->mOptions['conf'];
953 } elseif ( defined("MW_CONFIG_FILE") ) {
954 $settingsFile = MW_CONFIG_FILE;
955 } else {
956 $settingsFile = "$IP/LocalSettings.php";
957 }
958 if ( isset( $this->mOptions['wiki'] ) ) {
959 $bits = explode( '-', $this->mOptions['wiki'] );
960 if ( count( $bits ) == 1 ) {
961 $bits[] = '';
962 }
963 define( 'MW_DB', $bits[0] );
964 define( 'MW_PREFIX', $bits[1] );
965 }
966
967 if ( !is_readable( $settingsFile ) ) {
968 $this->error( "A copy of your installation's LocalSettings.php\n" .
969 "must exist and be readable in the source directory.\n" .
970 "Use --conf to specify it." , true );
971 }
972 $wgCommandLineMode = true;
973 return $settingsFile;
974 }
975
976 /**
977 * Support function for cleaning up redundant text records
978 * @param $delete Boolean: whether or not to actually delete the records
979 * @author Rob Church <robchur@gmail.com>
980 */
981 public function purgeRedundantText( $delete = true ) {
982 # Data should come off the master, wrapped in a transaction
983 $dbw = $this->getDB( DB_MASTER );
984 $dbw->begin();
985
986 $tbl_arc = $dbw->tableName( 'archive' );
987 $tbl_rev = $dbw->tableName( 'revision' );
988 $tbl_txt = $dbw->tableName( 'text' );
989
990 # Get "active" text records from the revisions table
991 $this->output( 'Searching for active text records in revisions table...' );
992 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
993 foreach ( $res as $row ) {
994 $cur[] = $row->rev_text_id;
995 }
996 $this->output( "done.\n" );
997
998 # Get "active" text records from the archive table
999 $this->output( 'Searching for active text records in archive table...' );
1000 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
1001 foreach ( $res as $row ) {
1002 $cur[] = $row->ar_text_id;
1003 }
1004 $this->output( "done.\n" );
1005
1006 # Get the IDs of all text records not in these sets
1007 $this->output( 'Searching for inactive text records...' );
1008 $set = implode( ', ', $cur );
1009 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
1010 $old = array();
1011 foreach ( $res as $row ) {
1012 $old[] = $row->old_id;
1013 }
1014 $this->output( "done.\n" );
1015
1016 # Inform the user of what we're going to do
1017 $count = count( $old );
1018 $this->output( "$count inactive items found.\n" );
1019
1020 # Delete as appropriate
1021 if ( $delete && $count ) {
1022 $this->output( 'Deleting...' );
1023 $set = implode( ', ', $old );
1024 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
1025 $this->output( "done.\n" );
1026 }
1027
1028 # Done
1029 $dbw->commit();
1030 }
1031
1032 /**
1033 * Get the maintenance directory.
1034 */
1035 protected function getDir() {
1036 return dirname( __FILE__ );
1037 }
1038
1039 /**
1040 * Get the list of available maintenance scripts. Note
1041 * that if you call this _before_ calling doMaintenance
1042 * you won't have any extensions in it yet
1043 * @return Array
1044 */
1045 public static function getMaintenanceScripts() {
1046 global $wgMaintenanceScripts;
1047 return $wgMaintenanceScripts + self::getCoreScripts();
1048 }
1049
1050 /**
1051 * Return all of the core maintenance scripts
1052 * @return array
1053 */
1054 protected static function getCoreScripts() {
1055 if ( !self::$mCoreScripts ) {
1056 $paths = array(
1057 dirname( __FILE__ ),
1058 dirname( __FILE__ ) . '/gearman',
1059 dirname( __FILE__ ) . '/language',
1060 dirname( __FILE__ ) . '/storage',
1061 );
1062 self::$mCoreScripts = array();
1063 foreach ( $paths as $p ) {
1064 $handle = opendir( $p );
1065 while ( ( $file = readdir( $handle ) ) !== false ) {
1066 if ( $file == 'Maintenance.php' ) {
1067 continue;
1068 }
1069 $file = $p . '/' . $file;
1070 if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
1071 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1072 continue;
1073 }
1074 require( $file );
1075 $vars = get_defined_vars();
1076 if ( array_key_exists( 'maintClass', $vars ) ) {
1077 self::$mCoreScripts[$vars['maintClass']] = $file;
1078 }
1079 }
1080 closedir( $handle );
1081 }
1082 }
1083 return self::$mCoreScripts;
1084 }
1085
1086 /**
1087 * Returns a database to be used by current maintenance script. It can be set by setDB().
1088 * If not set, wfGetDB() will be used.
1089 * This function has the same parameters as wfGetDB()
1090 *
1091 * @return DatabaseBase
1092 */
1093 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1094 if ( is_null( $this->mDb ) ) {
1095 return wfGetDB( $db, $groups, $wiki );
1096 } else {
1097 return $this->mDb;
1098 }
1099 }
1100
1101 /**
1102 * Sets database object to be returned by getDB().
1103 *
1104 * @param $db DatabaseBase: Database object to be used
1105 */
1106 public function setDB( &$db ) {
1107 $this->mDb = $db;
1108 }
1109
1110 /**
1111 * Lock the search index
1112 * @param &$db Database object
1113 */
1114 private function lockSearchindex( &$db ) {
1115 $write = array( 'searchindex' );
1116 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1117 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1118 }
1119
1120 /**
1121 * Unlock the tables
1122 * @param &$db Database object
1123 */
1124 private function unlockSearchindex( &$db ) {
1125 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1126 }
1127
1128 /**
1129 * Unlock and lock again
1130 * Since the lock is low-priority, queued reads will be able to complete
1131 * @param &$db Database object
1132 */
1133 private function relockSearchindex( &$db ) {
1134 $this->unlockSearchindex( $db );
1135 $this->lockSearchindex( $db );
1136 }
1137
1138 /**
1139 * Perform a search index update with locking
1140 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1141 * @param $callback callback String: the function that will update the function.
1142 * @param $dbw DatabaseBase object
1143 * @param $results
1144 */
1145 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1146 $lockTime = time();
1147
1148 # Lock searchindex
1149 if ( $maxLockTime ) {
1150 $this->output( " --- Waiting for lock ---" );
1151 $this->lockSearchindex( $dbw );
1152 $lockTime = time();
1153 $this->output( "\n" );
1154 }
1155
1156 # Loop through the results and do a search update
1157 foreach ( $results as $row ) {
1158 # Allow reads to be processed
1159 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1160 $this->output( " --- Relocking ---" );
1161 $this->relockSearchindex( $dbw );
1162 $lockTime = time();
1163 $this->output( "\n" );
1164 }
1165 call_user_func( $callback, $dbw, $row );
1166 }
1167
1168 # Unlock searchindex
1169 if ( $maxLockTime ) {
1170 $this->output( " --- Unlocking --" );
1171 $this->unlockSearchindex( $dbw );
1172 $this->output( "\n" );
1173 }
1174
1175 }
1176
1177 /**
1178 * Update the searchindex table for a given pageid
1179 * @param $dbw Database: a database write handle
1180 * @param $pageId Integer: the page ID to update.
1181 */
1182 public function updateSearchIndexForPage( $dbw, $pageId ) {
1183 // Get current revision
1184 $rev = Revision::loadFromPageId( $dbw, $pageId );
1185 $title = null;
1186 if ( $rev ) {
1187 $titleObj = $rev->getTitle();
1188 $title = $titleObj->getPrefixedDBkey();
1189 $this->output( "$title..." );
1190 # Update searchindex
1191 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1192 $u->doUpdate();
1193 $this->output( "\n" );
1194 }
1195 return $title;
1196 }
1197
1198 /**
1199 * Wrapper for posix_isatty()
1200 * We default as considering stdin a tty (for nice readline methods)
1201 * but treating stout as not a tty to avoid color codes
1202 *
1203 * @param $fd int File descriptor
1204 * @return bool
1205 */
1206 public static function posix_isatty( $fd ) {
1207 if ( !MWInit::functionExists( 'posix_isatty' ) ) {
1208 return !$fd;
1209 } else {
1210 return posix_isatty( $fd );
1211 }
1212 }
1213
1214 /**
1215 * Prompt the console for input
1216 * @param $prompt String what to begin the line with, like '> '
1217 * @return String response
1218 */
1219 public static function readconsole( $prompt = '> ' ) {
1220 static $isatty = null;
1221 if ( is_null( $isatty ) ) {
1222 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1223 }
1224
1225 if ( $isatty && function_exists( 'readline' ) ) {
1226 return readline( $prompt );
1227 } else {
1228 if ( $isatty ) {
1229 $st = self::readlineEmulation( $prompt );
1230 } else {
1231 if ( feof( STDIN ) ) {
1232 $st = false;
1233 } else {
1234 $st = fgets( STDIN, 1024 );
1235 }
1236 }
1237 if ( $st === false ) return false;
1238 $resp = trim( $st );
1239 return $resp;
1240 }
1241 }
1242
1243 /**
1244 * Emulate readline()
1245 * @param $prompt String what to begin the line with, like '> '
1246 * @return String
1247 */
1248 private static function readlineEmulation( $prompt ) {
1249 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1250 if ( !wfIsWindows() && $bash ) {
1251 $retval = false;
1252 $encPrompt = wfEscapeShellArg( $prompt );
1253 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1254 $encCommand = wfEscapeShellArg( $command );
1255 $line = wfShellExec( "$bash -c $encCommand", $retval );
1256
1257 if ( $retval == 0 ) {
1258 return $line;
1259 } elseif ( $retval == 127 ) {
1260 // Couldn't execute bash even though we thought we saw it.
1261 // Shell probably spit out an error message, sorry :(
1262 // Fall through to fgets()...
1263 } else {
1264 // EOF/ctrl+D
1265 return false;
1266 }
1267 }
1268
1269 // Fallback... we'll have no editing controls, EWWW
1270 if ( feof( STDIN ) ) {
1271 return false;
1272 }
1273 print $prompt;
1274 return fgets( STDIN, 1024 );
1275 }
1276 }
1277
1278 class FakeMaintenance extends Maintenance {
1279 protected $mSelf = "FakeMaintenanceScript";
1280 public function execute() {
1281 return;
1282 }
1283 }
1284
1285 abstract class LoggedUpdateMaintenance extends Maintenance {
1286 public function __construct() {
1287 parent::__construct();
1288 $this->addOption( 'force', 'Run the update even if it was completed already' );
1289 }
1290
1291 public function execute() {
1292 $db = $this->getDB( DB_MASTER );
1293 $key = $this->getUpdateKey();
1294
1295 if ( !$this->hasOption( 'force' ) &&
1296 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ ) )
1297 {
1298 $this->output( $this->updateSkippedMessage() . "\n" );
1299 return true;
1300 }
1301
1302 if ( !$this->doDBUpdates() ) {
1303 return false;
1304 }
1305
1306 if (
1307 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) )
1308 {
1309 return true;
1310 } else {
1311 $this->output( $this->updatelogFailedMessage() . "\n" );
1312 return false;
1313 }
1314 }
1315
1316 /**
1317 * Do the actual work. All child classes will need to implement this.
1318 * Return true to log the update as done or false (usually on failure).
1319 * @return Bool
1320 */
1321 abstract protected function doDBUpdates();
1322
1323 /**
1324 * Get the update key name to go in the update log table
1325 * @return String
1326 */
1327 abstract protected function getUpdateKey();
1328
1329 /**
1330 * Message to show that the update was done already and was just skipped
1331 * @return String
1332 */
1333 abstract protected function updateSkippedMessage();
1334
1335 /**
1336 * Message to show the the update log was unable to log the completion of this update
1337 * @return String
1338 */
1339 abstract protected function updatelogFailedMessage();
1340 }