Merge "Remove deprecated hook EditPageBeforeEditChecks"
[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 }
542
543 # Save additional script dependant options to display
544 #  them separately in help
545 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
546 }
547
548 /**
549 * @since 1.24
550 * @return Config
551 */
552 public function getConfig() {
553 if ( $this->config === null ) {
554 $this->config = MediaWikiServices::getInstance()->getMainConfig();
555 }
556
557 return $this->config;
558 }
559
560 /**
561 * @since 1.24
562 * @param Config $config
563 */
564 public function setConfig( Config $config ) {
565 $this->config = $config;
566 }
567
568 /**
569 * Indicate that the specified extension must be
570 * loaded before the script can run.
571 *
572 * This *must* be called in the constructor.
573 *
574 * @since 1.28
575 * @param string $name
576 */
577 protected function requireExtension( $name ) {
578 $this->requiredExtensions[] = $name;
579 }
580
581 /**
582 * Verify that the required extensions are installed
583 *
584 * @since 1.28
585 */
586 public function checkRequiredExtensions() {
587 $registry = ExtensionRegistry::getInstance();
588 $missing = [];
589 foreach ( $this->requiredExtensions as $name ) {
590 if ( !$registry->isLoaded( $name ) ) {
591 $missing[] = $name;
592 }
593 }
594
595 if ( $missing ) {
596 $joined = implode( ', ', $missing );
597 $msg = "The following extensions are required to be installed "
598 . "for this script to run: $joined. Please enable them and then try again.";
599 $this->fatalError( $msg );
600 }
601 }
602
603 /**
604 * Set triggers like when to try to run deferred updates
605 * @since 1.28
606 */
607 public function setAgentAndTriggers() {
608 if ( function_exists( 'posix_getpwuid' ) ) {
609 $agent = posix_getpwuid( posix_geteuid() )['name'];
610 } else {
611 $agent = 'sysadmin';
612 }
613 $agent .= '@' . wfHostname();
614
615 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
616 // Add a comment for easy SHOW PROCESSLIST interpretation
617 $lbFactory->setAgentName(
618 mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
619 );
620 self::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
621 }
622
623 /**
624 * @param LBFactory $LBFactory
625 * @param Config $config
626 * @since 1.28
627 */
628 public static function setLBFactoryTriggers( LBFactory $LBFactory, Config $config ) {
629 $services = MediaWikiServices::getInstance();
630 $stats = $services->getStatsdDataFactory();
631 // Hook into period lag checks which often happen in long-running scripts
632 $lbFactory = $services->getDBLoadBalancerFactory();
633 $lbFactory->setWaitForReplicationListener(
634 __METHOD__,
635 function () use ( $stats, $config ) {
636 // Check config in case of JobRunner and unit tests
637 if ( $config->get( 'CommandLineMode' ) ) {
638 DeferredUpdates::tryOpportunisticExecute( 'run' );
639 }
640 // Try to periodically flush buffered metrics to avoid OOMs
641 MediaWiki::emitBufferedStatsdData( $stats, $config );
642 }
643 );
644 // Check for other windows to run them. A script may read or do a few writes
645 // to the master but mostly be writing to something else, like a file store.
646 $lbFactory->getMainLB()->setTransactionListener(
647 __METHOD__,
648 function ( $trigger ) use ( $stats, $config ) {
649 // Check config in case of JobRunner and unit tests
650 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
651 DeferredUpdates::tryOpportunisticExecute( 'run' );
652 }
653 // Try to periodically flush buffered metrics to avoid OOMs
654 MediaWiki::emitBufferedStatsdData( $stats, $config );
655 }
656 );
657 }
658
659 /**
660 * Run a child maintenance script. Pass all of the current arguments
661 * to it.
662 * @param string $maintClass A name of a child maintenance class
663 * @param string $classFile Full path of where the child is
664 * @return Maintenance
665 */
666 public function runChild( $maintClass, $classFile = null ) {
667 // Make sure the class is loaded first
668 if ( !class_exists( $maintClass ) ) {
669 if ( $classFile ) {
670 require_once $classFile;
671 }
672 if ( !class_exists( $maintClass ) ) {
673 $this->error( "Cannot spawn child: $maintClass" );
674 }
675 }
676
677 /**
678 * @var $child Maintenance
679 */
680 $child = new $maintClass();
681 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
682 if ( !is_null( $this->mDb ) ) {
683 $child->setDB( $this->mDb );
684 }
685
686 return $child;
687 }
688
689 /**
690 * Do some sanity checking and basic setup
691 */
692 public function setup() {
693 global $IP, $wgCommandLineMode;
694
695 # Abort if called from a web server
696 # wfIsCLI() is not available yet
697 if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
698 $this->fatalError( 'This script must be run from the command line' );
699 }
700
701 if ( $IP === null ) {
702 $this->fatalError( "\$IP not set, aborting!\n" .
703 '(Did you forget to call parent::__construct() in your maintenance script?)' );
704 }
705
706 # Make sure we can handle script parameters
707 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
708 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
709 }
710
711 // Send PHP warnings and errors to stderr instead of stdout.
712 // This aids in diagnosing problems, while keeping messages
713 // out of redirected output.
714 if ( ini_get( 'display_errors' ) ) {
715 ini_set( 'display_errors', 'stderr' );
716 }
717
718 $this->loadParamsAndArgs();
719 $this->maybeHelp();
720
721 # Set the memory limit
722 # Note we need to set it again later in cache LocalSettings changed it
723 $this->adjustMemoryLimit();
724
725 # Set max execution time to 0 (no limit). PHP.net says that
726 # "When running PHP from the command line the default setting is 0."
727 # But sometimes this doesn't seem to be the case.
728 ini_set( 'max_execution_time', 0 );
729
730 # Define us as being in MediaWiki
731 define( 'MEDIAWIKI', true );
732
733 $wgCommandLineMode = true;
734
735 # Turn off output buffering if it's on
736 while ( ob_get_level() > 0 ) {
737 ob_end_flush();
738 }
739
740 $this->validateParamsAndArgs();
741 }
742
743 /**
744 * Normally we disable the memory_limit when running admin scripts.
745 * Some scripts may wish to actually set a limit, however, to avoid
746 * blowing up unexpectedly. We also support a --memory-limit option,
747 * to allow sysadmins to explicitly set one if they'd prefer to override
748 * defaults (or for people using Suhosin which yells at you for trying
749 * to disable the limits)
750 * @return string
751 */
752 public function memoryLimit() {
753 $limit = $this->getOption( 'memory-limit', 'max' );
754 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
755 return $limit;
756 }
757
758 /**
759 * Adjusts PHP's memory limit to better suit our needs, if needed.
760 */
761 protected function adjustMemoryLimit() {
762 $limit = $this->memoryLimit();
763 if ( $limit == 'max' ) {
764 $limit = -1; // no memory limit
765 }
766 if ( $limit != 'default' ) {
767 ini_set( 'memory_limit', $limit );
768 }
769 }
770
771 /**
772 * Activate the profiler (assuming $wgProfiler is set)
773 */
774 protected function activateProfiler() {
775 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
776
777 $output = $this->getOption( 'profiler' );
778 if ( !$output ) {
779 return;
780 }
781
782 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
783 $class = $wgProfiler['class'];
784 /** @var Profiler $profiler */
785 $profiler = new $class(
786 [ 'sampling' => 1, 'output' => [ $output ] ]
787 + $wgProfiler
788 + [ 'threshold' => $wgProfileLimit ]
789 );
790 $profiler->setTemplated( true );
791 Profiler::replaceStubInstance( $profiler );
792 }
793
794 $trxProfiler = Profiler::instance()->getTransactionProfiler();
795 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
796 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
797 }
798
799 /**
800 * Clear all params and arguments.
801 */
802 public function clearParamsAndArgs() {
803 $this->mOptions = [];
804 $this->mArgs = [];
805 $this->mInputLoaded = false;
806 }
807
808 /**
809 * Load params and arguments from a given array
810 * of command-line arguments
811 *
812 * @since 1.27
813 * @param array $argv
814 */
815 public function loadWithArgv( $argv ) {
816 $options = [];
817 $args = [];
818 $this->orderedOptions = [];
819
820 # Parse arguments
821 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
822 if ( $arg == '--' ) {
823 # End of options, remainder should be considered arguments
824 $arg = next( $argv );
825 while ( $arg !== false ) {
826 $args[] = $arg;
827 $arg = next( $argv );
828 }
829 break;
830 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
831 # Long options
832 $option = substr( $arg, 2 );
833 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
834 $param = next( $argv );
835 if ( $param === false ) {
836 $this->error( "\nERROR: $option parameter needs a value after it\n" );
837 $this->maybeHelp( true );
838 }
839
840 $this->setParam( $options, $option, $param );
841 } else {
842 $bits = explode( '=', $option, 2 );
843 if ( count( $bits ) > 1 ) {
844 $option = $bits[0];
845 $param = $bits[1];
846 } else {
847 $param = 1;
848 }
849
850 $this->setParam( $options, $option, $param );
851 }
852 } elseif ( $arg == '-' ) {
853 # Lonely "-", often used to indicate stdin or stdout.
854 $args[] = $arg;
855 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
856 # Short options
857 $argLength = strlen( $arg );
858 for ( $p = 1; $p < $argLength; $p++ ) {
859 $option = $arg[$p];
860 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
861 $option = $this->mShortParamsMap[$option];
862 }
863
864 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
865 $param = next( $argv );
866 if ( $param === false ) {
867 $this->error( "\nERROR: $option parameter needs a value after it\n" );
868 $this->maybeHelp( true );
869 }
870 $this->setParam( $options, $option, $param );
871 } else {
872 $this->setParam( $options, $option, 1 );
873 }
874 }
875 } else {
876 $args[] = $arg;
877 }
878 }
879
880 $this->mOptions = $options;
881 $this->mArgs = $args;
882 $this->loadSpecialVars();
883 $this->mInputLoaded = true;
884 }
885
886 /**
887 * Helper function used solely by loadParamsAndArgs
888 * to prevent code duplication
889 *
890 * This sets the param in the options array based on
891 * whether or not it can be specified multiple times.
892 *
893 * @since 1.27
894 * @param array $options
895 * @param string $option
896 * @param mixed $value
897 */
898 private function setParam( &$options, $option, $value ) {
899 $this->orderedOptions[] = [ $option, $value ];
900
901 if ( isset( $this->mParams[$option] ) ) {
902 $multi = $this->mParams[$option]['multiOccurrence'];
903 } else {
904 $multi = false;
905 }
906 $exists = array_key_exists( $option, $options );
907 if ( $multi && $exists ) {
908 $options[$option][] = $value;
909 } elseif ( $multi ) {
910 $options[$option] = [ $value ];
911 } elseif ( !$exists ) {
912 $options[$option] = $value;
913 } else {
914 $this->error( "\nERROR: $option parameter given twice\n" );
915 $this->maybeHelp( true );
916 }
917 }
918
919 /**
920 * Process command line arguments
921 * $mOptions becomes an array with keys set to the option names
922 * $mArgs becomes a zero-based array containing the non-option arguments
923 *
924 * @param string $self The name of the script, if any
925 * @param array $opts An array of options, in form of key=>value
926 * @param array $args An array of command line arguments
927 */
928 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
929 # If we were given opts or args, set those and return early
930 if ( $self ) {
931 $this->mSelf = $self;
932 $this->mInputLoaded = true;
933 }
934 if ( $opts ) {
935 $this->mOptions = $opts;
936 $this->mInputLoaded = true;
937 }
938 if ( $args ) {
939 $this->mArgs = $args;
940 $this->mInputLoaded = true;
941 }
942
943 # If we've already loaded input (either by user values or from $argv)
944 # skip on loading it again. The array_shift() will corrupt values if
945 # it's run again and again
946 if ( $this->mInputLoaded ) {
947 $this->loadSpecialVars();
948
949 return;
950 }
951
952 global $argv;
953 $this->mSelf = $argv[0];
954 $this->loadWithArgv( array_slice( $argv, 1 ) );
955 }
956
957 /**
958 * Run some validation checks on the params, etc
959 */
960 protected function validateParamsAndArgs() {
961 $die = false;
962 # Check to make sure we've got all the required options
963 foreach ( $this->mParams as $opt => $info ) {
964 if ( $info['require'] && !$this->hasOption( $opt ) ) {
965 $this->error( "Param $opt required!" );
966 $die = true;
967 }
968 }
969 # Check arg list too
970 foreach ( $this->mArgList as $k => $info ) {
971 if ( $info['require'] && !$this->hasArg( $k ) ) {
972 $this->error( 'Argument <' . $info['name'] . '> required!' );
973 $die = true;
974 }
975 }
976
977 if ( $die ) {
978 $this->maybeHelp( true );
979 }
980 }
981
982 /**
983 * Handle the special variables that are global to all scripts
984 */
985 protected function loadSpecialVars() {
986 if ( $this->hasOption( 'dbuser' ) ) {
987 $this->mDbUser = $this->getOption( 'dbuser' );
988 }
989 if ( $this->hasOption( 'dbpass' ) ) {
990 $this->mDbPass = $this->getOption( 'dbpass' );
991 }
992 if ( $this->hasOption( 'quiet' ) ) {
993 $this->mQuiet = true;
994 }
995 if ( $this->hasOption( 'batch-size' ) ) {
996 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
997 }
998 }
999
1000 /**
1001 * Maybe show the help.
1002 * @param bool $force Whether to force the help to show, default false
1003 */
1004 protected function maybeHelp( $force = false ) {
1005 if ( !$force && !$this->hasOption( 'help' ) ) {
1006 return;
1007 }
1008
1009 $screenWidth = 80; // TODO: Calculate this!
1010 $tab = " ";
1011 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1012
1013 ksort( $this->mParams );
1014 $this->mQuiet = false;
1015
1016 // Description ...
1017 if ( $this->mDescription ) {
1018 $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1019 }
1020 $output = "\nUsage: php " . basename( $this->mSelf );
1021
1022 // ... append parameters ...
1023 if ( $this->mParams ) {
1024 $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1025 }
1026
1027 // ... and append arguments.
1028 if ( $this->mArgList ) {
1029 $output .= ' ';
1030 foreach ( $this->mArgList as $k => $arg ) {
1031 if ( $arg['require'] ) {
1032 $output .= '<' . $arg['name'] . '>';
1033 } else {
1034 $output .= '[' . $arg['name'] . ']';
1035 }
1036 if ( $k < count( $this->mArgList ) - 1 ) {
1037 $output .= ' ';
1038 }
1039 }
1040 }
1041 $this->output( "$output\n\n" );
1042
1043 # TODO abstract some repetitive code below
1044
1045 // Generic parameters
1046 $this->output( "Generic maintenance parameters:\n" );
1047 foreach ( $this->mGenericParameters as $par => $info ) {
1048 if ( $info['shortName'] !== false ) {
1049 $par .= " (-{$info['shortName']})";
1050 }
1051 $this->output(
1052 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1053 "\n$tab$tab" ) . "\n"
1054 );
1055 }
1056 $this->output( "\n" );
1057
1058 $scriptDependantParams = $this->mDependantParameters;
1059 if ( count( $scriptDependantParams ) > 0 ) {
1060 $this->output( "Script dependant parameters:\n" );
1061 // Parameters description
1062 foreach ( $scriptDependantParams as $par => $info ) {
1063 if ( $info['shortName'] !== false ) {
1064 $par .= " (-{$info['shortName']})";
1065 }
1066 $this->output(
1067 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1068 "\n$tab$tab" ) . "\n"
1069 );
1070 }
1071 $this->output( "\n" );
1072 }
1073
1074 // Script specific parameters not defined on construction by
1075 // Maintenance::addDefaultParams()
1076 $scriptSpecificParams = array_diff_key(
1077 # all script parameters:
1078 $this->mParams,
1079 # remove the Maintenance default parameters:
1080 $this->mGenericParameters,
1081 $this->mDependantParameters
1082 );
1083 if ( count( $scriptSpecificParams ) > 0 ) {
1084 $this->output( "Script specific parameters:\n" );
1085 // Parameters description
1086 foreach ( $scriptSpecificParams 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 // Print arguments
1099 if ( count( $this->mArgList ) > 0 ) {
1100 $this->output( "Arguments:\n" );
1101 // Arguments description
1102 foreach ( $this->mArgList as $info ) {
1103 $openChar = $info['require'] ? '<' : '[';
1104 $closeChar = $info['require'] ? '>' : ']';
1105 $this->output(
1106 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1107 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1108 );
1109 }
1110 $this->output( "\n" );
1111 }
1112
1113 die( 1 );
1114 }
1115
1116 /**
1117 * Handle some last-minute setup here.
1118 */
1119 public function finalSetup() {
1120 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1121 global $wgDBadminuser, $wgDBadminpassword;
1122 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1123
1124 # Turn off output buffering again, it might have been turned on in the settings files
1125 if ( ob_get_level() ) {
1126 ob_end_flush();
1127 }
1128 # Same with these
1129 $wgCommandLineMode = true;
1130
1131 # Override $wgServer
1132 if ( $this->hasOption( 'server' ) ) {
1133 $wgServer = $this->getOption( 'server', $wgServer );
1134 }
1135
1136 # If these were passed, use them
1137 if ( $this->mDbUser ) {
1138 $wgDBadminuser = $this->mDbUser;
1139 }
1140 if ( $this->mDbPass ) {
1141 $wgDBadminpassword = $this->mDbPass;
1142 }
1143
1144 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1145 $wgDBuser = $wgDBadminuser;
1146 $wgDBpassword = $wgDBadminpassword;
1147
1148 if ( $wgDBservers ) {
1149 /**
1150 * @var $wgDBservers array
1151 */
1152 foreach ( $wgDBservers as $i => $server ) {
1153 $wgDBservers[$i]['user'] = $wgDBuser;
1154 $wgDBservers[$i]['password'] = $wgDBpassword;
1155 }
1156 }
1157 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1158 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1159 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1160 }
1161 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1162 }
1163
1164 # Apply debug settings
1165 if ( $this->hasOption( 'mwdebug' ) ) {
1166 require __DIR__ . '/../includes/DevelopmentSettings.php';
1167 }
1168
1169 // Per-script profiling; useful for debugging
1170 $this->activateProfiler();
1171
1172 $this->afterFinalSetup();
1173
1174 $wgShowSQLErrors = true;
1175
1176 Wikimedia\suppressWarnings();
1177 set_time_limit( 0 );
1178 Wikimedia\restoreWarnings();
1179
1180 $this->adjustMemoryLimit();
1181 }
1182
1183 /**
1184 * Execute a callback function at the end of initialisation
1185 */
1186 protected function afterFinalSetup() {
1187 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1188 call_user_func( MW_CMDLINE_CALLBACK );
1189 }
1190 }
1191
1192 /**
1193 * Potentially debug globals. Originally a feature only
1194 * for refreshLinks
1195 */
1196 public function globals() {
1197 if ( $this->hasOption( 'globals' ) ) {
1198 print_r( $GLOBALS );
1199 }
1200 }
1201
1202 /**
1203 * Generic setup for most installs. Returns the location of LocalSettings
1204 * @return string
1205 */
1206 public function loadSettings() {
1207 global $wgCommandLineMode, $IP;
1208
1209 if ( isset( $this->mOptions['conf'] ) ) {
1210 $settingsFile = $this->mOptions['conf'];
1211 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1212 $settingsFile = MW_CONFIG_FILE;
1213 } else {
1214 $settingsFile = "$IP/LocalSettings.php";
1215 }
1216 if ( isset( $this->mOptions['wiki'] ) ) {
1217 $bits = explode( '-', $this->mOptions['wiki'] );
1218 if ( count( $bits ) == 1 ) {
1219 $bits[] = '';
1220 }
1221 define( 'MW_DB', $bits[0] );
1222 define( 'MW_PREFIX', $bits[1] );
1223 } elseif ( isset( $this->mOptions['server'] ) ) {
1224 // Provide the option for site admins to detect and configure
1225 // multiple wikis based on server names. This offers --server
1226 // as alternative to --wiki.
1227 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1228 $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1229 }
1230
1231 if ( !is_readable( $settingsFile ) ) {
1232 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1233 "must exist and be readable in the source directory.\n" .
1234 "Use --conf to specify it." );
1235 }
1236 $wgCommandLineMode = true;
1237
1238 return $settingsFile;
1239 }
1240
1241 /**
1242 * Support function for cleaning up redundant text records
1243 * @param bool $delete Whether or not to actually delete the records
1244 * @author Rob Church <robchur@gmail.com>
1245 */
1246 public function purgeRedundantText( $delete = true ) {
1247 # Data should come off the master, wrapped in a transaction
1248 $dbw = $this->getDB( DB_MASTER );
1249 $this->beginTransaction( $dbw, __METHOD__ );
1250
1251 # Get "active" text records from the revisions table
1252 $cur = [];
1253 $this->output( 'Searching for active text records in revisions table...' );
1254 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1255 foreach ( $res as $row ) {
1256 $cur[] = $row->rev_text_id;
1257 }
1258 $this->output( "done.\n" );
1259
1260 # Get "active" text records from the archive table
1261 $this->output( 'Searching for active text records in archive table...' );
1262 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1263 foreach ( $res as $row ) {
1264 # old pre-MW 1.5 records can have null ar_text_id's.
1265 if ( $row->ar_text_id !== null ) {
1266 $cur[] = $row->ar_text_id;
1267 }
1268 }
1269 $this->output( "done.\n" );
1270
1271 # Get the IDs of all text records not in these sets
1272 $this->output( 'Searching for inactive text records...' );
1273 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1274 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1275 $old = [];
1276 foreach ( $res as $row ) {
1277 $old[] = $row->old_id;
1278 }
1279 $this->output( "done.\n" );
1280
1281 # Inform the user of what we're going to do
1282 $count = count( $old );
1283 $this->output( "$count inactive items found.\n" );
1284
1285 # Delete as appropriate
1286 if ( $delete && $count ) {
1287 $this->output( 'Deleting...' );
1288 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1289 $this->output( "done.\n" );
1290 }
1291
1292 # Done
1293 $this->commitTransaction( $dbw, __METHOD__ );
1294 }
1295
1296 /**
1297 * Get the maintenance directory.
1298 * @return string
1299 */
1300 protected function getDir() {
1301 return __DIR__;
1302 }
1303
1304 /**
1305 * Returns a database to be used by current maintenance script. It can be set by setDB().
1306 * If not set, wfGetDB() will be used.
1307 * This function has the same parameters as wfGetDB()
1308 *
1309 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1310 * @param string|string[] $groups default: empty array
1311 * @param string|bool $wiki default: current wiki
1312 * @return IMaintainableDatabase
1313 */
1314 protected function getDB( $db, $groups = [], $wiki = false ) {
1315 if ( is_null( $this->mDb ) ) {
1316 return wfGetDB( $db, $groups, $wiki );
1317 } else {
1318 return $this->mDb;
1319 }
1320 }
1321
1322 /**
1323 * Sets database object to be returned by getDB().
1324 *
1325 * @param IDatabase $db
1326 */
1327 public function setDB( IDatabase $db ) {
1328 $this->mDb = $db;
1329 }
1330
1331 /**
1332 * Begin a transcation on a DB
1333 *
1334 * This method makes it clear that begin() is called from a maintenance script,
1335 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1336 *
1337 * @param IDatabase $dbw
1338 * @param string $fname Caller name
1339 * @since 1.27
1340 */
1341 protected function beginTransaction( IDatabase $dbw, $fname ) {
1342 $dbw->begin( $fname );
1343 }
1344
1345 /**
1346 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1347 *
1348 * This method makes it clear that commit() is called from a maintenance script,
1349 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1350 *
1351 * @param IDatabase $dbw
1352 * @param string $fname Caller name
1353 * @return bool Whether the replica DB wait succeeded
1354 * @since 1.27
1355 */
1356 protected function commitTransaction( IDatabase $dbw, $fname ) {
1357 $dbw->commit( $fname );
1358 try {
1359 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1360 $lbFactory->waitForReplication(
1361 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1362 );
1363 $this->lastReplicationWait = microtime( true );
1364
1365 return true;
1366 } catch ( DBReplicationWaitError $e ) {
1367 return false;
1368 }
1369 }
1370
1371 /**
1372 * Rollback the transcation on a DB handle
1373 *
1374 * This method makes it clear that rollback() is called from a maintenance script,
1375 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1376 *
1377 * @param IDatabase $dbw
1378 * @param string $fname Caller name
1379 * @since 1.27
1380 */
1381 protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1382 $dbw->rollback( $fname );
1383 }
1384
1385 /**
1386 * Lock the search index
1387 * @param IMaintainableDatabase &$db
1388 */
1389 private function lockSearchindex( $db ) {
1390 $write = [ 'searchindex' ];
1391 $read = [
1392 'page',
1393 'revision',
1394 'text',
1395 'interwiki',
1396 'l10n_cache',
1397 'user',
1398 'page_restrictions'
1399 ];
1400 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1401 }
1402
1403 /**
1404 * Unlock the tables
1405 * @param IMaintainableDatabase &$db
1406 */
1407 private function unlockSearchindex( $db ) {
1408 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1409 }
1410
1411 /**
1412 * Unlock and lock again
1413 * Since the lock is low-priority, queued reads will be able to complete
1414 * @param IMaintainableDatabase &$db
1415 */
1416 private function relockSearchindex( $db ) {
1417 $this->unlockSearchindex( $db );
1418 $this->lockSearchindex( $db );
1419 }
1420
1421 /**
1422 * Perform a search index update with locking
1423 * @param int $maxLockTime The maximum time to keep the search index locked.
1424 * @param string $callback The function that will update the function.
1425 * @param IMaintainableDatabase $dbw
1426 * @param array $results
1427 */
1428 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1429 $lockTime = time();
1430
1431 # Lock searchindex
1432 if ( $maxLockTime ) {
1433 $this->output( " --- Waiting for lock ---" );
1434 $this->lockSearchindex( $dbw );
1435 $lockTime = time();
1436 $this->output( "\n" );
1437 }
1438
1439 # Loop through the results and do a search update
1440 foreach ( $results as $row ) {
1441 # Allow reads to be processed
1442 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1443 $this->output( " --- Relocking ---" );
1444 $this->relockSearchindex( $dbw );
1445 $lockTime = time();
1446 $this->output( "\n" );
1447 }
1448 call_user_func( $callback, $dbw, $row );
1449 }
1450
1451 # Unlock searchindex
1452 if ( $maxLockTime ) {
1453 $this->output( " --- Unlocking --" );
1454 $this->unlockSearchindex( $dbw );
1455 $this->output( "\n" );
1456 }
1457 }
1458
1459 /**
1460 * Update the searchindex table for a given pageid
1461 * @param IDatabase $dbw A database write handle
1462 * @param int $pageId The page ID to update.
1463 * @return null|string
1464 */
1465 public function updateSearchIndexForPage( $dbw, $pageId ) {
1466 // Get current revision
1467 $rev = Revision::loadFromPageId( $dbw, $pageId );
1468 $title = null;
1469 if ( $rev ) {
1470 $titleObj = $rev->getTitle();
1471 $title = $titleObj->getPrefixedDBkey();
1472 $this->output( "$title..." );
1473 # Update searchindex
1474 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1475 $u->doUpdate();
1476 $this->output( "\n" );
1477 }
1478
1479 return $title;
1480 }
1481
1482 /**
1483 * Count down from $seconds to zero on the terminal, with a one-second pause
1484 * between showing each number. If the maintenance script is in quiet mode,
1485 * this function does nothing.
1486 *
1487 * @since 1.31
1488 *
1489 * @codeCoverageIgnore
1490 * @param int $seconds
1491 */
1492 protected function countDown( $seconds ) {
1493 if ( $this->isQuiet() ) {
1494 return;
1495 }
1496 for ( $i = $seconds; $i >= 0; $i-- ) {
1497 if ( $i != $seconds ) {
1498 $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1499 }
1500 $this->output( $i );
1501 if ( $i ) {
1502 sleep( 1 );
1503 }
1504 }
1505 $this->output( "\n" );
1506 }
1507
1508 /**
1509 * Wrapper for posix_isatty()
1510 * We default as considering stdin a tty (for nice readline methods)
1511 * but treating stout as not a tty to avoid color codes
1512 *
1513 * @param mixed $fd File descriptor
1514 * @return bool
1515 */
1516 public static function posix_isatty( $fd ) {
1517 if ( !function_exists( 'posix_isatty' ) ) {
1518 return !$fd;
1519 } else {
1520 return posix_isatty( $fd );
1521 }
1522 }
1523
1524 /**
1525 * Prompt the console for input
1526 * @param string $prompt What to begin the line with, like '> '
1527 * @return string Response
1528 */
1529 public static function readconsole( $prompt = '> ' ) {
1530 static $isatty = null;
1531 if ( is_null( $isatty ) ) {
1532 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1533 }
1534
1535 if ( $isatty && function_exists( 'readline' ) ) {
1536 return readline( $prompt );
1537 } else {
1538 if ( $isatty ) {
1539 $st = self::readlineEmulation( $prompt );
1540 } else {
1541 if ( feof( STDIN ) ) {
1542 $st = false;
1543 } else {
1544 $st = fgets( STDIN, 1024 );
1545 }
1546 }
1547 if ( $st === false ) {
1548 return false;
1549 }
1550 $resp = trim( $st );
1551
1552 return $resp;
1553 }
1554 }
1555
1556 /**
1557 * Emulate readline()
1558 * @param string $prompt What to begin the line with, like '> '
1559 * @return string
1560 */
1561 private static function readlineEmulation( $prompt ) {
1562 $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1563 if ( !wfIsWindows() && $bash ) {
1564 $retval = false;
1565 $encPrompt = wfEscapeShellArg( $prompt );
1566 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1567 $encCommand = wfEscapeShellArg( $command );
1568 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1569
1570 if ( $retval == 0 ) {
1571 return $line;
1572 } elseif ( $retval == 127 ) {
1573 // Couldn't execute bash even though we thought we saw it.
1574 // Shell probably spit out an error message, sorry :(
1575 // Fall through to fgets()...
1576 } else {
1577 // EOF/ctrl+D
1578 return false;
1579 }
1580 }
1581
1582 // Fallback... we'll have no editing controls, EWWW
1583 if ( feof( STDIN ) ) {
1584 return false;
1585 }
1586 print $prompt;
1587
1588 return fgets( STDIN, 1024 );
1589 }
1590
1591 /**
1592 * Get the terminal size as a two-element array where the first element
1593 * is the width (number of columns) and the second element is the height
1594 * (number of rows).
1595 *
1596 * @return array
1597 */
1598 public static function getTermSize() {
1599 $default = [ 80, 50 ];
1600 if ( wfIsWindows() ) {
1601 return $default;
1602 }
1603 // It's possible to get the screen size with VT-100 terminal escapes,
1604 // but reading the responses is not possible without setting raw mode
1605 // (unless you want to require the user to press enter), and that
1606 // requires an ioctl(), which we can't do. So we have to shell out to
1607 // something that can do the relevant syscalls. There are a few
1608 // options. Linux and Mac OS X both have "stty size" which does the
1609 // job directly.
1610 $result = Shell::command( 'stty', 'size' )
1611 ->execute();
1612 if ( $result->getExitCode() !== 0 ) {
1613 return $default;
1614 }
1615 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1616 return $default;
1617 }
1618 return [ intval( $m[2] ), intval( $m[1] ) ];
1619 }
1620
1621 /**
1622 * Call this to set up the autoloader to allow classes to be used from the
1623 * tests directory.
1624 */
1625 public static function requireTestsAutoloader() {
1626 require_once __DIR__ . '/../tests/common/TestsAutoLoader.php';
1627 }
1628 }
1629
1630 /**
1631 * Fake maintenance wrapper, mostly used for the web installer/updater
1632 */
1633 class FakeMaintenance extends Maintenance {
1634 protected $mSelf = "FakeMaintenanceScript";
1635
1636 public function execute() {
1637 return;
1638 }
1639 }
1640
1641 /**
1642 * Class for scripts that perform database maintenance and want to log the
1643 * update in `updatelog` so we can later skip it
1644 */
1645 abstract class LoggedUpdateMaintenance extends Maintenance {
1646 public function __construct() {
1647 parent::__construct();
1648 $this->addOption( 'force', 'Run the update even if it was completed already' );
1649 $this->setBatchSize( 200 );
1650 }
1651
1652 public function execute() {
1653 $db = $this->getDB( DB_MASTER );
1654 $key = $this->getUpdateKey();
1655
1656 if ( !$this->hasOption( 'force' )
1657 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
1658 ) {
1659 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1660
1661 return true;
1662 }
1663
1664 if ( !$this->doDBUpdates() ) {
1665 return false;
1666 }
1667
1668 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, 'IGNORE' ) ) {
1669 return true;
1670 } else {
1671 $this->output( $this->updatelogFailedMessage() . "\n" );
1672
1673 return false;
1674 }
1675 }
1676
1677 /**
1678 * Message to show that the update was done already and was just skipped
1679 * @return string
1680 */
1681 protected function updateSkippedMessage() {
1682 $key = $this->getUpdateKey();
1683
1684 return "Update '{$key}' already logged as completed.";
1685 }
1686
1687 /**
1688 * Message to show that the update log was unable to log the completion of this update
1689 * @return string
1690 */
1691 protected function updatelogFailedMessage() {
1692 $key = $this->getUpdateKey();
1693
1694 return "Unable to log update '{$key}' as completed.";
1695 }
1696
1697 /**
1698 * Do the actual work. All child classes will need to implement this.
1699 * Return true to log the update as done or false (usually on failure).
1700 * @return bool
1701 */
1702 abstract protected function doDBUpdates();
1703
1704 /**
1705 * Get the update key name to go in the update log table
1706 * @return string
1707 */
1708 abstract protected function getUpdateKey();
1709 }