Browse Source

Remove unused classes

jmontoya 9 years ago
parent
commit
b2614991e7

+ 0 - 8
main/auth/key/index.php

@@ -1,8 +0,0 @@
-<?php
-/**
- * Display nothing. This ensure Apache doesn't display the list of files and folders
- * when it is not propertly configured.
- *
- * @license see /license.txt
- * @author Laurent Opprecht <laurent@opprecht.info>, Nicolas Rod for the University of Geneva
- */

+ 0 - 262
main/auth/key/key_auth.class.php

@@ -1,262 +0,0 @@
-<?php
-
-use ChamiloSession as Session;
-
-/**
- * Used to authenticate user with an access token. By default this method is disabled.
- * Method used primarily to make API calls: Rss, file upload.
- *
- * Access is granted only for the services that are enabled.
- *
- * To be secured this method must
- *
- *      1) be called through httpS to avoid sniffing (note that this is the case anyway with other methods such as cookies)
- *      2) the url/access token must be secured
- *
- * This authentication method is session less. This is to ensure that the navigator
- * do not receive an access cookie that will grant it access to other parts of the
- * application.
- *
- *
- * Usage:
- *
- * Enable KeyAuth for a specific service. Add the following lines so that
- * the key authentication method is enabled for a specific service before
- * calling global.inc.php.
- *
- *      include_once '.../main/inc/autoload.inc.php';
- *      KeyAuth::enable_services('my_service');
- *      include_once '.../main/inc/global.inc.php';
- *
- *
- * Enable url access for a short period of time:
- *
- *      token = KeyAuth::create_temp_token();
- *      url = '...?access_token=' . $token ;
- *
- * @see AccessToken
- * @license see /license.txt
- * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
- */
-class KeyAuth
-{
-
-    const PARAM_ACCESS_TOKEN = 'access_token';
-
-    protected static $services = array();
-
-    public static function create_temp_token($service = null, $duration = 60, $user_id = null)
-    {
-        return UserApiKeyManager::create_temp_token($service, $duration, $user_id);
-    }
-
-    /**
-     * Returns enabled services
-     *
-     * @return array
-     */
-    public static function get_services()
-    {
-        return self::$services;
-    }
-
-    /**
-     * Name of the service for which we are goint to check the API Key.
-     * If empty it disables authentication.
-     *
-     * !! 10 chars max !!
-     */
-    public static function enable_services($_)
-    {
-        $args = func_get_args();
-        $names = array();
-        foreach ($args as $arg) {
-            if (is_object($arg)) {
-                $f = array($arg, 'get_service_name');
-                $name = call_user_func($f);
-            } else {
-                $name = $arg;
-            }
-            $name = substr($name, 0, 10);
-            self::$services[$name] = $name;
-        }
-    }
-
-    public static function disable_services($_)
-    {
-        $args = func_get_args();
-        $names = array();
-        foreach ($args as $name) {
-            $name = substr($name, 0, 10);
-            unset(self::$services[$name]);
-        }
-    }
-
-    public static function is_service_enabled($service)
-    {
-        $services = self::get_services();
-        foreach ($services as $s) {
-            if ($s == $service) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    public static function clear_services()
-    {
-        self::$services[$name] = array();
-    }
-
-    /**
-     * Enable key authentication for the default service - i.e. chamilo
-     */
-    public static function enable()
-    {
-        self::enable_services(UserApiKeyManager::default_service());
-    }
-
-    public static function disable()
-    {
-        self::$services[$name] = array();
-    }
-
-    /**
-     * Returns true if the key authentication method is enabled. False otherwise.
-     * Default to false.
-     *
-     * @return bool
-     */
-    public static function is_enabled()
-    {
-        return !empty(self::$services);
-    }
-
-    /**
-     * @return KeyAuth
-     */
-    public static function instance()
-    {
-        static $result = null;
-        if (empty($result)) {
-            $result = new self();
-        }
-        return $result;
-    }
-
-    protected function __construct()
-    {
-
-    }
-
-    /**
-     * Returns true if authentication accepts to run otherwise returns false.
-     *
-     * @return boolean
-     */
-    public function accept()
-    {
-        /**
-         * Authentication method must be enabled
-         */
-        if (!self::is_enabled()) {
-            return false;
-        }
-
-        $token = $this->get_access_token();
-        if ($token->is_empty()) {
-            return false;
-        }
-
-        $key = UserApiKeyManager::get_by_id($token->get_id());
-        if (empty($key)) {
-            return false;
-        }
-
-        /**
-         * The service corresponding to the key must be enabled.
-         */
-        $service = $key['api_service'];
-        if (!self::is_service_enabled($service)) {
-            return false;
-        }
-
-        /**
-         * User associated with the key must be active
-         */
-        $user = api_get_user_info($token->get_user_id());
-        if (empty($user)) {
-            return false;
-        }
-        if (!$user['active']) {
-            return false;
-        }
-
-        /**
-         * Token must be valid.
-         */
-        return $token->is_valid();
-    }
-
-    /**
-     * If accepted tear down session, log in user and returns true.
-     * If not accepted do nothing and returns false.
-     *
-     * @return boolean
-     */
-    public function login()
-    {
-        if (!$this->accept()) {
-            return false;
-        }
-        /**
-         * ! important this is to ensure we don't grant access for other parts
-         */
-        Session::destroy();
-
-        /**
-         * We don't allow redirection since access is granted only for this call
-         */
-        global $no_redirection, $noredirection;
-        $no_redirection = true;
-        $noredirection = true;
-        Session::write('noredirection', $noredirection);
-
-        $user_id = $this->get_user_id();
-        $course_code = $this->get_course_code();
-        $group_id = $this->get_group_id();
-
-        Login::init_user($user_id, true);
-        Login::init_course($course_code, true);
-        Login::init_group($group_id, true);
-
-        return true;
-    }
-
-    /**
-     * Returns the request access token
-     *
-     * @return AccessToken
-     */
-    public function get_access_token()
-    {
-        $string = Request::get(self::PARAM_ACCESS_TOKEN);
-        return AccessToken::parse($string);
-    }
-
-    public function get_user_id()
-    {
-        return $this->get_access_token()->get_user_id();
-    }
-
-    public function get_course_code()
-    {
-        return Request::get('cidReq', 0);
-    }
-
-    public function get_group_id()
-    {
-        return Request::get('gidReq', 0);
-    }
-
-}

+ 119 - 88
main/inc/lib/chamilo_session.class.php

@@ -1,5 +1,7 @@
 <?php
 
+use Chamilo\CoreBundle\Framework\Container;
+
 /**
  * Chamilo session (i.e. the session that maintains the connection open after usr login)
  *
@@ -19,131 +21,160 @@
  * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
  */
 /**
- * @todo use session symfony component
  * @todo replace all $_SESSION calls with this class.
- * @todo remove System\Session class
  * ChamiloSession class definition
  */
-class ChamiloSession extends System\Session
+class ChamiloSession implements \ArrayAccess
 {
-    const NAME = 'ch_sid';
-
     /**
-     * Generate new session instance
-     * @return ChamiloSession
+     * @param string $variable
+     * @param null $default
+     * @return mixed|null
      */
-    static function instance()
+    static function read($variable, $default = null)
     {
-        static $result = null;
+        $session = Container::getSession();
+        $result = null;
+        if (isset($session)) {
+            $result = $session->get($variable);
+        }
+
+        // Check if the value exists in the $_SESSION array
         if (empty($result)) {
-            $result = new ChamiloSession();
+            return $default;
+        } else {
+            return $result;
         }
-        return $result;
     }
 
     /**
-     * Returns the session lifetime
-     * @return int The session lifetime as defined in the config file, in seconds
+     * @param string $variable
+     * @param mixed $value
      */
-    static function session_lifetime()
+    static function write($variable, $value)
     {
-        global $_configuration;
-        return $_configuration['session_lifetime'];
+        //$_SESSION[$variable] = $value;
+        $session = Container::getSession();
+        // Writing the session in 2 instances because
+        $_SESSION[$variable] = $value;
+        $session->set($variable, $value);
     }
 
+    /**
+     * @param string $variable
+     */
+    static function erase($variable)
+    {
+        $variable = (string) $variable;
+        $session = Container::getSession();
+        $session->remove($variable);
+
+        if (isset($GLOBALS[$variable])) {
+            unset($GLOBALS[$variable]);
+        }
+        if (isset($_SESSION[$variable])) {
+            unset($_SESSION[$variable]);
+        }
+    }
 
     /**
-     * Starts the Chamilo session.
+     * Returns true if session has variable set up, false otherwise.
      *
-     * The default lifetime for session is set here. It is not possible to have it
-     * as a database setting as it is used before the database connection has been made.
-     * It is taken from the configuration file, and if it doesn't exist there, it is set
-     * to 360000 seconds
+     * @param string $variable
      *
-     * @author Olivier Brouckaert
-     * @param  string variable - the variable name to save into the session
-     * @return void
+     * @return bool
      */
-    static function start($already_installed = true)
+    static function has($variable)
     {
-        global $_configuration;
-
-        /*
-         * Prevent Session fixation bug fixes
-         * See http://support.chamilo.org/issues/3600
-         * http://php.net/manual/en/session.configuration.php
-         * @todo use session_set_cookie_params with some custom admin parameters
-         */
-
-        //session.cookie_lifetime
-        //the session ID is only accepted from a cookie
-        ini_set('session.use_only_cookies', 1);
-
-        //HTTPS only if possible
-        //ini_set('session.cookie_secure', 1);
-        //session ID in the cookie is only readable by the server
-        ini_set('session.cookie_httponly', 1);
-
-        //Use entropy file
-        //session.entropy_file
-        //ini_set('session.entropy_length', 128);
-        //Do not include the identifier in the URL, and not to read the URL for
-        // identifiers.
-        ini_set('session.use_trans_sid', 0);
-
-        session_name(self::NAME);
-        session_start();
-
-        $session = self::instance();
-
-        if ($already_installed) {
-            if (!isset($session['checkChamiloURL'])) {
-                $session['checkChamiloURL'] = api_get_path(WEB_PATH);
-            } elseif ($session['checkChamiloURL'] != api_get_path(WEB_PATH)) {
-                self::clear();
-            }
-        }
+        return isset($_SESSION[$variable]);
+    }
 
-        /*if (!$session->has('starttime') && !$session->is_expired()) {
-            $session->write('starttime', time());
-        }*/
-        // If the session time has expired, refresh the starttime value,
-        //  so we're starting to count down from a later time
-        if ( $session->has('starttime') && $session->is_expired()) {
-            $session->destroy();
-        } else {
-            //error_log('Time not expired, extend session for a bit more');
-            $session->write('starttime', time());
-        }
+    /**
+     * Clear
+     */
+    static function clear()
+    {
+        $session = Container::getSession();
+        $session->clear();
     }
 
     /**
-     * Session start time: that is the last time the user loaded a page (before this time)
-     * @return int timestamp
+     * Destroy
      */
-    function start_time()
+    static function destroy()
     {
-        return self::read('starttime');
+        $session = Container::getSession();
+        $session->invalidate();
+    }
+
+    /*
+     * ArrayAccess
+     */
+    public function offsetExists($offset)
+    {
+        return isset($_SESSION[$offset]);
     }
 
     /**
-     * Session end time: when the session expires. This is made of the last page
-     * load time + a number of seconds
-     * @return int UNIX timestamp (server's timezone)
+     * It it exists returns the value stored at the specified offset.
+     * If offset does not exists returns null. Do not trigger a warning.
+     *
+     * @param string $offset
+     * @return any
      */
-    function end_time()
+    public function offsetGet($offset)
     {
-        $start_time = $this->start_time();
-        $lifetime = self::session_lifetime();
-        return $start_time + $lifetime;
+        return self::read($offset);
+    }
+
+    public function offsetSet($offset, $value)
+    {
+        self::write($offset, $value);
+    }
+
+    public function offsetUnset($offset)
+    {
+        unset($_SESSION[$offset]);
+    }
+
+    /**
+     * @param string $name
+     */
+    public function __unset($name)
+    {
+        unset($_SESSION[$name]);
+    }
+
+    /**
+     * @param string $name
+     * @return bool
+     */
+    public function __isset($name)
+    {
+        return self::has($name);
+    }
+
+    /**
+     * It it exists returns the value stored at the specified offset.
+     * If offset does not exists returns null. Do not trigger a warning.
+     *
+     * @param string $name
+     *
+     * @return mixed
+     *
+     */
+    function __get($name)
+    {
+        return self::read($name);
     }
 
     /**
-     * Returns whether the session is expired
-     * @return bool True if the session is expired, false if it is still valid
+     *
+     * @param string $name
+     * @param mixed $value
      */
-    public function is_expired()
+    function __set($name, $value)
     {
-        return $this->end_time() < time();
+        self::write($name, $value);
     }
 }

+ 0 - 877
main/inc/lib/login.lib.php

@@ -1,877 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-use ChamiloSession as Session;
-
-use Chamilo\UserBundle\Entity\User;
-
-/**
- * Class Login
- * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
- * @author Julio Montoya <gugli100@gmail.com>
- * @package chamilo.login
- * @deprecated
- */
-class Login
-{
-    /**
-     * Get user account list
-     *
-     * @param array $user array with keys: email, password, uid, loginName
-     * @param boolean $reset
-     * @param boolean $by_username
-     * @return unknown
-     */
-    public static function get_user_account_list($user, $reset = false, $by_username = false)
-    {
-        $portal_url = api_get_path(WEB_PATH);
-
-        if (api_is_multiple_url_enabled()) {
-            $access_url_id = api_get_current_access_url_id();
-            if ($access_url_id != -1) {
-                $url = api_get_access_url($access_url_id);
-                $portal_url = $url['url'];
-            }
-        }
-
-        if ($reset) {
-            if ($by_username) {
-                $secret_word = self::get_secret_word($user['email']);
-                if ($reset) {
-                    $reset_link = $portal_url . "main/auth/lostPassword.php?reset=" . $secret_word . "&id=" . $user['uid'];
-                } else {
-                    $reset_link = get_lang('Pass') . " : $user[password]";
-                }
-                $user_account_list = get_lang('YourRegistrationData') . " : \n" . get_lang('UserName') . ' : ' . $user['loginName'] . "\n" . get_lang('ResetLink') . ' : ' . $reset_link . '';
-
-                if ($user_account_list) {
-                    $user_account_list = "\n-----------------------------------------------\n" . $user_account_list;
-                }
-            } else {
-                foreach ($user as $this_user) {
-                    $secret_word = self::get_secret_word($this_user['email']);
-                    if ($reset) {
-                        $reset_link = $portal_url . "main/auth/lostPassword.php?reset=" . $secret_word . "&id=" . $this_user['uid'];
-                    } else {
-                        $reset_link = get_lang('Pass') . " : $this_user[password]";
-                    }
-                    $user_account_list[] = get_lang('YourRegistrationData') . " : \n" . get_lang('UserName') . ' : ' . $this_user['loginName'] . "\n" . get_lang('ResetLink') . ' : ' . $reset_link . '';
-                }
-                if ($user_account_list) {
-                    $user_account_list = implode("\n-----------------------------------------------\n", $user_account_list);
-                }
-            }
-        } else {
-            if (!$by_username) {
-                $user = $user[0];
-            }
-            $reset_link = get_lang('Pass') . " : $user[password]";
-            $user_account_list = get_lang('YourRegistrationData') . " : \n" . get_lang('UserName') . ' : ' . $user['loginName'] . "\n" . $reset_link . '';
-        }
-        return $user_account_list;
-    }
-
-    /**
-     * This function sends the actual password to the user
-     *
-     * @param int $user
-     * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
-     */
-    public static function send_password_to_user($user, $by_username = false)
-    {
-        $email_subject = "[".api_get_setting(
-                'platform.site_name'
-            )."] ".get_lang('LoginRequest'); // SUBJECT
-
-        if ($by_username) { // Show only for lost password
-            $user_account_list = self::get_user_account_list($user, false, $by_username); // BODY
-            $email_to = $user['email'];
-        } else {
-            $user_account_list = self::get_user_account_list($user); // BODY
-            $email_to = $user[0]['email'];
-        }
-
-        $portal_url = api_get_path(WEB_PATH);
-        if (api_is_multiple_url_enabled()) {
-            $access_url_id = api_get_current_access_url_id();
-            if ($access_url_id != -1) {
-                $url = api_get_access_url($access_url_id);
-                $portal_url = $url['url'];
-            }
-        }
-
-        $email_body = get_lang('YourAccountParam') . " " . $portal_url . "\n\n$user_account_list";
-        // SEND MESSAGE
-        $sender_name = api_get_person_name(
-            api_get_setting('admin.administrator_name'),
-            api_get_setting('admin.administrator_surname'),
-            null,
-            PERSON_NAME_EMAIL_ADDRESS
-        );
-        $email_admin = api_get_setting('admin.administrator_email');
-
-        if (api_mail_html('', $email_to, $email_subject, $email_body, $sender_name, $email_admin) == 1) {
-
-            return get_lang('YourPasswordHasBeenReset');
-        } else {
-            $admin_email = Display:: encrypted_mailto_link(
-                api_get_setting('admin.administrator_email'),
-                api_get_person_name(
-                    api_get_setting('admin.administrator_name'),
-                    api_get_setting('admin.administrator_surname')
-                )
-            );
-
-            return sprintf(
-                get_lang('ThisPlatformWasUnableToSendTheEmailPleaseContactXForMoreInformation'),
-                $admin_email
-            );
-        }
-    }
-
-    /**
-     * Handle encrypted password, send an email to a user with his password
-     *
-     * @param int	user id
-     * @param bool	$by_username
-     *
-     * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
-     */
-    public static function handle_encrypted_password($user, $by_username = false)
-    {
-        $email_subject = "[".api_get_setting(
-                'platform.site_name'
-            )."] ".get_lang('LoginRequest'); // SUBJECT
-
-        if ($by_username) {
-        // Show only for lost password
-            $user_account_list = self::get_user_account_list($user, true, $by_username); // BODY
-            $email_to = $user['email'];
-        } else {
-            $user_account_list = self::get_user_account_list($user, true); // BODY
-            $email_to = $user[0]['email'];
-        }
-        $email_body = get_lang('DearUser') . " :\n" . get_lang('password_request') . "\n";
-        $email_body .= $user_account_list . "\n-----------------------------------------------\n\n";
-        $email_body .= get_lang('PasswordEncryptedForSecurity');
-
-        $email_body .= "\n\n".get_lang(
-                'SignatureFormula'
-            ).",\n".api_get_setting(
-                'admin.administrator_name'
-            )." ".api_get_setting(
-                'administratorSurname'
-            )."\n".get_lang('PlataformAdmin')." - ".api_get_setting(
-                'platform.site_name'
-            );
-
-        $sender_name = api_get_person_name(
-            api_get_setting('admin.administrator_name'),
-            api_get_setting('admin.administrator_surname'),
-            null,
-            PERSON_NAME_EMAIL_ADDRESS
-        );
-        $email_admin = api_get_setting('admin.administrator_email');
-
-        $result = @api_mail_html(
-            '',
-            $email_to,
-            $email_subject,
-            $email_body,
-            $sender_name,
-            $email_admin
-        );
-
-        if ($result == 1) {
-            return get_lang('YourPasswordHasBeenEmailed');
-        } else {
-            $admin_email = Display:: encrypted_mailto_link(
-                api_get_setting('admin.administrator_email'),
-                api_get_person_name(
-                    api_get_setting('admin.administrator_name'),
-                    api_get_setting('admin.administrator_surname')
-                )
-            );
-            $message = sprintf(get_lang('ThisPlatformWasUnableToSendTheEmailPleaseContactXForMoreInformation'), $admin_email);
-
-            return $message;
-        }
-    }
-
-    /**
-     * @param User $user
-     */
-    public static function sendResetEmail(User $user)
-    {
-        //if (null === $user->getConfirmationToken()) {
-            $uniqueId = api_get_unique_id();
-            $user->setConfirmationToken($uniqueId);
-            $user->setPasswordRequestedAt(new \DateTime());
-
-            Database::getManager()->persist($user);
-            Database::getManager()->flush();
-
-            $url = api_get_path(WEB_CODE_PATH).'auth/reset.php?token='.$uniqueId;
-
-            $mailTemplate = new Template(null, false, false, false, false, false);
-            $mailTemplate->assign('complete_user_name', $user->getCompleteName());
-            $mailTemplate->assign('link', $url);
-
-            $mailLayout = $mailTemplate->get_template('mail/reset_password.tpl');
-
-            $mailSubject = get_lang('ResetPasswordInstructions');
-            $mailBody = $mailTemplate->fetch($mailLayout);
-
-            api_mail_html(
-                $user->getCompleteName(),
-                $user->getEmail(),
-                $mailSubject,
-                $mailBody
-            );
-            Display::addFlash(Display::return_message(get_lang('CheckYourEmailAndFollowInstructions')));
-        //}
-    }
-
-    /**
-     * Gets the secret word
-     * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
-     */
-    public static function get_secret_word($add)
-    {
-        return $secret_word = sha1($add);
-    }
-
-    /**
-     * Resets a password
-     * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
-     */
-    public static function reset_password($secret, $id, $by_username = false)
-    {
-        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-        $id = intval($id);
-        $sql = "SELECT
-                    user_id AS uid,
-                    lastname AS lastName,
-                    firstname AS firstName,
-                    username AS loginName,
-                    password,
-                    email
-                FROM " . $tbl_user . "
-                WHERE user_id = $id";
-        $result = Database::query($sql);
-        $num_rows = Database::num_rows($result);
-
-        if ($result && $num_rows > 0) {
-            $user = Database::fetch_array($result);
-        } else {
-            return get_lang('CouldNotResetPassword');
-        }
-
-        if (self::get_secret_word($user['email']) == $secret) {
-            // OK, secret word is good. Now change password and mail it.
-            $user['password'] = api_generate_password();
-
-            UserManager::updatePassword($id, $user['password']);
-
-            return self::send_password_to_user($user, $by_username);
-        } else {
-            return get_lang('NotAllowed');
-        }
-    }
-
-    /**
-     *
-     * @global bool   $is_platformAdmin
-     * @global bool   $is_allowedCreateCourse
-     * @global object $_user
-     */
-    public static function init_user($user_id, $reset)
-    {
-        global $is_platformAdmin;
-        global $is_allowedCreateCourse;
-        global $_user;
-
-        if (isset($reset) && $reset) {    // session data refresh requested
-            unset($_SESSION['_user']['uidReset']);
-            $is_platformAdmin = false;
-            $is_allowedCreateCourse = false;
-            $_user['user_id'] = $user_id;
-
-            if (isset($_user['user_id']) && $_user['user_id'] && !api_is_anonymous()) {
-                // a uid is given (log in succeeded)
-                $user_table = Database::get_main_table(TABLE_MAIN_USER);
-                $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
-                $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-
-                $sql = "SELECT user.*, a.user_id is_admin, UNIX_TIMESTAMP(login.login_date) login_date
-                        FROM $user_table
-                        LEFT JOIN $admin_table a
-                        ON user.user_id = a.user_id
-                        LEFT JOIN $track_e_login login
-                        ON user.user_id  = login.login_user_id
-                        WHERE user.user_id = '" . $_user['user_id'] . "'
-                        ORDER BY login.login_date DESC LIMIT 1";
-
-                $result = Database::query($sql);
-
-                if (Database::num_rows($result) > 0) {
-                    // Extracting the user data
-
-                    $uData = Database::fetch_array($result);
-
-                    $_user['firstName'] = $uData['firstname'];
-                    $_user['lastName'] = $uData['lastname'];
-                    $_user['mail'] = $uData['email'];
-                    $_user['official_code'] = $uData['official_code'];
-                    $_user['picture_uri'] = $uData['picture_uri'];
-                    $_user['user_id'] = $uData['user_id'];
-                    $_user['language'] = $uData['language'];
-                    $_user['auth_source'] = $uData['auth_source'];
-                    $_user['theme'] = $uData['theme'];
-                    $_user['status'] = $uData['status'];
-
-                    $is_platformAdmin = (bool) (!is_null($uData['is_admin']));
-                    $is_allowedCreateCourse = (bool) (($uData ['status'] == 1) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == 4));
-                    ConditionalLogin::check_conditions($uData);
-
-                    Session::write('_user', $_user);
-                    UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
-                    Session::write('is_platformAdmin', $is_platformAdmin);
-                    Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
-                } else {
-                    header('location:' . api_get_path(WEB_PATH));
-                    //exit("WARNING UNDEFINED UID !! ");
-                }
-            } else { // no uid => logout or Anonymous
-                Session::erase('_user');
-                Session::erase('_uid');
-            }
-
-            Session::write('is_platformAdmin', $is_platformAdmin);
-            Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
-        } else { // continue with the previous values
-            $_user = $_SESSION['_user'];
-            $is_platformAdmin = $_SESSION['is_platformAdmin'];
-            $is_allowedCreateCourse = $_SESSION['is_allowedCreateCourse'];
-        }
-    }
-
-    /**
-     *
-     * @global bool $is_platformAdmin
-     * @global bool $is_allowedCreateCourse
-     * @global object $_user
-     * @global int $_cid
-     * @global array $_course
-     * @global int $_real_cid
-     * @global type $_courseUser
-     * @global type $is_courseAdmin
-     * @global type $is_courseTutor
-     * @global type $is_courseCoach
-     * @global type $is_courseMember
-     * @global type $is_sessionAdmin
-     * @global type $is_allowed_in_course
-     *
-     * @param type $course_id
-     * @param type $reset
-     */
-    static function init_course($course_id, $reset)
-    {
-        global $_configuration;
-        global $is_platformAdmin;
-        global $is_allowedCreateCourse;
-        global $_user;
-
-        global $_cid;
-        global $_course;
-        global $_real_cid;
-
-        global $is_courseAdmin;  //course teacher
-        global $is_courseTutor;  //course teacher - some rights
-        global $is_courseCoach;  //course coach
-        global $is_courseMember; //course student
-        global $is_sessionAdmin;
-        global $is_allowed_in_course;
-
-        if ($reset) {
-            // Course session data refresh requested or empty data
-            if ($course_id) {
-                $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
-                $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
-                $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
-                        FROM $course_table
-                        LEFT JOIN $course_cat_table
-                        ON course.category_code = course_category.code
-                        WHERE course.code = '$course_id'";
-                $result = Database::query($sql);
-
-                if (Database::num_rows($result) > 0) {
-                    $course_data = Database::fetch_array($result);
-                    //@TODO real_cid should be cid, for working with numeric course id
-                    $_real_cid = $course_data['id'];
-
-                    $_cid = $course_data['code'];
-                    $_course = array();
-                    $_course['real_id'] = $course_data['id'];
-                    $_course['id'] = $course_data['code']; //auto-assigned integer
-                    $_course['code'] = $course_data['code'];
-                    $_course['name'] = $course_data['title'];
-                    $_course['title'] = $course_data['title'];
-                    $_course['official_code'] = $course_data['visual_code']; // use in echo
-                    $_course['sysCode'] = $course_data['code']; // use as key in db
-                    $_course['path'] = $course_data['directory']; // use as key in path
-                    $_course['titular'] = $course_data['tutor_name']; // this should be deprecated and use the table course_rel_user
-                    $_course['language'] = $course_data['course_language'];
-                    $_course['extLink']['url'] = $course_data['department_url'];
-                    $_course['extLink']['name'] = $course_data['department_name'];
-                    $_course['categoryCode'] = $course_data['faCode'];
-                    $_course['categoryName'] = $course_data['faName'];
-                    $_course['visibility'] = $course_data['visibility'];
-                    $_course['subscribe_allowed'] = $course_data['subscribe'];
-                    $_course['unsubscribe'] = $course_data['unsubscribe'];
-                    $_course['activate_legal'] = $course_data['activate_legal'];
-                    $_course['show_score'] = $course_data['show_score']; //used in the work tool
-
-                    Session::write('_cid', $_cid);
-                    Session::write('_course', $_course);
-
-                    //@TODO real_cid should be cid, for working with numeric course id
-                    Session::write('_real_cid', $_real_cid);
-
-                    // if a session id has been given in url, we store the session
-
-                    // Database Table Definitions
-                    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
-
-                    if (!empty($_GET['id_session'])) {
-                        $_SESSION['id_session'] = intval($_GET['id_session']);
-                        $sql = 'SELECT name FROM ' . $tbl_session . ' WHERE id="' . intval($_SESSION['id_session']) . '"';
-                        $rs = Database::query($sql);
-                        list($_SESSION['session_name']) = Database::fetch_array($rs);
-                    } else {
-                        Session::erase('session_name');
-                        Session::erase('id_session');
-                    }
-
-                    if (!isset($_SESSION['login_as'])) {
-                        //Course login
-                        if (isset($_user['user_id'])) {
-                            Event::event_course_login(api_get_course_int_id(), $_user['user_id'], api_get_session_id());
-                        }
-                    }
-                } else {
-                    //exit("WARNING UNDEFINED CID !! ");
-                    header('location:' . api_get_path(WEB_PATH));
-                }
-            } else {
-                Session::erase('_cid');
-                Session::erase('_real_cid');
-                Session::erase('_course');
-
-                if (!empty($_SESSION)) {
-                    foreach ($_SESSION as $key => $session_item) {
-                        if (strpos($key, 'lp_autolaunch_') === false) {
-                            continue;
-                        } else {
-                            if (isset($_SESSION[$key])) {
-                                Session::erase($key);
-                            }
-                        }
-                    }
-                }
-                //Deleting session info
-                if (api_get_session_id()) {
-                    Session::erase('id_session');
-                    Session::erase('session_name');
-                }
-            }
-        } else {
-            // Continue with the previous values
-            if (empty($_SESSION['_course']) OR empty($_SESSION['_cid'])) { //no previous values...
-                $_cid = -1;        //set default values that will be caracteristic of being unset
-                $_course = -1;
-            } else {
-                $_cid = $_SESSION['_cid'];
-                $_course = $_SESSION['_course'];
-
-                // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
-                // Moreover, if we want to track a course with another session it can be usefull
-                if (!empty($_GET['id_session'])) {
-                    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
-                    $sql = 'SELECT name FROM ' . $tbl_session . ' WHERE id="' . intval($_SESSION['id_session']) . '"';
-                    $rs = Database::query($sql);
-                    list($_SESSION['session_name']) = Database::fetch_array($rs);
-                    $_SESSION['id_session'] = intval($_GET['id_session']);
-                }
-
-                if (!isset($_SESSION['login_as'])) {
-                    $save_course_access = true;
-
-                    //The value  $_dont_save_user_course_access should be added before the call of global.inc.php see the main/inc/chat.ajax.php file
-                    //Disables the updates in the TRACK_E_COURSE_ACCESS table
-                    if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
-                        $save_course_access = false;
-                    }
-
-                    if ($save_course_access) {
-                        $course_tracking_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
-
-                        /*
-                         * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
-                         * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
-                         * login_course_date > now() - INTERVAL $session_lifetime SECOND
-                         *
-                         */
-                        /*
-                          if (isset($_configuration['session_lifetime'])) {
-                          $session_lifetime    = $_configuration['session_lifetime'];
-                          } else {
-                          $session_lifetime    = 3600; // 1 hour
-                          } */
-
-                        $session_lifetime = 3600; // 1 hour
-                        $time = api_get_utc_datetime();
-
-                        if (isset($_user['user_id']) && !empty($_user['user_id'])) {
-
-                            //We select the last record for the current course in the course tracking table
-                            //But only if the login date is < than now + max_life_time
-                            $sql = "SELECT course_access_id FROM $course_tracking_table
-                                    WHERE
-                                        user_id     = " . intval($_user ['user_id']) . " AND
-                                        c_id = '".api_get_course_int_id()."' AND
-                                        session_id  = " . api_get_session_id() . " AND
-                                        login_course_date > now() - INTERVAL $session_lifetime SECOND
-                                    ORDER BY login_course_date DESC LIMIT 0,1";
-                            $result = Database::query($sql);
-
-                            if (Database::num_rows($result) > 0) {
-                                $i_course_access_id = Database::result($result, 0, 0);
-                                //We update the course tracking table
-                                $sql = "UPDATE $course_tracking_table
-                                        SET logout_course_date = '$time', counter = counter+1
-                                        WHERE course_access_id = " . intval($i_course_access_id) . " AND session_id = " . api_get_session_id();
-                                Database::query($sql);
-                            } else {
-                                $sql = "INSERT INTO $course_tracking_table (c_id, user_id, login_course_date, logout_course_date, counter, session_id)" .
-                                        "VALUES('" . api_get_course_int_id() . "', '" . $_user['user_id'] . "', '$time', '$time', '1','" . api_get_session_id() . "')";
-                                Database::query($sql);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        /*  COURSE / USER REL. INIT */
-
-        $session_id = api_get_session_id();
-        $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
-
-        //Course permissions
-        $is_courseAdmin = false; //course teacher
-        $is_courseTutor = false; //course teacher - some rights
-        $is_courseMember = false; //course student
-        //Course - User permissions
-        $is_sessionAdmin = false;
-
-        if ($reset) {
-
-            if (isset($user_id) && $user_id && isset($_cid) && $_cid) {
-
-                //Check if user is subscribed in a course
-                $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-                $sql = "SELECT * FROM $course_user_table
-                       WHERE
-                        user_id  = '" . $user_id . "' AND
-                        relation_type <> " . COURSE_RELATION_TYPE_RRHH . " AND
-                        course_code = '$course_id'";
-                $result = Database::query($sql);
-
-                $cuData = null;
-                if (Database::num_rows($result) > 0) {
-                    // this  user have a recorded state for this course
-                    $cuData = Database::fetch_array($result, 'ASSOC');
-                    $is_courseAdmin = (bool) $cuData['status'] == 1;
-                    $is_courseTutor = (bool) $cuData['is_tutor'] == 1;
-                    $is_courseMember = true;
-
-                    // Checking if the user filled the course legal agreement
-                    if ($_course['activate_legal'] == 1 && !api_is_platform_admin()) {
-                        $user_is_subscribed = CourseManager::is_user_accepted_legal(
-                            $user_id,
-                            $_course['id'],
-                            $session_id
-                        );
-                        if (!$user_is_subscribed) {
-                            $url = api_get_path(WEB_CODE_PATH) . 'course_info/legal.php?course_code=' . $_course['code'] . '&session_id=' . $session_id;
-                            header('Location: ' . $url);
-                            exit;
-                        }
-                    }
-                }
-
-                //We are in a session course? Check session permissions
-                if (!empty($session_id)) {
-
-                    //I'm not the teacher of the course
-                    if ($is_courseAdmin == false) {
-                        // this user has no status related to this course
-                        // The user is subscribed in a session? The user is a Session coach a Session admin ?
-
-                        $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
-                        $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-                        $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-                        //Session coach, session admin, course coach admin
-                        $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id
-                                FROM $tbl_session session, $tbl_session_course_user session_rcru
-                                WHERE
-                                   session_rcru.session_id = session.id AND
-                                   session_rcru.c_id = '$_real_cid' AND
-                                   session_rcru.user_id = '$user_id' AND
-                                   session_rcru.session_id  = $session_id AND
-                                   session_rcru.status = 2";
-
-                        $result = Database::query($sql);
-                        $row = Database::store_result($result);
-
-                        //I'm a session admin?
-                        if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
-                            $is_courseMember = false;
-                            $is_courseTutor = false;
-                            $is_courseAdmin = false;
-                            $is_courseCoach = false;
-                            $is_sessionAdmin = true;
-                        } else {
-                            //Im a coach or a student?
-                            $sql = "SELECT user_id, status
-                                    FROM " . $tbl_session_course_user . "
-                                    WHERE
-                                        c_id = '$_cid' AND
-                                        user_id = '" . $user_id . "' AND
-                                        session_id = '" . $session_id . "'
-                                    LIMIT 1";
-                            $result = Database::query($sql);
-
-                            if (Database::num_rows($result)) {
-                                $row = Database::fetch_array($result, 'ASSOC');
-                                $session_course_status = $row['status'];
-
-                                switch ($session_course_status) {
-                                    case '2': // coach - teacher
-                                        $is_courseMember = true;
-                                        $is_courseTutor = true;
-                                        $is_courseCoach = true;
-                                        $is_sessionAdmin = false;
-
-                                        if (api_get_setting('extend_rights_for_coach') == 'true') {
-                                            $is_courseAdmin = true;
-                                        } else {
-                                            $is_courseAdmin = false;
-                                        }
-                                        break;
-                                    case '0': //student
-                                        $is_courseMember = true;
-                                        $is_courseTutor = false;
-                                        $is_courseAdmin = false;
-                                        $is_sessionAdmin = false;
-                                        break;
-                                    default:
-                                        //unregister user
-                                        $is_courseMember = false;
-                                        $is_courseTutor = false;
-                                        $is_courseAdmin = false;
-                                        $is_sessionAdmin = false;
-                                        break;
-                                }
-                            } else {
-                                //unregister user
-                                $is_courseMember = false;
-                                $is_courseTutor = false;
-                                $is_courseAdmin = false;
-                                $is_sessionAdmin = false;
-                            }
-                        }
-                    }
-
-                    //If I'm the admin platform i'm a teacher of the course
-                    if ($is_platformAdmin) {
-                        $is_courseAdmin = true;
-                    }
-                }
-            } else { // keys missing => not anymore in the course - user relation
-                // course
-                $is_courseMember = false;
-                $is_courseAdmin = false;
-                $is_courseTutor = false;
-                $is_courseCoach = false;
-                $is_sessionAdmin = false;
-            }
-
-            //Checking the course access
-            $is_allowed_in_course = false;
-
-            if (isset($_course)) {
-                switch ($_course['visibility']) {
-                    case COURSE_VISIBILITY_OPEN_WORLD: //3
-                        $is_allowed_in_course = true;
-                        break;
-                    case COURSE_VISIBILITY_OPEN_PLATFORM : //2
-                        if (isset($user_id) && !api_is_anonymous($user_id)) {
-                            $is_allowed_in_course = true;
-                        }
-                        break;
-                    case COURSE_VISIBILITY_REGISTERED: //1
-                        if ($is_platformAdmin || $is_courseMember) {
-                            $is_allowed_in_course = true;
-                        }
-                        break;
-                    case COURSE_VISIBILITY_CLOSED: //0
-                        if ($is_platformAdmin || $is_courseAdmin) {
-                            $is_allowed_in_course = true;
-                        }
-                        break;
-                    case COURSE_VISIBILITY_HIDDEN: //4
-                        if ($is_platformAdmin) {
-                            $is_allowed_in_course = true;
-                        }
-                        break;
-                }
-            }
-
-            // check the session visibility
-            if ($is_allowed_in_course == true) {
-                //if I'm in a session
-
-                if ($session_id != 0) {
-                    if (!$is_platformAdmin) {
-                        // admin and session coach are *not* affected to the invisible session mode
-                        // the coach is not affected because he can log in some days after the end date of a session
-                        $session_visibility = api_get_session_visibility($session_id);
-
-                        switch ($session_visibility) {
-                            case SESSION_INVISIBLE:
-                                $is_allowed_in_course = false;
-                                break;
-                        }
-                        //checking date
-                    }
-                }
-            }
-
-            // save the states
-            Session::write('is_courseAdmin', $is_courseAdmin);
-            Session::write('is_courseMember', $is_courseMember);
-            Session::write('is_courseTutor', $is_courseTutor);
-            Session::write('is_courseCoach', $is_courseCoach);
-            Session::write('is_allowed_in_course', $is_allowed_in_course);
-
-            Session::write('is_sessionAdmin', $is_sessionAdmin);
-        } else {
-            // continue with the previous values
-            $is_courseAdmin = $_SESSION['is_courseAdmin'];
-            $is_courseTutor = $_SESSION['is_courseTutor'];
-            $is_courseCoach = $_SESSION['is_courseCoach'];
-            $is_courseMember = $_SESSION['is_courseMember'];
-            $is_allowed_in_course = $_SESSION['is_allowed_in_course'];
-        }
-    }
-
-    /**
-     *
-     * @global int $_cid
-     * @global array $_course
-     * @global int $_gid
-     *
-     * @param int $group_id
-     * @param bool $reset
-     */
-    static function init_group($group_id, $reset)
-    {
-        global $_cid;
-        global $_course;
-        global $_gid;
-
-        if ($reset) { // session data refresh requested
-            if ($group_id && $_cid && !empty($_course['real_id'])) { // have keys to search data
-                $group_table = Database::get_course_table(TABLE_GROUP);
-                $sql = "SELECT * FROM $group_table WHERE c_id = " . $_course['real_id'] . " AND id = '$group_id'";
-                $result = Database::query($sql);
-                if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
-                    $gpData = Database::fetch_array($result);
-                    $_gid = $gpData ['id'];
-                    Session::write('_gid', $_gid);
-                } else {
-                    Session::erase('_gid');
-                }
-            } elseif (isset($_SESSION['_gid']) or isset($_gid)) { // Keys missing => not anymore in the group - course relation
-                Session::erase('_gid');
-            }
-        } elseif (isset($_SESSION['_gid'])) { // continue with the previous values
-            $_gid = $_SESSION ['_gid'];
-        } else { //if no previous value, assign caracteristic undefined value
-            $_gid = -1;
-        }
-
-        //set variable according to student_view_enabled choices
-        if (api_get_setting('course.student_view_enabled') == "true") {
-            if (isset($_GET['isStudentView'])) {
-                if ($_GET['isStudentView'] == 'true') {
-                    if (isset($_SESSION['studentview'])) {
-                        if (!empty($_SESSION['studentview'])) {
-                            // switching to studentview
-                            $_SESSION['studentview'] = 'studentview';
-                        }
-                    }
-                } elseif ($_GET['isStudentView'] == 'false') {
-                    if (isset($_SESSION['studentview'])) {
-                        if (!empty($_SESSION['studentview'])) {
-                            // switching to teacherview
-                            $_SESSION['studentview'] = 'teacherview';
-                        }
-                    }
-                }
-            } elseif (!empty($_SESSION['studentview'])) {
-                //all is fine, no change to that, obviously
-            } elseif (empty($_SESSION['studentview'])) {
-                // We are in teacherview here
-                $_SESSION['studentview'] = 'teacherview';
-            }
-        }
-    }
-
-    /**
-     * Returns true if user exists in the platform when asking the password
-     *
-     * @param string $username (email or username)
-     * @return array|boolean
-     */
-    public static function get_user_accounts_by_username($username)
-    {
-        if (strpos($username,'@')){
-            $username = api_strtolower($username);
-            $email = true;
-        } else {
-            $username = api_strtolower($username);
-            $email = false;
-        }
-
-		if ($email) {
-			$condition = "LOWER(email) = '".Database::escape_string($username)."' ";
-		} else {
-            $condition = "LOWER(username) = '".Database::escape_string($username)."'";
-        }
-
-		$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-		$query = "SELECT user_id AS uid, lastname AS lastName, firstname AS firstName, username AS loginName, password, email,
-                         status AS status, official_code, phone, picture_uri, creator_id
-				 FROM $tbl_user
-				 WHERE ( $condition AND active = 1) ";
-		$result = Database::query($query);
-        $num_rows = Database::num_rows($result);
-        if ($result && $num_rows > 0) {
-            return Database::fetch_assoc($result);
-        }
-        return false;
-    }
-}

+ 0 - 166
main/inc/lib/system/session.class.php

@@ -1,166 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-namespace System;
-
-use Chamilo\CoreBundle\Framework\Container;
-
-/**
- * Session Management
- *
- * @see ChamiloSession
- *
- * @license see /license.txt
- * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
- */
-class Session implements \ArrayAccess
-{
-    /**
-     * @param string $variable
-     * @param null $default
-     * @return mixed|null
-     */
-    static function read($variable, $default = null)
-    {
-        $session = Container::getSession();
-        $result = null;
-        if (isset($session)) {
-            $result = $session->get($variable);
-        }
-
-        // Check if the value exists in the $_SESSION array
-        if (empty($result)) {
-            return $default;
-        } else {
-            return $result;
-        }
-    }
-
-    /**
-     * @param string $variable
-     * @param mixed $value
-     */
-    static function write($variable, $value)
-    {
-        //$_SESSION[$variable] = $value;
-        $session = Container::getSession();
-        // Writing the session in 2 instances because
-        $_SESSION[$variable] = $value;
-        $session->set($variable, $value);
-    }
-
-    /**
-     * @param string $variable
-     */
-    static function erase($variable)
-    {
-        $variable = (string) $variable;
-        $session = Container::getSession();
-        $session->remove($variable);
-
-        if (isset($GLOBALS[$variable])) {
-            unset($GLOBALS[$variable]);
-        }
-        if (isset($_SESSION[$variable])) {
-            unset($_SESSION[$variable]);
-        }
-    }
-
-    /**
-     * Returns true if session has variable set up, false otherwise.
-     *
-     * @param string $variable
-     *
-     * @return bool
-     */
-    static function has($variable)
-    {
-        return isset($_SESSION[$variable]);
-    }
-
-    /**
-     * Clear
-     */
-    static function clear()
-    {
-        $session = Container::getSession();
-        $session->clear();
-    }
-
-    /**
-     * Destroy
-     */
-    static function destroy()
-    {
-        $session = Container::getSession();
-        $session->invalidate();
-    }
-
-    /*
-     * ArrayAccess
-     */
-    public function offsetExists($offset)
-    {
-        return isset($_SESSION[$offset]);
-    }
-
-    /**
-     * It it exists returns the value stored at the specified offset.
-     * If offset does not exists returns null. Do not trigger a warning.
-     *
-     * @param string $offset
-     * @return any
-     */
-    public function offsetGet($offset)
-    {
-        return self::read($offset);
-    }
-
-    public function offsetSet($offset, $value)
-    {
-        self::write($offset, $value);
-    }
-
-    public function offsetUnset($offset)
-    {
-        unset($_SESSION[$offset]);
-    }
-
-    /**
-     * Magical methods
-     *
-     */
-
-    public function __unset($name)
-    {
-        unset($_SESSION[$name]);
-    }
-
-    public function __isset($name)
-    {
-        return self::has($name);
-    }
-
-    /**
-     * It it exists returns the value stored at the specified offset.
-     * If offset does not exists returns null. Do not trigger a warning.
-     *
-     * @param string $name
-     * @return any
-     *
-     */
-    function __get($name)
-    {
-        return self::read($name);
-    }
-
-    /**
-     *
-     * @param string $name
-     * @param any $value
-     */
-    function __set($name, $value)
-    {
-        self::write($name, $value);
-    }
-}

+ 0 - 61
main/inc/lib/system/web/request.class.php

@@ -1,61 +0,0 @@
-<?php
-
-/**
- * Provides access to various HTTP request elements: GET, POST, FILE, etc paramaters.
-
- * @license see /license.txt
- * @deprecated
- * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
- */
-class Request
-{
-
-    public static function get($key, $default = null)
-    {
-        return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
-    }
-
-    public static function has($key){
-        return isset($_REQUEST[$key]);
-    }
-
-    /**
-     * Returns true if the request is a GET request. False otherwise.
-     *
-     * @return bool
-     */
-    public static function is_get()
-    {
-        $method = self::server()->request_method();
-        $method = strtoupper($method);
-        return $method == 'GET';
-    }
-
-    public static function post($key, $default = null)
-    {
-        return isset($_POST[$key]) ? $_POST[$key] : $default;
-    }
-
-    /**
-     * Returns true if the request is a POST request. False otherwise.
-     *
-     * @return bool
-     */
-    public static function is_post()
-    {
-        $method = self::server()->request_method();
-        $method = strtoupper($method);
-        return $method == 'POST';
-    }
-
-    static function file($key, $default = null)
-    {
-        return isset($_FILES[$key]) ? $_FILES[$key] : $default;
-    }
-
-    static function environment($key, $default = null)
-    {
-        return isset($_ENV[$key]) ? $_ENV[$key] : $default;
-    }
-
-}

+ 0 - 1399
main/inc/local.inc.php

@@ -1,1399 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- *
- *                             SCRIPT PURPOSE
- *
- * This script initializes and manages Chamilo session information. It
- * keeps available session information up to date.
- *
- * You can request a course id. It will check if the course Id requested is the
- * same as the current one. If it isn't it will update session information from
- * the database. You can also force the course reset if you want ($cidReset).
- *
- * All the course information is stored in the $_course array.
- *
- * You can request a group id. The script will check if the group id requested is the
- * same as the current one. If it isn't it will update session information from
- * the database. You can also force the course reset if you want ($gidReset).
- *
- * The course id is stored in $_cid session variable.
- * The group  id is stored in $_gid session variable.
- *
- *
- *                    VARIABLES AFFECTING THE SCRIPT BEHAVIOR
- *
- * string  $login
- * string  $password
- * boolean $logout
- *
- * string  $cidReq   : course id requested
- * boolean $cidReset : ask for a course Reset, if no $cidReq is provided in the
- *                     same time, all course informations is removed from the
- *                     current session
- *
- * int     $gidReq   : group Id requested
- * boolean $gidReset : ask for a group Reset, if no $gidReq is provided in the
- *                     same time, all group informations is removed from the
- *                     current session
- *
- *
- *                   VARIABLES SET AND RETURNED BY THE SCRIPT
- *
- * All the variables below are set and returned by this script.
- *
- * USER VARIABLES
- *
- * string    $_user ['firstName'   ]
- * string    $_user ['lastName'    ]
- * string    $_user ['mail'        ]
- * string    $_user ['lastLogin'   ]
- * string    $_user ['official_code']
- * string    $_user ['picture_uri'  ]
- * string    $_user['user_id']
- *
- * boolean $is_platformAdmin
- * boolean $is_allowedCreateCourse
- *
- * COURSE VARIABLES
- * see the function get_course_info_with_category
-* boolean $is_courseMember
-* boolean $is_courseTutor
-* boolean $is_courseAdmin
-*
-*
-* GROUP VARIABLES
-*
-* int     $_gid (the group id)
-*
-*
-*                       IMPORTANT ADVICE FOR DEVELOPERS
-*
-* We strongly encourage developers to use a connection layer at the top of
-* their scripts rather than use these variables, as they are, inside the core
-* of their scripts. It will make code maintenance much easier.
-*
-*    Many if the functions you need you can already find in the
-*    main_api.lib.php
-*
-* We encourage you to use functions to access these global "kernel" variables.
-* You can add them to e.g. the main API library.
-*
-*
-*                               SCRIPT STRUCTURE
-*
-* 1. The script determines if there is an authentication attempt. This part
-* only chek if the login name and password are valid. Afterwards, it set the
-* $_user['user_id'] (user id) and the $uidReset flag. Other user informations are retrieved
-* later. It's also in this section that optional external authentication
-* devices step in.
-*
-* 2. The script determines what other session informations have to be set or
-* reset, setting correctly $cidReset (for course) and $gidReset (for group).
-*
-* 3. If needed, the script retrieves the other user informations (first name,
-*   last name, ...) and stores them in session.
-*
-* 4. If needed, the script retrieves the course information and stores them
-* in session
-*
-* 5. The script initializes the user permission status and permission for the
-* course level
-*
-* 6. If needed, the script retrieves group informations an store them in
-* session.
-*
-* 7. The script initializes the user status and permission for the group level.
-*
-*    @package chamilo.include
-*/
-
-// Verified if exists the username and password in session current
-
-use ChamiloSession as Session;
-
-// Facebook connexion, if activated
-if (api_is_facebook_auth_activated() && !api_get_user_id()) {
-    require_once api_get_path(SYS_PATH).'main/auth/external_login/facebook.inc.php';
-    if (isset($facebook_config['appId']) && isset($facebook_config['secret'])) {
-        facebookConnect();
-    }
-}
-
-// Conditional login
-if (isset($_SESSION['conditional_login']['uid']) && $_SESSION['conditional_login']['can_login'] === true) {
-    $uData = api_get_user_info($_SESSION['conditional_login']['uid']);
-    ConditionalLogin::check_conditions($uData);
-
-    $_user['user_id'] = $_SESSION['conditional_login']['uid'];
-    $_user['status']  = $uData['status'];
-    Session::write('_user', $_user);
-    Session::erase('conditional_login');
-    $uidReset=true;
-    Event::event_login($_user['user_id']);
-}
-
-// parameters passed via GET
-$logout = isset($_GET["logout"]) ? $_GET["logout"] : '';
-$gidReq = isset($_GET["gidReq"]) ? intval($_GET["gidReq"]) : '';
-
-//this fixes some problems with generic functionalities like
-//My Agenda & What's New icons linking to courses
-// $cidReq can be set in the index.php file of a course-area
-$cidReq = isset($cidReq) ? Database::escape_string($cidReq) : '';
-// $cidReq can be set in URL-parameter
-$cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : $cidReq;
-$cidReset = isset($cidReset) ? Database::escape_string($cidReset) : '';
-
-// $cidReset can be set in URL-parameter
-$cidReset = (
-    isset($_GET['cidReq']) &&
-    ((isset($_SESSION['_cid']) && $_GET['cidReq'] != $_SESSION['_cid']) || (!isset($_SESSION['_cid'])))
-) ? Database::escape_string($_GET["cidReq"]) : $cidReset;
-
-// $cDir is a special url param sent from a redirection from /courses/[DIR]/index.php...
-// It replaces cidReq in some opportunities
-$cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
-
-// if there is a cDir parameter in the URL and $cidReq could not be determined
-if (isset($cDir) && empty($cidReq)) {
-    $c = CourseManager::get_course_id_from_path($cDir);
-    if ($c) {
-        $cidReq = $c;
-    }
-    if (empty($cidReset)) {
-        if (!isset($_SESSION['_cid']) OR (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid'])) {
-            $cidReset = $cidReq;
-        }
-    }
-}
-
-$gidReset = isset($gidReset) ? $gidReset : '';
-// $gidReset can be set in URL-parameter
-
-// parameters passed via POST
-$login = isset($_POST["login"]) ? $_POST["login"] : '';
-// register if the user is just logging in, in order to redirect him
-$logging_in = false;
-
-/*  MAIN CODE  */
-
-if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) {
-    // uid is in session => login already done, continue with this value
-    $_user['user_id'] = $_SESSION['_user']['user_id'];
-    //Check if we have to reset user data
-    //This param can be used to reload user data if user has been logged by external script
-    if (isset($_SESSION['_user']['uidReset']) && $_SESSION['_user']['uidReset']) {
-        $uidReset = true;
-    }
-} else {
-    if (isset($_user['user_id'])) {
-        unset($_user['user_id']);
-    }
-
-    // Platform legal terms and conditions
-    if (api_get_setting('registration.allow_terms_conditions') == 'true') {
-        if (isset($_POST['login']) && isset($_POST['password']) &&
-            isset($_SESSION['term_and_condition']['user_id'])
-        ) {
-            // user id
-            $user_id = $_SESSION['term_and_condition']['user_id'];
-            // Update the terms & conditions
-            $legal_type = null;
-            //verify type of terms and conditions
-            if (isset($_POST['legal_info'])) {
-                $info_legal = explode(':', $_POST['legal_info']);
-                $legal_type = LegalManager::get_type_of_terms_and_conditions(
-                    $info_legal[0],
-                    $info_legal[1]
-                );
-            }
-
-            //is necessary verify check
-            if ($legal_type == 1) {
-                if ((isset($_POST['legal_accept']) && $_POST['legal_accept']=='1')) {
-                    $legal_option = true;
-                } else {
-                    $legal_option = false;
-                }
-            }
-
-            //no is check option
-            if ($legal_type == 0) {
-                $legal_option=true;
-            }
-
-            if (isset($_POST['legal_accept_type']) && $legal_option === true) {
-                $cond_array = explode(':', $_POST['legal_accept_type']);
-                if (!empty($cond_array[0]) && !empty($cond_array[1])) {
-                    $time = time();
-                    $condition_to_save = intval($cond_array[0]).':'.intval($cond_array[1]).':'.$time;
-                    UserManager::update_extra_field_value(
-                        $user_id,
-                        'legal_accept',
-                        $condition_to_save
-                    );
-                }
-            }
-        }
-    }
-
-    //IF cas is activated and user isn't logged in
-    if (api_get_setting('cas_activate') == 'true') {
-        $cas_activated = true;
-    } else {
-        $cas_activated = false;
-    }
-
-    $cas_login = false;
-    if ($cas_activated && !isset($_user['user_id']) && !isset($_POST['login']) && !$logout) {
-        require_once(api_get_path(SYS_PATH).'main/auth/cas/authcas.php');
-        $cas_login = cas_is_authenticated();
-    }
-
-    if ((isset($_POST['login']) && isset($_POST['password'])) || ($cas_login)) {
-
-        // $login && $password are given to log in
-        if ($cas_login && empty($_POST['login'])) {
-            $login = $cas_login;
-        } else {
-            $login = $_POST['login'];
-            $password = $_POST['password'];
-        }
-
-        $userManager = UserManager::getManager();
-        $userRepository = UserManager::getRepository();
-
-        // Lookup the user in the main database
-        $user_table = Database::get_main_table(TABLE_MAIN_USER);
-        $sql = "SELECT user_id, username, password, auth_source, active, expiration_date, status
-                FROM $user_table
-                WHERE username = '".Database::escape_string($login)."'";
-        $result = Database::query($sql);
-
-        $captchaValidated = true;
-        $captcha = api_get_setting('allow_captcha');
-        $allowCaptcha = $captcha == 'true';
-
-        if (Database::num_rows($result) > 0) {
-            $uData = Database::fetch_array($result, 'ASSOC');
-            if ($allowCaptcha) {
-                // Checking captcha
-                if (isset($_POST['captcha'])) {
-                    // Check captcha
-                    $captchaText = $_POST['captcha'];
-                    /** @var Text_CAPTCHA $obj */
-                    $obj = isset($_SESSION['template.lib']) ? $_SESSION['template.lib'] : null;
-                    if ($obj) {
-                        $obj->getPhrase();
-                        if ($obj->getPhrase() != $captchaText) {
-                            $captchaValidated = false;
-                        } else {
-                            $captchaValidated = true;
-                        }
-                    }
-                    if (isset($_SESSION['captcha_question'])) {
-                        $captcha_question = $_SESSION['captcha_question'];
-                        $captcha_question->destroy();
-                    }
-                }
-
-                // Redirect to login page
-                if ($captchaValidated == false) {
-                    $loginFailed = true;
-                    Session::erase('_uid');
-                    Session::write('loginFailed', '1');
-
-                    header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=wrong_captcha');
-                    exit;
-                }
-
-                // Check if account is blocked by captcha user extra field see function api_block_account_captcha()
-                $blockedUntilDate = api_get_user_blocked_by_captcha($login);
-
-                if (isset($blockedUntilDate) && !empty($blockedUntilDate)) {
-                    if (time() > api_strtotime($blockedUntilDate, 'UTC')) {
-                        api_clean_account_captcha($login);
-
-                    } else {
-                        $loginFailed = true;
-                        Session::erase('_uid');
-                        Session::write('loginFailed', '1');
-
-                        header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=blocked_by_captcha');
-                        exit;
-                    }
-                }
-            }
-
-            if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE ||
-                $uData['auth_source'] == CAS_AUTH_SOURCE
-            ) {
-                $validPassword = false;
-
-                $user = $userManager->findUserByUsername($login);
-
-                if ($user) {
-                    $validPassword = UserManager::isPasswordValid(
-                        $password,
-                        $user
-                    );
-                }
-
-                // The authentication of this user is managed by Chamilo itself
-                //$password = api_get_encrypted_password(trim(stripslashes($password)));
-
-                // Check the user's password
-                if (($validPassword || $cas_login) &&
-                    (trim($login) == $uData['username'])
-                ) {
-                    $update_type = UserManager::get_extra_user_data_by_field(
-                        $uData['user_id'],
-                        'update_type'
-                    );
-
-                    $update_type = $update_type['update_type'];
-                    if (!empty($extAuthSource[$update_type]['updateUser'])
-                        && file_exists($extAuthSource[$update_type]['updateUser'])
-                    ) {
-                        include_once $extAuthSource[$update_type]['updateUser'];
-                    }
-
-                    // Check if the account is active (not locked)
-                    if ($uData['active'] == '1') {
-
-                        // Check if the expiration date has not been reached
-                        if ($uData['expiration_date'] > date('Y-m-d H:i:s')
-                            || empty($uData['expiration_date'])
-                        ) {
-                            global $_configuration;
-
-                            if (api_is_multiple_url_enabled()) {
-
-                                // Check if user is an admin
-                                $my_user_is_admin = UserManager::is_admin($uData['user_id']);
-
-                                // This user is subscribed in these sites => $my_url_list
-                                $my_url_list = api_get_access_url_from_user($uData['user_id']);
-
-                                //Check the access_url configuration setting if
-                                // the user is registered in the access_url_rel_user table
-                                //Getting the current access_url_id of the platform
-                                $current_access_url_id = api_get_current_access_url_id();
-
-                                if ($my_user_is_admin === false) {
-
-                                    // the user have the permissions to enter at this site
-                                    if (is_array($my_url_list) &&
-                                        in_array($current_access_url_id, $my_url_list)
-                                    ) {
-                                        ConditionalLogin::check_conditions($uData);
-
-                                        $_user['user_id'] = $uData['user_id'];
-                                        $_user['status'] = $uData['status'];
-                                        Session::write('_user', $_user);
-                                        Event::event_login($_user['user_id']);
-                                        $logging_in = true;
-                                    } else {
-                                        $loginFailed = true;
-                                        Session::erase('_uid');
-                                        Session::write('loginFailed', '1');
-
-                                        // Fix cas redirection loop
-                                        // https://support.chamilo.org/issues/6124
-                                        $location = api_get_path(WEB_PATH)
-                                            .'index.php?loginFailed=1&error=access_url_inactive';
-                                        if ($cas_login) {
-                                            cas_logout(null, $location);
-                                        } else {
-                                            header('Location: '.$location);
-                                        }
-                                        exit;
-                                    }
-                                } else {
-                                    //Only admins of the "main" (first) Chamilo portal can login wherever they want
-                                    if (in_array(1, $my_url_list)) {
-                                        //Check if this admin have the access_url_id = 1 which means the principal
-                                        ConditionalLogin::check_conditions($uData);
-                                        $_user['user_id'] = $uData['user_id'];
-                                        $_user['status']  = $uData['status'];
-                                        Session::write('_user', $_user);
-                                        Event::event_login($_user['user_id']);
-                                        $logging_in = true;
-                                    } else {
-                                        //This means a secondary admin wants to login so we check as he's a normal user
-                                        if (in_array($current_access_url_id, $my_url_list)) {
-                                            $_user['user_id'] = $uData['user_id'];
-                                            $_user['status']  = $uData['status'];
-                                            Session::write('_user', $_user);
-                                            Event::event_login($_user['user_id']);
-                                            $logging_in = true;
-                                        } else {
-                                            $loginFailed = true;
-                                            Session::erase('_uid');
-                                            Session::write('loginFailed', '1');
-                                            header(
-                                                'Location: '.api_get_path(WEB_PATH)
-                                                .'index.php?loginFailed=1&error=access_url_inactive'
-                                            );
-                                            exit;
-                                        }
-                                    }
-                                }
-                            } else {
-
-                                ConditionalLogin::check_conditions($uData);
-                                $_user['user_id'] = $uData['user_id'];
-                                $_user['status'] = $uData['status'];
-
-                                Session::write('_user', $_user);
-                                Event::event_login($uData['user_id']);
-                                $logging_in = true;
-
-                            }
-                        } else {
-                            $loginFailed = true;
-                            Session::erase('_uid');
-                            Session::write('loginFailed', '1');
-                            header(
-                                'Location: '.api_get_path(WEB_PATH)
-                                .'index.php?loginFailed=1&error=account_expired'
-                            );
-                            exit;
-                        }
-                    } else {
-                        $loginFailed = true;
-                        Session::erase('_uid');
-                        Session::write('loginFailed', '1');
-                        header(
-                            'Location: '.api_get_path(WEB_PATH)
-                            .'index.php?loginFailed=1&error=account_inactive'
-                        );
-                        exit;
-                    }
-                } else {
-                    // login failed: username or password incorrect
-                    $loginFailed = true;
-                    Session::erase('_uid');
-                    Session::write('loginFailed', '1');
-
-                    if ($allowCaptcha) {
-
-                        if (isset($_SESSION['loginFailedCount'])) {
-                            $_SESSION['loginFailedCount']++;
-                        } else {
-                            $_SESSION['loginFailedCount'] = 1;
-                        }
-
-                        $numberMistakesToBlockAccount = api_get_setting('captcha_number_mistakes_to_block_account');
-
-                        if (isset($_SESSION['loginFailedCount'])) {
-                            if ($_SESSION['loginFailedCount'] >= $numberMistakesToBlockAccount) {
-                                api_block_account_captcha($login);
-                            }
-                        }
-                    }
-
-                    header(
-                        'Location: '.api_get_path(WEB_PATH)
-                        .'index.php?loginFailed=1&error=user_password_incorrect'
-                    );
-                    exit;
-                }
-
-                if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
-                    //first login for a not self registred
-                    //e.g. registered by a teacher
-                    //do nothing (code may be added later)
-                }
-            } elseif (!empty($extAuthSource[$uData['auth_source']]['login'])
-                && file_exists($extAuthSource[$uData['auth_source']]['login'])
-                ) {
-                /*
-                 * Process external authentication
-                 * on the basis of the given login name
-                 */
-                $loginFailed = true;  // Default initialisation. It could
-                // change after the external authentication
-                $key = $uData['auth_source']; //'ldap','shibboleth'...
-                /* >>>>>>>> External authentication modules <<<<<<<<< */
-                // see configuration.php to define these
-                include_once($extAuthSource[$key]['login']);
-                /* >>>>>>>> External authentication modules <<<<<<<<< */
-            } else { // no standard Chamilo login - try external authentification
-                //huh... nothing to do... we shouldn't get here
-                error_log(
-                    'Chamilo Authentication file defined in'.
-                    ' $extAuthSource could not be found - this might prevent'.
-                    ' your system from doing the corresponding authentication'.
-                    ' process',
-                    0
-                );
-            }
-        } else {
-            // login failed, Database::num_rows($result) <= 0
-            $loginFailed = true;  // Default initialisation. It could
-            // change after the external authentication
-
-            /*
-             * In this section:
-             * there is no entry for the $login user in the Chamilo
-             * database. This also means there is no auth_source for the user.
-             * We let all external procedures attempt to add him/her
-             * to the system.
-             *
-             * Process external login on the basis
-             * of the authentication source list
-             * provided by the configuration settings.
-             * If the login succeeds, for going further,
-             * Chamilo needs the $_user['user_id'] variable to be
-             * set and registered in the session. It's the
-             * responsability of the external login script
-             * to provide this $_user['user_id'].
-             */
-
-            if (isset($extAuthSource) && is_array($extAuthSource)) {
-                foreach ($extAuthSource as $thisAuthSource) {
-                    if (!empty($thisAuthSource['newUser']) && file_exists($thisAuthSource['newUser'])) {
-                        include_once($thisAuthSource['newUser']);
-                    } else {
-                        error_log(
-                            'Chamilo Authentication file '. $thisAuthSource['newUser'].
-                            ' could not be found - this might prevent your system from using'.
-                            ' the authentication process in the user creation process',
-                            0
-                        );
-                    }
-                }
-            } //end if is_array($extAuthSource)
-            if ($loginFailed) { //If we are here username given is wrong
-                Session::write('loginFailed', '1');
-                header(
-                    'Location: '.api_get_path(WEB_PATH)
-                    .'index.php?loginFailed=1&error=user_password_incorrect'
-                );
-                exit;
-            }
-        } //end else login failed
-    } elseif (api_get_setting('sso_authentication') === 'true'
-        && !in_array('webservices', explode('/', $_SERVER['REQUEST_URI']))
-        ) {
-        /**
-         * TODO:
-         * - Work on a better validation for webservices paths. Current is very poor and exit
-         */
-        $subsso = api_get_setting('sso_authentication_subclass');
-        if (!empty($subsso)) {
-            require_once api_get_path(SYS_CODE_PATH).'auth/sso/sso.'.$subsso.'.class.php';
-            $subsso = 'sso'.$subsso;
-            $osso = new $subsso(); //load the subclass
-        } else {
-            $osso = new sso();
-        }
-        if (isset($_SESSION['_user']['user_id'])) {
-            if ($logout) {
-                // Make custom redirect after logout
-                online_logout($_SESSION['_user']['user_id'], false);
-                $osso->logout(); //redirects and exits
-            }
-        } elseif (!$logout) {
-            // Handle cookie from Master Server
-
-            $forceSsoRedirect = api_get_setting('sso_force_redirect');
-            if ($forceSsoRedirect === 'true') {
-                // all users to be redirected unless they are connected (removed req on sso_cookie)
-                $redirectToMasterConditions = !isset($_GET['sso_referer']) && !isset($_GET['loginFailed']);
-            } else {
-                //  Users to still see the homepage without connecting
-                $redirectToMasterConditions = !isset($_GET['sso_referer']) && !isset($_GET['loginFailed']) && isset($_GET['sso_cookie']);
-            }
-
-            if ($redirectToMasterConditions) {
-                // Redirect to master server
-                $osso->ask_master();
-            } elseif (isset($_GET['sso_cookie'])) {
-
-                // Here we are going to check the origin of
-                // what the call says should be used for
-                // authentication, and ensure  we know it
-                $matches_domain = false;
-                if (isset($_GET['sso_referer'])) {
-                    $protocol = api_get_setting('sso_authentication_protocol');
-                    // sso_authentication_domain can list
-                    // several, comma-separated, domains
-                    $master_urls = preg_split('/,/', api_get_setting('sso_authentication_domain'));
-                    if (!empty($master_urls)) {
-                        $master_auth_uri = api_get_setting('sso_authentication_auth_uri');
-                        foreach ($master_urls as $mu) {
-                            if (empty($mu)) {
-                                continue;
-                            }
-                            // For each URL, check until we find *one* that matches the $_GET['sso_referer'],
-                            //  then skip other possibilities
-                            // Do NOT compare the whole referer, as this might cause confusing errors with friendly urls,
-                            // like in Drupal /?q=user& vs /user?
-                            $referrer = substr($_GET['sso_referer'], 0, strrpos($_GET['sso_referer'], '/'));
-                            if ($protocol.trim($mu) === $referrer) {
-                                $matches_domain = true;
-                                break;
-                            }
-                        }
-                    } else {
-                        error_log(
-                            'Your sso_authentication_master param is empty. '.
-                            'Check the platform configuration, security section. '.
-                            'It can be a list of comma-separated domains'
-                        );
-                    }
-                }
-                if ($matches_domain) {
-                    //make all the process of checking
-                    //if the user exists (delegated to the sso class)
-                    $osso->check_user();
-                } else {
-                    error_log('Check the sso_referer URL in your script, it doesn\'t match any of the possibilities');
-                    //Request comes from unknown source
-                    $loginFailed = true;
-                    Session::erase('_uid');
-                    Session::write('loginFailed', '1');
-                    header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=unrecognize_sso_origin');
-                    exit;
-                }
-            }
-            //end logout ... else ... login
-        } elseif ($logout) {
-            //if there was an attempted logout without a previous login, log
-            // this anonymous user out as well but avoid redirect
-            online_logout(null, false);
-            $osso->logout(); //redirects and exits
-        }
-    } elseif (api_get_setting('openid_authentication')=='true') {
-        if (!empty($_POST['openid_url'])) {
-            include api_get_path(SYS_CODE_PATH).'auth/openid/login.php';
-            openid_begin(trim($_POST['openid_url']), api_get_path(WEB_PATH).'index.php');
-            //this last function should trigger a redirect, so we can die here safely
-            die('Openid login redirection should be in progress');
-        } elseif (!empty($_GET['openid_identity'])) {
-            //it's usual for PHP to replace '.' (dot) by '_' (underscore) in URL parameters
-            include(api_get_path(SYS_CODE_PATH).'auth/openid/login.php');
-            $res = openid_complete($_GET);
-            if ($res['status'] == 'success') {
-                $id1 = Database::escape_string($res['openid.identity']);
-                //have another id with or without the final '/'
-                $id2 = (substr($id1, -1, 1)=='/'?substr($id1, 0, -1):$id1.'/');
-                //lookup the user in the main database
-                $user_table = Database::get_main_table(TABLE_MAIN_USER);
-                $sql = "SELECT user_id, username, password, auth_source, active, expiration_date
-                        FROM $user_table
-                        WHERE openid = '$id1'
-                        OR openid = '$id2' ";
-                $result = Database::query($sql);
-                if ($result !== false) {
-                    if (Database::num_rows($result)>0) {
-                        $uData = Database::fetch_array($result);
-
-                        if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
-                            //the authentification of this user is managed by Chamilo itself
-
-                            // check if the account is active (not locked)
-                            if ($uData['active']=='1') {
-                                // check if the expiration date has not been reached
-                                if ($uData['expiration_date'] > date('Y-m-d H:i:s')
-                                    || empty($uData['expiration_date'])
-                                ) {
-                                    $_user['user_id'] = $uData['user_id'];
-                                    $_user['status'] = $uData['status'];
-
-                                    Session::write('_user', $_user);
-                                    Event::event_login($_user['user_id']);
-                                } else {
-                                    $loginFailed = true;
-                                    Session::erase('_uid');
-                                    Session::write('loginFailed', '1');
-                                    header('Location: index.php?loginFailed=1&error=account_expired');
-                                    exit;
-                                }
-                            } else {
-                                $loginFailed = true;
-                                Session::erase('_uid');
-                                Session::write('loginFailed', '1');
-                                header('Location: index.php?loginFailed=1&error=account_inactive');
-                                exit;
-                            }
-                            if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
-                                //first login for a not self registred
-                                //e.g. registered by a teacher
-                                //do nothing (code may be added later)
-                            }
-                        }
-                    } else {
-                        //Redirect to the subscription form
-                        header(
-                            'Location: '.api_get_path(WEB_CODE_PATH)
-                            .'auth/inscription.php?username='.$res['openid.sreg.nickname']
-                            .'&email='.$res['openid.sreg.email']
-                            .'&openid='.$res['openid.identity']
-                            .'&openid_msg=idnotfound'
-                        );
-                        Session::write('loginFailed', '1');
-                        exit;
-                        //$loginFailed = true;
-                    }
-                } else {
-                    $loginFailed = true;
-                }
-            } else {
-                $loginFailed = true;
-            }
-        }
-    } elseif (KeyAuth::is_enabled()) {
-        $success = KeyAuth::instance()->login();
-        if ($success) {
-            $use_anonymous = false;
-        }
-    }
-    $uidReset = true;
-    //    $cidReset = true;
-    //    $gidReset = true;
-} // end else
-
- // Now check for anonymous user mode
-if (isset($use_anonymous) && $use_anonymous) {
-    //if anonymous mode is set, then try to set the current user as anonymous
-    //if he doesn't have a login yet
-    api_set_anonymous();
-} else {
-    //if anonymous mode is not set, then check if this user is anonymous. If it
-    //is, clean it from being anonymous (make him a nobody :-))
-    api_clear_anonymous();
-}
-
-// if the requested course is different from the course in session
-
-if (!empty($cidReq) && (!isset($_SESSION['_cid']) ||
-    (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))
-) {
-    $cidReset = true;
-    $gidReset = true;    // As groups depend from courses, group id is reset
-}
-
-/* USER INIT */
-if (isset($uidReset) && $uidReset) {
-    // session data refresh requested
-    unset($_SESSION['_user']['uidReset']);
-    $is_platformAdmin = false;
-    $is_allowedCreateCourse = false;
-    if (isset($_user['user_id']) && $_user['user_id'] && !api_is_anonymous()) {
-    //if (isset($_user['user_id']) && $_user['user_id']) {
-        // a uid is given (log in succeeded)
-
-        $_SESSION['loginFailed'] = false;
-        unset($_SESSION['loginFailedCount']);
-        unset($_SESSION['loginToBlock']);
-
-        $user_table = Database::get_main_table(TABLE_MAIN_USER);
-        $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
-        $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-
-        $sql = "SELECT user.*, a.user_id is_admin, login.login_date
-                FROM $user_table
-                LEFT JOIN $admin_table a
-                ON user.user_id = a.user_id
-                LEFT JOIN $track_e_login login
-                ON user.user_id  = login.login_user_id
-                WHERE user.user_id = '".$_user['user_id']."'
-                ORDER BY login.login_date DESC LIMIT 1";
-
-        $result = Database::query($sql);
-
-        if (Database::num_rows($result) > 0) {
-            // Extracting the user data
-
-            $uData = Database::fetch_array($result);
-            $_user = _api_format_user($uData, false);
-            $is_platformAdmin = (bool) (!is_null($uData['is_admin']));
-            $is_allowedCreateCourse = (bool) (($uData ['status'] == COURSEMANAGER) || (api_get_setting('drhCourseManagerRights') && $uData['status'] == DRH));
-            ConditionalLogin::check_conditions($uData);
-
-            Session::write('_user', $_user);
-            UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
-            Session::write('is_platformAdmin', $is_platformAdmin);
-            Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
-        } else {
-            header('location:'.api_get_path(WEB_PATH));
-            //exit("WARNING UNDEFINED UID !! ");
-        }
-    } else {
-        if (!api_is_anonymous()) {
-            // no uid => logout or Anonymous
-            Session::erase('_user');
-            Session::erase('_uid');
-        }
-    }
-    Session::write('is_platformAdmin', $is_platformAdmin);
-    Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
-} else { // continue with the previous values
-    $_user = $_SESSION['_user'];
-    $is_platformAdmin = isset($_SESSION['is_platformAdmin']) ? $_SESSION['is_platformAdmin'] : false;
-    $is_allowedCreateCourse = isset($_SESSION['is_allowedCreateCourse']) ? $_SESSION['is_allowedCreateCourse'] : false;
-}
-
-/*  COURSE INIT */
-
-if (isset($cidReset) && $cidReset) {
-    // Course session data refresh requested or empty data
-    if ($cidReq) {
-        $_course = api_get_course_info($cidReq);
-
-        if (!empty($_course)) {
-
-            //@TODO real_cid should be cid, for working with numeric course id
-            $_real_cid = $_course['real_id'];
-            $_cid = $_course['code'];
-
-            Session::write('_real_cid', $_real_cid);
-            Session::write('_cid', $_cid);
-            Session::write('_course', $_course);
-
-            // if a session id has been given in url, we store the session
-
-            // Database Table Definitions
-            $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
-            $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-            $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-            if (!empty($_GET['id_session'])) {
-                $sql = 'SELECT name FROM '.$tbl_session . '
-                        WHERE id="'.intval($_GET['id_session']) . '"';
-                $rs = Database::query($sql);
-                if (Database::num_rows($rs)) {
-                    list($_SESSION['session_name']) = Database::fetch_array(
-                        $rs
-                    );
-                    $_SESSION['id_session'] = intval($_GET['id_session']);
-                } else {
-                    api_not_allowed(true);
-                }
-
-            } else {
-                Session::erase('session_name');
-                Session::erase('id_session');
-            }
-
-            if (!empty($_GET['gidReq'])) {
-                $_SESSION['_gid'] = intval($_GET['gidReq']);
-            } else {
-                Session::erase('_gid');
-            }
-
-            if (!isset($_SESSION['login_as'])) {
-                //Course login
-                if (isset($_user['user_id'])) {
-                    Event::event_course_login(
-                        api_get_course_int_id(),
-                        api_get_user_id(),
-                        api_get_session_id()
-                    );
-                }
-            }
-        } else {
-            //exit("WARNING UNDEFINED CID !! ");
-            header('location:'.api_get_path(WEB_PATH));
-        }
-    } else {
-        Session::erase('_cid');
-        Session::erase('_real_cid');
-        Session::erase('_course');
-
-        if (!empty($_SESSION)) {
-            foreach ($_SESSION as $key => $session_item) {
-                if (strpos($key, 'lp_autolaunch_') === false) {
-                    continue;
-                } else {
-                    if (isset($_SESSION[$key])) {
-                        Session::erase($key);
-                    }
-                }
-            }
-        }
-
-        // Deleting session info.
-        if (api_get_session_id()) {
-            Session::erase('id_session');
-            Session::erase('session_name');
-        }
-
-        if (api_get_group_id()) {
-            Session::erase('_gid');
-        }
-    }
-} else {
-
-    // Continue with the previous values
-    if (empty($_SESSION['_course']) && !empty($_SESSION['_cid'])) {
-        //Just in case $_course is empty we try to load if the c_id still exists
-        $_course = api_get_course_info($_SESSION['_cid']);
-        if (!empty($_course)) {
-            $_real_cid = $_course['real_id'];
-            $_cid = $_course['code'];
-
-            Session::write('_real_cid', $_real_cid);
-            Session::write('_cid', $_cid);
-            Session::write('_course', $_course);
-        }
-    }
-
-    if (empty($_SESSION['_course']) or empty($_SESSION['_cid'])) { //no previous values...
-        $_cid = -1; // Set default values
-        $_course = -1;
-    } else {
-
-        $_cid = $_SESSION['_cid'];
-        $_course = $_SESSION['_course'];
-
-        // these lines are useful for tracking. Indeed we can have lost the id_session and not the cid.
-        // Moreover, if we want to track a course with another session it can be usefull
-        if (!empty($_GET['id_session']) && is_numeric($_GET['id_session'])) {
-            $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
-            $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_GET['id_session']). '"';
-            $rs = Database::query($sql);
-            if (Database::num_rows($rs)) {
-                list($_SESSION['session_name']) = Database::fetch_array($rs);
-                $_SESSION['id_session'] = intval($_GET['id_session']);
-            } else {
-                api_not_allowed(true);
-            }
-        }
-
-        if (!empty($_REQUEST['gidReq'])) {
-            $_SESSION['_gid'] = intval($_REQUEST['gidReq']);
-
-            $group_table = Database::get_course_table(TABLE_GROUP);
-            $sql = "SELECT * FROM $group_table
-                    WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'";
-            $result = Database::query($sql);
-            if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
-                $gpData = Database::fetch_array($result);
-                $_gid = $gpData ['id'];
-                Session::write('_gid', $_gid);
-            }
-        }
-
-        if (!isset($_SESSION['login_as'])) {
-            $save_course_access = true;
-
-            //The value  $_dont_save_user_course_access should be added before the call of global.inc.php see the main/inc/chat.ajax.php file
-            //Disables the updates in the TRACK_E_COURSE_ACCESS table
-            if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
-                $save_course_access = false;
-            }
-
-            if ($save_course_access) {
-                $course_tracking_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
-
-                /*
-                * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
-                * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
-                * login_course_date > now() - INTERVAL $session_lifetime SECOND
-                *
-                */
-                /*
-                if (isset($_configuration['session_lifetime'])) {
-                    $session_lifetime    = $_configuration['session_lifetime'];
-                } else {
-                    $session_lifetime    = 3600; // 1 hour
-                }*/
-
-                $session_lifetime    = 3600; // 1 hour
-
-                $course_code = $_course['sysCode'];
-                $time = api_get_utc_datetime();
-
-                if (isset($_user['user_id']) && !empty($_user['user_id'])) {
-
-                    //We select the last record for the current course in the course tracking table
-                    //But only if the login date is < than now + max_life_time
-                    $sql = "SELECT course_access_id
-                            FROM $course_tracking_table
-                            WHERE
-                                user_id = ".intval($_user['user_id'])." AND
-                                c_id = ".$_course['real_id']."  AND
-                                session_id  = ".api_get_session_id()." AND
-                                login_course_date > '$time' - INTERVAL $session_lifetime SECOND
-                            ORDER BY login_course_date DESC LIMIT 0,1";
-                    $result = Database::query($sql);
-                    if (Database::num_rows($result) > 0) {
-                        $i_course_access_id = Database::result($result, 0, 0);
-                        //We update the course tracking table
-                        $sql = "UPDATE $course_tracking_table  SET logout_course_date = '$time', counter = counter+1
-                                WHERE course_access_id = ".intval($i_course_access_id)." AND session_id = ".api_get_session_id();
-                        Database::query($sql);
-                    } else {
-                        $ip = api_get_real_ip();
-                        $sql="INSERT INTO $course_tracking_table (c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)" .
-                            "VALUES('".$_course['real_id']."', '".$ip."', '".$_user['user_id']."', '$time', '$time', '1','".api_get_session_id()."')";
-                        Database::query($sql);
-                    }
-                }
-            }
-        }
-    }
-}
-
-/*  COURSE / USER REL. INIT */
-
-$session_id = api_get_session_id();
-$user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
-
-//Course permissions
-//if this code is uncommented in some platforms the is_courseAdmin is not correctly saved see BT#5789
-/*$is_courseAdmin     = false; //course teacher
-$is_courseTutor     = false; //course teacher - some rights
-$is_courseMember    = false; //course student
-$is_courseCoach     = false; //course coach
-*/
-//Course - User permissions
-$is_sessionAdmin    = false;
-$is_courseCoach     = false; //course coach
-$is_courseAdmin     = false;
-$is_courseTutor     = false;
-$is_courseMember    = false;
-
-if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) {
-    if (isset($_cid) && $_cid) {
-        $my_user_id = isset($user_id) ? intval($user_id) : 0;
-        $variable = 'accept_legal_'.$my_user_id.'_'.$_course['real_id'].'_'.$session_id;
-
-        $user_pass_open_course = false;
-        if (api_check_user_access_to_legal($_course['visibility']) && Session::read($variable)) {
-            $user_pass_open_course = true;
-        }
-
-        //Checking if the user filled the course legal agreement
-        if ($_course['activate_legal'] == 1 && !api_is_platform_admin() && !api_is_anonymous()) {
-            $user_is_subscribed = CourseManager::is_user_accepted_legal($user_id, $_course['id'], $session_id) || $user_pass_open_course;
-            if (!$user_is_subscribed) {
-                $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?course_code='.$_course['code'].'&session_id='.$session_id;
-                header('Location: '.$url);
-                exit;
-            }
-        }
-    }
-
-    if (isset($user_id) && $user_id && isset($_real_cid) && $_real_cid) {
-
-        //Check if user is subscribed in a course
-        $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-        $sql = "SELECT * FROM $course_user_table
-                WHERE
-                    user_id  = '".$user_id."' AND
-                    relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
-                    c_id = '$_real_cid'";
-        $result = Database::query($sql);
-
-        $cuData = null;
-        if (Database::num_rows($result) > 0) { // this  user have a recorded state for this course
-            $cuData = Database::fetch_array($result, 'ASSOC');
-
-            $is_courseAdmin = (bool)($cuData['status'] == 1);
-            $is_courseTutor = (bool)($cuData['is_tutor'] == 1);
-            $is_courseMember = true;
-        }
-
-        // We are in a session course? Check session permissions
-        if (!empty($session_id)) {
-            // I'm not the teacher of the course
-            if ($is_courseAdmin == false) {
-                // This user has no status related to this course
-                // The user is subscribed in a session? The user is a Session coach a Session admin ?
-
-                $tbl_session  = Database :: get_main_table(TABLE_MAIN_SESSION);
-                $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-                $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-                // Session coach, session admin or course coach admin
-                $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id
-                        FROM $tbl_session session, $tbl_session_course_user session_rcru
-                        WHERE
-                            session_rcru.session_id  = session.id AND
-                            session_rcru.c_id = '$_real_cid' AND
-                            session_rcru.user_id = '$user_id' AND
-                            session_rcru.session_id = $session_id AND
-                            session_rcru.status = 2
-                        ";
-
-                $result = Database::query($sql);
-                $row = Database::store_result($result);
-
-                // Am I a session admin?
-                if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
-                    $is_courseMember     = false;
-                    $is_courseTutor      = false;
-                    $is_courseAdmin      = false;
-                    $is_courseCoach      = false;
-                    $is_sessionAdmin     = true;
-                } else {
-                    // Am I a session coach for this session?
-                    $sql = "SELECT session.id, session.id_coach FROM $tbl_session session
-                            INNER JOIN $tbl_session_course sc
-                            ON sc.session_id = session.id
-                            WHERE session.id = $session_id
-                            AND session.id_coach = $user_id
-                            AND sc.c_id = '$_real_cid'";
-                    $result = Database::query($sql);
-
-                    if (Database::num_rows($result)) {
-                        $is_courseMember     = true;
-                        $is_courseTutor      = false;
-                        $is_courseCoach      = true;
-                        $is_sessionAdmin     = false;
-                    } else {
-                        // Am I a course coach or a student?
-                        $sql = "SELECT cu.user_id, cu.status
-                               FROM $tbl_session_course_user cu
-                               WHERE
-                                    c_id = '$_real_cid' AND
-                                    cu.user_id     = '".$user_id."' AND
-                                    cu.session_id  = '".$session_id."'
-                               LIMIT 1";
-                        $result = Database::query($sql);
-
-                        if (Database::num_rows($result)) {
-                            $row = Database::fetch_array($result, 'ASSOC');
-
-                            $session_course_status = $row['status'];
-
-                            switch ($session_course_status) {
-                                case '2': // coach - teacher
-                                    $is_courseMember = true;
-                                    $is_courseTutor = true;
-                                    $is_courseCoach = true;
-                                    $is_sessionAdmin = false;
-
-                                    if (api_get_setting('extend_rights_for_coach') == 'true') {
-                                        $is_courseAdmin = true;
-                                    } else {
-                                        $is_courseAdmin = false;
-                                    }
-                                    break;
-                                case '0': //Student
-                                    $is_courseMember = true;
-                                    $is_courseTutor = false;
-                                    $is_courseAdmin = false;
-                                    $is_courseCoach = false;
-                                    $is_sessionAdmin = false;
-
-                                    break;
-                                default:
-                                    //unregister user
-                                    $is_courseMember = false;
-                                    $is_courseTutor = false;
-                                    $is_courseAdmin = false;
-                                    $is_sessionAdmin = false;
-                                    $is_courseCoach = false;
-                                    break;
-                            }
-                        } else {
-                            // Unregister user
-                            $is_courseMember = false;
-                            $is_courseTutor = false;
-                            $is_courseAdmin = false;
-                            $is_sessionAdmin = false;
-                            $is_courseCoach = false;
-                        }
-                    }
-                }
-
-                // Drh can enter to a course as an student see BT#6770
-                if (api_drh_can_access_all_session_content()) {
-                    $sessionInfo = SessionManager::getSessionFollowedByDrh($user_id, $session_id);
-                    if (!empty($sessionInfo) && !empty($sessionInfo['course_list'])) {
-                        if (isset($sessionInfo['course_list'][$_course['real_id']])) {
-                            $is_courseMember     = true;
-                            $is_courseTutor      = false;
-                            $is_courseCoach      = false;
-                            $is_sessionAdmin     = false;
-                        }
-                    }
-                }
-            }
-
-            //If I'm the admin platform i'm a teacher of the course
-            if ($is_platformAdmin) {
-                $is_courseAdmin     = true;
-            }
-        }
-    } else { // keys missing => not anymore in the course - user relation
-        // course
-        $is_courseMember = false;
-        $is_courseAdmin = false;
-        $is_courseTutor = false;
-        $is_courseCoach = false;
-        $is_sessionAdmin = false;
-    }
-
-    // Checking the course access
-    $is_allowed_in_course = false;
-
-    if (isset($_course) && isset($_course['visibility'])) {
-
-        switch ($_course['visibility']) {
-            case COURSE_VISIBILITY_OPEN_WORLD: //3
-                $is_allowed_in_course = true;
-                break;
-            case COURSE_VISIBILITY_OPEN_PLATFORM: //2
-                $courseCode = $_course['code'];
-                $isUserSubscribedInCourse = CourseManager::is_user_subscribed_in_course(
-                    $user_id,
-                    $courseCode,
-                    $session_id
-                );
-                if (isset($user_id) && $isUserSubscribedInCourse === true && !api_is_anonymous($user_id)) {
-                    $is_allowed_in_course = true;
-                }
-                break;
-            case COURSE_VISIBILITY_REGISTERED: //1
-                if ($is_platformAdmin || $is_courseMember) {
-                    $is_allowed_in_course = true;
-                }
-                break;
-            case COURSE_VISIBILITY_CLOSED: //0
-                if ($is_platformAdmin || $is_courseAdmin) {
-                    $is_allowed_in_course = true;
-                }
-                break;
-            case COURSE_VISIBILITY_HIDDEN: //4
-                if ($is_platformAdmin) {
-                    $is_allowed_in_course = true;
-                }
-        }
-    }
-
-    if (!$is_platformAdmin) {
-        if (!$is_courseMember &&
-            isset($_course['registration_code']) &&
-            !empty($_course['registration_code']) &&
-            !Session::read('course_password_'.$_course['real_id'], false)
-        ) {
-            // if we are here we try to access to a course requiring password
-            if ($is_allowed_in_course) {
-                // the course visibility allows to access the course
-                // with a password
-                $url = api_get_path(WEB_CODE_PATH).'auth/set_temp_password.php?course_id='.$_course['real_id'].'&session_id='.$session_id;
-                header('Location: '.$url);
-                exit;
-            } else {
-                $is_courseMember = false;
-                $is_courseAdmin = false;
-                $is_courseTutor = false;
-                $is_courseCoach = false;
-                $is_sessionAdmin = false;
-                $is_allowed_in_course = false;
-            }
-        }
-    } // check the session visibility
-
-    if ($is_allowed_in_course == true) {
-
-        //if I'm in a session
-        if ($session_id != 0) {
-            if (!$is_platformAdmin) {
-                // admin is not affected to the invisible session mode
-                $session_visibility = api_get_session_visibility($session_id);
-
-                switch ($session_visibility) {
-                    case SESSION_INVISIBLE:
-                        $is_allowed_in_course = false;
-                        break;
-                }
-                //checking date
-            }
-        }
-    }
-
-    // save the states
-    if (isset($is_courseAdmin)) {
-        Session::write('is_courseAdmin', $is_courseAdmin);
-        if ($is_courseAdmin) {
-            $is_allowed_in_course = true;
-        }
-    }
-    if (isset($is_courseMember)) {
-        Session::write('is_courseMember', $is_courseMember);
-    }
-    if (isset($is_courseTutor)) {
-        Session::write('is_courseTutor', $is_courseTutor);
-        if ($is_courseTutor) {
-            $is_allowed_in_course = true;
-        }
-    }
-    Session::write('is_courseCoach', $is_courseCoach);
-    Session::write('is_allowed_in_course', $is_allowed_in_course);
-    Session::write('is_sessionAdmin', $is_sessionAdmin);
-} else {
-    // Continue with the previous values
-
-    $is_courseAdmin = isset($_SESSION['is_courseAdmin']) ? $_SESSION['is_courseAdmin'] : false;
-    $is_courseTutor = isset($_SESSION['is_courseTutor']) ? $_SESSION['is_courseTutor'] : false;
-    $is_courseCoach = isset($_SESSION['is_courseCoach']) ? $_SESSION['is_courseCoach'] : false;
-    $is_courseMember = isset($_SESSION['is_courseMember']) ? $_SESSION['is_courseMember'] : false;
-    $is_allowed_in_course = isset($_SESSION ['is_allowed_in_course']) ? $_SESSION ['is_allowed_in_course'] : false;
-}
-
-//set variable according to student_view_enabled choices
-if (api_get_setting('course.student_view_enabled') == "true") {
-    if (isset($_GET['isStudentView'])) {
-        if ($_GET['isStudentView'] == 'true') {
-            if (isset($_SESSION['studentview'])) {
-                if (!empty($_SESSION['studentview'])) {
-                    // switching to studentview
-                    $_SESSION['studentview'] = 'studentview';
-                }
-            }
-        } elseif ($_GET['isStudentView'] == 'false') {
-            if (isset($_SESSION['studentview'])) {
-                if (!empty($_SESSION['studentview'])) {
-                    // switching to teacherview
-                    $_SESSION['studentview'] = 'teacherview';
-                }
-            }
-        }
-    } elseif (!empty($_SESSION['studentview'])) {
-        //all is fine, no change to that, obviously
-    } elseif (empty($_SESSION['studentview'])) {
-        // We are in teacherview here
-        $_SESSION['studentview'] = 'teacherview';
-    }
-}
-
-if (isset($_cid)) {
-    $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
-    $time = api_get_utc_datetime();
-    $sql = "UPDATE $tbl_course SET last_visit = '$time' WHERE code='$_cid'";
-    Database::query($sql);
-}
-
-// direct login to course
-if ((isset($cas_login) && $cas_login && exist_firstpage_parameter()) ||
-    ($logging_in && exist_firstpage_parameter())
-) {
-    $redirectCourseDir = api_get_firstpage_parameter();
-    api_delete_firstpage_parameter();    // delete the cookie
-
-    if (!isset($_SESSION['request_uri'])) {
-        if (CourseManager::get_course_id_from_path($redirectCourseDir)) {
-            $_SESSION['noredirection'] = false;
-            $_SESSION['request_uri'] = api_get_path(WEB_COURSE_PATH) . $redirectCourseDir . '/';
-        }
-    }
-} elseif (api_user_is_login() && exist_firstpage_parameter()) {
-    $redirectCourseDir = api_get_firstpage_parameter();
-    api_delete_firstpage_parameter(); // delete the cookie
-    if (CourseManager::get_course_id_from_path($redirectCourseDir)) {
-        $_SESSION['noredirection'] = false;
-        $_SESSION['request_uri'] = api_get_path(WEB_COURSE_PATH) . $redirectCourseDir . '/';
-    }
-}
-
-Redirect::session_request_uri($logging_in, $user_id);

