コード例 #1
0
 /**
  * @param SessionRepository $repo
  * @param AccessUrl $url
  * @throws \Exception
  */
 private function checkLimit($repo, AccessUrl $url)
 {
     $limit = $url->getLimitSessions();
     if (!empty($limit)) {
         $count = $repo->getCountSessionByUrl($url);
         if ($count >= $limit) {
             api_warn_hosting_contact('hosting_limit_sessions', $limit);
             throw new \Exception('PortalSessionsLimitReached');
         }
     }
 }
コード例 #2
0
 /**
  * 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;
 }
コード例 #3
0
ファイル: course.lib.php プロジェクト: feroli1000/chamilo-lms
 /**
  * Creates a course
  * @param   array $params columns in the main.course table
  *
  * @return  mixed  false if the course was not created, array with the course info
  */
 public static function create_course($params, $extraFields = array())
 {
     global $_configuration;
     // Check portal limits
     $access_url_id = 1;
     if (api_get_multiple_access_url()) {
         $access_url_id = api_get_current_access_url_id();
     }
     if (isset($_configuration[$access_url_id]) && is_array($_configuration[$access_url_id])) {
         if (isset($_configuration[$access_url_id]['hosting_limit_courses']) && $_configuration[$access_url_id]['hosting_limit_courses'] > 0) {
             $num = self::count_courses($access_url_id);
             if ($num >= $_configuration[$access_url_id]['hosting_limit_courses']) {
                 api_warn_hosting_contact('hosting_limit_courses');
                 return api_set_failure(get_lang('PortalCoursesLimitReached'));
             }
         }
         if (isset($_configuration[$access_url_id]['hosting_limit_active_courses']) && $_configuration[$access_url_id]['hosting_limit_active_courses'] > 0) {
             $num = self::countActiveCourses($access_url_id);
             if ($num >= $_configuration[$access_url_id]['hosting_limit_active_courses']) {
                 api_warn_hosting_contact('hosting_limit_active_courses');
                 return api_set_failure(get_lang('PortalActiveCoursesLimitReached'));
             }
         }
     }
     if (empty($params['title'])) {
         return false;
     }
     if (empty($params['wanted_code'])) {
         $params['wanted_code'] = $params['title'];
         // Check whether the requested course code has already been occupied.
         $params['wanted_code'] = CourseManager::generate_course_code(api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE));
     }
     // Create the course keys
     $keys = AddCourse::define_course_keys($params['wanted_code']);
     $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
     if (count($keys)) {
         $params['code'] = $keys['currentCourseCode'];
         $params['visual_code'] = $keys['currentCourseId'];
         $params['directory'] = $keys['currentCourseRepository'];
         $course_info = api_get_course_info($params['code']);
         if (empty($course_info)) {
             $course_id = AddCourse::register_course($params);
             $course_info = api_get_course_info_by_id($course_id);
             if (!empty($course_info)) {
                 AddCourse::prepare_course_repository($course_info['directory'], $course_info['code']);
                 AddCourse::fill_db_course($course_id, $course_info['directory'], $course_info['course_language'], $params['exemplary_content']);
                 if (api_get_setting('gradebook.gradebook_enable_grade_model') == 'true') {
                     //Create gradebook_category for the new course and add
                     // a gradebook model for the course
                     if (isset($params['gradebook_model_id']) && !empty($params['gradebook_model_id']) && $params['gradebook_model_id'] != '-1') {
                         GradebookUtils::create_default_course_gradebook($course_info['code'], $params['gradebook_model_id']);
                     }
                 }
                 // If parameter defined, copy the contents from a specific
                 // template course into this new course
                 $template = api_get_setting('course.course_creation_use_template');
                 if (!empty($template)) {
                     // Include the necessary libraries to generate a course copy
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseBuilder.class.php';
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseRestorer.class.php';
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseSelectForm.class.php';
                     // Call the course copy object
                     $originCourse = api_get_course_info_by_id($template);
                     $originCourse['official_code'] = $originCourse['code'];
                     $cb = new CourseBuilder(null, $originCourse);
                     $course = $cb->build(null, $originCourse['code']);
                     $cr = new CourseRestorer($course);
                     $cr->set_file_option();
                     $cr->restore($course_info['id']);
                     //course_info[id] is the course.code value (I know...)
                 }
                 $params['course_code'] = $course_info['code'];
                 $params['item_id'] = $course_info['real_id'];
                 $courseFieldValue = new ExtraFieldValue('course');
                 $courseFieldValue->saveFieldValues($params);
                 return $course_info;
             }
         }
     }
     return false;
 }
