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