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