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