Revert r97788
[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 = intval( $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 * Generic setup for most installs. Returns the location of LocalSettings
895 * @return String
896 */
897 public function loadSettings() {
898 global $wgCommandLineMode, $IP;
899
900 if ( isset( $this->mOptions['conf'] ) ) {
901 $settingsFile = $this->mOptions['conf'];
902 } elseif ( defined("MW_CONFIG_FILE") ) {
903 $settingsFile = MW_CONFIG_FILE;
904 } else {
905 $settingsFile = "$IP/LocalSettings.php";
906 }
907 if ( isset( $this->mOptions['wiki'] ) ) {
908 $bits = explode( '-', $this->mOptions['wiki'] );
909 if ( count( $bits ) == 1 ) {
910 $bits[] = '';
911 }
912 define( 'MW_DB', $bits[0] );
913 define( 'MW_PREFIX', $bits[1] );
914 }
915
916 if ( !is_readable( $settingsFile ) ) {
917 $this->error( "A copy of your installation's LocalSettings.php\n" .
918 "must exist and be readable in the source directory.\n" .
919 "Use --conf to specify it." , true );
920 }
921 $wgCommandLineMode = true;
922 return $settingsFile;
923 }
924
925 /**
926 * Support function for cleaning up redundant text records
927 * @param $delete Boolean: whether or not to actually delete the records
928 * @author Rob Church <robchur@gmail.com>
929 */
930 public function purgeRedundantText( $delete = true ) {
931 # Data should come off the master, wrapped in a transaction
932 $dbw = $this->getDB( DB_MASTER );
933 $dbw->begin();
934
935 $tbl_arc = $dbw->tableName( 'archive' );
936 $tbl_rev = $dbw->tableName( 'revision' );
937 $tbl_txt = $dbw->tableName( 'text' );
938
939 # Get "active" text records from the revisions table
940 $this->output( 'Searching for active text records in revisions table...' );
941 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
942 foreach ( $res as $row ) {
943 $cur[] = $row->rev_text_id;
944 }
945 $this->output( "done.\n" );
946
947 # Get "active" text records from the archive table
948 $this->output( 'Searching for active text records in archive table...' );
949 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
950 foreach ( $res as $row ) {
951 $cur[] = $row->ar_text_id;
952 }
953 $this->output( "done.\n" );
954
955 # Get the IDs of all text records not in these sets
956 $this->output( 'Searching for inactive text records...' );
957 $set = implode( ', ', $cur );
958 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
959 $old = array();
960 foreach ( $res as $row ) {
961 $old[] = $row->old_id;
962 }
963 $this->output( "done.\n" );
964
965 # Inform the user of what we're going to do
966 $count = count( $old );
967 $this->output( "$count inactive items found.\n" );
968
969 # Delete as appropriate
970 if ( $delete && $count ) {
971 $this->output( 'Deleting...' );
972 $set = implode( ', ', $old );
973 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
974 $this->output( "done.\n" );
975 }
976
977 # Done
978 $dbw->commit();
979 }
980
981 /**
982 * Get the maintenance directory.
983 */
984 protected function getDir() {
985 return dirname( __FILE__ );
986 }
987
988 /**
989 * Get the list of available maintenance scripts. Note
990 * that if you call this _before_ calling doMaintenance
991 * you won't have any extensions in it yet
992 * @return Array
993 */
994 public static function getMaintenanceScripts() {
995 global $wgMaintenanceScripts;
996 return $wgMaintenanceScripts + self::getCoreScripts();
997 }
998
999 /**
1000 * Return all of the core maintenance scripts
1001 * @return array
1002 */
1003 protected static function getCoreScripts() {
1004 if ( !self::$mCoreScripts ) {
1005 $paths = array(
1006 dirname( __FILE__ ),
1007 dirname( __FILE__ ) . '/gearman',
1008 dirname( __FILE__ ) . '/language',
1009 dirname( __FILE__ ) . '/storage',
1010 );
1011 self::$mCoreScripts = array();
1012 foreach ( $paths as $p ) {
1013 $handle = opendir( $p );
1014 while ( ( $file = readdir( $handle ) ) !== false ) {
1015 if ( $file == 'Maintenance.php' ) {
1016 continue;
1017 }
1018 $file = $p . '/' . $file;
1019 if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
1020 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
1021 continue;
1022 }
1023 require( $file );
1024 $vars = get_defined_vars();
1025 if ( array_key_exists( 'maintClass', $vars ) ) {
1026 self::$mCoreScripts[$vars['maintClass']] = $file;
1027 }
1028 }
1029 closedir( $handle );
1030 }
1031 }
1032 return self::$mCoreScripts;
1033 }
1034
1035 /**
1036 * Returns a database to be used by current maintenance script. It can be set by setDB().
1037 * If not set, wfGetDB() will be used.
1038 * This function has the same parameters as wfGetDB()
1039 *
1040 * @return DatabaseBase
1041 */
1042 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1043 if ( is_null( $this->mDb ) ) {
1044 return wfGetDB( $db, $groups, $wiki );
1045 } else {
1046 return $this->mDb;
1047 }
1048 }
1049
1050 /**
1051 * Sets database object to be returned by getDB().
1052 *
1053 * @param $db DatabaseBase: Database object to be used
1054 */
1055 public function setDB( &$db ) {
1056 $this->mDb = $db;
1057 }
1058
1059 /**
1060 * Lock the search index
1061 * @param &$db Database object
1062 */
1063 private function lockSearchindex( &$db ) {
1064 $write = array( 'searchindex' );
1065 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1066 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1067 }
1068
1069 /**
1070 * Unlock the tables
1071 * @param &$db Database object
1072 */
1073 private function unlockSearchindex( &$db ) {
1074 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1075 }
1076
1077 /**
1078 * Unlock and lock again
1079 * Since the lock is low-priority, queued reads will be able to complete
1080 * @param &$db Database object
1081 */
1082 private function relockSearchindex( &$db ) {
1083 $this->unlockSearchindex( $db );
1084 $this->lockSearchindex( $db );
1085 }
1086
1087 /**
1088 * Perform a search index update with locking
1089 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1090 * @param $callback callback String: the function that will update the function.
1091 * @param $dbw DatabaseBase object
1092 * @param $results
1093 */
1094 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1095 $lockTime = time();
1096
1097 # Lock searchindex
1098 if ( $maxLockTime ) {
1099 $this->output( " --- Waiting for lock ---" );
1100 $this->lockSearchindex( $dbw );
1101 $lockTime = time();
1102 $this->output( "\n" );
1103 }
1104
1105 # Loop through the results and do a search update
1106 foreach ( $results as $row ) {
1107 # Allow reads to be processed
1108 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1109 $this->output( " --- Relocking ---" );
1110 $this->relockSearchindex( $dbw );
1111 $lockTime = time();
1112 $this->output( "\n" );
1113 }
1114 call_user_func( $callback, $dbw, $row );
1115 }
1116
1117 # Unlock searchindex
1118 if ( $maxLockTime ) {
1119 $this->output( " --- Unlocking --" );
1120 $this->unlockSearchindex( $dbw );
1121 $this->output( "\n" );
1122 }
1123
1124 }
1125
1126 /**
1127 * Update the searchindex table for a given pageid
1128 * @param $dbw Database: a database write handle
1129 * @param $pageId Integer: the page ID to update.
1130 */
1131 public function updateSearchIndexForPage( $dbw, $pageId ) {
1132 // Get current revision
1133 $rev = Revision::loadFromPageId( $dbw, $pageId );
1134 $title = null;
1135 if ( $rev ) {
1136 $titleObj = $rev->getTitle();
1137 $title = $titleObj->getPrefixedDBkey();
1138 $this->output( "$title..." );
1139 # Update searchindex
1140 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1141 $u->doUpdate();
1142 $this->output( "\n" );
1143 }
1144 return $title;
1145 }
1146
1147 /**
1148 * Wrapper for posix_isatty()
1149 * We default as considering stdin a tty (for nice readline methods)
1150 * but treating stout as not a tty to avoid color codes
1151 *
1152 * @param $fd int File descriptor
1153 * @return bool
1154 */
1155 public static function posix_isatty( $fd ) {
1156 if ( !MWInit::functionExists( 'posix_isatty' ) ) {
1157 return !$fd;
1158 } else {
1159 return posix_isatty( $fd );
1160 }
1161 }
1162
1163 /**
1164 * Prompt the console for input
1165 * @param $prompt String what to begin the line with, like '> '
1166 * @return String response
1167 */
1168 public static function readconsole( $prompt = '> ' ) {
1169 static $isatty = null;
1170 if ( is_null( $isatty ) ) {
1171 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1172 }
1173
1174 if ( $isatty && function_exists( 'readline' ) ) {
1175 return readline( $prompt );
1176 } else {
1177 if ( $isatty ) {
1178 $st = self::readlineEmulation( $prompt );
1179 } else {
1180 if ( feof( STDIN ) ) {
1181 $st = false;
1182 } else {
1183 $st = fgets( STDIN, 1024 );
1184 }
1185 }
1186 if ( $st === false ) return false;
1187 $resp = trim( $st );
1188 return $resp;
1189 }
1190 }
1191
1192 /**
1193 * Emulate readline()
1194 * @param $prompt String what to begin the line with, like '> '
1195 * @return String
1196 */
1197 private static function readlineEmulation( $prompt ) {
1198 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1199 if ( !wfIsWindows() && $bash ) {
1200 $retval = false;
1201 $encPrompt = wfEscapeShellArg( $prompt );
1202 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1203 $encCommand = wfEscapeShellArg( $command );
1204 $line = wfShellExec( "$bash -c $encCommand", $retval );
1205
1206 if ( $retval == 0 ) {
1207 return $line;
1208 } elseif ( $retval == 127 ) {
1209 // Couldn't execute bash even though we thought we saw it.
1210 // Shell probably spit out an error message, sorry :(
1211 // Fall through to fgets()...
1212 } else {
1213 // EOF/ctrl+D
1214 return false;
1215 }
1216 }
1217
1218 // Fallback... we'll have no editing controls, EWWW
1219 if ( feof( STDIN ) ) {
1220 return false;
1221 }
1222 print $prompt;
1223 return fgets( STDIN, 1024 );
1224 }
1225 }
1226
1227 /**
1228 * Fake maintenance wrapper, mostly used for the web installer/updater
1229 */
1230 class FakeMaintenance extends Maintenance {
1231 protected $mSelf = "FakeMaintenanceScript";
1232 public function execute() {
1233 return;
1234 }
1235 }
1236
1237 /**
1238 * Class for scripts that perform database maintenance and want to log the
1239 * update in `updatelog` so we can later skip it
1240 */
1241 abstract class LoggedUpdateMaintenance extends Maintenance {
1242 public function __construct() {
1243 parent::__construct();
1244 $this->addOption( 'force', 'Run the update even if it was completed already' );
1245 $this->setBatchSize( 200 );
1246 }
1247
1248 public function execute() {
1249 $db = $this->getDB( DB_MASTER );
1250 $key = $this->getUpdateKey();
1251
1252 if ( !$this->hasOption( 'force' ) &&
1253 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ ) )
1254 {
1255 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1256 return true;
1257 }
1258
1259 if ( !$this->doDBUpdates() ) {
1260 return false;
1261 }
1262
1263 if (
1264 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) )
1265 {
1266 return true;
1267 } else {
1268 $this->output( $this->updatelogFailedMessage() . "\n" );
1269 return false;
1270 }
1271 }
1272
1273 /**
1274 * Message to show the the update log was unable to log the completion of this update
1275 * @return String
1276 */
1277 protected function updatelogFailedMessage() {
1278 $key = $this->getUpdateKey();
1279 return "Unable to log update '{$key}' as completed.";
1280 }
1281
1282 /**
1283 * Do the actual work. All child classes will need to implement this.
1284 * Return true to log the update as done or false (usually on failure).
1285 * @return Bool
1286 */
1287 abstract protected function doDBUpdates();
1288
1289 /**
1290 * Get the update key name to go in the update log table
1291 * @return String
1292 */
1293 abstract protected function getUpdateKey();
1294
1295 /**
1296 * Message to show that the update was done already and was just skipped
1297 * @return String
1298 */
1299 abstract protected function updateSkippedMessage();
1300 }