/** * Creates a new user for the platform * @author Hugues Peeters <*****@*****.**>, * @author Roan Embrechts <*****@*****.**> * @param string Firstname * @param string Lastname * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) * @param string e-mail address * @param string Login * @param string Password * @param string Any official code (optional) * @param string User language (optional) * @param string Phone number (optional) * @param string Picture URI (optional) * @param string Authentication source (optional, defaults to 'platform', dependind on constant) * @param string Account expiration date (optional, defaults to null) * @param int Whether the account is enabled or disabled by default * @param int The department of HR in which the user is registered (optional, defaults to 0) * @param array Extra fields * @param string Encrypt method used if password is given encrypted. Set to an empty string by default * @param bool $send_mail * @param bool $isAdmin * * @return mixed new user id - if the new user creation succeeds, false otherwise * @desc The function tries to retrieve user id from the session. * If it exists, the current user id is the creator id. If a problem arises, * it stores the error message in global $api_failureList * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1 * @assert ('Pippin','Took',null,null,'jo','jo') === false */ public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expirationDate = null, $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false, $isAdmin = false) { $currentUserId = api_get_user_id(); $hook = HookCreateUser::create(); if (!empty($hook)) { $hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE); } global $_configuration; $original_password = $password; $access_url_id = 1; if (api_get_multiple_access_url()) { $access_url_id = api_get_current_access_url_id(); } if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) { $num = self::get_number_of_users(); if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) { api_warn_hosting_contact('hosting_limit_users'); Display::addFlash(Display::return_message(get_lang('PortalUsersLimitReached'), 'warning')); return false; } } if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) { $num = self::get_number_of_users(1); if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) { Display::addFlash(Display::return_message(get_lang('PortalTeachersLimitReached'), 'warning')); api_warn_hosting_contact('hosting_limit_teachers'); return false; } } if (empty($password)) { Display::addFlash(Display::return_message(get_lang('ThisFieldIsRequired') . ': ' . get_lang('Password'), 'warning')); return false; } // database table definition $table_user = Database::get_main_table(TABLE_MAIN_USER); //Checking the user language $languages = api_get_languages(); $language = strtolower($language); if (!in_array($language, $languages['folder'])) { $language = api_get_setting('platformLanguage'); } if (!empty($currentUserId)) { $creator_id = $currentUserId; } else { $creator_id = ''; } // First check wether the login already exists if (!self::is_username_available($loginName)) { return api_set_failure('login-pass already taken'); } $currentDate = api_get_utc_datetime(); $now = new DateTime($currentDate); if (empty($expirationDate)) { // Default expiration date // if there is a default duration of a valid account then // we have to change the expiration_date accordingly if (api_get_setting('account_valid_duration') != '') { $expirationDate = new DateTime($currentDate); $days = intval(api_get_setting('account_valid_duration')); $expirationDate->modify('+' . $days . ' day'); } } else { $expirationDate = api_get_utc_datetime($expirationDate); $expirationDate = new \DateTime($expirationDate, new DateTimeZone('UTC')); } $userManager = self::getManager(); /** @var User $user */ $user = $userManager->createUser(); $user->setLastname($lastName)->setFirstname($firstName)->setUsername($loginName)->setStatus($status)->setPlainPassword($password)->setEmail($email)->setOfficialCode($official_code)->setPictureUri($picture_uri)->setCreatorId($creator_id)->setAuthSource($auth_source)->setPhone($phone)->setLanguage($language)->setRegistrationDate($now)->setHrDeptId($hr_dept_id)->setActive($active); if (!empty($expirationDate)) { $user->setExpirationDate($expirationDate); } $userManager->updateUser($user, true); $userId = $user->getId(); if (!empty($userId)) { $return = $userId; $sql = "UPDATE {$table_user} SET user_id = {$return} WHERE id = {$return}"; Database::query($sql); if ($isAdmin) { UserManager::add_user_as_admin($userId); } if (api_get_multiple_access_url()) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { //we are adding by default the access_url_user table with access_url_id = 1 UrlManager::add_user_to_url($return, 1); } if (!empty($email) && $send_mail) { $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS); $tplSubject = new Template(null, false, false, false, false, false); $layoutSubject = $tplSubject->get_template('mail/subject_registration_platform.tpl'); $emailSubject = $tplSubject->fetch($layoutSubject); $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); } } else { $url = $_configuration['root_web']; } $tplContent = new Template(null, false, false, false, false, false); // variables for the default template $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName))); $tplContent->assign('login_name', $loginName); $tplContent->assign('original_password', stripslashes($original_password)); $tplContent->assign('mailWebPath', $url); $layoutContent = $tplContent->get_template('mail/content_registration_platform.tpl'); $emailBody = $tplContent->fetch($layoutContent); /* MANAGE EVENT WITH MAIL */ if (EventsMail::check_if_using_class('user_registration')) { $values["about_user"] = $return; $values["password"] = $original_password; $values["send_to"] = array($return); $values["prior_lang"] = null; EventsDispatcher::events('user_registration', $values); } else { $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null; $additionalParameters = array('smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD, 'userId' => $return, 'mobilePhoneNumber' => $phoneNumber, 'password' => $original_password); api_mail_html($recipient_name, $email, $emailSubject, $emailBody, $sender_name, $email_admin, null, null, null, $additionalParameters); } /* ENDS MANAGE EVENT WITH MAIL */ } Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $return); } else { return api_set_failure('error inserting in Database'); } if (is_array($extra) && count($extra) > 0) { $res = true; foreach ($extra as $fname => $fvalue) { $res = $res && self::update_extra_field_value($return, $fname, $fvalue); } } self::update_extra_field_value($return, 'already_logged_in', 'false'); if (!empty($hook)) { $hook->setEventData(array('return' => $return, 'originalPassword' => $original_password)); $hook->notifyCreateUser(HOOK_EVENT_TYPE_POST); } return $return; }
/** * For the sake of genericity, this function is a switch. * It's called by EventsDispatcher and fires the good function * with the good require_once. * * @param string $event_name * @param array $params */ public static function event_send_mail($event_name, $params) { EventsMail::send_mail($event_name, $params); }
//File does not exist $fp = fopen($homep . $topf . '_' . $lang . $ext, 'w'); fputs($fp, $home_top); fclose($fp); foreach ($_languages['name'] as $key => $value) { $lang_name = $_languages['folder'][$key]; if (isset($_POST[$lang_name])) { if (file_exists($homep . $topf . '_' . $lang_name . $ext)) { $fp = fopen($homep . $topf . '_' . $lang_name . $ext, 'w'); fputs($fp, $home_top); fclose($fp); } } } } if (EventsMail::check_if_using_class('portal_homepage_edited')) { EventsDispatcher::events('portal_homepage_edited', array('about_user' => api_get_user_id())); } Event::addEvent(LOG_HOMEPAGE_CHANGED, 'edit_top', cut(strip_tags($home_top), 254), api_get_utc_datetime(), api_get_user_id()); break; case 'edit_notice': // Filter $notice_title = trim(strip_tags(stripslashes($_POST['notice_title']))); $notice_text = trim(str_replace(array("\r", "\n"), array('', '<br />'), strip_tags(stripslashes($_POST['notice_text']), '<a>'))); if (empty($notice_title) || empty($notice_text)) { $errorMsg = get_lang('NoticeWillBeNotDisplayed'); } // Write if (file_exists($homep . $noticef . '_' . $lang . $ext)) { if (is_writable($homep . $noticef . '_' . $lang . $ext)) { $fp = fopen($homep . $noticef . '_' . $lang . $ext, 'w');
/** * Creates a new user for the platform * @author Hugues Peeters <*****@*****.**>, * @author Roan Embrechts <*****@*****.**> * @param string Firstname * @param string Lastname * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) * @param string e-mail address * @param string Login * @param string Password * @param string Any official code (optional) * @param string User language (optional) (isocode) * @param string Phone number (optional) * @param string Picture URI (optional) * @param string Authentication source (optional, defaults to 'platform', dependind on constant) * @param string Account expiration date (optional, defaults to null) * @param int Whether the account is enabled or disabled by default * @param int The department of HR in which the user is registered (optional, defaults to 0) * @param array Extra fields * @param string Encrypt method used if password is given encrypted. Set to an empty string by default * @param bool $send_mail * @param bool $isAdmin * * @return mixed new user id - if the new user creation succeeds, false otherwise * @desc The function tries to retrieve user id from the session. * If it exists, the current user id is the creator id. If a problem arises, * it stores the error message in global $api_failureList * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1 * @assert ('Pippin','Took',null,null,'jo','jo') === false */ public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expirationDate = null, $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false, $isAdmin = false) { $currentUserId = api_get_user_id(); $hook = HookCreateUser::create(); if (!empty($hook)) { $hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE); } $original_password = $password; if (empty($password)) { Display::addFlash(Display::return_message(get_lang('ThisFieldIsRequired') . ': ' . get_lang('Password'), 'warning')); return false; } // database table definition $table_user = Database::get_main_table(TABLE_MAIN_USER); //Checking the user language $languages = api_get_languages(); if (!in_array($language, array_keys($languages))) { $language = api_get_setting('language.platform_language'); } if (!empty($currentUserId)) { $creator_id = $currentUserId; } else { $creator_id = 0; } // First check wether the login already exists if (!self::is_username_available($loginName)) { throw new \Exception("Username '{$loginName}' already exists"); } $currentDate = api_get_utc_datetime(); $now = new DateTime($currentDate); if (empty($expirationDate) || $expirationDate == '0000-00-00 00:00:00') { // Default expiration date // if there is a default duration of a valid account then // we have to change the expiration_date accordingly // Accept 0000-00-00 00:00:00 as a null value to avoid issues with // third party code using this method with the previous (pre-1.10) // value of 0000... if (api_get_setting('profile.account_valid_duration') != '') { $expirationDate = new DateTime($currentDate); $days = intval(api_get_setting('profile.account_valid_duration')); $expirationDate->modify('+' . $days . ' day'); } } else { $expirationDate = api_get_utc_datetime($expirationDate); $expirationDate = new \DateTime($expirationDate, new DateTimeZone('UTC')); } $em = Database::getManager(); $userManager = self::getManager(); /** @var User $user */ $user = $userManager->createUser(); $user->setLastname($lastName)->setFirstname($firstName)->setUsername($loginName)->setStatus($status)->setPlainPassword($password)->setEmail($email)->setOfficialCode($official_code)->setPictureUri($picture_uri)->setCreatorId($creator_id)->setAuthSource($auth_source)->setPhone($phone)->setLanguage($language)->setRegistrationDate($now)->setHrDeptId($hr_dept_id)->setActive($active)->setEnabled($active); $url = $em->getRepository('ChamiloCoreBundle:AccessUrl')->find(api_get_current_access_url_id()); $accessRelUser = new AccessUrlRelUser(); $accessRelUser->setUser($user); $accessRelUser->setPortal($url); $user->setPortal($accessRelUser); if (!empty($expirationDate)) { $user->setExpirationDate($expirationDate); } switch ($status) { case STUDENT: $group = 'student'; break; case COURSEMANAGER: $group = 'teacher'; break; case DRH: $group = 'drh'; break; case SESSIONADMIN: $group = 'session_manager'; break; /*case QUESTION: $group = 'question_manager'; break;*/ /*case QUESTION: $group = 'question_manager'; break;*/ case STUDENT_BOSS: $group = 'student_boss'; break; case INVITEE: $group = 'invitee'; break; } if ($isAdmin) { $group = 'admin'; } $criteria = ['code' => $group]; $group = $em->getRepository('ChamiloUserBundle:Group')->findOneBy($criteria); $user->setGroups(array($group)); $userManager->updateUser($user, true); $userId = $user->getId(); if (!empty($userId)) { $return = $userId; $sql = "UPDATE {$table_user} SET user_id = {$return} WHERE id = {$return}"; Database::query($sql); if ($isAdmin) { UserManager::add_user_as_admin($user); } if (api_get_multiple_access_url()) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { //we are adding by default the access_url_user table with access_url_id = 1 UrlManager::add_user_to_url($return, 1); } if (!empty($email) && $send_mail) { $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS); $emailSubject = Container::getTemplating()->render('@template_style/mail/subject_registration_platform.html.twig'); $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'); $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); } } $emailBody = Container::getTemplating()->render('@template_style/mail/content_registration_platform.html.twig', ['complete_name' => stripslashes(api_get_person_name($firstName, $lastName)), 'login_name' => $loginName, 'original_password' => stripslashes($original_password), 'mail_web_path' => $url]); /* MANAGE EVENT WITH MAIL */ if (EventsMail::check_if_using_class('user_registration')) { $values["about_user"] = $return; $values["password"] = $original_password; $values["send_to"] = array($return); $values["prior_lang"] = null; EventsDispatcher::events('user_registration', $values); } else { $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null; $additionalParameters = array('smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD, 'userId' => $return, 'mobilePhoneNumber' => $phoneNumber, 'password' => $original_password); api_mail_html($recipient_name, $email, $emailSubject, $emailBody, $sender_name, $email_admin, null, null, null, $additionalParameters); } /* ENDS MANAGE EVENT WITH MAIL */ } Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $return); } else { throw new \Exception('error inserting in Database'); } if (is_array($extra) && count($extra) > 0) { $res = true; foreach ($extra as $fname => $fvalue) { $res = $res && self::update_extra_field_value($return, $fname, $fvalue); } } self::update_extra_field_value($return, 'already_logged_in', 'false'); if (!empty($hook)) { $hook->setEventData(array('return' => $return, 'originalPassword' => $original_password)); $hook->notifyCreateUser(HOOK_EVENT_TYPE_POST); } return $return; }
/** * Creates a new user for the platform * @author Hugues Peeters <*****@*****.**>, * @author Roan Embrechts <*****@*****.**> * @param string Firstname * @param string Lastname * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) * @param string e-mail address * @param string Login * @param string Password * @param string Any official code (optional) * @param string User language (optional) * @param string Phone number (optional) * @param string Picture URI (optional) * @param string Authentication source (optional, defaults to 'platform', dependind on constant) * @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00') * @param int Whether the account is enabled or disabled by default * @param int The department of HR in which the user is registered (optional, defaults to 0) * @param array Extra fields * @param string Encrypt method used if password is given encrypted. Set to an empty string by default * @return mixed new user id - if the new user creation succeeds, false otherwise * @desc The function tries to retrieve $_user['user_id'] from the global space. If it exists, $_user['user_id'] is the creator id. If a problem arises, it stores the error message in global $api_failureList * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1 * @assert ('Pippin','Took',null,null,'jo','jo') === false */ public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false) { global $_configuration; $original_password = $password; $access_url_id = 1; if (api_get_multiple_access_url()) { $access_url_id = api_get_current_access_url_id(); } if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) { $num = self::get_number_of_users(); if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) { return api_set_failure('portal users limit reached'); } } if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) { $num = self::get_number_of_users(1); if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) { return api_set_failure('portal teachers limit reached'); } } $firstName = Security::remove_XSS($firstName); $lastName = Security::remove_XSS($lastName); $loginName = Security::remove_XSS($loginName); $phone = Security::remove_XSS($phone); // database table definition $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'); } $creator_id = api_get_user_id(); // First check wether the login already exists if (!self::is_username_available($loginName)) { return api_set_failure('login-pass already taken'); } if (empty($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'); } } //@todo replace this date with the api_get_utc_date function big problem with users that are already registered $current_date = api_get_utc_datetime(); $sql = "INSERT INTO {$table_user} " . "SET lastname = '" . Database::escape_string(trim($lastName)) . "'," . "firstname = '" . Database::escape_string(trim($firstName)) . "'," . "username = '******'," . "status = '" . Database::escape_string($status) . "'," . "password = '******'," . "email = '" . Database::escape_string($email) . "'," . "official_code = '" . Database::escape_string($official_code) . "'," . "picture_uri = '" . Database::escape_string($picture_uri) . "'," . "creator_id = '" . Database::escape_string($creator_id) . "'," . "auth_source = '" . Database::escape_string($auth_source) . "'," . "phone = '" . Database::escape_string($phone) . "'," . "language = '" . Database::escape_string($language) . "'," . "registration_date = '" . $current_date . "'," . "expiration_date = '" . Database::escape_string($expiration_date) . "'," . "hr_dept_id = '" . Database::escape_string($hr_dept_id) . "'," . "active = '" . Database::escape_string($active) . "'"; $result = Database::query($sql); if ($result) { //echo "id returned"; $return = Database::insert_id(); if (api_get_multiple_access_url()) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { //we are adding by default the access_url_user table with access_url_id = 1 UrlManager::add_user_to_url($return, 1); } // Adding user /** @var Entity\User $user */ $em = self::$em; $user = $em->getRepository('Entity\\User')->find($return); $role = $em->getRepository('Entity\\Role')->find($status); $user->getRolesObj()->add($role); $em->persist($user); $em->flush(); if (!empty($email) && $send_mail) { $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_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') . " : " . $loginName . "\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') . " : " . $loginName . "\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'); } /* MANAGE EVENT WITH MAIL */ if (EventsMail::check_if_using_class('user_registration')) { $values["about_user"] = $return; $values["password"] = $original_password; $values["send_to"] = array($return); $values["prior_lang"] = null; EventsDispatcher::events('user_registration', $values); } else { @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin); } /* ENDS MANAGE EVENT WITH MAIL */ } // Add event to system log $user_id_manager = api_get_user_id(); $user_info = api_get_user_info($return); event_system(LOG_USER_CREATE, LOG_USER_ID, $return, api_get_utc_datetime(), $user_id_manager); event_system(LOG_USER_CREATE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id_manager); } else { return api_set_failure('error inserting in Database'); } if (is_array($extra) && count($extra) > 0) { $res = true; foreach ($extra as $fname => $fvalue) { $res = $res && self::update_extra_field_value($return, $fname, $fvalue); } } self::update_extra_field_value($return, 'already_logged_in', 'false'); return $return; }
/** * Creates a new user for the platform * @author Hugues Peeters <*****@*****.**>, * @author Roan Embrechts <*****@*****.**> * @param string Firstname * @param string Lastname * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) * @param string e-mail address * @param string Login * @param string Password * @param string Any official code (optional) * @param string User language (optional) * @param string Phone number (optional) * @param string Picture URI (optional) * @param string Authentication source (optional, defaults to 'platform', dependind on constant) * @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00') * @param int Whether the account is enabled or disabled by default * @param int The department of HR in which the user is registered (optional, defaults to 0) * @param array Extra fields * @param string Encrypt method used if password is given encrypted. Set to an empty string by default * @return mixed new user id - if the new user creation succeeds, false otherwise * @desc The function tries to retrieve $_user['user_id'] from the global space. If it exists, $_user['user_id'] is the creator id. If a problem arises, it stores the error message in global $api_failureList * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1 * @assert ('Pippin','Took',null,null,'jo','jo') === false */ public static function create_user( $firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false ) { global $_user, $_configuration; $original_password = $password; $access_url_id = 1; if (api_get_multiple_access_url()) { $access_url_id = api_get_current_access_url_id(); } if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) { $num = self::get_number_of_users(); if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) { api_warn_hosting_contact('hosting_limit_users'); return api_set_failure('portal users limit reached'); } } if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0 ) { $num = self::get_number_of_users(1); if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) { api_warn_hosting_contact('hosting_limit_teachers'); return api_set_failure('portal teachers limit reached'); } } $firstName = Security::remove_XSS($firstName); $lastName = Security::remove_XSS($lastName); $loginName = Security::remove_XSS($loginName); $phone = Security::remove_XSS($phone); // database table definition $table_user = Database::get_main_table(TABLE_MAIN_USER); //Checking the user language $languages = api_get_languages(); $language = strtolower($language); if (!in_array($language, $languages['folder'])) { $language = api_get_setting('platformLanguage'); } if ($_user['user_id']) { $creator_id = intval($_user['user_id']); } else { $creator_id = ''; } // First check wether the login already exists if (!self::is_username_available($loginName)) { return api_set_failure('login-pass already taken'); } //$password = "******"; if (empty($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'); } } $current_date = api_get_utc_datetime(); $sql = "INSERT INTO $table_user SET lastname = '".Database::escape_string(trim($lastName))."', firstname = '".Database::escape_string(trim($firstName))."', username = '******', status = '".Database::escape_string($status)."', password = '******', email = '".Database::escape_string($email)."', official_code = '".Database::escape_string($official_code)."', picture_uri = '".Database::escape_string($picture_uri)."', creator_id = '".Database::escape_string($creator_id)."', auth_source = '".Database::escape_string($auth_source)."', phone = '".Database::escape_string($phone)."', language = '".Database::escape_string($language)."', registration_date = '".$current_date."', expiration_date = '".Database::escape_string($expiration_date)."', hr_dept_id = '".Database::escape_string($hr_dept_id)."', active = '".Database::escape_string($active)."'"; $result = Database::query($sql); if ($result) { //echo "id returned"; $return = Database::insert_id(); if (api_get_multiple_access_url()) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { //we are adding by default the access_url_user table with access_url_id = 1 UrlManager::add_user_to_url($return, 1); } if (!empty($email) && $send_mail) { $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')." : ".$loginName."\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')." : ".$loginName."\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'); } /* MANAGE EVENT WITH MAIL */ if (EventsMail::check_if_using_class('user_registration')) { $values["about_user"] = $return; $values["password"] = $original_password; $values["send_to"] = array($return); $values["prior_lang"] = null; EventsDispatcher::events('user_registration', $values); } else { $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null; $additionalParameters = array( 'smsType' => ClockworksmsPlugin::WELCOME_LOGIN_PASSWORD, 'userId' => $return, 'mobilePhoneNumber' => $phoneNumber, 'password' => $original_password ); api_mail_html( $recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin, null, null, null, $additionalParameters ); } /* ENDS MANAGE EVENT WITH MAIL */ } event_system(LOG_USER_CREATE, LOG_USER_ID, $return); } else { return api_set_failure('error inserting in Database'); } if (is_array($extra) && count($extra) > 0) { $res = true; foreach ($extra as $fname => $fvalue) { $res = $res && self::update_extra_field_value($return, $fname, $fvalue); } } self::update_extra_field_value($return, 'already_logged_in', 'false'); return $return; }