From 3b596dbf0b3c0ba9bfe21b59bedae88238dfd306 Mon Sep 17 00:00:00 2001 From: skodak Date: Wed, 27 May 2009 09:52:25 +0000 Subject: [PATCH] MDL-15249 sample cli scripts - sample implementation only, no localization - ideally we should now decide what parameters we need - let the heated discussion begin ;-) --- admin/cli/install.php | 539 +++++++++++++++ admin/cli/reset_password.php | 85 +++ admin/cli/upgrade.php | 109 +++ admin/cliupgrade.php | 1221 ---------------------------------- lib/clilib.php | 625 +++-------------- 5 files changed, 829 insertions(+), 1750 deletions(-) create mode 100644 admin/cli/install.php create mode 100644 admin/cli/reset_password.php create mode 100644 admin/cli/upgrade.php delete mode 100644 admin/cliupgrade.php diff --git a/admin/cli/install.php b/admin/cli/install.php new file mode 100644 index 0000000000..0ab9105199 --- /dev/null +++ b/admin/cli/install.php @@ -0,0 +1,539 @@ +. + +/** + * This script creates config.php file and prepares database. + * + * This script is not intended for beginners! + * Potential problems: + * - environment check is not present yet + * - su to apache account or sudo before execution + * - not compatible with Windows platform + * + * @package moodlecore + * @subpackage cli + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +if (isset($_SERVER['REMOTE_ADDR'])) { + error_log("admin/cli/install.php can not be called from web server!"); + exit; +} + +$olddir = getcwd(); + +// change directory so that includes bellow work properly +chdir(dirname($_SERVER['argv'][0])); + +// Nothing to do if config.php exists +$configfile = dirname(dirname(dirname(__FILE__))).'/config.php'; +if (file_exists($configfile)) { + die("Moodle already installed, please use admin/cli/upgrade.php if you want to upgrade your site.\n"); +} + +// make sure PHP errors are displayed - helps with diagnosing of problems +@error_reporting(E_ALL); +@ini_set('display_errors', '1'); +// we need a lot of memory +@ini_set('memory_limit', '128M'); + +// Check that PHP is of a sufficient version +if (version_compare(phpversion(), "5.2.8") < 0) { + $phpversion = phpversion(); + // do NOT localise - lang strings would not work here and we CAN NOT move it after installib + echo "Sorry, Moodle 2.0 requires PHP 5.2.8 or later (currently using version $phpversion).\n"; + echo "Please upgrade your server software or install latest Moodle 1.9.x instead."; + die; +} + +// set up configuration +$CFG = new stdClass(); +$CFG->lang = 'en_utf8'; +$CFG->dirroot = str_replace('\\', '/', dirname(dirname(dirname(__FILE__)))); // Fix for win32 +$CFG->libdir = "$CFG->dirroot/lib"; +$CFG->wwwroot = "http://localhost"; +$CFG->httpswwwroot = $CFG->wwwroot; +$CFG->httpsthemewww = $CFG->wwwroot; +$CFG->dataroot = str_replace('\\', '/', dirname(dirname(dirname(__FILE__))).'/moodledata'); +$CFG->docroot = 'http://docs.moodle.org'; +$CFG->directorypermissions = 00777; +$CFG->running_installer = true; +$parts = explode('/', str_replace('\\', '/', dirname(dirname(__FILE__)))); +$CFG->admin = array_pop($parts); + +require($CFG->dirroot.'/version.php'); +$CFG->target_release = $release; + +//point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else +//the problem is that we need specific version of quickforms and hacked excel files :-( +ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path')); + +require_once($CFG->libdir.'/installlib.php'); +require_once($CFG->libdir.'/clilib.php'); +require_once($CFG->libdir.'/setuplib.php'); +require_once($CFG->libdir.'/textlib.class.php'); +require_once($CFG->libdir.'/weblib.php'); +require_once($CFG->libdir.'/dmllib.php'); +require_once($CFG->libdir.'/moodlelib.php'); +require_once($CFG->libdir.'/deprecatedlib.php'); +require_once($CFG->libdir.'/adminlib.php'); +require_once($CFG->libdir.'/environmentlib.php'); +require_once($CFG->libdir.'/xmlize.php'); +require_once($CFG->libdir.'/componentlib.class.php'); +require_once($CFG->libdir.'/upgradelib.php'); + +//Database types +$databases = array('mysqli' => moodle_database::get_driver_instance('mysqli', 'native'), + 'pgsql' => moodle_database::get_driver_instance('pgsql', 'native'), + 'oci' => moodle_database::get_driver_instance('oci', 'native'), + //'sqlsrv' => moodle_database::get_driver_instance('sqlsrv', 'native'), // new MS sql driver - win32 only + //'mssql' => moodle_database::get_driver_instance('mssql', 'native'), // FreeTDS driver + ); +foreach ($databases as $type=>$database) { + if ($database->driver_installed() !== true) { + unset($databases[$type]); + } +} +if (empty($databases)) { + cli_error('No db drivers available!'); // TODO: localize +} + +reset($databases); +$defaultdb = key($databases); + +// now get cli options +list($options, $unrecognized) = cli_get_params(array('lang'=>$CFG->lang, 'wwwroot'=>'', 'dataroot'=>$CFG->dataroot, 'dbtype'=>$defaultdb, 'dbhost'=>'localhost', + 'dbname'=>'moodle', 'dbuser'=>'root', 'dbpass'=>'', 'dbsocket'=>false, 'prefix'=>'mdl_', 'admin-password'=>'', + 'non-interactive'=>false, 'agreelicense'=>false, 'help'=>false), + array('h'=>'help')); + +$interactive = empty($options['non-interactive']); + +// set up language +$lang = clean_param($options['lang'], PARAM_SAFEDIR); +if (file_exists($CFG->dirroot.'/install/lang/'.$lang)) { + $CFG->lang = $lang; +} else { + if (file_exists($CFG->dirroot.'/install/lang/'.$lang.'_utf8')) { + $CFG->lang = $lang.'_utf8'; + } +} + +if ($unrecognized) { + $error = implode("\n ", $unrecognized); + cli_error("Unrecognized options:\n $error \n. Please use --help option."); // TODO: localize, mark as needed in install +} + +if ($options['help']) { + +$help = +"Command line Moodle installer, creates config.php and initializes database. +Please note you must execute this script with the same uid as apache +or use chmod/chown after installation. + +Site defaults may be changed via local/defaults.php. + +Options: +--lang=CODE Installation and default site language. +--wwwroot=URL Web address for the Moodle site, + required in non-interactive mode. +--dataroot=DIR Location of the moodle data folder, + must not be web accessible. Default is moodleroot + in parent directory. +--dbtype=TYPE Database type. Default is mysqli +--dbhost=HOST Database host. Default is localhost +--dbname=NAME Database name. Default is moodle +--dbuser=USERNAME Database user. Default is root +--dbpass=PASSWORD Database password. Default is blank +--dbsocket Use database sockets. Available for some databases only. +--prefix=STRING Table prefix for above database tables. Default is mdl_ +--admin-password=PASS Password for the moodle admin account, + required in non-interactive mode. +--non-interactive No interactive questions, installation fails if any + problem encountered. +--agreelicense Indicates agreement with software license, + required in non-interactive mode. +-h, --help Print out this help + +Example: \$sudo -u wwwrun /usr/bin/php admin/cli/install.php --lang=cs +"; //TODO: localize, mark as needed in install + + echo $help; + die; +} + +$separator = str_repeat('=', 79)."\n"; + +//Print header +echo "Moodle $CFG->target_release command line installation program.\n"; // TODO: localize, mark as needed in install + +//Fist select language +if ($interactive) { + echo $separator; + $languages = install_get_list_of_languages(); + // fomrat the langs nicely - 4 per line + $c = 0; + $langlist = ''; + foreach ($languages as $key=>$lang) { + $c++; + $length = iconv_strlen($lang, 'UTF-8'); + $padded = $lang.str_repeat(' ', 28-$length); + $langlist .= $padded; + if ($c % 3 == 0) { + $langlist .= "\n"; + } + } + $default = str_replace('_utf8', '', $CFG->lang); + $prompt = "Available languages:\n$langlist\nType language code or press Enter to use default value ($default)"; // TODO: localize, mark as needed in install + $error = ''; + do { + echo $error; + $input = cli_input($prompt, $default); + $input = clean_param($input, PARAM_SAFEDIR); + + if (!file_exists($CFG->dirroot.'/install/lang/'.$input.'_utf8')) { + $error = "Incorrect value, please retry.\n"; // TODO: localize, mark as needed in install + } else { + $error = ''; + } + } while ($error !== ''); + $CFG->lang = $input.'_utf8'; +} else { + // already verified +} + + +//We need wwwroot before we test dataroot +$wwwroot = clean_param($options['wwwroot'], PARAM_URL); +$wwwroot = trim($wwwroot, '/'); +if ($interactive) { + echo $separator; + if (strpos($wwwroot, 'http') === 0) { + $prompt = "Type URL of your site \nor press Enter to use default value ($wwwroot)"; // TODO: localize, mark as needed in install + } else { + $prompt = "Type URL of your site"; // TODO: localize, mark as needed in install + } + $error = ''; + do { + echo $error; + $input = cli_input($prompt, $wwwroot); + $input = clean_param($input, PARAM_URL); + $input = trim($input, '/'); + if (strpos($input, 'http') !== 0) { + $error = "Incorrect value, please retry.\n"; // TODO: localize, mark as needed in install + } else { + $error = ''; + } + } while ($error !== ''); + $wwwroot = $input; + +} else { + if (strpos($wwwroot, 'http') !== 0) { + cli_error("Error:\n wwwroot parametr value \"$wwwroot\" in not correct. Please use different value."); // TODO: localize, mark as needed in install + } +} +$CFG->wwwroot = $wwwroot; +$CFG->httpswwwroot = $CFG->wwwroot; +$CFG->httpsthemewww = $CFG->wwwroot; + + +//We need dataroot before lang download +if ($interactive) { + echo $separator; + $i=0; + while(is_dataroot_insecure()) { + $parrent = dirname($CFG->dataroot); + $i++; + if ($parrent == '/' or $parrent == '.' or preg_match('/^[a-z]:\\\?$/i', $parrent) or ($i > 100)) { + $CFG->dataroot = ''; //can not find secure location for dataroot + break; + } + $CFG->dataroot = dirname($parrent).'/moodledata'; + } + $error = ''; + do { + if ($CFG->dataroot !== '') { + $prompt = "Type Moodle data directory \nor press Enter to use default value ($CFG->dataroot)"; // TODO: localize, mark as needed in install + } else { + $prompt = "Type Moodle data directory"; // TODO: localize, mark as needed in install + } + echo $error; + $CFG->dataroot = cli_input($prompt, $CFG->dataroot); + if ($CFG->dataroot === '') { + $error = "Incorrect value, please retry.\n"; // TODO: localize, mark as needed in install + } else if (is_dataroot_insecure()) { + $CFG->dataroot = ''; + $error = "Directory may not be secure, please retry.\n"; // TODO: localize, mark as needed in install + } else { + if (make_upload_directory('lang', false)) { + $error = ''; + } else { + $error = "Can not create dataroot directory, verify permissions or create directory manually.\n"; // TODO: localize, mark as needed in install + } + } + + } while ($error !== ''); + +} else { + if (is_dataroot_insecure()) { + cli_error("Error:\n directory $CFG->dataroot may be directly accessible via web. Please use different directory."); // TODO: localize, mark as needed in install + } +} + +//download lang pack with optional notification +if ($CFG->lang != 'en_utf8') { + if ($interactive) { + echo $separator; + echo "Downloading latest language package from moodle.org...\n"; // TODO: localize, mark as needed in install + } + if ($cd = new component_installer('http://download.moodle.org', 'lang16', $CFG->lang.'.zip', 'languages.md5', 'lang')) { + if ($cd->install() == COMPONENT_ERROR) { + if ($cd->get_error() == 'remotedownloaderror') { + $a = new stdClass(); + $a->url = 'http://download.moodle.org/lang16/'.$CFG->lang.'.zip'; + $a->dest = $CFG->dataroot.'/lang'; + cli_problem(get_string($cd->get_error(), 'error', $a)); + } else { + cli_problem(get_string($cd->get_error(), 'error')); + } + } else { + // install parent lang if defined + if ($parentlang = get_parent_language()) { + if ($cd = new component_installer('http://download.moodle.org', 'lang16', $parentlang.'.zip', 'languages.md5', 'lang')) { + $cd->install(); + } + } + } + } + if ($interactive) { + echo "...finished lang download.\n"; // TODO: localize + } +} +unset($CFG->running_installer); // we use full lang packs from now on + + +// ask for db type - show only drivers available +if ($interactive) { + $options['dbtype'] = strtolower($options['dbtype']); + echo $separator; + echo "Available database drivers\n"; + foreach ($databases as $type=>$database) { + echo " $type:".$database->get_name()."\n"; + } + echo "\n"; + if (!empty($databases[$options['dbtype']])) { + $prompt = "Type driver short name\nor press Enter to use default value (".$options['dbtype'].")"; // TODO: localize + } else { + $prompt = "Type driver short name"; // TODO: localize + } + + $CFG->dbtype = cli_input($prompt, $options['dbtype'], array_keys($databases)); + +} else { + if (empty($databases[$options['dbtype']])) { + cli_error("Error:\n dbtype parametr value \"".$options['dbtype']."\" in not correct. Please use different value."); // TODO: localize + } + $CFG->dbtype = $options['dbtype']; +} +$database = $databases[$CFG->dbtype]; + + +// ask for db host +if ($interactive) { + echo $separator; + if ($options['dbhost'] !== '') { + $prompt = "Type database host\nor press Enter to use default value (".$options['dbhost'].")"; // TODO: localize + } else { + $prompt = "Type database host"; // TODO: localize + } + + $CFG->dbhost = cli_input($prompt, $options['dbhost']); + +} else { + $CFG->dbhost = $options['dbhost']; +} + +// ask for db name +if ($interactive) { + echo $separator; + if ($options['dbname'] !== '') { + $prompt = "Type database name\nor press Enter to use default value (".$options['dbname'].")"; // TODO: localize + } else { + $prompt = "Type database name"; // TODO: localize + } + + $CFG->dbname = cli_input($prompt, $options['dbname']); + +} else { + $CFG->dbname = $options['dbname']; +} + +// ask for db prefix +if ($interactive) { + echo $separator; + //TODO: solve somehow the prefix trouble for oci + if ($options['prefix'] !== '') { + $prompt = "Type table prefix\nor press Enter to use default value (".$options['prefix'].")"; // TODO: localize + } else { + $prompt = "Type table prefix"; // TODO: localize + } + + $CFG->prefix = cli_input($prompt, $options['prefix']); + +} else { + $CFG->prefix = $options['prefix']; +} + +// ask for db user +if ($interactive) { + echo $separator; + if ($options['dbuser'] !== '') { + $prompt = "Type database user name\nor press Enter to use default value (".$options['dbuser'].")"; // TODO: localize + } else { + $prompt = "Type database user name"; // TODO: localize + } + + $CFG->dbuser = cli_input($prompt, $options['dbuser']); + +} else { + $CFG->dbuser = $options['dbuser']; +} + +// ask for db password +if ($interactive) { + echo $separator; + do { + if ($options['dbpass'] !== '') { + $prompt = "Type database user password\nor press Enter to use default value (".$options['dbpass'].")"; // TODO: localize + } else { + $prompt = "Type database user password"; // TODO: localize + } + + $CFG->dbpass = cli_input($prompt, $options['dbpass']); + $hint_database = install_db_validate($database, $CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->prefix, array('dbpersit'=>0, 'dbsocket'=>$options['dbsocket'])); + } while ($hint_database !== ''); + +} else { + $CFG->dbpass = $options['dbpass']; + $hint_database = install_db_validate($database, $CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname, $CFG->prefix, array('dbpersit'=>0, 'dbsocket'=>$options['dbsocket'])); + if ($hint_database !== '') { + cli_error('Can not open connection to database!'); + } +} + +// ask for admin user password +if ($interactive) { + echo $separator; + $prompt = "Type requested password for user 'admin'"; // TODO: localize + do { + $options['admin-password'] = cli_input($prompt); + } while (empty($options['admin-password']) or $options['admin-password'] === 'admin'); +} else { + if (empty($options['admin-password']) or $options['admin-password'] === 'admin') { + cli_error('Requested administrator password must not be empty or easy to guess..'); //TODO: localize + } +} + +if ($interactive) { + echo $separator; + if (!$options['agreelicense']) { + echo "Do you agree to Moodle license blah blah blah?\n"; //TODO: localize and use real license + $input = cli_input('Type yes or y if you agree, ctrl+c if not', '', array('yes', 'y')); // TODO: localize including yes/y + } +} else { + if (!$options['agreelicense']) { + cli_error('You must aggree to license by specifying --agreelicense'); //TODO: localize + } +} + +// Finally we have all info needed for config.php +$configphp = install_generate_configphp($database, $CFG); +umask(0137); +if (($fh = fopen($configfile, 'w')) !== false) { + fwrite($fh, $configphp); + fclose($fh); +} + +if (!file_exists($configfile)) { + cli_error('Can not create config file.'); +} else if ($interactive) { + echo $separator; + echo "config.php created\n"; +} + +// return back to original dir before executing setup.php chich changes the dir again +chdir($olddir); +// We have config.php, it is a real php script from now on :-) +require($configfile); + +// show as much debug as possible +@error_reporting(1023); +@ini_set('display_errors', '1'); +$CFG->debug = 38911; +$CFG->debugdisplay = true; + +$CFG->version = ""; +$CFG->release = ""; + +// read $version adn $release +require($CFG->dirroot.'/version.php'); + +if ($DB->get_tables() ) { + cli_error('Database tables already present, cli installation can not continue.'); +} + +if (!$DB->setup_is_unicodedb()) { + if (!$DB->change_db_encoding()) { + // If could not convert successfully, throw error, and prevent installation + cli_error(get_string('unicoderequired', 'admin')); + } +} + +if ($interactive) { + echo $separator; + echo get_string('databasesetup')."\n"; +} + +// install core +install_core($version, true); +set_config('release', $release); + +// install all plugins types, local, etc. +upgrade_noncore(true); + +// set up admin user password +$DB->set_field('user', 'password', hash_internal_user_password($options['admin-password'], array('username'=>'admin'))); + +// indicate that this site is fully configured +set_config('rolesactive', 1); +upgrade_finished(); + +// log in as admin - we need do anything when applying defaults +$admins = get_admins(); +$admin = reset($admins); +session_set_user($admin); +message_set_default_message_preferences($admin); + +// apply all default settings, do it twice to fill all defaults - some settings depend on other setting +admin_apply_default_settings(NULL, true); +admin_apply_default_settings(NULL, true); +set_config('registerauth', ''); + +echo "yay!!!\n"; + +exit(0); // 0 means success \ No newline at end of file diff --git a/admin/cli/reset_password.php b/admin/cli/reset_password.php new file mode 100644 index 0000000000..ee1a5b71e9 --- /dev/null +++ b/admin/cli/reset_password.php @@ -0,0 +1,85 @@ +. + +/** + * This script allows you to reset any local user password. + * + * @package moodlecore + * @subpackage cli + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +if (isset($_SERVER['REMOTE_ADDR'])) { + error_log("admin/cli/upgrade.php can not be called from web server!"); + exit; +} + +require_once dirname(dirname(dirname(__FILE__))).'/config.php'; +require_once($CFG->libdir.'/clilib.php'); // cli only functions + + +// now get cli options +list($options, $unrecognized) = cli_get_params(array('help'=>false), + array('h'=>'help')); + +$interactive = empty($options['non-interactive']); + +if ($unrecognized) { + $error = implode("\n ", $unrecognized); + cli_error("Unrecognized options:\n $error \n. Please use --help option."); // TODO: localize +} + +if ($options['help']) { + +$help = +"Reset local user passwords, useful especially for admin acounts. + +There are no security checks here because anybody who is able to +execute this file may execute any PHP too. + +Options: +-h, --help Print out this help + +Example: \$sudo -u wwwrun /usr/bin/php admin/cli/reset_password.php +"; //TODO: localize + + echo $help; + die; +} +$prompt = "Password reset - enter username (manual authentication only)"; // TODO: localize +$username = cli_input($prompt); + +if (!$user = $DB->get_record('user', array('auth'=>'manual', 'username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) { + cli_error("Can not find user '$username'"); +} + +$prompt = "Enter new password"; // TODO: localize +$password = cli_input($prompt); + +$errmsg = '';//prevent eclipse warning +if (!check_password_policy($password, $errmsg)) { + cli_error($errmsg); +} + +$hashedpassword = hash_internal_user_password($password); + +$DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id)); + +echo "yay!\n"; + +exit(0); // 0 means success \ No newline at end of file diff --git a/admin/cli/upgrade.php b/admin/cli/upgrade.php new file mode 100644 index 0000000000..2b2d4ad69b --- /dev/null +++ b/admin/cli/upgrade.php @@ -0,0 +1,109 @@ +. + +/** + * This script creates config.php file and prepares database. + * + * This script is not intended for beginners! + * Potential problems: + * - environment check is not present yet + * - su to apache account or sudo before execution + * - not compatible with Windows platform + * + * @package moodlecore + * @subpackage cli + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +if (isset($_SERVER['REMOTE_ADDR'])) { + error_log("admin/cli/upgrade.php can not be called from web server!"); + exit; +} + +require_once dirname(dirname(dirname(__FILE__))).'/config.php'; +require_once($CFG->libdir.'/adminlib.php'); // various admin-only functions +require_once($CFG->libdir.'/upgradelib.php'); // general upgrade/install related functions +require_once($CFG->libdir.'/clilib.php'); // cli only functions + + +// now get cli options +list($options, $unrecognized) = cli_get_params(array('non-interactive'=>false, 'help'=>false), + array('h'=>'help')); + +$interactive = empty($options['non-interactive']); + +if ($unrecognized) { + $error = implode("\n ", $unrecognized); + cli_error("Unrecognized options:\n $error \n. Please use --help option."); // TODO: localize +} + +if ($options['help']) { + +$help = +"Command line Moodle upgrade. +Please note you must execute this script with the same uid as apache! + +Site defaults may be changed via local/defaults.php. + +Options: +--non-interactive No interactive questions or confirmations +-h, --help Print out this help + +Example: \$sudo -u wwwrun /usr/bin/php admin/cli/upgrade.php +"; //TODO: localize + + echo $help; + die; +} + +if (empty($CFG->version)) { + cli_error('missingconfigversion', 'debug'); +} + +require("$CFG->dirroot/version.php"); // defines $version and $release +$CFG->target_release = $release; // used during installation and upgrades + +if ($version < $CFG->version) { + cli_error('The code you are using is OLDER than the version that made these databases!'); // TODO: localize +} + +if ($interactive) { + $prompt = "Do you really want to upgrade Moodle at '$CFG->wwwroot' from '$CFG->release' to '$release'?\nPress ctrl+c to cancel."; // TODO: localize + cli_input($prompt); +} + +if ($version > $CFG->version) { + upgrade_core($version, true); +} +set_config('release', $release); + +// uncoditionally upgrade +upgrade_noncore(true); + +// log in as admin - we need doanything permission when applying defaults +$admins = get_admins(); +$admin = reset($admins); +session_set_user($admin); + +// apply all default settings, just in case do it twice to fill all defaults +admin_apply_default_settings(NULL, true); +admin_apply_default_settings(NULL, true); + +echo "yay!\n"; + +exit(0); // 0 means success \ No newline at end of file diff --git a/admin/cliupgrade.php b/admin/cliupgrade.php deleted file mode 100644 index 6861a93749..0000000000 --- a/admin/cliupgrade.php +++ /dev/null @@ -1,1221 +0,0 @@ -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.'/installlib.php'); -require_once($CFG->libdir.'/clilib.php'); //cli-library -require_once($CFG->libdir.'/setuplib.php'); -require_once($CFG->libdir.'/adminlib.php'); -require_once($CFG->libdir.'/moodlelib.php'); -require_once($CFG->libdir.'/weblib.php'); -require_once($CFG->libdir.'/environmentlib.php'); -require_once($CFG->libdir.'/componentlib.class.php'); -require_once($CFG->dirroot.'/version.php'); - -error('TODO fix CLI installer'); //TODO: fix cli installer - - -/// 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('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('invalidargumenthelp'); - console_write( "\n", '', false); - 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('usagehelp'); - console_write( "\n", '', false); - 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( "\n", '', false); - console_write( "\n", '', false); - console_write('welcometext','install'); - console_write( "\n", '', false); - console_write( "\n", '', false); - } - //============================================================================// - //Language selection for the installation - - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['lang'])) ) ) { - $langs=get_installer_list_of_languages(); - - console_write( "\n", '', false); - console_write( "\n", '', false); - console_write('selectlanguage','install'); - console_write( "\n", '', false); - console_write('availablelangs','install'); - console_write( "\n", '', false); - //output available languages - foreach ( $langs as $language ) { - console_write("\t",'',false); - console_write($language,'',false); - console_write("\n",'',false); - } - console_write( "\n", '', false); - console_write('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( "\n", '', false); - console_write('checkingphpsettings','install'); - console_write( "\n", '', false); - } - /// Check that PHP is of a sufficient version - check_compatibility(inst_check_php_version(), get_string('phpversion', 'install'), get_string('php52versionerror', '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('register_globals'), get_string('globalsquotes', 'install'), get_string('globalswarning', '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( "\n", '', false); - console_write( "\n", '', false); - console_write('locationanddirectories','install'); - console_write( "\n", '', false); - console_write( "\n", '', false); - } - - //input the web directory - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dirroot'])) ) ) { - console_write('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('inputwebadress','install'); - $INSTALL['wwwroot']=read_url(); - } - //input data directory - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dataroot'])) ) ) { - console_write('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']."/$CFG->admin/cliupgrade.php", 'r')) === false) { - console_write_error(get_string('wwwrooterror'),'install',false); - } - } - if (isset($fh)) fclose($fh); - - /// check dirroot - if (($fh = @fopen($INSTALL['dirroot']."/$CFG->admin/cliupgrade.php", 'r')) === false ) { - console_write_error(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_error(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( "\n", '', false); - console_write( "\n", '', false); - console_write('databasesettingsformoodle','install'); - console_write( "\n", '', false); - console_write( "\n", '', false); - } - - //Input dialogs - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbhost']) ))) { - console_write('databasehost','install'); - $INSTALL['dbhost']=read(); // localhost - } - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbname']) ))) { - console_write('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( "\n", '', false); - console_write('availabledbtypes','install'); - console_write( "\n", '', false); - foreach ($dbtypes as $dbtype) { - console_write("\t",'',false); - console_write($dbtype,'install'); - console_write("\n",'',false); - } - - console_write('yourchoice','install'); - $INSTALL['dbtype']=read_element($dbtypes);//'mysql';// - } - - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbuser']) ))) { - console_write('databaseuser','install'); - $INSTALL['dbuser']=read();//'root'; - } - - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['dbpass']) ))) { - console_write('databasepass','install'); - $INSTALL['dbpass']=read();//''; - } - - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['prefix']) ))) { - console_write('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)) { - error_reporting(0); // Hide errors - - if (! $dbconnected = $DB->connect($INSTALL['dbhost'], $INSTALL['dbuser'], $INSTALL['dbpass'], $INSTALL['dbname'], $INSTALL['prefix'])) { - if (!$DB->create_database($INSTALL['dbhost'], $INSTALL['dbuser'], $INSTALL['dbpass'], $INSTALL['dbname'])) { - $errormsg = get_string('dbcreationerror', 'install'); - $nextstage = DATABASE; - } else { - $dbconnected = $DB->connect($INSTALL['dbhost'], $INSTALL['dbuser'], $INSTALL['dbpass'], $INSTALL['dbname'], $INSTALL['prefix']); - } - } else { -// TODO: db encoding checks ?? - } - } - - // check for errors in db section - if (isset($errormsg)) { - console_write_error($errormsg,'',false); - } - - - //==========================================================================// - // Check the environment - - //check connection to database - - if ($dbconnected) { - /// Execute environment check, not printing results - if (!check_moodle_environment($INSTALL['release'], $environment_results, false, ENV_SELECT_RELEASE)) { - $errormsg = get_string('errorsinenvironment', 'install') . "\n"; - } - } 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_error($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( "\n", '', false); - console_write( "\n", '', false); - console_write('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_error(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(get_string($cd->get_error(), 'error', $a),false); - } else { - $downloaderror = get_string($cd->get_error(), 'error'); - console_write(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 && !empty($downloadsuccess)) { - //print success message if language pack download is successful - console_write('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('creatingconfigfile','install'); - console_write( "\n", '', false); - } - - $str = 'export_dbconfig($CONFFILE['dbhost'], $CONFFILE['dbuser'], $CONFFILE['dbpass'], $CONFFILE['dbname'], $CONFFILE['prefix']); - - foreach ($dbconfig as $key=>$value) { - $key = str_pad($key, 9); - $str .= '$CFG->'.$key.' = '.var_export($value, true).";\r\n"; - } - $str .= "\r\n"; - - $str .= '$CFG->wwwroot = '.var_export($CONFFILE['wwwrootform'], true).";\r\n"; - $str .= '$CFG->dirroot = '.var_export($CONFFILE['dirrootform'], true).";\r\n"; - $str .= '$CFG->dataroot = '.var_export($CONFFILE['dataroot'], true).";\r\n"; - $str .= '$CFG->admin = '.var_export($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('configfilecreated','install'); - console_write( "\n", '', false); - } - } else { - console_write('configfilenotwritten','install'); - console_write( "\n", '', false); - console_write( "\n", '', false); - console_write_error( $str, '', false); - } - if ( $verbose ) { - console_write('installationiscomplete','install'); - console_write( "\n", '', false); - } -} - - -if ( file_exists(dirname(dirname(__FILE__)) . '/config.php')) { - // This is what happens if there is no upgrade.... - //console_write_error('configurationfileexist','install'); - //console_write( "\n", '', false); - //die; - - - - // If the configuration file does not exists exit, this should never occur !! - if (!file_exists(dirname(dirname(__FILE__)) . '/config.php')) { - console_write_error('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(), "5.2.4") < 0) { - $phpversion = phpversion(); - console_write_error("Sorry, Moodle requires PHP 5.2.4 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 - - /** - * @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_error("The PHP server variable 'session.auto_start' should be Off ",'',false); - } - - if (ini_get_bool('magic_quotes_runtime')) { - console_write_error("The PHP server variable 'magic_quotes_runtime' should be Off ",'',false); - } - - if (!ini_get_bool('file_uploads')) { - - console_write_error("The PHP server variable 'file_uploads' is not turned On" ,'',false); - } - - /// Check that config.php has been edited - - if ($CFG->wwwroot == "http://example.com/moodle") { - console_write_error("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_error("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_error('Main version.php was not readable or specified','',false);# without version, stop - } - - - if ( $verbose == CLI_NO ) { - $DB->set_debug(false); - } else if ( $verbose == CLI_FULL ) { - $DB->set_debug (true); - } - - /// Check if the main tables have been installed yet or not. - - if (!$tables = $DB->get_tables() ) { // 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($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(get_string('copyrightnotice'),'',false); - print_newline(); - console_write(get_string('gpl'),'',false); - print_newline(); - console_write('doyouagree','install',true); - $agreelicense = read_boolean(); - } - - if ( !isset($agreelicense)) { - $agreelicense = $DEFAULT['agreelicense']; - } - - if (!$agreelicense) { - console_write_error('disagreelicense'); - } - - if ( $interactive == CLI_FULL || ( $interactive == CLI_SEMI && (!isset($INSTALL['confirmrelease']) || empty($INSTALL['confirmrelease'])))) { - console_write(get_string("currentrelease"),'',false); - print_newline(); - console_write("Moodle $release",'',false); - print_newline(); - console_write('askcontinue'); - $confirmrelease = read_boolean(); - } - - if (!isset($confirmrelease)) { - $confirmrelease = $DEFAULT['confirmrelease']; - } - if (!$confirmrelease) { - console_write_error('versionerror'); - } - - $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_started(); - - /// Both old .sql files and new install.xml are supported - /// But we prioritise install.xml (XMLDB) if present - - if (!$DB->setup_is_unicodedb()) { - if (!$DB->change_db_encoding()) { - // If could not convert successfully, throw error, and prevent installation - console_write_error('unicoderequired', 'admin'); - } - } - - $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml"); //New method - - /// Continue with the instalation - - // Install the roles system. - moodle_install_roles(); - - // 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'; - - } - - - - - /// Check version of Moodle code on disk compared with database - /// and upgrade if possible. - - 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 - - $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($strdatabasechecking,'',false); - print_newline(); - console_write('askcontinue'); - $confirmupgrade = read_boolean(); - } - } - if (empty($confirmrelease)) { - - if ( $interactive == CLI_FULL || ($interactive == CLI_SEMI && !isset($INSTALL['confirmrelease']))) { - $strcurrentrelease = get_string("currentrelease"); - console_write($strcurrentrelease,'',false); - print_newline(); - console_write("Moodle $release",'',false); - print_newline(); - console_write(get_string('releasenoteslink', 'install', 'http://docs.moodle.org/en/Release_Notes'),'',false); - print_newline(); - console_write('askcontinue'); - $confirmrelease = read_boolean(); - } - require_once($CFG->libdir.'/environmentlib.php'); - - console_write('environment', 'admin'); - if (!check_moodle_environment($release, $environment_results, false, ENV_SELECT_RELEASE)) { - // Print Environment Status - if ($verbose > CLI_NO) { - print_newline(); - print_environment_status_detailed($environment_results); - print_newline(); - console_write('environmenterrorupgrade', 'admin'); - } - if(!read_boolean()){ - console_write_error('','',false); - } - } else { - - if ( $interactive == CLI_FULL || $interactive == CLI_SEMI) { - console_write('environmentok', 'admin'); - } - } - } - - $strdatabasesuccess = get_string("databasesuccess"); - - - - /// return to original debugging level - $CFG->debug = $origdebug; - error_reporting($CFG->debug); - upgrade_started(); - - /// Upgrade current language pack if we can - upgrade_language_pack(); - - if ( $verbose > CLI_NO ) { - console_write($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 (!update_capabilities()) { - console_write_error('Had trouble upgrading the core capabilities for the Roles System','',false); - } - if (set_config("version", $version)) { - remove_dir($CFG->dataroot . '/cache', true); // flush cache - notify($strdatabasesuccess, "green"); - /// print_continue("upgradesettings.php"); - } else { - console_write_error('Upgrade failed! (Could not update version in config table)','',false); - } - /// Main upgrade not success - } else { - console_write_error('Main Upgrade failed! See lib/db/upgrade.php','',false); - - } - - } else if ($version < $CFG->version) { - notify("WARNING!!! The code you are using is OLDER than the version that made these databases!"); - } - } else { - set_config("version", $version); - } - - - /// 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 - - /// 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/$CFG->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_finished(); - - /// Set up the site - if (! $site = get_site()) { - // We are about to create the site "course" - - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( (!isset($INSTALL['sitefullname'])) || (!isset($INSTALL['siteshortname'])) || (!isset($INSTALL['sitesummary'])) || (!isset($INSTALL['sitenewsitems'])) )) ) { - console_write('siteinfo'); - print_newline(); - } - - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['sitefullname'])) ) ) { - console_write('sitefullname'); - $sitefullname = read(); - } else if (isset($INSTALL['sitefullname'])) { - $sitefullname = $INSTALL['sitefullname']; - } - - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['siteshortname'])) ) ) { - console_write('siteshortname'); - $siteshortname = read(); - } else if (isset($INSTALL['siteshortname'])) { - $siteshortname = $INSTALL['siteshortname']; - } - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['sitesummary'])) ) ) { - console_write('sitesummary'); - $sitesummary =read(); - } else if (isset($INSTALL['sitesummary'])) { - $sitesummary = $INSTALL['sitesummary']; - } - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['sitenewsitems'])) ) ) { - console_write('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 = $sitefullname; - $newsite->shortname = $siteshortname; - $newsite->summary = $sitesummary; - $newsite->newsitems = $sitenewsitems; - $newsite->numsections = 0; - $newsite->category = 0; - $newsite->format = 'site'; // Only for this course - $newsite->timemodified = time(); - - if ($newid = $DB->insert_record('course', $newsite)) { - // Site created, add blocks for it - blocks_add_default_course_blocks($DB->get_record('course', array('id' => $newid))); - - // create default course category - $cat = get_course_category(); - - } - } - - /// 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 (!$DB->record_exists("user", array("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('admininfo'); - print_newline(); - } - // Assign the first name - if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( !isset($INSTALL['adminfirstname'])) ) ) { - console_write('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('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('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('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('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('upgradingcompleted'); - console_write( "\n", '', false); - } -} - - -?> diff --git a/lib/clilib.php b/lib/clilib.php index 3199047116..af015556a6 100644 --- a/lib/clilib.php +++ b/lib/clilib.php @@ -1,6 +1,7 @@ . /** - * CLI support functions - * - * @package moodlecore - * @copyright Dilan - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -/** - * include PEAR Console libraries - */ -set_include_path($CFG->libdir . PATH_SEPARATOR . $CFG->libdir . '/pear/'); -require_once('Console/Getopt.php'); - -/** - * Check the validity of the language - * return true or false + * Command line utility functions and classes * - * @global array - * @param string $lang (short code for language) - * @return bool true/false + * @package moodlecore + * @subpackage cli + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -function valid_language($lang) { - global $DEFAULT; - $langdir = dir($DEFAULT['dirroot'].'/install/lang'); - $i=0; - $validllangs = array(); - while (false !== ($file=$langdir->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 + * Get input from user + * @param string $prompt text prompt, should include possible obptions + * @param string $default default value when enter pressed + * @param array $options list of allowed options, empty means any text + * @param bool $casesensitive true if options are case sensitive + * @return string entered text */ -function get_short_codes ($lang = array()) { - $short_codes = array(); - - foreach ($lang as $key => $value) { - $short_codes[$key] = $key; +function cli_input($prompt, $default='', array $options=null, $casesensitiveoptions=false) { + echo $prompt; + echo "\n: "; + $input = fread(STDIN, 2048); + $input = trim($input); + if ($input === '') { + $input = $default; } - return $short_codes; -} -//========================================================================================// -/** - * Check value for valid yes/no argument - * Return true or false - * - * @param string $value - * @return bool 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; + if ($options) { + if (!$casesensitiveoptions) { + $input = strtolower($input); } - } else { - return false; - } -} -//========================================================================================// -/** - * Can value have a valid integer in the given range - * Return true or false - * @link valid_param() - * - * @uses PARAM_INT - * @param mixed $value - * @param int $start - * @param int $end - * @return bool 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; + if (!in_array($input, $options)) { + echo "Incorrect value, please retry.\n"; // TODO: localize, mark as needed in install + return cli_input($prompt, $default, $options, $casesensitiveoptions); } } + return $input; } /** - * 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 $value - * @param array $set of valid elements - * @return boolean + * Returns cli script parameters. + * @param array $longoptions array of --style options ex:('verbose'=>false) + * @param array $shortmapping array describing mapping of short to long style options ex:('h'=>'help', 'v'=>'verbose') + * @return array array of arrays, options, unrecognised as optionlongname=>value */ +function cli_get_params(array $longoptions, array $shortmapping=null) { + $shortmapping = (array)$shortmapping; + $options = array(); + $unrecognized = array(); -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; - } + if (empty($_SERVER['argv'])) { + // bad luck, we can continue in interactive mode ;-) + return array($options, $unrecognized); } -} - -/** - * 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 mixed $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 - * - * @uses CLI_VAL_REQ - * @uses CLI_VAL_OPT - * @param array $long_opt 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.'=='; - } + $rawoptions = $_SERVER['argv']; - } + //remove anything after '--', options can not be there + if (($key = array_search('--', $rawoptions)) !== false) { + $rawoptions = array_slice($rawoptions, 0, $key); } - return $opt; -} -//========================================================================================// -/** - * This funtion return an array of options with option as key containing the value of - * respective option - * - * @global array - * @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); + //remove script + unset($rawoptions[0]); + foreach ($rawoptions as $raw) { + if (substr($raw, 0, 2) === '--') { + $value = substr($raw, 2); + $parts = explode('=', $value); + if (count($parts) == 1) { + $key = reset($parts); + $value = true; + } else { + $key = array_shift($parts); + $value = implode('=', $parts); } - - //check with valid set of options - if (in_array($input_option,$LONG_OPTIONS)) { - $ret_arr[$input_option]=$value[1]; + if (array_key_exists($key, $longoptions)) { + $options[$key] = $value; + } else { + $unrecognized[] = $raw; } - } - - } - //return array - return $ret_arr; - -} - -//========================================================================================// - -//=========================================================================// -/** - * Validate options values - * - * @uses CLI_FULL - * @uses CLI_NO - * @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($values['lang'])) { - console_write_error('invalidvalueforlanguage'); - console_write( "\n", '', false); - } - } - 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_error('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_error('invalidverbosevalue'); - } - } - if (isset($values['interactivelevel'])) { - if(!valid_int_range($values['verbose'],CLI_NO,CLI_FULL)){ - console_write_error('invalidinteractivevalue'); - } - } - - if (isset($values['help'])) { - /** - * @todo nothing really - */ - } -} -//=========================================================================// -/** - * 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 - * - * @uses PARAM_INT - * @return integer - */ -function read_int() { - $input=read(); - if (valid_param($input,PARAM_INT)) { - return $input; - } else { - console_write_error('invalidint'); - console_write( "\n", '', false); - } -} -//=========================================================================// -/** - * 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_error('invalidintrange'); - console_write( "\n", '', false); - } - -} -//=========================================================================// -/** - * Read yes/no argument - * - * @return string|void yes/no or void - */ -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_error('invalidyesno'); - console_write( "\n", '', false); - } -} - -//=========================================================================// -/** - * Read a boolean parameter from the input - * - * @uses PARAM_BOOL - * @return boolean - */ -function read_boolean(){ - $input=read_yes_no(); - return clean_param($input,PARAM_BOOL); -} -//=========================================================================// -/** - * Reading an element from a given set - * - * @param mixed array $set - * @return mixed - */ -function read_element($set=array()) { - $input=read(); - if (valid_element($input,$set)) { - return $input; - } else { - console_write_error('invalidsetelement'); - console_write( "\n", '', false); - } -} -//=========================================================================// -/** - * Read URL - * - * @uses PARAM_URL - * @return mixed - */ -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_error('invalidurl'); - } - -} -//=========================================================================// -/** - * Enter description here... - * @todo Document this function - * @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(get_string('pass', 'install'),'',false); - } - } else { - if ($caution) { - if (!$silent) { - console_write(get_string('caution', 'install'),'',false); + } else if (substr($raw, 0, 1) === '-') { + $value = substr($raw, 1); + $parts = explode('=', $value); + if (count($parts) == 1) { + $key = reset($parts); + $value = true; + } else { + $key = array_shift($parts); + $value = implode('=', $parts); + } + if (array_key_exists($key, $shortmapping)) { + $options[$shortmapping[$key]] = $value; + } else { + $unrecognized[] = $raw; } } else { - console_write(get_string('fail', 'install'),'',false); - console_write_error($errormessage,'',false); + $unrecognized[] = $raw; + continue; } } - if (!$silent) { - console_write("\t\t",'',false); - console_write($testtext,'',false); - console_write("\n",'',false); - } - return $success; -} - -//==========================================================================// -/** - * Print environment status to standard out - * - * @param array $env of type object - */ -function print_environment_status($env = array()) { - console_write( get_string('name') . "\t\t\t" . get_string('info') . "\t" . get_string('status') . "\n\r", '', false); - //console_write("Status\t\tInfo\t\tPart\n\r",'',false); - foreach ( $env as $object) { - console_write($object->part,'',false); - console_write("\t\t",'',false); - if (!empty($object->info)) { - console_write( $object->info, '', false); - } else { - console_write( "\t", '', false); + //apply defaults + foreach ($longoptions as $key=>$default) { + if (!array_key_exists($key, $options)) { + $options[$key] = $default; } - console_write( "\t\t", '', false); - if ($object->status == 1 ) { - console_write('ok','',false); - } else { - console_write('fail','',false); - } - console_write("\n\r",'',false); } + // finished + return array($options, $unrecognized); } /** - * Print environment status to standard out - * - * @param array $env of type object + * Write error notification + * @param $text + * @return void */ -function print_environment_status_detailed($env = array()) { - console_write("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('ok ','',false); - } else if ($object->errorcode != 0) { - console_write('fail ','',false); - } else { - console_write('----','',false); - } - console_write("\t\t",'',false); - console_write($object->level,'',false); - console_write("\t\t",'',false); - console_write($object->current_version,'',false); - console_write("\t",'',false); - console_write($object->needed_version,'',false); - console_write("\t\t",'',false); - console_write($object->part,'',false); - console_write("\t\t",'',false); - console_write($object->info,'',false); - console_write("\n\r",'',false); - } +function cli_problem($text) { + fwrite(STDERR, $text, "\n"); } + /** - * Print a new line in the standard output + * Write to standard out and error with exit in error. * + * @param string $text + * @param int $errorcode + * @return void (does not return) */ - -function print_newline() { - console_write( "\n", '', false); +function cli_error($text, $errorcode=1) { + fwrite(STDERR, $text); + fwrite(STDERR, "\n"); + die($errorcode); } -?> -- 2.39.5