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