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