From 2f13f94ccc7fe3a004f736f513be54b4c4f0de3c Mon Sep 17 00:00:00 2001 From: mjollnir_ Date: Mon, 7 Jan 2008 01:54:28 +0000 Subject: [PATCH] New feature: Command line installer. Credit: Dilan Anurudda. This was a Google Summer of Code 2007 Project. This introduces two new files, admin/cliupgrader.php and lib/installlib.php. It also introduces a new PEAR library, Console_GetOpt. I have recieved permission from the upstream author to include this in GPL Moodle (essentially dual license it) - notes in lib/pear. Most stuff that outputs html during install gets suppressed by the use of a constant. Run the script like php admin/cliupgrade.php --help for info. Note that this all uses strings from install/ rather than lang, so I have updated stringnames.txt accordingly and they'll all be broken until the cronjob that generates them runs. --- admin/cliupgrade.php | 1308 +++++++++++++++++++++++++++++++++++ backup/lib.php | 32 +- install/stringnames.txt | 87 +++ lang/en_utf8/install.php | 101 +++ lib/adminlib.php | 75 +- lib/blocklib.php | 69 +- lib/dmllib.php | 6 + lib/installlib.php | 632 +++++++++++++++++ lib/locallib.php | 17 + lib/pear/Console/Getopt.php | 290 ++++++++ lib/pear/Console/README | 5 + lib/pear/README.txt | 5 + lib/setuplib.php | 3 + lib/weblib.php | 38 +- 14 files changed, 2642 insertions(+), 26 deletions(-) create mode 100644 admin/cliupgrade.php create mode 100644 lib/installlib.php create mode 100644 lib/pear/Console/Getopt.php create mode 100644 lib/pear/Console/README diff --git a/admin/cliupgrade.php b/admin/cliupgrade.php new file mode 100644 index 0000000000..95749584fa --- /dev/null +++ b/admin/cliupgrade.php @@ -0,0 +1,1308 @@ +CLI_VAL_REQ, +'webaddr' =>CLI_VAL_REQ, +'moodledir' =>CLI_VAL_REQ, +'datadir' =>CLI_VAL_REQ, +'dbtype' =>CLI_VAL_REQ, +'dbhost' =>CLI_VAL_REQ, +'dbname' =>CLI_VAL_REQ, +'dbuser' =>CLI_VAL_REQ, +'dbpass' =>CLI_VAL_REQ, +'prefix' =>CLI_VAL_REQ, +'agreelicense' =>CLI_VAL_REQ, +'confirmrelease' =>CLI_VAL_REQ, +'sitefullname' =>CLI_VAL_REQ, +'siteshortname' =>CLI_VAL_REQ, +'sitesummary' =>CLI_VAL_REQ, +'sitenewsitems' =>CLI_VAL_REQ, +'adminfirstname' =>CLI_VAL_REQ, +'adminlastname' =>CLI_VAL_REQ, +'adminusername' =>CLI_VAL_REQ, +'adminpassword' =>CLI_VAL_REQ, +'adminemail' =>CLI_VAL_REQ, +'verbose' =>CLI_VAL_REQ, +'interactivelevel' =>CLI_VAL_REQ, +'help' =>CLI_VAL_OPT); + +//Initialize the intall array +$INSTALL=array(); + +$SESSION->lang = $DEFAULT['lang']; +$CFG->dirroot = $DEFAULT['dirroot']; +$CFG->libdir = $DEFAULT['dirroot'].'/lib'; +$CFG->dataroot = $DEFAULT['dataroot']; +$CFG->admin = $DEFAULT['admindirname']; +$CFG->directorypermissions = 00777; +$CFG->running_installer = true; +$COURSE->id = 0; + +// include standard Moodle libraries + +require_once($CFG->libdir.'/adminlib.php'); +require_once($CFG->libdir.'/setuplib.php'); +require_once($CFG->libdir.'/moodlelib.php'); +require_once($CFG->libdir.'/weblib.php'); +require_once($CFG->libdir.'/adodb/adodb.inc.php'); +require_once($CFG->libdir.'/environmentlib.php'); +require_once($CFG->libdir.'/xmlize.php'); +require_once($CFG->libdir.'/componentlib.class.php'); +require_once($CFG->libdir.'/installlib.php'); //cli-library +require_once($CFG->dirroot.'/version.php'); + +//include PEAR Console libraries +set_include_path($CFG->libdir . PATH_SEPARATOR . $CFG->libdir . '/pear/'); +require_once('Console/Getopt.php'); + + +/// Set default values - things that require the libraries +$DEFAULT['adminfirstname'] = get_string('admin'); +$DEFAULT['adminlastname'] = get_string('user'); + + + +/// Set version and release +$INSTALL['version'] = $version; +$INSTALL['release'] = $release; + + + + +//========================================================================================// +//Command line option processing// + +//fetch arguments +$args = Console_Getopt::readPHPArgv(); + +//checking errors for argument fetching +if (PEAR::isError($args)) { + console_write(STDOUT,'pearargerror','install'); + die(); +} + +//short options +$short_opts = ''; +//long options +$long_opts = create_long_options($LONG_OPTIONS); + + +//get the argumets to options array +if ( realpath($_SERVER['argv'][0]) == __FILE__ && count($args)>1) { + $console_opt = Console_Getopt::getOpt($args,$short_opts,$long_opts); +} else { + $console_opt = Console_Getopt::getOpt($args,$short_opts,$long_opts); +} + +//detect erros in the options +if (PEAR::isError($console_opt)) { + console_write(STDOUT,'invalidargumenthelp'); + die(); +} + +//Get the option values to an array of option keys and values +$options=get_options($console_opt); + +// if user want help print the help without validating option values +if (is_array($options)) { + if(array_key_exists('help',$options)){ + console_write(STDOUT,'usagehelp'); + die ; + } +} + +//check for validity of options and exit if errors found +validate_option_values($options); + +// insert options array options into INSTALL array +foreach ( $options as $key=>$value) { + + //map input argument value to INSTALL array values, Argument names kept bcoz they make sense!!! + if ( $key == 'moodledir') { + $key='dirroot'; + } else if ($key == 'webaddr'){ + $key='wwwroot'; + } else if ($key == 'datadir') { + $key = 'dataroot'; + } + $INSTALL[$key]=$value; +} + + +// if verbose is not set at commandline assume default values +if (!isset($INSTALL['verbose'])) { + $INSTALL['verbose']=$DEFAULT['verbose']; +} +//if interactive level is not set at commandline assume default value +if (!isset($INSTALL['interactivelevel'])) { + $INSTALL['interactivelevel'] = $DEFAULT['interactivelevel']; +} + + +// set references for interactive level and verbose install array +$interactive = &$INSTALL['interactivelevel']; +$verbose = &$INSTALL['verbose']; + +if (!file_exists(dirname(dirname(__FILE__)) . '/config.php')) { + + $configfile = dirname(dirname(__FILE__)) . '/config.php'; + + + + //welcome message + if ($verbose > CLI_NO) { + console_write(STDOUT,'welcometext','install'); + } + //============================================================================// + //Language selection for the installation + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['lang'])) ) ) { + $langs=get_installer_list_of_languages(); + + console_write(STDOUT,'selectlanguage','install'); + console_write(STDOUT,'availablelangs','install'); + //output available languages + foreach ( $langs as $language ) { + console_write(STDOUT,"\t",'',false); + console_write(STDOUT,$language,'',false); + console_write(STDOUT,"\n",'',false); + } + console_write(STDOUT,'yourchoice','install'); + $short_code_langs = get_short_codes($langs); + + $INSTALL['lang']=read_element($short_code_langs); + $SESSION->lang = $INSTALL['lang']; + } + //==============================================================================// + //Checking PHP settings + + + $silent=false; + if ($verbose == CLI_NO) { + $silent=true; + }else{ + console_write(STDOUT,'checkingphpsettings','install'); + } + /// Check that PHP is of a sufficient version + check_compatibility(inst_check_php_version(), get_string('phpversion', 'install'), get_string('phpversionerror', 'install'),false,$silent); + /// Check session auto start + check_compatibility(!ini_get_bool('session.auto_start'), get_string('sessionautostart', 'install'), get_string('sessionautostarterror', 'install'),false,$silent); + /// Check magic quotes + check_compatibility(!ini_get_bool('magic_quotes_runtime'), get_string('magicquotesruntime', 'install'), get_string('magicquotesruntimeerror', 'install'),false,$silent); + /// Check unsupported PHP configuration + check_compatibility(ini_get_bool('magic_quotes_gpc') || (!ini_get_bool('register_globals')), get_string('globalsquotes', 'install'), get_string('globalsquoteserror', 'install'),false,$silent); + /// Check safe mode + check_compatibility(!ini_get_bool('safe_mode'), get_string('safemode', 'install'), get_string('safemodeerror', 'install'), true,$silent); + /// Check file uploads + check_compatibility(ini_get_bool('file_uploads'), get_string('fileuploads', 'install'), get_string('fileuploadserror', 'install'), true,$silent); + /// Check GD version + check_compatibility(check_gd_version(), get_string('gdversion', 'install'), get_string('gdversionerror', 'install'), true,$silent); + /// Check memory limit + check_compatibility(check_memory_limit(), get_string('memorylimit', 'install'), get_string('memorylimiterror', 'install'), true,$silent); + + + + + //================================================================================// + // Moodle directories and web address + + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dirroot']) || !isset($INSTALL['wwwroot']) || !isset($INSTALL['dataroot']) ) ) ) { + console_write(STDOUT,'locationanddirectories','install'); + } + + //input the web directory + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dirroot'])) ) ) { + console_write(STDOUT,'inputwebdirectory','install'); + //if directories validation lib is found change this to read_dir() and + //edit read_dir() in lib/installlib.php to point to validation code + $INSTALL['dirroot']=read(); + } + //input the web adress + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['wwwroot'])) ) ) { + console_write(STDOUT,'inputwebadress','install'); + $INSTALL['wwwroot']=read_url(); + } + //input data directory + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dataroot'])) ) ) { + console_write(STDOUT,'inputdatadirectory','install'); + //if directories validation lib is found change this to read_dir() and + //edit read_dir() in lib/installlib.php to point to validation code + $INSTALL['dataroot']=read(); + } + + + /// check wwwroot + if (ini_get('allow_url_fopen') && false) { /// This was not reliable + if (($fh = @fopen($INSTALL['wwwroot'].'/admin/cliupgrade.php', 'r')) === false) { + console_write(STDERR,get_string('wwwrooterror'),'install',false); + } + } + if (isset($fh)) fclose($fh); + + /// check dirroot + if (($fh = @fopen($INSTALL['dirroot'].'/admin/cliupgrade.php', 'r')) === false ) { + console_write(STDERR,get_string('dirrooterror'),'install',false); + } + if (isset($fh)) fclose($fh); + + /// check dataroot + $CFG->dataroot = $INSTALL['dataroot']; + if (make_upload_directory('sessions', false) === false ) { + console_write(STDERR,get_string('datarooterror'),'install',false); + } + + //================================================================================// + // Database settings Moodle database + + + // Database section heading + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbhost']) || !isset($INSTALL['dbname']) || !isset($INSTALL['dbtype']) || !isset($INSTALL['dbuser']) || !isset($INSTALL['dbpass']) || !isset($INSTALL['prefix']) ) ) ) { + console_write(STDOUT,'databasesettingsformoodle','install'); + } + + //Input dialogs + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbhost']) ))) { + console_write(STDOUT,'databasehost','install'); + $INSTALL['dbhost']=read(); // localhost + } + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbname']) ))) { + console_write(STDOUT,'databasename','install'); + $INSTALL['dbname']=read(); //'moodletest3'; + } + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbtype']) ))) { + $dbtypes=array('mysql','oci8po','postgres7','mssql','mssql_n','odbc_mssql'); + console_write(STDOUT,'availabledbtypes','install'); + foreach ($dbtypes as $dbtype) { + console_write(STDOUT,"\t",'',false); + console_write(STDOUT,$dbtype,'install'); + console_write(STDOUT,"\n",'',false); + } + + console_write(STDOUT,'yourchoice','install'); + $INSTALL['dbtype']=read_element($dbtypes);//'mysql';// + } + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbuser']) ))) { + console_write(STDOUT,'databaseuser','install'); + $INSTALL['dbuser']=read();//'root'; + } + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbpass']) ))) { + console_write(STDOUT,'databasepass','install'); + $INSTALL['dbpass']=read();//''; + } + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['prefix']) ))) { + console_write(STDOUT,'tableprefix','install'); + $INSTALL['prefix']=read();//'mdl_';// + } + + + // Running validation tests + + /// different format for postgres7 by socket + if ($INSTALL['dbtype'] == 'postgres7' and ($INSTALL['dbhost'] == 'localhost' || $INSTALL['dbhost'] == '127.0.0.1')) { + $INSTALL['dbhost'] = "user='{$INSTALL['dbuser']}' password='{$INSTALL['dbpass']}' dbname='{$INSTALL['dbname']}'"; + $INSTALL['dbuser'] = ''; + $INSTALL['dbpass'] = ''; + $INSTALL['dbname'] = ''; + + if ($INSTALL['prefix'] == '') { /// must have a prefix + $INSTALL['prefix'] = 'mdl_'; + } + } + + if ($INSTALL['dbtype'] == 'mysql') { /// Check MySQL extension is present + if (!extension_loaded('mysql')) { + $errormsg = get_string('mysqlextensionisnotpresentinphp', 'install'); + } + } + + if ($INSTALL['dbtype'] == 'postgres7') { /// Check PostgreSQL extension is present + if (!extension_loaded('pgsql')) { + $errormsg = get_string('pgsqlextensionisnotpresentinphp', 'install'); + } + } + + if ($INSTALL['dbtype'] == 'mssql') { /// Check MSSQL extension is present + if (!function_exists('mssql_connect')) { + $errormsg = get_string('mssqlextensionisnotpresentinphp', 'install'); + } + } + + if ($INSTALL['dbtype'] == 'mssql_n') { /// Check MSSQL extension is present + if (!function_exists('mssql_connect')) { + $errormsg = get_string('mssqlextensionisnotpresentinphp', 'install'); + } + } + + if ($INSTALL['dbtype'] == 'odbc_mssql') { /// Check ODBC extension is present + if (!extension_loaded('odbc')) { + $errormsg = get_string('odbcextensionisnotpresentinphp', 'install'); + } + } + + if ($INSTALL['dbtype'] == 'oci8po') { /// Check OCI extension is present + if (!extension_loaded('oci8')) { + $errormsg = get_string('ociextensionisnotpresentinphp', 'install'); + } + } + + if (empty($INSTALL['prefix']) && $INSTALL['dbtype'] != 'mysql') { // All DBs but MySQL require prefix (reserv. words) + $errormsg = get_string('dbwrongprefix', 'install'); + } + + if ($INSTALL['dbtype'] == 'oci8po' && strlen($INSTALL['prefix']) > 2) { // Oracle max prefix = 2cc (30cc limit) + $errormsg = get_string('dbwrongprefix', 'install'); + } + + if ($INSTALL['dbtype'] == 'oci8po' && !empty($INSTALL['dbhost'])) { // Oracle host must be blank (tnsnames.ora has it) + $errormsg = get_string('dbwronghostserver', 'install'); + } + + if (empty($errormsg)) { + + /// Have the $db object ready because we are going to use it often + // fnarg + if (empty($CFG->dbtype)) { + $CFG->dbtype = $INSTALL['dbtype']; + $resetcfgdb = true; + } + preconfigure_dbconnection(); + if (!empty($resetcfgdb)) { + $CFG->dbtype = false; + } + $db = &ADONewConnection($INSTALL['dbtype']); + + $db->SetFetchMode(ADODB_FETCH_ASSOC); + + if (! $dbconnected = $db->Connect($INSTALL['dbhost'],$INSTALL['dbuser'],$INSTALL['dbpass'],$INSTALL['dbname'])) { + $errormsg= get_string('cannotconnecttodb','install'); + } else { + /// We have been able to connect properly, just test the database encoding now. + /// It must be Unicode for 1.8 installations. + $encoding = ''; + switch ($INSTALL['dbtype']) { + case 'mysql': + /// Get MySQL character_set_database value + $rs = $db->Execute("SHOW VARIABLES LIKE 'character_set_database'"); + if ($rs && $rs->RecordCount() > 0) { + $records = $rs->GetAssoc(true); + $encoding = $records['character_set_database']['Value']; + if (strtoupper($encoding) != 'UTF8') { + /// Try to set the encoding now! + if (! $db->Metatables()) { // We have no tables so go ahead + $db->Execute("ALTER DATABASE `".$INSTALL['dbname']."` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); + $rs = $db->Execute("SHOW VARIABLES LIKE 'character_set_database'"); // this works + + } + } + /// If conversion fails, skip, let environment testing do the job + } + break; + case 'postgres7': + /// Skip, let environment testing do the job + break; + case 'oci8po': + /// Skip, let environment testing do the job + break; + } + } + } + + + // check for errors in db section + if (isset($errormsg)) { + console_write(STDERR,$errormsg,'',false); + } + + + //==========================================================================// + // Check the environment + + //check connection to database + + $dbconnected = $db->Connect($INSTALL['dbhost'],$INSTALL['dbuser'],$INSTALL['dbpass'],$INSTALL['dbname']); + if ($dbconnected) { + /// Execute environment check, printing results + if (!check_moodle_environment($INSTALL['release'], $environment_results, false)) { + $errormsg = get_string('errorsinenvironment', 'install'); + } + } else { + /// We never should reach this because DB has been tested before arriving here + $errormsg = get_string('dbconnectionerror', 'install'); + } + + // check for errors in environment + if (isset($errormsg)) { + console_write(STDERR,$errormsg,'',false); + } + + // Print Environment Status + if ($verbose > CLI_NO) { + print_environment_status($environment_results); + } + + + //==============================================================================// + //download the language pack if it doesn't exist + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['downloadlangaugepack']) ))) { + $site_langs=get_list_of_languages(); + if (!key_exists($INSTALL['lang'],$site_langs)) { + console_write(STDOUT,'downloadlanguagepack','install'); + $download_lang_pack=read_yes_no(); + if($download_lang_pack == 'yes'){ + + $downloadsuccess = false; + + /// Create necessary lang dir + if (!make_upload_directory('lang', false)) { + console_write(STDERR,get_string('cannotcreatelangdir','error'),false); + } + + /// Download and install component + if (($cd = new component_installer('http://download.moodle.org', 'lang16', + $INSTALL['lang'].'.zip', 'languages.md5', 'lang')) && empty($errormsg)) { + $status = $cd->install(); //returns ERROR | UPTODATE | INSTALLED + switch ($status) { + case ERROR: + if ($cd->get_error() == 'remotedownloadnotallowed') { + $a = new stdClass(); + $a->url = 'http://download.moodle.org/lang16/'.$pack.'.zip'; + $a->dest= $CFG->dataroot.'/lang'; + console_write(STDOUT,get_string($cd->get_error(), 'error', $a),false); + } else { + $downloaderror = get_string($cd->get_error(), 'error'); + console_write(STDOUT,get_string($cd->get_error(), 'error'),false); + } + break; + case UPTODATE: + case INSTALLED: + $downloadsuccess = true; + break; + default: + //We shouldn't reach this point + } + } else { + //We shouldn't reach this point + } + + + } + } + } + + if ( $verbose > CLI_NO && $downloadsuccess) { + //print success message if language pack download is successful + console_write(STDOUT,'downloadsuccess'); + print_newline(); + } + + $CONFFILE = array(); + //==================================================================================// + //set INSTALL array values to CONFFILE array + foreach ($INSTALL as $key => $value) { + $CONFFILE[$key] = $value; + } + + //==================================================================================// + //if any value is not set, set default values + + foreach ($DEFAULT as $key => $value){ + if (!isset($INSTALL[$key])){ + $CONFFILE[$key]=$value; + } + } + + + //==================================================================================// + //create configuration file depending on the previous settings + + + if ($verbose > CLI_NO) { + console_write(STDOUT,'creatingconfigfile','install'); + } + + $str = 'dbtype = \''.$CONFFILE['dbtype']."';\r\n"; + $str .= '$CFG->dbhost = \''.addslashes($CONFFILE['dbhost'])."';\r\n"; + if (!empty($CONFFILE['dbname'])) { + $str .= '$CFG->dbname = \''.$CONFFILE['dbname']."';\r\n"; + $str .= '$CFG->dbuser = \''.$CONFFILE['dbuser']."';\r\n"; + $str .= '$CFG->dbpass = \''.$CONFFILE['dbpass']."';\r\n"; + } + $str .= '$CFG->dbpersist = false;'."\r\n"; + $str .= '$CFG->prefix = \''.$CONFFILE['prefix']."';\r\n"; + $str .= "\r\n"; + + $str .= '$CFG->wwwroot = \''.s($CONFFILE['wwwroot'],true)."';\r\n"; + $str .= '$CFG->dirroot = \''.s($CONFFILE['dirroot'],true)."';\r\n"; + $str .= '$CFG->dataroot = \''.s($CONFFILE['dataroot'],true)."';\r\n"; + $str .= '$CFG->admin = \''.s($CONFFILE['admindirname'],true)."';\r\n"; + $str .= "\r\n"; + + $str .= '$CFG->directorypermissions = 00777; // try 02777 on a server in Safe Mode'."\r\n"; + $str .= "\r\n"; + + $str .= 'require_once("$CFG->dirroot/lib/setup.php");'."\r\n"; + $str .= '// MAKE SURE WHEN YOU EDIT THIS FILE THAT THERE ARE NO SPACES, BLANK LINES,'."\r\n"; + $str .= '// RETURNS, OR ANYTHING ELSE AFTER THE TWO CHARACTERS ON THE NEXT LINE.'."\r\n"; + $str .= '?>'; + + umask(0133); + + //save the configuration file + if (( $configsuccess = ($fh = @fopen($configfile, 'w')) ) !== false) { + fwrite($fh, $str); + fclose($fh); + if ($verbose > CLI_NO) { + console_write(STDOUT,'configfilecreated','install'); + } + } else { + console_write(STDERR,'writeconfigfilefailed','install'); + } + if ( $verbose ) { + console_write(STDOUT,'installationiscomplete','install'); + } +} + + +if ( file_exists(dirname(dirname(__FILE__)) . '/config.php')) { + // This is what happens if there is no upgrade.... + //console_write(STDERR,'configurationfileexist','install'); + //die; + + + + // If the configuration file does not exists exit, this should never occur !! + if (!file_exists(dirname(dirname(__FILE__)) . '/config.php')) { + console_write(STDERR,'configfiledoesnotexist','install'); + } + + /// Check that PHP is of a sufficient version + /// Moved here because older versions do not allow while(@ob_end_clean()); + if (version_compare(phpversion(), "4.3.0") < 0) { + $phpversion = phpversion(); + console_write(STDERR,"Sorry, Moodle requires PHP 4.3.0 or later (currently using version $phpversion)",'',false); + } + /// Turn off time limits and try to flush everything all the time, sometimes upgrades can be slow. + + @set_time_limit(0); + @ob_implicit_flush(true); + //check with someone who know? that does this do? + // while(@ob_end_clean()); // ob_end_flush prevents sending of headers + + //unset(); + + + require_once(dirname(dirname(__FILE__)) . '/config.php'); + require_once($CFG->libdir.'/adminlib.php'); // Contains various admin-only functions + require_once($CFG->libdir.'/ddllib.php'); // Install/upgrade related db functions + + /** + * @todo check upgrade status, if upgrader is running already, notify user and exit. + * existing thing might work for this with some modifications + * + */ + + ///check PHP Settings + if (ini_get_bool('session.auto_start')) { + console_write(STDERR,"The PHP server variable 'session.auto_start' should be Off ",'',false); + } + + if (ini_get_bool('magic_quotes_runtime')) { + console_write(STDERR,"The PHP server variable 'magic_quotes_runtime' should be Off ",'',false); + } + + if (!ini_get_bool('file_uploads')) { + + console_write(STDERR,"The PHP server variable 'file_uploads' is not turned On" ,'',false); + } + + if (empty($CFG->prefix) && $CFG->dbfamily != 'mysql') { //Enforce prefixes for everybody but mysql + console_write(STDERR,'$CFG->prefix can\'t be empty for your target DB (' . $CFG->dbtype . ')','',false); + } + + if ($CFG->dbfamily == 'oracle' && strlen($CFG->prefix) > 2) { //Max prefix length for Oracle is 2cc + console_write(STDERR,'$CFG->prefix maximum allowed length for Oracle DBs is 2cc.','',false); + } + + /// Check that config.php has been edited + + if ($CFG->wwwroot == "http://example.com/moodle") { + console_write(STDERR,"Moodle has not been configured yet. You need to edit config.php first.",'',false); + } + + + /// Check settings in config.php + + $dirroot = dirname(realpath("../index.php")); + if (!empty($dirroot) and $dirroot != $CFG->dirroot) { + console_write(STDERR,"Please fix your settings in config.php: + \nYou have: + \n\$CFG->dirroot = \"".addslashes($CFG->dirroot)."\"; + \nbut it should be: + \n\$CFG->dirroot = \"".addslashes($dirroot)."\";",'',false); + } + + /// Set some necessary variables during set-up to avoid PHP warnings later on this page + + + if (!isset($CFG->release)) { + $CFG->release = ""; + } + if (!isset($CFG->version)) { + $CFG->version = ""; + } + + if (is_readable("$CFG->dirroot/version.php")) { + include_once("$CFG->dirroot/version.php"); # defines $version + } + + if (!$version or !$release) { + console_write(STDERR,'Main version.php was not readable or specified','',false);# without version, stop + } + + + if ( $verbose == CLI_NO ) { + $db->debug = false; + } else if ( $verbose == CLI_FULL ) { + $db->debug = true; + } + + /// Check if the main tables have been installed yet or not. + + if (! $tables = $db->Metatables() ) { // No tables yet at all. + $maintables = false; + + } else { // Check for missing main tables + $maintables = true; + $mtables = array("config", "course", "course_categories", "course_modules", + "course_sections", "log", "log_display", "modules", + "user"); + foreach ($mtables as $mtable) { + if (!in_array($CFG->prefix.$mtable, $tables)) { + $maintables = false; + break; + } + } + } + + if (! $maintables) { + /// hide errors from headers in case debug enabled in config.php + $origdebug = $CFG->debug; + $CFG->debug = DEBUG_MINIMAL; + error_reporting($CFG->debug); + + if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && (!isset($INSTALL['agreelicense']) || empty($INSTALL['agreelicense']))) ) { + //Print copyright notice and ask to continue + console_write(STDOUT,get_string('copyrightnotice'),'',false); + print_newline(); + console_write(STDOUT,get_string('gpl'),'',false); + print_newline(); + console_write(STDOUT,'doyouagree','install',true); + $agreelicense = read_boolean(); + } + + if ( !isset($agreelicense)) { + $agreelicense = $DEFAULT['agreelicense']; + } + + if (!$agreelicense) { + console_write(STDERR,'disagreelicense'); + } + + if ( $interactive == CLI_FULL || ( $interactive == CLI_SEMI && (!isset($INSTALL['confirmrelease']) || empty($INSTALL['confirmrelease'])))) { + console_write(STDOUT,get_string("currentrelease"),'',false); + print_newline(); + console_write(STDOUT,"Moodle $release",'',false); + print_newline(); + console_write(STDOUT,'askcontinue'); + $confirmrelease = read_boolean(); + } + + if (!isset($confirmrelease)) { + $confirmrelease = $DEFAULT['confirmrelease']; + } + if (!$confirmrelease) { + console_write(STDERR,'versionerror'); + } + $autopilot = 1 ; + + $strdatabasesetup = get_string("databasesetup"); + $strdatabasesuccess = get_string("databasesuccess"); + // print_header($strdatabasesetup, $strdatabasesetup, $strdatabasesetup, + // "", upgrade_get_javascript(), false, " ", " "); + /// return to original debugging level + $CFG->debug = $origdebug; + error_reporting($CFG->debug); + upgrade_log_start(); + + /// Both old .sql files and new install.xml are supported + /// But we prioritise install.xml (XMLDB) if present + + change_db_encoding(); // first try to change db encoding to utf8 + + if (!setup_is_unicodedb()) { + // If could not convert successfully, throw error, and prevent installation + console_write(STDERR,'unicoderequired', 'admin'); + } + + $status = false; + if (file_exists("$CFG->libdir/db/install.xml")) { + $status = install_from_xmldb_file("$CFG->libdir/db/install.xml"); //New method + } else if (file_exists("$CFG->libdir/db/$CFG->dbtype.sql")) { + $status = modify_database("$CFG->libdir/db/$CFG->dbtype.sql"); //Old method + } else { + console_write(STDERR,"Error: Your database ($CFG->dbtype) is not yet fully supported by Moodle or install.xml is not present. See the lib/db directory.",'',false); + } + + // all new installs are in unicode - keep for backwards compatibility and 1.8 upgrade checks + set_config('unicodedb', 1); + + /// Continue with the instalation + + if ($status) { + // Install the roles system. + moodle_install_roles(); + set_config('statsrolesupgraded',time()); + + // Write default settings unconditionally (i.e. even if a setting is already set, overwrite it) + // (this should only have any effect during initial install). + $adminroot = admin_get_root(); + $adminroot->prune('backups'); // backup settings table not created yet + admin_apply_default_settings($adminroot); + + /// This is used to handle any settings that must exist in $CFG but which do not exist in + /// admin_get_root()/$ADMIN as admin_setting objects (there are some exceptions). + apply_default_exception_settings(array('alternateloginurl' => '', + 'auth' => 'email', + 'auth_pop3mailbox' => 'INBOX', + 'changepassword' => '', + 'enrol' => 'manual', + 'enrol_plugins_enabled' => 'manual', + 'guestloginbutton' => 1, + 'registerauth' => 'email', + 'style' => 'default', + 'template' => 'default', + 'theme' => 'standardwhite', + 'filter_multilang_converted' => 1)); + + notify($strdatabasesuccess, "green"); + require_once $CFG->dirroot.'/mnet/lib.php'; + } else { + console_write(STDERR,"Error: Main databases NOT set up successfully",''); + } + + } + + + + + /// Check version of Moodle code on disk compared with database + /// and upgrade if possible. + + if (file_exists("$CFG->dirroot/lib/db/$CFG->dbtype.php")) { + include_once("$CFG->dirroot/lib/db/$CFG->dbtype.php"); # defines old upgrades + } + if (file_exists("$CFG->dirroot/lib/db/upgrade.php")) { + include_once("$CFG->dirroot/lib/db/upgrade.php"); # defines new upgrades + } + + $stradministration = get_string("administration"); + + if ($CFG->version) { + if ($version > $CFG->version) { // upgrade + + /// If the database is not already Unicode then we do not allow upgrading! + /// Instead, we print an error telling them to upgrade to 1.7 first. MDL-6857 + if (empty($CFG->unicodedb)) { + console_write(STDERR,'unicodeupgradeerror', 'error'); + } + + $a->oldversion = "$CFG->release ($CFG->version)"; + $a->newversion = "$release ($version)"; + $strdatabasechecking = get_string("databasechecking", "", $a); + + // hide errors from headers in case debug is enabled + $origdebug = $CFG->debug; + $CFG->debug = DEBUG_MINIMAL; + error_reporting($CFG->debug); + + // logout in case we are upgrading from pre 1.7 version - prevention of weird session problems + if ($CFG->version < 2006050600) { + require_logout(); + } + + if (empty($confirmupgrade)) { + + if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && !isset($INSTALL['confirmupgrade']))) { + print_newline(); + console_write(STDOUT,$strdatabasechecking,'',false); + print_newline(); + console_write(STDOUT,'askcontinue'); + $confirmupgrade = read_boolean(); + } + } + if (empty($confirmrelease)) { + + if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && !isset($INSTALL['confirmrelease']))) { + $strcurrentrelease = get_string("currentrelease"); + console_write(STDOUT,$strcurrentrelease,'',false); + print_newline(); + console_write(STDOUT,"Moodle $release",'',false); + print_newline(); + console_write(STDOUT,get_string('releasenoteslink', 'install', 'http://docs.moodle.org/en/Release_Notes'),'',false); + print_newline(); + console_write(STDOUT,'askcontinue'); + $confirmrelease = read_boolean(); + } + require_once($CFG->libdir.'/environmentlib.php'); + + console_write(STDOUT,'environment', 'admin'); + if (!check_moodle_environment($release, $environment_results, false)) { + // Print Environment Status + if ($verbose > CLI_NO) { + print_newline(); + print_environment_status_detailed($environment_results); + print_newline(); + console_write(STDOUT,'environmenterrorupgrade', 'admin'); + } + if(!read_boolean()){ + console_write(STDERR,'','',false); + } + } else { + + if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && !isset($INSTALL['autopilot']))) { + console_write(STDOUT,'environmentok', 'admin'); + console_write(STDOUT,'unattendedoperation','admin'); + $autopilot = read_boolean(); + } + } + } + + $strdatabasesuccess = get_string("databasesuccess"); + + + + /// return to original debugging level + $CFG->debug = $origdebug; + error_reporting($CFG->debug); + upgrade_log_start(); + + /// Upgrade current language pack if we can + upgrade_language_pack(); + + if ( $verbose > CLI_NO ) { + console_write(STDOUT,$strdatabasechecking,'',false); + } + + /// Launch the old main upgrade (if exists) + $status = true; + if (function_exists('main_upgrade')) { + $status = main_upgrade($CFG->version); + } + /// If succesful and exists launch the new main upgrade (XMLDB), called xmldb_main_upgrade + if ($status && function_exists('xmldb_main_upgrade')) { + $status = xmldb_main_upgrade($CFG->version); + } + + /// If successful, continue upgrading roles and setting everything properly + if ($status) { + if (empty($CFG->rolesactive)) { + // Upgrade to the roles system. + moodle_install_roles(); + set_config('rolesactive', 1); + } else if (!update_capabilities()) { + console_write(STDERR,'Had trouble upgrading the core capabilities for the Roles System','',false); + } + require_once($CFG->libdir.'/statslib.php'); + if (!stats_upgrade_for_roles_wrapper()) { + notify('Couldn\'t upgrade the stats tables to use the new roles system'); + } + if (set_config("version", $version)) { + remove_dir($CFG->dataroot . '/cache', true); // flush cache + notify($strdatabasesuccess, "green"); + /// print_continue("upgradesettings.php"); + } else { + console_write(STDERR,'Upgrade failed! (Could not update version in config table)','',false); + } + /// Main upgrade not success + } else { + console_write(STDERR,'Main Upgrade failed! See lib/db/upgrade.php','',false); + + } + upgrade_log_finish(); + + } else if ($version < $CFG->version) { + upgrade_log_start(); + notify("WARNING!!! The code you are using is OLDER than the version that made these databases!"); + upgrade_log_finish(); + } + } else { + if (!set_config("version", $version)) { + console_write(STDERR,"A problem occurred inserting current version into databases",'',false); + } + } + + + /// Find and check all main modules and load them up or upgrade them if necessary + /// first old *.php update and then the new upgrade.php script + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingactivitymodule','install'),'',1); + } + upgrade_activity_modules('');// Don't return anywhere + + /// Check all questiontype plugins and upgrade if necessary + /// first old *.php update and then the new upgrade.php script + /// It is important that this is done AFTER the quiz module has been upgraded + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingqtypeplugin','install'),'',1); + } + upgrade_plugins('qtype', 'question/type', ''); // Don't return anywhere + + /// Upgrade backup/restore system if necessary + /// first old *.php update and then the new upgrade.php script + require_once("$CFG->dirroot/backup/lib.php"); + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingbackupdb','install'),'',1); + } + upgrade_backup_db(''); // Don't return anywhere + + /// Upgrade blocks system if necessary + /// first old *.php update and then the new upgrade.php script + require_once("$CFG->dirroot/lib/blocklib.php"); + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingblocksdb','install'),'',1); + } + upgrade_blocks_db(''); // Don't return anywhere + + /// Check all blocks and load (or upgrade them if necessary) + /// first old *.php update and then the new upgrade.php script + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingblocksplugin','install'),'',1); + } + upgrade_blocks_plugins(''); // Don't return anywhere + + /// Check all enrolment plugins and upgrade if necessary + /// first old *.php update and then the new upgrade.php script + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingenrolplugin','install'),'',1); + } + upgrade_plugins('enrol', 'enrol', ''); // Don't return anywhere + + /// Check all course formats and upgrade if necessary + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingcourseformatplugin','install'),'',1); + } + upgrade_plugins('format','course/format',''); // Don't return anywhere + + /// Check for local database customisations + /// first old *.php update and then the new upgrade.php script + require_once("$CFG->dirroot/lib/locallib.php"); + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradinglocaldb','install'),'',1); + } + upgrade_local_db(''); // Don't return anywhere + + /// Check for changes to RPC functions + require_once($CFG->dirroot.'/admin/mnet/adminlib.php'); + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingrpcfunctions','install'),'',1); + } + upgrade_RPC_functions(''); // Don't return anywhere + + /// Upgrade all plugins for gradebook + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradinggradeexportplugin','install'),'',1); + } + upgrade_plugins('gradeexport', 'grade/export', ''); // Don't return anywhere + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradinggradeimportplugin','install'),'',1); + } + upgrade_plugins('gradeimport', 'grade/import', ''); // Don't return anywhere + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradinggradereportplugin','install'),'',1); + } + upgrade_plugins('gradereport', 'grade/report', ''); // Don't return anywhere + + /// Check all message output plugins and upgrade if necessary + if ( $verbose > CLI_NO ) { + print_heading(get_string('upgradingmessageoutputpluggin','install'),'',1); + } + upgrade_plugins('message','message/output',''); // Don't return anywhere + + + /// just make sure upgrade logging is properly terminated + upgrade_log_finish(); + + unset($_SESSION['installautopilot']); + + /// Set up the site + if (! $site = get_site()) { + // We are about to create the site "course" + require_once($CFG->libdir.'/blocklib.php'); + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( (!isset($INSTALL['sitefullname'])) || (!isset($INSTALL['siteshortname'])) || (!isset($INSTALL['sitesummary'])) || (!isset($INSTALL['sitenewsitems'])) )) ) { + console_write(STDOUT,'siteinfo'); + print_newline(); + } + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['sitefullname'])) ) ) { + console_write(STDOUT,'sitefullname'); + $sitefullname = read(); + } else if (isset($INSTALL['sitefullname'])) { + $sitefullname = $INSTALL['sitefullname']; + } + + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['siteshortname'])) ) ) { + console_write(STDOUT,'siteshortname'); + $siteshortname = read(); + } else if (isset($INSTALL['siteshortname'])) { + $siteshortname = $INSTALL['siteshortname']; + } + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['sitesummary'])) ) ) { + console_write(STDOUT,'sitesummary'); + $sitesummary =read(); + } else if (isset($INSTALL['sitesummary'])) { + $sitesummary = $INSTALL['sitesummary']; + } + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['sitenewsitems'])) ) ) { + console_write(STDOUT,'sitenewsitems'); + $sitenewsitems = read_int(); + } else if (isset($INSTALL['sitenewsitems'])) { + $sitenewsitems = $INSTALL['sitenewsitems']; + } + + if (!isset($sitefullname)) { + $sitefullname = $DEFAULT['sitefullname']; + } + if (!isset($siteshortname)) { + $siteshortname = $DEFAULT['siteshortname']; + } + if (!isset($sitesummary)) { + $sitesummary = $DEFAULT['sitesummary']; + } + if (!isset($sitenewsitems)) { + $sitenewsitems = $DEFAULT['sitenewsitems']; + } + + $newsite = new Object(); + $newsite->fullname = addslashes($sitefullname); + $newsite->shortname = addslashes($siteshortname); + $newsite->summary = addslashes($sitesummary); + $newsite->newsitems = $sitenewsitems; + $newsite->numsections = 0; + $newsite->category = 0; + $newsite->format = 'site'; // Only for this course + $newsite->teacher = get_string("defaultcourseteacher"); + $newsite->teachers = get_string("defaultcourseteachers"); + $newsite->student = get_string("defaultcoursestudent"); + $newsite->students = get_string("defaultcoursestudents"); + $newsite->timemodified = time(); + + if ($newid = insert_record('course', $newsite)) { + // Site created, add blocks for it + $page = page_create_object(PAGE_COURSE_VIEW, $newid); + blocks_repopulate_page($page); // Return value not checked because you can always edit later + + $cat = new Object(); + $cat->name = get_string('miscellaneous'); + if (insert_record('course_categories', $cat)) { + // do nothing + } else { + error("Serious Error! Could not set up a default course category!"); + } + } else { + error("Serious Error! Could not set up the site!"); + } + } + + /// Define the unique site ID code if it isn't already + if (empty($CFG->siteidentifier)) { // Unique site identification code + set_config('siteidentifier', random_string(32).$_SERVER['HTTP_HOST']); + } + + /// Check if the guest user exists. If not, create one. + if (! record_exists("user", "username", "guest")) { + if (! $guest = create_guest_record()) { + notify("Could not create guest user record !!!"); + } + } + + + /// Set up the admin user + if (empty($CFG->rolesactive)) { + + // If full interactive or semi interactive with at least one option is not set print the admininfo message + if ( ($interactive == CLI_FULL) || ($interactive == CLI_SEMI && (!isset($INSTALL['adminfirstname']) || !isset($INSTALL['adminlastname']) || !isset($INSTALL['adminusername']) || !isset($INSTALL['adminpassword']) || !isset($INSTALL['adminemail']) ))) { + console_write(STDOUT,'admininfo'); + print_newline(); + } + // Assign the first name + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['adminfirstname'])) ) ) { + console_write(STDOUT,'adminfirstname'); + $adminfirstname = read(); + } else if (isset($INSTALL['adminfirstname'])) { + $adminfirstname = $INSTALL['adminfirstname']; + } + + // Assign the last name + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['adminlastname'])) ) ) { + console_write(STDOUT,'adminlastname'); + $adminlastname = read(); + } else if (isset($INSTALL['adminlastname'])) { + $adminlastname = $INSTALL['adminlastname']; + } + + // Assign user name + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['adminusername'])) ) ) { + console_write(STDOUT,'adminusername'); + $adminusername = read(); + } else if (isset($INSTALL['adminusername'])) { + $adminusername = $INSTALL['adminusername']; + } + + // Assign password + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['adminpassword'])) ) ) { + console_write(STDOUT,'adminpassword'); + $adminpassword = read(); + } else if (isset($INSTALL['adminpassword'])) { + $adminpassword = $INSTALL['adminpassword']; + } + + // Assign email + if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['adminemail'])) ) ) { + console_write(STDOUT,'adminemail'); + $adminemail = read(); + } else if (isset($INSTALL['adminemail'])) { + $adminemail = $INSTALL['adminemail']; + } + + /// If values not set in above set all values to their defaults + if (!isset($adminfirstname)) { + $adminfirstname = $DEFAULT['adminfirstname']; + } + if (!isset($adminlastname)) { + $adminlastname = $DEFAULT['adminlastname']; + } + if (!isset($adminusername)) { + $adminusername = $DEFAULT['adminusername']; + } + if (!isset($adminpassword)) { + $adminpassword = $DEFAULT['adminpassword']; + } + if (!isset($adminemail)) { + $adminemail = $DEFAULT['adminemail']; + } + + $user = new object(); + $user->auth = 'manual'; + $user->firstname = $adminfirstname; //get_string('admin'); + $user->lastname = $adminlastname; //get_string('user'); + $user->username = $adminusername; //'admin'; + $user->password = hash_internal_user_password($adminpassword); // 'admin' + $user->email = $adminemail; //'root@localhost'; + $user->confirmed = 1; + $user->mnethostid = $CFG->mnet_localhost_id; + $user->lang = $CFG->lang; + $user->maildisplay = 1; + $user->timemodified = time(); + + create_admin_user($user); + } + if ( $verbose > CLI_NO ) { + print_newline(); + console_write(STDOUT,'upgradingcompleted'); + } +} + + +?> diff --git a/backup/lib.php b/backup/lib.php index 8a5bc505ad..663ee96637 100644 --- a/backup/lib.php +++ b/backup/lib.php @@ -326,7 +326,7 @@ /// This function upgrades the backup tables, if necessary /// It's called from admin/index.php, also backup.php and restore.php - global $CFG, $db; + global $CFG, $db, $interactive; require_once ("$CFG->dirroot/backup/version.php"); // Get code versions @@ -336,12 +336,16 @@ $navlinks[] = array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'); $navigation = build_navigation($navlinks); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_header($strdatabaseupgrades, $strdatabaseupgrades, $navigation, "", upgrade_get_javascript(), false, " ", " "); + } upgrade_log_start(); print_heading('backup'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=true; + } /// Both old .sql files and new install.xml are supported /// but we priorize install.xml (XMLDB) if present @@ -351,15 +355,25 @@ } else if (file_exists($CFG->dirroot . '/backup/db/' . $CFG->dbtype . '.sql')) { $status = modify_database($CFG->dirroot . '/backup/db/' . $CFG->dbtype . '.sql'); //Old method } - + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = false; + } if ($status) { if (set_config("backup_version", $backup_version) and set_config("backup_release", $backup_release)) { notify(get_string("databasesuccess"), "green"); notify(get_string("databaseupgradebackups", "", $backup_version), "green"); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_continue($continueto); print_footer('none'); exit; + } else if ( CLI_UPGRADE && ($interative > CLI_SEMI ) ) { + console_write(STDOUT,'askcontinue'); + if (read_boolean()){ + return ; + }else { + console_write(STDERR,'','',false); + } + } } else { error("Upgrade of backup system failed! (Could not update version in config table)"); } @@ -405,22 +419,34 @@ /// Then, the new function if exists and the old one was ok $newupgrade_status = true; if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE) { $db->debug = true; + } $newupgrade_status = $newupgrade_function($CFG->backup_version); } else if ($newupgrade) { notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' . '/backup/db/upgrade.php'); } - + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE) { $db->debug=false; + } /// Now analyze upgrade results if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed if (set_config("backup_version", $backup_version) and set_config("backup_release", $backup_release)) { notify(get_string("databasesuccess"), "green"); notify(get_string("databaseupgradebackups", "", $backup_version), "green"); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE) { print_continue($continueto); print_footer('none'); exit; + } else if (CLI_UPGRADE) { + console_write(STDOUT,'askcontinue'); + if (read_boolean()){ + return ; + }else { + console_write(STDERR,'','',false); + } + } } else { error("Upgrade of backup system failed! (Could not update version in config table)"); } diff --git a/install/stringnames.txt b/install/stringnames.txt index e565e5569f..766dfa00cc 100644 --- a/install/stringnames.txt +++ b/install/stringnames.txt @@ -1,8 +1,21 @@ +aborting +abortinstallation admindirerror admindirname +admindirsetting admindirsettinghead admindirsettingsub +adminemail +adminfirstname +admininfo +adminlastname +adminpassword +adminusername +askcontinue +availabledbtypes +availablelangs bypassed +cannotconnecttodb cannotcreatelangdir cannotcreatetempdir cannotdownloadcomponents @@ -13,22 +26,36 @@ cannotsavezipfile cannotunzipfile caution check +checkingphpsettings +chooselanguage chooselanguagehead chooselanguagesub closewindow +compatibilitysettings compatibilitysettingshead compatibilitysettingssub componentisuptodate +configfilecreated +configfiledoesnotexist configfilenotwritten configfilewritten +configurationcomplete configurationcompletehead configurationcompletesub +configurationfileexist continue +creatingconfigfile curlrecommended customcheck database +databasecreationsettings databasecreationsettingshead databasecreationsettingssub +databasehost +databasename +databasepass +databasesettings +databasesettingsformoodle databasesettingshead databasesettingssub databasesettingssub_mssql @@ -39,27 +66,35 @@ databasesettingssub_oci8po databasesettingssub_odbc_mssql databasesettingssub_postgres7 databasesettingswillbecreated +databasetype +databaseuser dataroot datarooterror dbconnectionerror dbcreationerror dbhost +dbpass dbprefix dbtype dbwrongencoding dbwronghostserver dbwrongnlslang dbwrongprefix +directorysettings directorysettingshead directorysettingssub dirroot dirrooterror +disagreelicense download downloadedfilecheckfailed downloadlanguagebutton downloadlanguagehead downloadlanguagenotneeded +downloadlanguagepack downloadlanguagesub +downloadsuccess +doyouagree environmenterrortodo environmenthead environmentrecommendcustomcheck @@ -71,24 +106,44 @@ environmentrequireversion environmentsub environmentxmlerror error +errorsinenvironment fail fileuploads fileuploadserror +fileuploadshelp gdversion gdversionerror gdversionhelp globalsquotes globalsquoteserror +globalsquoteshelp help iconvrecommended info +inputdatadirectory +inputwebadress +inputwebdirectory installation +installationiscomplete +invalidargumenthelp +invalidemail +invalidhost +invalidint +invalidintrange invalidmd5 +invalidpath +invalidsetelement +invalidtextvalue +invalidurl +invalidvalueforlanguage +invalidyesno langdownloaderror langdownloadok language +locationanddirectories magicquotesruntime magicquotesruntimeerror +magicquotesruntimehelp mbstringrecommended memorylimit memorylimiterror @@ -105,6 +160,7 @@ mysql416required mysqlextensionisnotpresentinphp mysqliextensionisnotpresentinphp name +newline next oci8po ociextensionisnotpresentinphp @@ -115,6 +171,7 @@ opensslrecommended parentlanguage pass password +pearargerror pgsqlextensionisnotpresentinphp php50restricted phpversion @@ -124,24 +181,51 @@ postgres7 previous qtyperqpwillberemoved qtyperqpwillberemovedanyway +releasenoteslink remotedownloaderror remotedownloadnotallowed report restricted safemode safemodeerror +safemodehelp +selectlanguage serverchecks sessionautostart sessionautostarterror +sessionautostarthelp +sitefullname +siteinfo +sitenewsitems +siteshortname +sitesummary skipdbencodingtest status this_direction +tableprefix thischarset thisdirection thislanguage unicoderecommended unicoderequired +unsafedirname +upgradingactivitymodule +upgradingbackupdb +upgradingblocksdb +upgradingblocksplugin +upgradingcompleted +upgradingcourseformatplugin +upgradingenrolplugin +upgradinggradeexportplugin +upgradinggradeimportplugin +upgradinggradereportplugin +upgradinglocaldb +upgradingmessageoutputpluggin +upgradingqtypeplugin +upgradingrpcfunctions +usagehelp user +versionerror welcomep10 welcomep20 welcomep30 @@ -149,8 +233,11 @@ welcomep40 welcomep50 welcomep60 welcomep70 +welcometext +writetoconfigfilefaild wrongdestpath wrongsourcebase wrongzipfilename wwwroot wwwrooterror +yourchoice diff --git a/lang/en_utf8/install.php b/lang/en_utf8/install.php index 5defe78d60..020355d5c9 100644 --- a/lang/en_utf8/install.php +++ b/lang/en_utf8/install.php @@ -17,18 +17,33 @@ $string['admindirsettingsub'] = 'A very few webhosts use /admin as a special URL renaming the admin directory in your installation, and putting that new name here. For example:

