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