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