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