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