+ 0 - 26
main/install/htaccess.dist

@@ -1,26 +0,0 @@
-# Change this file to fit your configuration and save it as .htaccess in the courses folder #
-# Chamilo mod rewrite
-# Comment lines start with # and are not processed
-
-<IfModule mod_rewrite.c>
-RewriteEngine On
-
-# Rewrite base is the dir chamilo is installed in with trailing slash
-RewriteBase {CHAMILO_URL_APPEND_PATH}/courses/
-
-# Do not rewrite on the main dir
-# Change this path to the path of your main folder
-RewriteCond %{REQUEST_URI} !^{CHAMILO_URL_APPEND_PATH}/main/
-
-#replace nasty ampersands by 3 slashes, we change these back in download.php
-RewriteRule ([^/]+)/document/(.*)&(.*)$ $1/document/$2///$3 [N]
-
-# Rewrite everything in the scorm folder of a course to the download script
-RewriteRule ([^/]+)/scorm/(.*)$ {CHAMILO_URL_APPEND_PATH}/main/document/download_scorm.php?doc_url=/$2&cDir=$1 [QSA,L]
-
-# Rewrite everything in the document folder of a course to the download script
-RewriteRule ([^/]+)/document/(.*)$ {CHAMILO_URL_APPEND_PATH}/main/document/download.php?doc_url=/$2&cDir=$1 [QSA,L]
-
-# Rewrite everything in the work folder
-RewriteRule ([^/]+)/work/(.*)$ {CHAMILO_URL_APPEND_PATH}/main/work/download.php?file=work/$2&cDir=$1 [QSA,L]
-</IfModule>

