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