$email = trim(api_utf8_decode($node_user->Email));
             $official_code = trim(api_utf8_decode($node_user->OfficialCode));
             $phone = trim(api_utf8_decode($node_user->Phone));
             $status = trim(api_utf8_decode($node_user->Status));
             switch ($status) {
                 case 'student':
                     $status = 5;
                     break;
                 case 'teacher':
                     $status = 1;
                     break;
                 default:
                     $status = 5;
                     $error_message .= get_lang('StudentStatusWasGivenTo') . ' : ' . $username . '<br />';
             }
             $sql = "UPDATE {$tbl_user} SET\n                                    lastname = '" . Database::escape_string($lastname) . "',\n                                    firstname = '" . Database::escape_string($firstname) . "',\n                                    " . (empty($password) ? "" : "password = '******',") . "\n                                    email = '" . Database::escape_string($email) . "',\n                                    official_code = '" . Database::escape_string($official_code) . "',\n                                    phone = '" . Database::escape_string($phone) . "',\n                                    status = '" . intval($status) . "'\n                                WHERE username = '******'";
             Database::query($sql);
         }
     }
 }
 // Creating  courses from <Sessions> <Courses> base node.
 if (count($root->Courses->Course) > 0) {
     foreach ($root->Courses->Course as $courseNode) {
         $params = array();
         if (empty($courseNode->CourseTitle)) {
             $params['title'] = api_utf8_decode($courseNode->CourseCode);
         } else {
             $params['title'] = api_utf8_decode($courseNode->CourseTitle);
         }
         $params['wanted_code'] = api_utf8_decode($courseNode->CourseCode);
         $params['tutor_name'] = null;
Example #2
0
 /**
  * @param string $file
  * @param bool $moveFile
  */
 private function importStudents($file, $moveFile = true)
 {
     $data = Import::csv_to_array($file);
     /*
     * Another users import.
             Unique identifier: official code and username . ok
             Password should never get updated. ok
             If an update should need to occur (because it changed in the .csv),
             we’ll want that logged. We will handle this manually in that case.
             All other fields should be updateable, though passwords should of course not get updated. ok
             If a user gets deleted (not there anymore),
             He should be set inactive one year after the current date.
             So I presume you’ll just update the expiration date.
             We want to grant access to courses up to a year after deletion.
     */
     if (!empty($data)) {
         $language = $this->defaultLanguage;
         $this->logger->addInfo(count($data) . " records found.");
         foreach ($data as $row) {
             $row = $this->cleanUserRow($row);
             $user_id = UserManager::get_user_id_from_original_id($row['extra_' . $this->extraFieldIdNameList['user']], $this->extraFieldIdNameList['user']);
             $userInfo = array();
             $userInfoByOfficialCode = null;
             if (!empty($user_id)) {
                 $userInfo = api_get_user_info($user_id);
                 $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
             }
             $expirationDate = api_get_utc_datetime(strtotime("+" . intval($this->expirationDateInUserCreation) . "years"));
             if (empty($userInfo) && empty($userInfoByOfficialCode)) {
                 // Create user
                 $result = UserManager::create_user($row['firstname'], $row['lastname'], STUDENT, $row['email'], $row['username'], $row['password'], $row['official_code'], $language, $row['phone'], null, $row['auth_source'], $expirationDate, 1, 0, null, null, false);
                 if ($result) {
                     foreach ($row as $key => $value) {
                         if (substr($key, 0, 6) == 'extra_') {
                             //an extra field
                             UserManager::update_extra_field_value($result, substr($key, 6), $value);
                         }
                     }
                     $this->logger->addInfo("Students - User created: " . $row['username']);
                 } else {
                     $this->logger->addError("Students - User NOT created: " . $row['username'] . " " . $row['firstname'] . " " . $row['lastname']);
                 }
             } else {
                 if (empty($userInfo)) {
                     $this->logger->addError("Students - Can't update user :"******"Students - User email is not updated : " . $row['username'] . " because the avoid conditions (email).");
                             // Do not change email keep the old email.
                             $email = $userInfo['email'];
                         }
                         // 2. Condition
                         if (!in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
                             $email = $userInfo['email'];
                         }
                         // 3. Condition
                         if (in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
                             $email = $row['email'];
                         }
                         // Blocking password update
                         $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
                         if ($userInfo['password'] != api_get_encrypted_password($row['password']) && in_array($row['password'], $avoidUsersWithPassword)) {
                             $this->logger->addInfo("Students - User password is not updated: " . $row['username'] . " because the avoid conditions (password).");
                             $password = null;
                             $resetPassword = 0;
                             // disallow password change
                         }
                     }
                 }
                 $expirationDate = api_get_utc_datetime(strtotime("+" . intval($this->expirationDateInUserUpdate) . "years"));
                 // Update user
                 $result = UserManager::update_user($userInfo['user_id'], $row['firstname'], $row['lastname'], $row['username'], $password, $row['auth_source'], $email, STUDENT, $userInfo['official_code'], $userInfo['phone'], $userInfo['picture_uri'], $expirationDate, $userInfo['active'], null, 0, null, null, null, false, $resetPassword);
                 if ($result) {
                     if ($row['username'] != $userInfo['username']) {
                         $this->logger->addInfo("Students - Username was changes from '" . $userInfo['username'] . "' to '" . $row['username'] . "' ");
                     }
                     foreach ($row as $key => $value) {
                         if (substr($key, 0, 6) == 'extra_') {
                             //an extra field
                             UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
                         }
                     }
                     $this->logger->addInfo("Students - User updated: " . $row['username']);
                 } else {
                     $this->logger->addError("Students - User NOT updated: " . $row['username'] . " " . $row['firstname'] . " " . $row['lastname']);
                 }
             }
         }
     }
     if ($moveFile) {
         $this->moveFile($file);
     }
 }
