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