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