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