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