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