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