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