3476a32a6a260fa3c2879f33f830d2ce47176cd7
[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 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 $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
866 }
867 } elseif ( $arg == '-' ) {
868 # Lonely "-", often used to indicate stdin or stdout.
869 $args[] = $arg;
870 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
871 # Short options
872 $argLength = strlen( $arg );
873 for ( $p = 1; $p < $argLength; $p++ ) {
874 $option = $arg[$p];
875 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
876 $option = $this->mShortParamsMap[$option];
877 }
878
879 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
880 $param = next( $argv );
881 if ( $param === false ) {
882 $this->error( "\nERROR: $option parameter needs a value after it\n" );
883 $this->maybeHelp( true );
884 }
885 $this->setParam( $options, $option, $param );
886 } else {
887 $this->setParam( $options, $option, 1 );
888 }
889 }
890 } else {
891 $args[] = $arg;
892 }
893 }
894
895 $this->mOptions = $options;
896 $this->mArgs = $args;
897 $this->loadSpecialVars();
898 $this->mInputLoaded = true;
899 }
900
901 /**
902 * Helper function used solely by loadParamsAndArgs
903 * to prevent code duplication
904 *
905 * This sets the param in the options array based on
906 * whether or not it can be specified multiple times.
907 *
908 * @since 1.27
909 * @param array $options
910 * @param string $option
911 * @param mixed $value
912 */
913 private function setParam( &$options, $option, $value ) {
914 $this->orderedOptions[] = [ $option, $value ];
915
916 if ( isset( $this->mParams[$option] ) ) {
917 $multi = $this->mParams[$option]['multiOccurrence'];
918 } else {
919 $multi = false;
920 }
921 $exists = array_key_exists( $option, $options );
922 if ( $multi && $exists ) {
923 $options[$option][] = $value;
924 } elseif ( $multi ) {
925 $options[$option] = [ $value ];
926 } elseif ( !$exists ) {
927 $options[$option] = $value;
928 } else {
929 $this->error( "\nERROR: $option parameter given twice\n" );
930 $this->maybeHelp( true );
931 }
932 }
933
934 /**
935 * Process command line arguments
936 * $mOptions becomes an array with keys set to the option names
937 * $mArgs becomes a zero-based array containing the non-option arguments
938 *
939 * @param string|null $self The name of the script, if any
940 * @param array|null $opts An array of options, in form of key=>value
941 * @param array|null $args An array of command line arguments
942 */
943 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
944 # If we were given opts or args, set those and return early
945 if ( $self ) {
946 $this->mSelf = $self;
947 $this->mInputLoaded = true;
948 }
949 if ( $opts ) {
950 $this->mOptions = $opts;
951 $this->mInputLoaded = true;
952 }
953 if ( $args ) {
954 $this->mArgs = $args;
955 $this->mInputLoaded = true;
956 }
957
958 # If we've already loaded input (either by user values or from $argv)
959 # skip on loading it again. The array_shift() will corrupt values if
960 # it's run again and again
961 if ( $this->mInputLoaded ) {
962 $this->loadSpecialVars();
963
964 return;
965 }
966
967 global $argv;
968 $this->mSelf = $argv[0];
969 $this->loadWithArgv( array_slice( $argv, 1 ) );
970 }
971
972 /**
973 * Run some validation checks on the params, etc
974 */
975 protected function validateParamsAndArgs() {
976 $die = false;
977 # Check to make sure we've got all the required options
978 foreach ( $this->mParams as $opt => $info ) {
979 if ( $info['require'] && !$this->hasOption( $opt ) ) {
980 $this->error( "Param $opt required!" );
981 $die = true;
982 }
983 }
984 # Check arg list too
985 foreach ( $this->mArgList as $k => $info ) {
986 if ( $info['require'] && !$this->hasArg( $k ) ) {
987 $this->error( 'Argument <' . $info['name'] . '> required!' );
988 $die = true;
989 }
990 }
991 if ( !$this->mAllowUnregisteredOptions ) {
992 # Check for unexpected options
993 foreach ( $this->mOptions as $opt => $val ) {
994 if ( !$this->supportsOption( $opt ) ) {
995 $this->error( "Unexpected option $opt!" );
996 $die = true;
997 }
998 }
999 }
1000
1001 if ( $die ) {
1002 $this->maybeHelp( true );
1003 }
1004 }
1005
1006 /**
1007 * Handle the special variables that are global to all scripts
1008 */
1009 protected function loadSpecialVars() {
1010 if ( $this->hasOption( 'dbuser' ) ) {
1011 $this->mDbUser = $this->getOption( 'dbuser' );
1012 }
1013 if ( $this->hasOption( 'dbpass' ) ) {
1014 $this->mDbPass = $this->getOption( 'dbpass' );
1015 }
1016 if ( $this->hasOption( 'quiet' ) ) {
1017 $this->mQuiet = true;
1018 }
1019 if ( $this->hasOption( 'batch-size' ) ) {
1020 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1021 }
1022 }
1023
1024 /**
1025 * Maybe show the help.
1026 * @param bool $force Whether to force the help to show, default false
1027 */
1028 protected function maybeHelp( $force = false ) {
1029 if ( !$force && !$this->hasOption( 'help' ) ) {
1030 return;
1031 }
1032
1033 $screenWidth = 80; // TODO: Calculate this!
1034 $tab = " ";
1035 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1036
1037 ksort( $this->mParams );
1038 $this->mQuiet = false;
1039
1040 // Description ...
1041 if ( $this->mDescription ) {
1042 $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1043 }
1044 $output = "\nUsage: php " . basename( $this->mSelf );
1045
1046 // ... append parameters ...
1047 if ( $this->mParams ) {
1048 $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1049 }
1050
1051 // ... and append arguments.
1052 if ( $this->mArgList ) {
1053 $output .= ' ';
1054 foreach ( $this->mArgList as $k => $arg ) {
1055 if ( $arg['require'] ) {
1056 $output .= '<' . $arg['name'] . '>';
1057 } else {
1058 $output .= '[' . $arg['name'] . ']';
1059 }
1060 if ( $k < count( $this->mArgList ) - 1 ) {
1061 $output .= ' ';
1062 }
1063 }
1064 }
1065 $this->output( "$output\n\n" );
1066
1067 # TODO abstract some repetitive code below
1068
1069 // Generic parameters
1070 $this->output( "Generic maintenance parameters:\n" );
1071 foreach ( $this->mGenericParameters as $par => $info ) {
1072 if ( $info['shortName'] !== false ) {
1073 $par .= " (-{$info['shortName']})";
1074 }
1075 $this->output(
1076 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1077 "\n$tab$tab" ) . "\n"
1078 );
1079 }
1080 $this->output( "\n" );
1081
1082 $scriptDependantParams = $this->mDependantParameters;
1083 if ( count( $scriptDependantParams ) > 0 ) {
1084 $this->output( "Script dependant parameters:\n" );
1085 // Parameters description
1086 foreach ( $scriptDependantParams as $par => $info ) {
1087 if ( $info['shortName'] !== false ) {
1088 $par .= " (-{$info['shortName']})";
1089 }
1090 $this->output(
1091 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1092 "\n$tab$tab" ) . "\n"
1093 );
1094 }
1095 $this->output( "\n" );
1096 }
1097
1098 // Script specific parameters not defined on construction by
1099 // Maintenance::addDefaultParams()
1100 $scriptSpecificParams = array_diff_key(
1101 # all script parameters:
1102 $this->mParams,
1103 # remove the Maintenance default parameters:
1104 $this->mGenericParameters,
1105 $this->mDependantParameters
1106 );
1107 if ( count( $scriptSpecificParams ) > 0 ) {
1108 $this->output( "Script specific parameters:\n" );
1109 // Parameters description
1110 foreach ( $scriptSpecificParams as $par => $info ) {
1111 if ( $info['shortName'] !== false ) {
1112 $par .= " (-{$info['shortName']})";
1113 }
1114 $this->output(
1115 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1116 "\n$tab$tab" ) . "\n"
1117 );
1118 }
1119 $this->output( "\n" );
1120 }
1121
1122 // Print arguments
1123 if ( count( $this->mArgList ) > 0 ) {
1124 $this->output( "Arguments:\n" );
1125 // Arguments description
1126 foreach ( $this->mArgList as $info ) {
1127 $openChar = $info['require'] ? '<' : '[';
1128 $closeChar = $info['require'] ? '>' : ']';
1129 $this->output(
1130 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1131 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1132 );
1133 }
1134 $this->output( "\n" );
1135 }
1136
1137 die( 1 );
1138 }
1139
1140 /**
1141 * Handle some last-minute setup here.
1142 */
1143 public function finalSetup() {
1144 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1145 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1146 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1147
1148 # Turn off output buffering again, it might have been turned on in the settings files
1149 if ( ob_get_level() ) {
1150 ob_end_flush();
1151 }
1152 # Same with these
1153 $wgCommandLineMode = true;
1154
1155 # Override $wgServer
1156 if ( $this->hasOption( 'server' ) ) {
1157 $wgServer = $this->getOption( 'server', $wgServer );
1158 }
1159
1160 # If these were passed, use them
1161 if ( $this->mDbUser ) {
1162 $wgDBadminuser = $this->mDbUser;
1163 }
1164 if ( $this->mDbPass ) {
1165 $wgDBadminpassword = $this->mDbPass;
1166 }
1167 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1168 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1169
1170 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1171 }
1172
1173 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1174 $wgDBuser = $wgDBadminuser;
1175 $wgDBpassword = $wgDBadminpassword;
1176
1177 if ( $wgDBservers ) {
1178 /**
1179 * @var $wgDBservers array
1180 */
1181 foreach ( $wgDBservers as $i => $server ) {
1182 $wgDBservers[$i]['user'] = $wgDBuser;
1183 $wgDBservers[$i]['password'] = $wgDBpassword;
1184 }
1185 }
1186 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1187 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1188 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1189 }
1190 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1191 }
1192
1193 # Apply debug settings
1194 if ( $this->hasOption( 'mwdebug' ) ) {
1195 require __DIR__ . '/../includes/DevelopmentSettings.php';
1196 }
1197
1198 // Per-script profiling; useful for debugging
1199 $this->activateProfiler();
1200
1201 $this->afterFinalSetup();
1202
1203 $wgShowExceptionDetails = true;
1204 $wgShowHostnames = true;
1205
1206 Wikimedia\suppressWarnings();
1207 set_time_limit( 0 );
1208 Wikimedia\restoreWarnings();
1209
1210 $this->adjustMemoryLimit();
1211 }
1212
1213 /**
1214 * Execute a callback function at the end of initialisation
1215 */
1216 protected function afterFinalSetup() {
1217 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1218 call_user_func( MW_CMDLINE_CALLBACK );
1219 }
1220 }
1221
1222 /**
1223 * Potentially debug globals. Originally a feature only
1224 * for refreshLinks
1225 */
1226 public function globals() {
1227 if ( $this->hasOption( 'globals' ) ) {
1228 print_r( $GLOBALS );
1229 }
1230 }
1231
1232 /**
1233 * Generic setup for most installs. Returns the location of LocalSettings
1234 * @return string
1235 */
1236 public function loadSettings() {
1237 global $wgCommandLineMode, $IP;
1238
1239 if ( isset( $this->mOptions['conf'] ) ) {
1240 $settingsFile = $this->mOptions['conf'];
1241 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1242 $settingsFile = MW_CONFIG_FILE;
1243 } else {
1244 $settingsFile = "$IP/LocalSettings.php";
1245 }
1246 if ( isset( $this->mOptions['wiki'] ) ) {
1247 $bits = explode( '-', $this->mOptions['wiki'], 2 );
1248 define( 'MW_DB', $bits[0] );
1249 define( 'MW_PREFIX', $bits[1] ?? '' );
1250 } elseif ( isset( $this->mOptions['server'] ) ) {
1251 // Provide the option for site admins to detect and configure
1252 // multiple wikis based on server names. This offers --server
1253 // as alternative to --wiki.
1254 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1255 $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1256 }
1257
1258 if ( !is_readable( $settingsFile ) ) {
1259 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1260 "must exist and be readable in the source directory.\n" .
1261 "Use --conf to specify it." );
1262 }
1263 $wgCommandLineMode = true;
1264
1265 return $settingsFile;
1266 }
1267
1268 /**
1269 * Support function for cleaning up redundant text records
1270 * @param bool $delete Whether or not to actually delete the records
1271 * @author Rob Church <robchur@gmail.com>
1272 */
1273 public function purgeRedundantText( $delete = true ) {
1274 global $wgMultiContentRevisionSchemaMigrationStage;
1275
1276 # Data should come off the master, wrapped in a transaction
1277 $dbw = $this->getDB( DB_MASTER );
1278 $this->beginTransaction( $dbw, __METHOD__ );
1279
1280 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD ) {
1281 # Get "active" text records from the revisions table
1282 $cur = [];
1283 $this->output( 'Searching for active text records in revisions table...' );
1284 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1285 foreach ( $res as $row ) {
1286 $cur[] = $row->rev_text_id;
1287 }
1288 $this->output( "done.\n" );
1289
1290 # Get "active" text records from the archive table
1291 $this->output( 'Searching for active text records in archive table...' );
1292 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1293 foreach ( $res as $row ) {
1294 # old pre-MW 1.5 records can have null ar_text_id's.
1295 if ( $row->ar_text_id !== null ) {
1296 $cur[] = $row->ar_text_id;
1297 }
1298 }
1299 $this->output( "done.\n" );
1300 } else {
1301 # Get "active" text records via the content table
1302 $cur = [];
1303 $this->output( 'Searching for active text records via contents table...' );
1304 $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1305 $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1306 foreach ( $res as $row ) {
1307 $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1308 if ( $textId ) {
1309 $cur[] = $textId;
1310 }
1311 }
1312 $this->output( "done.\n" );
1313 }
1314 $this->output( "done.\n" );
1315
1316 # Get the IDs of all text records not in these sets
1317 $this->output( 'Searching for inactive text records...' );
1318 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1319 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1320 $old = [];
1321 foreach ( $res as $row ) {
1322 $old[] = $row->old_id;
1323 }
1324 $this->output( "done.\n" );
1325
1326 # Inform the user of what we're going to do
1327 $count = count( $old );
1328 $this->output( "$count inactive items found.\n" );
1329
1330 # Delete as appropriate
1331 if ( $delete && $count ) {
1332 $this->output( 'Deleting...' );
1333 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1334 $this->output( "done.\n" );
1335 }
1336
1337 $this->commitTransaction( $dbw, __METHOD__ );
1338 }
1339
1340 /**
1341 * Get the maintenance directory.
1342 * @return string
1343 */
1344 protected function getDir() {
1345 return __DIR__;
1346 }
1347
1348 /**
1349 * Returns a database to be used by current maintenance script. It can be set by setDB().
1350 * If not set, wfGetDB() will be used.
1351 * This function has the same parameters as wfGetDB()
1352 *
1353 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1354 * @param string|string[] $groups default: empty array
1355 * @param string|bool $wiki default: current wiki
1356 * @return IMaintainableDatabase
1357 */
1358 protected function getDB( $db, $groups = [], $wiki = false ) {
1359 if ( $this->mDb === null ) {
1360 return wfGetDB( $db, $groups, $wiki );
1361 }
1362 return $this->mDb;
1363 }
1364
1365 /**
1366 * Sets database object to be returned by getDB().
1367 *
1368 * @param IDatabase $db
1369 */
1370 public function setDB( IDatabase $db ) {
1371 $this->mDb = $db;
1372 }
1373
1374 /**
1375 * Begin a transcation on a DB
1376 *
1377 * This method makes it clear that begin() is called from a maintenance script,
1378 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1379 *
1380 * @param IDatabase $dbw
1381 * @param string $fname Caller name
1382 * @since 1.27
1383 */
1384 protected function beginTransaction( IDatabase $dbw, $fname ) {
1385 $dbw->begin( $fname );
1386 }
1387
1388 /**
1389 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1390 *
1391 * This method makes it clear that commit() is called from a maintenance script,
1392 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1393 *
1394 * @param IDatabase $dbw
1395 * @param string $fname Caller name
1396 * @return bool Whether the replica DB wait succeeded
1397 * @since 1.27
1398 */
1399 protected function commitTransaction( IDatabase $dbw, $fname ) {
1400 $dbw->commit( $fname );
1401 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1402 $waitSucceeded = $lbFactory->waitForReplication(
1403 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1404 );
1405 $this->lastReplicationWait = microtime( true );
1406 return $waitSucceeded;
1407 }
1408
1409 /**
1410 * Rollback the transcation on a DB handle
1411 *
1412 * This method makes it clear that rollback() is called from a maintenance script,
1413 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1414 *
1415 * @param IDatabase $dbw
1416 * @param string $fname Caller name
1417 * @since 1.27
1418 */
1419 protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1420 $dbw->rollback( $fname );
1421 }
1422
1423 /**
1424 * Lock the search index
1425 * @param IMaintainableDatabase &$db
1426 */
1427 private function lockSearchindex( $db ) {
1428 $write = [ 'searchindex' ];
1429 $read = [
1430 'page',
1431 'revision',
1432 'text',
1433 'interwiki',
1434 'l10n_cache',
1435 'user',
1436 'page_restrictions'
1437 ];
1438 $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1439 }
1440
1441 /**
1442 * Unlock the tables
1443 * @param IMaintainableDatabase &$db
1444 */
1445 private function unlockSearchindex( $db ) {
1446 $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1447 }
1448
1449 /**
1450 * Unlock and lock again
1451 * Since the lock is low-priority, queued reads will be able to complete
1452 * @param IMaintainableDatabase &$db
1453 */
1454 private function relockSearchindex( $db ) {
1455 $this->unlockSearchindex( $db );
1456 $this->lockSearchindex( $db );
1457 }
1458
1459 /**
1460 * Perform a search index update with locking
1461 * @param int $maxLockTime The maximum time to keep the search index locked.
1462 * @param string $callback The function that will update the function.
1463 * @param IMaintainableDatabase $dbw
1464 * @param array $results
1465 */
1466 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1467 $lockTime = time();
1468
1469 # Lock searchindex
1470 if ( $maxLockTime ) {
1471 $this->output( " --- Waiting for lock ---" );
1472 $this->lockSearchindex( $dbw );
1473 $lockTime = time();
1474 $this->output( "\n" );
1475 }
1476
1477 # Loop through the results and do a search update
1478 foreach ( $results as $row ) {
1479 # Allow reads to be processed
1480 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1481 $this->output( " --- Relocking ---" );
1482 $this->relockSearchindex( $dbw );
1483 $lockTime = time();
1484 $this->output( "\n" );
1485 }
1486 call_user_func( $callback, $dbw, $row );
1487 }
1488
1489 # Unlock searchindex
1490 if ( $maxLockTime ) {
1491 $this->output( " --- Unlocking --" );
1492 $this->unlockSearchindex( $dbw );
1493 $this->output( "\n" );
1494 }
1495 }
1496
1497 /**
1498 * Update the searchindex table for a given pageid
1499 * @param IDatabase $dbw A database write handle
1500 * @param int $pageId The page ID to update.
1501 * @return null|string
1502 */
1503 public function updateSearchIndexForPage( $dbw, $pageId ) {
1504 // Get current revision
1505 $rev = Revision::loadFromPageId( $dbw, $pageId );
1506 $title = null;
1507 if ( $rev ) {
1508 $titleObj = $rev->getTitle();
1509 $title = $titleObj->getPrefixedDBkey();
1510 $this->output( "$title..." );
1511 # Update searchindex
1512 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1513 $u->doUpdate();
1514 $this->output( "\n" );
1515 }
1516
1517 return $title;
1518 }
1519
1520 /**
1521 * Count down from $seconds to zero on the terminal, with a one-second pause
1522 * between showing each number. If the maintenance script is in quiet mode,
1523 * this function does nothing.
1524 *
1525 * @since 1.31
1526 *
1527 * @codeCoverageIgnore
1528 * @param int $seconds
1529 */
1530 protected function countDown( $seconds ) {
1531 if ( $this->isQuiet() ) {
1532 return;
1533 }
1534 for ( $i = $seconds; $i >= 0; $i-- ) {
1535 if ( $i != $seconds ) {
1536 $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1537 }
1538 $this->output( $i );
1539 if ( $i ) {
1540 sleep( 1 );
1541 }
1542 }
1543 $this->output( "\n" );
1544 }
1545
1546 /**
1547 * Wrapper for posix_isatty()
1548 * We default as considering stdin a tty (for nice readline methods)
1549 * but treating stout as not a tty to avoid color codes
1550 *
1551 * @param mixed $fd File descriptor
1552 * @return bool
1553 */
1554 public static function posix_isatty( $fd ) {
1555 if ( !function_exists( 'posix_isatty' ) ) {
1556 return !$fd;
1557 } else {
1558 return posix_isatty( $fd );
1559 }
1560 }
1561
1562 /**
1563 * Prompt the console for input
1564 * @param string $prompt What to begin the line with, like '> '
1565 * @return string Response
1566 */
1567 public static function readconsole( $prompt = '> ' ) {
1568 static $isatty = null;
1569 if ( is_null( $isatty ) ) {
1570 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1571 }
1572
1573 if ( $isatty && function_exists( 'readline' ) ) {
1574 return readline( $prompt );
1575 } else {
1576 if ( $isatty ) {
1577 $st = self::readlineEmulation( $prompt );
1578 } else {
1579 if ( feof( STDIN ) ) {
1580 $st = false;
1581 } else {
1582 $st = fgets( STDIN, 1024 );
1583 }
1584 }
1585 if ( $st === false ) {
1586 return false;
1587 }
1588 $resp = trim( $st );
1589
1590 return $resp;
1591 }
1592 }
1593
1594 /**
1595 * Emulate readline()
1596 * @param string $prompt What to begin the line with, like '> '
1597 * @return string
1598 */
1599 private static function readlineEmulation( $prompt ) {
1600 $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1601 if ( !wfIsWindows() && $bash ) {
1602 $retval = false;
1603 $encPrompt = wfEscapeShellArg( $prompt );
1604 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1605 $encCommand = wfEscapeShellArg( $command );
1606 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1607
1608 if ( $retval == 0 ) {
1609 return $line;
1610 } elseif ( $retval == 127 ) {
1611 // Couldn't execute bash even though we thought we saw it.
1612 // Shell probably spit out an error message, sorry :(
1613 // Fall through to fgets()...
1614 } else {
1615 // EOF/ctrl+D
1616 return false;
1617 }
1618 }
1619
1620 // Fallback... we'll have no editing controls, EWWW
1621 if ( feof( STDIN ) ) {
1622 return false;
1623 }
1624 print $prompt;
1625
1626 return fgets( STDIN, 1024 );
1627 }
1628
1629 /**
1630 * Get the terminal size as a two-element array where the first element
1631 * is the width (number of columns) and the second element is the height
1632 * (number of rows).
1633 *
1634 * @return array
1635 */
1636 public static function getTermSize() {
1637 $default = [ 80, 50 ];
1638 if ( wfIsWindows() ) {
1639 return $default;
1640 }
1641 if ( Shell::isDisabled() ) {
1642 return $default;
1643 }
1644 // It's possible to get the screen size with VT-100 terminal escapes,
1645 // but reading the responses is not possible without setting raw mode
1646 // (unless you want to require the user to press enter), and that
1647 // requires an ioctl(), which we can't do. So we have to shell out to
1648 // something that can do the relevant syscalls. There are a few
1649 // options. Linux and Mac OS X both have "stty size" which does the
1650 // job directly.
1651 $result = Shell::command( 'stty', 'size' )
1652 ->execute();
1653 if ( $result->getExitCode() !== 0 ) {
1654 return $default;
1655 }
1656 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1657 return $default;
1658 }
1659 return [ intval( $m[2] ), intval( $m[1] ) ];
1660 }
1661
1662 /**
1663 * Call this to set up the autoloader to allow classes to be used from the
1664 * tests directory.
1665 */
1666 public static function requireTestsAutoloader() {
1667 require_once __DIR__ . '/../tests/common/TestsAutoLoader.php';
1668 }
1669 }
1670
1671 /**
1672 * Fake maintenance wrapper, mostly used for the web installer/updater
1673 */
1674 class FakeMaintenance extends Maintenance {
1675 protected $mSelf = "FakeMaintenanceScript";
1676
1677 public function execute() {
1678 }
1679 }
1680
1681 /**
1682 * Class for scripts that perform database maintenance and want to log the
1683 * update in `updatelog` so we can later skip it
1684 */
1685 abstract class LoggedUpdateMaintenance extends Maintenance {
1686 public function __construct() {
1687 parent::__construct();
1688 $this->addOption( 'force', 'Run the update even if it was completed already' );
1689 $this->setBatchSize( 200 );
1690 }
1691
1692 public function execute() {
1693 $db = $this->getDB( DB_MASTER );
1694 $key = $this->getUpdateKey();
1695
1696 if ( !$this->hasOption( 'force' )
1697 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
1698 ) {
1699 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1700
1701 return true;
1702 }
1703
1704 if ( !$this->doDBUpdates() ) {
1705 return false;
1706 }
1707
1708 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, 'IGNORE' );
1709
1710 return true;
1711 }
1712
1713 /**
1714 * Message to show that the update was done already and was just skipped
1715 * @return string
1716 */
1717 protected function updateSkippedMessage() {
1718 $key = $this->getUpdateKey();
1719
1720 return "Update '{$key}' already logged as completed.";
1721 }
1722
1723 /**
1724 * Do the actual work. All child classes will need to implement this.
1725 * Return true to log the update as done or false (usually on failure).
1726 * @return bool
1727 */
1728 abstract protected function doDBUpdates();
1729
1730 /**
1731 * Get the update key name to go in the update log table
1732 * @return string
1733 */
1734 abstract protected function getUpdateKey();
1735 }