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