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