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