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