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