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