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