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