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