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