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