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