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