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