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