* (bug 28945) Keyboard shortcuts on history page no longer work in 1.18
[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 // Include global constants, including MW_VERSION and MW_MIN_PHP_VERSION
24 require_once( dirname( dirname( __FILE__ ) ) . '/includes/Defines.php' );
25
26 // Define this so scripts can easily find doMaintenance.php
27 define( 'RUN_MAINTENANCE_IF_MAIN', dirname( __FILE__ ) . '/doMaintenance.php' );
28 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
29
30 $maintClass = false;
31
32 // Make sure we're on PHP5 or better
33 if ( version_compare( PHP_VERSION, MW_MIN_PHP_VERSION ) < 0 ) {
34 die ( "Sorry! This version of MediaWiki requires PHP " . MW_MIN_PHP_VERSION . "; you are running " .
35 PHP_VERSION . ".\n\n" .
36 "If you are sure you already have PHP " . MW_MIN_PHP_VERSION . " or higher installed, it may be\n" .
37 "installed in a different path from PHP " . PHP_VERSION . ". Check with your system\n" .
38 "administrator.\n" );
39 }
40
41 // Wrapper for posix_isatty()
42 if ( !function_exists( 'posix_isatty' ) ) {
43 # We default as considering stdin a tty (for nice readline methods)
44 # but treating stout as not a tty to avoid color codes
45 function posix_isatty( $fd ) {
46 return !$fd;
47 }
48 }
49
50 /**
51 * Abstract maintenance class for quickly writing and churning out
52 * maintenance scripts with minimal effort. All that _must_ be defined
53 * is the execute() method. See docs/maintenance.txt for more info
54 * and a quick demo of how to use it.
55 *
56 * @author Chad Horohoe <chad@anyonecanedit.org>
57 * @since 1.16
58 * @ingroup Maintenance
59 */
60 abstract class Maintenance {
61
62 /**
63 * Constants for DB access type
64 * @see Maintenance::getDbType()
65 */
66 const DB_NONE = 0;
67 const DB_STD = 1;
68 const DB_ADMIN = 2;
69
70 // Const for getStdin()
71 const STDIN_ALL = 'all';
72
73 // This is the desired params
74 protected $mParams = array();
75
76 // Array of mapping short parameters to long ones
77 protected $mShortParamsMap = array();
78
79 // Array of desired args
80 protected $mArgList = array();
81
82 // This is the list of options that were actually passed
83 protected $mOptions = array();
84
85 // This is the list of arguments that were actually passed
86 protected $mArgs = array();
87
88 // Name of the script currently running
89 protected $mSelf;
90
91 // Special vars for params that are always used
92 protected $mQuiet = false;
93 protected $mDbUser, $mDbPass;
94
95 // A description of the script, children should change this
96 protected $mDescription = '';
97
98 // Have we already loaded our user input?
99 protected $mInputLoaded = false;
100
101 /**
102 * Batch size. If a script supports this, they should set
103 * a default with setBatchSize()
104 *
105 * @var int
106 */
107 protected $mBatchSize = null;
108
109 // Generic options added by addDefaultParams()
110 private $mGenericParameters = array();
111 // Generic options which might or not be supported by the script
112 private $mDependantParameters = array();
113
114 /**
115 * List of all the core maintenance scripts. This is added
116 * to scripts added by extensions in $wgMaintenanceScripts
117 * and returned by getMaintenanceScripts()
118 */
119 protected static $mCoreScripts = null;
120
121 /**
122 * Default constructor. Children should call this *first* if implementing
123 * their own constructors
124 */
125 public function __construct() {
126 // Setup $IP, using MW_INSTALL_PATH if it exists
127 global $IP;
128 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
129 ? getenv( 'MW_INSTALL_PATH' )
130 : realpath( dirname( __FILE__ ) . '/..' );
131
132 $this->addDefaultParams();
133 register_shutdown_function( array( $this, 'outputChanneled' ), false );
134 }
135
136 /**
137 * Should we execute the maintenance script, or just allow it to be included
138 * as a standalone class? It checks that the call stack only includes this
139 * function and a require (meaning was called from the file scope)
140 *
141 * @return Boolean
142 */
143 public static function shouldExecute() {
144 $bt = debug_backtrace();
145 if( count( $bt ) !== 2 ) {
146 return false;
147 }
148 return in_array( $bt[1]['function'], array( 'require_once', 'require', 'include' ) ) &&
149 $bt[0]['class'] == 'Maintenance' &&
150 $bt[0]['function'] == 'shouldExecute';
151 }
152
153 /**
154 * Do the actual work. All child classes will need to implement this
155 */
156 abstract public function execute();
157
158 /**
159 * Add a parameter to the script. Will be displayed on --help
160 * with the associated description
161 *
162 * @param $name String: the name of the param (help, version, etc)
163 * @param $description String: the description of the param to show on --help
164 * @param $required Boolean: is the param required?
165 * @param $withArg Boolean: is an argument required with this option?
166 * @param $shortName String: character to use as short name
167 */
168 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
169 $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
170 if ( $shortName !== false ) {
171 $this->mShortParamsMap[$shortName] = $name;
172 }
173 }
174
175 /**
176 * Checks to see if a particular param exists.
177 * @param $name String: the name of the param
178 * @return Boolean
179 */
180 protected function hasOption( $name ) {
181 return isset( $this->mOptions[$name] );
182 }
183
184 /**
185 * Get an option, or return the default
186 * @param $name String: the name of the param
187 * @param $default Mixed: anything you want, default null
188 * @return Mixed
189 */
190 protected function getOption( $name, $default = null ) {
191 if ( $this->hasOption( $name ) ) {
192 return $this->mOptions[$name];
193 } else {
194 // Set it so we don't have to provide the default again
195 $this->mOptions[$name] = $default;
196 return $this->mOptions[$name];
197 }
198 }
199
200 /**
201 * Add some args that are needed
202 * @param $arg String: name of the arg, like 'start'
203 * @param $description String: short description of the arg
204 * @param $required Boolean: is this required?
205 */
206 protected function addArg( $arg, $description, $required = true ) {
207 $this->mArgList[] = array(
208 'name' => $arg,
209 'desc' => $description,
210 'require' => $required
211 );
212 }
213
214 /**
215 * Remove an option. Useful for removing options that won't be used in your script.
216 * @param $name String: the option to remove.
217 */
218 protected function deleteOption( $name ) {
219 unset( $this->mParams[$name] );
220 }
221
222 /**
223 * Set the description text.
224 * @param $text String: the text of the description
225 */
226 protected function addDescription( $text ) {
227 $this->mDescription = $text;
228 }
229
230 /**
231 * Does a given argument exist?
232 * @param $argId Integer: the integer value (from zero) for the arg
233 * @return Boolean
234 */
235 protected function hasArg( $argId = 0 ) {
236 return isset( $this->mArgs[$argId] );
237 }
238
239 /**
240 * Get an argument.
241 * @param $argId Integer: the integer value (from zero) for the arg
242 * @param $default Mixed: the default if it doesn't exist
243 * @return mixed
244 */
245 protected function getArg( $argId = 0, $default = null ) {
246 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
247 }
248
249 /**
250 * Set the batch size.
251 * @param $s Integer: the number of operations to do in a batch
252 */
253 protected function setBatchSize( $s = 0 ) {
254 $this->mBatchSize = $s;
255 }
256
257 /**
258 * Get the script's name
259 * @return String
260 */
261 public function getName() {
262 return $this->mSelf;
263 }
264
265 /**
266 * Return input from stdin.
267 * @param $len Integer: the number of bytes to read. If null,
268 * just return the handle. Maintenance::STDIN_ALL returns
269 * the full length
270 * @return Mixed
271 */
272 protected function getStdin( $len = null ) {
273 if ( $len == Maintenance::STDIN_ALL ) {
274 return file_get_contents( 'php://stdin' );
275 }
276 $f = fopen( 'php://stdin', 'rt' );
277 if ( !$len ) {
278 return $f;
279 }
280 $input = fgets( $f, $len );
281 fclose( $f );
282 return rtrim( $input );
283 }
284
285 public function isQuiet() {
286 return $this->mQuiet;
287 }
288
289 /**
290 * Throw some output to the user. Scripts can call this with no fears,
291 * as we handle all --quiet stuff here
292 * @param $out String: the text to show to the user
293 * @param $channel Mixed: unique identifier for the channel. See
294 * function outputChanneled.
295 */
296 protected function output( $out, $channel = null ) {
297 if ( $this->mQuiet ) {
298 return;
299 }
300 if ( $channel === null ) {
301 $this->cleanupChanneled();
302
303 $f = fopen( 'php://stdout', 'w' );
304 fwrite( $f, $out );
305 fclose( $f );
306 }
307 else {
308 $out = preg_replace( '/\n\z/', '', $out );
309 $this->outputChanneled( $out, $channel );
310 }
311 }
312
313 /**
314 * Throw an error to the user. Doesn't respect --quiet, so don't use
315 * this for non-error output
316 * @param $err String: the error to display
317 * @param $die Boolean: If true, go ahead and die out.
318 */
319 protected function error( $err, $die = false ) {
320 $this->outputChanneled( false );
321 if ( php_sapi_name() == 'cli' ) {
322 fwrite( STDERR, $err . "\n" );
323 } else {
324 $f = fopen( 'php://stderr', 'w' );
325 fwrite( $f, $err . "\n" );
326 fclose( $f );
327 }
328 if ( $die ) {
329 die();
330 }
331 }
332
333 private $atLineStart = true;
334 private $lastChannel = null;
335
336 /**
337 * Clean up channeled output. Output a newline if necessary.
338 */
339 public function cleanupChanneled() {
340 if ( !$this->atLineStart ) {
341 $handle = fopen( 'php://stdout', 'w' );
342 fwrite( $handle, "\n" );
343 fclose( $handle );
344 $this->atLineStart = true;
345 }
346 }
347
348 /**
349 * Message outputter with channeled message support. Messages on the
350 * same channel are concatenated, but any intervening messages in another
351 * channel start a new line.
352 * @param $msg String: the message without trailing newline
353 * @param $channel Channel identifier or null for no
354 * channel. Channel comparison uses ===.
355 */
356 public function outputChanneled( $msg, $channel = null ) {
357 if ( $msg === false ) {
358 $this->cleanupChanneled();
359 return;
360 }
361
362 $handle = fopen( 'php://stdout', 'w' );
363
364 // End the current line if necessary
365 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
366 fwrite( $handle, "\n" );
367 }
368
369 fwrite( $handle, $msg );
370
371 $this->atLineStart = false;
372 if ( $channel === null ) {
373 // For unchanneled messages, output trailing newline immediately
374 fwrite( $handle, "\n" );
375 $this->atLineStart = true;
376 }
377 $this->lastChannel = $channel;
378
379 // Cleanup handle
380 fclose( $handle );
381 }
382
383 /**
384 * Does the script need different DB access? By default, we give Maintenance
385 * scripts normal rights to the DB. Sometimes, a script needs admin rights
386 * access for a reason and sometimes they want no access. Subclasses should
387 * override and return one of the following values, as needed:
388 * Maintenance::DB_NONE - For no DB access at all
389 * Maintenance::DB_STD - For normal DB access, default
390 * Maintenance::DB_ADMIN - For admin DB access
391 * @return Integer
392 */
393 public function getDbType() {
394 return Maintenance::DB_STD;
395 }
396
397 /**
398 * Add the default parameters to the scripts
399 */
400 protected function addDefaultParams() {
401
402 # Generic (non script dependant) options:
403
404 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
405 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
406 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
407 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
408 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
409 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' );
410 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
411 "http://en.wikipedia.org. This is sometimes necessary because " .
412 "server name detection may fail in command line scripts.", false, true );
413
414 # Save generic options to display them separately in help
415 $this->mGenericParameters = $this->mParams ;
416
417 # Script dependant options:
418
419 // If we support a DB, show the options
420 if ( $this->getDbType() > 0 ) {
421 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
422 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
423 }
424 // If we support $mBatchSize, show the option
425 if ( $this->mBatchSize ) {
426 $this->addOption( 'batch-size', 'Run this many operations ' .
427 'per batch, default: ' . $this->mBatchSize, false, true );
428 }
429 # Save additional script dependant options to display
430 # them separately in help
431 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
432 }
433
434 /**
435 * Run a child maintenance script. Pass all of the current arguments
436 * to it.
437 * @param $maintClass String: a name of a child maintenance class
438 * @param $classFile String: full path of where the child is
439 * @return Maintenance child
440 */
441 public function runChild( $maintClass, $classFile = null ) {
442 // Make sure the class is loaded first
443 if ( !MWInit::classExists( $maintClass ) ) {
444 if ( $classFile ) {
445 require_once( $classFile );
446 }
447 if ( !MWInit::classExists( $maintClass ) ) {
448 $this->error( "Cannot spawn child: $maintClass" );
449 }
450 }
451
452 $child = new $maintClass();
453 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
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 ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
600 $param = next( $argv );
601 if ( $param === false ) {
602 $this->error( "\nERROR: $option needs a value after it\n" );
603 $this->maybeHelp( true );
604 }
605 $options[$option] = $param;
606 } else {
607 $bits = explode( '=', $option, 2 );
608 if ( count( $bits ) > 1 ) {
609 $option = $bits[0];
610 $param = $bits[1];
611 } else {
612 $param = 1;
613 }
614 $options[$option] = $param;
615 }
616 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
617 # Short options
618 for ( $p = 1; $p < strlen( $arg ); $p++ ) {
619 $option = $arg { $p } ;
620 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
621 $option = $this->mShortParamsMap[$option];
622 }
623 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
624 $param = next( $argv );
625 if ( $param === false ) {
626 $this->error( "\nERROR: $option needs a value after it\n" );
627 $this->maybeHelp( true );
628 }
629 $options[$option] = $param;
630 } else {
631 $options[$option] = 1;
632 }
633 }
634 } else {
635 $args[] = $arg;
636 }
637 }
638
639 $this->mOptions = $options;
640 $this->mArgs = $args;
641 $this->loadSpecialVars();
642 $this->mInputLoaded = true;
643 }
644
645 /**
646 * Run some validation checks on the params, etc
647 */
648 protected function validateParamsAndArgs() {
649 $die = false;
650 # Check to make sure we've got all the required options
651 foreach ( $this->mParams as $opt => $info ) {
652 if ( $info['require'] && !$this->hasOption( $opt ) ) {
653 $this->error( "Param $opt required!" );
654 $die = true;
655 }
656 }
657 # Check arg list too
658 foreach ( $this->mArgList as $k => $info ) {
659 if ( $info['require'] && !$this->hasArg( $k ) ) {
660 $this->error( 'Argument <' . $info['name'] . '> required!' );
661 $die = true;
662 }
663 }
664
665 if ( $die ) {
666 $this->maybeHelp( true );
667 }
668 }
669
670 /**
671 * Handle the special variables that are global to all scripts
672 */
673 protected function loadSpecialVars() {
674 if ( $this->hasOption( 'dbuser' ) ) {
675 $this->mDbUser = $this->getOption( 'dbuser' );
676 }
677 if ( $this->hasOption( 'dbpass' ) ) {
678 $this->mDbPass = $this->getOption( 'dbpass' );
679 }
680 if ( $this->hasOption( 'quiet' ) ) {
681 $this->mQuiet = true;
682 }
683 if ( $this->hasOption( 'batch-size' ) ) {
684 $this->mBatchSize = $this->getOption( 'batch-size' );
685 }
686 }
687
688 /**
689 * Maybe show the help.
690 * @param $force boolean Whether to force the help to show, default false
691 */
692 protected function maybeHelp( $force = false ) {
693 if( !$force && !$this->hasOption( 'help' ) ) {
694 return;
695 }
696
697 $screenWidth = 80; // TODO: Caculate this!
698 $tab = " ";
699 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
700
701 ksort( $this->mParams );
702 $this->mQuiet = false;
703
704 // Description ...
705 if ( $this->mDescription ) {
706 $this->output( "\n" . $this->mDescription . "\n" );
707 }
708 $output = "\nUsage: php " . basename( $this->mSelf );
709
710 // ... append parameters ...
711 if ( $this->mParams ) {
712 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
713 }
714
715 // ... and append arguments.
716 if ( $this->mArgList ) {
717 $output .= ' ';
718 foreach ( $this->mArgList as $k => $arg ) {
719 if ( $arg['require'] ) {
720 $output .= '<' . $arg['name'] . '>';
721 } else {
722 $output .= '[' . $arg['name'] . ']';
723 }
724 if ( $k < count( $this->mArgList ) - 1 )
725 $output .= ' ';
726 }
727 }
728 $this->output( "$output\n\n" );
729
730 # TODO abstract some repetitive code below
731
732 // Generic parameters
733 $this->output( "Generic maintenance parameters:\n" );
734 foreach ( $this->mGenericParameters as $par => $info ) {
735 if ( $info['shortName'] !== false ) {
736 $par .= " (-{$info['shortName']})";
737 }
738 $this->output(
739 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
740 "\n$tab$tab" ) . "\n"
741 );
742 }
743 $this->output( "\n" );
744
745 $scriptDependantParams = $this->mDependantParameters;
746 if( count($scriptDependantParams) > 0 ) {
747 $this->output( "Script dependant parameters:\n" );
748 // Parameters description
749 foreach ( $scriptDependantParams as $par => $info ) {
750 if ( $info['shortName'] !== false ) {
751 $par .= " (-{$info['shortName']})";
752 }
753 $this->output(
754 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
755 "\n$tab$tab" ) . "\n"
756 );
757 }
758 $this->output( "\n" );
759 }
760
761
762 // Script specific parameters not defined on construction by
763 // Maintenance::addDefaultParams()
764 $scriptSpecificParams = array_diff_key(
765 # all script parameters:
766 $this->mParams,
767 # remove the Maintenance default parameters:
768 $this->mGenericParameters,
769 $this->mDependantParameters
770 );
771 if( count($scriptSpecificParams) > 0 ) {
772 $this->output( "Script specific parameters:\n" );
773 // Parameters description
774 foreach ( $scriptSpecificParams as $par => $info ) {
775 if ( $info['shortName'] !== false ) {
776 $par .= " (-{$info['shortName']})";
777 }
778 $this->output(
779 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
780 "\n$tab$tab" ) . "\n"
781 );
782 }
783 $this->output( "\n" );
784 }
785
786 // Print arguments
787 if( count( $this->mArgList ) > 0 ) {
788 $this->output( "Arguments:\n" );
789 // Arguments description
790 foreach ( $this->mArgList as $info ) {
791 $openChar = $info['require'] ? '<' : '[';
792 $closeChar = $info['require'] ? '>' : ']';
793 $this->output(
794 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
795 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
796 );
797 }
798 $this->output( "\n" );
799 }
800
801 die( 1 );
802 }
803
804 /**
805 * Handle some last-minute setup here.
806 */
807 public function finalSetup() {
808 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
809 global $wgDBadminuser, $wgDBadminpassword;
810 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
811
812 # Turn off output buffering again, it might have been turned on in the settings files
813 if ( ob_get_level() ) {
814 ob_end_flush();
815 }
816 # Same with these
817 $wgCommandLineMode = true;
818
819 # Override $wgServer
820 if( $this->hasOption( 'server') ) {
821 $wgServer = $this->getOption( 'server', $wgServer );
822 }
823
824 # If these were passed, use them
825 if ( $this->mDbUser ) {
826 $wgDBadminuser = $this->mDbUser;
827 }
828 if ( $this->mDbPass ) {
829 $wgDBadminpassword = $this->mDbPass;
830 }
831
832 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
833 $wgDBuser = $wgDBadminuser;
834 $wgDBpassword = $wgDBadminpassword;
835
836 if ( $wgDBservers ) {
837 foreach ( $wgDBservers as $i => $server ) {
838 $wgDBservers[$i]['user'] = $wgDBuser;
839 $wgDBservers[$i]['password'] = $wgDBpassword;
840 }
841 }
842 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
843 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
844 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
845 }
846 LBFactory::destroyInstance();
847 }
848
849 $this->afterFinalSetup();
850
851 $wgShowSQLErrors = true;
852 @set_time_limit( 0 );
853 $this->adjustMemoryLimit();
854 }
855
856 /**
857 * Execute a callback function at the end of initialisation
858 */
859 protected function afterFinalSetup() {
860 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
861 call_user_func( MW_CMDLINE_CALLBACK );
862 }
863 }
864
865 /**
866 * Potentially debug globals. Originally a feature only
867 * for refreshLinks
868 */
869 public function globals() {
870 if ( $this->hasOption( 'globals' ) ) {
871 print_r( $GLOBALS );
872 }
873 }
874
875 /**
876 * Do setup specific to WMF
877 */
878 public function loadWikimediaSettings() {
879 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
880
881 if ( empty( $wgNoDBParam ) ) {
882 # Check if we were passed a db name
883 if ( isset( $this->mOptions['wiki'] ) ) {
884 $db = $this->mOptions['wiki'];
885 } else {
886 $db = array_shift( $this->mArgs );
887 }
888 list( $site, $lang ) = $wgConf->siteFromDB( $db );
889
890 # If not, work out the language and site the old way
891 if ( is_null( $site ) || is_null( $lang ) ) {
892 if ( !$db ) {
893 $lang = 'aa';
894 } else {
895 $lang = $db;
896 }
897 if ( isset( $this->mArgs[0] ) ) {
898 $site = array_shift( $this->mArgs );
899 } else {
900 $site = 'wikipedia';
901 }
902 }
903 } else {
904 $lang = 'aa';
905 $site = 'wikipedia';
906 }
907
908 # This is for the IRC scripts, which now run as the apache user
909 # The apache user doesn't have access to the wikiadmin_pass command
910 if ( $_ENV['USER'] == 'apache' ) {
911 # if ( posix_geteuid() == 48 ) {
912 $wgUseNormalUser = true;
913 }
914
915 putenv( 'wikilang=' . $lang );
916
917 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
918
919 if ( $lang == 'test' && $site == 'wikipedia' ) {
920 define( 'TESTWIKI', 1 );
921 }
922 }
923
924 /**
925 * Generic setup for most installs. Returns the location of LocalSettings
926 * @return String
927 */
928 public function loadSettings() {
929 global $wgWikiFarm, $wgCommandLineMode, $IP;
930
931 $wgWikiFarm = false;
932 if ( isset( $this->mOptions['conf'] ) ) {
933 $settingsFile = $this->mOptions['conf'];
934 } else if ( 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 = wfGetDB( 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 * Lock the search index
1069 * @param &$db Database object
1070 */
1071 private function lockSearchindex( &$db ) {
1072 $write = array( 'searchindex' );
1073 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
1074 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
1075 }
1076
1077 /**
1078 * Unlock the tables
1079 * @param &$db Database object
1080 */
1081 private function unlockSearchindex( &$db ) {
1082 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
1083 }
1084
1085 /**
1086 * Unlock and lock again
1087 * Since the lock is low-priority, queued reads will be able to complete
1088 * @param &$db Database object
1089 */
1090 private function relockSearchindex( &$db ) {
1091 $this->unlockSearchindex( $db );
1092 $this->lockSearchindex( $db );
1093 }
1094
1095 /**
1096 * Perform a search index update with locking
1097 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
1098 * @param $callback callback String: the function that will update the function.
1099 * @param $dbw DatabaseBase object
1100 * @param $results
1101 */
1102 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1103 $lockTime = time();
1104
1105 # Lock searchindex
1106 if ( $maxLockTime ) {
1107 $this->output( " --- Waiting for lock ---" );
1108 $this->lockSearchindex( $dbw );
1109 $lockTime = time();
1110 $this->output( "\n" );
1111 }
1112
1113 # Loop through the results and do a search update
1114 foreach ( $results as $row ) {
1115 # Allow reads to be processed
1116 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1117 $this->output( " --- Relocking ---" );
1118 $this->relockSearchindex( $dbw );
1119 $lockTime = time();
1120 $this->output( "\n" );
1121 }
1122 call_user_func( $callback, $dbw, $row );
1123 }
1124
1125 # Unlock searchindex
1126 if ( $maxLockTime ) {
1127 $this->output( " --- Unlocking --" );
1128 $this->unlockSearchindex( $dbw );
1129 $this->output( "\n" );
1130 }
1131
1132 }
1133
1134 /**
1135 * Update the searchindex table for a given pageid
1136 * @param $dbw Database: a database write handle
1137 * @param $pageId Integer: the page ID to update.
1138 */
1139 public function updateSearchIndexForPage( $dbw, $pageId ) {
1140 // Get current revision
1141 $rev = Revision::loadFromPageId( $dbw, $pageId );
1142 $title = null;
1143 if ( $rev ) {
1144 $titleObj = $rev->getTitle();
1145 $title = $titleObj->getPrefixedDBkey();
1146 $this->output( "$title..." );
1147 # Update searchindex
1148 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1149 $u->doUpdate();
1150 $this->output( "\n" );
1151 }
1152 return $title;
1153 }
1154
1155 /**
1156 * Prompt the console for input
1157 * @param $prompt String what to begin the line with, like '> '
1158 * @return String response
1159 */
1160 public static function readconsole( $prompt = '> ' ) {
1161 static $isatty = null;
1162 if ( is_null( $isatty ) ) {
1163 $isatty = posix_isatty( 0 /*STDIN*/ );
1164 }
1165
1166 if ( $isatty && function_exists( 'readline' ) ) {
1167 return readline( $prompt );
1168 } else {
1169 if ( $isatty ) {
1170 $st = self::readlineEmulation( $prompt );
1171 } else {
1172 if ( feof( STDIN ) ) {
1173 $st = false;
1174 } else {
1175 $st = fgets( STDIN, 1024 );
1176 }
1177 }
1178 if ( $st === false ) return false;
1179 $resp = trim( $st );
1180 return $resp;
1181 }
1182 }
1183
1184 /**
1185 * Emulate readline()
1186 * @param $prompt String what to begin the line with, like '> '
1187 * @return String
1188 */
1189 private static function readlineEmulation( $prompt ) {
1190 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) );
1191 if ( !wfIsWindows() && $bash ) {
1192 $retval = false;
1193 $encPrompt = wfEscapeShellArg( $prompt );
1194 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1195 $encCommand = wfEscapeShellArg( $command );
1196 $line = wfShellExec( "$bash -c $encCommand", $retval );
1197
1198 if ( $retval == 0 ) {
1199 return $line;
1200 } elseif ( $retval == 127 ) {
1201 // Couldn't execute bash even though we thought we saw it.
1202 // Shell probably spit out an error message, sorry :(
1203 // Fall through to fgets()...
1204 } else {
1205 // EOF/ctrl+D
1206 return false;
1207 }
1208 }
1209
1210 // Fallback... we'll have no editing controls, EWWW
1211 if ( feof( STDIN ) ) {
1212 return false;
1213 }
1214 print $prompt;
1215 return fgets( STDIN, 1024 );
1216 }
1217 }
1218
1219 class FakeMaintenance extends Maintenance {
1220 protected $mSelf = "FakeMaintenanceScript";
1221 public function execute() {
1222 return;
1223 }
1224 }
1225