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