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