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