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