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