コード例 #4
0
 /**
  * Create a session
  * @author Carlos Vargas <*****@*****.**>, from existing code
  * @param   string  $name
  * @param   string  $startDate (YYYY-MM-DD hh:mm:ss)
  * @param   string  $endDate (YYYY-MM-DD hh:mm:ss)
  * @param   string  $displayStartDate (YYYY-MM-DD hh:mm:ss)
  * @param   string  $displayEndDate (YYYY-MM-DD hh:mm:ss)
  * @param   string  $coachStartDate (YYYY-MM-DD hh:mm:ss)
  * @param   string  $coachEndDate (YYYY-MM-DD hh:mm:ss)
  * @param   mixed   $coachId If integer, this is the session coach id, if string, the coach ID will be looked for from the user table
  * @param   integer $sessionCategoryId ID of the session category in which this session is registered
  * @param   integer $visibility Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
  * @param   bool    $fixSessionNameIfExists
  * @param   string  $duration
  * @param   string  $description Optional. The session description
  * @param   int     $showDescription Optional. Whether show the session description
  * @param   array   $extraFields
  * @param   int     $sessionAdminId Optional. If this sessions was created by a session admin, assign it to him
  * @param boolean $sendSubscritionNotification Optional.
  *          Whether send a mail notification to users being subscribed
  * @todo use an array to replace all this parameters or use the model.lib.php ...
  * @return mixed       Session ID on success, error message otherwise
  * */
 public static function create_session($name, $startDate, $endDate, $displayStartDate, $displayEndDate, $coachStartDate, $coachEndDate, $coachId, $sessionCategoryId, $visibility = 1, $fixSessionNameIfExists = false, $duration = null, $description = null, $showDescription = 0, $extraFields = array(), $sessionAdminId = 0, $sendSubscritionNotification = false)
 {
     global $_configuration;
     //Check portal limits
     $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_sessions']) && $_configuration[$access_url_id]['hosting_limit_sessions'] > 0) {
         $num = self::count_sessions();
         if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
             api_warn_hosting_contact('hosting_limit_sessions');
             return get_lang('PortalSessionsLimitReached');
         }
     }
     $name = Database::escape_string(trim($name));
     $sessionCategoryId = intval($sessionCategoryId);
     $visibility = intval($visibility);
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $startDate = Database::escape_string($startDate);
     $endDate = Database::escape_string($endDate);
     if (empty($name)) {
         $msg = get_lang('SessionNameIsRequired');
         return $msg;
     } elseif (empty($coachId)) {
         $msg = get_lang('CoachIsRequired');
         return $msg;
     } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') && !api_is_valid_date($startDate, 'Y-m-d H:i:s')) {
         $msg = get_lang('InvalidStartDate');
         return $msg;
     } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') && !api_is_valid_date($endDate, 'Y-m-d H:i:s')) {
         $msg = get_lang('InvalidEndDate');
         return $msg;
     } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
         $msg = get_lang('StartDateShouldBeBeforeEndDate');
         return $msg;
     } else {
         $ready_to_create = false;
         if ($fixSessionNameIfExists) {
             $name = self::generateNextSessionName($name);
             if ($name) {
                 $ready_to_create = true;
             } else {
                 $msg = get_lang('SessionNameAlreadyExists');
                 return $msg;
             }
         } else {
             $rs = Database::query("SELECT 1 FROM {$tbl_session} WHERE name='" . $name . "'");
             if (Database::num_rows($rs)) {
                 $msg = get_lang('SessionNameAlreadyExists');
                 return $msg;
             }
             $ready_to_create = true;
         }
         if ($ready_to_create) {
             $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
             $values = array('name' => $name, 'id_coach' => $coachId, 'session_admin_id' => $sessionAdminId, 'visibility' => $visibility, 'description' => $description, 'show_description' => intval($showDescription), 'send_subscription_notification' => $sendSubscritionNotification);
             if (!empty($startDate)) {
                 $values['access_start_date'] = $startDate;
             }
             if (!empty($endDate)) {
                 $values['access_end_date'] = $endDate;
             }
             if (!empty($displayStartDate)) {
                 $values['display_start_date'] = $displayStartDate;
             }
             if (!empty($displayEndDate)) {
                 $values['display_end_date'] = $displayEndDate;
             }
             if (!empty($coachStartDate)) {
                 $values['coach_access_start_date'] = $coachStartDate;
             }
             if (!empty($coachEndDate)) {
                 $values['coach_access_end_date'] = $coachEndDate;
             }
             if (!empty($sessionCategoryId)) {
                 $values['session_category_id'] = $sessionCategoryId;
             }
             $session_id = Database::insert($tbl_session, $values);
             $duration = intval($duration);
             if (!empty($duration)) {
                 $sql = "UPDATE {$tbl_session} SET\n                        access_start_date = NULL,\n                        access_end_date = NULL,\n                        display_start_date = NULL,\n                        display_end_date = NULL,\n                        coach_access_start_date = NULL,\n                        coach_access_end_date = NULL,\n                        duration = {$duration}\n                    WHERE id = {$session_id}";
                 Database::query($sql);
             } else {
                 $sql = "UPDATE {$tbl_session}\n                        SET duration = 0\n                        WHERE id = {$session_id}";
                 Database::query($sql);
             }
             if (!empty($session_id)) {
                 $extraFields['item_id'] = $session_id;
                 $sessionFieldValue = new ExtraFieldValue('session');
                 $sessionFieldValue->saveFieldValues($extraFields);
                 /*
                  Sends a message to the user_id = 1
                 
                  $user_info = api_get_user_info(1);
                  $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
                  $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
                  $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
                  api_mail_html($complete_name, $user_info['email'], $subject, $message);
                 *
                 */
                 //Adding to the correct URL
                 $access_url_id = api_get_current_access_url_id();
                 UrlManager::add_session_to_url($session_id, $access_url_id);
                 // add event to system log
                 $user_id = api_get_user_id();
                 Event::addEvent(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), $user_id);
             }
             return $session_id;
         }
     }
 }
