MediaWiki
REL1_20
|
00001 <?php 00023 // Make sure we're on PHP5.3.2 or better 00024 if ( !function_exists( 'version_compare' ) || version_compare( PHP_VERSION, '5.3.2' ) < 0 ) { 00025 // We need to use dirname( __FILE__ ) here cause __DIR__ is PHP5.3+ 00026 require_once( dirname( __FILE__ ) . '/../includes/PHPVersionError.php' ); 00027 wfPHPVersionError( 'cli' ); 00028 } 00029 00035 // Define this so scripts can easily find doMaintenance.php 00036 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' ); 00037 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless 00038 00039 $maintClass = false; 00040 00051 abstract class Maintenance { 00052 00057 const DB_NONE = 0; 00058 const DB_STD = 1; 00059 const DB_ADMIN = 2; 00060 00061 // Const for getStdin() 00062 const STDIN_ALL = 'all'; 00063 00064 // This is the desired params 00065 protected $mParams = array(); 00066 00067 // Array of mapping short parameters to long ones 00068 protected $mShortParamsMap = array(); 00069 00070 // Array of desired args 00071 protected $mArgList = array(); 00072 00073 // This is the list of options that were actually passed 00074 protected $mOptions = array(); 00075 00076 // This is the list of arguments that were actually passed 00077 protected $mArgs = array(); 00078 00079 // Name of the script currently running 00080 protected $mSelf; 00081 00082 // Special vars for params that are always used 00083 protected $mQuiet = false; 00084 protected $mDbUser, $mDbPass; 00085 00086 // A description of the script, children should change this 00087 protected $mDescription = ''; 00088 00089 // Have we already loaded our user input? 00090 protected $mInputLoaded = false; 00091 00098 protected $mBatchSize = null; 00099 00100 // Generic options added by addDefaultParams() 00101 private $mGenericParameters = array(); 00102 // Generic options which might or not be supported by the script 00103 private $mDependantParameters = array(); 00104 00109 private $mDb = null; 00110 00116 protected static $mCoreScripts = null; 00117 00122 public function __construct() { 00123 // Setup $IP, using MW_INSTALL_PATH if it exists 00124 global $IP; 00125 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== '' 00126 ? getenv( 'MW_INSTALL_PATH' ) 00127 : realpath( __DIR__ . '/..' ); 00128 00129 $this->addDefaultParams(); 00130 register_shutdown_function( array( $this, 'outputChanneled' ), false ); 00131 } 00132 00140 public static function shouldExecute() { 00141 $bt = debug_backtrace(); 00142 $count = count( $bt ); 00143 if ( $count < 2 ) { 00144 return false; // sanity 00145 } 00146 if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) { 00147 return false; // last call should be to this function 00148 } 00149 $includeFuncs = array( 'require_once', 'require', 'include', 'include_once' ); 00150 for( $i=1; $i < $count; $i++ ) { 00151 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) { 00152 return false; // previous calls should all be "requires" 00153 } 00154 } 00155 return true; 00156 } 00157 00161 abstract public function execute(); 00162 00173 protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) { 00174 $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName ); 00175 if ( $shortName !== false ) { 00176 $this->mShortParamsMap[$shortName] = $name; 00177 } 00178 } 00179 00185 protected function hasOption( $name ) { 00186 return isset( $this->mOptions[$name] ); 00187 } 00188 00195 protected function getOption( $name, $default = null ) { 00196 if ( $this->hasOption( $name ) ) { 00197 return $this->mOptions[$name]; 00198 } else { 00199 // Set it so we don't have to provide the default again 00200 $this->mOptions[$name] = $default; 00201 return $this->mOptions[$name]; 00202 } 00203 } 00204 00211 protected function addArg( $arg, $description, $required = true ) { 00212 $this->mArgList[] = array( 00213 'name' => $arg, 00214 'desc' => $description, 00215 'require' => $required 00216 ); 00217 } 00218 00223 protected function deleteOption( $name ) { 00224 unset( $this->mParams[$name] ); 00225 } 00226 00231 protected function addDescription( $text ) { 00232 $this->mDescription = $text; 00233 } 00234 00240 protected function hasArg( $argId = 0 ) { 00241 return isset( $this->mArgs[$argId] ); 00242 } 00243 00250 protected function getArg( $argId = 0, $default = null ) { 00251 return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default; 00252 } 00253 00258 protected function setBatchSize( $s = 0 ) { 00259 $this->mBatchSize = $s; 00260 00261 // If we support $mBatchSize, show the option. 00262 // Used to be in addDefaultParams, but in order for that to 00263 // work, subclasses would have to call this function in the constructor 00264 // before they called parent::__construct which is just weird 00265 // (and really wasn't done). 00266 if ( $this->mBatchSize ) { 00267 $this->addOption( 'batch-size', 'Run this many operations ' . 00268 'per batch, default: ' . $this->mBatchSize, false, true ); 00269 if ( isset( $this->mParams['batch-size'] ) ) { 00270 // This seems a little ugly... 00271 $this->mDependantParameters['batch-size'] = $this->mParams['batch-size']; 00272 } 00273 } 00274 } 00275 00280 public function getName() { 00281 return $this->mSelf; 00282 } 00283 00291 protected function getStdin( $len = null ) { 00292 if ( $len == Maintenance::STDIN_ALL ) { 00293 return file_get_contents( 'php://stdin' ); 00294 } 00295 $f = fopen( 'php://stdin', 'rt' ); 00296 if ( !$len ) { 00297 return $f; 00298 } 00299 $input = fgets( $f, $len ); 00300 fclose( $f ); 00301 return rtrim( $input ); 00302 } 00303 00307 public function isQuiet() { 00308 return $this->mQuiet; 00309 } 00310 00318 protected function output( $out, $channel = null ) { 00319 if ( $this->mQuiet ) { 00320 return; 00321 } 00322 if ( $channel === null ) { 00323 $this->cleanupChanneled(); 00324 print( $out ); 00325 } else { 00326 $out = preg_replace( '/\n\z/', '', $out ); 00327 $this->outputChanneled( $out, $channel ); 00328 } 00329 } 00330 00337 protected function error( $err, $die = 0 ) { 00338 $this->outputChanneled( false ); 00339 if ( php_sapi_name() == 'cli' ) { 00340 fwrite( STDERR, $err . "\n" ); 00341 } else { 00342 print $err; 00343 } 00344 $die = intval( $die ); 00345 if ( $die > 0 ) { 00346 die( $die ); 00347 } 00348 } 00349 00350 private $atLineStart = true; 00351 private $lastChannel = null; 00352 00356 public function cleanupChanneled() { 00357 if ( !$this->atLineStart ) { 00358 print "\n"; 00359 $this->atLineStart = true; 00360 } 00361 } 00362 00371 public function outputChanneled( $msg, $channel = null ) { 00372 if ( $msg === false ) { 00373 $this->cleanupChanneled(); 00374 return; 00375 } 00376 00377 // End the current line if necessary 00378 if ( !$this->atLineStart && $channel !== $this->lastChannel ) { 00379 print "\n"; 00380 } 00381 00382 print $msg; 00383 00384 $this->atLineStart = false; 00385 if ( $channel === null ) { 00386 // For unchanneled messages, output trailing newline immediately 00387 print "\n"; 00388 $this->atLineStart = true; 00389 } 00390 $this->lastChannel = $channel; 00391 } 00392 00403 public function getDbType() { 00404 return Maintenance::DB_STD; 00405 } 00406 00410 protected function addDefaultParams() { 00411 00412 # Generic (non script dependant) options: 00413 00414 $this->addOption( 'help', 'Display this help message', false, false, 'h' ); 00415 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' ); 00416 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true ); 00417 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true ); 00418 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' ); 00419 $this->addOption( 'memory-limit', 'Set a specific memory limit for the script, "max" for no limit or "default" to avoid changing it' ); 00420 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " . 00421 "http://en.wikipedia.org. This is sometimes necessary because " . 00422 "server name detection may fail in command line scripts.", false, true ); 00423 00424 # Save generic options to display them separately in help 00425 $this->mGenericParameters = $this->mParams ; 00426 00427 # Script dependant options: 00428 00429 // If we support a DB, show the options 00430 if ( $this->getDbType() > 0 ) { 00431 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true ); 00432 $this->addOption( 'dbpass', 'The password to use for this script', false, true ); 00433 } 00434 00435 # Save additional script dependant options to display 00436 # them separately in help 00437 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters ); 00438 } 00439 00447 public function runChild( $maintClass, $classFile = null ) { 00448 // Make sure the class is loaded first 00449 if ( !MWInit::classExists( $maintClass ) ) { 00450 if ( $classFile ) { 00451 require_once( $classFile ); 00452 } 00453 if ( !MWInit::classExists( $maintClass ) ) { 00454 $this->error( "Cannot spawn child: $maintClass" ); 00455 } 00456 } 00457 00461 $child = new $maintClass(); 00462 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs ); 00463 if ( !is_null( $this->mDb ) ) { 00464 $child->setDB( $this->mDb ); 00465 } 00466 return $child; 00467 } 00468 00472 public function setup() { 00473 global $wgCommandLineMode, $wgRequestTime; 00474 00475 # Abort if called from a web server 00476 if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) { 00477 $this->error( 'This script must be run from the command line', true ); 00478 } 00479 00480 # Make sure we can handle script parameters 00481 if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) { 00482 $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true ); 00483 } 00484 00485 if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) { 00486 // Send PHP warnings and errors to stderr instead of stdout. 00487 // This aids in diagnosing problems, while keeping messages 00488 // out of redirected output. 00489 if ( ini_get( 'display_errors' ) ) { 00490 ini_set( 'display_errors', 'stderr' ); 00491 } 00492 00493 // Don't touch the setting on earlier versions of PHP, 00494 // as setting it would disable output if you'd wanted it. 00495 00496 // Note that exceptions are also sent to stderr when 00497 // command-line mode is on, regardless of PHP version. 00498 } 00499 00500 $this->loadParamsAndArgs(); 00501 $this->maybeHelp(); 00502 00503 # Set the memory limit 00504 # Note we need to set it again later in cache LocalSettings changed it 00505 $this->adjustMemoryLimit(); 00506 00507 # Set max execution time to 0 (no limit). PHP.net says that 00508 # "When running PHP from the command line the default setting is 0." 00509 # But sometimes this doesn't seem to be the case. 00510 ini_set( 'max_execution_time', 0 ); 00511 00512 $wgRequestTime = microtime( true ); 00513 00514 # Define us as being in MediaWiki 00515 define( 'MEDIAWIKI', true ); 00516 00517 $wgCommandLineMode = true; 00518 # Turn off output buffering if it's on 00519 @ob_end_flush(); 00520 00521 $this->validateParamsAndArgs(); 00522 } 00523 00533 public function memoryLimit() { 00534 $limit = $this->getOption( 'memory-limit', 'max' ); 00535 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood 00536 return $limit; 00537 } 00538 00542 protected function adjustMemoryLimit() { 00543 $limit = $this->memoryLimit(); 00544 if ( $limit == 'max' ) { 00545 $limit = -1; // no memory limit 00546 } 00547 if ( $limit != 'default' ) { 00548 ini_set( 'memory_limit', $limit ); 00549 } 00550 } 00551 00555 public function clearParamsAndArgs() { 00556 $this->mOptions = array(); 00557 $this->mArgs = array(); 00558 $this->mInputLoaded = false; 00559 } 00560 00570 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) { 00571 # If we were given opts or args, set those and return early 00572 if ( $self ) { 00573 $this->mSelf = $self; 00574 $this->mInputLoaded = true; 00575 } 00576 if ( $opts ) { 00577 $this->mOptions = $opts; 00578 $this->mInputLoaded = true; 00579 } 00580 if ( $args ) { 00581 $this->mArgs = $args; 00582 $this->mInputLoaded = true; 00583 } 00584 00585 # If we've already loaded input (either by user values or from $argv) 00586 # skip on loading it again. The array_shift() will corrupt values if 00587 # it's run again and again 00588 if ( $this->mInputLoaded ) { 00589 $this->loadSpecialVars(); 00590 return; 00591 } 00592 00593 global $argv; 00594 $this->mSelf = array_shift( $argv ); 00595 00596 $options = array(); 00597 $args = array(); 00598 00599 # Parse arguments 00600 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) { 00601 if ( $arg == '--' ) { 00602 # End of options, remainder should be considered arguments 00603 $arg = next( $argv ); 00604 while ( $arg !== false ) { 00605 $args[] = $arg; 00606 $arg = next( $argv ); 00607 } 00608 break; 00609 } elseif ( substr( $arg, 0, 2 ) == '--' ) { 00610 # Long options 00611 $option = substr( $arg, 2 ); 00612 if ( array_key_exists( $option, $options ) ) { 00613 $this->error( "\nERROR: $option parameter given twice\n" ); 00614 $this->maybeHelp( true ); 00615 } 00616 if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) { 00617 $param = next( $argv ); 00618 if ( $param === false ) { 00619 $this->error( "\nERROR: $option parameter needs a value after it\n" ); 00620 $this->maybeHelp( true ); 00621 } 00622 $options[$option] = $param; 00623 } else { 00624 $bits = explode( '=', $option, 2 ); 00625 if ( count( $bits ) > 1 ) { 00626 $option = $bits[0]; 00627 $param = $bits[1]; 00628 } else { 00629 $param = 1; 00630 } 00631 $options[$option] = $param; 00632 } 00633 } elseif ( substr( $arg, 0, 1 ) == '-' ) { 00634 # Short options 00635 for ( $p = 1; $p < strlen( $arg ); $p++ ) { 00636 $option = $arg { $p } ; 00637 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) { 00638 $option = $this->mShortParamsMap[$option]; 00639 } 00640 if ( array_key_exists( $option, $options ) ) { 00641 $this->error( "\nERROR: $option parameter given twice\n" ); 00642 $this->maybeHelp( true ); 00643 } 00644 if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) { 00645 $param = next( $argv ); 00646 if ( $param === false ) { 00647 $this->error( "\nERROR: $option parameter needs a value after it\n" ); 00648 $this->maybeHelp( true ); 00649 } 00650 $options[$option] = $param; 00651 } else { 00652 $options[$option] = 1; 00653 } 00654 } 00655 } else { 00656 $args[] = $arg; 00657 } 00658 } 00659 00660 $this->mOptions = $options; 00661 $this->mArgs = $args; 00662 $this->loadSpecialVars(); 00663 $this->mInputLoaded = true; 00664 } 00665 00669 protected function validateParamsAndArgs() { 00670 $die = false; 00671 # Check to make sure we've got all the required options 00672 foreach ( $this->mParams as $opt => $info ) { 00673 if ( $info['require'] && !$this->hasOption( $opt ) ) { 00674 $this->error( "Param $opt required!" ); 00675 $die = true; 00676 } 00677 } 00678 # Check arg list too 00679 foreach ( $this->mArgList as $k => $info ) { 00680 if ( $info['require'] && !$this->hasArg( $k ) ) { 00681 $this->error( 'Argument <' . $info['name'] . '> required!' ); 00682 $die = true; 00683 } 00684 } 00685 00686 if ( $die ) { 00687 $this->maybeHelp( true ); 00688 } 00689 } 00690 00694 protected function loadSpecialVars() { 00695 if ( $this->hasOption( 'dbuser' ) ) { 00696 $this->mDbUser = $this->getOption( 'dbuser' ); 00697 } 00698 if ( $this->hasOption( 'dbpass' ) ) { 00699 $this->mDbPass = $this->getOption( 'dbpass' ); 00700 } 00701 if ( $this->hasOption( 'quiet' ) ) { 00702 $this->mQuiet = true; 00703 } 00704 if ( $this->hasOption( 'batch-size' ) ) { 00705 $this->mBatchSize = intval( $this->getOption( 'batch-size' ) ); 00706 } 00707 } 00708 00713 protected function maybeHelp( $force = false ) { 00714 if( !$force && !$this->hasOption( 'help' ) ) { 00715 return; 00716 } 00717 00718 $screenWidth = 80; // TODO: Caculate this! 00719 $tab = " "; 00720 $descWidth = $screenWidth - ( 2 * strlen( $tab ) ); 00721 00722 ksort( $this->mParams ); 00723 $this->mQuiet = false; 00724 00725 // Description ... 00726 if ( $this->mDescription ) { 00727 $this->output( "\n" . $this->mDescription . "\n" ); 00728 } 00729 $output = "\nUsage: php " . basename( $this->mSelf ); 00730 00731 // ... append parameters ... 00732 if ( $this->mParams ) { 00733 $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]"; 00734 } 00735 00736 // ... and append arguments. 00737 if ( $this->mArgList ) { 00738 $output .= ' '; 00739 foreach ( $this->mArgList as $k => $arg ) { 00740 if ( $arg['require'] ) { 00741 $output .= '<' . $arg['name'] . '>'; 00742 } else { 00743 $output .= '[' . $arg['name'] . ']'; 00744 } 00745 if ( $k < count( $this->mArgList ) - 1 ) 00746 $output .= ' '; 00747 } 00748 } 00749 $this->output( "$output\n\n" ); 00750 00751 # TODO abstract some repetitive code below 00752 00753 // Generic parameters 00754 $this->output( "Generic maintenance parameters:\n" ); 00755 foreach ( $this->mGenericParameters as $par => $info ) { 00756 if ( $info['shortName'] !== false ) { 00757 $par .= " (-{$info['shortName']})"; 00758 } 00759 $this->output( 00760 wordwrap( "$tab--$par: " . $info['desc'], $descWidth, 00761 "\n$tab$tab" ) . "\n" 00762 ); 00763 } 00764 $this->output( "\n" ); 00765 00766 $scriptDependantParams = $this->mDependantParameters; 00767 if( count($scriptDependantParams) > 0 ) { 00768 $this->output( "Script dependant parameters:\n" ); 00769 // Parameters description 00770 foreach ( $scriptDependantParams as $par => $info ) { 00771 if ( $info['shortName'] !== false ) { 00772 $par .= " (-{$info['shortName']})"; 00773 } 00774 $this->output( 00775 wordwrap( "$tab--$par: " . $info['desc'], $descWidth, 00776 "\n$tab$tab" ) . "\n" 00777 ); 00778 } 00779 $this->output( "\n" ); 00780 } 00781 00782 00783 // Script specific parameters not defined on construction by 00784 // Maintenance::addDefaultParams() 00785 $scriptSpecificParams = array_diff_key( 00786 # all script parameters: 00787 $this->mParams, 00788 # remove the Maintenance default parameters: 00789 $this->mGenericParameters, 00790 $this->mDependantParameters 00791 ); 00792 if( count($scriptSpecificParams) > 0 ) { 00793 $this->output( "Script specific parameters:\n" ); 00794 // Parameters description 00795 foreach ( $scriptSpecificParams as $par => $info ) { 00796 if ( $info['shortName'] !== false ) { 00797 $par .= " (-{$info['shortName']})"; 00798 } 00799 $this->output( 00800 wordwrap( "$tab--$par: " . $info['desc'], $descWidth, 00801 "\n$tab$tab" ) . "\n" 00802 ); 00803 } 00804 $this->output( "\n" ); 00805 } 00806 00807 // Print arguments 00808 if( count( $this->mArgList ) > 0 ) { 00809 $this->output( "Arguments:\n" ); 00810 // Arguments description 00811 foreach ( $this->mArgList as $info ) { 00812 $openChar = $info['require'] ? '<' : '['; 00813 $closeChar = $info['require'] ? '>' : ']'; 00814 $this->output( 00815 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " . 00816 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n" 00817 ); 00818 } 00819 $this->output( "\n" ); 00820 } 00821 00822 die( 1 ); 00823 } 00824 00828 public function finalSetup() { 00829 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer; 00830 global $wgDBadminuser, $wgDBadminpassword; 00831 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf; 00832 00833 # Turn off output buffering again, it might have been turned on in the settings files 00834 if ( ob_get_level() ) { 00835 ob_end_flush(); 00836 } 00837 # Same with these 00838 $wgCommandLineMode = true; 00839 00840 # Override $wgServer 00841 if( $this->hasOption( 'server') ) { 00842 $wgServer = $this->getOption( 'server', $wgServer ); 00843 } 00844 00845 # If these were passed, use them 00846 if ( $this->mDbUser ) { 00847 $wgDBadminuser = $this->mDbUser; 00848 } 00849 if ( $this->mDbPass ) { 00850 $wgDBadminpassword = $this->mDbPass; 00851 } 00852 00853 if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) { 00854 $wgDBuser = $wgDBadminuser; 00855 $wgDBpassword = $wgDBadminpassword; 00856 00857 if ( $wgDBservers ) { 00861 foreach ( $wgDBservers as $i => $server ) { 00862 $wgDBservers[$i]['user'] = $wgDBuser; 00863 $wgDBservers[$i]['password'] = $wgDBpassword; 00864 } 00865 } 00866 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) { 00867 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser; 00868 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword; 00869 } 00870 LBFactory::destroyInstance(); 00871 } 00872 00873 $this->afterFinalSetup(); 00874 00875 $wgShowSQLErrors = true; 00876 @set_time_limit( 0 ); 00877 $this->adjustMemoryLimit(); 00878 } 00879 00883 protected function afterFinalSetup() { 00884 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) { 00885 call_user_func( MW_CMDLINE_CALLBACK ); 00886 } 00887 } 00888 00893 public function globals() { 00894 if ( $this->hasOption( 'globals' ) ) { 00895 print_r( $GLOBALS ); 00896 } 00897 } 00898 00903 public function loadSettings() { 00904 global $wgCommandLineMode, $IP; 00905 00906 if ( isset( $this->mOptions['conf'] ) ) { 00907 $settingsFile = $this->mOptions['conf']; 00908 } elseif ( defined("MW_CONFIG_FILE") ) { 00909 $settingsFile = MW_CONFIG_FILE; 00910 } else { 00911 $settingsFile = "$IP/LocalSettings.php"; 00912 } 00913 if ( isset( $this->mOptions['wiki'] ) ) { 00914 $bits = explode( '-', $this->mOptions['wiki'] ); 00915 if ( count( $bits ) == 1 ) { 00916 $bits[] = ''; 00917 } 00918 define( 'MW_DB', $bits[0] ); 00919 define( 'MW_PREFIX', $bits[1] ); 00920 } 00921 00922 if ( !is_readable( $settingsFile ) ) { 00923 $this->error( "A copy of your installation's LocalSettings.php\n" . 00924 "must exist and be readable in the source directory.\n" . 00925 "Use --conf to specify it." , true ); 00926 } 00927 $wgCommandLineMode = true; 00928 return $settingsFile; 00929 } 00930 00936 public function purgeRedundantText( $delete = true ) { 00937 # Data should come off the master, wrapped in a transaction 00938 $dbw = $this->getDB( DB_MASTER ); 00939 $dbw->begin( __METHOD__ ); 00940 00941 $tbl_arc = $dbw->tableName( 'archive' ); 00942 $tbl_rev = $dbw->tableName( 'revision' ); 00943 $tbl_txt = $dbw->tableName( 'text' ); 00944 00945 # Get "active" text records from the revisions table 00946 $this->output( 'Searching for active text records in revisions table...' ); 00947 $res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" ); 00948 foreach ( $res as $row ) { 00949 $cur[] = $row->rev_text_id; 00950 } 00951 $this->output( "done.\n" ); 00952 00953 # Get "active" text records from the archive table 00954 $this->output( 'Searching for active text records in archive table...' ); 00955 $res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" ); 00956 foreach ( $res as $row ) { 00957 $cur[] = $row->ar_text_id; 00958 } 00959 $this->output( "done.\n" ); 00960 00961 # Get the IDs of all text records not in these sets 00962 $this->output( 'Searching for inactive text records...' ); 00963 $set = implode( ', ', $cur ); 00964 $res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" ); 00965 $old = array(); 00966 foreach ( $res as $row ) { 00967 $old[] = $row->old_id; 00968 } 00969 $this->output( "done.\n" ); 00970 00971 # Inform the user of what we're going to do 00972 $count = count( $old ); 00973 $this->output( "$count inactive items found.\n" ); 00974 00975 # Delete as appropriate 00976 if ( $delete && $count ) { 00977 $this->output( 'Deleting...' ); 00978 $set = implode( ', ', $old ); 00979 $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" ); 00980 $this->output( "done.\n" ); 00981 } 00982 00983 # Done 00984 $dbw->commit( __METHOD__ ); 00985 } 00986 00991 protected function getDir() { 00992 return __DIR__; 00993 } 00994 01001 public static function getMaintenanceScripts() { 01002 global $wgMaintenanceScripts; 01003 return $wgMaintenanceScripts + self::getCoreScripts(); 01004 } 01005 01010 protected static function getCoreScripts() { 01011 if ( !self::$mCoreScripts ) { 01012 $paths = array( 01013 __DIR__, 01014 __DIR__ . '/language', 01015 __DIR__ . '/storage', 01016 ); 01017 self::$mCoreScripts = array(); 01018 foreach ( $paths as $p ) { 01019 $handle = opendir( $p ); 01020 while ( ( $file = readdir( $handle ) ) !== false ) { 01021 if ( $file == 'Maintenance.php' ) { 01022 continue; 01023 } 01024 $file = $p . '/' . $file; 01025 if ( is_dir( $file ) || !strpos( $file, '.php' ) || 01026 ( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) { 01027 continue; 01028 } 01029 require( $file ); 01030 $vars = get_defined_vars(); 01031 if ( array_key_exists( 'maintClass', $vars ) ) { 01032 self::$mCoreScripts[$vars['maintClass']] = $file; 01033 } 01034 } 01035 closedir( $handle ); 01036 } 01037 } 01038 return self::$mCoreScripts; 01039 } 01040 01048 protected function &getDB( $db, $groups = array(), $wiki = false ) { 01049 if ( is_null( $this->mDb ) ) { 01050 return wfGetDB( $db, $groups, $wiki ); 01051 } else { 01052 return $this->mDb; 01053 } 01054 } 01055 01061 public function setDB( &$db ) { 01062 $this->mDb = $db; 01063 } 01064 01069 private function lockSearchindex( &$db ) { 01070 $write = array( 'searchindex' ); 01071 $read = array( 'page', 'revision', 'text', 'interwiki', 'l10n_cache' ); 01072 $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ ); 01073 } 01074 01079 private function unlockSearchindex( &$db ) { 01080 $db->unlockTables( __CLASS__ . '::' . __METHOD__ ); 01081 } 01082 01088 private function relockSearchindex( &$db ) { 01089 $this->unlockSearchindex( $db ); 01090 $this->lockSearchindex( $db ); 01091 } 01092 01100 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) { 01101 $lockTime = time(); 01102 01103 # Lock searchindex 01104 if ( $maxLockTime ) { 01105 $this->output( " --- Waiting for lock ---" ); 01106 $this->lockSearchindex( $dbw ); 01107 $lockTime = time(); 01108 $this->output( "\n" ); 01109 } 01110 01111 # Loop through the results and do a search update 01112 foreach ( $results as $row ) { 01113 # Allow reads to be processed 01114 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) { 01115 $this->output( " --- Relocking ---" ); 01116 $this->relockSearchindex( $dbw ); 01117 $lockTime = time(); 01118 $this->output( "\n" ); 01119 } 01120 call_user_func( $callback, $dbw, $row ); 01121 } 01122 01123 # Unlock searchindex 01124 if ( $maxLockTime ) { 01125 $this->output( " --- Unlocking --" ); 01126 $this->unlockSearchindex( $dbw ); 01127 $this->output( "\n" ); 01128 } 01129 01130 } 01131 01138 public function updateSearchIndexForPage( $dbw, $pageId ) { 01139 // Get current revision 01140 $rev = Revision::loadFromPageId( $dbw, $pageId ); 01141 $title = null; 01142 if ( $rev ) { 01143 $titleObj = $rev->getTitle(); 01144 $title = $titleObj->getPrefixedDBkey(); 01145 $this->output( "$title..." ); 01146 # Update searchindex 01147 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getText() ); 01148 $u->doUpdate(); 01149 $this->output( "\n" ); 01150 } 01151 return $title; 01152 } 01153 01162 public static function posix_isatty( $fd ) { 01163 if ( !MWInit::functionExists( 'posix_isatty' ) ) { 01164 return !$fd; 01165 } else { 01166 return posix_isatty( $fd ); 01167 } 01168 } 01169 01175 public static function readconsole( $prompt = '> ' ) { 01176 static $isatty = null; 01177 if ( is_null( $isatty ) ) { 01178 $isatty = self::posix_isatty( 0 /*STDIN*/ ); 01179 } 01180 01181 if ( $isatty && function_exists( 'readline' ) ) { 01182 return readline( $prompt ); 01183 } else { 01184 if ( $isatty ) { 01185 $st = self::readlineEmulation( $prompt ); 01186 } else { 01187 if ( feof( STDIN ) ) { 01188 $st = false; 01189 } else { 01190 $st = fgets( STDIN, 1024 ); 01191 } 01192 } 01193 if ( $st === false ) return false; 01194 $resp = trim( $st ); 01195 return $resp; 01196 } 01197 } 01198 01204 private static function readlineEmulation( $prompt ) { 01205 $bash = Installer::locateExecutableInDefaultPaths( array( 'bash' ) ); 01206 if ( !wfIsWindows() && $bash ) { 01207 $retval = false; 01208 $encPrompt = wfEscapeShellArg( $prompt ); 01209 $command = "read -er -p $encPrompt && echo \"\$REPLY\""; 01210 $encCommand = wfEscapeShellArg( $command ); 01211 $line = wfShellExec( "$bash -c $encCommand", $retval ); 01212 01213 if ( $retval == 0 ) { 01214 return $line; 01215 } elseif ( $retval == 127 ) { 01216 // Couldn't execute bash even though we thought we saw it. 01217 // Shell probably spit out an error message, sorry :( 01218 // Fall through to fgets()... 01219 } else { 01220 // EOF/ctrl+D 01221 return false; 01222 } 01223 } 01224 01225 // Fallback... we'll have no editing controls, EWWW 01226 if ( feof( STDIN ) ) { 01227 return false; 01228 } 01229 print $prompt; 01230 return fgets( STDIN, 1024 ); 01231 } 01232 } 01233 01237 class FakeMaintenance extends Maintenance { 01238 protected $mSelf = "FakeMaintenanceScript"; 01239 public function execute() { 01240 return; 01241 } 01242 } 01243 01248 abstract class LoggedUpdateMaintenance extends Maintenance { 01249 public function __construct() { 01250 parent::__construct(); 01251 $this->addOption( 'force', 'Run the update even if it was completed already' ); 01252 $this->setBatchSize( 200 ); 01253 } 01254 01255 public function execute() { 01256 $db = $this->getDB( DB_MASTER ); 01257 $key = $this->getUpdateKey(); 01258 01259 if ( !$this->hasOption( 'force' ) && 01260 $db->selectRow( 'updatelog', '1', array( 'ul_key' => $key ), __METHOD__ ) ) 01261 { 01262 $this->output( "..." . $this->updateSkippedMessage() . "\n" ); 01263 return true; 01264 } 01265 01266 if ( !$this->doDBUpdates() ) { 01267 return false; 01268 } 01269 01270 if ( 01271 $db->insert( 'updatelog', array( 'ul_key' => $key ), __METHOD__, 'IGNORE' ) ) 01272 { 01273 return true; 01274 } else { 01275 $this->output( $this->updatelogFailedMessage() . "\n" ); 01276 return false; 01277 } 01278 } 01279 01284 protected function updateSkippedMessage() { 01285 $key = $this->getUpdateKey(); 01286 return "Update '{$key}' already logged as completed."; 01287 } 01288 01293 protected function updatelogFailedMessage() { 01294 $key = $this->getUpdateKey(); 01295 return "Unable to log update '{$key}' as completed."; 01296 } 01297 01303 abstract protected function doDBUpdates(); 01304 01309 abstract protected function getUpdateKey(); 01310 }