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