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