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