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