='); } /** * This function checks if a php extension exists or not and returns an HTML status string. * * @param string $extensionName Name of the PHP extension to be checked * @param string $returnSuccess Text to show when extension is available (defaults to 'Yes') * @param string $returnFailure Text to show when extension is available (defaults to 'No') * @param bool $optional Whether this extension is optional (then show unavailable text in orange rather than * red) * @param string $enabledTerm If this string is not null, then use to check if the corresponding parameter is = 1. * If not, mention it's present but not enabled. For example, for opcache, this should be * 'opcache.enable' * * @return string HTML string reporting the status of this extension. Language-aware. * * @author Christophe Gesch?? * @author Patrick Cool , Ghent University * @author Yannick Warnier */ function checkExtension( $extensionName, $returnSuccess = 'Yes', $returnFailure = 'No', $optional = false, $enabledTerm = '' ) { if (extension_loaded($extensionName)) { if (!empty($enabledTerm)) { $isEnabled = ini_get($enabledTerm); if ('1' == $isEnabled) { return Display::label($returnSuccess, 'success'); } else { if ($optional) { return Display::label(get_lang('Extension installed but not enabled'), 'warning'); } return Display::label(get_lang('Extension installed but not enabled'), 'important'); } } return Display::label($returnSuccess, 'success'); } else { if ($optional) { return Display::label($returnFailure, 'warning'); } return Display::label($returnFailure, 'important'); } } /** * This function checks whether a php setting matches the recommended value. * * @param string $phpSetting A PHP setting to check * @param string $recommendedValue A recommended value to show on screen * @param mixed $returnSuccess What to show on success * @param mixed $returnFailure What to show on failure * * @return string A label to show * * @author Patrick Cool , Ghent University */ function checkPhpSetting( $phpSetting, $recommendedValue, $returnSuccess = false, $returnFailure = false ) { $currentPhpValue = getPhpSetting($phpSetting); if ($currentPhpValue == $recommendedValue) { return Display::label($currentPhpValue.' '.$returnSuccess, 'success'); } return Display::label($currentPhpValue.' '.$returnSuccess, 'important'); } /** * This function return the value of a php.ini setting if not "" or if exists, * otherwise return false. * * @param string $phpSetting The name of a PHP setting * * @return mixed The value of the setting, or false if not found */ function checkPhpSettingExists($phpSetting) { if ('' != ini_get($phpSetting)) { return ini_get($phpSetting); } return false; } /** * Returns a textual value ('ON' or 'OFF') based on a requester 2-state ini- configuration setting. * * @param string $val a php ini value * * @return bool ON or OFF * * @author Joomla */ function getPhpSetting($val) { $value = ini_get($val); switch ($val) { case 'display_errors': global $originalDisplayErrors; $value = $originalDisplayErrors; break; } return '1' == $value ? 'ON' : 'OFF'; } /** * This function returns a string "true" or "false" according to the passed parameter. * * @param int $var The variable to present as text * * @return string the string "true" or "false" * * @author Christophe Gesch?? */ function trueFalse($var) { return $var ? 'true' : 'false'; } /** * This function checks if the given folder is writable. * * @param string $folder Full path to a folder * @param bool $suggestion Whether to show a suggestion or not * * @return string */ function check_writable($folder, $suggestion = false) { if (is_writable($folder)) { return Display::label(get_lang('Writable'), 'success'); } else { if ($suggestion) { return Display::label(get_lang('Not writable'), 'info'); } else { return Display::label(get_lang('Not writable'), 'important'); } } } /** * This function checks if the given folder is readable. * * @param string $folder Full path to a folder * @param bool $suggestion Whether to show a suggestion or not * * @return string */ function checkReadable($folder, $suggestion = false) { if (is_readable($folder)) { return Display::label(get_lang('Readable'), 'success'); } else { if ($suggestion) { return Display::label(get_lang('Not readable'), 'info'); } else { return Display::label(get_lang('Not readable'), 'important'); } } } /** * We assume this function is called from install scripts that reside inside the install folder. */ function set_file_folder_permissions() { @chmod('.', 0755); //set permissions on install dir @chmod('..', 0755); //set permissions on parent dir of install dir } /** * Write the main system config file. * * @param string $path Path to the config file */ function writeSystemConfigFile($path) { $content = file_get_contents(__DIR__.'/'.SYSTEM_CONFIG_FILENAME); $config['{DATE_GENERATED}'] = date('r'); $config['{SECURITY_KEY}'] = md5(uniqid(rand().time())); foreach ($config as $key => $value) { $content = str_replace($key, $value, $content); } $fp = @fopen($path, 'w'); if (!$fp) { echo ' Your script doesn\'t have write access to the config directory
('.str_replace('\\', '/', realpath($path)).')

You probably do not have write access on Chamilo root directory, i.e. you should CHMOD 777 or 755 or 775.

Your problems can be related on two possible causes:
  • Permission problems.
    Try initially with chmod -R 777 and increase restrictions gradually.
  • PHP is running in Safe-Mode. If possible, try to switch it off.
Read about this problem in Support Forum

Please go back to step 5.

'; exit; } fwrite($fp, $content); fclose($fp); } /** * This function returns the value of a parameter from the configuration file. * * WARNING - this function relies heavily on global variables $updateFromConfigFile * and $configFile, and also changes these globals. This can be rewritten. * * @param string $param the parameter of which the value is returned * @param string $updatePath If we want to give the path rather than take it from POST * * @return string the value of the parameter * * @author Olivier Brouckaert * @author Reworked by Ivan Tcholakov, 2010 */ function get_config_param($param, $updatePath = '') { global $updateFromConfigFile; if (empty($updatePath) && !empty($_POST['updatePath'])) { $updatePath = $_POST['updatePath']; } if (empty($updatePath)) { $updatePath = api_get_path(SYMFONY_SYS_PATH); } $updatePath = api_add_trailing_slash(str_replace('\\', '/', realpath($updatePath))); if (empty($updateFromConfigFile)) { // If update from previous install was requested, if (file_exists($updatePath.'app/config/configuration.php')) { $updateFromConfigFile = 'app/config/configuration.php'; } else { // Give up recovering. return null; } } if (file_exists($updatePath.$updateFromConfigFile) && !is_dir($updatePath.$updateFromConfigFile) ) { require $updatePath.$updateFromConfigFile; $config = new Laminas\Config\Config($_configuration); return $config->get($param); } error_log('Config array could not be found in get_config_param()', 0); return null; } /** * Gets a configuration parameter from the database. Returns returns null on failure. * * @param string $param Name of param we want * * @return mixed The parameter value or null if not found */ function get_config_param_from_db($param = '') { $param = Database::escape_string($param); if (false !== ($res = Database::query("SELECT * FROM settings_current WHERE variable = '$param'"))) { if (Database::num_rows($res) > 0) { $row = Database::fetch_array($res); return $row['selected_value']; } } return null; } /** * Connect to the database and returns the entity manager. * * @param string $host * @param string $username * @param string $password * @param string $databaseName * @param int $port * * @return \Database */ function connectToDatabase( $host, $username, $password, $databaseName, $port = 3306 ) { $database = new \Database(); $database->connect( [ 'driver' => 'pdo_mysql', 'host' => $host, 'port' => $port, 'user' => $username, 'password' => $password, 'dbname' => $databaseName, ] ); return $database; } /** * This function prints class=active_step $current_step=$param. * * @param int $param A step in the installer process * * @author Patrick Cool , Ghent University */ function step_active($param) { global $current_step; if ($param == $current_step) { echo 'active'; } } /** * This function displays the Step X of Y -. * * @return string String that says 'Step X of Y' with the right values */ function display_step_sequence() { global $current_step; return get_lang('Step'.$current_step).' – '; } /** * Displays a drop down box for selection the preferred language. */ function display_language_selection_box($name = 'language_list', $default_language = 'en_US') { // Displaying the box. return Display::select( 'language_list', array_column(LanguageFixtures::getLanguages(),'english_name', 'isocode'), $default_language, ['class' => 'form-control'], false ); } /** * This function displays a language dropdown box so that the installatioin * can be done in the language of the user. */ function display_language_selection() { ?>

, Ghent University */ function display_requirements( $installType, $badUpdatePath, $updatePath = '', $upgradeFromVersion = [] ) { global $_setting, $originalMemoryLimit; $dir = api_get_path(SYS_ARCHIVE_PATH).'temp/'; $fileToCreate = 'test'; $perms_dir = [0777, 0755, 0775, 0770, 0750, 0700]; $perms_fil = [0666, 0644, 0664, 0660, 0640, 0600]; $course_test_was_created = false; $dir_perm_verified = 0777; foreach ($perms_dir as $perm) { $r = @mkdir($dir, $perm); if (true === $r) { $dir_perm_verified = $perm; $course_test_was_created = true; break; } } $fil_perm_verified = 0666; $file_course_test_was_created = false; if (is_dir($dir)) { foreach ($perms_fil as $perm) { if (true == $file_course_test_was_created) { break; } $r = @touch($dir.'/'.$fileToCreate, $perm); if (true === $r) { $fil_perm_verified = $perm; $file_course_test_was_created = true; } } } @unlink($dir.'/'.$fileToCreate); @rmdir($dir); echo '

'.display_step_sequence().get_lang('Requirements').'

'; echo '
'; echo ''.get_lang('Please read the following requirements thoroughly.').'
'; echo get_lang('For more details').' '. get_lang('Read the installation guide').'.
'."\n"; if ('update' == $installType) { echo get_lang( 'If you plan to upgrade from an older version of Chamilo, you might want to have a look at the changelog to know what\'s new and what has been changed').'
'; } echo '
'; // SERVER REQUIREMENTS echo '

'.get_lang('Server requirements').'

'; $timezone = checkPhpSettingExists('date.timezone'); if (!$timezone) { echo "
 ". get_lang('We have detected that your PHP installation does not define the date.timezone setting. This is a requirement of Chamilo. Please make sure it is configured by checking your php.ini configuration, otherwise you will run into problems. We warned you!').'
'; } echo '
'.get_lang('Server requirementsInfo').'
'; echo '
'; echo '
'.get_lang('PHP version').' >= '.REQUIRED_PHP_VERSION.' '; if (version_compare(phpversion(), REQUIRED_PHP_VERSION, '>=') > 1) { echo ''.get_lang('PHP versionError').''; } else { echo ''.get_lang('PHP versionOK').' '.phpversion().''; } echo '
Session '.get_lang('Support').' '. checkExtension('session', get_lang('Yes'), get_lang('Sessions extension not available')).'
pdo_mysql '.get_lang('Support').' '. checkExtension('pdo_mysql', get_lang('Yes'), get_lang('MySQL extension not available')).'
Zip '.get_lang('Support').' '. checkExtension('zip', get_lang('Yes'), get_lang('Extension not available')).'
Zlib '.get_lang('Support').' '. checkExtension('zlib', get_lang('Yes'), get_lang('Zlib extension not available')).'
Perl-compatible regular expressions '.get_lang('Support').' '. checkExtension('pcre', get_lang('Yes'), get_lang('PCRE extension not available')).'
XML '.get_lang('Support').' '. checkExtension('xml', get_lang('Yes'), get_lang('No')).'
Internationalization '.get_lang('Support').' '.checkExtension('intl', get_lang('Yes'), get_lang('No')).'
JSON '.get_lang('Support').' '.checkExtension('json', get_lang('Yes'), get_lang('No')).'
GD '.get_lang('Support').' '. checkExtension('gd', get_lang('Yes'), get_lang('GD Extension not available')).'
cURL'.get_lang('Support').' '. checkExtension('curl', get_lang('Yes'), get_lang('No')).'
Multibyte string '.get_lang('Support').' '. checkExtension('mbstring', get_lang('Yes'), get_lang('MBString extension not available'), true).'
Exif '.get_lang('Support').' '. checkExtension('exif', get_lang('Yes'), get_lang('Exif extension not available'), true).'
Zend OpCache '.get_lang('Support').' ('.get_lang('Optional').') '. checkExtension('Zend OPcache', get_lang('Yes'), get_lang('No'), true, 'opcache.enable').'
APCu '.get_lang('Support').' ('.get_lang('Optional').') '. checkExtension('apcu', get_lang('Yes'), get_lang('No'), true, 'apc.enabled').'
Iconv '.get_lang('Support').' ('.get_lang('Optional').') '. checkExtension('iconv', get_lang('Yes'), get_lang('No'), true).'
LDAP '.get_lang('Support').' ('.get_lang('Optional').') '. checkExtension('ldap', get_lang('Yes'), get_lang('LDAP Extension not available'), true).'
Xapian '.get_lang('Support').' ('.get_lang('Optional').') '. checkExtension('xapian', get_lang('Yes'), get_lang('No'), true).'
'; echo '
'; // RECOMMENDED SETTINGS // Note: these are the settings for Joomla, does this also apply for Chamilo? // Note: also add upload_max_filesize here so that large uploads are possible echo '

'.get_lang('(recommended) settings').'

'; echo '
'.get_lang('(recommended) settingsInfo').'
'; echo '
'; echo '
'.get_lang('Setting').' '.get_lang('(recommended)').' '.get_lang('Currently').'
Display Errors '.checkPhpSetting('display_errors', 'OFF').'
File Uploads '.checkPhpSetting('file_uploads', 'ON').'
Session auto start '.checkPhpSetting('session.auto_start', 'OFF').'
Short Open Tag '.checkPhpSetting('short_open_tag', 'OFF').'
Cookie HTTP Only '.checkPhpSetting('session.cookie_httponly', 'ON').'
Maximum upload file size '.compare_setting_values(ini_get('upload_max_filesize'), REQUIRED_MIN_UPLOAD_MAX_FILESIZE).'
Maximum post size '.compare_setting_values(ini_get('post_max_size'), REQUIRED_MIN_POST_MAX_SIZE).'
Memory Limit '.compare_setting_values($originalMemoryLimit, REQUIRED_MIN_MEMORY_LIMIT).'
'; echo '
'; // DIRECTORY AND FILE PERMISSIONS echo '

'.get_lang('Directory and files permissions').'

'; echo '
'.get_lang('Directory and files permissionsInfo').'
'; echo '
'; $_SESSION['permissions_for_new_directories'] = $_setting['permissions_for_new_directories'] = $dir_perm_verified; $_SESSION['permissions_for_new_files'] = $_setting['permissions_for_new_files'] = $fil_perm_verified; $dir_perm = Display::label('0'.decoct($dir_perm_verified), 'info'); $file_perm = Display::label('0'.decoct($fil_perm_verified), 'info'); $oldConf = ''; if (file_exists(api_get_path(SYS_CODE_PATH).'inc/conf/configuration.php')) { $oldConf = ' '.api_get_path(SYS_CODE_PATH).'inc/conf '.check_writable(api_get_path(SYS_CODE_PATH).'inc/conf').' '; } $basePath = api_get_path(SYMFONY_SYS_PATH); echo ' '.$oldConf.'
'.$basePath.'var/ '.check_writable($basePath.'var').'
'.$basePath.'.env.local '.checkCanCreateFile($basePath.'.env.local').'
'.$basePath.'config/ '.check_writable($basePath.'config').'
'.get_lang('Permissions for new directories').' '.$dir_perm.'
'.get_lang('Permissions for new files').' '.$file_perm.'
'; echo '
'; if ('update' === $installType && (empty($updatePath) || $badUpdatePath)) { if ($badUpdatePath) { echo '
'; echo get_lang('Error'); echo '
'; echo 'Chamilo '.implode('|', $upgradeFromVersion).' '.get_lang('has not been found in that directory').'
'; } else { echo '
'; } ?>

:

The user would have to adjust the permissions manually if (count($notWritable) > 0) { error_log('Installer: At least one needed directory or file is not writeable'); $error = true; ?>

', ''); ?>

'; foreach ($notWritable as $value) { echo '
  • '.$value.'
  • '; } echo ''; } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) { // Check wether a Chamilo configuration file already exists. echo '

    '; echo get_lang('Warning !ExistingLMSInstallationDetected'); echo '

    '; } $deprecated = [ api_get_path(SYS_CODE_PATH).'exercice/', api_get_path(SYS_CODE_PATH).'newscorm/', api_get_path(SYS_PLUGIN_PATH).'ticket/', api_get_path(SYS_PLUGIN_PATH).'skype/', ]; $deprecatedToRemove = []; foreach ($deprecated as $deprecatedDirectory) { if (!is_dir($deprecatedDirectory)) { continue; } $deprecatedToRemove[] = $deprecatedDirectory; } if (count($deprecatedToRemove) > 0) { ?>

    '.display_step_sequence().get_lang('Licence').'

    '; echo '

    '.get_lang('Chamilo is free software distributed under the GNU General Public licence (GPL).').'

    '; echo '

    '.get_lang('Printable version').'

    '; $license = api_htmlentities(@file_get_contents(api_get_path(SYMFONY_SYS_PATH).'public/documentation/license.txt')); echo ''; echo '
                '.$license.'
            

    '. get_lang('The images and media galleries of Chamilo use images from Nuvola, Crystal Clear and Tango icon galleries. Other images and media like diagrams and Flash animations are borrowed from Wikimedia and Ali Pakdel\'s and Denis Hoa\'s courses with their agreement and released under BY-SA Creative Commons license. You may find the license details at the CC website, where a link to the full text of the license is provided at the bottom of the page.').'

    '.get_lang('Contact informationDescription').'

    '.get_contact_registration_form().'


    '; } /** * Get contact registration form. */ function get_contact_registration_form() { return '
    '.get_countries_list_from_array(true).'
     
     
    *'.get_lang('Mandatory field').'
    '; } /** * Displays a parameter in a table row. * Used by the display_database_settings_form function. * * @param string Type of install * @param string Name of parameter * @param string Field name (in the HTML form) * @param string Field value * @param string Extra notice (to show on the right side) * @param bool Whether to display in update mode * @param string Additional attribute for the element */ function displayDatabaseParameter( $installType, $parameterName, $formFieldName, $parameterValue, $extra_notice, $displayWhenUpdate = true ) { echo "
    $parameterName
    "; echo '
    '; if (INSTALL_TYPE_UPDATE == $installType && $displayWhenUpdate) { echo ''.$parameterValue; } else { $inputType = 'dbPassForm' === $formFieldName ? 'password' : 'text'; //Slightly limit the length of the database prefix to avoid having to cut down the databases names later on $maxLength = 'dbPrefixForm' === $formFieldName ? '15' : MAX_FORM_FIELD_LENGTH; if (INSTALL_TYPE_UPDATE == $installType) { echo ''; echo api_htmlentities($parameterValue); } else { echo ' '.$extra_notice.' '; } } echo '
    '; } /** * Displays step 3 - a form where the user can enter the installation settings * regarding the databases - login and password, names, prefixes, single * or multiple databases, tracking or not... * * @param string $installType * @param string $dbHostForm * @param string $dbUsernameForm * @param string $dbPassForm * @param string $dbNameForm * @param int $dbPortForm * @param string $installationProfile */ function display_database_settings_form( $installType, $dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm, $dbPortForm = 3306, $installationProfile = '' ) { if ('update' === $installType) { $dbHostForm = get_config_param('db_host'); $dbUsernameForm = get_config_param('db_user'); $dbPassForm = get_config_param('db_password'); $dbNameForm = get_config_param('main_database'); $dbPortForm = get_config_param('db_port'); echo '

    '.display_step_sequence().get_lang('Database settings').'

    '; echo '
    '; echo get_lang('The upgrade script will recover and update the Chamilo database(s). In order to do this, this script will use the databases and settings defined below. Because our software runs on a wide range of systems and because all of them might not have been tested, we strongly recommend you do a full backup of your databases before you proceed with the upgrade!'); echo '
    '; } else { echo '

    '.display_step_sequence().get_lang('Database settings').'

    '; echo '
    '; echo get_lang('The install script will create (or use) the Chamilo database using the database name given here. Please make sure the user you give has the right to create the database by the name given here. If a database with this name exists, it will be overwritten. Please do not use the root user as the Chamilo database user. This can lead to serious security issues.'); echo '
    '; } echo '
    '.get_lang('Database Host').'
    '; if ('update' === $installType) { echo '
    '.$dbHostForm.'
    '; } else { echo '
    '.get_lang('ex.').'localhost
    '; } echo '
    '.get_lang('Port').'
    '; if ('update' === $installType) { echo '
    '.$dbPortForm.'
    '; } else { echo '
    '.get_lang('ex.').' 3306
    '; } //database user username $example_login = get_lang('ex.').' root'; displayDatabaseParameter( $installType, get_lang('Database Login'), 'dbUsernameForm', $dbUsernameForm, $example_login ); //database user password $example_password = get_lang('ex.').' '.api_generate_password(); displayDatabaseParameter($installType, get_lang('Database Password'), 'dbPassForm', $dbPassForm, $example_password); // Database Name fix replace weird chars if (INSTALL_TYPE_UPDATE != $installType) { $dbNameForm = str_replace(['-', '*', '$', ' ', '.'], '', $dbNameForm); } displayDatabaseParameter( $installType, get_lang('Database name'), 'dbNameForm', $dbNameForm, ' ', null, 'id="optional_param1"' ); echo '
    '; if (INSTALL_TYPE_UPDATE != $installType) { ?> getConnection(); $connection->connect(); $schemaManager = $connection->getSchemaManager(); // Test create/alter/drop table $table = 'zXxTESTxX_'.mt_rand(0, 1000); $sql = "CREATE TABLE $table (id INT AUTO_INCREMENT NOT NULL, name varchar(255), PRIMARY KEY(id))"; $connection->executeQuery($sql); $tableCreationWorks = false; $tableDropWorks = false; if ($schemaManager->tablesExist($table)) { $sql = "ALTER TABLE $table ADD COLUMN name2 varchar(140) "; $connection->executeQuery($sql); $schemaManager->dropTable($table); $tableDropWorks = false === $schemaManager->tablesExist($table); } } else { $manager = connectToDatabase( $dbHostForm, $dbUsernameForm, $dbPassForm, null, $dbPortForm ); $schemaManager = $manager->getConnection()->getSchemaManager(); $databases = $schemaManager->listDatabases(); if (in_array($dbNameForm, $databases)) { $databaseExistsText = '
    '. get_lang('A database with the same name already exists. It will be deleted.'). '
    '; } } } catch (Exception $e) { $databaseExistsText = $e->getMessage(); $manager = false; } if ($manager && $manager->getConnection()->isConnected()) { echo $databaseExistsText; ?>
    Database host: getConnection()->getHost(); ?>
    Database port: getConnection()->getPort(); ?>
    Database driver: getConnection()->getDriver()->getName(); ?>
    Ok'; echo '
    '; echo get_lang('AlterTableWorks').' Ok'; echo '
    '; echo get_lang('DropColumnWorks').' Ok'; } ?>

    '; $html .= ''; if (INSTALL_TYPE_UPDATE == $installType && $displayWhenUpdate) { $html .= ''.$parameterValue; } else { $html .= '
    '.'
    '; } $html .= ''; return $html; } /** * Displays step 4 of the installation - configuration settings about Chamilo itself. * * @param string $installType * @param string $urlForm * @param string $languageForm * @param string $emailForm * @param string $adminFirstName * @param string $adminLastName * @param string $adminPhoneForm * @param string $campusForm * @param string $institutionForm * @param string $institutionUrlForm * @param string $encryptPassForm * @param bool $allowSelfReg * @param bool $allowSelfRegProf * @param string $loginForm * @param string $passForm */ function display_configuration_settings_form( $installType, $urlForm, $languageForm, $emailForm, $adminFirstName, $adminLastName, $adminPhoneForm, $campusForm, $institutionForm, $institutionUrlForm, $encryptPassForm, $allowSelfReg, $allowSelfRegProf, $loginForm, $passForm ) { if ('update' !== $installType && empty($languageForm)) { $languageForm = $_SESSION['install_language']; } echo '
    '; echo '

    '.display_step_sequence().get_lang('Configuration settings').'

    '; echo '
    '; // Parameter 1: administrator's login if ('update' === $installType) { $rootSys = get_config_param('root_web'); $html = display_configuration_parameter( $installType, get_lang('Chamilo URL'), 'loginForm', $rootSys, true ); $rootSys = get_config_param('root_sys'); $html .= display_configuration_parameter( $installType, get_lang('Path'), 'loginForm', $rootSys, true ); $systemVersion = get_config_param('system_version'); $html .= display_configuration_parameter( $installType, get_lang('Version'), 'loginForm', $systemVersion, true ); echo Display::panel($html, get_lang('System')); } $html = display_configuration_parameter( $installType, get_lang('Administrator login'), 'loginForm', $loginForm, 'update' == $installType ); // Parameter 2: administrator's password if ('update' !== $installType) { $html .= display_configuration_parameter( $installType, get_lang('Administrator password (you may want to change this)'), 'passForm', $passForm, false ); } // Parameters 3 and 4: administrator's names $html .= display_configuration_parameter( $installType, get_lang('Administrator first name'), 'adminFirstName', $adminFirstName ); $html .= display_configuration_parameter( $installType, get_lang('Administrator last name'), 'adminLastName', $adminLastName ); // Parameter 3: administrator's email $html .= display_configuration_parameter($installType, get_lang('Admin-mail'), 'emailForm', $emailForm); // Parameter 6: administrator's telephone $html .= display_configuration_parameter( $installType, get_lang('Administrator telephone'), 'adminPhoneForm', $adminPhoneForm ); echo Display::panel($html, get_lang('Administrator')); // First parameter: language. $html = '
    '; $html .= ''; if ('update' === $installType) { $html .= ''. $languageForm; } else { $html .= '
    '; $html .= display_language_selection_box('languageForm', $languageForm); $html .= '
    '; } $html .= '
    '; // Second parameter: Chamilo URL if ('install' === $installType) { $html .= '
    '; $html .= ''; $html .= '
    '; $html .= ''; $html .= '
    '; $html .= '
    '; } // Parameter 9: campus name $html .= display_configuration_parameter( $installType, get_lang('Your portal name'), 'campusForm', $campusForm ); // Parameter 10: institute (short) name $html .= display_configuration_parameter( $installType, get_lang('Your company short name'), 'institutionForm', $institutionForm ); // Parameter 11: institute (short) name $html .= display_configuration_parameter( $installType, get_lang('URL of this company'), 'institutionUrlForm', $institutionUrlForm ); $html .= '
    '; if ('update' === $installType) { $html .= ''.$encryptPassForm; } else { $html .= '
    '; $html .= ''; $html .= ''; $html .= ''; $html .= '
    '; } $html .= '
    '; $html .= '
    '; if ('update' === $installType) { if ('true' === $allowSelfReg) { $label = get_lang('Yes'); } elseif ('false' === $allowSelfReg) { $label = get_lang('No'); } else { $label = get_lang('After approval'); } $html .= ''.$label; } else { $html .= '
    '; $html .= ''; $html .= ''; $html .= ''; $html .= '
    '; } $html .= '
    '; $html .= '
    '; $html .= '
    '; $html .= '
    '; if ('update' === $installType) { if ('true' === $allowSelfRegProf) { $label = get_lang('Yes'); } else { $label = get_lang('No'); } $html .= ''.$label; } else { $html .= '
    '; $html .= ''; $html .= '
    '; } $html .= '
    '; echo Display::panel($html, get_lang('Portal')); ?>
    get('translator'); $html = '
    '. $trans->trans( 'When you enter your portal for the first time, the best way to understand it is to create a course with the \'Create course\' link in the menu and play around a little.').'
    '; $html .= '
    '; $html .= ''.$trans->trans('Security advice').''; $html .= ': '; $html .= sprintf($trans->trans( 'To protect your site, make the whole %s directory read-only (chmod -R 0555 on Linux) and delete the %s directory.'), 'var/config/', 'main/install/'); $html .= '

    '.$trans->trans('Go to your newly created portal.').' '; return $html; } /** * This function return countries list from array (hardcoded). * * @param bool $combo (Optional) True for returning countries list with select html * * @return array|string countries list */ function get_countries_list_from_array($combo = false) { $a_countries = [ 'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombi', 'Comoros', 'Congo (Brazzaville)', 'Congo', 'Costa Rica', "Cote d'Ivoire", 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'East Timor (Timor Timur)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia, The', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, North', 'Korea, South', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepa', 'Netherlands', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russia', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia and Montenegro', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe', ]; if ($combo) { $country_select = ''; return $country_select; } return $a_countries; } /** * Lock settings that can't be changed in other portals. */ function lockSettings() { $settings = api_get_locked_settings(); $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT); foreach ($settings as $setting) { $sql = "UPDATE $table SET access_url_locked = 1 WHERE variable = '$setting'"; Database::query($sql); } } /** * Update dir values. */ function updateDirAndFilesPermissions() { $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT); $permissions_for_new_directories = isset($_SESSION['permissions_for_new_directories']) ? $_SESSION['permissions_for_new_directories'] : 0770; $permissions_for_new_files = isset($_SESSION['permissions_for_new_files']) ? $_SESSION['permissions_for_new_files'] : 0660; // use decoct() to store as string Database::update( $table, ['selected_value' => '0'.decoct($permissions_for_new_directories)], ['variable = ?' => 'permissions_for_new_directories'] ); Database::update( $table, ['selected_value' => '0'.decoct($permissions_for_new_files)], ['variable = ?' => 'permissions_for_new_files'] ); if (isset($_SESSION['permissions_for_new_directories'])) { unset($_SESSION['permissions_for_new_directories']); } if (isset($_SESSION['permissions_for_new_files'])) { unset($_SESSION['permissions_for_new_files']); } } /** * @param $current_value * @param $wanted_value * * @return string */ function compare_setting_values($current_value, $wanted_value) { $current_value_string = $current_value; $current_value = (float) $current_value; $wanted_value = (float) $wanted_value; if ($current_value >= $wanted_value) { return Display::label($current_value_string, 'success'); } return Display::label($current_value_string, 'important'); } /** * Save settings values. * * @param string $organizationName * @param string $organizationUrl * @param string $siteName * @param string $adminEmail * @param string $adminLastName * @param string $adminFirstName * @param string $language * @param string $allowRegistration * @param string $allowTeacherSelfRegistration * @param string $installationProfile The name of an installation profile file in main/install/profiles/ */ function installSettings( $organizationName, $organizationUrl, $siteName, $adminEmail, $adminLastName, $adminFirstName, $language, $allowRegistration, $allowTeacherSelfRegistration, $installationProfile = '' ) { error_log('installSettings'); $allowTeacherSelfRegistration = $allowTeacherSelfRegistration ? 'true' : 'false'; $settings = [ 'institution' => $organizationName, 'institution_url' => $organizationUrl, 'site_name' => $siteName, 'administrator_email' => $adminEmail, 'administrator_surname' => $adminLastName, 'administrator_name' => $adminFirstName, 'platform_language' => $language, 'allow_registration' => $allowRegistration, 'allow_registration_as_teacher' => $allowTeacherSelfRegistration, ]; foreach ($settings as $variable => $value) { $sql = "UPDATE settings_current SET selected_value = '$value' WHERE variable = '$variable'"; Database::query($sql); } installProfileSettings($installationProfile); } /** * Executes DB changes based in the classes defined in * /src/CoreBundle/Migrations/Schema/V200/*. * * @return bool */ function migrate(EntityManager $manager) { $debug = true; $connection = $manager->getConnection(); $to = null; // if $to == null then schema will be migrated to latest version // Loading migration configuration. $config = new PhpFile('./migrations.php'); $dependency = DependencyFactory::fromConnection($config, new ExistingConnection($connection)); // Check if old "version" table exists from 1.11.x, use new version. $schema = $manager->getConnection()->getSchemaManager(); $dropOldVersionTable = false; if ($schema->tablesExist('version')) { $columns = $schema->listTableColumns('version'); if (in_array('id', array_keys($columns), true)) { $dropOldVersionTable = true; } } if ($dropOldVersionTable) { error_log('Drop version table'); $schema->dropTable('version'); } // Creates "version" table. $dependency->getMetadataStorage()->ensureInitialized(); // Loading migrations. $migratorConfigurationFactory = $dependency->getConsoleInputMigratorConfigurationFactory(); $result = ''; $input = new Symfony\Component\Console\Input\StringInput($result); $migratorConfiguration = $migratorConfigurationFactory->getMigratorConfiguration($input); $migrator = $dependency->getMigrator(); $planCalculator = $dependency->getMigrationPlanCalculator(); $migrations = $planCalculator->getMigrations(); $lastVersion = $migrations->getLast(); $plan = $dependency->getMigrationPlanCalculator()->getPlanUntilVersion($lastVersion->getVersion()); foreach ($plan->getItems() as $item) { error_log("Version to be executed: ".$item->getVersion()); $item->getMigration()->setEntityManager($manager); $item->getMigration()->setContainer(Container::$container); } // Execute migration!! /** @var $migratedVersions */ $versions = $migrator->migrate($plan, $migratorConfiguration); if ($debug) { /** @var Query[] $queries */ $versionCounter = 1; foreach ($versions as $version => $queries) { $total = count($queries); echo '----------------------------------------------
    '; $message = "VERSION: $version"; echo "$message
    "; error_log('-------------------------------------'); error_log($message); $counter = 1; foreach ($queries as $query) { $sql = $query->getStatement(); echo "$sql
    "; error_log("$counter/$total : $sql"); $counter++; } $versionCounter++; } echo '
    DONE!
    '; error_log('DONE!'); } return true; } /** * @param string $distFile * @param string $envFile * @param array $params */ function updateEnvFile($distFile, $envFile, $params) { $requirements = [ 'DATABASE_HOST', 'DATABASE_PORT', 'DATABASE_NAME', 'DATABASE_USER', 'DATABASE_PASSWORD', 'APP_INSTALLED', 'APP_ENCRYPT_METHOD', ]; foreach ($requirements as $requirement) { if (!isset($params['{{'.$requirement.'}}'])) { throw new \Exception("The parameter $requirement is needed in order to edit the .env.local file"); } } $contents = file_get_contents($distFile); $contents = str_replace(array_keys($params), array_values($params), $contents); file_put_contents($envFile, $contents); error_log("File env saved here: $envFile"); } function installTools($container, $manager, $upgrade = false) { error_log('installTools'); // Install course tools (table "tool") /** @var ToolChain $toolChain */ $toolChain = $container->get(ToolChain::class); $toolChain->createTools($manager); } /** * @param SymfonyContainer $container * @param bool $upgrade */ function installSchemas($container, $upgrade = false) { error_log('installSchemas'); $settingsManager = $container->get('chamilo.settings.manager'); $urlRepo = $container->get(AccessUrlRepository::class); $accessUrl = $urlRepo->find(1); if (null === $accessUrl) { $em = Database::getManager(); // Creating AccessUrl. $accessUrl = new AccessUrl(); $accessUrl ->setUrl(AccessUrl::DEFAULT_ACCESS_URL) ->setDescription('') ->setActive(1) ->setCreatedBy(1) ; $em->persist($accessUrl); $em->flush(); error_log('AccessUrl created'); } if ($upgrade) { error_log('Upgrade settings'); $settingsManager->updateSchemas($accessUrl); } else { error_log('Install settings'); // Installing schemas (filling settings_current table) $settingsManager->installSchemas($accessUrl); } } /** * @param SymfonyContainer $container */ function upgradeWithContainer($container) { Container::setContainer($container); Container::setLegacyServices($container, false); error_log('setLegacyServices'); $manager = Database::getManager(); /** @var GroupRepository $repo */ $repo = $container->get(GroupRepository::class); $repo->createDefaultGroups(); // @todo check if adminId = 1 installTools($container, $manager, true); installSchemas($container, true); } /** * After the schema was created (table creation), the function adds * admin/platform information. * * @param \Psr\Container\ContainerInterface $container * @param string $sysPath * @param string $encryptPassForm * @param string $passForm * @param string $adminLastName * @param string $adminFirstName * @param string $loginForm * @param string $emailForm * @param string $adminPhoneForm * @param string $languageForm * @param string $institutionForm * @param string $institutionUrlForm * @param string $siteName * @param string $allowSelfReg * @param string $allowSelfRegProf * @param string $installationProfile Installation profile, if any was provided */ function finishInstallationWithContainer( $container, $sysPath, $encryptPassForm, $passForm, $adminLastName, $adminFirstName, $loginForm, $emailForm, $adminPhoneForm, $languageForm, $institutionForm, $institutionUrlForm, $siteName, $allowSelfReg, $allowSelfRegProf, $installationProfile = '' ) { error_log('finishInstallationWithContainer'); Container::setContainer($container); Container::setLegacyServices($container, false); error_log('setLegacyServices'); //UserManager::setPasswordEncryption($encryptPassForm); $timezone = api_get_timezone(); error_log('user creation - admin'); $repo = Container::getUserRepository(); /** @var User $admin */ $admin = $repo->findOneBy(['username' => 'admin']); $admin ->setLastname($adminLastName) ->setFirstname($adminFirstName) ->setUsername($loginForm) ->setStatus(1) ->setPlainPassword($passForm) ->setEmail($emailForm) ->setOfficialCode('ADMIN') ->setAuthSource(PLATFORM_AUTH_SOURCE) ->setPhone($adminPhoneForm) ->setLocale($languageForm) ->setTimezone($timezone) ; $repo->updateUser($admin); $repo = Container::getUserRepository(); $repo->updateUser($admin); // Set default language Database::update( Database::get_main_table(TABLE_MAIN_LANGUAGE), ['available' => 1], ['english_name = ?' => $languageForm] ); // Install settings installSettings( $institutionForm, $institutionUrlForm, $siteName, $emailForm, $adminLastName, $adminFirstName, $languageForm, $allowSelfReg, $allowSelfRegProf, $installationProfile ); lockSettings(); updateDirAndFilesPermissions(); } /** * Update settings based on installation profile defined in a JSON file. * * @param string $installationProfile The name of the JSON file in main/install/profiles/ folder * * @return bool false on failure (no bad consequences anyway, just ignoring profile) */ function installProfileSettings($installationProfile = '') { error_log('installProfileSettings'); if (empty($installationProfile)) { return false; } $jsonPath = api_get_path(SYS_PATH).'main/install/profiles/'.$installationProfile.'.json'; // Make sure the path to the profile is not hacked if (!Security::check_abs_path($jsonPath, api_get_path(SYS_PATH).'main/install/profiles/')) { return false; } if (!is_file($jsonPath)) { return false; } if (!is_readable($jsonPath)) { return false; } if (!function_exists('json_decode')) { // The php-json extension is not available. Ignore profile. return false; } $json = file_get_contents($jsonPath); $params = json_decode($json); if (false === $params or null === $params) { return false; } $settings = $params->params; if (!empty($params->parent)) { installProfileSettings($params->parent); } $tblSettings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT); foreach ($settings as $id => $param) { $conditions = ['variable = ? ' => $param->variable]; if (!empty($param->subkey)) { $conditions['AND subkey = ? '] = $param->subkey; } Database::update( $tblSettings, ['selected_value' => $param->selected_value], $conditions ); } return true; } /** * Quick function to remove a directory with its subdirectories. * * @param $dir */ function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ('.' != $object && '..' != $object) { if ('dir' == filetype($dir.'/'.$object)) { @rrmdir($dir.'/'.$object); } else { @unlink($dir.'/'.$object); } } } reset($objects); rmdir($dir); } } /** * Control the different steps of the migration through a big switch. * * @param string $fromVersion * @param EntityManager $manager * @param bool $processFiles * * @return bool Always returns true except if the process is broken */ function migrateSwitch($fromVersion, $manager, $processFiles = true) { error_log('-----------------------------------------'); error_log('Starting migration process from '.$fromVersion.' ('.date('Y-m-d H:i:s').')'); //echo ''.get_lang('Details').'
    '; //echo ''; return true; } /** * @return string */ function generateRandomToken() { return hash('sha1', uniqid(mt_rand(), true)); } /** * This function checks if the given file can be created or overwritten. * * @param string $file Full path to a file * * @return string An HTML coloured label showing success or failure */ function checkCanCreateFile($file) { if (file_exists($file)) { if (is_writable($file)) { return Display::label(get_lang('Writable'), 'success'); } else { return Display::label(get_lang('Not writable'), 'important'); } } else { $write = @file_put_contents($file, ''); if (false !== $write) { unlink($file); return Display::label(get_lang('Writable'), 'success'); } else { return Display::label(get_lang('Not writable'), 'important'); } } }