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