moodleadmin

This will fix admin links in Moodle.'; +$string['adminemail'] = 'Email :'; +$string['adminfirstname'] = 'First Name :'; +$string['admininfo'] = 'Administrator Details'; +$string['adminlastname'] = 'Last Name :'; +$string['adminpassword'] = 'Password :'; +$string['adminusername'] = 'Username :'; +$string['askcontinue'] = 'Continue (yes/no) :'; +$string['availabledbtypes']='\nAvailable db types \n'; +$string['availablelangs']='List of available languages \n'; +$string['cannotconnecttodb'] = 'Cannot connect to db \n'; $string['caution'] = 'Caution'; +$string['checkingphpsettings']='\n\nChecking PHP Settings\n\n'; $string['chooselanguage'] = 'Choose a language'; $string['chooselanguagehead'] = 'Choose a language'; $string['chooselanguagesub'] = 'Please choose a language for the installation ONLY. You will be able to choose site and user languages on a later screen.'; $string['compatibilitysettings'] = 'Checking your PHP settings ...'; $string['compatibilitysettingshead'] = 'Checking your PHP settings ...'; $string['compatibilitysettingssub'] = 'Your server should pass all these tests to make Moodle run properly'; +$string['configfilecreated'] = 'Configuration file successfully created\n '; +$string['configfiledoesnotexist'] = 'Configuration file does not exist !!!'; $string['configfilenotwritten'] = 'The installer script was not able to automatically create a config.php file containing your chosen settings, probably because the Moodle directory is not writeable. You can manually copy the following code into a file named config.php within the root directory of Moodle.'; $string['configfilewritten'] = 'config.php has been successfully created'; $string['configurationcomplete'] = 'Configuration completed'; $string['configurationcompletehead'] = 'Configuration completed'; $string['configurationcompletesub'] = 'Moodle made an attempt to save your configuration in a file in the root of your Moodle installation.'; +$string['configurationfileexist']='Configuration file already exist!\n'; +$string['creatingconfigfile'] =' Creating configuration file ...\n'; $string['database'] = 'Database'; $string['databasecreationsettings'] = 'Now you need to configure the database settings where most Moodle data will be stored. This database will be created automatically by the installer @@ -49,6 +64,9 @@ $string['databasecreationsettingssub'] = 'Type: fixed to \"mysql\" by the User: fixed to \"root\" by the installer
Password: your database password
Tables Prefix: optional prefix to use for all table names'; +$string['databasehost']='Database host :'; +$string['databasename']='Database name : '; +$string['databasepass']='Database password :'; $string['databasesettings'] = 'Now you need to configure the database where most Moodle data will be stored. This database must already have been created and a username and password created to access it.
@@ -59,6 +77,7 @@ $string['databasesettings'] = 'Now you need to configure the database where most User: your database username
Password: your database password
Tables Prefix: optional prefix to use for all table names'; +$string['databasesettingsformoodle']='\n\nDatabase settings for Moodle\n\n'; $string['databasesettingshead'] = 'Now you need to configure the database where most Moodle data will be stored. This database must already have been created and a username and password created to access it.'; @@ -111,6 +130,8 @@ $string['databasesettingssub_postgres7'] = 'Type: PostgreSQL
Password: your database password
Tables Prefix: prefix to use for all table names (mandatory)'; $string['databasesettingswillbecreated'] = 'Note: The installer will try to create the database automatically if not exists.'; +$string['databasetype']='Database type :'; +$string['databaseuser']='Database user :'; $string['dataroot'] = 'Data Directory'; $string['datarooterror'] = 'The \'Data Directory\' you specified could not be found or created. Either correct the path or create that directory manually.'; $string['dbconnectionerror'] = 'We could not connect to the database you specified. Please check your database settings.'; @@ -123,6 +144,7 @@ $string['dbwrongencoding'] = 'The selected database is running under one non-rec $string['dbwronghostserver'] = 'You must follow \"Host\" rules as explained above.'; $string['dbwrongnlslang'] = 'The NLS_LANG environment variable in your web server must use the AL32UTF8 charset. See PHP documentation about how to configure OCI8 properly.'; $string['dbwrongprefix'] = 'You must follow \"Tables Prefix\" rules as explained above.'; +$string['disagreelicense'] = 'Upgrade cannot proceed due to disagreement to GPL!'; $string['directorysettings'] = '

