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