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