Allow overriding default memory limits in maintenance scripts (which is usually to...
[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' );
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 # Set the memory limit
435 # Note we need to set it again later in cache LocalSettings changed it
436 ini_set( 'memory_limit', $this->memoryLimit() );
437
438 # Set max execution time to 0 (no limit). PHP.net says that
439 # "When running PHP from the command line the default setting is 0."
440 # But sometimes this doesn't seem to be the case.
441 ini_set( 'max_execution_time', 0 );
442
443 $wgRequestTime = microtime( true );
444
445 # Define us as being in MediaWiki
446 define( 'MEDIAWIKI', true );
447
448 # Setup $IP, using MW_INSTALL_PATH if it exists
449 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
450 ? getenv( 'MW_INSTALL_PATH' )
451 : realpath( dirname( __FILE__ ) . '/..' );
452
453 $wgCommandLineMode = true;
454 # Turn off output buffering if it's on
455 @ob_end_flush();
456
457 $this->loadParamsAndArgs();
458 $this->maybeHelp();
459 $this->validateParamsAndArgs();
460 }
461
462 /**
463 * Normally we disable the memory_limit when running admin scripts.
464 * Some scripts may wish to actually set a limit, however, to avoid
465 * blowing up unexpectedly. We also support a --memory-limit option,
466 * to allow sysadmins to explicitly set one if they'd prefer to override
467 * defaults (or for people using Suhosin which yells at you for trying
468 * to disable the limits)
469 */
470 public function memoryLimit() {
471 return $this->getOption( 'memory-limit', -1 );
472 }
473
474 /**
475 * Clear all params and arguments.
476 */
477 public function clearParamsAndArgs() {
478 $this->mOptions = array();
479 $this->mArgs = array();
480 $this->mInputLoaded = false;
481 }
482
483 /**
484 * Process command line arguments
485 * $mOptions becomes an array with keys set to the option names
486 * $mArgs becomes a zero-based array containing the non-option arguments
487 *
488 * @param $self String The name of the script, if any
489 * @param $opts Array An array of options, in form of key=>value
490 * @param $args Array An array of command line arguments
491 */
492 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
493 # If we were given opts or args, set those and return early
494 if ( $self ) {
495 $this->mSelf = $self;
496 $this->mInputLoaded = true;
497 }
498 if ( $opts ) {
499 $this->mOptions = $opts;
500 $this->mInputLoaded = true;
501 }
502 if ( $args ) {
503 $this->mArgs = $args;
504 $this->mInputLoaded = true;
505 }
506
507 # If we've already loaded input (either by user values or from $argv)
508 # skip on loading it again. The array_shift() will corrupt values if
509 # it's run again and again
510 if ( $this->mInputLoaded ) {
511 $this->loadSpecialVars();
512 return;
513 }
514
515 global $argv;
516 $this->mSelf = array_shift( $argv );
517
518 $options = array();
519 $args = array();
520
521 # Parse arguments
522 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
523 if ( $arg == '--' ) {
524 # End of options, remainder should be considered arguments
525 $arg = next( $argv );
526 while ( $arg !== false ) {
527 $args[] = $arg;
528 $arg = next( $argv );
529 }
530 break;
531 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
532 # Long options
533 $option = substr( $arg, 2 );
534 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
535 $param = next( $argv );
536 if ( $param === false ) {
537 $this->error( "\nERROR: $option needs a value after it\n" );
538 $this->maybeHelp( true );
539 }
540 $options[$option] = $param;
541 } else {
542 $bits = explode( '=', $option, 2 );
543 if ( count( $bits ) > 1 ) {
544 $option = $bits[0];
545 $param = $bits[1];
546 } else {
547 $param = 1;
548 }
549 $options[$option] = $param;
550 }
551 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
552 # Short options
553 for ( $p = 1; $p < strlen( $arg ); $p++ ) {
554 $option = $arg { $p } ;
555 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
556 $param = next( $argv );
557 if ( $param === false ) {
558 $this->error( "\nERROR: $option needs a value after it\n" );
559 $this->maybeHelp( true );
560 }
561 $options[$option] = $param;
562 } else {
563 $options[$option] = 1;
564 }
565 }
566 } else {
567 $args[] = $arg;
568 }
569 }
570
571 $this->mOptions = $options;
572 $this->mArgs = $args;
573 $this->loadSpecialVars();
574 $this->mInputLoaded = true;
575 }
576
577 /**
578 * Run some validation checks on the params, etc
579 */
580 protected function validateParamsAndArgs() {
581 $die = false;
582 # Check to make sure we've got all the required options
583 foreach ( $this->mParams as $opt => $info ) {
584 if ( $info['require'] && !$this->hasOption( $opt ) ) {
585 $this->error( "Param $opt required!" );
586 $die = true;
587 }
588 }
589 # Check arg list too
590 foreach ( $this->mArgList as $k => $info ) {
591 if ( $info['require'] && !$this->hasArg( $k ) ) {
592 $this->error( 'Argument <' . $info['name'] . '> required!' );
593 $die = true;
594 }
595 }
596
597 if ( $die ) {
598 $this->maybeHelp( true );
599 }
600 }
601
602 /**
603 * Handle the special variables that are global to all scripts
604 */
605 protected function loadSpecialVars() {
606 if ( $this->hasOption( 'dbuser' ) ) {
607 $this->mDbUser = $this->getOption( 'dbuser' );
608 }
609 if ( $this->hasOption( 'dbpass' ) ) {
610 $this->mDbPass = $this->getOption( 'dbpass' );
611 }
612 if ( $this->hasOption( 'quiet' ) ) {
613 $this->mQuiet = true;
614 }
615 if ( $this->hasOption( 'batch-size' ) ) {
616 $this->mBatchSize = $this->getOption( 'batch-size' );
617 }
618 }
619
620 /**
621 * Maybe show the help.
622 * @param $force boolean Whether to force the help to show, default false
623 */
624 protected function maybeHelp( $force = false ) {
625 $screenWidth = 80; // TODO: Caculate this!
626 $tab = " ";
627 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
628
629 ksort( $this->mParams );
630 if ( $this->hasOption( 'help' ) || $force ) {
631 $this->mQuiet = false;
632
633 if ( $this->mDescription ) {
634 $this->output( "\n" . $this->mDescription . "\n" );
635 }
636 $output = "\nUsage: php " . basename( $this->mSelf );
637 if ( $this->mParams ) {
638 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
639 }
640 if ( $this->mArgList ) {
641 $output .= " <";
642 foreach ( $this->mArgList as $k => $arg ) {
643 $output .= $arg['name'] . ">";
644 if ( $k < count( $this->mArgList ) - 1 )
645 $output .= " <";
646 }
647 }
648 $this->output( "$output\n" );
649 foreach ( $this->mParams as $par => $info ) {
650 $this->output(
651 wordwrap( "$tab$par : " . $info['desc'], $descWidth,
652 "\n$tab$tab" ) . "\n"
653 );
654 }
655 foreach ( $this->mArgList as $info ) {
656 $this->output(
657 wordwrap( "$tab<" . $info['name'] . "> : " .
658 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
659 );
660 }
661 die( 1 );
662 }
663 }
664
665 /**
666 * Handle some last-minute setup here.
667 */
668 public function finalSetup() {
669 global $wgCommandLineMode, $wgShowSQLErrors;
670 global $wgProfiling, $wgDBadminuser, $wgDBadminpassword;
671 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
672
673 # Turn off output buffering again, it might have been turned on in the settings files
674 if ( ob_get_level() ) {
675 ob_end_flush();
676 }
677 # Same with these
678 $wgCommandLineMode = true;
679
680 # If these were passed, use them
681 if ( $this->mDbUser ) {
682 $wgDBadminuser = $this->mDbUser;
683 }
684 if ( $this->mDbPass ) {
685 $wgDBadminpassword = $this->mDbPass;
686 }
687
688 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
689 $wgDBuser = $wgDBadminuser;
690 $wgDBpassword = $wgDBadminpassword;
691
692 if ( $wgDBservers ) {
693 foreach ( $wgDBservers as $i => $server ) {
694 $wgDBservers[$i]['user'] = $wgDBuser;
695 $wgDBservers[$i]['password'] = $wgDBpassword;
696 }
697 }
698 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
699 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
700 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
701 }
702 LBFactory::destroyInstance();
703 }
704
705 $this->afterFinalSetup();
706
707 $wgShowSQLErrors = true;
708 @set_time_limit( 0 );
709 ini_set( 'memory_limit', $this->memoryLimit() );
710
711 $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
712 }
713
714 /**
715 * Execute a callback function at the end of initialisation
716 */
717 protected function afterFinalSetup() {
718 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
719 call_user_func( MW_CMDLINE_CALLBACK );
720 }
721 }
722
723 /**
724 * Potentially debug globals. Originally a feature only
725 * for refreshLinks
726 */
727 public function globals() {
728 if ( $this->hasOption( 'globals' ) ) {
729 print_r( $GLOBALS );
730 }
731 }
732
733 /**
734 * Do setup specific to WMF
735 */
736 public function loadWikimediaSettings() {
737 global $IP, $wgNoDBParam, $wgUseNormalUser, $wgConf, $site, $lang;
738
739 if ( empty( $wgNoDBParam ) ) {
740 # Check if we were passed a db name
741 if ( isset( $this->mOptions['wiki'] ) ) {
742 $db = $this->mOptions['wiki'];
743 } else {
744 $db = array_shift( $this->mArgs );
745 }
746 list( $site, $lang ) = $wgConf->siteFromDB( $db );
747
748 # If not, work out the language and site the old way
749 if ( is_null( $site ) || is_null( $lang ) ) {
750 if ( !$db ) {
751 $lang = 'aa';
752 } else {
753 $lang = $db;
754 }
755 if ( isset( $this->mArgs[0] ) ) {
756 $site = array_shift( $this->mArgs );
757 } else {
758 $site = 'wikipedia';
759 }
760 }
761 } else {
762 $lang = 'aa';
763 $site = 'wikipedia';
764 }
765
766 # This is for the IRC scripts, which now run as the apache user
767 # The apache user doesn't have access to the wikiadmin_pass command
768 if ( $_ENV['USER'] == 'apache' ) {
769 # if ( posix_geteuid() == 48 ) {
770 $wgUseNormalUser = true;
771 }
772
773 putenv( 'wikilang=' . $lang );
774
775 ini_set( 'include_path', ".:$IP:$IP/includes:$IP/languages:$IP/maintenance" );
776
777 if ( $lang == 'test' && $site == 'wikipedia' ) {
778 define( 'TESTWIKI', 1 );
779 }
780 }
781
782 /**
783 * Generic setup for most installs. Returns the location of LocalSettings
784 * @return String
785 */
786 public function loadSettings() {
787 global $wgWikiFarm, $wgCommandLineMode, $IP;
788
789 $wgWikiFarm = false;
790 if ( isset( $this->mOptions['conf'] ) ) {
791 $settingsFile = $this->mOptions['conf'];
792 } else {
793 $settingsFile = "$IP/LocalSettings.php";
794 }
795 if ( isset( $this->mOptions['wiki'] ) ) {
796 $bits = explode( '-', $this->mOptions['wiki'] );
797 if ( count( $bits ) == 1 ) {
798 $bits[] = '';
799 }
800 define( 'MW_DB', $bits[0] );
801 define( 'MW_PREFIX', $bits[1] );
802 }
803
804 if ( !is_readable( $settingsFile ) ) {
805 $this->error( "A copy of your installation's LocalSettings.php\n" .
806 "must exist and be readable in the source directory.", true );
807 }
808 $wgCommandLineMode = true;
809 return $settingsFile;
810 }
811
812 /**
813 * Support function for cleaning up redundant text records
814 * @param $delete Boolean: whether or not to actually delete the records
815 * @author Rob Church <robchur@gmail.com>
816 */
817 public function purgeRedundantText( $delete = true ) {
818 # Data should come off the master, wrapped in a transaction
819 $dbw = wfGetDB( DB_MASTER );
820 $dbw->begin();
821
822 $tbl_arc = $dbw->tableName( 'archive' );
823 $tbl_rev = $dbw->tableName( 'revision' );
824 $tbl_txt = $dbw->tableName( 'text' );
825
826 # Get "active" text records from the revisions table
827 $this->output( 'Searching for active text records in revisions table...' );
828 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
829 foreach ( $res as $row ) {
830 $cur[] = $row->rev_text_id;
831 }
832 $this->output( "done.\n" );
833
834 # Get "active" text records from the archive table
835 $this->output( 'Searching for active text records in archive table...' );
836 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
837 foreach ( $res as $row ) {
838 $cur[] = $row->ar_text_id;
839 }
840 $this->output( "done.\n" );
841
842 # Get the IDs of all text records not in these sets
843 $this->output( 'Searching for inactive text records...' );
844 $set = implode( ', ', $cur );
845 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
846 $old = array();
847 foreach ( $res as $row ) {
848 $old[] = $row->old_id;
849 }
850 $this->output( "done.\n" );
851
852 # Inform the user of what we're going to do
853 $count = count( $old );
854 $this->output( "$count inactive items found.\n" );
855
856 # Delete as appropriate
857 if ( $delete && $count ) {
858 $this->output( 'Deleting...' );
859 $set = implode( ', ', $old );
860 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
861 $this->output( "done.\n" );
862 }
863
864 # Done
865 $dbw->commit();
866 }
867
868 /**
869 * Get the maintenance directory.
870 */
871 protected function getDir() {
872 return dirname( __FILE__ );
873 }
874
875 /**
876 * Get the list of available maintenance scripts. Note
877 * that if you call this _before_ calling doMaintenance
878 * you won't have any extensions in it yet
879 * @return Array
880 */
881 public static function getMaintenanceScripts() {
882 global $wgMaintenanceScripts;
883 return $wgMaintenanceScripts + self::getCoreScripts();
884 }
885
886 /**
887 * Return all of the core maintenance scripts
888 * @return array
889 */
890 protected static function getCoreScripts() {
891 if ( !self::$mCoreScripts ) {
892 self::disableSetup();
893 $paths = array(
894 dirname( __FILE__ ),
895 dirname( __FILE__ ) . '/gearman',
896 dirname( __FILE__ ) . '/language',
897 dirname( __FILE__ ) . '/storage',
898 );
899 self::$mCoreScripts = array();
900 foreach ( $paths as $p ) {
901 $handle = opendir( $p );
902 while ( ( $file = readdir( $handle ) ) !== false ) {
903 if ( $file == 'Maintenance.php' ) {
904 continue;
905 }
906 $file = $p . '/' . $file;
907 if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
908 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
909 continue;
910 }
911 require( $file );
912 $vars = get_defined_vars();
913 if ( array_key_exists( 'maintClass', $vars ) ) {
914 self::$mCoreScripts[$vars['maintClass']] = $file;
915 }
916 }
917 closedir( $handle );
918 }
919 }
920 return self::$mCoreScripts;
921 }
922
923 /**
924 * Lock the search index
925 * @param &$db Database object
926 */
927 private function lockSearchindex( &$db ) {
928 $write = array( 'searchindex' );
929 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' );
930 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
931 }
932
933 /**
934 * Unlock the tables
935 * @param &$db Database object
936 */
937 private function unlockSearchindex( &$db ) {
938 $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
939 }
940
941 /**
942 * Unlock and lock again
943 * Since the lock is low-priority, queued reads will be able to complete
944 * @param &$db Database object
945 */
946 private function relockSearchindex( &$db ) {
947 $this->unlockSearchindex( $db );
948 $this->lockSearchindex( $db );
949 }
950
951 /**
952 * Perform a search index update with locking
953 * @param $maxLockTime Integer: the maximum time to keep the search index locked.
954 * @param $callback callback String: the function that will update the function.
955 * @param $dbw Database object
956 * @param $results
957 */
958 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
959 $lockTime = time();
960
961 # Lock searchindex
962 if ( $maxLockTime ) {
963 $this->output( " --- Waiting for lock ---" );
964 $this->lockSearchindex( $dbw );
965 $lockTime = time();
966 $this->output( "\n" );
967 }
968
969 # Loop through the results and do a search update
970 foreach ( $results as $row ) {
971 # Allow reads to be processed
972 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
973 $this->output( " --- Relocking ---" );
974 $this->relockSearchindex( $dbw );
975 $lockTime = time();
976 $this->output( "\n" );
977 }
978 call_user_func( $callback, $dbw, $row );
979 }
980
981 # Unlock searchindex
982 if ( $maxLockTime ) {
983 $this->output( " --- Unlocking --" );
984 $this->unlockSearchindex( $dbw );
985 $this->output( "\n" );
986 }
987
988 }
989
990 /**
991 * Update the searchindex table for a given pageid
992 * @param $dbw Database: a database write handle
993 * @param $pageId Integer: the page ID to update.
994 */
995 public function updateSearchIndexForPage( $dbw, $pageId ) {
996 // Get current revision
997 $rev = Revision::loadFromPageId( $dbw, $pageId );
998 $title = null;
999 if ( $rev ) {
1000 $titleObj = $rev->getTitle();
1001 $title = $titleObj->getPrefixedDBkey();
1002 $this->output( "$title..." );
1003 # Update searchindex
1004 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() );
1005 $u->doUpdate();
1006 $this->output( "\n" );
1007 }
1008 return $title;
1009 }
1010
1011 }