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