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