Please confirm the locations of this Moodle installation.

Web Address: @@ -164,9 +186,13 @@ $string['download'] = 'Download'; $string['downloadlanguagebutton'] = 'Download the "$a" language pack'; $string['downloadlanguagehead'] = 'Download language pack'; $string['downloadlanguagenotneeded'] = 'You may continue the installation process using the default language pack, \"$a\".'; +$string['downloadlanguagepack']='\n\nDo you want to download language pack now(yes/no) :'; $string['downloadlanguagesub'] = 'You now have the option of downloading a language pack and continuing the installation process in this language.

If you are unable to download the language pack, the installation process will continue in English. (Once the installation process is complete, you will have the opportunity to download and install additional language packs.)'; +$string['downloadsuccess'] = 'Language Pack Downloaded Successfuly'; +$string['doyouagree'] = 'Do you agree ? (yes/no):'; $string['environmenthead'] = 'Checking your environment ...'; $string['environmentsub'] = 'We are checking if the various components of your system meet the system requirements'; +$string['errorsinenvironment'] ='Errors in the environment !\n'; $string['fail'] = 'Fail'; $string['fileuploads'] = 'File Uploads'; $string['fileuploadserror'] = 'This should be on'; @@ -201,9 +227,28 @@ $string['globalsquoteshelp'] = '

