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