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