+ 0 - 865
main/install/index.php

@@ -1,865 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo installation
- *
- * As seen from the user, the installation proceeds in 6 steps.
- * The user is presented with several webpages where he/she has to make choices
- * and/or fill in data.
- *
- * The aim is, as always, to have good default settings and suggestions.
- *
- * @todo reduce high level of duplication in this code
- * @todo (busy) organise code into functions
- * @package chamilo.install
- */
-
-use ChamiloSession as Session;
-
-require_once __DIR__.'/../../vendor/autoload.php';
-
-define('SYSTEM_INSTALLATION', 1);
-define('INSTALL_TYPE_UPDATE', 'update');
-define('FORM_FIELD_DISPLAY_LENGTH', 40);
-define('DATABASE_FORM_FIELD_DISPLAY_LENGTH', 25);
-define('MAX_FORM_FIELD_LENGTH', 80);
-
-// Including necessary libraries.
-require_once '../inc/lib/api.lib.php';
-
-api_check_php_version('../inc/');
-
-/* INITIALIZATION SECTION */
-
-ob_implicit_flush(true);
-session_start();
-require_once api_get_path(LIBRARY_PATH).'database.constants.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'banner.lib.php';
-require_once 'install.lib.php';
-
-// The function api_get_setting() might be called within the installation scripts.
-// We need to provide some limited support for it through initialization of the
-// global array-type variable $_setting.
-$_setting = array(
-    'platform_charset' => 'UTF-8',
-    'server_type' => 'production', // 'production' | 'test'
-    'permissions_for_new_directories' => '0770',
-    'permissions_for_new_files' => '0660',
-    'stylesheets' => 'chamilo'
-);
-
-// Determination of the language during the installation procedure.
-if (!empty($_POST['language_list'])) {
-    $search = array('../', '\\0');
-    $install_language = str_replace($search, '', urldecode($_POST['language_list']));
-    Session::write('install_language', $install_language);
-} elseif (isset($_SESSION['install_language']) && $_SESSION['install_language']) {
-    $install_language = $_SESSION['install_language'];
-} else {
-    // Trying to switch to the browser's language, it is covenient for most of the cases.
-    $install_language = detect_browser_language();
-}
-
-// Language validation.
-if (!array_key_exists($install_language, get_language_folder_list())) {
-    $install_language = 'english';
-}
-
-$installationGuideLink = '../../documentation/installation_guide.html';
-
-// Loading language files.
-require api_get_path(SYS_LANG_PATH).'english/trad4all.inc.php';
-if ($install_language != 'english') {
-    include_once api_get_path(SYS_LANG_PATH).$install_language.'/trad4all.inc.php';
-    switch ($install_language) {
-        case 'french':
-            $installationGuideLink = '../../documentation/installation_guide_fr_FR.html';
-            break;
-        case 'spanish':
-            $installationGuideLink = '../../documentation/installation_guide_es_ES.html';
-            break;
-        case 'italian':
-            $installationGuideLink = '../../documentation/installation_guide_it_IT.html';
-            break;
-        default:
-            break;
-    }
-}
-
-// These global variables must be set for proper working of the function get_lang(...) during the installation.
-$language_interface = $install_language;
-$language_interface_initial_value = $install_language;
-
-// Character set during the installation, it is always to be 'UTF-8'.
-$charset = 'UTF-8';
-
-// Enables the portablity layer and configures PHP for UTF-8
-\Patchwork\Utf8\Bootup::initAll();
-
-// Page encoding initialization.
-header('Content-Type: text/html; charset='. $charset);
-
-// Setting the error reporting levels.
-error_reporting(E_ALL);
-
-// Overriding the timelimit (for large campusses that have to be migrated).
-@set_time_limit(0);
-
-// Upgrading from any subversion of 1.9
-$update_from_version_8 = array(
-    '1.9.0',
-    '1.9.2',
-    '1.9.4',
-    '1.9.6',
-    '1.9.6.1',
-    '1.9.8',
-    '1.9.8.1',
-    '1.9.8.2',
-    '1.9.10',
-    '1.9.10.2'
-);
-
-$my_old_version = '';
-if (empty($tmp_version)) {
-    $tmp_version = get_config_param('system_version');
-}
-
-if (!empty($_POST['old_version'])) {
-    $my_old_version = $_POST['old_version'];
-} elseif (!empty($tmp_version)) {
-    $my_old_version = $tmp_version;
-}
-
-require_once __DIR__.'/version.php';
-
-// Try to delete old symfony folder (generates conflicts with composer)
-$oldSymfonyFolder = '../inc/lib/symfony';
-if (is_dir($oldSymfonyFolder)) {
-    @rmdir($oldSymfonyFolder);
-}
-
-// A protection measure for already installed systems.
-
-if (isAlreadyInstalledSystem()) {
-    // The system has already been installed, so block re-installation.
-    $global_error_code = 6;
-    require '../inc/global_error_message.inc.php';
-    die();
-}
-
-/* STEP 1 : INITIALIZES FORM VARIABLES IF IT IS THE FIRST VISIT */
-
-// Is valid request
-$is_valid_request = isset($_REQUEST['is_executable']) ? $_REQUEST['is_executable'] : null;
-/*foreach ($_POST as $request_index => $request_value) {
-    if (substr($request_index, 0, 4) == 'step') {
-        if ($request_index != $is_valid_request) {
-            unset($_POST[$request_index]);
-        }
-    }
-}*/
-
-$badUpdatePath = false;
-$emptyUpdatePath = true;
-$proposedUpdatePath = '';
-
-if (!empty($_POST['updatePath'])) {
-    $proposedUpdatePath = $_POST['updatePath'];
-}
-
-if (@$_POST['step2_install'] || @$_POST['step2_update_8'] || @$_POST['step2_update_6']) {
-    if (@$_POST['step2_install']) {
-        $installType = 'new';
-        $_POST['step2'] = 1;
-    } else {
-        $installType = 'update';
-        if (@$_POST['step2_update_8']) {
-            $emptyUpdatePath = false;
-            $proposedUpdatePath = api_add_trailing_slash(empty($_POST['updatePath']) ? api_get_path(SYS_PATH) : $_POST['updatePath']);
-            if (file_exists($proposedUpdatePath)) {
-                if (in_array($my_old_version, $update_from_version_8)) {
-                    $_POST['step2'] = 1;
-                } else {
-                    $badUpdatePath = true;
-                }
-            } else {
-                $badUpdatePath = true;
-            }
-        }
-    }
-} elseif (@$_POST['step1']) {
-    $_POST['updatePath'] = '';
-    $installType = '';
-    $updateFromConfigFile = '';
-    unset($_GET['running']);
-} else {
-    $installType = isset($_GET['installType']) ? $_GET['installType'] : null;
-    $updateFromConfigFile = isset($_GET['updateFromConfigFile']) ? $_GET['updateFromConfigFile'] : false;
-}
-
-if ($installType == 'update' && in_array($my_old_version, $update_from_version_8)) {
-    // This is the main configuration file of the system before the upgrade.
-    // Old configuration file.
-    // Don't change to include_once
-    $oldConfigPath = api_get_path(SYS_CODE_PATH) . 'inc/conf/configuration.php';
-    if (file_exists($oldConfigPath)) {
-        include $oldConfigPath;
-    }
-}
-
-if (!isset($_GET['running'])) {
-    $dbHostForm = 'localhost';
-    $dbUsernameForm = 'root';
-    $dbPassForm = '';
-    $dbNameForm = 'chamilo';
-    $dbPortForm = 3306;
-
-    // Extract the path to append to the url if Chamilo is not installed on the web root directory.
-    $urlAppendPath = api_remove_trailing_slash(api_get_path(REL_PATH));
-    $urlForm = api_get_path(WEB_PATH);
-    $pathForm = api_get_path(SYS_PATH);
-    $emailForm = 'webmaster@localhost';
-    if (!empty($_SERVER['SERVER_ADMIN'])) {
-        $emailForm = $_SERVER['SERVER_ADMIN'];
-    }
-    $email_parts = explode('@', $emailForm);
-    if (isset($email_parts[1]) && $email_parts[1] == 'localhost') {
-        $emailForm .= '.localdomain';
-    }
-    $adminLastName = get_lang('DefaultInstallAdminLastname');
-    $adminFirstName = get_lang('DefaultInstallAdminFirstname');
-    $loginForm = 'admin';
-    $passForm = api_generate_password();
-
-    $campusForm = 'My campus';
-    $educationForm = 'Albert Einstein';
-    $adminPhoneForm = '(000) 001 02 03';
-    $institutionForm = 'My Organisation';
-    $institutionUrlForm = 'http://www.chamilo.org';
-    $languageForm = api_get_interface_language();
-
-    $checkEmailByHashSent = 0;
-    $ShowEmailNotCheckedToStudent = 1;
-    $userMailCanBeEmpty = 1;
-    $allowSelfReg = 1;
-    $allowSelfRegProf = 1;
-    $encryptPassForm = 'sha1';
-    $session_lifetime = 360000;
-    if (!empty($_GET['profile'])) {
-        $installationProfile = api_htmlentities($_GET['profile'], ENT_QUOTES);
-    }
-} else {
-    foreach ($_POST as $key => $val) {
-        $magic_quotes_gpc = ini_get('magic_quotes_gpc');
-        if (is_string($val)) {
-            if ($magic_quotes_gpc) {
-                $val = stripslashes($val);
-            }
-            $val = trim($val);
-            $_POST[$key] = $val;
-        } elseif (is_array($val)) {
-            foreach ($val as $key2 => $val2) {
-                if ($magic_quotes_gpc) {
-                    $val2 = stripslashes($val2);
-                }
-                $val2 = trim($val2);
-                $_POST[$key][$key2] = $val2;
-            }
-        }
-        $GLOBALS[$key] = $_POST[$key];
-    }
-}
-
-/* NEXT STEPS IMPLEMENTATION */
-
-$total_steps = 7;
-if (!$_POST) {
-    $current_step = 1;
-} elseif (!empty($_POST['language_list']) or !empty($_POST['step1']) or ((!empty($_POST['step2_update_8']) or (!empty($_POST['step2_update_6']))) && ($emptyUpdatePath or $badUpdatePath))) {
-    $current_step = 2;
-} elseif (!empty($_POST['step2']) or (!empty($_POST['step2_update_8']) or (!empty($_POST['step2_update_6'])))) {
-    $current_step = 3;
-} elseif (!empty($_POST['step3'])) {
-    $current_step = 4;
-} elseif (!empty($_POST['step4'])) {
-    $current_step = 5;
-} elseif (!empty($_POST['step5'])) {
-    $current_step = 6;
-} elseif (@$_POST['step6']) {
-    $current_step = 7;
-}
-
-// Managing the $encryptPassForm
-if ($encryptPassForm == '1') {
-    $encryptPassForm = 'sha1';
-} elseif ($encryptPassForm == '0') {
-    $encryptPassForm = 'none';
-}
-
-?>
-<!DOCTYPE html>
-<head>
-    <title>&mdash; <?php echo get_lang('ChamiloInstallation').' &mdash; '.get_lang('Version_').' '.$new_version; ?></title>
-    <style type="text/css" media="screen, projection">
-        @import "../../web/assets/bootstrap/dist/css/bootstrap.min.css";
-        @import "../inc/lib/javascript/bootstrap-select/css/bootstrap-select.css";
-        @import "../../web/assets/fontawesome/css/font-awesome.min.css";
-        @import "../../web/css/base.css";
-        @import "../../web/css/themes/chamilo/default.css";
-    </style>
-    <script type="text/javascript" src="../../web/assets/jquery/dist/jquery.min.js"></script>
-    <script type="text/javascript" src="../../web/assets/bootstrap/dist/js/bootstrap.min.js"></script>
-    <script type="text/javascript" src="../inc/lib/javascript/bootstrap-select/js/bootstrap-select.min.js"></script>
-    <script type="text/javascript">
-        $(document).ready( function() {
-
-            $("#details_button").click(function() {
-                $( "#details" ).toggle("slow", function() {
-                });
-            });
-
-            $("#button_please_wait").hide();
-            $("button").addClass('btn btn-default');
-
-            // Allow Chamilo install in IE
-            $("button").click(function() {
-                $("#is_executable").attr("value",$(this).attr("name"));
-            });
-
-            //Blocking step6 button
-            $("#button_step6").click(function() {
-                $("#button_step6").hide();
-                $("#button_please_wait").html('<?php echo addslashes(get_lang('PleaseWait'));?>');
-                $("#button_please_wait").show();
-                $("#button_please_wait").attr('disabled', true);
-                $("#is_executable").attr("value",'step6');
-            });
-        });
-
-        init_visibility=0;
-        $(document).ready( function() {
-            $(".advanced_parameters").click(function() {
-                if ($("#id_contact_form").css("display") == "none") {
-                    $("#id_contact_form").css("display","block");
-                    $("#img_plus_and_minus").html('&nbsp;<img src="<?php echo api_get_path(WEB_IMG_PATH) ?>div_hide.gif" alt="<?php echo get_lang('Hide') ?>" title="<?php echo get_lang('Hide')?>" style ="vertical-align:middle" >&nbsp;<?php echo get_lang('ContactInformation') ?>');
-                } else {
-                    $("#id_contact_form").css("display","none");
-                    $("#img_plus_and_minus").html('&nbsp;<img src="<?php echo api_get_path(WEB_IMG_PATH) ?>div_show.gif" alt="<?php echo get_lang('Show') ?>" title="<?php echo get_lang('Show') ?>" style ="vertical-align:middle" >&nbsp;<?php echo get_lang('ContactInformation') ?>');
-                }
-            });
-        });
-
-        function send_contact_information() {
-            var data_post = "";
-            data_post += "person_name="+$("#person_name").val()+"&";
-            data_post += "person_email="+$("#person_email").val()+"&";
-            data_post += "company_name="+$("#company_name").val()+"&";
-            data_post += "company_activity="+$("#company_activity option:selected").val()+"&";
-            data_post += "person_role="+$("#person_role option:selected").val()+"&";
-            data_post += "company_country="+$("#country option:selected").val()+"&";
-            data_post += "company_city="+$("#company_city").val()+"&";
-            data_post += "language="+$("#language option:selected").val()+"&";
-            data_post += "financial_decision="+$("input[@name='financial_decision']:checked").val();
-
-            $.ajax({
-                contentType: "application/x-www-form-urlencoded",
-                beforeSend: function(objeto) {},
-                type: "POST",
-                url: "<?php echo api_get_path(WEB_AJAX_PATH) ?>install.ajax.php?a=send_contact_information",
-                data: data_post,
-                success: function(datos) {
-                    if (datos == 'required_field_error') {
-                        message = "<?php echo get_lang('FormHasErrorsPleaseComplete') ?>";
-                    } else if (datos == '1') {
-                        message = "<?php echo get_lang('ContactInformationHasBeenSent') ?>";
-                    } else {
-                        message = "<?php echo get_lang('Error').': '.get_lang('ContactInformationHasNotBeenSent') ?>";
-                    }
-                    alert(message);
-                }
-            });
-        }
-    </script>
-    <meta http-equiv="Content-Type" content="text/html; charset=<?php echo api_get_system_encoding(); ?>" />
-</head>
-<body dir="<?php echo api_get_text_direction(); ?>">
-
-<div id="page-install">
-<div id="main" class="container">
-    <header class="row">
-        <div class="col-md-12">
-            <div class="logo">
-                <img src="<?php echo api_get_path(WEB_CSS_PATH) ?>themes/chamilo/images/header-logo.png" hspace="10" vspace="10" alt="Chamilo" />
-            </div>
-        </div>
-    </header>
-    <div class="panel panel-default">
-        <div class="panel-heading">
-            <?php
-            echo '<h4>'.get_lang('ChamiloInstallation').' &ndash; '.get_lang('Version_').' '.$new_version.'</h4>';
-            ?>
-        </div>
-    <div class="panel-body">
-    <div class="row">
-        <div class="col-md-4">
-            <div class="well install-steps-menu">
-                <ol>
-                    <li <?php step_active('1'); ?>><?php echo get_lang('InstallationLanguage'); ?></li>
-                    <li <?php step_active('2'); ?>><?php echo get_lang('Requirements'); ?></li>
-                    <li <?php step_active('3'); ?>><?php echo get_lang('Licence'); ?></li>
-                    <li <?php step_active('4'); ?>><?php echo get_lang('DBSetting'); ?></li>
-                    <li <?php step_active('5'); ?>><?php echo get_lang('CfgSetting'); ?></li>
-                    <li <?php step_active('6'); ?>><?php echo get_lang('PrintOverview'); ?></li>
-                    <li <?php step_active('7'); ?>><?php echo get_lang('Installing'); ?></li>
-                </ol>
-            </div>
-            <div id="note">
-                <a class="btn btn-default" href="<?php echo $installationGuideLink; ?>" target="_blank">
-                    <em class="fa fa-file-text-o"></em> <?php echo get_lang('ReadTheInstallationGuide'); ?>
-                </a>
-            </div>
-        </div>
-
-        <div class="col-md-8">
-
-<form class="form-horizontal" id="install_form" method="post" action="<?php echo api_get_self(); ?>?running=1&amp;installType=<?php echo $installType; ?>&amp;updateFromConfigFile=<?php echo urlencode($updateFromConfigFile); ?>">
-<?php
-
-$instalation_type_label = '';
-if ($installType == 'new') {
-    $instalation_type_label  = get_lang('NewInstallation');
-} elseif ($installType == 'update') {
-    $update_from_version = isset($update_from_version) ? $update_from_version : null;
-    $instalation_type_label = get_lang('UpdateFromLMSVersion').(is_array($update_from_version) ? implode('|', $update_from_version) : '');
-}
-
-if (!empty($instalation_type_label) && empty($_POST['step6'])) {
-    echo '<div class="page-header"><h2>'.$instalation_type_label.'</h2></div>';
-}
-if (empty($installationProfile)) {
-    $installationProfile = '';
-    if (!empty($_POST['installationProfile'])) {
-        $installationProfile = api_htmlentities($_POST['installationProfile']);
-    }
-}
-    ?>
-    <input type="hidden" name="updatePath"         value="<?php if (!$badUpdatePath) echo api_htmlentities($proposedUpdatePath, ENT_QUOTES); ?>" />
-    <input type="hidden" name="urlAppendPath"      value="<?php echo api_htmlentities($urlAppendPath, ENT_QUOTES); ?>" />
-    <input type="hidden" name="pathForm"           value="<?php echo api_htmlentities($pathForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="urlForm"            value="<?php echo api_htmlentities($urlForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="dbHostForm"         value="<?php echo api_htmlentities($dbHostForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="dbPortForm"         value="<?php echo api_htmlentities($dbPortForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="dbUsernameForm"     value="<?php echo api_htmlentities($dbUsernameForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="dbPassForm"         value="<?php echo api_htmlentities($dbPassForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="dbNameForm"         value="<?php echo api_htmlentities($dbNameForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="allowSelfReg"       value="<?php echo api_htmlentities($allowSelfReg, ENT_QUOTES); ?>" />
-    <input type="hidden" name="allowSelfRegProf"   value="<?php echo api_htmlentities($allowSelfRegProf, ENT_QUOTES); ?>" />
-    <input type="hidden" name="emailForm"          value="<?php echo api_htmlentities($emailForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="adminLastName"      value="<?php echo api_htmlentities($adminLastName, ENT_QUOTES); ?>" />
-    <input type="hidden" name="adminFirstName"     value="<?php echo api_htmlentities($adminFirstName, ENT_QUOTES); ?>" />
-    <input type="hidden" name="adminPhoneForm"     value="<?php echo api_htmlentities($adminPhoneForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="loginForm"          value="<?php echo api_htmlentities($loginForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="passForm"           value="<?php echo api_htmlentities($passForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="languageForm"       value="<?php echo api_htmlentities($languageForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="campusForm"         value="<?php echo api_htmlentities($campusForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="educationForm"      value="<?php echo api_htmlentities($educationForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="institutionForm"    value="<?php echo api_htmlentities($institutionForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="institutionUrlForm" value="<?php echo api_stristr($institutionUrlForm, 'http://', false) ? api_htmlentities($institutionUrlForm, ENT_QUOTES) : api_stristr($institutionUrlForm, 'https://', false) ? api_htmlentities($institutionUrlForm, ENT_QUOTES) : 'http://'.api_htmlentities($institutionUrlForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="checkEmailByHashSent" value="<?php echo api_htmlentities($checkEmailByHashSent, ENT_QUOTES); ?>" />
-    <input type="hidden" name="ShowEmailNotCheckedToStudent" value="<?php echo api_htmlentities($ShowEmailNotCheckedToStudent, ENT_QUOTES); ?>" />
-    <input type="hidden" name="userMailCanBeEmpty" value="<?php echo api_htmlentities($userMailCanBeEmpty, ENT_QUOTES); ?>" />
-    <input type="hidden" name="encryptPassForm"    value="<?php echo api_htmlentities($encryptPassForm, ENT_QUOTES); ?>" />
-    <input type="hidden" name="session_lifetime"   value="<?php echo api_htmlentities($session_lifetime, ENT_QUOTES); ?>" />
-    <input type="hidden" name="old_version"        value="<?php echo api_htmlentities($my_old_version, ENT_QUOTES); ?>" />
-    <input type="hidden" name="new_version"        value="<?php echo api_htmlentities($new_version, ENT_QUOTES); ?>" />
-    <input type="hidden" name="installationProfile" value="<?php echo api_htmlentities($installationProfile, ENT_QUOTES); ?>" />
-<?php
-
-if (@$_POST['step2']) {
-    //STEP 3 : LICENSE
-    display_license_agreement();
-} elseif (@$_POST['step3']) {
-    //STEP 4 : MYSQL DATABASE SETTINGS
-    display_database_settings_form(
-        $installType,
-        $dbHostForm,
-        $dbUsernameForm,
-        $dbPassForm,
-        $dbNameForm,
-        $dbPortForm,
-        $installationProfile
-    );
-} elseif (@$_POST['step4']) {
-    //STEP 5 : CONFIGURATION SETTINGS
-
-    //if update, try getting settings from the database...
-    if ($installType == 'update') {
-        $db_name = $dbNameForm;
-
-        $manager = connectToDatabase(
-            $dbHostForm,
-            $dbUsernameForm,
-            $dbPassForm,
-            $dbNameForm,
-            $dbPortForm
-        );
-
-        $tmp = get_config_param_from_db('platformLanguage');
-        if (!empty($tmp)) {
-            $languageForm = $tmp;
-        }
-
-        $tmp = get_config_param_from_db('emailAdministrator');
-        if (!empty($tmp)) {
-            $emailForm = $tmp;
-        }
-
-        $tmp = get_config_param_from_db('administratorName');
-        if (!empty($tmp)) {
-            $adminFirstName = $tmp;
-        }
-
-        $tmp = get_config_param_from_db('administratorSurname');
-        if (!empty($tmp)) {
-            $adminLastName = $tmp;
-        }
-
-        $tmp = get_config_param_from_db('administratorTelephone');
-        if (!empty($tmp)) {
-            $adminPhoneForm = $tmp;
-        }
-
-        $tmp = get_config_param_from_db('siteName');
-        if (!empty($tmp)) {
-            $campusForm = $tmp;
-        }
-
-        $tmp = get_config_param_from_db('Institution');
-        if (!empty($tmp)) {
-            $institutionForm = $tmp;
-        }
-
-        $tmp = get_config_param_from_db('InstitutionUrl');
-        if (!empty($tmp)) {
-            $institutionUrlForm = $tmp;
-        }
-
-        // For version 1.9
-        $urlForm = $_configuration['root_web'];
-        $encryptPassForm = get_config_param('password_encryption');
-        // Managing the $encryptPassForm
-        if ($encryptPassForm == '1') {
-            $encryptPassForm = 'sha1';
-        } elseif ($encryptPassForm == '0') {
-            $encryptPassForm = 'none';
-        }
-
-        $allowSelfReg = false;
-        $tmp = get_config_param_from_db('allow_registration');
-        if (!empty($tmp)) {
-            $allowSelfReg = $tmp;
-        }
-
-        $allowSelfRegProf = false;
-        $tmp = get_config_param_from_db('allow_registration_as_teacher');
-        if (!empty($tmp)) {
-            $allowSelfRegProf = $tmp;
-        }
-    }
-
-    display_configuration_settings_form(
-        $installType,
-        $urlForm,
-        $languageForm,
-        $emailForm,
-        $adminFirstName,
-        $adminLastName,
-        $adminPhoneForm,
-        $campusForm,
-        $institutionForm,
-        $institutionUrlForm,
-        $encryptPassForm,
-        $allowSelfReg,
-        $allowSelfRegProf,
-        $loginForm,
-        $passForm
-    );
-
-} elseif (@$_POST['step5']) {
-    //STEP 6 : LAST CHECK BEFORE INSTALL
-?>
-    <div class="RequirementHeading">
-       <h3><?php echo display_step_sequence().get_lang('LastCheck'); ?></h3>
-    </div>
-    <div class="RequirementContent">
-       <?php echo get_lang('HereAreTheValuesYouEntered'); ?>
-    </div>
-
-    <?php
-    if ($installType == 'new') {
-        echo get_lang('AdminLogin') . ' : <strong>' . $loginForm . '</strong><br />';
-        echo get_lang('AdminPass') . ' : <strong>' . $passForm . '</strong><br /><br />'; /* TODO: Maybe this password should be hidden too? */
-    }
-
-    echo get_lang('AdminFirstName').' : '.$adminFirstName, '<br />', get_lang('AdminLastName').' : '.$adminLastName, '<br />';
-    echo get_lang('AdminEmail').' : '.$emailForm; ?><br />
-    <?php echo get_lang('AdminPhone').' : '.$adminPhoneForm; ?><br />
-    <?php echo get_lang('MainLang').' : '.$languageForm; ?><br /><br />
-    <?php echo get_lang('DBHost').' : '.$dbHostForm; ?><br />
-    <?php echo get_lang('DBPort').' : '.$dbPortForm; ?><br />
-    <?php echo get_lang('DBLogin').' : '.$dbUsernameForm; ?><br />
-    <?php echo get_lang('DBPassword').' : '.str_repeat('*', api_strlen($dbPassForm)); ?><br />
-    <?php echo get_lang('MainDB').' : <strong>'.$dbNameForm; ?></strong><br />
-    <?php echo get_lang('AllowSelfReg').' : '.($allowSelfReg ? get_lang('Yes') : get_lang('No')); ?><br />
-    <?php echo get_lang('EncryptMethodUserPass').' : ';
-    echo $encryptPassForm;
-    ?>
-    <br /><br />
-
-    <?php echo get_lang('CampusName').' : '.$campusForm; ?><br />
-    <?php echo get_lang('InstituteShortName').' : '.$institutionForm; ?><br />
-    <?php echo get_lang('InstituteURL').' : '.$institutionUrlForm; ?><br />
-    <?php echo get_lang('ChamiloURL').' : '.$urlForm; ?><br /><br />
-    <?php
-    if ($installType == 'new') {
-        echo Display::display_warning_message(
-            '<h4 style="text-align: center">'.get_lang(
-                'Warning'
-            ).'</h4>'.get_lang('TheInstallScriptWillEraseAllTables'),
-            false
-        );
-    }
-    ?>
-
-    <table width="100%">
-        <tr>
-            <td>
-                <button type="submit" class="btn btn-default" name="step4" value="&lt; <?php echo get_lang('Previous'); ?>" >
-                    <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
-                </button>
-            </td>
-            <td align="right">
-                <input type="hidden" name="is_executable" id="is_executable" value="-" />
-                <input type="hidden" name="step6" value="1" />
-                <button id="button_step6" class="btn btn-success" type="submit" name="button_step6" value="<?php echo get_lang('InstallChamilo'); ?>">
-                    <em class="fa fa-floppy-o"> </em>
-                    <?php echo get_lang('InstallChamilo'); ?>
-                </button>
-                <button class="btn btn-save" id="button_please_wait"></button>
-            </td>
-        </tr>
-    </table>
-
-    <?php
-} elseif (@$_POST['step6']) {
-    //STEP 6 : INSTALLATION PROCESS
-    $current_step = 7;
-    $msg = get_lang('InstallExecution');
-    if ($installType == 'update') {
-        $msg = get_lang('UpdateExecution');
-    }
-    echo '<div class="RequirementHeading">
-          <h3>'.display_step_sequence().$msg.'</h3>';
-    if (!empty($installationProfile)) {
-        echo '    <h3>('.$installationProfile.')</h3>';
-    }
-    echo '    <div id="pleasewait" class="alert alert-success">'.get_lang('PleaseWaitThisCouldTakeAWhile').'
-
-          <div class="progress">
-          <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
-            <span class="sr-only">100% Complete</span>
-          </div>
-        </div>
-          </div>
-          </div>';
-
-    // Push the web server to send these strings before we start the real
-    // installation process
-    flush();
-    $f = ob_get_contents();
-    if (!empty($f)) {
-        ob_flush(); //#5565
-    }
-
-    if ($installType == 'update') {
-        remove_memory_and_time_limits();
-
-        $manager = connectToDatabase(
-            $dbHostForm,
-            $dbUsernameForm,
-            $dbPassForm,
-            $dbNameForm,
-            $dbPortForm
-        );
-
-        $perm = api_get_permissions_for_new_directories();
-        $perm_file = api_get_permissions_for_new_files();
-
-        error_log('Starting migration process from '.$my_old_version.' ('.date('Y-m-d H:i:s').')');
-
-        switch ($my_old_version) {
-            case '1.9.0':
-            case '1.9.2':
-            case '1.9.4':
-            case '1.9.6':
-            case '1.9.6.1':
-            case '1.9.8':
-            case '1.9.8.1':
-            case '1.9.8.2':
-            case '1.9.10':
-            case '1.9.10.2':
-
-                // Fix type "enum" before running the migration with Doctrine
-                Database::query("ALTER TABLE course_category MODIFY COLUMN auth_course_child VARCHAR(40) DEFAULT 'TRUE'");
-                Database::query("ALTER TABLE course_category MODIFY COLUMN auth_cat_child VARCHAR(40) DEFAULT 'TRUE'");
-                Database::query("ALTER TABLE c_quiz_answer MODIFY COLUMN hotspot_type varchar(40) default NULL");
-                Database::query("ALTER TABLE c_tool MODIFY COLUMN target varchar(20) NOT NULL default '_self'");
-                Database::query("ALTER TABLE c_link MODIFY COLUMN on_homepage char(10) NOT NULL default '0'");
-                Database::query("ALTER TABLE c_blog_rating MODIFY COLUMN rating_type char(40) NOT NULL default 'post'");
-                Database::query("ALTER TABLE c_survey MODIFY COLUMN anonymous char(10) NOT NULL default '0'");
-                Database::query("ALTER TABLE c_document MODIFY COLUMN filetype char(10) NOT NULL default 'file'");
-                Database::query("ALTER TABLE c_student_publication MODIFY COLUMN filetype char(10) NOT NULL default 'file'");
-
-                echo '<a class="btn btn-default" href="javascript:void(0)" id="details_button">'.get_lang('Details').'</a><br />';
-                echo '<div id="details" style="display:none">';
-                // Migrate using the migration files located in:
-                // src/Chamilo/CoreBundle/Migrations/Schema/V110
-                $result = migrate(
-                    110,
-                    $manager
-                );
-
-                echo '</div>';
-
-                if ($result) {
-                    error_log('Migrations files were executed.');
-
-                    fixIds($manager);
-
-                    include 'update-files-1.9.0-1.10.0.inc.php';
-                    // Only updates the configuration.inc.php with the new version
-                    include 'update-configuration.inc.php';
-
-                    $configurationFiles = array(
-                        'mail.conf.php',
-                        'profile.conf.php',
-                        'course_info.conf.php',
-                        'add_course.conf.php',
-                        'events.conf.php',
-                        'auth.conf.php',
-                        'portfolio.conf.php'
-                    );
-
-                    error_log('Copy conf files');
-
-                    foreach ($configurationFiles as $file) {
-                        if (file_exists(api_get_path(SYS_CODE_PATH) . 'inc/conf/'.$file)) {
-                            copy(
-                                api_get_path(SYS_CODE_PATH).'inc/conf/'.$file,
-                                api_get_path(CONFIGURATION_PATH).$file
-                            );
-                        }
-                    }
-
-                    error_log('Finish upgrade process! ('.date('Y-m-d H:i:s').')');
-                } else {
-                    error_log('There was an error during running migrations. Check error.log');
-                }
-                break;
-            default:
-                break;
-        }
-    } else {
-        set_file_folder_permissions();
-
-        $manager = connectToDatabase(
-            $dbHostForm,
-            $dbUsernameForm,
-            $dbPassForm,
-            null,
-            $dbPortForm
-        );
-
-        $dbNameForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbNameForm);
-
-        // Drop and create the database anyways
-        $manager->getConnection()->getSchemaManager()->dropAndCreateDatabase($dbNameForm);
-
-        $manager = connectToDatabase(
-            $dbHostForm,
-            $dbUsernameForm,
-            $dbPassForm,
-            $dbNameForm,
-            $dbPortForm
-        );
-
-        $metadataList = $manager->getMetadataFactory()->getAllMetadata();
-        $schema = $manager->getConnection()->getSchemaManager()->createSchema();
-
-        // Create database schema
-        $tool = new \Doctrine\ORM\Tools\SchemaTool($manager);
-        $tool->createSchema($metadataList);
-
-        $sysPath = api_get_path(SYS_PATH);
-
-        finishInstallation(
-            $manager,
-            $sysPath,
-            $encryptPassForm,
-            $passForm,
-            $adminLastName,
-            $adminFirstName,
-            $loginForm,
-            $emailForm,
-            $adminPhoneForm,
-            $languageForm,
-            $institutionForm,
-            $institutionUrlForm,
-            $campusForm,
-            $allowSelfReg,
-            $allowSelfRegProf,
-            $installationProfile
-        );
-
-        include 'install_files.inc.php';
-    }
-
-    display_after_install_message($installType);
-
-    // Hide the "please wait" message sent previously
-    echo '<script>$(\'#pleasewait\').hide(\'fast\');</script>';
-
-} elseif (@$_POST['step1'] || $badUpdatePath) {
-    //STEP 1 : REQUIREMENTS
-    //make sure that proposed path is set, shouldn't be necessary but...
-    if (empty($proposedUpdatePath)) {
-        $proposedUpdatePath = $_POST['updatePath'];
-    }
-    display_requirements($installType, $badUpdatePath, $proposedUpdatePath, $update_from_version_8);
-} else {
-    // This is the start screen.
-    display_language_selection();
-    if (!empty($_GET['profile'])) {
-        $installationProfile = api_htmlentities($_GET['profile'], ENT_QUOTES);
-    }
-    echo '<input type="hidden" name="installationProfile" value="'.api_htmlentities($installationProfile, ENT_QUOTES).'" />';
-}
-
-$poweredBy = 'Powered by <a href="http://www.chamilo.org" target="_blank"> Chamilo </a> &copy; '.date('Y');
-?>
-          </form>
-        </div>
-      </div>
-    </div>
-    </div>
-        <footer class="panel panel-default">
-            <div class="panel-body">
-                <div style="text-align: center;">
-                    <?php echo $poweredBy; ?>
-                </div>
-            </div>
-        </footer>
-  </body>
-</html>

+ 0 - 2781
main/install/install.lib.php

@@ -1,2781 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- * This file contains functions used by the install and upgrade scripts.
- *
- * Ideas for future additions:
- * - a function get_old_version_settings to retrieve the config file settings
- *   of older versions before upgrading.
- */
-
-use Doctrine\ORM\EntityManager;
-use Chamilo\CoreBundle\Entity\ExtraField;
-use Chamilo\CoreBundle\Entity\ExtraFieldOptions;
-use Chamilo\CoreBundle\Entity\ExtraFieldValues;
-
-/*      CONSTANTS */
-define('SYSTEM_CONFIG_FILENAME', 'configuration.dist.php');
-
-/**
- * This function detects whether the system has been already installed.
- * It should be used for prevention from second running the installation
- * script and as a result - destroying a production system.
- * @return bool     The detected result;
- * @author Ivan Tcholakov, 2010;
- */
-function isAlreadyInstalledSystem()
-{
-    global $new_version, $_configuration;
-
-    if (empty($new_version)) {
-        return true; // Must be initialized.
-    }
-
-    $current_config_file = api_get_path(CONFIGURATION_PATH).'configuration.php';
-    if (!file_exists($current_config_file)) {
-        return false; // Configuration file does not exist, install the system.
-    }
-    require $current_config_file;
-
-    $current_version = null;
-    if (isset($_configuration['system_version'])) {
-        $current_version = trim($_configuration['system_version']);
-    }
-
-    // If the current version is old, upgrading is assumed, the installer goes ahead.
-    return empty($current_version) ? false : version_compare($current_version, $new_version, '>=');
-}
-
-/**
- * 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   boolean $optional Whether this extension is optional (then show unavailable text in orange rather than red)
- * @return  string  HTML string reporting the status of this extension. Language-aware.
- * @author  Christophe Gesch??
- * @author  Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @author  Yannick Warnier <yannick.warnier@dokeos.com>
- */
-function checkExtension($extensionName, $returnSuccess = 'Yes', $returnFailure = 'No', $optional = false)
-{
-    if (extension_loaded($extensionName)) {
-        return Display::label($returnSuccess, 'success');
-    } else {
-        if ($optional) {
-            return Display::label($returnFailure, 'warning');
-        } else {
-            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 <patrick.cool@UGent.be>, Ghent University
- */
-function checkPhpSetting($phpSetting, $recommendedValue, $returnSuccess = false, $returnFailure = false)
-{
-    $currentPhpValue = getPhpSetting($phpSetting);
-    if ($currentPhpValue == $recommendedValue) {
-        return Display::label($currentPhpValue.' '.$returnSuccess, 'success');
-    } else {
-        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 boolean: ON or OFF
- * @author Joomla <http://www.joomla.org>
- */
-function getPhpSetting($val)
-{
-    return ini_get($val) == '1' ? 'ON' : 'OFF';
-}
-
-/**
- * This function returns a string "true" or "false" according to the passed parameter.
- *
- * @param integer  $var  The variable to present as text
- * @return  string  the string "true" or "false"
- * @author Christophe Gesch??
- */
-function trueFalse($var)
-{
-    return $var ? 'true' : 'false';
-}
-
-/**
- * Removes memory and time limits as much as possible.
- */
-function remove_memory_and_time_limits()
-{
-    if (function_exists('ini_set')) {
-        ini_set('memory_limit', -1);
-        ini_set('max_execution_time', 0);
-        error_log('Update-db script: memory_limit set to -1', 0);
-        error_log('Update-db script: max_execution_time 0', 0);
-    } else {
-        error_log('Update-db script: could not change memory and time limits', 0);
-    }
-}
-
-/**
- * Detects browser's language.
- * @return string       Returns a language identificator, i.e. 'english', 'spanish', ...
- * @author Ivan Tcholakov, 2010
- */
-function detect_browser_language()
-{
-    static $language_index = array(
-        'ar' => 'arabic',
-        'ast' => 'asturian',
-        'bg' => 'bulgarian',
-        'bs' => 'bosnian',
-        'ca' => 'catalan',
-        'zh' => 'simpl_chinese',
-        'zh-tw' => 'trad_chinese',
-        'cs' => 'czech',
-        'da' => 'danish',
-        'prs' => 'dari',
-        'de' => 'german',
-        'el' => 'greek',
-        'en' => 'english',
-        'es' => 'spanish',
-        'eo' => 'esperanto',
-        'eu' => 'basque',
-        'fa' => 'persian',
-        'fr' => 'french',
-        'fur' => 'friulian',
-        'gl' => 'galician',
-        'ka' => 'georgian',
-        'hr' => 'croatian',
-        'he' => 'hebrew',
-        'hi' => 'hindi',
-        'id' => 'indonesian',
-        'it' => 'italian',
-        'ko' => 'korean',
-        'lv' => 'latvian',
-        'lt' => 'lithuanian',
-        'mk' => 'macedonian',
-        'hu' => 'hungarian',
-        'ms' => 'malay',
-        'nl' => 'dutch',
-        'ja' => 'japanese',
-        'no' => 'norwegian',
-        'oc' => 'occitan',
-        'ps' => 'pashto',
-        'pl' => 'polish',
-        'pt' => 'portuguese',
-        'pt-br' => 'brazilian',
-        'ro' => 'romanian',
-        'qu' => 'quechua_cusco',
-        'ru' => 'russian',
-        'sk' => 'slovak',
-        'sl' => 'slovenian',
-        'sr' => 'serbian',
-        'fi' => 'finnish',
-        'sv' => 'swedish',
-        'th' => 'thai',
-        'tr' => 'turkish',
-        'uk' => 'ukrainian',
-        'vi' => 'vietnamese',
-        'sw' => 'swahili',
-        'yo' => 'yoruba'
-    );
-
-    $system_available_languages = & get_language_folder_list();
-
-    $accept_languages = strtolower(str_replace('_', '-', $_SERVER['HTTP_ACCEPT_LANGUAGE']));
-    foreach ($language_index as $code => $language) {
-        if (strpos($accept_languages, $code) === 0) {
-            if (!empty($system_available_languages[$language])) {
-                return $language;
-            }
-        }
-    }
-
-    $user_agent = strtolower(str_replace('_', '-', $_SERVER['HTTP_USER_AGENT']));
-    foreach ($language_index as $code => $language) {
-        if (@preg_match("/[\[\( ]{$code}[;,_\-\)]/", $user_agent)) {
-            if (!empty($system_available_languages[$language])) {
-                return $language;
-            }
-        }
-    }
-
-    return 'english';
-}
-
-/*      FILESYSTEM RELATED FUNCTIONS */
-
-/**
- * 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('NotWritable'), 'info');
-        } else {
-            return Display::label(get_lang('NotWritable'), '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('NotReadable'), 'info');
-        } else {
-            return Display::label(get_lang('NotReadable'), 'important');
-        }
-    }
-}
-
-/**
- * This function is similar to the core file() function, except that it
- * works with line endings in Windows (which is not the case of file())
- * @param   string  $filename
- *
- * @return  array   The lines of the file returned as an array
- */
-function file_to_array($filename)
-{
-    if (!is_readable($filename) || is_dir($filename)) {
-        return array();
-    }
-    $fp = fopen($filename, 'rb');
-    $buffer = fread($fp, filesize($filename));
-    fclose($fp);
-
-    return explode('<br />', nl2br($buffer));
-}
-
-/**
- * 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
-}
-
-/**
- * Add's a .htaccess file to the courses directory
- * @param string $url_append The path from your webroot to your chamilo root
- * @return bool Result of writing the file
- */
-/*function write_courses_htaccess_file($url_append)
-{
-    $content = file_get_contents(dirname(__FILE__).'/'.COURSES_HTACCESS_FILENAME);
-    $content = str_replace('{CHAMILO_URL_APPEND_PATH}', $url_append, $content);
-    $fp = @fopen(api_get_path(SYS_COURSE_PATH).'.htaccess', 'w');
-    if ($fp) {
-        fwrite($fp, $content);
-        return fclose($fp);
-    }
-    return false;
-}*/
-
-/**
- * Write the main system config file
- * @param string $path Path to the config file
- */
-function write_system_config_file($path)
-{
-    global $dbHostForm;
-    global $dbPortForm;
-    global $dbUsernameForm;
-    global $dbPassForm;
-    global $dbNameForm;
-    global $urlForm;
-    global $pathForm;
-    global $urlAppendPath;
-    global $languageForm;
-    global $encryptPassForm;
-    global $session_lifetime;
-    global $new_version;
-    global $new_version_stable;
-
-    $root_sys = api_add_trailing_slash(str_replace('\\', '/', realpath($pathForm)));
-    $content = file_get_contents(dirname(__FILE__).'/'.SYSTEM_CONFIG_FILENAME);
-
-    $config['{DATE_GENERATED}'] = date('r');
-    $config['{DATABASE_HOST}'] = $dbHostForm;
-    $config['{DATABASE_PORT}'] = $dbPortForm;
-    $config['{DATABASE_USER}'] = $dbUsernameForm;
-    $config['{DATABASE_PASSWORD}'] = $dbPassForm;
-    $config['{DATABASE_MAIN}'] = $dbNameForm;
-    $config['{ROOT_WEB}'] = $urlForm;
-    $config['{ROOT_SYS}'] = $root_sys;
-    $config['{URL_APPEND_PATH}'] = $urlAppendPath;
-    $config['{PLATFORM_LANGUAGE}'] = $languageForm;
-    $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
-    $config['{ENCRYPT_PASSWORD}'] = $encryptPassForm;
-
-    $config['SESSION_LIFETIME'] = $session_lifetime;
-    $config['{NEW_VERSION}'] = $new_version;
-    $config['NEW_VERSION_STABLE'] = trueFalse($new_version_stable);
-
-    foreach ($config as $key => $value) {
-        $content = str_replace($key, $value, $content);
-    }
-
-    $fp = @ fopen($path, 'w');
-
-    if (!$fp) {
-        echo '<strong><font color="red">Your script doesn\'t have write access to the config directory</font></strong><br />
-                        <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
-                        You probably do not have write access on Chamilo root directory,
-                        i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
-                        Your problems can be related on two possible causes:<br />
-                        <ul>
-                          <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
-                          <li>PHP is running in <a href="http://www.php.net/manual/en/features.safe-mode.php" target="_blank">Safe-Mode</a>. If possible, try to switch it off.</li>
-                        </ul>
-                        <a href="http://forum.chamilo.org/" target="_blank">Read about this problem in Support Forum</a><br /><br />
-                        Please go back to step 5.
-                        <p><input type="submit" name="step5" value="&lt; Back" /></p>
-                        </td></tr></table></form></body></html>';
-        exit;
-    }
-
-    fwrite($fp, $content);
-    fclose($fp);
-}
-
-/**
- * Returns a list of language directories.
- */
-function & get_language_folder_list()
-{
-    static $result;
-    if (!is_array($result)) {
-        $result = array();
-        $exceptions = array('.', '..', 'CVS', '.svn');
-        $search       = array('_latin',   '_unicode',   '_corporate',   '_org'  , '_KM',   '_');
-        $replace_with = array(' (Latin)', ' (unicode)', ' (corporate)', ' (org)', ' (KM)', ' ');
-        $dirname = api_get_path(SYS_LANG_PATH);
-        $handle = opendir($dirname);
-        while ($entries = readdir($handle)) {
-            if (in_array($entries, $exceptions)) {
-                continue;
-            }
-            if (is_dir($dirname.$entries)) {
-                if (is_file($dirname.$entries.'/install_disabled')) {
-                    // Skip all languages that have this file present, just for
-                    // the install process (languages incomplete)
-                    continue;
-                }
-                $result[$entries] = ucwords(str_replace($search, $replace_with, $entries));
-            }
-        }
-        closedir($handle);
-        asort($result);
-    }
-    return $result;
-}
-
-/**
- * TODO: my_directory_to_array() - maybe within the main API there is already a suitable function?
- * @param   string  $directory  Full path to a directory
- * @return  array   A list of files and dirs in the directory
- */
-function my_directory_to_array($directory)
-{
-    $array_items = array();
-    if ($handle = opendir($directory)) {
-        while (false !== ($file = readdir($handle))) {
-            if ($file != "." && $file != "..") {
-                if (is_dir($directory. "/" . $file)) {
-                    $array_items = array_merge($array_items, my_directory_to_array($directory. '/' . $file));
-                    $file = $directory . "/" . $file;
-                    $array_items[] = preg_replace("/\/\//si", '/', $file);
-                }
-            }
-        }
-        closedir($handle);
-    }
-    return $array_items;
-}
-
-/**
- * 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  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 $configFile, $updateFromConfigFile;
-
-    // Look if we already have the queried parameter.
-    if (is_array($configFile) && isset($configFile[$param])) {
-        return $configFile[$param];
-    }
-    if (empty($updatePath) && !empty($_POST['updatePath'])) {
-        $updatePath = $_POST['updatePath'];
-    }
-
-    if (empty($updatePath)) {
-        $updatePath = api_get_path(SYS_PATH);
-    }
-    $updatePath = api_add_trailing_slash(str_replace('\\', '/', realpath($updatePath)));
-    $updateFromInstalledVersionFile = '';
-
-    if (empty($updateFromConfigFile)) {
-        // If update from previous install was requested,
-        // try to recover config file from Chamilo 1.9.x
-        if (file_exists($updatePath.'main/inc/conf/configuration.php')) {
-            $updateFromConfigFile = 'main/inc/conf/configuration.php';
-        } else {
-            // Give up recovering.
-            //error_log('Chamilo Notice: Could not find previous config file at '.$updatePath.'main/inc/conf/configuration.php nor at '.$updatePath.'claroline/inc/conf/claro_main.conf.php in get_config_param(). Will start new config (in '.__FILE__.', line '.__LINE__.')', 0);
-            return null;
-        }
-    }
-
-    if (file_exists($updatePath.$updateFromConfigFile) &&
-        !is_dir($updatePath.$updateFromConfigFile)
-    ) {
-        require $updatePath.$updateFromConfigFile;
-        $config = new Zend\Config\Config($_configuration);
-        return $config->get($param);
-    }
-
-    error_log('Config array could not be found in get_config_param()', 0);
-    return null;
-
-    /*if (file_exists($updatePath.$updateFromConfigFile)) {
-        return $val;
-    } else {
-        error_log('Config array could not be found in get_config_param()', 0);
-        return null;
-    }*/
-}
-
-/*      DATABASE RELATED FUNCTIONS */
-
-/**
- * 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 = '')
-{
-    if (($res = Database::query("SELECT * FROM settings_current WHERE variable = '$param'")) !== false) {
-        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  $dbHostForm DB host
- * @param string  $dbUsernameForm DB username
- * @param string  $dbPassForm DB password
- * @param string  $dbNameForm DB name
- * @param int     $dbPortForm DB port
- *
- * @return EntityManager
- */
-function connectToDatabase($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm, $dbPortForm = 3306)
-{
-    $dbParams = array(
-        'driver' => 'pdo_mysql',
-        'host' => $dbHostForm,
-        'port' => $dbPortForm,
-        'user' => $dbUsernameForm,
-        'password' => $dbPassForm,
-        'dbname' => $dbNameForm
-    );
-
-    $database = new \Database();
-    $database->connect($dbParams);
-
-    return $database->getManager();
-}
-
-/*      DISPLAY FUNCTIONS */
-
-/**
- * This function prints class=active_step $current_step=$param
- * @param   int $param  A step in the installer process
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- */
-function step_active($param)
-{
-    global $current_step;
-    if ($param == $current_step) {
-        echo 'class="current-step" ';
-    }
-}
-
-/**
- * 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).' &ndash; ';
-}
-
-/**
- * Displays a drop down box for selection the preferred language.
- */
-function display_language_selection_box($name = 'language_list', $default_language = 'english')
-{
-    // Reading language list.
-    $language_list = get_language_folder_list();
-
-    /*
-    // Reduction of the number of languages shown. Enable this fragment of code for customization purposes.
-    // Modify the language list according to your preference. Don't exclude the 'english' item.
-    $language_to_display = array('asturian', 'bulgarian', 'english', 'italian', 'french', 'slovenian', 'slovenian_unicode', 'spanish');
-    foreach ($language_list as $key => & $value) {
-        if (!in_array($key, $language_to_display)) {
-            unset($language_list[$key]);
-        }
-    }
-    */
-
-    // Sanity checks due to the possibility for customizations.
-    if (!is_array($language_list) || empty($language_list)) {
-        $language_list = array('english' => 'English');
-    }
-
-    // Sorting again, if it is necessary.
-    //asort($language_list);
-
-    // More sanity checks.
-    if (!array_key_exists($default_language, $language_list)) {
-        if (array_key_exists('english', $language_list)) {
-            $default_language = 'english';
-        } else {
-            $language_keys = array_keys($language_list);
-            $default_language = $language_keys[0];
-        }
-    }
-
-    // Displaying the box.
-    $html = '';
-    $html .= "\t\t<select class='selectpicker show-tick' name=\"$name\">\n";
-    foreach ($language_list as $key => $value) {
-        if ($key == $default_language) {
-            $option_end = ' selected="selected">';
-        } else {
-            $option_end = '>';
-        }
-        $html .= "\t\t\t<option value=\"$key\"$option_end";
-        $html .= $value;
-        $html .= "</option>\n";
-    }
-    $html .= "\t\t</select>\n";
-    return $html;
-}
-
-/**
- * This function displays a language dropdown box so that the installatioin
- * can be done in the language of the user
- */
-function display_language_selection()
-{ ?>
-    <h2><?php get_lang('WelcomeToTheChamiloInstaller'); ?></h2>
-    <div class="RequirementHeading">
-        <h2><?php echo display_step_sequence(); ?>
-            <?php echo get_lang('InstallationLanguage');?>
-        </h2>
-        <p><?php echo get_lang('PleaseSelectInstallationProcessLanguage'); ?>:</p>
-        <form id="lang_form" method="post" action="<?php echo api_get_self(); ?>">
-        <div class="form-group">
-            <div class="col-sm-4">
-                <?php echo display_language_selection_box('language_list', api_get_interface_language()); ?>
-            </div>
-            <div class="col-sm-6">
-                <button type="submit" name="step1" class="btn btn-success" value="<?php echo get_lang('Next'); ?>">
-                    <em class="fa fa-forward"> </em>
-                    <?php echo get_lang('Next'); ?></button>
-            </div>
-        </div>
-
-        <input type="hidden" name="is_executable" id="is_executable" value="-" />
-        </form>
-
-    </div>
-    <div class="RequirementHeading">
-        <?php echo get_lang('YourLanguageNotThereContactUs'); ?>
-    </div>
-<?php
-}
-
-/**
- * This function displays the requirements for installing Chamilo.
- *
- * @param string $installType
- * @param boolean $badUpdatePath
- * @param boolean $badUpdatePath
- * @param string $updatePath The updatePath given (if given)
- * @param array $update_from_version_8 The different subversions from version 1.9
- *
- * @author unknow
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- */
-function display_requirements(
-    $installType,
-    $badUpdatePath,
-    $updatePath = '',
-    $update_from_version_8 = array()
-) {
-    global $_setting;
-    echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Requirements')."</h2></div>";
-    echo '<div class="RequirementText">';
-    echo '<strong>'.get_lang('ReadThoroughly').'</strong><br />';
-    echo get_lang('MoreDetails').' <a href="../../documentation/installation_guide.html" target="_blank">'.get_lang('ReadTheInstallationGuide').'</a>.<br />'."\n";
-
-    if ($installType == 'update') {
-        echo get_lang('IfYouPlanToUpgradeFromOlderVersionYouMightWantToHaveAlookAtTheChangelog').'<br />';
-    }
-    echo '</div>';
-
-    //  SERVER REQUIREMENTS
-    echo '<div class="RequirementHeading"><h4>'.get_lang('ServerRequirements').'</h4>';
-
-    $timezone = checkPhpSettingExists("date.timezone");
-    if (!$timezone) {
-        echo "<div class='warning-message'>".
-            Display::return_icon('warning.png', get_lang('Warning'), '', ICON_SIZE_MEDIUM).
-            get_lang("DateTimezoneSettingNotSet")."</div>";
-    }
-
-    echo '<div class="RequirementText">'.get_lang('ServerRequirementsInfo').'</div>';
-    echo '<div class="RequirementContent">';
-    echo '<table class="table">
-            <tr>
-                <td class="requirements-item">'.get_lang('PHPVersion').' >= '.REQUIRED_PHP_VERSION.'</td>
-                <td class="requirements-value">';
-    if (phpversion() < REQUIRED_PHP_VERSION) {
-        echo '<strong><font color="red">'.get_lang('PHPVersionError').'</font></strong>';
-    } else {
-        echo '<strong><font color="green">'.get_lang('PHPVersionOK'). ' '.phpversion().'</font></strong>';
-    }
-    echo '</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('session', get_lang('Yes'), get_lang('ExtensionSessionsNotAvailable')).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.mysql.php" target="_blank">MySQL</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('mysql', get_lang('Yes'), get_lang('ExtensionMySQLNotAvailable')).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('zlib', get_lang('Yes'), get_lang('ExtensionZlibNotAvailable')).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.pcre.php" target="_blank">Perl-compatible regular expressions</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('pcre', get_lang('Yes'), get_lang('ExtensionPCRENotAvailable')).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('xml', get_lang('Yes'), get_lang('No')).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('intl', get_lang('Yes'), get_lang('No')).'</td>
-            </tr>
-               <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('json', get_lang('Yes'), get_lang('No')).'</td>
-            </tr>
-             <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> '.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('gd', get_lang('Yes'), get_lang('ExtensionGDNotAvailable')).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.curl.php" target="_blank">cURL</a>'.get_lang('support').'</td>
-                <td class="requirements-value">'.checkExtension('curl', get_lang('Yes'), get_lang('No')).'</td>
-            </tr>
-
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-                <td class="requirements-value">'.checkExtension('mbstring', get_lang('Yes'), get_lang('ExtensionMBStringNotAvailable'), true).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.iconv.php" target="_blank">Iconv</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-                <td class="requirements-value">'.checkExtension('iconv', get_lang('Yes'), get_lang('No'), true).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/en/book.ldap.php" target="_blank">LDAP</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-                <td class="requirements-value">'.checkExtension('ldap', get_lang('Yes'), get_lang('ExtensionLDAPNotAvailable'), true).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://xapian.org/" target="_blank">Xapian</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-                <td class="requirements-value">'.checkExtension('xapian', get_lang('Yes'), get_lang('No'), true).'</td>
-            </tr>
-        </table>';
-    echo '</div>';
-    echo '</div>';
-
-    // 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 '<div class="RequirementHeading"><h4>'.get_lang('RecommendedSettings').'</h4>';
-    echo '<div class="RequirementText">'.get_lang('RecommendedSettingsInfo').'</div>';
-    echo '<div class="RequirementContent">';
-    echo '<table class="table">
-            <tr>
-                <th>'.get_lang('Setting').'</th>
-                <th>'.get_lang('Recommended').'</th>
-                <th>'.get_lang('Actual').'</th>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/features.safe-mode.php">Safe Mode</a></td>
-                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('safe_mode', 'OFF').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
-                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('display_errors', 'OFF').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
-                <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('file_uploads', 'ON').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-gpc">Magic Quotes GPC</a></td>
-                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('magic_quotes_gpc', 'OFF').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-runtime">Magic Quotes Runtime</a></td>
-                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('magic_quotes_runtime', 'OFF').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/security.globals.php">Register Globals</a></td>
-                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('register_globals', 'OFF').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
-                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('session.auto_start', 'OFF').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
-                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('short_open_tag', 'OFF').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly">Cookie HTTP Only</a></td>
-                <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
-                <td class="requirements-value">'.checkPhpSetting('session.cookie_httponly', 'ON').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
-                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M', 'success').'</td>
-                <td class="requirements-value">'.compare_setting_values(ini_get('upload_max_filesize'), REQUIRED_MIN_UPLOAD_MAX_FILESIZE).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
-                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_POST_MAX_SIZE.'M', 'success').'</td>
-                <td class="requirements-value">'.compare_setting_values(ini_get('post_max_size'), REQUIRED_MIN_POST_MAX_SIZE).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item"><a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit">Memory Limit</a></td>
-                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_MEMORY_LIMIT.'M', 'success').'</td>
-                <td class="requirements-value">'.compare_setting_values(ini_get('memory_limit'), REQUIRED_MIN_MEMORY_LIMIT).'</td>
-            </tr>
-          </table>';
-    echo '  </div>';
-    echo '</div>';
-
-    // DIRECTORY AND FILE PERMISSIONS
-    echo '<div class="RequirementHeading"><h4>'.get_lang('DirectoryAndFilePermissions').'</h4>';
-    echo '<div class="RequirementText">'.get_lang('DirectoryAndFilePermissionsInfo').'</div>';
-    echo '<div class="RequirementContent">';
-
-    $course_attempt_name = '__XxTestxX__';
-    $course_dir = api_get_path(SYS_COURSE_PATH).$course_attempt_name;
-
-    //Just in case
-    @unlink($course_dir.'/test.php');
-    @rmdir($course_dir);
-
-    $perms_dir = array(0777, 0755, 0775, 0770, 0750, 0700);
-    $perms_fil = array(0666, 0644, 0664, 0660, 0640, 0600);
-
-    $course_test_was_created = false;
-
-    $dir_perm_verified = 0777;
-    foreach ($perms_dir as $perm) {
-        $r = @mkdir($course_dir, $perm);
-        if ($r === true) {
-            $dir_perm_verified = $perm;
-            $course_test_was_created = true;
-            break;
-        }
-    }
-
-    $fil_perm_verified = 0666;
-    $file_course_test_was_created = false;
-
-    if (is_dir($course_dir)) {
-        foreach ($perms_fil as $perm) {
-            if ($file_course_test_was_created == true) {
-                break;
-            }
-            $r = @touch($course_dir.'/test.php',$perm);
-            if ($r === true) {
-                $fil_perm_verified = $perm;
-                if (check_course_script_interpretation($course_dir, $course_attempt_name, 'test.php')) {
-                    $file_course_test_was_created = true;
-                }
-            }
-        }
-    }
-
-    @unlink($course_dir.'/test.php');
-    @rmdir($course_dir);
-
-    $_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');
-
-    $courseTestLabel = Display::label(get_lang('No'), 'important');
-
-    if ($course_test_was_created && $file_course_test_was_created) {
-        $courseTestLabel = Display::label(get_lang('Yes'), 'success');
-    }
-
-    if ($course_test_was_created && !$file_course_test_was_created) {
-        $courseTestLabel = Display::label(
-            sprintf(
-                get_lang('InstallWarningCouldNotInterpretPHP'),
-                api_get_path(WEB_COURSE_PATH).$course_attempt_name.'/test.php'
-            ),
-            'warning'
-        );
-    }
-
-    if (!$course_test_was_created && !$file_course_test_was_created) {
-        $courseTestLabel = Display::label(get_lang('No'), 'important');
-    }
-
-    $oldConf = '';
-    if (file_exists(api_get_path(SYS_CODE_PATH).'inc/conf/configuration.php')) {
-        $oldConf = '<tr>
-            <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'inc/conf</td>
-            <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'inc/conf').'</td>
-        </tr>';
-    }
-
-    echo '<table class="table">
-            '.$oldConf.'
-            <tr>
-                <td class="requirements-item">'.api_get_path(SYS_APP_PATH).'</td>
-                <td class="requirements-value">'.check_writable(api_get_path(SYS_APP_PATH)).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'default_course_document/images/</td>
-                <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'default_course_document/images/').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'lang/</td>
-                <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'lang/', true).' <br />('.get_lang('SuggestionOnlyToEnableSubLanguageFeature').')</td>
-            </tr>
-            <tr>
-                <td class="requirements-item">'.api_get_path(SYS_PATH).'vendor/</td>
-                <td class="requirements-value">'.checkReadable(api_get_path(SYS_PATH).'vendor').'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item">'.api_get_path(SYS_PUBLIC_PATH).'</td>
-                <td class="requirements-value">'.check_writable(api_get_path(SYS_PUBLIC_PATH)).'</td>
-            </tr>
-            <tr>
-                <td class="requirements-item">'.get_lang('CourseTestWasCreated').'</td>
-                <td class="requirements-value">'.$courseTestLabel.' </td>
-            </tr>
-            <tr>
-                <td class="requirements-item">'.get_lang('PermissionsForNewDirs').'</td>
-                <td class="requirements-value">'.$dir_perm.' </td>
-            </tr>
-            <tr>
-                <td class="requirements-item">'.get_lang('PermissionsForNewFiles').'</td>
-                <td class="requirements-value">'.$file_perm.' </td>
-            </tr>
-            ';
-    echo '    </table>';
-    echo '  </div>';
-    echo '</div>';
-
-    if ($installType == 'update' && (empty($updatePath) || $badUpdatePath)) {
-        if ($badUpdatePath) { ?>
-            <div class="alert alert-warning">
-                <?php echo get_lang('Error'); ?>!<br />
-                Chamilo <?php echo implode('|', $update_from_version_8).' '.get_lang('HasNotBeenFoundInThatDir'); ?>.
-            </div>
-        <?php }
-        else {
-            echo '<br />';
-        }
-        ?>
-            <div class="row">
-                <div class="col-md-12">
-                    <p><?php echo get_lang('OldVersionRootPath'); ?>:
-                        <input type="text" name="updatePath" size="50" value="<?php echo ($badUpdatePath && !empty($updatePath)) ? htmlentities($updatePath) : api_get_path(SYS_SERVER_ROOT_PATH).'old_version/'; ?>" />
-                    </p>
-                    <p>
-                        <button type="submit" class="btn btn-default" name="step1" value="<?php echo get_lang('Back'); ?>" >
-                            <em class="fa fa-backward"> <?php echo get_lang('Back'); ?></em>
-                        </button>
-                        <input type="hidden" name="is_executable" id="is_executable" value="-" />
-                        <button type="submit" class="btn btn-success" name="<?php echo (isset($_POST['step2_update_6']) ? 'step2_update_6' : 'step2_update_8'); ?>" value="<?php echo get_lang('Next'); ?> &gt;" >
-                            <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
-                        </button>
-                    </p>
-                </div>
-            </div>
-
-        <?php
-    } else {
-        $error = false;
-        // First, attempt to set writing permissions if we don't have them yet
-        $perm = api_get_permissions_for_new_directories();
-        $perm_file = api_get_permissions_for_new_files();
-
-        $notWritable = array();
-
-        $checked_writable = api_get_path(SYS_APP_PATH);
-        if (!is_writable($checked_writable)) {
-            $notWritable[] = $checked_writable;
-            @chmod($checked_writable, $perm);
-        }
-
-        $checked_writable = api_get_path(SYS_PUBLIC_PATH);
-        if (!is_writable($checked_writable)) {
-            $notWritable[] = $checked_writable;
-            @chmod($checked_writable, $perm);
-        }
-
-        $checked_writable = api_get_path(SYS_CODE_PATH).'default_course_document/images/';
-        if (!is_writable($checked_writable)) {
-            $notWritable[] = $checked_writable;
-            @chmod($checked_writable, $perm);
-        }
-
-        if ($course_test_was_created == false) {
-            $error = true;
-        }
-
-        $checked_writable = api_get_path(CONFIGURATION_PATH).'configuration.php';
-        if (file_exists($checked_writable) && !is_writable($checked_writable)) {
-            $notWritable[] = $checked_writable;
-            @chmod($checked_writable, $perm_file);
-        }
-
-        // Second, if this fails, report an error
-
-        //--> The user would have to adjust the permissions manually
-        if (count($notWritable) > 0) {
-            $error = true;
-            echo '<div class="error-message">';
-                echo '<center><h3>'.get_lang('Warning').'</h3></center>';
-                printf(get_lang('NoWritePermissionPleaseReadInstallGuide'), '</font>
-                <a href="../../documentation/installation_guide.html" target="blank">', '</a> <font color="red">');
-            echo '</div>';
-            echo '<ul>';
-            foreach ($notWritable as $value) {
-                echo '<li>'.$value.'</li>';
-            }
-            echo '</ul>';
-        } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) {
-            // Check wether a Chamilo configuration file already exists.
-            echo '<div class="alert alert-warning"><h4><center>';
-            echo get_lang('WarningExistingLMSInstallationDetected');
-            echo '</center></h4></div>';
-        }
-
-        // And now display the choice buttons (go back or install)
-        ?>
-        <p align="center" style="padding-top:15px">
-        <button type="submit" name="step1" class="btn btn-default" onclick="javascript: window.location='index.php'; return false;" value="<?php echo get_lang('Previous'); ?>" >
-            <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
-        </button>
-        <button type="submit" name="step2_install" class="btn btn-success" value="<?php echo get_lang("NewInstallation"); ?>" <?php if ($error) echo 'disabled="disabled"'; ?> >
-            <em class="fa fa-forward"> </em> <?php echo get_lang('NewInstallation'); ?>
-        </button>
-        <input type="hidden" name="is_executable" id="is_executable" value="-" />
-        <?php
-        // Real code
-        echo '<button type="submit" class="btn btn-default" name="step2_update_8" value="Upgrade from Chamilo 1.9.x"';
-        if ($error) echo ' disabled="disabled"';
-        echo ' ><em class="fa fa-forward"> </em> '.get_lang('UpgradeFromLMS19x').'</button>';
-
-        echo '</p>';
-    }
-}
-
-/**
- * Displays the license (GNU GPL) as step 2, with
- * - an "I accept" button named step3 to proceed to step 3;
- * - a "Back" button named step1 to go back to the first step.
- */
-
-function display_license_agreement()
-{
-    echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Licence').'</h2>';
-    echo '<p>'.get_lang('LMSLicenseInfo').'</p>';
-    echo '<p><a href="../../documentation/license.html" target="_blank">'.get_lang('PrintVers').'</a></p>';
-    echo '</div>';
-    ?>
-    <div class="row">
-        <div class="col-md-12">
-            <pre style="overflow: auto; height: 200px; margin-top: 5px;">
-                <?php echo api_htmlentities(@file_get_contents(api_get_path(SYS_PATH).'documentation/license.txt')); ?>
-            </pre>
-            <div class="checkbox">
-                <label>
-                    <input type="checkbox" name="accept" id="accept_licence" value="1" />
-                    <?php echo get_lang('IAccept'); ?>
-                </label>
-            </div>
-            <button type="submit" class="btn btn-default" name="step1" value="&lt; <?php echo get_lang('Previous'); ?>" >
-                <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
-            </button>
-            <input type="hidden" name="is_executable" id="is_executable" value="-" />
-            <button type="submit" class="btn btn-success" name="step3" onclick="javascript: if(!document.getElementById('accept_licence').checked) { alert('<?php echo get_lang('YouMustAcceptLicence')?>');return false;}" value="<?php echo get_lang('Next'); ?> &gt;" >
-                <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
-            </button>
-
-        </div>
-    </div>
-    <div class="row">
-        <div class="col-md-12">
-            <p class="alert alert-info"><?php echo get_lang('LMSMediaLicense'); ?></p>
-        </div>
-    </div>
-
-    <!-- Contact information form -->
-    <div>
-        <a href="javascript://" class = "advanced_parameters" >
-        <span id="img_plus_and_minus">&nbsp;<img src="<?php echo api_get_path(WEB_IMG_PATH) ?>div_hide.gif" alt="<?php echo get_lang('Hide') ?>" title="<?php echo get_lang('Hide')?>" style ="vertical-align:middle" />&nbsp;<?php echo get_lang('ContactInformation') ?></span>
-        </a>
-    </div>
-
-    <div id="id_contact_form" style="display:block">
-        <div class="normal-message"><?php echo get_lang('ContactInformationDescription') ?></div>
-        <div id="contact_registration">
-            <p><?php echo get_contact_registration_form() ?></p><br />
-        </div>
-    </div>
-    <?php
-}
-
-
-/**
- * Get contact registration form
- */
-function get_contact_registration_form()
-{
-
-    $html ='
-   <form class="form-horizontal">
-    <div class="panel panel-default">
-    <div class="panel-body">
-    <div id="div_sent_information"></div>
-    <div class="form-group">
-            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Name').'</label>
-            <div class="col-sm-9"><input id="person_name" class="form-control" type="text" name="person_name" size="30" /></div>
-    </div>
-    <div class="form-group">
-            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Email').'</label>
-            <div class="col-sm-9"><input id="person_email" class="form-control" type="text" name="person_email" size="30" /></div>
-    </div>
-    <div class="form-group">
-            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyName').'</label>
-            <div class="col-sm-9"><input id="company_name" class="form-control" type="text" name="company_name" size="30" /></div>
-    </div>
-    <div class="form-group">
-            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyActivity').'</label>
-            <div class="col-sm-9">
-                    <select class="selectpicker show-tick" name="company_activity" id="company_activity" >
-                            <option value="">--- '.get_lang('SelectOne').' ---</option>
-                            <Option value="Advertising/Marketing/PR">Advertising/Marketing/PR</Option><Option value="Agriculture/Forestry">Agriculture/Forestry</Option>
-                            <Option value="Architecture">Architecture</Option><Option value="Banking/Finance">Banking/Finance</Option>
-                            <Option value="Biotech/Pharmaceuticals">Biotech/Pharmaceuticals</Option><Option value="Business Equipment">Business Equipment</Option>
-                            <Option value="Business Services">Business Services</Option><Option value="Construction">Construction</Option>
-                            <Option value="Consulting/Research">Consulting/Research</Option><Option value="Education">Education</Option>
-                            <Option value="Engineering">Engineering</Option><Option value="Environmental">Environmental</Option>
-                            <Option value="Government">Government</Option><Option value="Healthcare">Health Care</Option>
-                            <Option value="Hospitality/Lodging/Travel">Hospitality/Lodging/Travel</Option><Option value="Insurance">Insurance</Option>
-                            <Option value="Legal">Legal</Option><Option value="Manufacturing">Manufacturing</Option>
-                            <Option value="Media/Entertainment">Media/Entertainment</Option><Option value="Mortgage">Mortgage</Option>
-                            <Option value="Non-Profit">Non-Profit</Option><Option value="Real Estate">Real Estate</Option>
-                            <Option value="Restaurant">Restaurant</Option><Option value="Retail">Retail</Option>
-                            <Option value="Shipping/Transportation">Shipping/Transportation</Option>
-                            <Option value="Technology">Technology</Option><Option value="Telecommunications">Telecommunications</Option>
-                            <Option value="Other">Other</Option>
-                    </select>
-            </div>
-    </div>
-
-    <div class="form-group">
-            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('PersonRole').'</label>
-            <div class="col-sm-9">
-                    <select class="selectpicker show-tick" name="person_role" id="person_role" >
-                            <option value="">--- '.get_lang('SelectOne').' ---</option>
-                            <Option value="Administration">Administration</Option><Option value="CEO/President/ Owner">CEO/President/ Owner</Option>
-                            <Option value="CFO">CFO</Option><Option value="CIO/CTO">CIO/CTO</Option>
-                            <Option value="Consultant">Consultant</Option><Option value="Customer Service">Customer Service</Option>
-                            <Option value="Engineer/Programmer">Engineer/Programmer</Option><Option value="Facilities/Operations">Facilities/Operations</Option>
-                            <Option value="Finance/ Accounting Manager">Finance/ Accounting Manager</Option><Option value="Finance/ Accounting Staff">Finance/ Accounting Staff</Option>
-                            <Option value="General Manager">General Manager</Option><Option value="Human Resources">Human Resources</Option>
-                            <Option value="IS/IT Management">IS/IT Management</Option><Option value="IS/ IT Staff">IS/ IT Staff</Option>
-                            <Option value="Marketing Manager">Marketing Manager</Option><Option value="Marketing Staff">Marketing Staff</Option>
-                            <Option value="Partner/Principal">Partner/Principal</Option><Option value="Purchasing Manager">Purchasing Manager</Option>
-                            <Option value="Sales/ Business Dev. Manager">Sales/ Business Dev. Manager</Option><Option value="Sales/ Business Dev.">Sales/ Business Dev.</Option>
-                            <Option value="Vice President/Senior Manager">Vice President/Senior Manager</Option><Option value="Other">Other</Option>
-                    </select>
-            </div>
-    </div>
-
-    <div class="form-group">
-            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyCountry').'</label>
-            <div class="col-sm-9">'.get_countries_list_from_array(true).'</div>
-    </div>
-    <div class="form-group">
-            <label class="col-sm-3">'.get_lang('CompanyCity').'</label>
-            <div class="col-sm-9">
-                    <input type="text" class="form-control" id="company_city" name="company_city" size="30" />
-            </div>
-    </div>
-    <div class="form-group">
-            <label class="col-sm-3">'.get_lang('WhichLanguageWouldYouLikeToUseWhenContactingYou').'</label>
-            <div class="col-sm-9">
-                    <select class="selectpicker show-tick" id="language" name="language">
-                            <option value="bulgarian">Bulgarian</option>
-                            <option value="indonesian">Bahasa Indonesia</option>
-                            <option value="bosnian">Bosanski</option>
-                            <option value="german">Deutsch</option>
-                            <option selected="selected" value="english">English</option>
-                            <option value="spanish">Spanish</option>
-                            <option value="french">Français</option>
-                            <option value="italian">Italian</option>
-                            <option value="hungarian">Magyar</option>
-                            <option value="dutch">Nederlands</option>
-                            <option value="brazilian">Português do Brasil</option>
-                            <option value="portuguese">Português europeu</option>
-                            <option value="slovenian">Slovenčina</option>
-                    </select>
-            </div>
-    </div>
-
-    <div class="form-group">
-            <label class="col-sm-3">'.get_lang('HaveYouThePowerToTakeFinancialDecisions').'</label>
-            <div class="col-sm-9">
-                <div class="radio">
-                    <label>
-                        <input type="radio" name="financial_decision" id="financial_decision1" value="1" checked /> ' . get_lang('Yes') . '
-                    </label>
-                </div>
-                <div class="radio">
-                    <label>
-                        <input type="radio" name="financial_decision" id="financial_decision2" value="0" /> '.get_lang('No').'
-                    </label>
-                </div>
-            </div>
-    </div>
-    <div class="clear"></div>
-    <div class="form-group">
-            <div class="col-sm-3">&nbsp;</div>
-            <div class="col-sm-9"><button type="button" class="btn btn-default" onclick="javascript:send_contact_information();" value="'.get_lang('SendInformation').'" ><em class="fa fa-floppy-o"></em> '.get_lang('SendInformation').'</button></div>
-    </div>
-    <div class="form-group">
-            <div class="col-sm-3">&nbsp;</div>
-            <div class="col-sm-9"><span class="form_required">*</span><small>'.get_lang('FieldRequired').'</small></div>
-    </div></div></div>
-</form>';
-
-    return $html;
-}
-
-/**
- * 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   boolean Whether to display in update mode
- * @param   string  Additional attribute for the <tr> element
- * @return  void    Direct output
- */
-function displayDatabaseParameter(
-    $installType,
-    $parameterName,
-    $formFieldName,
-    $parameterValue,
-    $extra_notice,
-    $displayWhenUpdate = true,
-    $tr_attribute = ''
-) {
-    //echo "<tr ".$tr_attribute.">";
-    echo "<label class='col-sm-4'>$parameterName</label>";
-
-    if ($installType == INSTALL_TYPE_UPDATE && $displayWhenUpdate) {
-        echo '<input type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'" value="'.api_htmlentities($parameterValue).'" />'.$parameterValue;
-    } else {
-        $inputType = $formFieldName == 'dbPassForm' ? 'password' : 'text';
-
-        //Slightly limit the length of the database prefix to avoid having to cut down the databases names later on
-        $maxLength = $formFieldName == 'dbPrefixForm' ? '15' : MAX_FORM_FIELD_LENGTH;
-        if ($installType == INSTALL_TYPE_UPDATE) {
-            echo '<input type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'" value="'.api_htmlentities($parameterValue).'" />';
-            echo api_htmlentities($parameterValue);
-        } else {
-            echo '<div class="col-sm-5"><input type="' . $inputType . '" class="form-control" size="' . DATABASE_FORM_FIELD_DISPLAY_LENGTH . '" maxlength="' . $maxLength . '" name="' . $formFieldName . '" id="' . $formFieldName . '" value="' . api_htmlentities($parameterValue) . '" />' . "</div>";
-            echo '<div class="col-sm-3">' . $extra_notice . '</div>';
-        }
-
-    }
-
-}
-
-/**
- * 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 ($installType == 'update') {
-        global $_configuration;
-        $dbHostForm = $_configuration['db_host'];
-        $dbUsernameForm = $_configuration['db_user'];
-        $dbPassForm = $_configuration['db_password'];
-        $dbNameForm = $_configuration['main_database'];
-        $dbPortForm = isset($_configuration['db_port']) ? $_configuration['db_port'] : '';
-
-        echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
-        echo '<div class="RequirementContent">';
-        echo get_lang('DBSettingUpgradeIntro');
-        echo '</div>';
-    } else {
-        echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
-        echo '<div class="RequirementContent">';
-        echo get_lang('DBSettingIntro');
-        echo '</div>';
-    }
-    ?>
-    <div class="panel panel-default">
-        <div class="panel-body">
-        <div class="form-group">
-            <label class="col-sm-4"><?php echo get_lang('DBHost'); ?> </label>
-            <?php if ($installType == 'update'){ ?>
-            <div class="col-sm-5">
-                <input type="hidden" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /><?php echo $dbHostForm; ?>
-            </div>
-            <div class="col-sm-3"></div>
-            <?php }else{ ?>
-            <div class="col-sm-5">
-                <input type="text" class="form-control" size="25" maxlength="50" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" />
-            </div>
-            <div class="col-sm-3"><?php echo get_lang('EG').' localhost'; ?></div>
-            <?php } ?>
-        </div>
-        <div class="form-group">
-            <label class="col-sm-4"><?php echo get_lang('DBPort'); ?> </label>
-            <?php if ($installType == 'update'){ ?>
-            <div class="col-sm-5">
-                <input type="hidden" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" /><?php echo $dbPortForm; ?>
-            </div>
-            <div class="col-sm-3"></div>
-            <?php }else{ ?>
-            <div class="col-sm-5">
-                <input type="text" class="form-control" size="25" maxlength="50" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" />
-            </div>
-            <div class="col-sm-3"><?php echo get_lang('EG').' 3306'; ?></div>
-            <?php } ?>
-        </div>
-        <div class="form-group">
-            <?php
-                //database user username
-                $example_login = get_lang('EG').' root';
-                displayDatabaseParameter($installType, get_lang('DBLogin'), 'dbUsernameForm', $dbUsernameForm, $example_login);
-            ?>
-        </div>
-        <div class="form-group">
-            <?php
-            //database user password
-            $example_password = get_lang('EG').' '.api_generate_password();
-            displayDatabaseParameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password);
-
-            ?>
-        </div>
-        <div class="form-group">
-            <?php
-            //Database Name fix replace weird chars
-            if ($installType != INSTALL_TYPE_UPDATE) {
-                $dbNameForm = str_replace(array('-','*', '$', ' ', '.'), '', $dbNameForm);
-            }
-
-            displayDatabaseParameter(
-                $installType,
-                get_lang('MainDB'),
-                'dbNameForm',
-                $dbNameForm,
-                '&nbsp;',
-                null,
-                'id="optional_param1"'
-                );
-            ?>
-        </div>
-       <?php if ($installType != INSTALL_TYPE_UPDATE) { ?>
-        <div class="form-group">
-            <div class="col-sm-3"></div>
-            <div class="col-sm-9">
-            <button type="submit" class="btn btn-primary" name="step3" value="step3">
-                <em class="fa fa-refresh"> </em>
-                <?php echo get_lang('CheckDatabaseConnection'); ?>
-            </button>
-            </div>
-        </div>
-        <?php } ?>
-
-        </div>
-    </div>
-
-        <?php
-
-        $database_exists_text = '';
-        $manager = null;
-        try {
-            $manager = connectToDatabase(
-                $dbHostForm,
-                $dbUsernameForm,
-                $dbPassForm,
-                null,
-                $dbPortForm
-            );
-            $databases = $manager->getConnection()->getSchemaManager()->listDatabases();
-            if (in_array($dbNameForm, $databases)) {
-                $database_exists_text = '<div class="alert alert-warning">'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'</div>';
-            }
-        } catch (Exception $e) {
-            $database_exists_text = $e->getMessage();
-        }
-
-        if ($manager->getConnection()->isConnected()): ?>
-
-            <?php echo $database_exists_text ?>
-            <div id="db_status" class="alert alert-success">
-                Database host: <strong><?php echo $manager->getConnection()->getHost(); ?></strong><br />
-                Database port: <strong><?php echo $manager->getConnection()->getPort(); ?></strong><br />
-                Database driver: <strong><?php echo $manager->getConnection()->getDriver()->getName(); ?></strong><br />
-
-            </div>
-
-        <?php else: ?>
-
-            <?php echo $database_exists_text ?>
-            <div id="db_status" style="float:left;" class="alert alert-danger">
-                <div style="float:left;">
-                    <?php echo get_lang('FailedConectionDatabase'); ?></strong>
-                </div>
-            </div>
-
-        <?php endif; ?>
-   <div class="form-group">
-       <div class="col-sm-6">
-           <button type="submit" name="step2" class="btn btn-default pull-right" value="&lt; <?php echo get_lang('Previous'); ?>" >
-               <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
-           </button>
-       </div>
-      <div class="col-sm-6">
-       <input type="hidden" name="is_executable" id="is_executable" value="-" />
-       <?php if ($manager) { ?>
-           <button type="submit"  class="btn btn-success" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
-               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
-           </button>
-       <?php } else { ?>
-           <button disabled="disabled" type="submit" class="btn btn-success disabled" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
-               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
-           </button>
-       <?php } ?>
-      </div>
-   </div>
-
-    <?php
-}
-function panel($content = null, $title = null, $id = null, $style = null) {
-    $html = '';
-    if (empty($style)) {
-        $style = 'default';
-    }
-    if (!empty($title)) {
-        $panelTitle = Display::div($title, array('class' => 'panel-heading'));
-        $panelBody = Display::div($content, array('class' => 'panel-body'));
-        $panelParent = Display::div($panelTitle . $panelBody, array('id' => $id, 'class' => 'panel panel-'.$style));
-    } else {
-        $panelBody = Display::div($html, array('class' => 'panel-body'));
-        $panelParent = Display::div($panelBody, array('id' => $id, 'class' => 'panel panel-'.$style));
-    }
-    $html .= $panelParent;
-    return $html;
-}
-/**
- * Displays a parameter in a table row.
- * Used by the display_configuration_settings_form function.
- * @param string $installType
- * @param string $parameterName
- * @param string $formFieldName
- * @param string $parameterValue
- * @param string $displayWhenUpdate
- */
-function display_configuration_parameter(
-    $installType,
-    $parameterName,
-    $formFieldName,
-    $parameterValue,
-    $displayWhenUpdate = 'true'
-) {
-    $html = '<div class="form-group">';
-    $html .= '<label class="col-sm-6 control-label">' . $parameterName . '</label>';
-    if ($installType == INSTALL_TYPE_UPDATE && $displayWhenUpdate) {
-        $html .= '<input type="hidden" name="' . $formFieldName . '" value="'. api_htmlentities($parameterValue, ENT_QUOTES). '" />' . $parameterValue;
-    } else {
-        $html .= '<div class="col-sm-6"><input class="form-control" type="text" size="'.FORM_FIELD_DISPLAY_LENGTH.'" maxlength="'.MAX_FORM_FIELD_LENGTH.'" name="'.$formFieldName.'" value="'.api_htmlentities($parameterValue, ENT_QUOTES).'" />'."</div>";
-    }
-    $html .= "</div>";
-    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 ($installType != 'update' && empty($languageForm)) {
-        $languageForm = $_SESSION['install_language'];
-    }
-    echo '<div class="RequirementHeading">';
-    echo "<h2>" . display_step_sequence() . get_lang("CfgSetting") . "</h2>";
-    echo '</div>';
-
-    echo '<p>'.get_lang('ConfigSettingsInfo').' <strong>app/config/configuration.php</strong></p>';
-
-    // Parameter 1: administrator's login
-
-    $html = '';
-
-    $html .= display_configuration_parameter($installType, get_lang('AdminLogin'), 'loginForm', $loginForm, $installType == 'update');
-
-    // Parameter 2: administrator's password
-    if ($installType != 'update') {
-        $html .= display_configuration_parameter($installType, get_lang('AdminPass'), 'passForm', $passForm, false);
-    }
-
-    // Parameters 3 and 4: administrator's names
-
-    $html .=  display_configuration_parameter($installType, get_lang('AdminFirstName'), 'adminFirstName', $adminFirstName);
-    $html .=  display_configuration_parameter($installType, get_lang('AdminLastName'), 'adminLastName', $adminLastName);
-
-    //Parameter 3: administrator's email
-    $html .=  display_configuration_parameter($installType, get_lang('AdminEmail'), 'emailForm', $emailForm);
-
-    //Parameter 6: administrator's telephone
-    $html .=  display_configuration_parameter($installType, get_lang('AdminPhone'), 'adminPhoneForm', $adminPhoneForm);
-
-
-    echo panel($html, get_lang('Administrator'), 'administrator');
-
-
-    //echo '<table class="table">';
-
-    //First parameter: language
-    $html = '<div class="form-group">';
-    $html .= '<label class="col-sm-6 control-label">'.get_lang('MainLang')."</label>";
-    if ($installType == 'update') {
-        $html .= '<input type="hidden" name="languageForm" value="'.api_htmlentities($languageForm, ENT_QUOTES).'" />'.$languageForm;
-
-    } else { // new installation
-        $html .= '<div class="col-sm-6">';
-        $html .= display_language_selection_box('languageForm', $languageForm);
-        $html .= '</div>';
-    }
-    $html.= "</div>";
-
-
-    //Second parameter: Chamilo URL
-    $html .= '<div class="form-group">';
-    $html .= '<label class="col-sm-6 control-label">'.get_lang('ChamiloURL') .get_lang('ThisFieldIsRequired').'</label>';
-
-
-
-    if ($installType == 'update') {
-        $html .= api_htmlentities($urlForm, ENT_QUOTES)."\n";
-    } else {
-        $html .= '<div class="col-sm-6">';
-        $html .= '<input class="form-control" type="text" size="40" maxlength="100" name="urlForm" value="'.api_htmlentities($urlForm, ENT_QUOTES).'" />';
-        $html .= '</div>';
-    }
-    $html .= '</div>';
-
-    //Parameter 9: campus name
-    $html .= display_configuration_parameter($installType, get_lang('CampusName'), 'campusForm', $campusForm);
-
-    //Parameter 10: institute (short) name
-    $html .= display_configuration_parameter($installType, get_lang('InstituteShortName'), 'institutionForm', $institutionForm);
-
-    //Parameter 11: institute (short) name
-    $html .= display_configuration_parameter($installType, get_lang('InstituteURL'), 'institutionUrlForm', $institutionUrlForm);
-
-
-    $html .= '<div class="form-group">
-            <label class="col-sm-6 control-label">' . get_lang("EncryptMethodUserPass") . '</label>
-        <div class="col-sm-6">';
-    if ($installType == 'update') {
-        $html .= '<input type="hidden" name="encryptPassForm" value="'. $encryptPassForm .'" />'. $encryptPassForm;
-    } else {
-
-        $html .= '<div class="checkbox">
-                    <label>
-                        <input  type="radio" name="encryptPassForm" value="bcrypt" id="encryptPass1" '. ($encryptPassForm == 'bcrypt' ? 'checked="checked" ':'') .'/> bcrypt
-                    </label>';
-
-        $html .= '<label>
-                        <input  type="radio" name="encryptPassForm" value="sha1" id="encryptPass1" '. ($encryptPassForm == 'sha1' ? 'checked="checked" ':'') .'/> sha1
-                    </label>';
-
-        $html .= '<label>
-                        <input type="radio" name="encryptPassForm" value="md5" id="encryptPass0" '. ($encryptPassForm == 'md5' ? 'checked="checked" ':'') .'/> md5
-                    </label>';
-
-        $html .= '<label>
-                        <input type="radio" name="encryptPassForm" value="none" id="encryptPass2" '. ($encryptPassForm == 'none' ? 'checked="checked" ':'') .'/>'. get_lang('None').'
-                    </label>';
-        $html .= '</div>';
-    }
-    $html .= '</div></div>';
-
-    $html .= '<div class="form-group">
-            <label class="col-sm-6 control-label">' . get_lang('AllowSelfReg') . '</label>
-            <div class="col-sm-6">';
-    if ($installType == 'update') {
-        if ($allowSelfReg == 'true') {
-            $label = get_lang('Yes');
-        } elseif ($allowSelfReg == 'false') {
-            $label = get_lang('No');
-        } else {
-            $label = get_lang('AfterApproval');
-        }
-        $html .= '<input type="hidden" name="allowSelfReg" value="'. $allowSelfReg .'" />'. $label;
-    } else {
-        $html .= '<div class="control-group">';
-        $html .= '<label class="checkbox-inline">
-                        <input type="radio" name="allowSelfReg" value="1" id="allowSelfReg1" '. ($allowSelfReg == 'true' ? 'checked="checked" ' : '') . ' /> '. get_lang('Yes') .'
-                    </label>';
-        $html .= '<label class="checkbox-inline">
-                        <input type="radio" name="allowSelfReg" value="0" id="allowSelfReg0" '. ($allowSelfReg == 'false' ? '' : 'checked="checked" ') .' /> '. get_lang('No') .'
-                    </label>';
-         $html .= '<label class="checkbox-inline">
-                    <input type="radio" name="allowSelfReg" value="0" id="allowSelfReg0" '. ($allowSelfReg == 'approval' ? '' : 'checked="checked" ') .' /> '. get_lang('AfterApproval') .'
-                </label>';
-        $html .= '</div>';
-    }
-    $html .= '</div>';
-    $html .= '</div>';
-
-    $html .= '<div class="form-group">';
-    $html .= '<label class="col-sm-6 control-label">'. get_lang('AllowSelfRegProf') .'</label>
-        <div class="col-sm-6">';
-    if ($installType == 'update') {
-        if ($allowSelfRegProf == 'true') {
-            $label = get_lang('Yes');
-        } else {
-            $label = get_lang('No');
-        }
-        $html .= '<input type="hidden" name="allowSelfRegProf" value="'. $allowSelfRegProf.'" />'. $label;
-    } else {
-        $html .= '<div class="control-group">
-                <label class="checkbox-inline">
-                    <input type="radio" name="allowSelfRegProf" value="1" id="allowSelfRegProf1" '. ($allowSelfRegProf ? 'checked="checked" ' : '') .'/>
-                ' . get_lang('Yes') .'
-                </label>';
-        $html .= '<label class="checkbox-inline">
-                    <input type="radio" name="allowSelfRegProf" value="0" id="allowSelfRegProf0" '. ($allowSelfRegProf ? '' : 'checked="checked" ') .' />
-                   '. get_lang('No') .'
-                </label>';
-        $html .= '</div>';
-    }
-    $html .= '</div>
-    </div>';
-
-    echo panel($html, get_lang('Platform'), 'platform');
- ?>
-    <div class='form-group'>
-        <div class="col-sm-6">
-            <button type="submit" class="btn btn-default pull-right" name="step3" value="&lt; <?php echo get_lang('Previous'); ?>" ><em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?></button>
-            <input type="hidden" name="is_executable" id="is_executable" value="-" />
-        </div>
-        <div class="col-sm-6">
-            <button class="btn btn-success" type="submit" name="step5" value="<?php echo get_lang('Next'); ?> &gt;" ><em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?></button>
-        </div>
-    </div>
-
-    <?php
-}
-
-/**
- * After installation is completed (step 6), this message is displayed.
- * @param string $installType
- */
-function display_after_install_message($installType)
-{
-    echo '<div class="RequirementContent">'.get_lang('FirstUseTip').'</div>';
-    echo '<div class="alert alert-warning">';
-    echo '<strong>'.get_lang('SecurityAdvice').'</strong>';
-    echo ': ';
-    printf(get_lang('ToProtectYourSiteMakeXReadOnlyAndDeleteY'), 'app/config/', 'main/install/');
-    echo '</div>';
-    ?></form>
-    <br />
-    <a class="btn btn-success btn-large btn-install" href="../../index.php">
-        <?php echo get_lang('GoToYourNewlyCreatedPortal'); ?>
-    </a>
-    <?php
-}
-
-/**
- * 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 = array(
-        "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"
-    );
-
-    $country_select = '';
-    if ($combo) {
-        $country_select = '<select class="selectpicker show-tick" id="country" name="country">';
-        $country_select .= '<option value="">--- '.get_lang('SelectOne').' ---</option>';
-        foreach ($a_countries as $country) {
-            $country_select .= '<option value="'.$country.'">'.$country.'</option>';
-        }
-        $country_select .= '</select>';
-        return $country_select;
-    }
-
-    return $a_countries;
-}
-
-/**
- * Lock settings that can't be changed in other portals
- */
-function lockSettings()
-{
-    $access_url_locked_settings = api_get_locked_settings();
-    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-    foreach ($access_url_locked_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
-    $sql = "UPDATE $table SET selected_value = '0" . decoct($permissions_for_new_directories) . "'
-              WHERE variable  = 'permissions_for_new_directories'";
-    Database::query($sql);
-
-    $sql = "UPDATE $table SET selected_value = '0" . decoct($permissions_for_new_files) . "' WHERE variable  = 'permissions_for_new_files'";
-    Database::query($sql);
-
-    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');
-    } else {
-        return Display::label($current_value_string, 'important');
-    }
-}
-
-/**
- * @param $course_dir
- * @param $course_attempt_name
- * @param string $file
- * @return bool
- */
-function check_course_script_interpretation($course_dir, $course_attempt_name, $file = 'test.php')
-{
-    $output = false;
-    //Write in file
-    $file_name = $course_dir.'/'.$file;
-    $content = '<?php echo "123"; exit;';
-
-    if (is_writable($file_name)) {
-        if ($handler = @fopen($file_name, "w")) {
-            //write content
-            if (fwrite($handler, $content)) {
-                $sock_errno = '';
-                $sock_errmsg = '';
-                $url = api_get_path(WEB_PATH).'app/courses/'.$course_attempt_name.'/'.$file;
-
-                $parsed_url = parse_url($url);
-                //$scheme = isset($parsedUrl['scheme']) ? $parsedUrl['scheme'] : ''; //http
-                $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
-                // Patch if the host is the default host and is used through
-                // the IP address (sometimes the host is not taken correctly
-                // in this case)
-                if (empty($host) && !empty($_SERVER['HTTP_HOST'])) {
-                    $host = $_SERVER['HTTP_HOST'];
-                    $url = preg_replace('#:///#', '://'.$host.'/', $url);
-                }
-                $path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
-                $port = isset($parsed_url['port']) ? $parsed_url['port'] : '80';
-
-                //Check fsockopen (doesn't work with https)
-                if ($fp = @fsockopen(str_replace('http://', '', $url), -1, $sock_errno, $sock_errmsg, 60)) {
-                    $out  = "GET $path HTTP/1.1\r\n";
-                    $out .= "Host: $host\r\n";
-                    $out .= "Connection: Close\r\n\r\n";
-
-                    fwrite($fp, $out);
-                    while (!feof($fp)) {
-                        $result = str_replace("\r\n", '',fgets($fp, 128));
-                        if (!empty($result) && $result == '123') {
-                            $output = true;
-                        }
-                    }
-                    fclose($fp);
-                    //Check allow_url_fopen
-                } elseif (ini_get('allow_url_fopen')) {
-                    if ($fp = @fopen($url, 'r')) {
-                        while ($result = fgets($fp, 1024)) {
-                            if (!empty($result) && $result == '123') {
-                                $output = true;
-                            }
-                        }
-                        fclose($fp);
-                    }
-                    // Check if has support for cURL
-                } elseif (function_exists('curl_init')) {
-                    $ch = curl_init();
-                    curl_setopt($ch, CURLOPT_HEADER, 0);
-                    curl_setopt($ch, CURLOPT_URL, $url);
-                    //curl_setopt($ch, CURLOPT_TIMEOUT, 30);
-                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-                    $result = curl_exec ($ch);
-                    if (!empty($result) && $result == '123') {
-                        $output = true;
-                    }
-                    curl_close($ch);
-                }
-            }
-            @fclose($handler);
-        }
-    }
-
-    return $output;
-}
-
-/**
- * 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 = ''
-) {
-    $allowRegistration = $allowRegistration ? 'true' : 'false';
-    $allowTeacherSelfRegistration = $allowTeacherSelfRegistration ? 'true' : 'false';
-
-    // Use PHP 5.3 to avoid issue with weird peripherical auto-installers like travis-ci
-    $settings = array(
-        'Institution' => $organizationName,
-        'InstitutionUrl' => $organizationUrl,
-        'siteName' => $siteName,
-        'emailAdministrator' => $adminEmail,
-        'administratorSurname' => $adminLastName,
-        'administratorName' => $adminFirstName,
-        'platformLanguage' => $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/Chamilo/CoreBundle/Migrations/Schema/*
- *
- * @param string $chamiloVersion
- * @param EntityManager $manager
- * @throws \Doctrine\DBAL\DBALException
- */
-function migrate($chamiloVersion, EntityManager $manager)
-{
-    $debug = true;
-    $connection = $manager->getConnection();
-
-    $config = new \Doctrine\DBAL\Migrations\Configuration\Configuration($connection);
-
-    // Table name that will store migrations log (will be created automatically,
-    // default name is: doctrine_migration_versions)
-    $config->setMigrationsTableName('version');
-    // Namespace of your migration classes, do not forget escape slashes, do not add last slash
-    $config->setMigrationsNamespace('Application\Migrations\Schema\V'.$chamiloVersion);
-    // Directory where your migrations are located
-    $config->setMigrationsDirectory(api_get_path(SYS_PATH).'app/Migrations/Schema/V'.$chamiloVersion);
-    // Load your migrations
-    $config->registerMigrationsFromDirectory($config->getMigrationsDirectory());
-
-    $migration = new \Doctrine\DBAL\Migrations\Migration($config);
-    $versions = $config->getMigrations();
-
-    /** @var Doctrine\DBAL\Migrations\Version $migrationItem */
-    foreach ($versions as $version) {
-        $version->getMigration()->setEntityManager($manager);
-    }
-
-    $to = null; // if $to == null then schema will be migrated to latest version
-
-    echo "<pre>";
-
-    try {
-        // Execute migration!
-        $migratedSQL = $migration->migrate($to);
-
-        if ($debug) {
-            foreach ($migratedSQL as $version => $sqlList) {
-                echo "VERSION: $version<br>";
-                echo "----------------------------------------------<br>";
-
-                foreach ($sqlList as $sql) {
-                    echo "<code>$sql</code><br>";
-                }
-            }
-
-            echo "<br>DONE!<br>";
-        }
-
-        return true;
-    } catch (Exception $ex) {
-        if ($debug) {
-            echo "ERROR: {$ex->getMessage()}<br>";
-            return false;
-        }
-    }
-
-    echo "</pre>";
-
-    return false;
-}
-
-/**
-* @param EntityManager $em
- *
-* @throws \Doctrine\DBAL\DBALException
- */
-function fixIds(EntityManager $em)
-{
-    $debug = true;
-    $connection = $em->getConnection();
-
-    if ($debug) {
-        error_log('fixIds');
-    }
-
-    // Create temporary indexes to increase speed of the following operations
-    // Adding and removing indexes will usually take much less time than
-    // the execution without indexes of the queries in this function, particularly
-    // for large tables
-    $sql = "ALTER TABLE c_document ADD INDEX tmpidx_doc(c_id, id)";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_student_publication ADD INDEX tmpidx_stud (c_id, id)";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_quiz ADD INDEX tmpidx_quiz (c_id, id)";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_item_property ADD INDEX tmpidx_ip (to_group_id)";
-    $connection->executeQuery($sql);
-
-    $sql = "SELECT * FROM c_lp_item";
-    $result = $connection->fetchAll($sql);
-    foreach ($result as $item) {
-        $courseId = $item['c_id'];
-        $iid = isset($item['iid']) ? intval($item['iid']) : 0;
-        $ref = isset($item['ref']) ? intval($item['ref']) : 0;
-        $sql = null;
-
-        $newId = '';
-
-        switch ($item['item_type']) {
-            case TOOL_LINK:
-                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_STUDENTPUBLICATION:
-                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_QUIZ:
-                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_DOCUMENT:
-                $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case TOOL_FORUM:
-                $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND forum_id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-            case 'thread':
-                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
-                $data = $connection->fetchAssoc($sql);
-                if ($data) {
-                    $newId = $data['iid'];
-                }
-                break;
-        }
-
-        if (!empty($sql) && !empty($newId) && !empty($iid)) {
-            $sql = "UPDATE c_lp_item SET ref = $newId WHERE iid = $iid";
-
-            $connection->executeQuery($sql);
-        }
-    }
-
-    // Set NULL if session = 0
-    $sql = "UPDATE c_item_property SET session_id = NULL WHERE session_id = 0";
-    $connection->executeQuery($sql);
-
-    // Set NULL if group = 0
-    $sql = "UPDATE c_item_property SET to_group_id = NULL WHERE to_group_id = 0";
-    $connection->executeQuery($sql);
-
-    // Set NULL if insert_user_id = 0
-    $sql = "UPDATE c_item_property SET insert_user_id = NULL WHERE insert_user_id = 0";
-    $connection->executeQuery($sql);
-
-    // Delete session data of sessions that don't exist.
-    $sql = "DELETE FROM c_item_property
-            WHERE session_id IS NOT NULL AND session_id NOT IN (SELECT id FROM session)";
-    $connection->executeQuery($sql);
-
-    // Delete group data of groups that don't exist.
-    $sql = "DELETE FROM c_item_property
-            WHERE to_group_id IS NOT NULL AND to_group_id NOT IN (SELECT DISTINCT id FROM c_group_info)";
-    $connection->executeQuery($sql);
-
-    // This updates the group_id with c_group_info.iid instead of c_group_info.id
-
-    if ($debug) {
-        error_log('update iids');
-    }
-
-    $groupTableToFix = [
-        'c_group_rel_user',
-        'c_group_rel_tutor',
-        'c_permission_group',
-        'c_role_group',
-        'c_survey_invitation',
-        'c_attendance_calendar_rel_group'
-    ];
-
-    foreach ($groupTableToFix as $table) {
-        $sql = "SELECT * FROM $table";
-        $result = $connection->fetchAll($sql);
-        foreach ($result as $item) {
-            $iid = $item['iid'];
-            $courseId = $item['c_id'];
-            $groupId = intval($item['group_id']);
-
-            // Fix group id
-            if (!empty($groupId)) {
-                $sql = "SELECT * FROM c_group_info
-                        WHERE c_id = $courseId AND id = $groupId
-                        LIMIT 1";
-                $data = $connection->fetchAssoc($sql);
-                if (!empty($data)) {
-                    $newGroupId = $data['iid'];
-                    $sql = "UPDATE $table SET group_id = $newGroupId
-                            WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                } else {
-                    // The group does not exists clean this record
-                    $sql = "DELETE FROM $table WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-    }
-
-    // Fix c_item_property
-    if ($debug) {
-        error_log('update c_item_property');
-    }
-
-    $sql = "SELECT * FROM course";
-    $courseList = $connection->fetchAll($sql);
-    if ($debug) {
-        error_log('Getting course list');
-    }
-
-    $totalCourse = count($courseList);
-    $counter = 0;
-
-    foreach ($courseList as $courseData) {
-        $courseId = $courseData['id'];
-        if ($debug) {
-            error_log('Updating course: '.$courseData['code']);
-        }
-
-        $sql = "SELECT * FROM c_item_property WHERE c_id = $courseId";
-        $result = $connection->fetchAll($sql);
-
-        foreach ($result as $item) {
-            //$courseId = $item['c_id'];
-            $sessionId = intval($item['session_id']);
-            $groupId = intval($item['to_group_id']);
-            $iid = $item['iid'];
-            $ref = $item['ref'];
-
-            // Fix group id
-            if (!empty($groupId)) {
-                $sql = "SELECT * FROM c_group_info
-                        WHERE c_id = $courseId AND id = $groupId";
-                $data = $connection->fetchAssoc($sql);
-                if (!empty($data)) {
-                    $newGroupId = $data['iid'];
-                    $sql = "UPDATE c_item_property SET to_group_id = $newGroupId
-                            WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                } else {
-                    // The group does not exists clean this record
-                    $sql = "DELETE FROM c_item_property WHERE iid = $iid";
-                    $connection->executeQuery($sql);
-                }
-            }
-
-            $sql = '';
-            $newId = '';
-            switch ($item['tool']) {
-                case TOOL_LINK:
-                    $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
-                    break;
-                case TOOL_STUDENTPUBLICATION:
-                    $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case TOOL_QUIZ:
-                    $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case TOOL_DOCUMENT:
-                    $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case TOOL_FORUM:
-                    $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND id = $ref";
-                    break;
-                case 'thread':
-                    $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND id = $ref";
-                    break;
-            }
-
-            if (!empty($sql) && !empty($newId)) {
-                $data = $connection->fetchAssoc($sql);
-                if (isset($data['iid'])) {
-                    $newId = $data['iid'];
-                }
-                $sql = "UPDATE c_item_property SET ref = $newId WHERE iid = $iid";
-                error_log($sql);
-                $connection->executeQuery($sql);
-            }
-
-            if ($debug) {
-                // Print a status in the log once in a while
-                error_log("Process item #$counter/$totalCourse");
-            }
-            $counter++;
-        }
-    }
-
-    if ($debug) {
-        error_log('update gradebook_link');
-    }
-
-    // Fix gradebook_link
-    $sql = "SELECT * FROM gradebook_link";
-    $result = $connection->fetchAll($sql);
-    foreach ($result as $item) {
-        $courseCode = $item['course_code'];
-        $courseInfo = api_get_course_info($courseCode);
-
-        if (empty($courseInfo)) {
-            continue;
-        }
-        $courseId = $courseInfo['real_id'];
-        $ref = $item['ref_id'];
-        $iid = $item['id'];
-        $sql = '';
-
-        switch ($item['type']) {
-            case LINK_LEARNPATH:
-                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
-                break;
-            case LINK_STUDENTPUBLICATION:
-                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
-                break;
-            case LINK_EXERCISE:
-                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
-                break;
-            case LINK_ATTENDANCE:
-                //$sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
-                break;
-            case LINK_FORUM_THREAD:
-                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
-                break;
-        }
-
-        if (!empty($sql)) {
-            $data = $connection->fetchAssoc($sql);
-            if (isset($data) && isset($data['iid'])) {
-                $newId = $data['iid'];
-                $sql = "UPDATE gradebook_link SET ref_id = $newId
-                        WHERE id = $iid";
-                $connection->executeQuery($sql);
-            }
-        }
-    }
-
-    if ($debug) {
-        error_log('update groups');
-    }
-
-    $sql = "SELECT * FROM groups";
-    $result = $connection->executeQuery($sql);
-    $groups = $result->fetchAll();
-
-    $oldGroups = array();
-
-    if (!empty($groups)) {
-        foreach ($groups as $group) {
-            if (empty($group['name'])) {
-                continue;
-            }
-
-            /*$group['description'] = Database::escape_string($group['description']);
-            $group['name'] = Database::escape_string($group['name']);
-            $sql = "INSERT INTO usergroup (name, group_type, description, picture, url, visibility, updated_at, created_at)
-                    VALUES ('{$group['name']}', '1', '{$group['description']}', '{$group['picture_uri']}', '{$group['url']}', '{$group['visibility']}', '{$group['updated_on']}', '{$group['created_on']}')";
-            */
-            $params = [
-                'name' => $group['name'],
-                'description' => $group['description'],
-                'group_type' => 1,
-                'picture' => $group['picture_uri'],
-                'url' => $group['url'],
-                'visibility' => $group['visibility'],
-                'updated_at' => $group['updated_on'],
-                'created_at' => $group['created_on']
-            ];
-            $connection->insert('usergroup', $params);
-            //$connection->executeQuery($sql);
-            $id = $connection->lastInsertId('id');
-            $oldGroups[$group['id']] = $id;
-        }
-    }
-
-    if (!empty($oldGroups)) {
-        foreach ($oldGroups as $oldId => $newId) {
-            $path = \GroupPortalManager::get_group_picture_path_by_id(
-                $oldId,
-                'system'
-            );
-
-            if (!empty($path)) {
-                $newPath = str_replace(
-                    "groups/$oldId/",
-                    "groups/$newId/",
-                    $path['dir']
-                );
-                $command = "mv {$path['dir']} $newPath ";
-                system($command);
-            }
-        }
-
-        $sql = "SELECT * FROM group_rel_user";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']])) {
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-                    $sql = "INSERT INTO usergroup_rel_user (usergroup_id, user_id, relation_type)
-                            VALUES ('{$data['group_id']}', '{$data['user_id']}', '{$data['relation_type']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-
-        $sql = "SELECT * FROM group_rel_group";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']]) && isset($oldGroups[$data['subgroup_id']])) {
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-                    $data['subgroup_id'] = $oldGroups[$data['subgroup_id']];
-                    $sql = "INSERT INTO usergroup_rel_usergroup (group_id, subgroup_id, relation_type)
-                            VALUES ('{$data['group_id']}', '{$data['subgroup_id']}', '{$data['relation_type']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-
-        $sql = "SELECT * FROM announcement_rel_group";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']])) {
-                    // Deleting relation
-                    $sql = "DELETE FROM announcement_rel_group WHERE group_id = {$data['group_id']}";
-                    $connection->executeQuery($sql);
-
-                    // Add new relation
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-                    $sql = "INSERT INTO announcement_rel_group(group_id, announcement_id)
-                            VALUES ('{$data['group_id']}', '{$data['announcement_id']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-
-        $sql = "SELECT * FROM group_rel_tag";
-        $result = $connection->executeQuery($sql);
-        $dataList = $result->fetchAll();
-        if (!empty($dataList)) {
-            foreach ($dataList as $data) {
-                if (isset($oldGroups[$data['group_id']])) {
-                    $data['group_id'] = $oldGroups[$data['group_id']];
-                    $sql = "INSERT INTO usergroup_rel_tag (tag_id, usergroup_id)
-                            VALUES ('{$data['tag_id']}', '{$data['group_id']}')";
-                    $connection->executeQuery($sql);
-                }
-            }
-        }
-    }
-
-    if ($debug) {
-        error_log('update extra fields');
-    }
-
-    // Extra fields
-    $extraFieldTables = [
-        ExtraField::USER_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_USER_FIELD),
-        ExtraField::COURSE_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
-        //ExtraField::LP_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_LP_FIELD),
-        ExtraField::SESSION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
-        //ExtraField::CALENDAR_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
-        //ExtraField::QUESTION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
-        //ExtraField::USER_FIELD_TYPE => //Database::get_main_table(TABLE_MAIN_SPECIFIC_FIELD),
-    ];
-
-    foreach ($extraFieldTables as $type => $table) {
-        //continue;
-        $sql = "SELECT * FROM $table ";
-        if ($debug) {
-            error_log($sql);
-        }
-        $result = $connection->query($sql);
-        $fields = $result->fetchAll();
-
-        foreach ($fields as $field) {
-            if ($debug) {
-                error_log("Loading field: ".$field['field_variable']);
-            }
-            $originalId = $field['id'];
-            $extraField = new ExtraField();
-            $extraField
-                ->setExtraFieldType($type)
-                ->setVariable($field['field_variable'])
-                ->setFieldType($field['field_type'])
-                ->setDisplayText($field['field_display_text'])
-                ->setDefaultValue($field['field_default_value'])
-                ->setFieldOrder($field['field_order'])
-                ->setVisible($field['field_visible'])
-                ->setChangeable($field['field_changeable'])
-                ->setFilter($field['field_filter']);
-
-            $em->persist($extraField);
-            $em->flush();
-
-            $values = array();
-            $handlerId = null;
-            switch ($type) {
-                case ExtraField::USER_FIELD_TYPE:
-                    $optionTable = Database::get_main_table(
-                        TABLE_MAIN_USER_FIELD_OPTIONS
-                    );
-                    $valueTable = Database::get_main_table(
-                        TABLE_MAIN_USER_FIELD_VALUES
-                    );
-                    $handlerId = 'user_id';
-                    break;
-                case ExtraField::COURSE_FIELD_TYPE:
-                    $optionTable = Database::get_main_table(
-                        TABLE_MAIN_COURSE_FIELD_OPTIONS
-                    );
-                    $valueTable = Database::get_main_table(
-                        TABLE_MAIN_COURSE_FIELD_VALUES
-                    );
-                    $handlerId = 'c_id';
-                    break;
-                case ExtraField::SESSION_FIELD_TYPE:
-                    $optionTable = Database::get_main_table(
-                        TABLE_MAIN_SESSION_FIELD_OPTIONS
-                    );
-                    $valueTable = Database::get_main_table(
-                        TABLE_MAIN_SESSION_FIELD_VALUES
-                    );
-                    $handlerId = 'session_id';
-                    break;
-            }
-
-            if (!empty($optionTable)) {
-                $sql = "SELECT * FROM $optionTable WHERE field_id = $originalId ";
-                $result = $connection->query($sql);
-                $options = $result->fetchAll();
-
-                foreach ($options as $option) {
-                    $extraFieldOption = new ExtraFieldOptions();
-                    $extraFieldOption
-                        ->setDisplayText($option['option_display_text'])
-                        ->setField($extraField)
-                        ->setOptionOrder($option['option_order'])
-                        ->setValue($option['option_value']);
-                    $em->persist($extraFieldOption);
-                    $em->flush();
-                }
-
-                $sql = "SELECT * FROM $valueTable WHERE field_id = $originalId ";
-                $result = $connection->query($sql);
-                $values = $result->fetchAll();
-                if ($debug) {
-                    error_log("Fetch all values for field");
-                }
-            }
-
-            if (!empty($values)) {
-                if ($debug) {
-                    error_log("Saving field value in new table");
-                }
-                $k = 0;
-                foreach ($values as $value) {
-                    if (isset($value[$handlerId])) {
-                        /*
-                        $extraFieldValue = new ExtraFieldValues();
-                        $extraFieldValue
-                            ->setValue($value['field_value'])
-                            ->setField($extraField)
-                            ->setItemId($value[$handlerId]);
-                        $em->persist($extraFieldValue);
-                        $em->flush();
-                        */
-                        // Insert without the use of the entity as it reduces
-                        // speed to 2 records per second (much too slow)
-                        $params = [
-                            'field_id' => $extraField->getId(),
-                            'value' => $value['field_value'],
-                            'item_id' => $value[$handlerId]
-                        ];
-                        $connection->insert('extra_field_values', $params);
-                        if ($debug && ($k % 10000 == 0)) {
-                            error_log("Saving field $k");
-                    }
-                        $k++;
-                    }
-                }
-            }
-        }
-    }
-
-    if ($debug) {
-        error_log('Remove index');
-    }
-
-    // Drop temporary indexes added to increase speed of this function's queries
-    $sql = "ALTER TABLE c_document DROP INDEX tmpidx_doc";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_student_publication DROP INDEX tmpidx_stud";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_quiz DROP INDEX tmpidx_quiz";
-    $connection->executeQuery($sql);
-    $sql = "ALTER TABLE c_item_property DROP INDEX tmpidx_ip";
-    $connection->executeQuery($sql);
-
-    if ($debug) {
-        error_log('Finish fixId function');
-    }
-}
-
-/**
- *
- * After the schema was created (table creation), the function adds
- * admin/platform information.
- *
- * @param EntityManager $manager
- * @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 finishInstallation(
-    $manager,
-    $sysPath,
-    $encryptPassForm,
-    $passForm,
-    $adminLastName,
-    $adminFirstName,
-    $loginForm,
-    $emailForm,
-    $adminPhoneForm,
-    $languageForm,
-    $institutionForm,
-    $institutionUrlForm,
-    $siteName,
-    $allowSelfReg,
-    $allowSelfRegProf,
-    $installationProfile = ''
-) {
-    $sysPath = !empty($sysPath) ? $sysPath : api_get_path(SYS_PATH);
-
-    // Inserting data
-    $data = file_get_contents($sysPath.'main/install/data.sql');
-    $result = $manager->getConnection()->prepare($data);
-    $result->execute();
-    $result->closeCursor();
-
-    UserManager::setPasswordEncryption($encryptPassForm);
-
-    // Create admin user.
-    UserManager::create_user(
-        $adminFirstName,
-        $adminLastName,
-        1,
-        $emailForm,
-        $loginForm,
-        $passForm,
-        'ADMIN', //$official_code = '',
-        $languageForm,
-        $adminPhoneForm,
-        '', //$picture_uri = '',
-        PLATFORM_AUTH_SOURCE,
-        '',//$expirationDate,
-        1,
-        0,
-        null,
-        '',
-        false,  //$send_mail = false,
-        true //$isAdmin = false
-    );
-
-    // Create anonymous user.
-    UserManager::create_user(
-        'Joe',
-        'Anonymous',
-        6,
-        'anonymous@localhost',
-        'anon',
-        'anon',
-        'anonymous', //$official_code = '',
-        $languageForm,
-        '',
-        '', //$picture_uri = '',
-        PLATFORM_AUTH_SOURCE,
-        '',
-        1,
-        0,
-        null,
-        '',
-        false,  //$send_mail = false,
-        false //$isAdmin = false
-    );
-
-    // Set default language
-    $sql = "UPDATE language SET available=1 WHERE dokeos_folder = '$languageForm'";
-    Database::query($sql);
-
-    // 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 = '')
-{
-    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 ($params === false or $params === null) {
-        return false;
-    }
-    $settings = $params->params;
-    if (!empty($params->parent)) {
-        installProfileSettings($params->parent);
-    }
-    foreach ($settings as $id => $param) {
-        $sql = "UPDATE settings_current
-                SET selected_value = '".$param->selected_value."'
-                WHERE variable = '".$param->variable."'";
-        if (!empty($param->subkey)) {
-            $sql .= " AND subkey='" . $param->subkey . "'";
-        }
-        Database::query($sql);
-    }
-
-    return true;
-}

+ 0 - 59
main/install/install_files.inc.php

@@ -1,59 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Install the Chamilo files
- * Notice : This script has to be included by install/index.php
- *
- * The script creates two files:
- * - configuration.php, the file that contains very important info for Chamilo
- *   such as the database names.
- * - .htaccess file (in the courses directory) that is optional but improves
- *   security
- *
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Write the system config file
-    write_system_config_file(api_get_path(CONFIGURATION_PATH) . 'configuration.php');
-
-    // Write a distribution file with the config as a backup for the admin
-    //write_system_config_file(api_get_path(CONFIGURATION_PATH) . 'configuration.dist.php');
-
-    // Write a .htaccess file in the course repository
-    //write_courses_htaccess_file($urlAppendPath);
-
-    // Copy distribution files with renaming for being the actual system configuration files.
-    copy(
-        api_get_path(CONFIGURATION_PATH) . 'add_course.conf.dist.php',
-        api_get_path(CONFIGURATION_PATH) . 'add_course.conf.php'
-    );
-    copy(
-        api_get_path(CONFIGURATION_PATH) . 'course_info.conf.dist.php',
-        api_get_path(CONFIGURATION_PATH) . 'course_info.conf.php'
-    );
-    copy(
-        api_get_path(CONFIGURATION_PATH) . 'mail.conf.dist.php',
-        api_get_path(CONFIGURATION_PATH) . 'mail.conf.php'
-    );
-    copy(
-        api_get_path(CONFIGURATION_PATH) . 'profile.conf.dist.php',
-        api_get_path(CONFIGURATION_PATH) . 'profile.conf.php'
-    );
-    copy(
-        api_get_path(CONFIGURATION_PATH) . 'events.conf.dist.php',
-        api_get_path(CONFIGURATION_PATH) . 'events.conf.php'
-    );
-    copy(
-        api_get_path(CONFIGURATION_PATH) . 'auth.conf.dist.php',
-        api_get_path(CONFIGURATION_PATH) . 'auth.conf.php'
-    );
-    copy(
-        api_get_path(CONFIGURATION_PATH) . 'portfolio.conf.dist.php',
-        api_get_path(CONFIGURATION_PATH) . 'portfolio.conf.php'
-    );
-} else {
-    echo 'You are not allowed here !' . __FILE__;
-}

+ 0 - 78
main/install/update-configuration.inc.php

@@ -1,78 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- *
- * Chamilo LMS
- *
- * Only updates the  main/inc/conf/configuration.php
- * @package chamilo.install
- */
-if (defined('SYSTEM_INSTALLATION')) {
-
-    error_log("Starting " . basename(__FILE__));
-    $perm = api_get_permissions_for_new_files();
-
-    $oldConfFile = api_get_path(SYS_CODE_PATH) . 'inc/conf/configuration.php';
-    $newConfFile = api_get_path(CONFIGURATION_PATH) . 'configuration.php';
-
-    if (file_exists($oldConfFile)) {
-        copy($oldConfFile, $newConfFile);
-        @chmod($newConfFile, $perm);
-        @rmdir($oldConfFile);
-    }
-
-    // Edit the configuration file.
-    $file = file($newConfFile);
-    $fh = fopen($newConfFile, 'w');
-
-    $found_version_old = false;
-    $found_stable_old = false;
-    $found_version = false;
-    $found_stable = false;
-    $found_software_name = false;
-    $found_software_url = false;
-
-    foreach ($file as $line) {
-        $ignore = false;
-        if (stripos($line, '$_configuration[\'system_version\']') !== false) {
-            $found_version = true;
-            $line = '$_configuration[\'system_version\'] = \'' . $new_version . '\';' . "\r\n";
-       } elseif (stripos($line, '$_configuration[\'system_stable\']') !== false) {
-            $found_stable = true;
-            $line = '$_configuration[\'system_stable\'] = ' . ($new_version_stable ? 'true' : 'false') . ';' . "\r\n";
-        } elseif (stripos($line, '$_configuration[\'software_name\']') !== false) {
-            $found_software_name = true;
-            $line = '$_configuration[\'software_name\'] = \'' . $software_name . '\';' . "\r\n";
-        } elseif (stripos($line, '$_configuration[\'software_url\']') !== false) {
-            $found_software_url = true;
-            $line = '$_configuration[\'software_url\'] = \'' . $software_url . '\';' . "\r\n";
-        } elseif (stripos($line, '$userPasswordCrypted') !== false) {
-            $line = '$_configuration[\'password_encryption\'] = \'' .$userPasswordCrypted.'\';' . "\r\n";
-        } elseif (stripos($line, '?>') !== false) {
-            $ignore = true;
-        }
-        if (!$ignore) {
-            fwrite($fh, $line);
-        }
-    }
-
-    if (!$found_version) {
-        fwrite($fh, '$_configuration[\'system_version\'] = \'' . $new_version . '\';' . "\r\n");
-    }
-    if (!$found_stable) {
-        fwrite($fh, '$_configuration[\'system_stable\'] = ' . ($new_version_stable ? 'true' : 'false') . ';' . "\r\n");
-    }
-    if (!$found_software_name) {
-        fwrite($fh, '$_configuration[\'software_name\'] = \'' . $software_name . '\';' . "\r\n");
-    }
-    if (!$found_software_url) {
-        fwrite($fh, '$_configuration[\'software_url\'] = \'' . $software_url . '\';' . "\r\n");
-    }
-    fwrite($fh, '?>');
-    fclose($fh);
-
-    error_log("configuration.php file updated.");
-} else {
-    echo 'You are not allowed here !'. __FILE__;
-}

+ 0 - 260
main/install/update-files-1.9.0-1.10.0.inc.php

@@ -1,260 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-use Symfony\Component\Filesystem\Filesystem;
-use Symfony\Component\Finder\Finder;
-
-/**
- * Chamilo LMS
- *
- * Updates the Chamilo files from version 1.9.0 to version 1.10.0
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * @package chamilo.install
- */
-error_log("Starting " . basename(__FILE__));
-
-global $debug;
-
-if (defined('SYSTEM_INSTALLATION')) {
-    // Changes for 1.10.x
-    // Delete directories and files that are not necessary anymore
-    // pChart (1) lib, etc
-
-    // Delete the "chat" file in all language directories, as variables have been moved to the trad4all file
-    $langPath = api_get_path(SYS_CODE_PATH).'lang/';
-    // Only erase files from Chamilo languages (not sublanguages defined by the users)
-    $officialLanguages = array(
-        'arabic',
-        'asturian',
-        'basque',
-        'bengali',
-        'bosnian',
-        'brazilian',
-        'bulgarian',
-        'catalan',
-        'croatian',
-        'czech',
-        'danish',
-        'dari',
-        'dutch',
-        'english',
-        'esperanto',
-        'faroese',
-        'finnish',
-        'french',
-        'friulian',
-        'galician',
-        'georgian',
-        'german',
-        'greek',
-        'hebrew',
-        'hindi',
-        'hungarian',
-        'indonesian',
-        'italian',
-        'japanese',
-        'korean',
-        'latvian',
-        'lithuanian',
-        'macedonian',
-        'malay',
-        'norwegian',
-        'occitan',
-        'pashto',
-        'persian',
-        'polish',
-        'portuguese',
-        'quechua_cusco',
-        'romanian',
-        'russian',
-        'serbian',
-        'simpl_chinese',
-        'slovak',
-        'slovenian',
-        'somali',
-        'spanish',
-        'spanish_latin',
-        'swahili',
-        'swedish',
-        'tagalog',
-        'thai',
-        'tibetan',
-        'trad_chinese',
-        'turkish',
-        'ukrainian',
-        'vietnamese',
-        'xhosa',
-        'yoruba',
-    );
-
-    $filesToDelete = array(
-        'accessibility',
-        'admin',
-        'agenda',
-        'announcements',
-        'blog',
-        'chat',
-        'coursebackup',
-        'course_description',
-        'course_home',
-        'course_info',
-        'courses',
-        'create_course',
-        'document',
-        'dropbox',
-        'exercice',
-        'external_module',
-        'forum',
-        'glossary',
-        'gradebook',
-        'group',
-        'help',
-        'import',
-        'index',
-        'install',
-        'learnpath',
-        'link',
-        'md_document',
-        'md_link',
-        'md_mix',
-        'md_scorm',
-        'messages',
-        'myagenda',
-        'notebook',
-        'notification',
-        'registration',
-        'reservation',
-        'pedaSuggest',
-        'resourcelinker',
-        'scorm',
-        'scormbuilder',
-        'scormdocument',
-        'slideshow',
-        'survey',
-        'tracking',
-        'userInfo',
-        'videoconf',
-        'wiki',
-        'work',
-    );
-
-    $list = scandir($langPath);
-    foreach ($list as $entry) {
-        if (is_dir($langPath . $entry) &&
-            in_array($entry, $officialLanguages)
-        ) {
-            foreach ($filesToDelete as $file) {
-                if (is_file($langPath . $entry . '/' . $file . '.inc.php')) {
-                    unlink($langPath . $entry . '/' . $file . '.inc.php');
-                }
-            }
-        }
-    }
-
-    if ($debug) {
-        error_log('Cleaning folders');
-    }
-
-    // Remove the "main/conference/" directory that wasn't used since years long
-    // past - see rrmdir function declared below
-    @rrmdir(api_get_path(SYS_CODE_PATH).'conference');
-    // Other files that we renamed
-    // events.lib.inc.php has been renamed to events.lib.php
-    if (is_file(api_get_path(LIBRARY_PATH).'events.lib.inc.php')) {
-        @unlink(api_get_path(LIBRARY_PATH).'events.lib.inc.php');
-    }
-
-    if (is_file(api_get_path(SYS_PATH).'courses/.htaccess')) {
-        unlink(api_get_path(SYS_PATH).'courses/.htaccess');
-    }
-
-    // Move dirs into new structures.
-    $movePathList = [
-        api_get_path(SYS_CODE_PATH).'upload/users/groups' => api_get_path(SYS_UPLOAD_PATH),
-        api_get_path(SYS_CODE_PATH).'upload/users' => api_get_path(SYS_UPLOAD_PATH),
-        api_get_path(SYS_CODE_PATH).'upload/badges' => api_get_path(SYS_UPLOAD_PATH),
-        api_get_path(SYS_PATH).'courses' => api_get_path(SYS_APP_PATH),
-        api_get_path(SYS_PATH).'searchdb' => api_get_path(SYS_UPLOAD_PATH).'plugins/xapian/',
-        api_get_path(SYS_PATH).'home' => api_get_path(SYS_APP_PATH)
-    ];
-
-    if ($debug) {
-        error_log('Moving folders');
-    }
-
-    foreach ($movePathList as $origin => $destination) {
-        if (is_dir($origin)) {
-            move($origin, $destination, true, true);
-        }
-    }
-
-    // Delete all "courses/ABC/index.php" files.
-
-    if ($debug) {
-        error_log('Deleting old courses/ABC/index.php files');
-    }
-    $finder = new Finder();
-
-    $courseDir = api_get_path(SYS_APP_PATH).'courses';
-    if (is_dir($courseDir)) {
-        $dirs = $finder->directories()->in($courseDir);
-        $fs = new Filesystem();
-        /** @var Symfony\Component\Finder\SplFileInfo $dir */
-        foreach ($dirs as $dir) {
-            $indexFile = $dir->getPath().'/index.php';
-            if ($debug) {
-                error_log('Deleting '.$indexFile);
-            }
-            if ($fs->exists($indexFile)) {
-                $fs->remove($indexFile);
-            }
-        }
-    }
-
-    // Remove old "courses" folder if empty
-    $originalCourseDir = api_get_path(SYS_PATH).'courses';
-
-    if (is_dir($originalCourseDir)) {
-        $dirs = $finder->directories()->in($originalCourseDir);
-        $files = $finder->directories()->in($originalCourseDir);
-        $dirCount = $dirs->count();
-        $fileCount = $dirs->count();
-        if ($fileCount == 0 && $dirCount == 0) {
-            @rrmdir(api_get_path(SYS_PATH).'courses');
-        }
-    }
-
-    if ($debug) {
-        error_log('Remove archive folder');
-    }
-
-    // Remove archive
-    @rrmdir(api_get_path(SYS_PATH).'archive');
-
-} else {
-    echo 'You are not allowed here !'. __FILE__;
-}
-
-/**
- * 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 (filetype($dir."/".$object) == "dir") {
-                    @rrmdir($dir."/".$object);
-                } else {
-                    @unlink($dir."/".$object);
-                }
-            }
-        }
-        reset($objects);
-        rmdir($dir);
-    }
-}