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