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