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