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