Example #3
0
 if ($cas_login && empty($_POST['login'])) {
     $login = $cas_login;
 } else {
     $login = $_POST['login'];
     $password = $_POST['password'];
 }
 //Lookup the user in the main database
 $user_table = Database::get_main_table(TABLE_MAIN_USER);
 $sql = "SELECT user_id, username, auth_source, password FROM {$user_table}\n                WHERE username = '******'";
 $result = Database::query($sql);
 // @todo use a UserProvider
 if (Database::num_rows($result) > 0) {
     $uData = Database::fetch_array($result);
     if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE || $uData['auth_source'] == CAS_AUTH_SOURCE) {
         //The authentification of this user is managed by Chamilo itself
         $password = api_get_encrypted_password(trim(stripslashes($password)));
         // Check the user's password
         if (($password == $uData['password'] or $cas_login) and trim($login) == $uData['username']) {
             $uData = api_get_user_info($uData['user_id'], false, false, true);
             $extraFields = $uData['extra_fields'];
             // $update_type = UserManager::get_extra_user_data_by_field($uData['user_id'], 'update_type');
             $update_type = isset($extraFields['extra_update_type']) ? $extraFields['extra_update_type'] : null;
             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') or $uData['expiration_date'] == '0000-00-00 00:00:00') {
                     global $_configuration;
                     if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
Example #4
0
 /**
  * Resets a password
  * @author Olivier Cauberghe <*****@*****.**>, 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();
         $crypted = api_get_encrypted_password($user['password']);
         $sql = "UPDATE " . $tbl_user . " SET password='******' WHERE user_id = {$id}";
         Database::query($sql);
         return self::send_password_to_user($user, $by_username);
     } else {
         return get_lang('NotAllowed');
     }
 }
function WSEditUser($params)
{
    global $_configuration;
    if (!WSHelperVerifyKey($params)) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
    $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
    $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
    $original_user_id_value = $params['original_user_id_value'];
    $original_user_id_name = $params['original_user_id_name'];
    $firstname = $params['firstname'];
    $lastname = $params['lastname'];
    $username = $params['username'];
    $password = null;
    $auth_source = null;
    $email = $params['email'];
    $status = $params['status'];
    $official_code = '';
    $phone = $params['phone'];
    $picture_uri = '';
    $expiration_date = $params['expiration_date'];
    $active = 1;
    $creator_id = null;
    $hr_dept_id = 0;
    $extra = null;
    $extra_list = $params['extra'];
    if (!empty($params['password'])) {
        $password = $params['password'];
    }
    // Get user id from id wiener
    $user_id = UserManager::get_user_id_from_original_id($original_user_id_value, $original_user_id_name);
    if ($user_id == 0) {
        return 0;
    } else {
        $sql = "SELECT user_id FROM {$table_user} WHERE user_id ='{$user_id}' AND active= '0'";
        $resu = Database::query($sql);
        $r_check_user = Database::fetch_row($resu);
        if (!empty($r_check_user[0])) {
            return 0;
        }
    }
    // Check whether username already exits.
    $sql = "SELECT username FROM {$table_user} WHERE username = '******' AND user_id <> '{$user_id}'";
    $res_un = Database::query($sql);
    $r_username = Database::fetch_row($res_un);
    if (!empty($r_username[0])) {
        return 0;
    }
    // Edit lastname an firstname only if not empty
    $sql = "UPDATE {$table_user} SET ";
    if (!empty($lastname)) {
        $sql .= " lastname='" . Database::escape_string($lastname) . "', ";
    }
    if (!empty($firstname)) {
        $sql .= " firstname='" . Database::escape_string($firstname) . "', ";
    }
    $sql .= " username='******',";
    if (!is_null($password)) {
        $password = $_configuration['password_encryption'] ? api_get_encrypted_password($password) : $password;
        $sql .= " password='******',";
    }
    if (!is_null($auth_source)) {
        $sql .= " auth_source='" . Database::escape_string($auth_source) . "',";
    }
    $sqladmin = "SELECT user_id FROM {$t_admin} WHERE user_id = " . intval($user_id);
    $resadmin = Database::query($sqladmin);
    $is_admin = Database::num_rows($resadmin);
    if (empty($status) && $is_admin) {
        $status = 1;
    } else {
        $status = 5;
    }
    $sql .= "\n            email='" . Database::escape_string($email) . "',\n            status='" . Database::escape_string($status) . "',\n            official_code='" . Database::escape_string($official_code) . "',\n            phone='" . Database::escape_string($phone) . "',\n            picture_uri='" . Database::escape_string($picture_uri) . "',\n            expiration_date='" . Database::escape_string($expiration_date) . "',\n            active='" . Database::escape_string($active) . "',\n            hr_dept_id=" . intval($hr_dept_id);
    if (!is_null($creator_id)) {
        $sql .= ", creator_id='" . Database::escape_string($creator_id) . "'";
    }
    $sql .= " WHERE user_id='{$user_id}'";
    $return = @Database::query($sql);
    if (is_array($extra_list) && count($extra_list) > 0) {
        foreach ($extra_list as $extra) {
            $extra_field_name = $extra['field_name'];
            $extra_field_value = $extra['field_value'];
            // Save the external system's id into user_field_value table.
            $res = UserManager::update_extra_field_value($user_id, $extra_field_name, $extra_field_value);
        }
    }
    return $return;
}
Example #6
0
 }
 // end if datachecked
 /*=============================
   NEW USER REGISTRATION PROCESS
   =============================*/
 if ($dataChecked && !$userExists && !$loginExists) {
     /*---------------------------
           PLATFORM REGISTRATION
       ----------------------------*/
     if ($_cid) {
         $platformStatus = STUDENT;
     } else {
         $platformStatus = $platformStatus;
     }
     // admin section of the platform context...
     $pw = api_get_encrypted_password($password_form);
     $result = Database::query("INSERT INTO {$tbl_user}\n                               SET lastname       = '{$lastname_form}',\n                                   firstname    = '{$firstname_form}',\n                                   username  = '******',\n                                   password  = '******',\n                                   email     = '{$email_form}',\n                                   status    = '{$platformStatus}',\n                                   official_code = '{$official_code_form}',\n                                   creator_id = '" . $_user['user_id'] . "'");
     $userId = Database::insert_id();
     if ($userId) {
         $platformRegSucceed = true;
     }
 }
 if ($userId && $_cid) {
     /*
       Note : As we temporarly use this script in the platform administration
       section to also add user to the platform, We have to prevent course
       registration. That's why we check if $_cid is initialized, it gives us
       an hint about the use context of the script
     */
     /*---------------------------
           COURSE REGISTRATION
/**
 * E-mails list loop
 */
foreach ($list as $mail) {
    $mail = trim($mail);
    $sql = "SELECT user_id, official_code, firstname, lastname, email, username, language FROM {$users} WHERE email = '{$mail}'\n";
    $res = Database::query($sql);
    if ($res === false) {
        echo 'Error in database with email ' . $mail . "\n";
    }
    if (Database::num_rows($res) == 0) {
        echo '[Error] Email not found in database: ' . $row['email'] . "\n";
    } else {
        $row = Database::fetch_assoc($res);
        $pass = api_substr($row['username'], 0, 4) . rand(0, 9) . rand(0, 9);
        $crypass = api_get_encrypted_password($password);
        $sqlu = "UPDATE {$users} SET password='******' WHERE user_id = " . $row['user_id'];
        $resu = Database::query($sqlu);
        if ($resu === false) {
            echo "[Error] Error updating password. Skipping {$mail}\n";
            continue;
        }
        $user = array('FirstName' => $row['firstname'], 'LastName' => $row['lastname'], 'UserName' => $row['username'], 'Password' => $pass, 'Email' => $mail);
        $l = api_get_interface_language();
        if (!empty($row['language'])) {
            $l = $row['language'];
        }
        //This comes from main/admin/user_import.php::save_data() slightly modified
        $recipient_name = api_get_person_name($user['FirstName'], $user['LastName'], null, PERSON_NAME_EMAIL_ADDRESS);
        $emailsubject = '[' . api_get_setting('platform.site_name') . '] ' . get_lang('YourReg', null, $l) . ' ' . api_get_setting('platform.site_name');
        $emailbody = get_lang('Dear', null, $l) . ' ' . api_get_person_name($user['FirstName'], $user['LastName']) . ",\n\n" . get_lang('YouAreReg', null, $l) . " " . api_get_setting('platform.site_name') . " " . get_lang('WithTheFollowingSettings', null, $l) . "\n\n" . get_lang('Username', null, $l) . " : " . $user['UserName'] . "\n" . get_lang('Pass', null, $l) . " : " . $user['Password'] . "\n\n" . get_lang('Address', null, $l) . " " . api_get_setting('platform.site_name') . " " . get_lang('Is', null, $l) . " : " . api_get_path(WEB_PATH) . " \n\n" . get_lang('Problem', null, $l) . "\n\n" . get_lang('Formula', null, $l) . ",\n\n" . api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname')) . "\n" . get_lang('Manager', null, $l) . " " . api_get_setting('platform.site_name') . "\nT. " . api_get_setting('administratorTelephone') . "\n" . get_lang('Email', null, $l) . " : " . api_get_setting('platform.administrator_email') . "";
function WSEditUserWithPicture($params) {
    global $_configuration;

    if(!WSHelperVerifyKey($params)) {
        return return_error(WS_ERROR_SECRET_KEY);
    }

    $table_user = Database :: get_main_table(TABLE_MAIN_USER);
    $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
    $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);

    $original_user_id_value = $params['original_user_id_value'];
    $original_user_id_name = $params['original_user_id_name'];
    $firstname = $params['firstname'];
    $lastname = $params['lastname'];
    $username = $params['username'];
    $password = null;
    $auth_source = null;
    $email = $params['email'];
    $status = $params['status'];
    $official_code = '';
    $phone = $params['phone'];
    $picture_url = $params['picture_url'];
    $picture_uri = '';
    $expiration_date = $params['expiration_date'];
    $active = 1;
    $creator_id = null;
    $hr_dept_id = 0;
    $extra = null;
    $extra_list = $params['extra'];

    if (!empty($params['password'])) { $password = $params['password']; }


    // Get user id from id wiener

    $user_id = UserManager::get_user_id_from_original_id($original_user_id_value, $original_user_id_name);

    // Get picture and generate uri.
    $filename = basename($picture_url);
    $tempdir = sys_get_temp_dir();
    $tempDir = api_get_path(SYS_ARCHIVE_PATH);
    file_put_contents($tempDir.$filename, file_get_contents($picture_url));
    $picture_uri = UserManager::update_user_picture($user_id, $filename, $tempDir.$filename);

    if ($user_id == 0) {
        return 0;
    } else {
        $sql = "SELECT user_id FROM $table_user WHERE user_id ='$user_id' AND active= '0'";
        $resu = Database::query($sql);
        $r_check_user = Database::fetch_row($resu);
        if (!empty($r_check_user[0])) {
            return 0;
        }
    }

    // Check whether username already exits.
    $sql = "SELECT username FROM $table_user WHERE username = '******' AND user_id <> '$user_id'";
    $res_un = Database::query($sql);
    $r_username = Database::fetch_row($res_un);

    if (!empty($r_username[0])) {
        return 0;
    }
    // Edit lastname an firstname only if not empty
    $sql = "UPDATE $table_user SET ";
    if (!empty($lastname)) {
        $sql .= " lastname='".Database::escape_string($lastname)."', ";
    }
    if (!empty($firstname)) {
        $sql .= " firstname='".Database::escape_string($firstname)."', ";
    }
    $sql .= " username='******',";
    if (!is_null($password)) {
        $password = $_configuration['password_encryption'] ? api_get_encrypted_password($password) : $password;
        $sql .= " password='******',";
    }
    if (!is_null($auth_source)) {
        $sql .=    " auth_source='".Database::escape_string($auth_source)."',";
    }

    // Exception for admins in case no status is provided in WS call...
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
    $resadmin = Database::query($sqladmin);
    $is_admin = Database::num_rows($resadmin);

    if (empty($status)) {
        $status = 5;
    }

    if ($is_admin) {
        $status = 1;
    }

    $sql .=    "
            email='".Database::escape_string($email)."',
            status='".Database::escape_string($status)."',
            official_code='".Database::escape_string($official_code)."',
            phone='".Database::escape_string($phone)."',
            picture_uri='".Database::escape_string($picture_uri)."',
            expiration_date='".Database::escape_string($expiration_date)."',
            active='".Database::escape_string($active)."',
            hr_dept_id=".intval($hr_dept_id);

    if (!is_null($creator_id)) {
        $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
    }
    $sql .=    " WHERE user_id='$user_id'";
    $return = @Database::query($sql);

    if (is_array($extra_list) && count($extra_list) > 0) {
        foreach ($extra_list as $extra) {
            $extra_field_name = $extra['field_name'];
            $extra_field_value = $extra['field_value'];
            // Save the external system's id into user_field_value table.
            $res = UserManager::update_extra_field_value($user_id, $extra_field_name, $extra_field_value);
        }
    }

    return  $return;
}
Example #9
0
/**
 * Check current user's current password
 * @param    char    password
 * @return    bool true o false
 * @uses Gets user ID from global variable
 */
function check_user_password($password)
{
    global $_user;
    $user_id = api_get_user_id();
    if ($user_id != strval(intval($user_id)) || empty($password)) {
        return false;
    }
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
    $password = api_get_encrypted_password($password);
    $password = Database::escape_string($password);
    $sql_password = "******" . $user_id . "' AND password='******'";
    $result = Database::query($sql_password);
    return Database::num_rows($result) != 0;
}
 /**
  * Update user information with all the parameters passed to this function
  * @param int The ID of the user to be updated
  * @param string The user's firstname
  * @param string The user's lastname
  * @param string The user's username (login)
  * @param string The user's password
  * @param string The authentication source (default: "platform")
  * @param string The user's e-mail address
  * @param int The user's status
  * @param string The user's official code (usually just an internal institutional code)
  * @param string The user's phone number
  * @param string The user's picture URL (internal to the Chamilo directory)
  * @param int The user ID of the person who registered this user (optional, defaults to null)
  * @param int The department of HR in which the user is registered (optional, defaults to 0)
  * @param    array    A series of additional fields to add to this user as extra fields (optional, defaults to null)
  * @return boolean true if the user information was updated
  * @assert (false) === false
  */
 public static function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email = null, $status = STUDENT, $official_code = null, $phone = null, $picture_uri = null, $expiration_date = null, $active = 1, $creator_id = null, $hr_dept_id = 0, $extra = null, $language = 'english', $encrypt_method = '', $send_email = false, $reset_password = 0)
 {
     global $_configuration;
     $original_password = $password;
     $user_info = api_get_user_info($user_id, false, true);
     if ($reset_password == 0) {
         $password = null;
         $auth_source = $user_info['auth_source'];
     } elseif ($reset_password == 1) {
         $original_password = $password = api_generate_password();
         $auth_source = PLATFORM_AUTH_SOURCE;
     } elseif ($reset_password == 2) {
         $password = $password;
         $auth_source = PLATFORM_AUTH_SOURCE;
     } elseif ($reset_password == 3) {
         $password = $password;
         $auth_source = $auth_source;
     }
     if ($user_id != strval(intval($user_id))) {
         return false;
     }
     if ($user_id === false) {
         return false;
     }
     $table_user = Database::get_main_table(TABLE_MAIN_USER);
     //Checking the user language
     $languages = api_get_languages();
     if (!in_array($language, $languages['folder'])) {
         $language = api_get_setting('platformLanguage');
     }
     $sql = "UPDATE {$table_user} SET\n                lastname='" . Database::escape_string($lastname) . "',\n                firstname='" . Database::escape_string($firstname) . "',\n                username='******',\n                language='" . Database::escape_string($language) . "',";
     if (!is_null($password)) {
         if ($encrypt_method == '') {
             $password = api_get_encrypted_password($password);
         } else {
             if ($_configuration['password_encryption'] === $encrypt_method) {
                 if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
                     return api_set_failure('encrypt_method invalid');
                 } else {
                     if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
                         return api_set_failure('encrypt_method invalid');
                     }
                 }
             } else {
                 return api_set_failure('encrypt_method invalid');
             }
         }
         $sql .= " password='******',";
     }
     if (!is_null($auth_source)) {
         $sql .= " auth_source='" . Database::escape_string($auth_source) . "',";
     }
     $sql .= "\n                email='" . Database::escape_string($email) . "',\n                status='" . Database::escape_string($status) . "',\n                official_code='" . Database::escape_string($official_code) . "',\n                phone='" . Database::escape_string($phone) . "',\n                picture_uri='" . Database::escape_string($picture_uri) . "',\n                expiration_date='" . Database::escape_string($expiration_date) . "',\n                active='" . Database::escape_string($active) . "',\n                hr_dept_id=" . intval($hr_dept_id);
     if (!is_null($creator_id)) {
         $sql .= ", creator_id='" . Database::escape_string($creator_id) . "'";
     }
     $sql .= " WHERE user_id = '{$user_id}' ";
     $return = Database::query($sql);
     if (is_array($extra) && count($extra) > 0) {
         $res = true;
         foreach ($extra as $fname => $fvalue) {
             $res = $res && self::update_extra_field_value($user_id, $fname, $fvalue);
         }
     }
     if ($user_info['active'] != $active) {
         self::change_active_state($user_id, $active);
     }
     global $app;
     // Adding user
     /** @var Entity\User $user */
     $em = $app['orm.ems']['db_write'];
     $user = $em->getRepository('Entity\\User')->find($user_id);
     $role = $em->getRepository('Entity\\Role')->find($status);
     $user->getRolesObj()->remove(0);
     $user->getRolesObj()->add($role);
     $em->persist($user);
     $em->flush();
     if (!empty($email) && $send_email) {
         $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
         $emailsubject = '[' . api_get_setting('siteName') . '] ' . get_lang('YourReg') . ' ' . api_get_setting('siteName');
         $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
         $email_admin = api_get_setting('emailAdministrator');
         if ($_configuration['multiple_access_urls']) {
             $access_url_id = api_get_current_access_url_id();
             if ($access_url_id != -1) {
                 $url = api_get_current_access_url_info();
                 $emailbody = get_lang('Dear') . " " . stripslashes(api_get_person_name($firstname, $lastname)) . ",\n\n" . get_lang('YouAreReg') . " " . api_get_setting('siteName') . " " . get_lang('WithTheFollowingSettings') . "\n\n" . get_lang('Username') . " : " . $username . ($reset_password > 0 ? "\n" . get_lang('Pass') . " : " . stripslashes($original_password) : "") . "\n\n" . get_lang('Address') . " " . api_get_setting('siteName') . " " . get_lang('Is') . " : " . $url['url'] . "\n\n" . get_lang('Problem') . "\n\n" . get_lang('Formula') . ",\n\n" . api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')) . "\n" . get_lang('Manager') . " " . api_get_setting('siteName') . "\nT. " . api_get_setting('administratorTelephone') . "\n" . get_lang('Email') . " : " . api_get_setting('emailAdministrator');
             }
         } else {
             $emailbody = get_lang('Dear') . " " . stripslashes(api_get_person_name($firstname, $lastname)) . ",\n\n" . get_lang('YouAreReg') . " " . api_get_setting('siteName') . " " . get_lang('WithTheFollowingSettings') . "\n\n" . get_lang('Username') . " : " . $username . ($reset_password > 0 ? "\n" . get_lang('Pass') . " : " . stripslashes($original_password) : "") . "\n\n" . get_lang('Address') . " " . api_get_setting('siteName') . " " . get_lang('Is') . " : " . $_configuration['root_web'] . "\n\n" . get_lang('Problem') . "\n\n" . get_lang('Formula') . ",\n\n" . api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')) . "\n" . get_lang('Manager') . " " . api_get_setting('siteName') . "\nT. " . api_get_setting('administratorTelephone') . "\n" . get_lang('Email') . " : " . api_get_setting('emailAdministrator');
         }
         @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
     }
     $user_info = api_get_user_info($user_id);
     event_system(LOG_USER_UPDATED, LOG_USER_ID, $user_id, api_get_utc_datetime(), api_get_user_id());
     event_system(LOG_USER_UPDATED, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), api_get_user_id());
     return $return;
 }
 /**
  * Return the encrypted pass
  * @param <String> $pass
  * @return <String> $pass encrypted
  */
 public function encryptPass($pass)
 {
     return api_get_encrypted_password($pass);
 }
