Rewrite importUseModWiki to subclass maintenance, general cleanup, etc. Also fixing...
[lhc/web/wiklou.git] / maintenance / Maintenance.php
index 2c96c52..db32201 100644 (file)
@@ -1,19 +1,39 @@
 <?php
 /**
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
  * @file
  * @ingroup Maintenance
  * @defgroup Maintenance Maintenance
  */
 
+// Include global constants, including MW_VERSION and MW_MIN_PHP_VERSION
+require_once( dirname( dirname( __FILE__ ) ) . '/includes/Defines.php' );
+
 // Define this so scripts can easily find doMaintenance.php
-define( 'DO_MAINTENANCE', dirname( __FILE__ ) . '/doMaintenance.php' );
+define( 'RUN_MAINTENANCE_IF_MAIN', dirname( __FILE__ ) . '/doMaintenance.php' );
+define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
+
 $maintClass = false;
 
 // Make sure we're on PHP5 or better
-if ( version_compare( PHP_VERSION, '5.1.0' ) < 0 ) {
-       die ( "Sorry! This version of MediaWiki requires PHP 5.1.x; you are running " .
+if ( version_compare( PHP_VERSION, MW_MIN_PHP_VERSION ) < 0 ) {
+       die ( "Sorry! This version of MediaWiki requires PHP " . MW_MIN_PHP_VERSION . "; you are running " .
                PHP_VERSION . ".\n\n" .
-               "If you are sure you already have PHP 5.1.x or higher installed, it may be\n" .
+               "If you are sure you already have PHP " . MW_MIN_PHP_VERSION . " or higher installed, it may be\n" .
                "installed in a different path from PHP " . PHP_VERSION . ". Check with your system\n" .
                "administrator.\n" );
 }
@@ -33,21 +53,6 @@ if ( !function_exists( 'posix_isatty' ) ) {
  * is the execute() method. See docs/maintenance.txt for more info
  * and a quick demo of how to use it.
  *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- *
  * @author Chad Horohoe <chad@anyonecanedit.org>
  * @since 1.16
  * @ingroup Maintenance
@@ -68,6 +73,9 @@ abstract class Maintenance {
        // This is the desired params
        protected $mParams = array();
 
+       // Array of mapping short parameters to long ones
+       protected $mShortParamsMap = array();
+
        // Array of desired args
        protected $mArgList = array();
 
@@ -90,10 +98,19 @@ abstract class Maintenance {
        // Have we already loaded our user input?
        protected $mInputLoaded = false;
 
-       // Batch size. If a script supports this, they should set
-       // a default with setBatchSize()
+       /**
+        * Batch size. If a script supports this, they should set
+        * a default with setBatchSize()
+        *
+        * @var int
+        */
        protected $mBatchSize = null;
 
+       // Generic options added by addDefaultParams()
+       private $mGenericParameters = array();
+       // Generic options which might or not be supported by the script
+       private $mDependantParameters = array();
+
        /**
         * List of all the core maintenance scripts. This is added
         * to scripts added by extensions in $wgMaintenanceScripts
@@ -102,14 +119,37 @@ abstract class Maintenance {
        protected static $mCoreScripts = null;
 
        /**
-        * Default constructor. Children should call this if implementing
+        * Default constructor. Children should call this *first* if implementing
         * their own constructors
         */
        public function __construct() {
+               // Setup $IP, using MW_INSTALL_PATH if it exists
+               global $IP;
+               $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
+                       ? getenv( 'MW_INSTALL_PATH' )
+                       : realpath( dirname( __FILE__ ) . '/..' );
+
                $this->addDefaultParams();
                register_shutdown_function( array( $this, 'outputChanneled' ), false );
        }
 
+       /**
+        * Should we execute the maintenance script, or just allow it to be included
+        * as a standalone class? It checks that the call stack only includes this
+        * function and a require (meaning was called from the file scope)
+        *
+        * @return Boolean
+        */
+       public static function shouldExecute() {
+               $bt = debug_backtrace();
+               if( count( $bt ) !== 2 ) {
+                       return false;
+               }
+               return in_array( $bt[1]['function'], array( 'require_once', 'require', 'include' ) ) &&
+                       $bt[0]['class'] == 'Maintenance' &&
+                       $bt[0]['function'] == 'shouldExecute';
+       }
+
        /**
         * Do the actual work. All child classes will need to implement this
         */
@@ -123,9 +163,13 @@ abstract class Maintenance {
         * @param $description String: the description of the param to show on --help
         * @param $required Boolean: is the param required?
         * @param $withArg Boolean: is an argument required with this option?
+        * @param $shortName String: character to use as short name
         */
-       protected function addOption( $name, $description, $required = false, $withArg = false ) {
-               $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg );
+       protected function addOption( $name, $description, $required = false, $withArg = false, $shortName = false ) {
+               $this->mParams[$name] = array( 'desc' => $description, 'require' => $required, 'withArg' => $withArg, 'shortName' => $shortName );
+               if ( $shortName !== false ) {
+                       $this->mShortParamsMap[$shortName] = $name;
+               }
        }
 
        /**
@@ -354,8 +398,11 @@ abstract class Maintenance {
         * Add the default parameters to the scripts
         */
        protected function addDefaultParams() {
-               $this->addOption( 'help', 'Display this help message' );
-               $this->addOption( 'quiet', 'Whether to supress non-error output' );
+
+               # Generic (non script dependant) options:
+
+               $this->addOption( 'help', 'Display this help message', false, false, 'h' );
+               $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
                $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
                $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
                $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
@@ -363,6 +410,12 @@ abstract class Maintenance {
                $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
                                "http://en.wikipedia.org. This is sometimes necessary because " .
                                "server name detection may fail in command line scripts.", false, true );
+
+               # Save generic options to display them separately in help
+               $this->mGenericParameters = $this->mParams ;
+
+               # Script dependant options:
+
                // If we support a DB, show the options
                if ( $this->getDbType() > 0 ) {
                        $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
@@ -373,6 +426,9 @@ abstract class Maintenance {
                        $this->addOption( 'batch-size', 'Run this many operations ' .
                                'per batch, default: ' . $this->mBatchSize, false, true );
                }
+               # Save additional script dependant options to display
+               # them separately in help
+               $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
        }
 
        /**
@@ -383,16 +439,12 @@ abstract class Maintenance {
         * @return Maintenance child
         */
        public function runChild( $maintClass, $classFile = null ) {
-               // If we haven't already specified, kill setup procedures
-               // for child scripts, we've already got a sane environment
-               self::disableSetup();
-
                // Make sure the class is loaded first
-               if ( !class_exists( $maintClass ) ) {
+               if ( !MWInit::classExists( $maintClass ) ) {
                        if ( $classFile ) {
                                require_once( $classFile );
                        }
-                       if ( !class_exists( $maintClass ) ) {
+                       if ( !MWInit::classExists( $maintClass ) ) {
                                $this->error( "Cannot spawn child: $maintClass" );
                        }
                }
@@ -402,20 +454,11 @@ abstract class Maintenance {
                return $child;
        }
 
-       /**
-        * Disable Setup.php mostly
-        */
-       protected static function disableSetup() {
-               if ( !defined( 'MW_NO_SETUP' ) ) {
-                       define( 'MW_NO_SETUP', true );
-               }
-       }
-
        /**
         * Do some sanity checking and basic setup
         */
        public function setup() {
-               global $IP, $wgCommandLineMode, $wgRequestTime;
+               global $wgCommandLineMode, $wgRequestTime;
 
                # Abort if called from a web server
                if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
@@ -423,7 +466,7 @@ abstract class Maintenance {
                }
 
                # Make sure we can handle script parameters
-               if ( !ini_get( 'register_argc_argv' ) ) {
+               if ( !function_exists( 'hphp_thread_set_warmup_enabled' ) && !ini_get( 'register_argc_argv' ) ) {
                        $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
                }
 
@@ -459,11 +502,6 @@ abstract class Maintenance {
                # Define us as being in MediaWiki
                define( 'MEDIAWIKI', true );
 
-               # Setup $IP, using MW_INSTALL_PATH if it exists
-               $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
-                       ? getenv( 'MW_INSTALL_PATH' )
-                       : realpath( dirname( __FILE__ ) . '/..' );
-
                $wgCommandLineMode = true;
                # Turn off output buffering if it's on
                @ob_end_flush();
@@ -579,6 +617,9 @@ abstract class Maintenance {
                                # Short options
                                for ( $p = 1; $p < strlen( $arg ); $p++ ) {
                                        $option = $arg { $p } ;
+                                       if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
+                                               $option = $this->mShortParamsMap[$option];
+                                       }
                                        if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
                                                $param = next( $argv );
                                                if ( $param === false ) {
@@ -686,22 +727,75 @@ abstract class Maintenance {
                }
                $this->output( "$output\n\n" );
 
-               // Parameters description
-               foreach ( $this->mParams as $par => $info ) {
+               # TODO abstract some repetitive code below
+
+               // Generic parameters
+               $this->output( "Generic maintenance parameters:\n" );
+               foreach ( $this->mGenericParameters as $par => $info ) {
+                       if ( $info['shortName'] !== false ) {
+                               $par .= " (-{$info['shortName']})";
+                       }
                        $this->output(
                                wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
                                                "\n$tab$tab" ) . "\n"
                        );
                }
+               $this->output( "\n" );
 
-               // Arguments description
-               foreach ( $this->mArgList as $info ) {
-                       $openChar = $info['require'] ? '<' : '[';
-                       $closeChar = $info['require'] ? '>' : ']';
-                       $this->output(
-                               wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
-                                       $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
-                       );
+               $scriptDependantParams = $this->mDependantParameters;
+               if( count($scriptDependantParams) > 0 ) {
+                       $this->output( "Script dependant parameters:\n" );
+                       // Parameters description
+                       foreach ( $scriptDependantParams as $par => $info ) {
+                               if ( $info['shortName'] !== false ) {
+                                       $par .= " (-{$info['shortName']})";
+                               }
+                               $this->output(
+                                       wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
+                                                       "\n$tab$tab" ) . "\n"
+                               );
+                       }
+                       $this->output( "\n" );
+               }
+
+
+               // Script specific parameters not defined on construction by
+               // Maintenance::addDefaultParams()
+               $scriptSpecificParams = array_diff_key(
+                       # all script parameters:
+                       $this->mParams,
+                       # remove the Maintenance default parameters:
+                       $this->mGenericParameters,
+                       $this->mDependantParameters
+               );
+               if( count($scriptSpecificParams) > 0 ) {
+                       $this->output( "Script specific parameters:\n" );
+                       // Parameters description
+                       foreach ( $scriptSpecificParams as $par => $info ) {
+                               if ( $info['shortName'] !== false ) {
+                                       $par .= " (-{$info['shortName']})";
+                               }
+                               $this->output(
+                                       wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
+                                                       "\n$tab$tab" ) . "\n"
+                               );
+                       }
+                       $this->output( "\n" );
+               }
+
+               // Print arguments
+               if( count( $this->mArgList ) > 0 ) {
+                       $this->output( "Arguments:\n" );
+                       // Arguments description
+                       foreach ( $this->mArgList as $info ) {
+                               $openChar = $info['require'] ? '<' : '[';
+                               $closeChar = $info['require'] ? '>' : ']';
+                               $this->output(
+                                       wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
+                                               $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
+                               );
+                       }
+                       $this->output( "\n" );
                }
 
                die( 1 );
@@ -712,7 +806,7 @@ abstract class Maintenance {
         */
        public function finalSetup() {
                global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
-               global $wgProfiling, $wgDBadminuser, $wgDBadminpassword;
+               global $wgDBadminuser, $wgDBadminpassword;
                global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
 
                # Turn off output buffering again, it might have been turned on in the settings files
@@ -757,8 +851,6 @@ abstract class Maintenance {
                $wgShowSQLErrors = true;
                @set_time_limit( 0 );
                $this->adjustMemoryLimit();
-
-               $wgProfiling = false; // only for Profiler.php mode; avoids OOM errors
        }
 
        /**
@@ -942,7 +1034,6 @@ abstract class Maintenance {
         */
        protected static function getCoreScripts() {
                if ( !self::$mCoreScripts ) {
-                       self::disableSetup();
                        $paths = array(
                                dirname( __FILE__ ),
                                dirname( __FILE__ ) . '/gearman',
@@ -1005,7 +1096,7 @@ abstract class Maintenance {
         * Perform a search index update with locking
         * @param $maxLockTime Integer: the maximum time to keep the search index locked.
         * @param $callback callback String: the function that will update the function.
-        * @param $dbw Database object
+        * @param $dbw DatabaseBase object
         * @param $results
         */
        public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
@@ -1069,11 +1160,7 @@ abstract class Maintenance {
        public static function readconsole( $prompt = '> ' ) {
                static $isatty = null;
                if ( is_null( $isatty ) ) {
-                       if ( posix_isatty( 0 /*STDIN*/ ) ) {
-                               $isatty = true;
-                       } else {
-                               $isatty = false;
-                       }
+                       $isatty = posix_isatty( 0 /*STDIN*/ );
                }
 
                if ( $isatty && function_exists( 'readline' ) ) {