コード例 #5
0
    /**
     * Create a session
     * @author Carlos Vargas <*****@*****.**>, from existing code
     * @param	string 		name
     * @param 	integer		Start year (yyyy)
     * @param 	integer		Start month (mm)
     * @param 	integer		Start day (dd)
     * @param 	integer		End year (yyyy)
     * @param 	integer		End month (mm)
     * @param 	integer		End day (dd)
     * @param 	integer		Number of days that the coach can access the session before the start date
     * @param 	integer		Number of days that the coach can access the session after the end date
     * @param 	integer		If 1, means there are no date limits
     * @param 	mixed		If integer, this is the session coach id, if string, the coach ID will be looked for from the user table
     * @param 	integer		ID of the session category in which this session is registered
     * @param  integer     Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
     * @param  string      Start limit = true if the start date has to be considered
     * @param  string      End limit = true if the end date has to be considered
     * @param  string $fix_name
     * @todo use an array to replace all this parameters or use the model.lib.php ...
     * @return mixed       Session ID on success, error message otherwise
     * */
    public static function create_session(
        $sname,
        $syear_start,
        $smonth_start,
        $sday_start,
        $syear_end,
        $smonth_end,
        $sday_end,
        $snb_days_acess_before,
        $snb_days_acess_after,
        $nolimit,
        $coach_username,
        $id_session_category,
        $id_visibility,
        $start_limit = true,
        $end_limit = true,
        $fix_name = false,
        $duration = null,
        $showDescription = null
    ) {
        global $_configuration;

        //Check portal limits
        $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_sessions']) &&
            $_configuration[$access_url_id]['hosting_limit_sessions'] > 0
        ) {
            $num = self::count_sessions();
            if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
                api_warn_hosting_contact('hosting_limit_sessions');
                return get_lang('PortalSessionsLimitReached');
            }
        }

        $name = Database::escape_string(trim($sname));
        $year_start = intval($syear_start);
        $month_start = intval($smonth_start);
        $day_start = intval($sday_start);
        $year_end = intval($syear_end);
        $month_end = intval($smonth_end);
        $day_end = intval($sday_end);
        $nb_days_acess_before = intval($snb_days_acess_before);
        $nb_days_acess_after = intval($snb_days_acess_after);
        $id_session_category = intval($id_session_category);
        $id_visibility = intval($id_visibility);
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);

        if (is_int($coach_username)) {
            $id_coach = $coach_username;
        } else {
            $sql = 'SELECT user_id FROM ' . $tbl_user . ' WHERE username="******"';
            $rs = Database::query($sql);
            $id_coach = Database::result($rs, 0, 'user_id');
        }

        if (empty($nolimit)) {
            $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
            $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
        } else {
            $id_visibility = 1; // by default session visibility is read only
            $date_start = "0000-00-00";
            $date_end = "0000-00-00";
        }

        if (empty($end_limit)) {
            $date_end = "0000-00-00";
            $id_visibility = 1; // by default session visibility is read only
        }

        if (empty($start_limit)) {
            $date_start = "0000-00-00";
        }

        if (empty($name)) {
            $msg = get_lang('SessionNameIsRequired');
            return $msg;
        } elseif (empty($coach_username)) {
            $msg = get_lang('CoachIsRequired');
            return $msg;
        } elseif (!empty($start_limit) && empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start))) {
            $msg = get_lang('InvalidStartDate');
            return $msg;
        } elseif (!empty($end_limit) && empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end))) {
            $msg = get_lang('InvalidEndDate');
            return $msg;
        } elseif (!empty($start_limit) && !empty($end_limit) && empty($nolimit) && $date_start >= $date_end) {
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
            return $msg;
        } else {
            $ready_to_create = false;
            if ($fix_name) {
                $name = self::generate_nice_next_session_name($name);
                if ($name) {
                    $ready_to_create = true;
                } else {
                    $msg = get_lang('SessionNameAlreadyExists');
                    return $msg;
                }
            } else {
                $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='" . $name . "'");
                if (Database::num_rows($rs)) {
                    $msg = get_lang('SessionNameAlreadyExists');
                    return $msg;
                }
                $ready_to_create = true;
            }

            if ($ready_to_create) {
                $sql = "INSERT INTO $tbl_session(name,date_start,date_end,id_coach,session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end, session_category_id,visibility)
                        VALUES('" . $name . "','$date_start','$date_end','$id_coach'," . api_get_user_id() . "," . $nb_days_acess_before . ", " . $nb_days_acess_after . ", " . $id_session_category . ", " . $id_visibility . ")";
                Database::query($sql);
                $session_id = Database::insert_id();

                if (self::durationPerUserIsEnabled()) {
                    $duration = intval($duration);

                    if (empty($duration)) {
                        $duration = null;
                    } else {
                        $sql = "UPDATE $tbl_session SET
                                  date_start = '0000-00-00',
                                  date_end = '0000-00-00'
                                WHERE id = $session_id";
                        Database::query($sql);
                    }
                    $sql = "UPDATE $tbl_session
                            SET duration = '$duration'
                            WHERE id = $session_id";
                    Database::query($sql);
                }

                if (!is_null($showDescription)) {
                    $showDescription = intval($showDescription);
                    $sql = "UPDATE $tbl_session
                            SET show_description = '$showDescription'
                            WHERE id = $session_id";
                    Database::query($sql);
                }

                if (!empty($session_id)) {
                    /*
                      Sends a message to the user_id = 1

                      $user_info = api_get_user_info(1);
                      $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
                      $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
                      $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
                      api_mail_html($complete_name, $user_info['email'], $subject, $message);
                     *
                     */
                    //Adding to the correct URL
                    $access_url_id = api_get_current_access_url_id();
                    UrlManager::add_session_to_url($session_id, $access_url_id);

                    // add event to system log
                    $user_id = api_get_user_id();
                    event_system(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), $user_id);
                }
                return $session_id;
            }
        }
    }
