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