Combination of disabled Magic Quotes GPC and

php_value magic_quotes_gpc On
php_value register_globals Off

'; +$string['inputdatadirectory']='Data Directory :'; +$string['inputwebadress']='Web address :'; +$string['inputwebdirectory']='Moodle Directory :'; $string['installation'] = 'Installation'; +$string['installationiscomplete'] = 'Installtion is completed !\n'; +$string['invalidargumenthelp']=' + Error: Invalid argument(s) + Usage: \$php cliupgrade.php OPTIONS + Use --help option to get more help\n'; +$string['invalidemail'] = 'Invalid Email'; +$string['invalidhost'] = 'Invalid Host '; +$string['invalidint']='Error: value is not an integer \n'; +$string['invalidintrange'] = 'Error: Value is outside valid range\n'; +$string['invalidpath'] = 'Invalid Path '; +$string['invalidsetelement']= 'Error: Value given is not in the given options \n'; +$string['invalidtextvalue'] = 'Invalid Text Value'; +$string['invalidurl'] = 'Invalid URL '; +$string['invalidvalueforlanguage']='Invalid value for --lang option. Type --help for more help\n'; +$string['invalidyesno'] = 'Error: value is not a valid yes/no argument \n'; $string['langdownloaderror'] = 'Unfortunately the language \"$a\" was not installed. The installation process will continue in English.'; $string['langdownloadok'] = 'The language \"$a\" was installed successfully. The installation process will continue in this language.'; +$string['locationanddirectories']= '\n\nLocation and directories \n\n'; $string['magicquotesruntime'] = 'Magic Quotes Run Time'; $string['magicquotesruntimeerror'] = 'This should be off'; $string['magicquotesruntimehelp'] = '