コード例 #6
0
$courseInfo['disk_quota'] = round(DocumentManager::get_course_quota($courseInfo['code']) / 1024 / 1024, 1);
$courseInfo['real_code'] = $courseInfo['code'];
$courseInfo['add_teachers_to_sessions_courses'] = isset($courseInfo['add_teachers_to_sessions_courses']) ? $courseInfo['add_teachers_to_sessions_courses'] : 0;
$form->setDefaults($courseInfo);
// Validate form
if ($form->validate()) {
    $course = $form->getSubmitValues();
    $visibility = $course['visibility'];
    global $_configuration;
    $urlId = api_get_current_access_url_id();
    if (isset($_configuration[$urlId]) && isset($_configuration[$urlId]['hosting_limit_active_courses']) && $_configuration[$urlId]['hosting_limit_active_courses'] > 0) {
        // Check if
        if ($courseInfo['visibility'] == COURSE_VISIBILITY_HIDDEN && $visibility != $courseInfo['visibility']) {
            $num = CourseManager::countActiveCourses($urlId);
            if ($num >= $_configuration[$urlId]['hosting_limit_active_courses']) {
                api_warn_hosting_contact('hosting_limit_active_courses');
                api_set_failure(get_lang('PortalActiveCoursesLimitReached'));
                header('Location: course_list.php?action=show_msg&warn=' . urlencode(get_lang('PortalActiveCoursesLimitReached')));
                exit;
            }
        }
    }
    $visual_code = $course['visual_code'];
    $visual_code = CourseManager::generate_course_code($visual_code);
    // Check if the visual code is already used by *another* course
    $visual_code_is_used = false;
    $warn = get_lang('TheFollowingCoursesAlreadyUseThisVisualCode');
    if (!empty($visual_code)) {
        $list = CourseManager::get_courses_info_from_visual_code($visual_code);
        foreach ($list as $course_temp) {
            if ($course_temp['code'] != $course_code) {
コード例 #7
0
 /**
  * @param CourseRepository $repo
  * @param Course $course
  * @param AccessUrl $url
  * @throws \Exception
  */
 private function checkLimit($repo, Course $course, AccessUrl $url)
 {
     $limit = $url->getLimitCourses();
     if (!empty($limit)) {
         $count = $repo->getCountCoursesByUrl($url);
         if ($count >= $limit) {
             api_warn_hosting_contact('hosting_limit_courses', $limit);
             throw new \Exception('PortalCoursesLimitReached');
         }
     }
     if ($course->getVisibility() != COURSE_VISIBILITY_HIDDEN) {
         $limit = $url->getLimitActiveCourses();
         if (!empty($limit)) {
             $count = $repo->getCountActiveCoursesByUrl($url);
             if ($count >= $limit) {
                 api_warn_hosting_contact('hosting_limit_active_courses', $limit);
                 throw new \Exception('PortalActiveCoursesLimitReached');
             }
         }
     }
 }
コード例 #8
0
    /**
     * 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;
    }