Example #12
0
 /**
  * Update user information with all the parameters passed to this function
  * @param int The ID of the user to be updated
  * @param string The user's firstname
  * @param string The user's lastname
  * @param string The user's username (login)
  * @param string The user's password
  * @param string The authentication source (default: "platform")
  * @param string The user's e-mail address
  * @param int The user's status
  * @param string The user's official code (usually just an internal institutional code)
  * @param string The user's phone number
  * @param string The user's picture URL (internal to the Chamilo directory)
  * @param int The user ID of the person who registered this user (optional, defaults to null)
  * @param int The department of HR in which the user is registered (optional, defaults to 0)
  * @param    array    A series of additional fields to add to this user as extra fields (optional, defaults to null)
  * @return boolean true if the user information was updated
  * @assert (false) === false
  */
 public static function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email = null, $status = STUDENT, $official_code = null, $phone = null, $picture_uri = null, $expiration_date = null, $active = 1, $creator_id = null, $hr_dept_id = 0, $extra = null, $language = 'english', $encrypt_method = '', $send_email = false, $reset_password = 0)
 {
     global $_configuration;
     $original_password = $password;
     $user_info = api_get_user_info($user_id, false, true);
     if ($reset_password == 0) {
         $password = null;
         $auth_source = $user_info['auth_source'];
     } elseif ($reset_password == 1) {
         $original_password = $password = api_generate_password();
         $auth_source = PLATFORM_AUTH_SOURCE;
     } elseif ($reset_password == 2) {
         $password = $password;
         $auth_source = PLATFORM_AUTH_SOURCE;
     } elseif ($reset_password == 3) {
         $password = $password;
         $auth_source = $auth_source;
     }
     if ($user_id != strval(intval($user_id))) {
         return false;
     }
     if ($user_id === false) {
         return false;
     }
     // Checking the user language.
     $languages = api_get_platform_isocodes();
     if (!in_array($language, $languages)) {
         $language = Container::getTranslator()->getLocale();
     }
     if (!is_null($password)) {
         if ($encrypt_method == '') {
             $password = api_get_encrypted_password($password);
         } else {
             if ($_configuration['password_encryption'] === $encrypt_method) {
                 if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
                     return api_set_failure('encrypt_method invalid');
                 } else {
                     if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
                         return api_set_failure('encrypt_method invalid');
                     }
                 }
             } else {
                 return api_set_failure('encrypt_method invalid');
             }
         }
     }
     $em = Database::getManager();
     /** @var Chamilo\UserBundle\Entity\User $user */
     $user = $em->getRepository('ChamiloUserBundle:User')->find($user_id);
     if (is_array($extra) && count($extra) > 0) {
         $res = true;
         foreach ($extra as $name => $value) {
             //$userField = $em->getRepository('ChamiloUserBundle:UserField')->findOneByName($name);
             $res = $res && self::update_extra_field_value($user_id, $name, $value);
         }
     }
     if ($user_info['active'] != $active) {
         self::change_active_state($user_id, $active);
     }
     // Updating user
     $user->setLastname($lastname)->setFirstname($firstname)->setUsername($username)->setAuthSource($auth_source)->setLanguage($language)->setEmail($email)->setOfficialCode($official_code)->setPhone($phone)->setPictureUri($picture_uri)->setExpirationDate($expiration_date)->setActive($active)->setHrDeptId($hr_dept_id);
     if (!empty($original_password)) {
         $user->setPlainPassword($original_password);
     }
     if (is_array($status)) {
         foreach ($status as $groupId) {
             $group = $em->getRepository('ChamiloUserBundle:Group')->find($groupId);
             $user->addGroup($group);
         }
     } else {
         $group = $em->getRepository('ChamiloUserBundle:Group')->find($status);
         $user->addGroup($group);
     }
     Container::getUserManager()->updateUser($user, true);
     if (!empty($email) && $send_email) {
         $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
         $emailsubject = '[' . api_get_setting('platform.site_name') . '] ' . get_lang('YourReg') . ' ' . api_get_setting('platform.site_name');
         $sender_name = api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname'), null, PERSON_NAME_EMAIL_ADDRESS);
         $email_admin = api_get_setting('platform.administrator_email');
         $emailbody = null;
         /*api_mail_html($recipient_name, $email, $emailsubject,
           $emailbody, $sender_name, $email_admin);*/
     }
     $user_info = api_get_user_info($user_id);
     Event::addEvent(LOG_USER_UPDATED, LOG_USER_ID, $user_id, api_get_utc_datetime(), api_get_user_id());
     Event::addEvent(LOG_USER_UPDATED, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), api_get_user_id());
     return $user_id;
 }
    /**
     * Update user information with all the parameters passed to this function
     * @param int The ID of the user to be updated
     * @param string The user's firstname
     * @param string The user's lastname
     * @param string The user's username (login)
     * @param string The user's password
     * @param string The authentication source (default: "platform")
     * @param string The user's e-mail address
     * @param int The user's status
     * @param string The user's official code (usually just an internal institutional code)
     * @param string The user's phone number
     * @param string The user's picture URL (internal to the Chamilo directory)
     * @param int The user ID of the person who registered this user (optional, defaults to null)
     * @param int The department of HR in which the user is registered (optional, defaults to 0)
     * @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
     * @return boolean true if the user information was updated
     * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
     */
    public static function update_user(
        $user_id,
        $firstname,
        $lastname,
        $username,
        $password = null,
        $auth_source = null,
        $email,
        $status,
        $official_code,
        $phone,
        $picture_uri,
        $expiration_date,
        $active,
        $creator_id = null,
        $hr_dept_id = 0,
        $extra = null,
        $language = 'english',
        $encrypt_method = '',
        $send_email = false,
        $reset_password = 0
    ) {
        global $_configuration;
        $original_password = $password;

        if (empty($user_id)) { return false; }
        $user_info = api_get_user_info($user_id, false, true);

        if ($reset_password == 0) {
            $password = null;
            $auth_source = $user_info['auth_source'];
        } elseif ($reset_password == 1) {
            $original_password = $password = api_generate_password();
            $auth_source = PLATFORM_AUTH_SOURCE;
        } elseif ($reset_password == 2) {
            $password = $password;
            $auth_source = PLATFORM_AUTH_SOURCE;
        } elseif ($reset_password == 3) {
            $password = $password;
            $auth_source = $auth_source;
        }

        if ($user_id != strval(intval($user_id)))
            return false;
        if ($user_id === false)
            return false;

        $table_user = Database :: get_main_table(TABLE_MAIN_USER);

        //Checking the user language
        $languages = api_get_languages();
        if (!in_array($language, $languages['folder'])) {
            $language = api_get_setting('platformLanguage');
        }
        $change_active = 0;
        if ($user_info['active'] != $active) {
            $change_active = 1;
        }
        $sql = "UPDATE $table_user SET
                lastname='".Database::escape_string($lastname)."',
                firstname='".Database::escape_string($firstname)."',
                username='******',
                language='".Database::escape_string($language)."',";

        if (!is_null($password)) {
            if ($encrypt_method == '') {
                $password = api_get_encrypted_password($password);
            } else {
                if ($_configuration['password_encryption'] === $encrypt_method) {
                    if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
                        return api_set_failure('encrypt_method invalid');
                    } else if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
                        return api_set_failure('encrypt_method invalid');
                    }
                } else {
                    return api_set_failure('encrypt_method invalid');
                }
            }
            $sql .= " password='******',";
        }
        if (!is_null($auth_source)) {
            $sql .= " auth_source='".Database::escape_string($auth_source)."',";
        }
        $sql .= "
                email='".Database::escape_string($email)."',
                status='".Database::escape_string($status)."',
                official_code='".Database::escape_string($official_code)."',
                phone='".Database::escape_string($phone)."',
                picture_uri='".Database::escape_string($picture_uri)."',
                expiration_date='".Database::escape_string($expiration_date)."',
                active='".Database::escape_string($active)."',
                hr_dept_id=".intval($hr_dept_id);
        if (!is_null($creator_id)) {
            $sql .= ", creator_id='".intval($creator_id)."'";
        }
        $sql .= " WHERE user_id='$user_id'";
        $return = Database::query($sql);
        if ($change_active == 1 && $return) {
            if ($active == 1) {
                $event_title = LOG_USER_ENABLE;
            } else {
                $event_title = LOG_USER_DISABLE;
            }
            event_system($event_title, LOG_USER_ID, $user_id);
        }
        if (is_array($extra) && count($extra) > 0) {
            $res = true;
            foreach ($extra as $fname => $fvalue) {
                $res = $res && self::update_extra_field_value($user_id, $fname, $fvalue);
            }
        }

        if (!empty($email) && $send_email) {
            $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
            $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
            $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
            $email_admin = api_get_setting('emailAdministrator');

            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);
                    $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$url['url']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
                }
            } else {
                $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$_configuration['root_web']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
            }
            @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
        }

        return $return;
    }