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