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