Magic quotes runtime should be turned off for Moodle to function properly.

@@ -255,6 +300,7 @@ $string['phpversionhelp'] = '

Moodle requires a PHP version of at least 4.3.0

You must upgrade PHP or move to a host with a newer version of PHP!
(In case of 5.0.x you could also downgrade to 4.4.x version)

'; $string['postgres7'] = 'PostgreSQL (postgres7)'; +$string['releasenoteslink'] = 'For information about this version of Moodle, please see Release Notes at $a'; $string['safemode'] = 'Safe Mode'; $string['safemodeerror'] = 'Moodle may have trouble with safe mode on'; $string['safemodehelp'] = '

Moodle may have a variety of problems with safe mode on, not least is that @@ -264,12 +310,64 @@ $string['safemodehelp'] = '

Moodle may have a variety of problems with safe mo to just find a new web hosting company for your Moodle site.

You can try continuing the install if you like, but expect a few problems later on.

'; +$string['selectlanguage']='\n\nSelecting a language for installation\n'; $string['sessionautostart'] = 'Session Auto Start'; $string['sessionautostarterror'] = 'This should be off'; $string['sessionautostarthelp'] = '

Moodle requires session support and will not function without it.

Sessions can be enabled in the php.ini file ... look for the session.auto_start parameter.

