2cc791b10ecc6ba319836da8e640cae14a6bf35f
[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 $wgCommandLineMode = true;
531
532 # Turn off output buffering if it's on
533 while ( ob_get_level() > 0 ) {
534 ob_end_flush();
535 }
536
537 $this->validateParamsAndArgs();
538 }
539
540 /**
541 * Normally we disable the memory_limit when running admin scripts.
542 * Some scripts may wish to actually set a limit, however, to avoid
543 * blowing up unexpectedly. We also support a --memory-limit option,
544 * to allow sysadmins to explicitly set one if they'd prefer to override
545 * defaults (or for people using Suhosin which yells at you for trying
546 * to disable the limits)
547 * @return string
548 */
549 public function memoryLimit() {
550 $limit = $this->getOption( 'memory-limit', 'max' );
551 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
552 return $limit;
553 }
554
555 /**
556 * Adjusts PHP's memory limit to better suit our needs, if needed.
557 */
558 protected function adjustMemoryLimit() {
559 $limit = $this->memoryLimit();
560 if ( $limit == 'max' ) {
561 $limit = -1; // no memory limit
562 }
563 if ( $limit != 'default' ) {
564 ini_set( 'memory_limit', $limit );
565 }
566 }
567
568 /**
569 * Clear all params and arguments.
570 */
571 public function clearParamsAndArgs() {
572 $this->mOptions = array();
573 $this->mArgs = array();
574 $this->mInputLoaded = false;
575 }
576
577 /**
578 * Process command line arguments
579 * $mOptions becomes an array with keys set to the option names
580 * $mArgs becomes a zero-based array containing the non-option arguments
581 *
582 * @param string $self The name of the script, if any
583 * @param array $opts An array of options, in form of key=>value
584 * @param array $args An array of command line arguments
585 */
586 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
587 # If we were given opts or args, set those and return early
588 if ( $self ) {
589 $this->mSelf = $self;
590 $this->mInputLoaded = true;
591 }
592 if ( $opts ) {
593 $this->mOptions = $opts;
594 $this->mInputLoaded = true;
595 }
596 if ( $args ) {
597 $this->mArgs = $args;
598 $this->mInputLoaded = true;
599 }
600
601 # If we've already loaded input (either by user values or from $argv)
602 # skip on loading it again. The array_shift() will corrupt values if
603 # it's run again and again
604 if ( $this->mInputLoaded ) {
605 $this->loadSpecialVars();
606
607 return;
608 }
609
610 global $argv;
611 $this->mSelf = array_shift( $argv );
612
613 $options = array();
614 $args = array();
615
616 # Parse arguments
617 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
618 if ( $arg == '--' ) {
619 # End of options, remainder should be considered arguments
620 $arg = next( $argv );
621 while ( $arg !== false ) {
622 $args[] = $arg;
623 $arg = next( $argv );
624 }
625 break;
626 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
627 # Long options
628 $option = substr( $arg, 2 );
629 if ( array_key_exists( $option, $options ) ) {
630 $this->error( "\nERROR: $option parameter given twice\n" );
631 $this->maybeHelp( true );
632 }
633 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
634 $param = next( $argv );
635 if ( $param === false ) {
636 $this->error( "\nERROR: $option parameter needs a value after it\n" );
637 $this->maybeHelp( true );
638 }
639 $options[$option] = $param;
640 } else {
641 $bits = explode( '=', $option, 2 );
642 if ( count( $bits ) > 1 ) {
643 $option = $bits[0];
644 $param = $bits[1];
645 } else {
646 $param = 1;
647 }
648 $options[$option] = $param;
649 }
650 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
651 # Short options
652 $argLength = strlen( $arg );
653 for ( $p = 1; $p < $argLength; $p++ ) {
654 $option = $arg[$p];
655 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
656 $option = $this->mShortParamsMap[$option];
657 }
658 if ( array_key_exists( $option, $options ) ) {
659 $this->error( "\nERROR: $option parameter given twice\n" );
660 $this->maybeHelp( true );
661 }
662 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
663 $param = next( $argv );
664 if ( $param === false ) {
665 $this->error( "\nERROR: $option parameter needs a value after it\n" );
666 $this->maybeHelp( true );
667 }
668 $options[$option] = $param;
669 } else {
670 $options[$option] = 1;
671 }
672 }
673 } else {
674 $args[] = $arg;
675 }
676 }
677
678 $this->mOptions = $options;
679 $this->mArgs = $args;
680 $this->loadSpecialVars();
681 $this->mInputLoaded = true;
682 }
683
684 /**
685 * Run some validation checks on the params, etc
686 */
687 protected function validateParamsAndArgs() {
688 $die = false;
689 # Check to make sure we've got all the required options
690 foreach ( $this->mParams as $opt => $info ) {
691 if ( $info['require'] && !$this->hasOption( $opt ) ) {
692 $this->error( "Param $opt required!" );
693 $die = true;
694 }
695 }
696 # Check arg list too
697 foreach ( $this->mArgList as $k => $info ) {
698 if ( $info['require'] && !$this->hasArg( $k ) ) {
699 $this->error( 'Argument <' . $info['name'] . '> required!' );
700 $die = true;
701 }
702 }
703
704 if ( $die ) {
705 $this->maybeHelp( true );
706 }
707 }
708
709 /**
710 * Handle the special variables that are global to all scripts
711 */
712 protected function loadSpecialVars() {
713 if ( $this->hasOption( 'dbuser' ) ) {
714 $this->mDbUser = $this->getOption( 'dbuser' );
715 }
716 if ( $this->hasOption( 'dbpass' ) ) {
717 $this->mDbPass = $this->getOption( 'dbpass' );
718 }
719 if ( $this->hasOption( 'quiet' ) ) {
720 $this->mQuiet = true;
721 }
722 if ( $this->hasOption( 'batch-size' ) ) {
723 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
724 }
725 }
726
727 /**
728 * Maybe show the help.
729 * @param bool $force Whether to force the help to show, default false
730 */
731 protected function maybeHelp( $force = false ) {
732 if ( !$force && !$this->hasOption( 'help' ) ) {
733 return;
734 }
735
736 $screenWidth = 80; // TODO: Calculate this!
737 $tab = " ";
738 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
739
740 ksort( $this->mParams );
741 $this->mQuiet = false;
742
743 // Description ...
744 if ( $this->mDescription ) {
745 $this->output( "\n" . $this->mDescription . "\n" );
746 }
747 $output = "\nUsage: php " . basename( $this->mSelf );
748
749 // ... append parameters ...
750 if ( $this->mParams ) {
751 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
752 }
753
754 // ... and append arguments.
755 if ( $this->mArgList ) {
756 $output .= ' ';
757 foreach ( $this->mArgList as $k => $arg ) {
758 if ( $arg['require'] ) {
759 $output .= '<' . $arg['name'] . '>';
760 } else {
761 $output .= '[' . $arg['name'] . ']';
762 }
763 if ( $k < count( $this->mArgList ) - 1 ) {
764 $output .= ' ';
765 }
766 }
767 }
768 $this->output( "$output\n\n" );
769
770 # TODO abstract some repetitive code below
771
772 // Generic parameters
773 $this->output( "Generic maintenance parameters:\n" );
774 foreach ( $this->mGenericParameters as $par => $info ) {
775 if ( $info['shortName'] !== false ) {
776 $par .= " (-{$info['shortName']})";
777 }
778 $this->output(
779 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
780 "\n$tab$tab" ) . "\n"
781 );
782 }
783 $this->output( "\n" );
784
785 $scriptDependantParams = $this->mDependantParameters;
786 if ( count( $scriptDependantParams ) > 0 ) {
787 $this->output( "Script dependant parameters:\n" );
788 // Parameters description
789 foreach ( $scriptDependantParams as $par => $info ) {
790 if ( $info['shortName'] !== false ) {
791 $par .= " (-{$info['shortName']})";
792 }
793 $this->output(
794 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
795 "\n$tab$tab" ) . "\n"
796 );
797 }
798 $this->output( "\n" );
799 }
800
801 // Script specific parameters not defined on construction by
802 // Maintenance::addDefaultParams()
803 $scriptSpecificParams = array_diff_key(
804 # all script parameters:
805 $this->mParams,
806 # remove the Maintenance default parameters:
807 $this->mGenericParameters,
808 $this->mDependantParameters
809 );
810 if ( count( $scriptSpecificParams ) > 0 ) {
811 $this->output( "Script specific parameters:\n" );
812 // Parameters description
813 foreach ( $scriptSpecificParams as $par => $info ) {
814 if ( $info['shortName'] !== false ) {
815 $par .= " (-{$info['shortName']})";
816 }
817 $this->output(
818 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
819 "\n$tab$tab" ) . "\n"
820 );
821 }
822 $this->output( "\n" );
823 }
824
825 // Print arguments
826 if ( count( $this->mArgList ) > 0 ) {
827 $this->output( "Arguments:\n" );
828 // Arguments description
829 foreach ( $this->mArgList as $info ) {
830 $openChar = $info['require'] ? '<' : '[';
831 $closeChar = $info['require'] ? '>' : ']';
832 $this->output(
833 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
834 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
835 );
836 }
837 $this->output( "\n" );
838 }
839
840 die( 1 );
841 }
842
843 /**
844 * Handle some last-minute setup here.
845 */
846 public function finalSetup() {
847 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
848 global $wgDBadminuser, $wgDBadminpassword;
849 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
850
851 # Turn off output buffering again, it might have been turned on in the settings files
852 if ( ob_get_level() ) {
853 ob_end_flush();
854 }
855 # Same with these
856 $wgCommandLineMode = true;
857
858 # Override $wgServer
859 if ( $this->hasOption( 'server' ) ) {
860 $wgServer = $this->getOption( 'server', $wgServer );
861 }
862
863 # If these were passed, use them
864 if ( $this->mDbUser ) {
865 $wgDBadminuser = $this->mDbUser;
866 }
867 if ( $this->mDbPass ) {
868 $wgDBadminpassword = $this->mDbPass;
869 }
870
871 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
872 $wgDBuser = $wgDBadminuser;
873 $wgDBpassword = $wgDBadminpassword;
874
875 if ( $wgDBservers ) {
876 /**
877 * @var $wgDBservers array
878 */
879 foreach ( $wgDBservers as $i => $server ) {
880 $wgDBservers[$i]['user'] = $wgDBuser;
881 $wgDBservers[$i]['password'] = $wgDBpassword;
882 }
883 }
884 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
885 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
886 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
887 }
888 LBFactory::destroyInstance();
889 }
890
891 $this->afterFinalSetup();
892
893 $wgShowSQLErrors = true;
894
895 // @codingStandardsIgnoreStart Allow error supppression. wfSuppressWarnings()
896 // is not avaiable.
897 @set_time_limit( 0 );
898 // @codingStandardsIgnoreStart
899
900 $this->adjustMemoryLimit();
901
902 // Per-script profiling; useful for debugging
903 $forcedProfiler = $this->getOption( 'profiler' );
904 if ( $forcedProfiler === 'text' ) {
905 Profiler::setInstance( new ProfilerSimpleText( array() ) );
906 Profiler::instance()->setTemplated( true );
907 } elseif ( $forcedProfiler === 'trace' ) {
908 Profiler::setInstance( new ProfilerSimpleTrace( array() ) );
909 Profiler::instance()->setTemplated( true );
910 }
911 }
912
913 /**
914 * Execute a callback function at the end of initialisation
915 */
916 protected function afterFinalSetup() {
917 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
918 call_user_func( MW_CMDLINE_CALLBACK );
919 }
920 }
921
922 /**
923 * Potentially debug globals. Originally a feature only
924 * for refreshLinks
925 */
926 public function globals() {
927 if ( $this->hasOption( 'globals' ) ) {
928 print_r( $GLOBALS );
929 }
930 }
931
932 /**
933 * Generic setup for most installs. Returns the location of LocalSettings
934 * @return string
935 */
936 public function loadSettings() {
937 global $wgCommandLineMode, $IP;
938
939 if ( isset( $this->mOptions['conf'] ) ) {
940 $settingsFile = $this->mOptions['conf'];
941 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
942 $settingsFile = MW_CONFIG_FILE;
943 } else {
944 $settingsFile = "$IP/LocalSettings.php";
945 }
946 if ( isset( $this->mOptions['wiki'] ) ) {
947 $bits = explode( '-', $this->mOptions['wiki'] );
948 if ( count( $bits ) == 1 ) {
949 $bits[] = '';
950 }
951 define( 'MW_DB', $bits[0] );
952 define( 'MW_PREFIX', $bits[1] );
953 }
954
955 if ( !is_readable( $settingsFile ) ) {
956 $this->error( "A copy of your installation's LocalSettings.php\n" .
957 "must exist and be readable in the source directory.\n" .
958 "Use --conf to specify it.", true );
959 }
960 $wgCommandLineMode = true;
961
962 return $settingsFile;
963 }
964
965 /**
966 * Support function for cleaning up redundant text records
967 * @param bool $delete Whether or not to actually delete the records
968 * @author Rob Church <robchur@gmail.com>
969 */
970 public function purgeRedundantText( $delete = true ) {
971 # Data should come off the master, wrapped in a transaction
972 $dbw = $this->getDB( DB_MASTER );
973 $dbw->begin( __METHOD__ );
974
975 # Get "active" text records from the revisions table
976 $this->output( 'Searching for active text records in revisions table...' );
977 $res = $dbw->select( 'revision', 'rev_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
978 foreach ( $res as $row ) {
979 $cur[] = $row->rev_text_id;
980 }
981 $this->output( "done.\n" );
982
983 # Get "active" text records from the archive table
984 $this->output( 'Searching for active text records in archive table...' );
985 $res = $dbw->select( 'archive', 'ar_text_id', array(), __METHOD__, array( 'DISTINCT' ) );
986 foreach ( $res as $row ) {
987 # old pre-MW 1.5 records can have null ar_text_id's.
988 if ( $row->ar_text_id !== null ) {
989 $cur[] = $row->ar_text_id;
990 }
991 }
992 $this->output( "done.\n" );
993
994 # Get the IDs of all text records not in these sets
995 $this->output( 'Searching for inactive text records...' );
996 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
997 $res = $dbw->select( 'text', 'old_id', array( $cond ), __METHOD__, array( 'DISTINCT' ) );
998 $old = array();
999 foreach ( $res as $row ) {
1000 $old[] = $row->old_id;
1001 }
1002 $this->output( "done.\n" );
1003
1004 # Inform the user of what we're going to do
1005 $count = count( $old );
1006 $this->output( "$count inactive items found.\n" );
1007
1008 # Delete as appropriate
1009 if ( $delete && $count ) {
1010 $this->output( 'Deleting...' );
1011 $dbw->delete( 'text', array( 'old_id' => $old ), __METHOD__ );
1012 $this->output( "done.\n" );
1013 }
1014
1015 # Done
1016 $dbw->commit( __METHOD__ );
1017 }
1018
1019 /**
1020 * Get the maintenance directory.
1021 * @return string
1022 */
1023 protected function getDir() {
1024 return __DIR__;
1025 }
1026
1027 /**
1028 * Returns a database to be used by current maintenance script. It can be set by setDB().
1029 * If not set, wfGetDB() will be used.
1030 * This function has the same parameters as wfGetDB()
1031 *
1032 * @return DatabaseBase
1033 */
1034 protected function &getDB( $db, $groups = array(), $wiki = false ) {
1035 if ( is_null( $this->mDb ) ) {
1036 return wfGetDB( $db, $groups, $wiki );
1037 } else {
1038 return $this->mDb;
1039 }
1040 }
1041
1042 /**
1043 * Sets database object to be returned by getDB().
1044 *
1045 * @param DatabaseBase $db Database object to be used
1046 */
1047 public function setDB( &$db ) {
1048 $this->mDb = $db;
1049 }
1050
1051 /**
1052 * Lock the search index
1053 * @param DatabaseBase &$db
1054 */
1055 private function lockSearchindex( &$db ) {
1056 $write = array( 'searchindex' );
1057 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache', 'user' );
1058 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1059 }
1060
1061 /**
1062 * Unlock the tables
1063 * @param DatabaseBase &$db
1064 */
1065 private function unlockSearchindex( &$db ) {
1066 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1067 }
1068
1069 /**
1070 * Unlock and lock again
1071 * Since the lock is low-priority, queued reads will be able to complete
1072 * @param DatabaseBase &$db
1073 */
1074 private function relockSearchindex( &$db ) {
1075 $this->unlockSearchindex( $db );
1076 $this->lockSearchindex( $db );
1077 }
1078
1079 /**
1080 * Perform a search index update with locking
1081 * @param int $maxLockTime The maximum time to keep the search index locked.
1082 * @param string $callback The function that will update the function.
1083 * @param DatabaseBase $dbw
1084 * @param array $results
1085 */
1086 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1087 $lockTime = time();
1088
1089 # Lock searchindex
1090 if ( $maxLockTime ) {
1091 $this->output( " --- Waiting for lock ---" );
1092 $this->lockSearchindex( $dbw );
1093 $lockTime = time();
1094 $this->output( "\n" );
1095 }
1096
1097 # Loop through the results and do a search update
1098 foreach ( $results as $row ) {
1099 # Allow reads to be processed
1100 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1101 $this->output( " --- Relocking ---" );
1102 $this->relockSearchindex( $dbw );
1103 $lockTime = time();
1104 $this->output( "\n" );
1105 }
1106 call_user_func( $callback, $dbw, $row );
1107 }
1108
1109 # Unlock searchindex
1110 if ( $maxLockTime ) {
1111 $this->output( " --- Unlocking --" );
1112 $this->unlockSearchindex( $dbw );
1113 $this->output( "\n" );
1114 }
1115 }
1116
1117 /**
1118 * Update the searchindex table for a given pageid
1119 * @param DatabaseBase $dbw A database write handle
1120 * @param int $pageId The page ID to update.
1121 * @return null|string
1122 */
1123 public function updateSearchIndexForPage( $dbw, $pageId ) {
1124 // Get current revision
1125 $rev = Revision::loadFromPageId( $dbw, $pageId );
1126 $title = null;
1127 if ( $rev ) {
1128 $titleObj = $rev->getTitle();
1129 $title = $titleObj->getPrefixedDBkey();
1130 $this->output( "$title..." );
1131 # Update searchindex
1132 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1133 $u->doUpdate();
1134 $this->output( "\n" );
1135 }
1136
1137 return $title;
1138 }
1139
1140 /**
1141 * Wrapper for posix_isatty()
1142 * We default as considering stdin a tty (for nice readline methods)
1143 * but treating stout as not a tty to avoid color codes
1144 *
1145 * @param int $fd File descriptor
1146 * @return bool
1147 */
1148 public static function posix_isatty( $fd ) {
1149 if ( !function_exists( 'posix_isatty' ) ) {
1150 return !$fd;
1151 } else {
1152 return posix_isatty( $fd );
1153 }
1154 }
1155
1156 /**
1157 * Prompt the console for input
1158 * @param string $prompt What to begin the line with, like '> '
1159 * @return string Response
1160 */
1161 public static function readconsole( $prompt = '> ' ) {
1162 static $isatty = null;
1163 if ( is_null( $isatty ) ) {
1164 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1165 }
1166
1167 if ( $isatty && function_exists( 'readline' ) ) {
1168 return readline( $prompt );
1169 } else {
1170 if ( $isatty ) {
1171 $st = self::readlineEmulation( $prompt );
1172 } else {
1173 if ( feof( STDIN ) ) {
1174 $st = false;
1175 } else {
1176 $st = fgets( STDIN, 1024 );
1177 }
1178 }
1179 if ( $st === false ) {
1180 return false;
1181 }
1182 $resp = trim( $st );
1183
1184 return $resp;
1185 }
1186 }
1187
1188 /**
1189 * Emulate readline()
1190 * @param string $prompt What to begin the line with, like '> '
1191 * @return string
1192 */
1193 private static function readlineEmulation( $prompt ) {
1194 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1195 if ( !wfIsWindows() && $bash ) {
1196 $retval = false;
1197 $encPrompt = wfEscapeShellArg( $prompt );
1198 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1199 $encCommand = wfEscapeShellArg( $command );
1200 $line = wfShellExec( "$bash -c $encCommand", $retval, array(), array( 'walltime' => 0 ) );
1201
1202 if ( $retval == 0 ) {
1203 return $line;
1204 } elseif ( $retval == 127 ) {
1205 // Couldn't execute bash even though we thought we saw it.
1206 // Shell probably spit out an error message, sorry :(
1207 // Fall through to fgets()...
1208 } else {
1209 // EOF/ctrl+D
1210 return false;
1211 }
1212 }
1213
1214 // Fallback... we'll have no editing controls, EWWW
1215 if ( feof( STDIN ) ) {
1216 return false;
1217 }
1218 print $prompt;
1219
1220 return fgets( STDIN, 1024 );
1221 }
1222 }
1223
1224 /**
1225 * Fake maintenance wrapper, mostly used for the web installer/updater
1226 */
1227 class FakeMaintenance extends Maintenance {
1228 protected $mSelf = "FakeMaintenanceScript";
1229
1230 public function execute() {
1231 return;
1232 }
1233 }
1234
1235 /**
1236 * Class for scripts that perform database maintenance and want to log the
1237 * update in `updatelog` so we can later skip it
1238 */
1239 abstract class LoggedUpdateMaintenance extends Maintenance {
1240 public function __construct() {
1241 parent::__construct();
1242 $this->addOption( 'force', 'Run the update even if it was completed already' );
1243 $this->setBatchSize( 200 );
1244 }
1245
1246 public function execute() {
1247 $db = $this->getDB( DB_MASTER );
1248 $key = $this->getUpdateKey();
1249
1250 if ( !$this->hasOption( 'force' )
1251 && $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ )
1252 ) {
1253 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1254
1255 return true;
1256 }
1257
1258 if ( !$this->doDBUpdates() ) {
1259 return false;
1260 }
1261
1262 if ( $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) ) {
1263 return true;
1264 } else {
1265 $this->output( $this->updatelogFailedMessage() . "\n" );
1266
1267 return false;
1268 }
1269 }
1270
1271 /**
1272 * Message to show that the update was done already and was just skipped
1273 * @return string
1274 */
1275 protected function updateSkippedMessage() {
1276 $key = $this->getUpdateKey();
1277
1278 return "Update '{$key}' already logged as completed.";
1279 }
1280
1281 /**
1282 * Message to show the the update log was unable to log the completion of this update
1283 * @return string
1284 */
1285 protected function updatelogFailedMessage() {
1286 $key = $this->getUpdateKey();
1287
1288 return "Unable to log update '{$key}' as completed.";
1289 }
1290
1291 /**
1292 * Do the actual work. All child classes will need to implement this.
1293 * Return true to log the update as done or false (usually on failure).
1294 * @return bool
1295 */
1296 abstract protected function doDBUpdates();
1297
1298 /**
1299 * Get the update key name to go in the update log table
1300 * @return string
1301 */
1302 abstract protected function getUpdateKey();
1303 }