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