'; +$string['sitefullname'] = 'Site full name :'; +$string['siteinfo'] = 'Site Details'; +$string['sitenewsitems'] = 'News Items :'; +$string['siteshortname'] = 'Site short name :'; +$string['sitesummary'] ='Site summary :'; $string['skipdbencodingtest'] = 'Skip DB Encoding Test'; +$string['tableprefix']='Table prefix :'; +$string['unsafedirname'] = 'Error: Unsafe characters in directory name. valid characters are a-zA-Z0-9_-\n'; +$string['upgradingactivitymodule']= 'Upgrading Activity Module'; +$string['upgradingbackupdb'] = 'Upgrading Backup Database'; +$string['upgradingblocksdb'] = 'Upgrading Blocks Database'; +$string['upgradingblocksplugin'] = 'Upgrading Blocks Plugin'; +$string['upgradingcompleted'] = 'Upgrading completed...\n'; +$string['upgradingcourseformatplugin'] = 'Upgrading Course Format Pluggin'; +$string['upgradingenrolplugin'] = 'Upgrading Enrol Plugin'; +$string['upgradinggradeexportplugin'] = 'Upgrading Grade Export Plugin'; +$string['upgradinggradeimportplugin'] = 'Upgrading Grame Import Plugin'; +$string['upgradinggradereportplugin'] = 'Upgrading Grade Report Plugin'; +$string['upgradinglocaldb'] = 'Upgrading Local Database'; +$string['upgradingmessageoutputpluggin'] = 'Upgrading Message Output Plugin'; +$string['upgradingqtypeplugin'] = 'Upgrading Question/type Plugin'; +$string['upgradingrpcfunctions'] = 'Upgrading RPC Functions'; +$string['usagehelp']=' +Synopsis: +\$php cliupgrade.php OPTIONS\n +OPTIONS +--lang Valid installed language for installation. Default is English(en) +--webaddr Web address for the Moodle site +--moodledir Location of the moodle web folder +--datadir Location of the moodle data folder (should not be web visible) +--dbtype Database type. Default it mysql +--dbhost Database host. Default localhost +--dbname Database name. Default is moodle +--dbuser Database user. Default is blank +--dbpass Database password. Default is blank +--prefix Table prefix for above database tables. Default is mdl +--verbose 0 No output, 1 Summarized output(Default), 2 Detailed output +--interactivelevel 0 Non interactive, 1 semi interactive(Default), 2 interactive +--agreelicense Yes(Default) or No +--confirmrelease Yes(Default) or No +--sitefullname Full name for the site. Default is : Moodle Site (Please Change Site Name!!) +--siteshortname Short name for the site. Default is moodle +--sitesummary Summary of the site. Default is blank +--adminfirstname First name of the admin. Default is Admin +--adminlastname Last name of the admin. Default is User +--adminusername Username for the admin. Default is admin +--adminpassword Password for the admin. Default is admin +--adminemail Email address of admin. Default is root@localhost +--help print out this help\n +Usage: +\$php cliupgrade.php --lang=en --webaddr=http://www.example.com --moodledir=/var/www/html/moodle --datadir=/var/moodledata --dbtype=mysql --dbhost=localhost --dbname=moodle --dbuser=root --prefix=mdl --agreelicense=yes --confirmrelease=yes --sitefullname=\"Example Moodle Site\" --siteshortname=moodle --sitesummary=siteforme --adminfirstname=Admin --adminlastname=User --adminusername=admin --adminpassword=admin --adminemail=admin@example.com --verbose=1 --interactivelevel=2 \n'; +$string['versionerror'] = 'User aborted due to version Error '; $string['welcomep10'] = '$a->installername ($a->installerversion)'; $string['welcomep20'] = 'You are seeing this page because you have successfully installed and launched the $a->packname $a->packversion package in your computer. Congratulations!'; @@ -284,7 +382,10 @@ $string['welcomep60'] = 'The following pages will lead you through some easy to configure and set up Moodle on your computer. You may accept the default settings or, optionally, amend them to suit your own needs.'; $string['welcomep70'] = 'Click the \"Next\" button below to continue with the set up of Moodle.'; +$string['welcometext']='\n\n---Welcome to moodle commandline installer---\n\n'; +$string['writetoconfigfilefaild'] = 'Error: Write to config file failed '; $string['wwwroot'] = 'Web address'; $string['wwwrooterror'] = 'The \'Web Address\' does not appear to be valid - this Moodle installation doesn\'t appear to be there. The value below has been reset.'; +$string['yourchoice']='\nYour choice :'; ?> diff --git a/lib/adminlib.php b/lib/adminlib.php index 0db89340d4..3a5130a882 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -49,7 +49,7 @@ function upgrade_blocks_savepoint($result, $version, $type) { * @param string $return The url to prompt the user to continue to */ function upgrade_plugins($type, $dir, $return) { - global $CFG, $db; + global $CFG, $db, $interactive; /// Let's know if the header has been printed, so the funcion is being called embedded in an outer page $embedded = defined('HEADER_PRINTED'); @@ -123,7 +123,9 @@ function upgrade_plugins($type, $dir, $return) { $updated_plugins = true; upgrade_log_start(); print_heading($dir.'/'. $plugin->name .' plugin needs upgrading'); - $db->debug = true; + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { + $db->debug = true; + } @set_time_limit(0); // To allow slow databases to complete the long SQL if ($CFG->$pluginversion == 0) { // It's a new install of this plugin @@ -137,8 +139,9 @@ function upgrade_plugins($type, $dir, $return) { } else { $status = true; } - - $db->debug = false; + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { + $db->debug = false; + } /// Continue with the instalation, roles and other stuff if ($status) { /// OK so far, now update the plugins record @@ -174,7 +177,9 @@ function upgrade_plugins($type, $dir, $return) { /// First, the old function if exists $oldupgrade_status = true; if ($oldupgrade && function_exists($oldupgrade_function)) { - $db->debug = true; + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { + $db->debug = true; + } $oldupgrade_status = $oldupgrade_function($CFG->$pluginversion); } else if ($oldupgrade) { notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' . @@ -184,14 +189,17 @@ function upgrade_plugins($type, $dir, $return) { /// Then, the new function if exists and the old one was ok $newupgrade_status = true; if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) { - $db->debug = true; + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { + $db->debug = true; + } $newupgrade_status = $newupgrade_function($CFG->$pluginversion); } else if ($newupgrade) { notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' . $fullplug . '/db/upgrade.php'); } - - $db->debug=false; + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { + $db->debug=false; + } /// Now analyze upgrade results if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed // OK so far, now update the plugins record @@ -205,7 +213,9 @@ function upgrade_plugins($type, $dir, $return) { notify('Upgrading '. $plugin->name .' from '. $CFG->$pluginversion .' to '. $plugin->version .' FAILED!'); } } - echo '
'; + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { + echo '
'; + } } else { upgrade_log_start(); error('Version mismatch: '. $plugin->name .' can\'t downgrade '. $CFG->$pluginversion .' -> '. $plugin->version .' !'); @@ -215,9 +225,18 @@ function upgrade_plugins($type, $dir, $return) { upgrade_log_finish(); if ($updated_plugins && !$embedded) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_continue($return); print_footer('none'); die; + } else if (CLI_UPGRADE && ($interactive > CLI_SEMI )) { + console_write(STDOUT,'askcontinue'); + if (read_boolean()){ + return ; + }else { + console_write(STDERR,'','',false); + } + } } } @@ -231,7 +250,7 @@ function upgrade_plugins($type, $dir, $return) { */ function upgrade_activity_modules($return) { - global $CFG, $db; + global $CFG, $db, $interactive; if (!$mods = get_list_of_plugins('mod') ) { error('No modules installed!'); @@ -311,6 +330,7 @@ function upgrade_activity_modules($return) { upgrade_get_javascript(), false, ' ', ' '); } upgrade_log_start(); + print_heading($module->name .' module needs upgrading'); /// Run de old and new upgrade functions for the module @@ -320,7 +340,9 @@ function upgrade_activity_modules($return) { /// First, the old function if exists $oldupgrade_status = true; if ($oldupgrade && function_exists($oldupgrade_function)) { + if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE) { $db->debug = true; + } $oldupgrade_status = $oldupgrade_function($currmodule->version, $module); if (!$oldupgrade_status) { notify ('Upgrade function ' . $oldupgrade_function . @@ -334,14 +356,17 @@ function upgrade_activity_modules($return) { /// Then, the new function if exists and the old one was ok $newupgrade_status = true; if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = true; + } $newupgrade_status = $newupgrade_function($currmodule->version, $module); } else if ($newupgrade && $oldupgrade_status) { notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' . $mod . ': ' . $fullmod . '/db/upgrade.php'); } - + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=false; + } /// Now analyze upgrade results if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed // OK so far, now update the modules record @@ -351,7 +376,9 @@ function upgrade_activity_modules($return) { } remove_dir($CFG->dataroot . '/cache', true); // flush cache notify(get_string('modulesuccess', '', $module->name), 'notifysuccess'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE) { echo '
'; + } } else { notify('Upgrading '. $module->name .' from '. $currmodule->version .' to '. $module->version .' FAILED!'); } @@ -371,14 +398,19 @@ function upgrade_activity_modules($return) { } else { // module not installed yet, so install it if (!$updated_modules) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_header($strmodulesetup, $strmodulesetup, build_navigation(array(array('name' => $strmodulesetup, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); } + } upgrade_log_start(); print_heading($module->name); $updated_modules = true; + // To avoid unnecessary output from the SQL queries in the CLI version + if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE ) { $db->debug = true; + } @set_time_limit(0); // To allow slow databases to complete the long SQL /// Both old .sql files and new install.xml are supported @@ -389,7 +421,9 @@ function upgrade_activity_modules($return) { $status = modify_database($fullmod .'/db/'. $CFG->dbtype .'.sql'); //Old method } + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = false; + } /// Continue with the installation, roles and other stuff if ($status) { @@ -412,7 +446,9 @@ function upgrade_activity_modules($return) { } notify(get_string('modulesuccess', '', $module->name), 'notifysuccess'); + if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE ) { echo '
'; + } } else { error($module->name .' module could not be added to the module list!'); } @@ -428,7 +464,6 @@ function upgrade_activity_modules($return) { $submoduleupgrade(); } - /// Run any defaults or final code that is necessary for this module if ( is_readable($fullmod .'/defaults.php')) { @@ -448,9 +483,18 @@ function upgrade_activity_modules($return) { upgrade_log_finish(); // finish logging if started if ($updated_modules) { + if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE ) { print_continue($return); print_footer('none'); die; + } else if ( CLI_UPGRADE && ($interactive > CLI_SEMI) ) { + console_write(STDOUT,'askcontinue'); + if (read_boolean()){ + return ; + }else { + console_write(STDERR,'','',false); + } + } } } @@ -554,7 +598,7 @@ function upgrade_get_javascript() { return $linktoscrolltoerrors; } -function create_admin_user() { +function create_admin_user($user_input=NULL) { global $CFG, $USER; if (empty($CFG->rolesactive)) { // No admin user yet. @@ -572,6 +616,9 @@ function create_admin_user() { $user->maildisplay = 1; $user->timemodified = time(); + if ($user_input) { + $user = $user_input; + } if (!$user->id = insert_record('user', $user)) { error('SERIOUS ERROR: Could not create admin user record !!!'); } @@ -596,7 +643,9 @@ function create_admin_user() { $USER->newadminuser = 1; load_all_capabilities(); + if (!defined('CLI_UPGRADE')||!CLI_UPGRADE) { redirect("$CFG->wwwroot/user/editadvanced.php?id=$user->id"); // Edit thyself + } } else { error('Can not create admin!'); } diff --git a/lib/blocklib.php b/lib/blocklib.php index be131b7942..5a2d9c9dca 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -1036,20 +1036,22 @@ function upgrade_blocks_db($continueto) { /// This function upgrades the blocks tables, if necessary /// It's called from admin/index.php - global $CFG, $db; + global $CFG, $db, $interactive; require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions if (empty($CFG->blocks_version)) { // Blocks have never been installed. $strdatabaseupgrades = get_string('databaseupgrades'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_header($strdatabaseupgrades, $strdatabaseupgrades, build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); - + } upgrade_log_start(); print_heading('blocks'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=true; - + } /// Both old .sql files and new install.xml are supported /// but we priorize install.xml (XMLDB) if present $status = false; @@ -1058,15 +1060,25 @@ function upgrade_blocks_db($continueto) { } else if (file_exists($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql')) { $status = modify_database($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql'); //Old method } - + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = false; + } if ($status) { if (set_config('blocks_version', $blocks_version)) { notify(get_string('databasesuccess'), 'notifysuccess'); notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_continue($continueto); print_footer('none'); exit; + } else if (CLI_UPGRADE && ($interactive > CLI_SEMI) ) { + console_write(STDOUT,'askcontinue'); + if (read_boolean()){ + return ; + }else { + console_write(STDERR,'','',false); + } + } } else { error('Upgrade of blocks system failed! (Could not update version in config table)'); } @@ -1089,10 +1101,12 @@ function upgrade_blocks_db($continueto) { if ($blocks_version > $CFG->blocks_version) { // Upgrade tables $strdatabaseupgrades = get_string('databaseupgrades'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_header($strdatabaseupgrades, $strdatabaseupgrades, build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript()); - + } upgrade_log_start(); + print_heading('blocks'); /// Run de old and new upgrade functions for the module @@ -1102,7 +1116,9 @@ function upgrade_blocks_db($continueto) { /// First, the old function if exists $oldupgrade_status = true; if ($oldupgrade && function_exists($oldupgrade_function)) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = true; + } $oldupgrade_status = $oldupgrade_function($CFG->blocks_version); } else if ($oldupgrade) { notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' . @@ -1112,22 +1128,27 @@ function upgrade_blocks_db($continueto) { /// Then, the new function if exists and the old one was ok $newupgrade_status = true; if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = true; + } $newupgrade_status = $newupgrade_function($CFG->blocks_version); } else if ($newupgrade) { notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' . '/blocks/db/upgrade.php'); } - + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=false; + } /// Now analyze upgrade results if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed if (set_config('blocks_version', $blocks_version)) { notify(get_string('databasesuccess'), 'notifysuccess'); notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_continue($continueto); print_footer('none'); exit; + } } else { error('Upgrade of blocks system failed! (Could not update version in config table)'); } @@ -1146,7 +1167,7 @@ function upgrade_blocks_db($continueto) { //into blocks table or do all the upgrade process if newer function upgrade_blocks_plugins($continueto) { - global $CFG, $db; + global $CFG, $db, $interactive; $blocktitles = array(); $invalidblocks = array(); @@ -1255,12 +1276,15 @@ function upgrade_blocks_plugins($continueto) { } else if ($currblock->version < $block->version) { if (empty($updated_blocks)) { $strblocksetup = get_string('blocksetup'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_header($strblocksetup, $strblocksetup, build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); + } } $updated_blocks = true; upgrade_log_start(); + print_heading('New version of '.$blocktitle.' ('.$block->name.') exists'); @set_time_limit(0); // To allow slow databases to complete the long SQL @@ -1271,7 +1295,9 @@ function upgrade_blocks_plugins($continueto) { /// First, the old function if exists $oldupgrade_status = true; if ($oldupgrade && function_exists($oldupgrade_function)) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = true; + } $oldupgrade_status = $oldupgrade_function($currblock->version, $block); } else if ($oldupgrade) { notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' . @@ -1281,14 +1307,17 @@ function upgrade_blocks_plugins($continueto) { /// Then, the new function if exists and the old one was ok $newupgrade_status = true; if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = true; + } $newupgrade_status = $newupgrade_function($currblock->version, $block); } else if ($newupgrade) { notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' . $fullblock . '/db/upgrade.php'); } - + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=false; + } /// Now analyze upgrade results if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed @@ -1310,7 +1339,9 @@ function upgrade_blocks_plugins($continueto) { } else { notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!'); } + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { echo '
'; + } } else { upgrade_log_start(); error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!'); @@ -1332,18 +1363,26 @@ function upgrade_blocks_plugins($continueto) { if($conflictblock !== false && $conflictblock !== NULL) { // Duplicate block titles are not allowed, they confuse people // AND PHP's associative arrays ;) + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { error('Naming conflict: block '.$block->name.' has the same title with an existing block, '.$conflictblock.'!'); + } else if (CLI_UPGRADE) { + error('Naming conflict: block "'.$block->name.'" has the same title with an existing block, "'.$conflictblock.'"!'); + } } if (empty($updated_blocks)) { $strblocksetup = get_string('blocksetup'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE) { print_header($strblocksetup, $strblocksetup, build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); } + } $updated_blocks = true; upgrade_log_start(); print_heading($block->name); + if (!defined('CLI_UPGRADE')||!CLI_UPGRADE) { $db->debug = true; + } @set_time_limit(0); // To allow slow databases to complete the long SQL /// Both old .sql files and new install.xml are supported @@ -1356,8 +1395,9 @@ function upgrade_blocks_plugins($continueto) { } else { $status = true; } - + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = false; + } if ($status) { if ($block->id = insert_record('block', $block)) { $blockobj->after_install(); @@ -1368,7 +1408,9 @@ function upgrade_blocks_plugins($continueto) { events_update_definition($component); notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess'); + if (!defined('CLI_UPGRADE')|| !CLI_UPGRADE) { echo '
'; + } } else { error($block->name .' block could not be added to the block list!'); } @@ -1410,9 +1452,18 @@ function upgrade_blocks_plugins($continueto) { upgrade_log_finish(); if (!empty($updated_blocks)) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE) { print_continue($continueto); print_footer('none'); die; + } else if ( CLI_UPGRADE && ($interactive > CLI_SEMI) ) { + console_write(STDOUT,'askcontinue'); + if (read_boolean()){ + return ; + }else { + console_write(STDERR,'','',false); + } + } } } diff --git a/lib/dmllib.php b/lib/dmllib.php index 47a5043032..0597c8acbb 100644 --- a/lib/dmllib.php +++ b/lib/dmllib.php @@ -65,8 +65,10 @@ function execute_sql($command, $feedback=true) { $olddebug = $db->debug; if (!$feedback) { + if ( !defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug = false; } + } if ($CFG->version >= 2006101007) { //Look for trailing ; from Moodle 1.7.0 $command = trim($command); @@ -97,7 +99,11 @@ function execute_sql($command, $feedback=true) { return true; } else { if ($feedback) { + if ( defined('CLI_UPGRADE') && CLI_UPGRADE ) { + notify (get_string('error')); + } else { notify('' . get_string('error') . ''); + } } // these two may go to difference places debugging($db->ErrorMsg() .'

'. s($command)); diff --git a/lib/installlib.php b/lib/installlib.php new file mode 100644 index 0000000000..d14cf1138c --- /dev/null +++ b/lib/installlib.php @@ -0,0 +1,632 @@ +read())) { + if ($file[0] != '.' ) { + $validllangs[$i++]=$file; + } + } + if (in_array($lang,$validllangs)) { + return true; + } else { + return false; + } +} +//========================================================================================// +/** + * Read from array of language strings and return a array of string elements in which + * both values and keys are set to input array's key + * + * @param array $lang string elements + * @return array of string element + */ +function get_short_codes ($lang = array()) { + $short_codes = array(); + + foreach ($lang as $key => $value) { + $short_codes[$key] = $key; + } + return $short_codes; +} +//========================================================================================// +/** + * Check value for valid yes/no argument + * Return true or false + * + * @param string $value + * @return true/false + */ +function valid_yes_no($value){ + $valid=array('yes','y','n','no'); + $value=strtolower($value); + + if (in_array($value,$valid)) { + if ($value[0]=='y') { + return true; + } else if ($value[0]=='n') { + return true; + } + } else { + return false; + } +} +//========================================================================================// +/** + * Can value have a valid integer in the given range + * Return true or false + * @link valid_param() + * + * + * @param mixedtype $value + * @param int $start + * @param int $end + * @return true/false + */ +function valid_int_range($value,$start,$end) { + if (valid_param($value,PARAM_INT)) { + if ($value < $end && $value > $start) { + return true; + } else { + return false; + } + } +} + +/** + * Take a value and and check it with the given set of values + * If value if found in the set return true. False otherwise + * + * @param mixed type $value + * @param array $set of valid elements + * @return boolean + */ + +function valid_element($value,$set) { + if(!empty($set)) { + //convert all the elements from set to lower case + foreach ($set as $key=>$opt) { + $set[$key]=strtolower($opt); + } + $value=strtolower($value); + if (in_array($value,$set)) { + return true; + } else { + return false; + } + } +} + +/** + * Take a value and Type of the value + * If value match the type return true, false otherwise + * uses {@link clean_param()} in moodlelib.php + * @param mixedtype $value + * @param int $type + * @return boolean + */ +function valid_param($value,$type){ + $clean_val = clean_param($value,$type); + if ($clean_val == $value) { + return true; + }else { + return false; + } +} +//========================================================================================// +/** + * Creat long arument list for PEAR method invocation using LONGOPTOIN array + * + * @param long option array $long_opt + * @return PEAR method compatible long option array + */ +function create_long_options($long_opt) { + $opt=array(); + $i=0; + if (is_array($long_opt)) { + foreach ($long_opt as $key=>$value) { + if ($value == CLI_VAL_REQ) { + $opt[$i++]=$key.'='; + } else if ($value == CLI_VAL_OPT) { + $opt[$i++]=$key.'=='; + } + + } + } + return $opt; +} +//========================================================================================// +/** + * This funtion return an array of options with option as key containing the value of + * respective option + * + * @param array of option arguments as defined by PEAR GetOpt calss $opt + * @return return a options arguments with options as keys and values as respective value for key + */ +function get_options($opt=array()) { + + global $LONG_OPTIONS; + $ret_arr=array(); + + //get the options from the defined list of arguments + if (!empty($opt[0]) && is_array($opt[0])) { + + foreach ($opt[0] as $key=>$value) { + + if (substr($value[0],0,2)=='--') { //if the argument is a long option + $input_option=substr($value[0],2); + } else if (substr($value[0],0,1)=='-'){ //if the argument is a short option + $input_option=substr($value[0],1); + } + + //check with valid set of options + if (in_array($input_option,$LONG_OPTIONS)) { + $ret_arr[$input_option]=$value[1]; + } + } + + } + //return array + return $ret_arr; + +} + +//========================================================================================// + +/** + * This function returns a list of languages and their full names. + * The list of available languages is fetched from install/lang/xx/installer.php + * and it's used exclusively by the installation process + * @return array An associative array with contents in the form of LanguageCode => LanguageName + */ +function get_installer_list_of_languages() { + + global $CFG; + + $languages = array(); + + /// Get raw list of lang directories + $langdirs = get_list_of_plugins('install/lang'); + asort($langdirs); + /// Get some info from each lang + foreach ($langdirs as $lang) { + if (file_exists($CFG->dirroot .'/install/lang/'. $lang .'/installer.php')) { + include($CFG->dirroot .'/install/lang/'. $lang .'/installer.php'); + if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show + $shortlang = substr($lang, 0, -5); + } else { + $shortlang = $lang; + } + //if ($lang == 'en') { //Explain this is non-utf8 en + // $shortlang = 'non-utf8 en'; + //} + if (!empty($string['thislanguage'])) { + $languages[$lang] = $string['thislanguage'] .' ('. $lang .')'; + } + unset($string); + } + } + /// Return array + return $languages; +} +//=========================================================================// +/** + * Validate options values + * + * @param array $options + */ +function validate_option_values($options){ + $values=array(); + $i=0; + foreach ($options as $val) { + $values[$i++]=$val; + } + if (isset($values['lang'])) { + if (!valid_language($INSTALL['lang'])) { + console_write(STDERR,'invalidvalueforlanguage'); + } + } + if (isset($values['webdir'])) { + /** + * @todo check valid directory path + */ + } + if (isset($values['webaddr'])) { + /** + * @todo check valid http url + */ + } + if (isset($values['moodledir'])) { + /** + * @todo check valid directory path + */ + } + if (isset($values['datadir'])) { + /** + * @todo check valid directory path + */ + } + if (isset($values['dbtype'])) { + $dbtypes=array('mysql','oci8po','postgres7','mssql','mssql_n','odbc_mssql'); + if (!in_array($values['dbtype'],$dbtypes)) { + console_write(STDERR,'invaliddbtype'); + } + } + if (isset($values['dbhost'])) { + /** + * @todo check host? + */ + } + if (isset($values['dbname'])) { + /** + * @todo check name for valid ones if required + */ + } + if (isset($values['dbuser'])) { + /** + * @todo check validity of db user if required + */ + } + if (isset($values['dbpass'])) { + /** + * @todo check validity of database password if required + */ + } + if (isset($values['prefix'])) { + /** + * @todo check for valid prefix + */ + } + if (isset($values['sitefullname'])) { + /** + * @todo check for valid fullname for site + */ + } + if (isset($values['siteshortname'])) { + /** + * @todo check for valid short name for site + */ + } + if (isset($values['sitesummary'])) { + /** + * @todo check for valid summary + */ + } + if (isset($values['sitenewsitems'])) { + /** + * @todo check for valid news items + */ + } + if (isset($values['adminfirstname'])) { + /** + * @todo check for valid admin first name + */ + } + if (isset($values['adminlastname'])) { + /** + * @todo check for valid last name + */ + } + if (isset($values['adminusername'])) { + /** + * @todo check for valid username + */ + } + if (isset($values['adminpassword'])) { + /** + * @todo check for valid password + */ + } + if (isset($values['adminemail'])) { + /** + * @todo check for valid email + */ + } + if (isset($values['verbose'])) { + if(!valid_int_range($values['verbose'],CLI_NO,CLI_FULL)){ + console_write(STDERR,'invalidverbosevalue'); + } + } + if (isset($values['interactivelevel'])) { + if(!valid_int_range($values['verbose'],CLI_NO,CLI_FULL)){ + console_write(STDERR,'invalidinteractivevalue'); + } + } + + if (isset($values['help'])) { + /** + * @todo nothing really + */ + } +} +//=========================================================================// +/** + * Write to standard out and error with exit in error + * + * @param standard out/err $stream + * @param string $identifier + * @param name of module $module + */ +function console_write($stream,$identifier,$module='install',$use_string_lib=true) { + if ($use_string_lib) { + fwrite($stream,get_string($identifier,$module)); + } else { + fwrite($stream,$identifier); + } + if ($stream == STDERR) { + fwrite($stream,get_string('aborting',$module)); + die; + } +} +//=========================================================================// +/** + * Read a mixed type + * + * @param stream $from + * @param int $size + * @return mixed type + */ +function read($from=STDIN,$size=1024) { + $input= trim(fread($from,$size)); + return $input; +} +/** + * Read an integer + * + * @return integer + */ +function read_int() { + $input=read(); + if (valid_param($input,PARAM_INT)) { + return $input; + } else { + console_write(STDERR,'invalidint'); + } +} +//=========================================================================// +/** + * Read and integer value within range + * + * @param int $start + * @param int $end + * @return int + */ +function read_int_range($start,$end) { + $input=read_int(); + if (valid_int_range($input,$start,$end)) { + return $input; + } else { + console_write(STDERR,'invalidintrange'); + } + +} +//=========================================================================// +/** + * Read yes/no argument + * + * @return string yes/no + */ +function read_yes_no() { + $input=strtolower(read()); + if (valid_yes_no($input)) { + if ($input[0]=='y') { + return 'yes'; + } else if($input[0]=='n') { + return 'no'; + } + } else { + console_write(STDERR,'invalidyesno'); + } +} + +//=========================================================================// +/** + * Read a boolean parameter from the input + * + * @return boolean + */ +function read_boolean(){ + $input=read_yes_no(); + return clean_param($input,PARAM_BOOL); + +} +//=========================================================================// +/** + * Reading an element from a given set + * + * @param mixed type array $set + * @return mixed type + */ +function read_element($set=array()) { + $input=read(); + if (valid_element($input,$set)) { + return $input; + } else { + console_write(STDERR,'invalidsetelement'); + } +} +//=========================================================================// +function read_url() { + $input = read(); + $localhost = false; + if ( strpos($input,'localhost') !== false) { + $input = str_replace('localhost','127.0.0.1',$input); + $localhost=true; + } + if (valid_param($input,PARAM_URL)) { + if ($localhost) { + return str_replace('127.0.0.1','localhost',$input); + } else { + return $input; + } + } else { + console_write(STDERR,'invalidurl'); + } + +} +//=========================================================================// +/** + * Enter description here... + * + * @return string + */ +function read_dir() { + $input = read(); + return $input; +} +//===========================================================================// +/** + * Print compatibility message to standard out, and errors to standard error + * + * @param boolean $success + * @param string $testtext + * @param string $errormessage + * @param boolean $caution + * @param boolean $silent + * @return boolean + */ +function check_compatibility($success, $testtext,$errormessage,$caution=false,$silent=false) { + if ($success) { + if (!$silent) { + console_write(STDOUT,get_string('pass', 'install'),'',false); + } + } else { + if ($caution) { + if (!$silent) { + console_write(STDOUT,get_string('caution', 'install'),'',false); + } + } else { + console_write(STDOUT,get_string('fail', 'install'),'',false); + console_write(STDERR,$errormessage,'',false); + } + } + if (!$silent) { + console_write(STDOUT,"\t\t",'',false); + console_write(STDOUT,$testtext,'',false); + console_write(STDOUT,"\n",'',false); + } + return $success; +} + +//==========================================================================// +/** + * Get memeory limit + * + * @return int + */ +function get_memory_limit() { + if ($limit = ini_get('memory_limit')) { + return $limit; + } else { + return get_cfg_var('memory_limit'); + } +} + +//==========================================================================// +/** + * Check memory limit + * + * @return boolean + */ +function check_memory_limit() { + + /// if limit is already 40 or more then we don't care if we can change it or not + if ((int)str_replace('M', '', get_memory_limit()) >= 40) { + return true; + } + + /// Otherwise, see if we can change it ourselves + @ini_set('memory_limit', '40M'); + return ((int)str_replace('M', '', get_memory_limit()) >= 40); +} + +//==========================================================================// +/** + * Check php version + * + * @return boolean + */ +function inst_check_php_version() { + if (!check_php_version("4.3.0")) { + return false; + } else if (check_php_version("5.0.0")) { + return check_php_version("5.1.0"); // 5.0.x is too buggy + } + return true; // 4.3.x or 4.4.x is fine +} +/** + * Print environment status to standard out + * + * @param array $env, of type object + */ +function print_environment_status($env = array()) { + console_write(STDOUT,"Status\t\tInfo\t\tPart\n\r",'',false); + foreach ( $env as $object) { + + if ($object->status == 1 ) { + console_write(STDOUT,'ok','',false); + } else { + console_write(STDOUT,'fail','',false); + } + console_write(STDOUT,"\t\t",'',false); + console_write(STDOUT,$object->info,'',false); + console_write(STDOUT,"\t\t",'',false); + console_write(STDOUT,$object->part,'',false); + console_write(STDOUT,"\n\r",'',false); + } +} + +/** + * Print environment status to standard out + * + * @param array $env, of type object + */ +function print_environment_status_detailed($env = array()) { + console_write(STDOUT,"Status\t\tLevel\t\tCurrent ver\tRequired ver\t\tPart\t\tInfo\n\r",'',false); + foreach ( $env as $object) { + + if ($object->status == 1 ) { + console_write(STDOUT,'ok ','',false); + } else if ($object->errorcode != 0) { + console_write(STDOUT,'fail ','',false); + } else { + console_write(STDOUT,'----','',false); + } + console_write(STDOUT,"\t\t",'',false); + console_write(STDOUT,$object->level,'',false); + console_write(STDOUT,"\t\t",'',false); + console_write(STDOUT,$object->current_version,'',false); + console_write(STDOUT,"\t",'',false); + console_write(STDOUT,$object->needed_version,'',false); + console_write(STDOUT,"\t\t",'',false); + console_write(STDOUT,$object->part,'',false); + console_write(STDOUT,"\t\t",'',false); + console_write(STDOUT,$object->info,'',false); + console_write(STDOUT,"\n\r",'',false); + } +} +/** + * Print a new line in the standard output + * + */ + +function print_newline() { + console_write(STDOUT,'newline','install'); +} +?> diff --git a/lib/locallib.php b/lib/locallib.php index 6aad8b20a2..f1f1ecc190 100644 --- a/lib/locallib.php +++ b/lib/locallib.php @@ -90,26 +90,43 @@ function upgrade_local_db($continueto) { if ($local_version > $CFG->local_version) { // upgrade! $strdatabaseupgrades = get_string('databaseupgrades'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_header($strdatabaseupgrades, $strdatabaseupgrades, build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript()); + } upgrade_log_start(); require_once ($CFG->dirroot .'/local/db/upgrade.php'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=true; + } if (xmldb_local_upgrade($CFG->local_version)) { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=false; + } if (set_config('local_version', $local_version)) { notify(get_string('databasesuccess'), 'notifysuccess'); notify(get_string('databaseupgradelocal', '', $local_version), 'notifysuccess'); + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { print_continue($continueto); print_footer('none'); exit; + } else if (CLI_UPGRADE && ($interactive > CLI_SEMI) ) { + console_write(STDOUT,'askcontinue'); + if (read_boolean()){ + return ; + }else { + console_write(STDERR,'','',false); + } + } } else { error('Upgrade of local database customisations failed! (Could not update version in config table)'); } } else { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $db->debug=false; + } error('Upgrade failed! See local/version.php'); } diff --git a/lib/pear/Console/Getopt.php b/lib/pear/Console/Getopt.php new file mode 100644 index 0000000000..b256d0eed3 --- /dev/null +++ b/lib/pear/Console/Getopt.php @@ -0,0 +1,290 @@ + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +require_once 'PEAR.php'; + +/** + * Command-line options parsing class. + * + * @author Andrei Zmievski + * + */ +class Console_Getopt { + /** + * Parses the command-line options. + * + * The first parameter to this function should be the list of command-line + * arguments without the leading reference to the running program. + * + * The second parameter is a string of allowed short options. Each of the + * option letters can be followed by a colon ':' to specify that the option + * requires an argument, or a double colon '::' to specify that the option + * takes an optional argument. + * + * The third argument is an optional array of allowed long options. The + * leading '--' should not be included in the option name. Options that + * require an argument should be followed by '=', and options that take an + * option argument should be followed by '=='. + * + * The return value is an array of two elements: the list of parsed + * options and the list of non-option command-line arguments. Each entry in + * the list of parsed options is a pair of elements - the first one + * specifies the option, and the second one specifies the option argument, + * if there was one. + * + * Long and short options can be mixed. + * + * Most of the semantics of this function are based on GNU getopt_long(). + * + * @param array $args an array of command-line arguments + * @param string $short_options specifies the list of allowed short options + * @param array $long_options specifies the list of allowed long options + * + * @return array two-element array containing the list of parsed options and + * the non-option arguments + * + * @access public + * + */ + function getopt2($args, $short_options, $long_options = null) + { + return Console_Getopt::doGetopt(2, $args, $short_options, $long_options); + } + + /** + * This function expects $args to start with the script name (POSIX-style). + * Preserved for backwards compatibility. + * @see getopt2() + */ + function getopt($args, $short_options, $long_options = null) + { + return Console_Getopt::doGetopt(1, $args, $short_options, $long_options); + } + + /** + * The actual implementation of the argument parsing code. + */ + function doGetopt($version, $args, $short_options, $long_options = null) + { + // in case you pass directly readPHPArgv() as the first arg + if (PEAR::isError($args)) { + return $args; + } + if (empty($args)) { + return array(array(), array()); + } + $opts = array(); + $non_opts = array(); + + settype($args, 'array'); + + if ($long_options) { + sort($long_options); + } + + /* + * Preserve backwards compatibility with callers that relied on + * erroneous POSIX fix. + */ + if ($version < 2) { + if (isset($args[0]{0}) && $args[0]{0} != '-') { + array_shift($args); + } + } + + reset($args); + while (list($i, $arg) = each($args)) { + + /* The special element '--' means explicit end of + options. Treat the rest of the arguments as non-options + and end the loop. */ + if ($arg == '--') { + $non_opts = array_merge($non_opts, array_slice($args, $i + 1)); + break; + } + + if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) { + $non_opts = array_merge($non_opts, array_slice($args, $i)); + break; + } elseif (strlen($arg) > 1 && $arg{1} == '-') { + $error = Console_Getopt::_parseLongOption(substr($arg, 2), $long_options, $opts, $args); + if (PEAR::isError($error)) + return $error; + } elseif ($arg == '-') { + // - is stdin + $non_opts = array_merge($non_opts, array_slice($args, $i)); + break; + } else { + $error = Console_Getopt::_parseShortOption(substr($arg, 1), $short_options, $opts, $args); + if (PEAR::isError($error)) + return $error; + } + } + + return array($opts, $non_opts); + } + + /** + * @access private + * + */ + function _parseShortOption($arg, $short_options, &$opts, &$args) + { + for ($i = 0; $i < strlen($arg); $i++) { + $opt = $arg{$i}; + $opt_arg = null; + + /* Try to find the short option in the specifier string. */ + if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') + { + return PEAR::raiseError("Console_Getopt: unrecognized option -- $opt"); + } + + if (strlen($spec) > 1 && $spec{1} == ':') { + if (strlen($spec) > 2 && $spec{2} == ':') { + if ($i + 1 < strlen($arg)) { + /* Option takes an optional argument. Use the remainder of + the arg string if there is anything left. */ + $opts[] = array($opt, substr($arg, $i + 1)); + break; + } + } else { + /* Option requires an argument. Use the remainder of the arg + string if there is anything left. */ + if ($i + 1 < strlen($arg)) { + $opts[] = array($opt, substr($arg, $i + 1)); + break; + } else if (list(, $opt_arg) = each($args)) { + /* Else use the next argument. */; + if (Console_Getopt::_isShortOpt($opt_arg) || Console_Getopt::_isLongOpt($opt_arg)) { + return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt"); + } + } else { + return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt"); + } + } + } + + $opts[] = array($opt, $opt_arg); + } + } + + /** + * @access private + * + */ + function _isShortOpt($arg) + { + return strlen($arg) == 2 && $arg[0] == '-' && preg_match('/[a-zA-Z]/', $arg[1]); + } + + /** + * @access private + * + */ + function _isLongOpt($arg) + { + return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' && + preg_match('/[a-zA-Z]+$/', substr($arg, 2)); + } + + /** + * @access private + * + */ + function _parseLongOption($arg, $long_options, &$opts, &$args) + { + @list($opt, $opt_arg) = explode('=', $arg, 2); + $opt_len = strlen($opt); + + for ($i = 0; $i < count($long_options); $i++) { + $long_opt = $long_options[$i]; + $opt_start = substr($long_opt, 0, $opt_len); + $long_opt_name = str_replace('=', '', $long_opt); + + /* Option doesn't match. Go on to the next one. */ + if ($long_opt_name != $opt) { + continue; + } + + $opt_rest = substr($long_opt, $opt_len); + + /* Check that the options uniquely matches one of the allowed + options. */ + if ($i + 1 < count($long_options)) { + $next_option_rest = substr($long_options[$i + 1], $opt_len); + } else { + $next_option_rest = ''; + } + if ($opt_rest != '' && $opt{0} != '=' && + $i + 1 < count($long_options) && + $opt == substr($long_options[$i+1], 0, $opt_len) && + $next_option_rest != '' && + $next_option_rest{0} != '=') { + return PEAR::raiseError("Console_Getopt: option --$opt is ambiguous"); + } + + if (substr($long_opt, -1) == '=') { + if (substr($long_opt, -2) != '==') { + /* Long option requires an argument. + Take the next argument if one wasn't specified. */; + if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) { + return PEAR::raiseError("Console_Getopt: option --$opt requires an argument"); + } + if (Console_Getopt::_isShortOpt($opt_arg) || Console_Getopt::_isLongOpt($opt_arg)) { + return PEAR::raiseError("Console_Getopt: option requires an argument --$opt"); + } + } + } else if ($opt_arg) { + return PEAR::raiseError("Console_Getopt: option --$opt doesn't allow an argument"); + } + + $opts[] = array('--' . $opt, $opt_arg); + return; + } + + return PEAR::raiseError("Console_Getopt: unrecognized option --$opt"); + } + + /** + * Safely read the $argv PHP array across different PHP configurations. + * Will take care on register_globals and register_argc_argv ini directives + * + * @access public + * @return mixed the $argv PHP array or PEAR error if not registered + */ + function readPHPArgv() + { + global $argv; + if (!is_array($argv)) { + if (!@is_array($_SERVER['argv'])) { + if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) { + return PEAR::raiseError("Console_Getopt: Could not read cmd args (register_argc_argv=Off?)"); + } + return $GLOBALS['HTTP_SERVER_VARS']['argv']; + } + return $_SERVER['argv']; + } + return $argv; + } + +} + +?> diff --git a/lib/pear/Console/README b/lib/pear/Console/README new file mode 100644 index 0000000000..85816b6c80 --- /dev/null +++ b/lib/pear/Console/README @@ -0,0 +1,5 @@ +This is licensed originally under the PHP license which is incompatible with the GPL. However, I got explicit permission from the author (Andrei Zmievski ) on 18/12/07 to dual license it: + +"I am fine with my library to be distributed under the GPL by Moodle project (which basically means that it's dual-licensed, as far as I can tell)." + +-- Penny diff --git a/lib/pear/README.txt b/lib/pear/README.txt index e92bdae3b1..b4a216f82f 100644 --- a/lib/pear/README.txt +++ b/lib/pear/README.txt @@ -50,6 +50,11 @@ In detail, the libraries added here are: Greg Beaver and Martin Jansen - License: PHP - http://pear.php.net/package/PEAR +- PEAR Console_Getopt + - Current version: 1.2.3 + - by Andrei Zmievski, Greg Beaver, Stig Bakken + - License: PHP (Permission given to Moodle to redistribute under GPL) + - http://pear.php.net/package/Console_Getopt diff --git a/lib/setuplib.php b/lib/setuplib.php index 5e29ce10ee..875427a94c 100644 --- a/lib/setuplib.php +++ b/lib/setuplib.php @@ -266,6 +266,9 @@ function set_dbfamily() { */ function preconfigure_dbconnection() { + if (defined('ADODB_ASSOC_CASE')) { + return; // when in cli mode, it's possible for this to be called twice (eg cli installer) + } global $CFG; /// Define dbfamily diff --git a/lib/weblib.php b/lib/weblib.php index 278d7d4634..e1b93a08b1 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -2349,6 +2349,16 @@ function print_header ($title='', $heading='', $navigation='', $focus='', $heading = format_string($heading); // Fix for MDL-8582 + if (defined('CLI_UPGRADE') && CLI_UPGRADE ) { + $output = $heading; + if ($return) { + return $output; + } else { + console_write(STDOUT,$output,'',false); + return; + } + } + /// This makes sure that the header is never repeated twice on a page if (defined('HEADER_PRINTED')) { debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: error() and redirect() are now safe to call after print_header().'); @@ -3787,18 +3797,33 @@ function print_headline($text, $size=2, $return=false) { * @param int $size The size to set the font for text display. */ function print_heading($text, $align='', $size=2, $class='main', $return=false) { + global $verbose; if ($align) { $align = ' style="text-align:'.$align.';"'; } if ($class) { $class = ' class="'.$class.'"'; } + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { $output = "".stripslashes_safe($text).""; + } else if ( CLI_UPGRADE ) { + $output = stripslashes_safe($text); + if ($size == 1) { + $output = '=>'.$output; + } else if ($size == 2) { + $output = '-->'.$output; + } + } if ($return) { return $output; } else { + if (!defined('CLI_UPGRADE') || !CLI_UPGRADE ) { echo $output; + } else if (CLI_UPGRADE && ($verbose > CLI_NO) ) { + console_write(STDOUT,$output,'',false); + print_newline(); + } } } @@ -5730,6 +5755,11 @@ function error ($message, $link='') { global $CFG, $SESSION, $THEME; $message = clean_text($message); // In case nasties are in here + if (defined('CLI_UPGRADE') || CLI_UPGRADE) { + console_write(STDERR,$message,'',false); + die ; + } + if (defined('FULLME') && FULLME == 'cron') { // Errors in cron should be mtrace'd. mtrace($message); @@ -6185,13 +6215,19 @@ function redirect($url, $message='', $delay=-1) { * @param bool $return whether to return an output string or echo now */ function notify($message, $style='notifyproblem', $align='center', $return=false) { + global $db; + if ($style == 'green') { $style = 'notifysuccess'; // backward compatible with old color system } $message = clean_text($message); - + if(!defined('CLI_UPGRADE')||!CLI_UPGRADE) { $output = '
'. $message .'
'."\n"; + } else if (CLI_UPGRADE && $db->debug) { + $output = '++'.$message.'++'; + return ; + } if ($return) { return $output; -- 2.39.5