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