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