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