/**
  * Uninstall the Create User hook
  */
 public function uninstallHook()
 {
     /** @var HookCreateDrupalUser $observer */
     $observer = HookCreateDrupalUser::create();
     $event = HookCreateUser::create();
     if ($event) {
         $event->detach($observer);
     }
 }
 /**
  * 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;
 }
 /**
  * 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;
 }