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