Merge "Add support for PHP7 random_bytes in favor of mcrypt_create_iv"
[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 use Wikimedia\Rdbms\LBFactory;
42
43 /**
44 * Abstract maintenance class for quickly writing and churning out
45 * maintenance scripts with minimal effort. All that _must_ be defined
46 * is the execute() method. See docs/maintenance.txt for more info
47 * and a quick demo of how to use it.
48 *
49 * @author Chad Horohoe <chad@anyonecanedit.org>
50 * @since 1.16
51 * @ingroup Maintenance
52 */
53 abstract class Maintenance {
54 /**
55 * Constants for DB access type
56 * @see Maintenance::getDbType()
57 */
58 const DB_NONE = 0;
59 const DB_STD = 1;
60 const DB_ADMIN = 2;
61
62 // Const for getStdin()
63 const STDIN_ALL = 'all';
64
65 // This is the desired params
66 protected $mParams = [];
67
68 // Array of mapping short parameters to long ones
69 protected $mShortParamsMap = [];
70
71 // Array of desired args
72 protected $mArgList = [];
73
74 // This is the list of options that were actually passed
75 protected $mOptions = [];
76
77 // This is the list of arguments that were actually passed
78 protected $mArgs = [];
79
80 // Name of the script currently running
81 protected $mSelf;
82
83 // Special vars for params that are always used
84 protected $mQuiet = false;
85 protected $mDbUser, $mDbPass;
86
87 // A description of the script, children should change this via addDescription()
88 protected $mDescription = '';
89
90 // Have we already loaded our user input?
91 protected $mInputLoaded = false;
92
93 /**
94 * Batch size. If a script supports this, they should set
95 * a default with setBatchSize()
96 *
97 * @var int
98 */
99 protected $mBatchSize = null;
100
101 // Generic options added by addDefaultParams()
102 private $mGenericParameters = [];
103 // Generic options which might or not be supported by the script
104 private $mDependantParameters = [];
105
106 /**
107 * Used by getDB() / setDB()
108 * @var Database
109 */
110 private $mDb = null;
111
112 /** @var float UNIX timestamp */
113 private $lastReplicationWait = 0.0;
114
115 /**
116 * Used when creating separate schema files.
117 * @var resource
118 */
119 public $fileHandle;
120
121 /**
122 * Accessible via getConfig()
123 *
124 * @var Config
125 */
126 private $config;
127
128 /**
129 * @see Maintenance::requireExtension
130 * @var array
131 */
132 private $requiredExtensions = [];
133
134 /**
135 * Used to read the options in the order they were passed.
136 * Useful for option chaining (Ex. dumpBackup.php). It will
137 * be an empty array if the options are passed in through
138 * loadParamsAndArgs( $self, $opts, $args ).
139 *
140 * This is an array of arrays where
141 * 0 => the option and 1 => parameter value.
142 *
143 * @var array
144 */
145 public $orderedOptions = [];
146
147 /**
148 * Default constructor. Children should call this *first* if implementing
149 * their own constructors
150 */
151 public function __construct() {
152 // Setup $IP, using MW_INSTALL_PATH if it exists
153 global $IP;
154 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
155 ? getenv( 'MW_INSTALL_PATH' )
156 : realpath( __DIR__ . '/..' );
157
158 $this->addDefaultParams();
159 register_shutdown_function( [ $this, 'outputChanneled' ], false );
160 }
161
162 /**
163 * Should we execute the maintenance script, or just allow it to be included
164 * as a standalone class? It checks that the call stack only includes this
165 * function and "requires" (meaning was called from the file scope)
166 *
167 * @return bool
168 */
169 public static function shouldExecute() {
170 global $wgCommandLineMode;
171
172 if ( !function_exists( 'debug_backtrace' ) ) {
173 // If someone has a better idea...
174 return $wgCommandLineMode;
175 }
176
177 $bt = debug_backtrace();
178 $count = count( $bt );
179 if ( $count < 2 ) {
180 return false; // sanity
181 }
182 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
183 return false; // last call should be to this function
184 }
185 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
186 for ( $i = 1; $i < $count; $i++ ) {
187 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
188 return false; // previous calls should all be "requires"
189 }
190 }
191
192 return true;
193 }
194
195 /**
196 * Do the actual work. All child classes will need to implement this
197 */
198 abstract public function execute();
199
200 /**
201 * Add a parameter to the script. Will be displayed on --help
202 * with the associated description
203 *
204 * @param string $name The name of the param (help, version, etc)
205 * @param string $description The description of the param to show on --help
206 * @param bool $required Is the param required?
207 * @param bool $withArg Is an argument required with this option?
208 * @param string $shortName Character to use as short name
209 * @param bool $multiOccurrence Can this option be passed multiple times?
210 */
211 protected function addOption( $name, $description, $required = false,
212 $withArg = false, $shortName = false, $multiOccurrence = false
213 ) {
214 $this->mParams[$name] = [
215 'desc' => $description,
216 'require' => $required,
217 'withArg' => $withArg,
218 'shortName' => $shortName,
219 'multiOccurrence' => $multiOccurrence
220 ];
221
222 if ( $shortName !== false ) {
223 $this->mShortParamsMap[$shortName] = $name;
224 }
225 }
226
227 /**
228 * Checks to see if a particular param exists.
229 * @param string $name The name of the param
230 * @return bool
231 */
232 protected function hasOption( $name ) {
233 return isset( $this->mOptions[$name] );
234 }
235
236 /**
237 * Get an option, or return the default.
238 *
239 * If the option was added to support multiple occurrences,
240 * this will return an array.
241 *
242 * @param string $name The name of the param
243 * @param mixed $default Anything you want, default null
244 * @return mixed
245 */
246 protected function getOption( $name, $default = null ) {
247 if ( $this->hasOption( $name ) ) {
248 return $this->mOptions[$name];
249 } else {
250 // Set it so we don't have to provide the default again
251 $this->mOptions[$name] = $default;
252
253 return $this->mOptions[$name];
254 }
255 }
256
257 /**
258 * Add some args that are needed
259 * @param string $arg Name of the arg, like 'start'
260 * @param string $description Short description of the arg
261 * @param bool $required Is this required?
262 */
263 protected function addArg( $arg, $description, $required = true ) {
264 $this->mArgList[] = [
265 'name' => $arg,
266 'desc' => $description,
267 'require' => $required
268 ];
269 }
270
271 /**
272 * Remove an option. Useful for removing options that won't be used in your script.
273 * @param string $name The option to remove.
274 */
275 protected function deleteOption( $name ) {
276 unset( $this->mParams[$name] );
277 }
278
279 /**
280 * Set the description text.
281 * @param string $text The text of the description
282 */
283 protected function addDescription( $text ) {
284 $this->mDescription = $text;
285 }
286
287 /**
288 * Does a given argument exist?
289 * @param int $argId The integer value (from zero) for the arg
290 * @return bool
291 */
292 protected function hasArg( $argId = 0 ) {
293 return isset( $this->mArgs[$argId] );
294 }
295
296 /**
297 * Get an argument.
298 * @param int $argId The integer value (from zero) for the arg
299 * @param mixed $default The default if it doesn't exist
300 * @return mixed
301 */
302 protected function getArg( $argId = 0, $default = null ) {
303 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
304 }
305
306 /**
307 * Set the batch size.
308 * @param int $s The number of operations to do in a batch
309 */
310 protected function setBatchSize( $s = 0 ) {
311 $this->mBatchSize = $s;
312
313 // If we support $mBatchSize, show the option.
314 // Used to be in addDefaultParams, but in order for that to
315 // work, subclasses would have to call this function in the constructor
316 // before they called parent::__construct which is just weird
317 // (and really wasn't done).
318 if ( $this->mBatchSize ) {
319 $this->addOption( 'batch-size', 'Run this many operations ' .
320 'per batch, default: ' . $this->mBatchSize, false, true );
321 if ( isset( $this->mParams['batch-size'] ) ) {
322 // This seems a little ugly...
323 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
324 }
325 }
326 }
327
328 /**
329 * Get the script's name
330 * @return string
331 */
332 public function getName() {
333 return $this->mSelf;
334 }
335
336 /**
337 * Return input from stdin.
338 * @param int $len The number of bytes to read. If null, just return the handle.
339 * Maintenance::STDIN_ALL returns the full length
340 * @return mixed
341 */
342 protected function getStdin( $len = null ) {
343 if ( $len == Maintenance::STDIN_ALL ) {
344 return file_get_contents( 'php://stdin' );
345 }
346 $f = fopen( 'php://stdin', 'rt' );
347 if ( !$len ) {
348 return $f;
349 }
350 $input = fgets( $f, $len );
351 fclose( $f );
352
353 return rtrim( $input );
354 }
355
356 /**
357 * @return bool
358 */
359 public function isQuiet() {
360 return $this->mQuiet;
361 }
362
363 /**
364 * Throw some output to the user. Scripts can call this with no fears,
365 * as we handle all --quiet stuff here
366 * @param string $out The text to show to the user
367 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
368 */
369 protected function output( $out, $channel = null ) {
370 if ( $this->mQuiet ) {
371 return;
372 }
373 if ( $channel === null ) {
374 $this->cleanupChanneled();
375 print $out;
376 } else {
377 $out = preg_replace( '/\n\z/', '', $out );
378 $this->outputChanneled( $out, $channel );
379 }
380 }
381
382 /**
383 * Throw an error to the user. Doesn't respect --quiet, so don't use
384 * this for non-error output
385 * @param string $err The error to display
386 * @param int $die If > 0, go ahead and die out using this int as the code
387 */
388 protected function error( $err, $die = 0 ) {
389 $this->outputChanneled( false );
390 if ( PHP_SAPI == 'cli' ) {
391 fwrite( STDERR, $err . "\n" );
392 } else {
393 print $err;
394 }
395 $die = intval( $die );
396 if ( $die > 0 ) {
397 die( $die );
398 }
399 }
400
401 private $atLineStart = true;
402 private $lastChannel = null;
403
404 /**
405 * Clean up channeled output. Output a newline if necessary.
406 */
407 public function cleanupChanneled() {
408 if ( !$this->atLineStart ) {
409 print "\n";
410 $this->atLineStart = true;
411 }
412 }
413
414 /**
415 * Message outputter with channeled message support. Messages on the
416 * same channel are concatenated, but any intervening messages in another
417 * channel start a new line.
418 * @param string $msg The message without trailing newline
419 * @param string $channel Channel identifier or null for no
420 * channel. Channel comparison uses ===.
421 */
422 public function outputChanneled( $msg, $channel = null ) {
423 if ( $msg === false ) {
424 $this->cleanupChanneled();
425
426 return;
427 }
428
429 // End the current line if necessary
430 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
431 print "\n";
432 }
433
434 print $msg;
435
436 $this->atLineStart = false;
437 if ( $channel === null ) {
438 // For unchanneled messages, output trailing newline immediately
439 print "\n";
440 $this->atLineStart = true;
441 }
442 $this->lastChannel = $channel;
443 }
444
445 /**
446 * Does the script need different DB access? By default, we give Maintenance
447 * scripts normal rights to the DB. Sometimes, a script needs admin rights
448 * access for a reason and sometimes they want no access. Subclasses should
449 * override and return one of the following values, as needed:
450 * Maintenance::DB_NONE - For no DB access at all
451 * Maintenance::DB_STD - For normal DB access, default
452 * Maintenance::DB_ADMIN - For admin DB access
453 * @return int
454 */
455 public function getDbType() {
456 return Maintenance::DB_STD;
457 }
458
459 /**
460 * Add the default parameters to the scripts
461 */
462 protected function addDefaultParams() {
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 = MediaWikiServices::getInstance()->getMainConfig();
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 * Set triggers like when to try to run deferred updates
553 * @since 1.28
554 */
555 public function setAgentAndTriggers() {
556 if ( function_exists( 'posix_getpwuid' ) ) {
557 $agent = posix_getpwuid( posix_geteuid() )['name'];
558 } else {
559 $agent = 'sysadmin';
560 }
561 $agent .= '@' . wfHostname();
562
563 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
564 // Add a comment for easy SHOW PROCESSLIST interpretation
565 $lbFactory->setAgentName(
566 mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
567 );
568 self::setLBFactoryTriggers( $lbFactory );
569 }
570
571 /**
572 * @param LBFactory $LBFactory
573 * @since 1.28
574 */
575 public static function setLBFactoryTriggers( LBFactory $LBFactory ) {
576 // Hook into period lag checks which often happen in long-running scripts
577 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
578 $lbFactory->setWaitForReplicationListener(
579 __METHOD__,
580 function () {
581 global $wgCommandLineMode;
582 // Check config in case of JobRunner and unit tests
583 if ( $wgCommandLineMode ) {
584 DeferredUpdates::tryOpportunisticExecute( 'run' );
585 }
586 }
587 );
588 // Check for other windows to run them. A script may read or do a few writes
589 // to the master but mostly be writing to something else, like a file store.
590 $lbFactory->getMainLB()->setTransactionListener(
591 __METHOD__,
592 function ( $trigger ) {
593 global $wgCommandLineMode;
594 // Check config in case of JobRunner and unit tests
595 if ( $wgCommandLineMode && $trigger === IDatabase::TRIGGER_COMMIT ) {
596 DeferredUpdates::tryOpportunisticExecute( 'run' );
597 }
598 }
599 );
600 }
601
602 /**
603 * Run a child maintenance script. Pass all of the current arguments
604 * to it.
605 * @param string $maintClass A name of a child maintenance class
606 * @param string $classFile Full path of where the child is
607 * @return Maintenance
608 */
609 public function runChild( $maintClass, $classFile = null ) {
610 // Make sure the class is loaded first
611 if ( !class_exists( $maintClass ) ) {
612 if ( $classFile ) {
613 require_once $classFile;
614 }
615 if ( !class_exists( $maintClass ) ) {
616 $this->error( "Cannot spawn child: $maintClass" );
617 }
618 }
619
620 /**
621 * @var $child Maintenance
622 */
623 $child = new $maintClass();
624 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
625 if ( !is_null( $this->mDb ) ) {
626 $child->setDB( $this->mDb );
627 }
628
629 return $child;
630 }
631
632 /**
633 * Do some sanity checking and basic setup
634 */
635 public function setup() {
636 global $IP, $wgCommandLineMode, $wgRequestTime;
637
638 # Abort if called from a web server
639 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
640 $this->error( 'This script must be run from the command line', true );
641 }
642
643 if ( $IP === null ) {
644 $this->error( "\$IP not set, aborting!\n" .
645 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
646 }
647
648 # Make sure we can handle script parameters
649 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
650 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
651 }
652
653 // Send PHP warnings and errors to stderr instead of stdout.
654 // This aids in diagnosing problems, while keeping messages
655 // out of redirected output.
656 if ( ini_get( 'display_errors' ) ) {
657 ini_set( 'display_errors', 'stderr' );
658 }
659
660 $this->loadParamsAndArgs();
661 $this->maybeHelp();
662
663 # Set the memory limit
664 # Note we need to set it again later in cache LocalSettings changed it
665 $this->adjustMemoryLimit();
666
667 # Set max execution time to 0 (no limit). PHP.net says that
668 # "When running PHP from the command line the default setting is 0."
669 # But sometimes this doesn't seem to be the case.
670 ini_set( 'max_execution_time', 0 );
671
672 $wgRequestTime = microtime( true );
673
674 # Define us as being in MediaWiki
675 define( 'MEDIAWIKI', true );
676
677 $wgCommandLineMode = true;
678
679 # Turn off output buffering if it's on
680 while ( ob_get_level() > 0 ) {
681 ob_end_flush();
682 }
683
684 $this->validateParamsAndArgs();
685 }
686
687 /**
688 * Normally we disable the memory_limit when running admin scripts.
689 * Some scripts may wish to actually set a limit, however, to avoid
690 * blowing up unexpectedly. We also support a --memory-limit option,
691 * to allow sysadmins to explicitly set one if they'd prefer to override
692 * defaults (or for people using Suhosin which yells at you for trying
693 * to disable the limits)
694 * @return string
695 */
696 public function memoryLimit() {
697 $limit = $this->getOption( 'memory-limit', 'max' );
698 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
699 return $limit;
700 }
701
702 /**
703 * Adjusts PHP's memory limit to better suit our needs, if needed.
704 */
705 protected function adjustMemoryLimit() {
706 $limit = $this->memoryLimit();
707 if ( $limit == 'max' ) {
708 $limit = -1; // no memory limit
709 }
710 if ( $limit != 'default' ) {
711 ini_set( 'memory_limit', $limit );
712 }
713 }
714
715 /**
716 * Activate the profiler (assuming $wgProfiler is set)
717 */
718 protected function activateProfiler() {
719 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
720
721 $output = $this->getOption( 'profiler' );
722 if ( !$output ) {
723 return;
724 }
725
726 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
727 $class = $wgProfiler['class'];
728 /** @var Profiler $profiler */
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 $cur = [];
1186 $this->output( 'Searching for active text records in revisions table...' );
1187 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1188 foreach ( $res as $row ) {
1189 $cur[] = $row->rev_text_id;
1190 }
1191 $this->output( "done.\n" );
1192
1193 # Get "active" text records from the archive table
1194 $this->output( 'Searching for active text records in archive table...' );
1195 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1196 foreach ( $res as $row ) {
1197 # old pre-MW 1.5 records can have null ar_text_id's.
1198 if ( $row->ar_text_id !== null ) {
1199 $cur[] = $row->ar_text_id;
1200 }
1201 }
1202 $this->output( "done.\n" );
1203
1204 # Get the IDs of all text records not in these sets
1205 $this->output( 'Searching for inactive text records...' );
1206 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1207 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1208 $old = [];
1209 foreach ( $res as $row ) {
1210 $old[] = $row->old_id;
1211 }
1212 $this->output( "done.\n" );
1213
1214 # Inform the user of what we're going to do
1215 $count = count( $old );
1216 $this->output( "$count inactive items found.\n" );
1217
1218 # Delete as appropriate
1219 if ( $delete && $count ) {
1220 $this->output( 'Deleting...' );
1221 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1222 $this->output( "done.\n" );
1223 }
1224
1225 # Done
1226 $this->commitTransaction( $dbw, __METHOD__ );
1227 }
1228
1229 /**
1230 * Get the maintenance directory.
1231 * @return string
1232 */
1233 protected function getDir() {
1234 return __DIR__;
1235 }
1236
1237 /**
1238 * Returns a database to be used by current maintenance script. It can be set by setDB().
1239 * If not set, wfGetDB() will be used.
1240 * This function has the same parameters as wfGetDB()
1241 *
1242 * @param integer $db DB index (DB_REPLICA/DB_MASTER)
1243 * @param array $groups; default: empty array
1244 * @param string|bool $wiki; default: current wiki
1245 * @return Database
1246 */
1247 protected function getDB( $db, $groups = [], $wiki = false ) {
1248 if ( is_null( $this->mDb ) ) {
1249 return wfGetDB( $db, $groups, $wiki );
1250 } else {
1251 return $this->mDb;
1252 }
1253 }
1254
1255 /**
1256 * Sets database object to be returned by getDB().
1257 *
1258 * @param IDatabase $db Database object to be used
1259 */
1260 public function setDB( IDatabase $db ) {
1261 $this->mDb = $db;
1262 }
1263
1264 /**
1265 * Begin a transcation on a DB
1266 *
1267 * This method makes it clear that begin() is called from a maintenance script,
1268 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1269 *
1270 * @param IDatabase $dbw
1271 * @param string $fname Caller name
1272 * @since 1.27
1273 */
1274 protected function beginTransaction( IDatabase $dbw, $fname ) {
1275 $dbw->begin( $fname );
1276 }
1277
1278 /**
1279 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1280 *
1281 * This method makes it clear that commit() is called from a maintenance script,
1282 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1283 *
1284 * @param IDatabase $dbw
1285 * @param string $fname Caller name
1286 * @return bool Whether the replica DB wait succeeded
1287 * @since 1.27
1288 */
1289 protected function commitTransaction( IDatabase $dbw, $fname ) {
1290 $dbw->commit( $fname );
1291 try {
1292 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1293 $lbFactory->waitForReplication(
1294 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1295 );
1296 $this->lastReplicationWait = microtime( true );
1297
1298 return true;
1299 } catch ( DBReplicationWaitError $e ) {
1300 return false;
1301 }
1302 }
1303
1304 /**
1305 * Rollback the transcation on a DB handle
1306 *
1307 * This method makes it clear that rollback() is called from a maintenance script,
1308 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1309 *
1310 * @param IDatabase $dbw
1311 * @param string $fname Caller name
1312 * @since 1.27
1313 */
1314 protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1315 $dbw->rollback( $fname );
1316 }
1317
1318 /**
1319 * Lock the search index
1320 * @param Database &$db
1321 */
1322 private function lockSearchindex( $db ) {
1323 $write = [ 'searchindex' ];
1324 $read = [
1325 'page',
1326 'revision',
1327 'text',
1328 'interwiki',
1329 'l10n_cache',
1330 'user',
1331 'page_restrictions'
1332 ];
1333 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1334 }
1335
1336 /**
1337 * Unlock the tables
1338 * @param Database &$db
1339 */
1340 private function unlockSearchindex( $db ) {
1341 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1342 }
1343
1344 /**
1345 * Unlock and lock again
1346 * Since the lock is low-priority, queued reads will be able to complete
1347 * @param Database &$db
1348 */
1349 private function relockSearchindex( $db ) {
1350 $this->unlockSearchindex( $db );
1351 $this->lockSearchindex( $db );
1352 }
1353
1354 /**
1355 * Perform a search index update with locking
1356 * @param int $maxLockTime The maximum time to keep the search index locked.
1357 * @param string $callback The function that will update the function.
1358 * @param Database $dbw
1359 * @param array $results
1360 */
1361 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1362 $lockTime = time();
1363
1364 # Lock searchindex
1365 if ( $maxLockTime ) {
1366 $this->output( " --- Waiting for lock ---" );
1367 $this->lockSearchindex( $dbw );
1368 $lockTime = time();
1369 $this->output( "\n" );
1370 }
1371
1372 # Loop through the results and do a search update
1373 foreach ( $results as $row ) {
1374 # Allow reads to be processed
1375 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1376 $this->output( " --- Relocking ---" );
1377 $this->relockSearchindex( $dbw );
1378 $lockTime = time();
1379 $this->output( "\n" );
1380 }
1381 call_user_func( $callback, $dbw, $row );
1382 }
1383
1384 # Unlock searchindex
1385 if ( $maxLockTime ) {
1386 $this->output( " --- Unlocking --" );
1387 $this->unlockSearchindex( $dbw );
1388 $this->output( "\n" );
1389 }
1390 }
1391
1392 /**
1393 * Update the searchindex table for a given pageid
1394 * @param Database $dbw A database write handle
1395 * @param int $pageId The page ID to update.
1396 * @return null|string
1397 */
1398 public function updateSearchIndexForPage( $dbw, $pageId ) {
1399 // Get current revision
1400 $rev = Revision::loadFromPageId( $dbw, $pageId );
1401 $title = null;
1402 if ( $rev ) {
1403 $titleObj = $rev->getTitle();
1404 $title = $titleObj->getPrefixedDBkey();
1405 $this->output( "$title..." );
1406 # Update searchindex
1407 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1408 $u->doUpdate();
1409 $this->output( "\n" );
1410 }
1411
1412 return $title;
1413 }
1414
1415 /**
1416 * Wrapper for posix_isatty()
1417 * We default as considering stdin a tty (for nice readline methods)
1418 * but treating stout as not a tty to avoid color codes
1419 *
1420 * @param mixed $fd File descriptor
1421 * @return bool
1422 */
1423 public static function posix_isatty( $fd ) {
1424 if ( !function_exists( 'posix_isatty' ) ) {
1425 return !$fd;
1426 } else {
1427 return posix_isatty( $fd );
1428 }
1429 }
1430
1431 /**
1432 * Prompt the console for input
1433 * @param string $prompt What to begin the line with, like '> '
1434 * @return string Response
1435 */
1436 public static function readconsole( $prompt = '> ' ) {
1437 static $isatty = null;
1438 if ( is_null( $isatty ) ) {
1439 $isatty = self::posix_isatty( 0 /*STDIN*/ );
1440 }
1441
1442 if ( $isatty && function_exists( 'readline' ) ) {
1443 $resp = readline( $prompt );
1444 if ( $resp === null ) {
1445 // Workaround for https://github.com/facebook/hhvm/issues/4776
1446 return false;
1447 } else {
1448 return $resp;
1449 }
1450 } else {
1451 if ( $isatty ) {
1452 $st = self::readlineEmulation( $prompt );
1453 } else {
1454 if ( feof( STDIN ) ) {
1455 $st = false;
1456 } else {
1457 $st = fgets( STDIN, 1024 );
1458 }
1459 }
1460 if ( $st === false ) {
1461 return false;
1462 }
1463 $resp = trim( $st );
1464
1465 return $resp;
1466 }
1467 }
1468
1469 /**
1470 * Emulate readline()
1471 * @param string $prompt What to begin the line with, like '> '
1472 * @return string
1473 */
1474 private static function readlineEmulation( $prompt ) {
1475 $bash = Installer::locateExecutableInDefaultPaths( [ 'bash' ] );
1476 if ( !wfIsWindows() && $bash ) {
1477 $retval = false;
1478 $encPrompt = wfEscapeShellArg( $prompt );
1479 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1480 $encCommand = wfEscapeShellArg( $command );
1481 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1482
1483 if ( $retval == 0 ) {
1484 return $line;
1485 } elseif ( $retval == 127 ) {
1486 // Couldn't execute bash even though we thought we saw it.
1487 // Shell probably spit out an error message, sorry :(
1488 // Fall through to fgets()...
1489 } else {
1490 // EOF/ctrl+D
1491 return false;
1492 }
1493 }
1494
1495 // Fallback... we'll have no editing controls, EWWW
1496 if ( feof( STDIN ) ) {
1497 return false;
1498 }
1499 print $prompt;
1500
1501 return fgets( STDIN, 1024 );
1502 }
1503
1504 /**
1505 * Get the terminal size as a two-element array where the first element
1506 * is the width (number of columns) and the second element is the height
1507 * (number of rows).
1508 *
1509 * @return array
1510 */
1511 public static function getTermSize() {
1512 $default = [ 80, 50 ];
1513 if ( wfIsWindows() ) {
1514 return $default;
1515 }
1516 // It's possible to get the screen size with VT-100 terminal escapes,
1517 // but reading the responses is not possible without setting raw mode
1518 // (unless you want to require the user to press enter), and that
1519 // requires an ioctl(), which we can't do. So we have to shell out to
1520 // something that can do the relevant syscalls. There are a few
1521 // options. Linux and Mac OS X both have "stty size" which does the
1522 // job directly.
1523 $retval = false;
1524 $size = wfShellExec( 'stty size', $retval );
1525 if ( $retval !== 0 ) {
1526 return $default;
1527 }
1528 if ( !preg_match( '/^(\d+) (\d+)$/', $size, $m ) ) {
1529 return $default;
1530 }
1531 return [ intval( $m[2] ), intval( $m[1] ) ];
1532 }
1533
1534 /**
1535 * Call this to set up the autoloader to allow classes to be used from the
1536 * tests directory.
1537 */
1538 public static function requireTestsAutoloader() {
1539 require_once __DIR__ . '/../tests/common/TestsAutoLoader.php';
1540 }
1541 }
1542
1543 /**
1544 * Fake maintenance wrapper, mostly used for the web installer/updater
1545 */
1546 class FakeMaintenance extends Maintenance {
1547 protected $mSelf = "FakeMaintenanceScript";
1548
1549 public function execute() {
1550 return;
1551 }
1552 }
1553
1554 /**
1555 * Class for scripts that perform database maintenance and want to log the
1556 * update in `updatelog` so we can later skip it
1557 */
1558 abstract class LoggedUpdateMaintenance extends Maintenance {
1559 public function __construct() {
1560 parent::__construct();
1561 $this->addOption( 'force', 'Run the update even if it was completed already' );
1562 $this->setBatchSize( 200 );
1563 }
1564
1565 public function execute() {
1566 $db = $this->getDB( DB_MASTER );
1567 $key = $this->getUpdateKey();
1568
1569 if ( !$this->hasOption( 'force' )
1570 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
1571 ) {
1572 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1573
1574 return true;
1575 }
1576
1577 if ( !$this->doDBUpdates() ) {
1578 return false;
1579 }
1580
1581 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, 'IGNORE' ) ) {
1582 return true;
1583 } else {
1584 $this->output( $this->updatelogFailedMessage() . "\n" );
1585
1586 return false;
1587 }
1588 }
1589
1590 /**
1591 * Message to show that the update was done already and was just skipped
1592 * @return string
1593 */
1594 protected function updateSkippedMessage() {
1595 $key = $this->getUpdateKey();
1596
1597 return "Update '{$key}' already logged as completed.";
1598 }
1599
1600 /**
1601 * Message to show that the update log was unable to log the completion of this update
1602 * @return string
1603 */
1604 protected function updatelogFailedMessage() {
1605 $key = $this->getUpdateKey();
1606
1607 return "Unable to log update '{$key}' as completed.";
1608 }
1609
1610 /**
1611 * Do the actual work. All child classes will need to implement this.
1612 * Return true to log the update as done or false (usually on failure).
1613 * @return bool
1614 */
1615 abstract protected function doDBUpdates();
1616
1617 /**
1618 * Get the update key name to go in the update log table
1619 * @return string
1620 */
1621 abstract protected function getUpdateKey();
1622 }