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