Debian Codegraph @

maintenance/includes/Maintenance.php

raw symbols SCIP
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 */
20
21 namespace MediaWiki\Maintenance;
22
23 use ExecutableFinder;
24 use MediaWiki;
25 use MediaWiki\Config\Config;
26 use MediaWiki\Debug\MWDebug;
27 use MediaWiki\HookContainer\HookContainer;
28 use MediaWiki\HookContainer\HookRunner;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Registration\ExtensionRegistry;
32 use MediaWiki\Settings\SettingsBuilder;
33 use MediaWiki\Shell\Shell;
34 use MediaWiki\User\User;
35 use StatusValue;
36 use Wikimedia\Rdbms\IConnectionProvider;
37 use Wikimedia\Rdbms\IDatabase;
38 use Wikimedia\Rdbms\IMaintainableDatabase;
39 use Wikimedia\Rdbms\IReadableDatabase;
40
41 // NOTE: MaintenanceParameters is needed in the constructor, and we may not have
42 // autoloading enabled at this point?
43 require_once __DIR__ . '/MaintenanceParameters.php';
44
45 /**
46 * Abstract maintenance class for quickly writing and churning out
47 * maintenance scripts with minimal effort. All that _must_ be defined
48 * is the execute() method. See docs/maintenance.txt for more info
49 * and a quick demo of how to use it.
50 *
51 * Terminology:
52 * params: registry of named values that may be passed to the script
53 * arg list: registry of positional values that may be passed to the script
54 * options: passed param values
55 * args: passed positional values
56 *
57 * In the command:
58 * mwscript somescript.php --foo=bar baz
59 * foo is a param
60 * bar is the option value of the option for param foo
61 * baz is the arg value at index 0 in the arg list
62 *
63 * WARNING: the constructor, MaintenanceRunner::shouldExecute(), setup(), finalSetup(),
64 * and getName() are called before Setup.php is complete, which means most of the common
65 * infrastructure, like logging or autoloading, is not available. Be careful when changing
66 * these methods or the ones called from them. Likewise, be careful with the constructor
67 * when subclassing. MediaWikiServices instance is not yet available at this point.
68 *
69 * @stable to extend
70 *
71 * @since 1.16
72 * @ingroup Maintenance
73 */
74 abstract class Maintenance {
75 /**
76 * Constants for DB access type
77 * @see Maintenance::getDbType()
78 */
79 public const DB_NONE = 0;
80 public const DB_STD = 1;
81 public const DB_ADMIN = 2;
82
83 // Const for getStdin()
84 public const STDIN_ALL = -1;
85
86 // Help group names
87 public const SCRIPT_DEPENDENT_PARAMETERS = 'Common options';
88 public const GENERIC_MAINTENANCE_PARAMETERS = 'Script runner options';
89
90 /**
91 * @var MaintenanceParameters
92 */
93 protected $parameters;
94
95 /**
96 * Empty.
97 * @deprecated since 1.39, use $this->parameters instead.
98 * @var array[]
99 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string,multiOccurrence:bool}>
100 */
101 protected $mParams = [];
102
103 /**
104 * @var array This is the list of options that were actually passed
105 * @deprecated since 1.39, use {@see addOption} instead.
106 */
107 protected $mOptions = [];
108
109 /**
110 * @var array This is the list of arguments that were actually passed
111 * @deprecated since 1.39, use {@see addArg} instead.
112 */
113 protected $mArgs = [];
114
115 /** @var string|null Name of the script currently running */
116 protected $mSelf;
117
118 /** @var bool Special vars for params that are always used */
119 protected $mQuiet = false;
120 protected ?string $mDbUser = null;
121 protected ?string $mDbPass = null;
122
123 /**
124 * @var string A description of the script, children should change this via addDescription()
125 * @deprecated since 1.39, use {@see addDescription} instead.
126 */
127 protected $mDescription = '';
128
129 /**
130 * @var bool Have we already loaded our user input?
131 * @deprecated since 1.39, treat as private to the Maintenance base class
132 */
133 protected $mInputLoaded = false;
134
135 /**
136 * Batch size. If a script supports this, they should set
137 * a default with setBatchSize()
138 *
139 * @var int|null
140 */
141 protected $mBatchSize = null;
142
143 /**
144 * Used by getDB() / setDB()
145 * @var IMaintainableDatabase|null
146 */
147 private $mDb = null;
148
149 /** @var float UNIX timestamp */
150 private $lastReplicationWait = 0.0;
151
152 /**
153 * Used when creating separate schema files.
154 * @var resource|null
155 */
156 public $fileHandle;
157
158 /** @var HookContainer|null */
159 private $hookContainer;
160
161 /** @var HookRunner|null */
162 private $hookRunner;
163
164 /**
165 * Accessible via getConfig()
166 *
167 * @var Config|null
168 */
169 private $config;
170
171 /**
172 * @see Maintenance::requireExtension
173 * @var array
174 */
175 private $requiredExtensions = [];
176
177 /**
178 * Used to read the options in the order they were passed.
179 * Useful for option chaining (Ex. dumpBackup.php). It will
180 * be an empty array if the options are passed in through
181 * loadParamsAndArgs( $self, $opts, $args ).
182 *
183 * This is an array of arrays where
184 * 0 => the option and 1 => parameter value.
185 *
186 * @deprecated since 1.39, use $this->getParameters()->getOptionsSequence() instead.
187 * @var array
188 */
189 public $orderedOptions = [];
190 private ?IConnectionProvider $dbProvider = null;
191
192 /**
193 * Default constructor. Children should call this *first* if implementing
194 * their own constructors
195 *
196 * @stable to call
197 */
198 public function __construct() {
199 $this->parameters = new MaintenanceParameters();
200 $this->mOptions =& $this->parameters->getFieldReference( 'mOptions' );
201 $this->orderedOptions =& $this->parameters->getFieldReference( 'optionsSequence' );
202 $this->mArgs =& $this->parameters->getFieldReference( 'mArgs' );
203 $this->addDefaultParams();
204 }
205
206 /**
207 * @since 1.39
208 * @return MaintenanceParameters
209 */
210 public function getParameters() {
211 return $this->parameters;
212 }
213
214 /**
215 * Do the actual work. All child classes will need to implement this
216 *
217 * @return bool|null|void True for success, false for failure. Not returning
218 * a value, or returning null, is also interpreted as success. Returning
219 * false for failure will cause doMaintenance.php to exit the process
220 * with a non-zero exit status.
221 */
222 abstract public function execute();
223
224 /**
225 * Whether this script can run without LocalSettings.php. Scripts that need to be able
226 * to run when MediaWiki has not been installed should override this to return true.
227 * Scripts that return true from this method must be able to function without
228 * a storage backend. When no LocalSettings.php file is present, any attempt to access
229 * the database will fail with a fatal error.
230 *
231 * @note Subclasses that override this method to return true should also override
232 * getDbType() to return self::DB_NONE, unless they are going to use the database
233 * connection when it is available.
234 *
235 * @see getDbType()
236 * @since 1.40
237 * @stable to override
238 * @return bool
239 */
240 public function canExecuteWithoutLocalSettings(): bool {
241 return false;
242 }
243
244 /**
245 * Checks to see if a particular option in supported. Normally this means it
246 * has been registered by the script via addOption.
247 * @param string $name The name of the option
248 * @return bool true if the option exists, false otherwise
249 */
250 protected function supportsOption( $name ) {
251 return $this->parameters->supportsOption( $name );
252 }
253
254 /**
255 * Add a parameter to the script. Will be displayed on --help
256 * with the associated description
257 *
258 * @param string $name The name of the param (help, version, etc)
259 * @param string $description The description of the param to show on --help
260 * @param bool $required Is the param required?
261 * @param bool $withArg Is an argument required with this option?
262 * @param string|bool $shortName Character to use as short name
263 * @param bool $multiOccurrence Can this option be passed multiple times?
264 */
265 protected function addOption( $name, $description, $required = false,
266 $withArg = false, $shortName = false, $multiOccurrence = false
267 ) {
268 $this->parameters->addOption(
269 $name,
270 $description,
271 $required,
272 $withArg,
273 $shortName,
274 $multiOccurrence
275 );
276 }
277
278 /**
279 * Checks to see if a particular option was set.
280 *
281 * @param string $name The name of the option
282 * @return bool
283 */
284 protected function hasOption( $name ) {
285 return $this->parameters->hasOption( $name );
286 }
287
288 /**
289 * Get an option, or return the default.
290 *
291 * If the option was added to support multiple occurrences,
292 * this will return an array.
293 *
294 * @param string $name The name of the param
295 * @param mixed|null $default Anything you want, default null
296 * @return mixed
297 * @return-taint none
298 */
299 protected function getOption( $name, $default = null ) {
300 return $this->parameters->getOption( $name, $default );
301 }
302
303 /**
304 * Add some args that are needed
305 * @param string $arg Name of the arg, like 'start'
306 * @param string $description Short description of the arg
307 * @param bool $required Is this required?
308 * @param bool $multi Does it allow multiple values? (Last arg only)
309 */
310 protected function addArg( $arg, $description, $required = true, $multi = false ) {
311 $this->parameters->addArg( $arg, $description, $required, $multi );
312 }
313
314 /**
315 * Remove an option. Useful for removing options that won't be used in your script.
316 * @param string $name The option to remove.
317 */
318 protected function deleteOption( $name ) {
319 $this->parameters->deleteOption( $name );
320 }
321
322 /**
323 * Sets whether to allow unregistered options, which are options passed to
324 * a script that do not match an expected parameter.
325 * @param bool $allow Should we allow?
326 */
327 protected function setAllowUnregisteredOptions( $allow ) {
328 $this->parameters->setAllowUnregisteredOptions( $allow );
329 }
330
331 /**
332 * Set the description text.
333 * @param string $text The text of the description
334 */
335 protected function addDescription( $text ) {
336 $this->parameters->setDescription( $text );
337 }
338
339 /**
340 * Does a given argument exist?
341 * @param int|string $argId The index (from zero) of the argument, or
342 * the name declared for the argument by addArg().
343 * @return bool
344 */
345 protected function hasArg( $argId = 0 ) {
346 return $this->parameters->hasArg( $argId );
347 }
348
349 /**
350 * Get an argument.
351 * @param int|string $argId The index (from zero) of the argument, or
352 * the name declared for the argument by addArg().
353 * @param mixed|null $default The default if it doesn't exist
354 * @return mixed
355 * @return-taint none
356 */
357 protected function getArg( $argId = 0, $default = null ) {
358 return $this->parameters->getArg( $argId, $default );
359 }
360
361 /**
362 * Get arguments.
363 * @since 1.40
364 *
365 * @param int|string $offset The index (from zero) of the first argument, or
366 * the name declared for the argument by addArg().
367 * @return string[]
368 */
369 protected function getArgs( $offset = 0 ) {
370 return $this->parameters->getArgs( $offset );
371 }
372
373 /**
374 * Get the name of an argument.
375 * @since 1.43
376 *
377 * @param int $argId The index (from zero) of the argument.
378 *
379 * @return string|null The name of the argument, or null if the argument does not exist.
380 */
381 protected function getArgName( int $argId ): ?string {
382 return $this->parameters->getArgName( $argId );
383 }
384
385 /**
386 * Programmatically set the value of the given option.
387 * Useful for setting up child scripts, see runChild().
388 *
389 * @since 1.39
390 *
391 * @param string $name
392 * @param mixed|null $value
393 */
394 public function setOption( string $name, $value ): void {
395 $this->parameters->setOption( $name, $value );
396 }
397
398 /**
399 * Programmatically set the value of the given argument.
400 * Useful for setting up child scripts, see runChild().
401 *
402 * @since 1.39
403 *
404 * @param string|int $argId Arg index or name
405 * @param mixed|null $value
406 */
407 public function setArg( $argId, $value ): void {
408 $this->parameters->setArg( $argId, $value );
409 }
410
411 /**
412 * Returns batch size
413 *
414 * @since 1.31
415 *
416 * @return int|null
417 */
418 protected function getBatchSize() {
419 return $this->mBatchSize;
420 }
421
422 /**
423 * @param int $s The number of operations to do in a batch
424 */
425 protected function setBatchSize( $s = 0 ) {
426 $this->mBatchSize = $s;
427
428 // If we support $mBatchSize, show the option.
429 // Used to be in addDefaultParams, but in order for that to
430 // work, subclasses would have to call this function in the constructor
431 // before they called parent::__construct which is just weird
432 // (and really wasn't done).
433 if ( $this->mBatchSize ) {
434 $this->addOption( 'batch-size', 'Run this many operations ' .
435 'per batch, default: ' . $this->mBatchSize, false, true );
436 if ( $this->supportsOption( 'batch-size' ) ) {
437 // This seems a little ugly...
438 $this->parameters->assignGroup( self::SCRIPT_DEPENDENT_PARAMETERS, [ 'batch-size' ] );
439 }
440 }
441 }
442
443 /**
444 * Get the script's name
445 * @return string
446 */
447 public function getName() {
448 return $this->mSelf;
449 }
450
451 /**
452 * Return input from stdin.
453 * @param int|null $len The number of bytes to read. If null, just
454 * return the handle. Maintenance::STDIN_ALL returns the full content
455 * @return mixed
456 */
457 protected function getStdin( $len = null ) {
458 if ( $len == self::STDIN_ALL ) {
459 return file_get_contents( 'php://stdin' );
460 }
461 $f = fopen( 'php://stdin', 'rt' );
462 if ( !$len ) {
463 return $f;
464 }
465 $input = fgets( $f, $len );
466 fclose( $f );
467
468 return rtrim( $input );
469 }
470
471 /**
472 * @return bool
473 */
474 public function isQuiet() {
475 return $this->mQuiet;
476 }
477
478 /**
479 * Throw some output to the user. Scripts can call this with no fears,
480 * as we handle all --quiet stuff here
481 * @stable to override
482 * @param string $out The text to show to the user
483 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
484 */
485 protected function output( $out, $channel = null ) {
486 // This is sometimes called very early, before Setup.php is included.
487 if ( defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' ) ) {
488 // Flush stats periodically in long-running CLI scripts to avoid OOM (T181385)
489 $stats = $this->getServiceContainer()->getStatsdDataFactory();
490 if ( $stats->getDataCount() > 1000 ) {
491 MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
492 }
493 }
494
495 if ( $this->mQuiet ) {
496 return;
497 }
498 if ( $channel === null ) {
499 $this->cleanupChanneled();
500 print $out;
501 } else {
502 $out = preg_replace( '/\n\z/', '', $out );
503 $this->outputChanneled( $out, $channel );
504 }
505 }
506
507 /**
508 * Throw an error to the user. Doesn't respect --quiet, so don't use
509 * this for non-error output
510 * @stable to override
511 * @param string|StatusValue $err The error to display
512 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
513 */
514 protected function error( $err, $die = 0 ) {
515 if ( intval( $die ) !== 0 ) {
516 wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
517 $this->fatalError( $err, intval( $die ) );
518 }
519 if ( $err instanceof StatusValue ) {
520 foreach ( [ 'warning' => 'Warning: ', 'error' => 'Error: ' ] as $type => $prefix ) {
521 foreach ( $err->getMessages( $type ) as $msg ) {
522 $this->error(
523 $prefix . wfMessage( $msg )
524 ->inLanguage( 'en' )
525 ->useDatabase( false )
526 ->text()
527 );
528 }
529 }
530 return;
531 }
532 $this->outputChanneled( false );
533 if (
534 ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
535 !defined( 'MW_PHPUNIT_TEST' )
536 ) {
537 fwrite( STDERR, $err . "\n" );
538 } else {
539 print $err . "\n";
540 }
541 }
542
543 /**
544 * Output a message and terminate the current script.
545 *
546 * @stable to override
547 * @param string|StatusValue $msg Error message
548 * @param int $exitCode PHP exit status. Should be in range 1-254.
549 * @since 1.31
550 * @return never
551 */
552 protected function fatalError( $msg, $exitCode = 1 ) {
553 $this->error( $msg );
554 // If running PHPUnit tests we don't want to call exit, as it will end the test suite early.
555 // Instead, throw an exception that will still cause the relevant test to fail if the ::fatalError
556 // call was not expected.
557 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
558 throw new MaintenanceFatalError( $exitCode );
559 } else {
560 exit( $exitCode );
561 }
562 }
563
564 /** @var bool */
565 private $atLineStart = true;
566 /** @var string|null */
567 private $lastChannel = null;
568
569 /**
570 * Clean up channeled output. Output a newline if necessary.
571 */
572 public function cleanupChanneled() {
573 if ( !$this->atLineStart ) {
574 print "\n";
575 $this->atLineStart = true;
576 }
577 }
578
579 /**
580 * Message outputter with channeled message support. Messages on the
581 * same channel are concatenated, but any intervening messages in another
582 * channel start a new line.
583 * @param string|false $msg The message without trailing newline
584 * @param string|null $channel Channel identifier or null for no
585 * channel. Channel comparison uses ===.
586 */
587 public function outputChanneled( $msg, $channel = null ) {
588 if ( $msg === false ) {
589 $this->cleanupChanneled();
590
591 return;
592 }
593
594 // End the current line if necessary
595 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
596 print "\n";
597 }
598
599 print $msg;
600
601 $this->atLineStart = false;
602 if ( $channel === null ) {
603 // For unchanneled messages, output trailing newline immediately
604 print "\n";
605 $this->atLineStart = true;
606 }
607 $this->lastChannel = $channel;
608 }
609
610 /**
611 * Does the script need different DB access? By default, we give Maintenance
612 * scripts normal rights to the DB. Sometimes, a script needs admin rights
613 * access for a reason and sometimes they want no access. Subclasses should
614 * override and return one of the following values, as needed:
615 * Maintenance::DB_NONE - For no DB access at all
616 * Maintenance::DB_STD - For normal DB access, default
617 * Maintenance::DB_ADMIN - For admin DB access
618 *
619 * @note Subclasses that override this method to return self::DB_NONE should
620 * also override canExecuteWithoutLocalSettings() to return true, unless they
621 * need the wiki to be set up for reasons beyond access to a database connection.
622 *
623 * @see canExecuteWithoutLocalSettings()
624 * @stable to override
625 * @return int
626 */
627 public function getDbType() {
628 return self::DB_STD;
629 }
630
631 /**
632 * Add the default parameters to the scripts
633 */
634 protected function addDefaultParams() {
635 # Generic (non-script-dependent) options:
636
637 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
638 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
639
640 # Save generic options to display them separately in help
641 $generic = [ 'help', 'quiet' ];
642 $this->parameters->assignGroup( self::GENERIC_MAINTENANCE_PARAMETERS, $generic );
643
644 # Script-dependent options:
645
646 // If we support a DB, show the options
647 if ( $this->getDbType() > 0 ) {
648 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
649 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
650 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
651 }
652
653 # Save additional script-dependent options to display
654 # them separately in help
655 $dependent = array_diff(
656 $this->parameters->getOptionNames(),
657 $generic
658 );
659 $this->parameters->assignGroup( self::SCRIPT_DEPENDENT_PARAMETERS, $dependent );
660 }
661
662 /**
663 * @since 1.24
664 * @stable to override
665 * @return Config
666 */
667 public function getConfig() {
668 if ( $this->config === null ) {
669 $this->config = $this->getServiceContainer()->getMainConfig();
670 }
671
672 return $this->config;
673 }
674
675 /**
676 * Returns the main service container.
677 *
678 * @since 1.40
679 * @return MediaWikiServices
680 */
681 protected function getServiceContainer() {
682 return MediaWikiServices::getInstance();
683 }
684
685 /**
686 * @since 1.24
687 * @param Config $config
688 */
689 public function setConfig( Config $config ) {
690 $this->config = $config;
691 }
692
693 /**
694 * Indicate that the specified extension must be
695 * loaded before the script can run.
696 *
697 * This *must* be called in the constructor.
698 *
699 * @since 1.28
700 * @param string $name
701 */
702 protected function requireExtension( $name ) {
703 $this->requiredExtensions[] = $name;
704 }
705
706 /**
707 * Verify that the required extensions are installed
708 *
709 * @since 1.28
710 */
711 public function checkRequiredExtensions() {
712 $registry = ExtensionRegistry::getInstance();
713 $missing = [];
714 foreach ( $this->requiredExtensions as $name ) {
715 if ( !$registry->isLoaded( $name ) ) {
716 $missing[] = $name;
717 }
718 }
719
720 if ( $missing ) {
721 if ( count( $missing ) === 1 ) {
722 $msg = 'The "' . $missing[ 0 ] . '" extension must be installed for this script to run. '
723 . 'Please enable it and then try again.';
724 } else {
725 $msg = 'The following extensions must be installed for this script to run: "'
726 . implode( '", "', $missing ) . '". Please enable them and then try again.';
727 }
728 $this->fatalError( $msg );
729 }
730 }
731
732 /**
733 * Returns an instance of the given maintenance script, with all of the current arguments
734 * passed to it.
735 *
736 * Callers are expected to run the returned maintenance script instance by calling {@link Maintenance::execute}
737 *
738 * @deprecated Since 1.43. Use {@link Maintenance::createChild} instead. This method is an alias to that method.
739 * @param string $maintClass A name of a child maintenance class
740 * @param string|null $classFile Full path of where the child is
741 * @return Maintenance The created instance, which the caller is expected to run by calling
742 * {@link Maintenance::execute} on the returned object.
743 */
744 public function runChild( $maintClass, $classFile = null ) {
745 MWDebug::detectDeprecatedOverride( $this, __CLASS__, 'runChild', '1.43' );
746 return self::createChild( $maintClass, $classFile );
747 }
748
749 /**
750 * Returns an instance of the given maintenance script, with all of the current arguments
751 * passed to it.
752 *
753 * Callers are expected to run the returned maintenance script instance by calling {@link Maintenance::execute}
754 *
755 * @param string $maintClass A name of a child maintenance class
756 * @param string|null $classFile Full path of where the child is
757 * @stable to override
758 * @return Maintenance The created instance, which the caller is expected to run by calling
759 * {@link Maintenance::execute} on the returned object.
760 */
761 public function createChild( string $maintClass, ?string $classFile = null ): Maintenance {
762 // Make sure the class is loaded first
763 if ( !class_exists( $maintClass ) ) {
764 if ( $classFile ) {
765 require_once $classFile;
766 }
767 if ( !class_exists( $maintClass ) ) {
768 $this->fatalError( "Cannot spawn child: $maintClass" );
769 }
770 }
771
772 /**
773 * @var Maintenance $child
774 */
775 $child = new $maintClass();
776 $child->loadParamsAndArgs(
777 $this->mSelf,
778 $this->parameters->getOptions(),
779 $this->parameters->getArgs()
780 );
781 if ( $this->mDb !== null ) {
782 $child->setDB( $this->mDb );
783 }
784 if ( $this->dbProvider !== null ) {
785 $child->setDBProvider( $this->dbProvider );
786 }
787
788 return $child;
789 }
790
791 /**
792 * Provides subclasses with an opportunity to perform initial checks.
793 * @stable to override
794 */
795 public function setup() {
796 // noop
797 }
798
799 /**
800 * Normally we disable the memory_limit when running admin scripts.
801 * Some scripts may wish to actually set a limit, however, to avoid
802 * blowing up unexpectedly.
803 * @stable to override
804 * @return string
805 */
806 public function memoryLimit() {
807 return 'max';
808 }
809
810 /**
811 * Clear all params and arguments.
812 */
813 public function clearParamsAndArgs() {
814 $this->parameters->clear();
815 $this->mInputLoaded = false;
816 }
817
818 /**
819 * @since 1.40
820 * @internal
821 * @param string $name
822 */
823 public function setName( string $name ) {
824 $this->mSelf = $name;
825 $this->parameters->setName( $this->mSelf );
826 }
827
828 /**
829 * Load params and arguments from a given array
830 * of command-line arguments
831 *
832 * @since 1.27
833 * @param array $argv The argument array, not including the script itself.
834 */
835 public function loadWithArgv( $argv ) {
836 if ( $this->mDescription ) {
837 $this->parameters->setDescription( $this->mDescription );
838 }
839
840 $this->parameters->loadWithArgv( $argv );
841
842 if ( $this->parameters->hasErrors() ) {
843 $errors = "\nERROR: " . implode( "\nERROR: ", $this->parameters->getErrors() ) . "\n";
844 $this->error( $errors );
845 $this->maybeHelp( true );
846 }
847
848 $this->loadSpecialVars();
849 $this->mInputLoaded = true;
850 }
851
852 /**
853 * Process command line arguments when running as a child script
854 *
855 * @param string|null $self The name of the script, if any
856 * @param array|null $opts An array of options, in form of key=>value
857 * @param array|null $args An array of command line arguments
858 */
859 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
860 # If we were given opts or args, set those and return early
861 if ( $self !== null || $opts !== null || $args !== null ) {
862 if ( $self !== null ) {
863 $this->mSelf = $self;
864 $this->parameters->setName( $self );
865 }
866 $this->parameters->setOptionsAndArgs( $opts ?? [], $args ?? [] );
867 $this->mInputLoaded = true;
868 }
869
870 # If we've already loaded input (either by user values or from $argv)
871 # skip on loading it again.
872 if ( $this->mInputLoaded ) {
873 $this->loadSpecialVars();
874
875 return;
876 }
877
878 global $argv;
879 $this->mSelf = $argv[0];
880 $this->parameters->setName( $this->mSelf );
881 $this->loadWithArgv( array_slice( $argv, 1 ) );
882 }
883
884 /**
885 * Run some validation checks on the params, etc
886 * @stable to override
887 */
888 public function validateParamsAndArgs() {
889 $valid = $this->parameters->validate();
890
891 $this->maybeHelp( !$valid );
892 }
893
894 /**
895 * Handle the special variables that are global to all scripts
896 * @stable to override
897 */
898 protected function loadSpecialVars() {
899 if ( $this->hasOption( 'dbuser' ) ) {
900 $this->mDbUser = $this->getOption( 'dbuser' );
901 }
902 if ( $this->hasOption( 'dbpass' ) ) {
903 $this->mDbPass = $this->getOption( 'dbpass' );
904 }
905 if ( $this->hasOption( 'quiet' ) ) {
906 $this->mQuiet = true;
907 }
908 if ( $this->hasOption( 'batch-size' ) ) {
909 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
910 }
911 }
912
913 /**
914 * Maybe show the help. If the help is shown, exit.
915 *
916 * @param bool $force Whether to force the help to show, default false
917 */
918 protected function maybeHelp( $force = false ) {
919 if ( !$force && !$this->hasOption( 'help' ) ) {
920 return;
921 }
922
923 if ( $this->parameters->hasErrors() && !$this->hasOption( 'help' ) ) {
924 $errors = "\nERROR: " . implode( "\nERROR: ", $this->parameters->getErrors() ) . "\n";
925 $this->error( $errors );
926 }
927
928 $this->showHelp();
929 $this->fatalError( '' );
930 }
931
932 /**
933 * Definitely show the help. Does not exit.
934 */
935 protected function showHelp() {
936 $this->mQuiet = false;
937 $help = $this->parameters->getHelp();
938 $this->output( $help );
939 }
940
941 /**
942 * Handle some last-minute setup here.
943 *
944 * @stable to override
945 *
946 * @param SettingsBuilder $settingsBuilder
947 */
948 public function finalSetup( SettingsBuilder $settingsBuilder ) {
949 $config = $settingsBuilder->getConfig();
950 $overrides = [];
951 $overrides['DBadminuser'] = $config->get( MainConfigNames::DBadminuser );
952 $overrides['DBadminpassword'] = $config->get( MainConfigNames::DBadminpassword );
953
954 # Turn off output buffering again, it might have been turned on in the settings files
955 if ( ob_get_level() ) {
956 ob_end_flush();
957 }
958
959 # Override $wgServer
960 if ( $this->hasOption( 'server' ) ) {
961 $overrides['Server'] = $this->getOption( 'server', $config->get( MainConfigNames::Server ) );
962 }
963
964 # If these were passed, use them
965 if ( $this->mDbUser ) {
966 $overrides['DBadminuser'] = $this->mDbUser;
967 }
968 if ( $this->mDbPass ) {
969 $overrides['DBadminpassword'] = $this->mDbPass;
970 }
971 if ( $this->hasOption( 'dbgroupdefault' ) ) {
972 $overrides['DBDefaultGroup'] = $this->getOption( 'dbgroupdefault', null );
973 // TODO: once MediaWikiServices::getInstance() starts throwing exceptions
974 // and not deprecation warnings for premature access to service container,
975 // we can remove this line. This method is called before Setup.php,
976 // so it would be guaranteed DBLoadBalancerFactory is not yet initialized.
977 if ( MediaWikiServices::hasInstance() ) {
978 $service = $this->getServiceContainer()->peekService( 'DBLoadBalancerFactory' );
979 if ( $service ) {
980 $service->destroy();
981 }
982 }
983 }
984
985 if ( $this->getDbType() == self::DB_ADMIN && isset( $overrides[ 'DBadminuser' ] ) ) {
986 $overrides['DBuser'] = $overrides[ 'DBadminuser' ];
987 $overrides['DBpassword'] = $overrides[ 'DBadminpassword' ];
988
989 /** @var array $dbServers */
990 $dbServers = $config->get( MainConfigNames::DBservers );
991 if ( $dbServers ) {
992 foreach ( $dbServers as $i => $server ) {
993 $dbServers[$i]['user'] = $overrides['DBuser'];
994 $dbServers[$i]['password'] = $overrides['DBpassword'];
995 }
996 $overrides['DBservers'] = $dbServers;
997 }
998
999 $lbFactoryConf = $config->get( MainConfigNames::LBFactoryConf );
1000 if ( isset( $lbFactoryConf['serverTemplate'] ) ) {
1001 $lbFactoryConf['serverTemplate']['user'] = $overrides['DBuser'];
1002 $lbFactoryConf['serverTemplate']['password'] = $overrides['DBpassword'];
1003 $overrides['LBFactoryConf'] = $lbFactoryConf;
1004 }
1005
1006 // TODO: once MediaWikiServices::getInstance() starts throwing exceptions
1007 // and not deprecation warnings for premature access to service container,
1008 // we can remove this line. This method is called before Setup.php,
1009 // so it would be guaranteed DBLoadBalancerFactory is not yet initialized.
1010 if ( MediaWikiServices::hasInstance() ) {
1011 $service = $this->getServiceContainer()->peekService( 'DBLoadBalancerFactory' );
1012 if ( $service ) {
1013 $service->destroy();
1014 }
1015 }
1016 }
1017
1018 $this->afterFinalSetup();
1019
1020 $overrides['ShowExceptionDetails'] = true;
1021 $overrides['ShowHostname'] = true;
1022
1023 ini_set( 'max_execution_time', '0' );
1024 $settingsBuilder->putConfigValues( $overrides );
1025 }
1026
1027 /**
1028 * Override to perform any required operation at the end of initialisation
1029 * @stable to override
1030 */
1031 protected function afterFinalSetup() {
1032 }
1033
1034 /**
1035 * Support function for cleaning up redundant text records
1036 * @param bool $delete Whether or not to actually delete the records
1037 * @author Rob Church <[email protected]>
1038 */
1039 public function purgeRedundantText( $delete = true ) {
1040 # Data should come off the master, wrapped in a transaction
1041 $dbw = $this->getPrimaryDB();
1042 $this->beginTransaction( $dbw, __METHOD__ );
1043
1044 # Get "active" text records via the content table
1045 $cur = [];
1046 $this->output( 'Searching for active text records via contents table...' );
1047 $res = $dbw->newSelectQueryBuilder()
1048 ->select( 'content_address' )
1049 ->distinct()
1050 ->from( 'content' )
1051 ->caller( __METHOD__ )->fetchResultSet();
1052 $blobStore = $this->getServiceContainer()->getBlobStore();
1053 foreach ( $res as $row ) {
1054 // @phan-suppress-next-line PhanUndeclaredMethod
1055 $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1056 if ( $textId ) {
1057 $cur[] = $textId;
1058 }
1059 }
1060 $this->output( "done.\n" );
1061
1062 # Get the IDs of all text records not in these sets
1063 $this->output( 'Searching for inactive text records...' );
1064 $textTableQueryBuilder = $dbw->newSelectQueryBuilder()
1065 ->select( 'old_id' )
1066 ->distinct()
1067 ->from( 'text' );
1068 if ( count( $cur ) ) {
1069 $textTableQueryBuilder->where( $dbw->expr( 'old_id', '!=', $cur ) );
1070 }
1071 $res = $textTableQueryBuilder
1072 ->caller( __METHOD__ )
1073 ->fetchResultSet();
1074 $old = [];
1075 foreach ( $res as $row ) {
1076 $old[] = $row->old_id;
1077 }
1078 $this->output( "done.\n" );
1079
1080 # Inform the user of what we're going to do
1081 $count = count( $old );
1082 $this->output( "$count inactive items found.\n" );
1083
1084 # Delete as appropriate
1085 if ( $delete && $count ) {
1086 $this->output( 'Deleting...' );
1087 $dbw->newDeleteQueryBuilder()
1088 ->deleteFrom( 'text' )
1089 ->where( [ 'old_id' => $old ] )
1090 ->caller( __METHOD__ )
1091 ->execute();
1092 $this->output( "done.\n" );
1093 }
1094
1095 $this->commitTransaction( $dbw, __METHOD__ );
1096 }
1097
1098 /**
1099 * Get the maintenance directory.
1100 * @return string
1101 */
1102 protected function getDir() {
1103 return __DIR__ . '/../';
1104 }
1105
1106 /**
1107 * Returns a database to be used by current maintenance script.
1108 *
1109 * This uses the main LBFactory instance by default unless overriden via setDB().
1110 *
1111 * This function has the same parameters as LoadBalancer::getConnection().
1112 *
1113 * For simple cases, use ::getReplicaDB() or ::getPrimaryDB() instead.
1114 *
1115 * @stable to override
1116 *
1117 * @param int $db DB index (DB_REPLICA/DB_PRIMARY)
1118 * @param string|string[] $groups default: empty array
1119 * @param string|bool $dbDomain default: current wiki
1120 * @return IMaintainableDatabase
1121 */
1122 protected function getDB( $db, $groups = [], $dbDomain = false ) {
1123 if ( $this->mDb === null ) {
1124 return $this->getServiceContainer()
1125 ->getDBLoadBalancerFactory()
1126 ->getMainLB( $dbDomain )
1127 ->getMaintenanceConnectionRef( $db, $groups, $dbDomain );
1128 }
1129
1130 return $this->mDb;
1131 }
1132
1133 /**
1134 * Sets database object to be returned by getDB().
1135 * @stable to override
1136 *
1137 * @param IMaintainableDatabase $db
1138 */
1139 public function setDB( IMaintainableDatabase $db ) {
1140 $this->mDb = $db;
1141 }
1142
1143 /**
1144 * @return IReadableDatabase
1145 * @since 1.42
1146 */
1147 protected function getReplicaDB(): IReadableDatabase {
1148 if ( $this->dbProvider === null ) {
1149 $this->dbProvider = $this->getServiceContainer()->getConnectionProvider();
1150 }
1151 return $this->dbProvider->getReplicaDatabase();
1152 }
1153
1154 /**
1155 * @return IDatabase
1156 * @since 1.42
1157 */
1158 protected function getPrimaryDB(): IDatabase {
1159 if ( $this->dbProvider === null ) {
1160 $this->dbProvider = $this->getServiceContainer()->getConnectionProvider();
1161 }
1162 return $this->dbProvider->getPrimaryDatabase();
1163 }
1164
1165 /**
1166 * @internal
1167 * @param IConnectionProvider $dbProvider
1168 * @return void
1169 */
1170 public function setDBProvider( IConnectionProvider $dbProvider ) {
1171 $this->dbProvider = $dbProvider;
1172 }
1173
1174 /**
1175 * Begin a transaction on a DB
1176 *
1177 * This method makes it clear that begin() is called from a maintenance script,
1178 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1179 *
1180 * @param IDatabase $dbw
1181 * @param string $fname Caller name
1182 * @since 1.27
1183 */
1184 protected function beginTransaction( IDatabase $dbw, $fname ) {
1185 $dbw->begin( $fname );
1186 }
1187
1188 /**
1189 * Commit the transaction on a DB handle and wait for replica DBs to catch up
1190 *
1191 * This method makes it clear that commit() is called from a maintenance script,
1192 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1193 *
1194 * @param IDatabase $dbw
1195 * @param string $fname Caller name
1196 * @return bool Whether the replica DB wait succeeded
1197 * @since 1.27
1198 */
1199 protected function commitTransaction( IDatabase $dbw, $fname ) {
1200 $dbw->commit( $fname );
1201 return $this->waitForReplication();
1202 }
1203
1204 /**
1205 * Wait for replica DBs to catch up.
1206 *
1207 * @note Since 1.39, this also calls LBFactory::autoReconfigure().
1208 *
1209 * @return bool Whether the replica DB wait succeeded
1210 * @since 1.36
1211 */
1212 protected function waitForReplication() {
1213 $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
1214 $waitSucceeded = $lbFactory->waitForReplication(
1215 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1216 );
1217 $this->lastReplicationWait = microtime( true );
1218
1219 // If possible, apply changes to the database configuration.
1220 // The primary use case for this is taking replicas out of rotation.
1221 // Long-running scripts may otherwise keep connections to
1222 // de-pooled database hosts, and may even re-connect to them.
1223 // If no config callback was configured, this has no effect.
1224 $lbFactory->autoReconfigure();
1225
1226 return $waitSucceeded;
1227 }
1228
1229 /**
1230 * Rollback the transaction on a DB handle
1231 *
1232 * This method makes it clear that rollback() is called from a maintenance script,
1233 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1234 *
1235 * @param IDatabase $dbw
1236 * @param string $fname Caller name
1237 * @since 1.27
1238 */
1239 protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1240 $dbw->rollback( $fname );
1241 }
1242
1243 /**
1244 * Count down from $seconds to zero on the terminal, with a one-second pause
1245 * between showing each number. If the maintenance script is in quiet mode,
1246 * this function does nothing.
1247 *
1248 * @since 1.31
1249 *
1250 * @codeCoverageIgnore
1251 * @param int $seconds
1252 */
1253 protected function countDown( $seconds ) {
1254 if ( $this->isQuiet() ) {
1255 return;
1256 }
1257 for ( $i = $seconds; $i >= 0; $i-- ) {
1258 if ( $i != $seconds ) {
1259 $this->output( str_repeat( "\x08", strlen( (string)( $i + 1 ) ) ) );
1260 }
1261 $this->output( (string)$i );
1262 if ( $i ) {
1263 sleep( 1 );
1264 }
1265 }
1266 $this->output( "\n" );
1267 }
1268
1269 /**
1270 * Wrapper for posix_isatty()
1271 * We default as considering stdin a tty (for nice readline methods)
1272 * but treating stout as not a tty to avoid color codes
1273 *
1274 * @param mixed $fd File descriptor
1275 * @return bool
1276 */
1277 public static function posix_isatty( $fd ) {
1278 if ( !function_exists( 'posix_isatty' ) ) {
1279 return !$fd;
1280 }
1281
1282 return posix_isatty( $fd );
1283 }
1284
1285 /**
1286 * Prompt the console for input
1287 * @param string $prompt What to begin the line with, like '> '
1288 * @return string|false Response
1289 */
1290 public static function readconsole( $prompt = '> ' ) {
1291 static $isatty = null;
1292 $isatty ??= self::posix_isatty( 0 /*STDIN*/ );
1293
1294 if ( $isatty && function_exists( 'readline' ) ) {
1295 return readline( $prompt );
1296 }
1297
1298 if ( $isatty ) {
1299 $st = self::readlineEmulation( $prompt );
1300 } elseif ( feof( STDIN ) ) {
1301 $st = false;
1302 } else {
1303 $st = fgets( STDIN, 1024 );
1304 }
1305 if ( $st === false ) {
1306 return false;
1307 }
1308
1309 return trim( $st );
1310 }
1311
1312 /**
1313 * Emulate readline()
1314 * @param string $prompt What to begin the line with, like '> '
1315 * @return string|false
1316 */
1317 private static function readlineEmulation( $prompt ) {
1318 $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1319 if ( !wfIsWindows() && $bash ) {
1320 $encPrompt = Shell::escape( $prompt );
1321 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1322 $result = Shell::command( $bash, '-c', $command )
1323 ->passStdin()
1324 ->forwardStderr()
1325 ->execute();
1326
1327 if ( $result->getExitCode() == 0 ) {
1328 return $result->getStdout();
1329 }
1330
1331 if ( $result->getExitCode() == 127 ) {
1332 // Couldn't execute bash even though we thought we saw it.
1333 // Shell probably spit out an error message, sorry :(
1334 // Fall through to fgets()...
1335 } else {
1336 // EOF/ctrl+D
1337 return false;
1338 }
1339 }
1340
1341 // Fallback... we'll have no editing controls, EWWW
1342 if ( feof( STDIN ) ) {
1343 return false;
1344 }
1345 print $prompt;
1346
1347 return fgets( STDIN, 1024 );
1348 }
1349
1350 /**
1351 * Get the terminal size as a two-element array where the first element
1352 * is the width (number of columns) and the second element is the height
1353 * (number of rows).
1354 *
1355 * @return array
1356 */
1357 public static function getTermSize() {
1358 static $termSize = null;
1359
1360 if ( $termSize !== null ) {
1361 return $termSize;
1362 }
1363
1364 $default = [ 80, 50 ];
1365
1366 if ( wfIsWindows() || Shell::isDisabled() ) {
1367 $termSize = $default;
1368
1369 return $termSize;
1370 }
1371
1372 // It's possible to get the screen size with VT-100 terminal escapes,
1373 // but reading the responses is not possible without setting raw mode
1374 // (unless you want to require the user to press enter), and that
1375 // requires an ioctl(), which we can't do. So we have to shell out to
1376 // something that can do the relevant syscalls. There are a few
1377 // options. Linux and Mac OS X both have "stty size" which does the
1378 // job directly.
1379 $result = Shell::command( 'stty', 'size' )->passStdin()->execute();
1380 if ( $result->getExitCode() !== 0 ||
1381 !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m )
1382 ) {
1383 $termSize = $default;
1384
1385 return $termSize;
1386 }
1387
1388 $termSize = [ intval( $m[2] ), intval( $m[1] ) ];
1389
1390 return $termSize;
1391 }
1392
1393 /**
1394 * Call this to set up the autoloader to allow classes to be used from the
1395 * tests directory.
1396 *
1397 * @deprecated since 1.41. Set the MW_AUTOLOAD_TEST_CLASSES in file scope instead.
1398 */
1399 public static function requireTestsAutoloader() {
1400 require_once __DIR__ . '/../../tests/common/TestsAutoLoader.php';
1401 }
1402
1403 /**
1404 * Get a HookContainer, for running extension hooks or for hook metadata.
1405 *
1406 * @since 1.35
1407 * @return HookContainer
1408 */
1409 protected function getHookContainer() {
1410 if ( !$this->hookContainer ) {
1411 $this->hookContainer = $this->getServiceContainer()->getHookContainer();
1412 }
1413 return $this->hookContainer;
1414 }
1415
1416 /**
1417 * Get a HookRunner for running core hooks.
1418 *
1419 * @internal This is for use by core only. Hook interfaces may be removed
1420 * without notice.
1421 * @since 1.35
1422 * @return HookRunner
1423 */
1424 protected function getHookRunner() {
1425 if ( !$this->hookRunner ) {
1426 $this->hookRunner = new HookRunner( $this->getHookContainer() );
1427 }
1428 return $this->hookRunner;
1429 }
1430
1431 /**
1432 * Utility function to parse a string (perhaps from a command line option)
1433 * into a list of integers (perhaps some kind of numeric IDs).
1434 *
1435 * @since 1.35
1436 *
1437 * @param string $text
1438 *
1439 * @return int[]
1440 */
1441 protected function parseIntList( $text ) {
1442 $ids = preg_split( '/[\s,;:|]+/', $text );
1443 $ids = array_map(
1444 static function ( $id ) {
1445 return (int)$id;
1446 },
1447 $ids
1448 );
1449 return array_filter( $ids );
1450 }
1451
1452 /**
1453 * @param string $errorMsg Error message to be displayed if neither --user or --userid are passed.
1454 *
1455 * @since 1.37
1456 *
1457 * @return User
1458 */
1459 protected function validateUserOption( $errorMsg ) {
1460 if ( $this->hasOption( "user" ) ) {
1461 $user = User::newFromName( $this->getOption( 'user' ) );
1462 } elseif ( $this->hasOption( "userid" ) ) {
1463 $user = User::newFromId( $this->getOption( 'userid' ) );
1464 } else {
1465 $this->fatalError( $errorMsg );
1466 }
1467 if ( !$user || !$user->isRegistered() ) {
1468 if ( $this->hasOption( "user" ) ) {
1469 $this->fatalError( "No such user: " . $this->getOption( 'user' ) );
1470 } elseif ( $this->hasOption( "userid" ) ) {
1471 $this->fatalError( "No such user id: " . $this->getOption( 'userid' ) );
1472 }
1473 }
1474
1475 return $user;
1476 }
1477
1478 /**
1479 * @param string $prompt The prompt to display to the user
1480 * @param string|null $default The default value to return if the user just presses enter
1481 *
1482 * @return string|null
1483 *
1484 * @since 1.43
1485 */
1486 protected function prompt( string $prompt, ?string $default = null ): ?string {
1487 $defaultText = $default === null ? ' > ' : " [{$default}] > ";
1488 $promptWithDefault = $prompt . $defaultText;
1489 $line = self::readconsole( $promptWithDefault );
1490 if ( $line === false ) {
1491 return $default;
1492 }
1493 if ( $line === '' ) {
1494 return $default;
1495 }
1496
1497 return $line;
1498 }
1499 }
1500
1501 /** @deprecated class alias since 1.43 */
1502 class_alias( Maintenance::class, 'Maintenance' );