/**
  * @param string $file
  * @param bool $updatesession options:
  * true: if the session exists it will be updated
  * false: if session exists a new session will be created adding a counter session1, session2, etc
  * @param int $user_id
  * @param $logger
  * @param array convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  * @param array extra fields
  * @param string extra field id
  * @param int $daysCoachAccessBeforeBeginning
  * @param int $daysCoachAccessAfterBeginning
  * @param int $sessionVisibility
  * @return array
  */
 static function importCSV($file, $updatesession, $defaultUserId = null, $logger = null, $extraFields = array(), $extraFieldId = null, $daysCoachAccessBeforeBeginning = null, $daysCoachAccessAfterBeginning = null, $sessionVisibility = 1, $fieldsToAvoidUpdate = array())
 {
     $content = file($file);
     $error_message = null;
     $session_counter = 0;
     if (empty($defaultUserId)) {
         $defaultUserId = api_get_user_id();
     }
     $eol = PHP_EOL;
     if (PHP_SAPI != 'cli') {
         $eol = '<br />';
     }
     $debug = false;
     if (isset($logger)) {
         $debug = true;
     }
     $extraParameters = null;
     if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
         $extraParameters .= ' , nb_days_access_before_beginning = ' . intval($daysCoachAccessBeforeBeginning);
         $extraParameters .= ' , nb_days_access_after_end = ' . intval($daysCoachAccessAfterBeginning);
     }
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
     $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
     $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $sessions = array();
     if (!api_strstr($content[0], ';')) {
         $error_message = get_lang('NotCSV');
     } else {
         $tag_names = array();
         foreach ($content as $key => $enreg) {
             $enreg = explode(';', trim($enreg));
             if ($key) {
                 foreach ($tag_names as $tag_key => $tag_name) {
                     $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
                 }
             } else {
                 foreach ($enreg as $tag_name) {
                     $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\\-]/', '', $tag_name);
                 }
                 if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
                     $error_message = get_lang('NoNeededData');
                     break;
                 }
             }
         }
         // Looping the sessions.
         foreach ($sessions as $enreg) {
             $user_counter = 0;
             $course_counter = 0;
             if (isset($extraFields) && !empty($extraFields)) {
                 foreach ($extraFields as $original => $to) {
                     $enreg[$to] = $enreg[$original];
                 }
             }
             $session_name = Database::escape_string($enreg['SessionName']);
             $date_start = $enreg['DateStart'];
             $date_end = $enreg['DateEnd'];
             $visibility = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
             $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
             // Searching a general coach.
             if (!empty($enreg['Coach'])) {
                 $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                 if ($coach_id === false) {
                     // If the coach-user does not exist - I'm the coach.
                     $coach_id = $defaultUserId;
                 }
             } else {
                 $coach_id = $defaultUserId;
             }
             if (!$updatesession) {
                 // Always create a session.
                 $unique_name = false;
                 // This MUST be initializead.
                 $i = 0;
                 // Change session name, verify that session doesn't exist.
                 $suffix = null;
                 while (!$unique_name) {
                     if ($i > 1) {
                         $suffix = ' - ' . $i;
                     }
                     $sql = 'SELECT 1 FROM ' . $tbl_session . ' WHERE name="' . $session_name . $suffix . '"';
                     $rs = Database::query($sql);
                     if (Database::result($rs, 0, 0)) {
                         $i++;
                     } else {
                         $unique_name = true;
                         $session_name .= $suffix;
                     }
                 }
                 // Creating the session.
                 /*$sql_session = "INSERT IGNORE INTO $tbl_session SET
                           name = '".$session_name."',
                           id_coach = '$coach_id',
                           date_start = '$date_start',
                           date_end = '$date_end',
                           visibility = '$visibility',
                           session_category_id = '$session_category_id',
                           session_admin_id=".intval($defaultUserId).$extraParameters;
                   Database::query($sql_session);*/
                 $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId);
                 $session_id = SessionManager::add($params);
                 if ($debug) {
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         $logger->addInfo("Sessions - Session created: #{$session_id} - {$session_name}");
                     } else {
                         $logger->addError("Sessions - Session NOT created: {$session_name}");
                     }
                 }
                 $session_counter++;
             } else {
                 $sessionId = null;
                 if (isset($extraFields) && !empty($extraFields)) {
                     $sessionId = self::get_session_id_from_original_id($enreg['extra_' . $extraFieldId], $extraFieldId);
                     if (empty($sessionId)) {
                         $my_session_result = false;
                     } else {
                         $my_session_result = true;
                     }
                 } else {
                     $my_session_result = self::get_session_by_name($enreg['SessionName']);
                 }
                 if ($my_session_result === false) {
                     // Creating a session.
                     /*$sql_session = "INSERT IGNORE INTO $tbl_session SET
                       name = '$session_name',
                       id_coach = '$coach_id',
                       date_start = '$date_start',
                       date_end = '$date_end',
                       visibility = '$visibility',
                       session_category_id = '$session_category_id' ".$extraParameters;*/
                     $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId);
                     $session_id = SessionManager::add($params);
                     // We get the last insert id.
                     /*$my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
                       $session_id = $my_session_result['id'];*/
                     if ($debug) {
                         if ($session_id) {
                             foreach ($enreg as $key => $value) {
                                 if (substr($key, 0, 6) == 'extra_') {
                                     //an extra field
                                     self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                                 }
                             }
                             $logger->addInfo("Sessions - #{$session_id} created: {$session_name}");
                         } else {
                             $logger->addError("Sessions - Session NOT created: {$session_name}");
                         }
                     }
                 } else {
                     $params = array('id_coach' => $coach_id, 'date_start' => $date_start, 'date_end' => $date_end, 'visibility' => $visibility, 'session_category_id' => $session_category_id);
                     if (!empty($fieldsToAvoidUpdate)) {
                         foreach ($fieldsToAvoidUpdate as $field) {
                             unset($params[$field]);
                         }
                     }
                     if (isset($sessionId) && !empty($sessionId)) {
                         // The session already exists, update it then.
                         Database::update($tbl_session, $params, array('id = ?' => $sessionId));
                         $session_id = $sessionId;
                     } else {
                         Database::update($tbl_session, $params, array("name = '?' " => $enreg['SessionName']));
                         $row = Database::query("SELECT id FROM {$tbl_session} WHERE name = '{$session_name}'");
                         list($session_id) = Database::fetch_array($row);
                     }
                     foreach ($enreg as $key => $value) {
                         if (substr($key, 0, 6) == 'extra_') {
                             //an extra field
                             self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                         }
                     }
                     Database::query("DELETE FROM {$tbl_session_user} WHERE id_session='{$session_id}'");
                     Database::query("DELETE FROM {$tbl_session_course} WHERE id_session='{$session_id}'");
                     Database::query("DELETE FROM {$tbl_session_course_user} WHERE id_session='{$session_id}'");
                 }
                 $session_counter++;
             }
             $users = explode('|', $enreg['Users']);
             // Adding the relationship "Session - User".
             if (is_array($users)) {
                 foreach ($users as $user) {
                     $user_id = UserManager::get_user_id_from_username($user);
                     if ($user_id !== false) {
                         // Insert new users.
                         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                    id_user = '******',\n                                    id_session = '{$session_id}'";
                         Database::query($sql);
                         if ($debug) {
                             $logger->addInfo("Sessions - Adding User #{$user_id} ({$user}) to session #{$session_id}");
                         }
                         $user_counter++;
                     }
                 }
             }
             $courses = explode('|', $enreg['Courses']);
             foreach ($courses as $course) {
                 $course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
                 if (CourseManager::course_exists($course_code)) {
                     $courseInfo = api_get_course_info($course_code);
                     $courseId = $courseInfo['real_id'];
                     // Adding the course to a session.
                     $sql_course = "INSERT IGNORE INTO {$tbl_session_course}\n                                       SET c_id = '" . $courseId . "', id_session = '{$session_id}'";
                     Database::query($sql_course);
                     if ($debug) {
                         $logger->addInfo("Sessions - Adding course '{$course_code}' to session #{$session_id}");
                     }
                     $course_counter++;
                     $pattern = "/\\[(.*?)\\]/";
                     preg_match_all($pattern, $course, $matches);
                     if (isset($matches[1])) {
                         $course_coaches = $matches[1][0];
                         $course_users = $matches[1][1];
                     }
                     $course_users = explode(',', $course_users);
                     $course_coaches = explode(',', $course_coaches);
                     // Adding coaches to session course user
                     if (!empty($course_coaches)) {
                         foreach ($course_coaches as $course_coach) {
                             $coach_id = UserManager::get_user_id_from_username($course_coach);
                             if ($coach_id !== false) {
                                 $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                            id_user='******',\n                                            c_id ='{$courseId}',\n                                            id_session = '{$session_id}',\n                                            status = 2 ";
                                 Database::query($sql);
                                 if ($debug) {
                                     $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                 }
                             } else {
                                 $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                             }
                         }
                     }
                     $users_in_course_counter = 0;
                     // Adding the relationship "Session - Course - User".
                     foreach ($course_users as $user) {
                         $user_id = UserManager::get_user_id_from_username($user);
                         if ($user_id !== false) {
                             $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                        id_user='******',\n                                        c_id = '{$courseId}',\n                                        id_session = '{$session_id}'";
                             Database::query($sql);
                             if ($debug) {
                                 $logger->addInfo("Sessions - Adding student: user #{$user_id} ({$user}) to course: '{$course_code}' and session #{$session_id}");
                             }
                             $users_in_course_counter++;
                         } else {
                             $error_message .= get_lang('UserDoesNotExist') . ': ' . $user . $eol;
                         }
                     }
                     $sql = "UPDATE {$tbl_session_course} SET nbr_users='{$users_in_course_counter}' WHERE c_id ='{$courseId}'";
                     Database::query($sql);
                     $course_info = CourseManager::get_course_information($course_code);
                     $inserted_in_course[$course_code] = $course_info['title'];
                 }
             }
             $access_url_id = api_get_current_access_url_id();
             UrlManager::add_session_to_url($session_id, $access_url_id);
             $sql_update_users = "UPDATE {$tbl_session} SET nbr_users ='{$user_counter}', nbr_courses='{$course_counter}' WHERE id='{$session_id}'";
             Database::query($sql_update_users);
         }
     }
     return array('error_message' => $error_message, 'session_counter' => $session_counter);
 }
Пример #2
0
 /**
  * @param string $file
  * @param bool $updateSession options:
  *  true: if the session exists it will be updated.
  *  false: if session exists a new session will be created adding a counter session1, session2, etc
  * @param int $defaultUserId
  * @param mixed $logger
  * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  * @param string $extraFieldId
  * @param int $daysCoachAccessBeforeBeginning
  * @param int $daysCoachAccessAfterBeginning
  * @param int $sessionVisibility
  * @param array $fieldsToAvoidUpdate
  * @param bool $deleteUsersNotInList
  * @param bool $updateCourseCoaches
  * @param bool $sessionWithCoursesModifier
  * @param int $showDescription
  * @return array
  */
 static function importCSV($file, $updateSession, $defaultUserId = null, $logger = null, $extraFields = array(), $extraFieldId = null, $daysCoachAccessBeforeBeginning = null, $daysCoachAccessAfterBeginning = null, $sessionVisibility = 1, $fieldsToAvoidUpdate = array(), $deleteUsersNotInList = false, $updateCourseCoaches = false, $sessionWithCoursesModifier = false, $addOriginalCourseTeachersAsCourseSessionCoaches = true, $removeAllTeachersFromCourse = true, $showDescription = null)
 {
     $content = file($file);
     $error_message = null;
     $session_counter = 0;
     if (empty($defaultUserId)) {
         $defaultUserId = api_get_user_id();
     }
     $eol = PHP_EOL;
     if (PHP_SAPI != 'cli') {
         $eol = '<br />';
     }
     $debug = false;
     if (isset($logger)) {
         $debug = true;
     }
     $extraParameters = null;
     if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
         $extraParameters .= ' , nb_days_access_before_beginning = ' . intval($daysCoachAccessBeforeBeginning);
         $extraParameters .= ' , nb_days_access_after_end = ' . intval($daysCoachAccessAfterBeginning);
     }
     if (!is_null($showDescription)) {
         $extraParameters .= ' , show_description = ' . intval($showDescription);
     }
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
     $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
     $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $sessions = array();
     if (!api_strstr($content[0], ';')) {
         $error_message = get_lang('NotCSV');
     } else {
         $tag_names = array();
         foreach ($content as $key => $enreg) {
             $enreg = explode(';', trim($enreg));
             if ($key) {
                 foreach ($tag_names as $tag_key => $tag_name) {
                     $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
                 }
             } else {
                 foreach ($enreg as $tag_name) {
                     $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\\-]/', '', $tag_name);
                 }
                 if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
                     $error_message = get_lang('NoNeededData');
                     break;
                 }
             }
         }
         $sessionList = array();
         // Looping the sessions.
         foreach ($sessions as $enreg) {
             $user_counter = 0;
             $course_counter = 0;
             if (isset($extraFields) && !empty($extraFields)) {
                 foreach ($extraFields as $original => $to) {
                     $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
                 }
             }
             $session_name = Database::escape_string($enreg['SessionName']);
             // Default visibility
             $visibilityAfterExpirationPerSession = $sessionVisibility;
             if (isset($enreg['VisibilityAfterExpiration'])) {
                 $visibility = $enreg['VisibilityAfterExpiration'];
                 switch ($visibility) {
                     case 'read_only':
                         $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
                         break;
                     case 'accessible':
                         $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
                         break;
                     case 'not_accessible':
                         $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
                         break;
                 }
             }
             if (empty($session_name)) {
                 continue;
             }
             $date_start = $enreg['DateStart'];
             $date_end = $enreg['DateEnd'];
             $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
             $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
             $extraSessionParameters = null;
             if (!empty($sessionDescription)) {
                 $extraSessionParameters = " , description = '" . Database::escape_string($sessionDescription) . "'";
             }
             // Searching a general coach.
             if (!empty($enreg['Coach'])) {
                 $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                 if ($coach_id === false) {
                     // If the coach-user does not exist - I'm the coach.
                     $coach_id = $defaultUserId;
                 }
             } else {
                 $coach_id = $defaultUserId;
             }
             if (!$updateSession) {
                 // Always create a session.
                 $unique_name = false;
                 $i = 0;
                 // Change session name, verify that session doesn't exist.
                 $suffix = null;
                 while (!$unique_name) {
                     if ($i > 1) {
                         $suffix = ' - ' . $i;
                     }
                     $sql = 'SELECT 1 FROM ' . $tbl_session . '
                             WHERE name="' . $session_name . $suffix . '"';
                     $rs = Database::query($sql);
                     if (Database::result($rs, 0, 0)) {
                         $i++;
                     } else {
                         $unique_name = true;
                         $session_name .= $suffix;
                     }
                 }
                 $sessionCondition = '';
                 if (!empty($session_category_id)) {
                     $sessionCondition = "session_category_id = '{$session_category_id}',";
                 }
                 // Creating the session.
                 $sql = "INSERT IGNORE INTO {$tbl_session} SET\n                            name = '" . $session_name . "',\n                            id_coach = '{$coach_id}',\n                            access_start_date = '{$date_start}',\n                            access_end_date = '{$date_end}',\n                            visibility = '{$visibilityAfterExpirationPerSession}',\n                            {$sessionCondition}\n                            session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
                 Database::query($sql);
                 $session_id = Database::insert_id();
                 if ($debug) {
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         $logger->addInfo("Sessions - Session created: #{$session_id} - {$session_name}");
                     } else {
                         $logger->addError("Sessions - Session NOT created: {$session_name}");
                     }
                 }
                 $session_counter++;
             } else {
                 $sessionId = null;
                 if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_' . $extraFieldId])) {
                     $sessionId = self::getSessionIdFromOriginalId($enreg['extra_' . $extraFieldId], $extraFieldId);
                     if (empty($sessionId)) {
                         $my_session_result = false;
                     } else {
                         $my_session_result = true;
                     }
                 } else {
                     $my_session_result = self::get_session_by_name($enreg['SessionName']);
                 }
                 if ($my_session_result === false) {
                     // Creating a session.
                     $sql = "INSERT IGNORE INTO {$tbl_session} SET\n                                name = '{$session_name}',\n                                id_coach = '{$coach_id}',\n                                access_start_date = '{$date_start}',\n                                access_end_date = '{$date_end}',\n                                visibility = '{$visibilityAfterExpirationPerSession}',\n                                session_category_id = '{$session_category_id}' " . $extraParameters . $extraSessionParameters;
                     Database::query($sql);
                     // We get the last insert id.
                     $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
                     $session_id = $my_session_result['id'];
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         if ($debug) {
                             $logger->addInfo("Sessions - #{$session_id} created: {$session_name}");
                         }
                         // Delete session-user relation only for students
                         $sql = "DELETE FROM {$tbl_session_user}\n                                    WHERE session_id = '{$session_id}' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
                         Database::query($sql);
                         $sql = "DELETE FROM {$tbl_session_course} WHERE session_id = '{$session_id}'";
                         Database::query($sql);
                         // Delete session-course-user relationships students and coaches.
                         if ($updateCourseCoaches) {
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status in ('0', '2')";
                             Database::query($sql);
                         } else {
                             // Delete session-course-user relation ships *only* for students.
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status <> 2";
                             Database::query($sql);
                         }
                     }
                 } else {
                     if ($debug) {
                         $logger->addError("Sessions - Session to be updated: {$session_name}");
                     }
                     // Updating the session.
                     $params = array('id_coach' => $coach_id, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'visibility' => $visibilityAfterExpirationPerSession, 'session_category_id' => $session_category_id);
                     if (!empty($sessionDescription)) {
                         $params['description'] = $sessionDescription;
                     }
                     if (!empty($fieldsToAvoidUpdate)) {
                         foreach ($fieldsToAvoidUpdate as $field) {
                             unset($params[$field]);
                         }
                     }
                     if (isset($sessionId) && !empty($sessionId)) {
                         if (!empty($enreg['SessionName'])) {
                             $params['name'] = $enreg['SessionName'];
                         }
                         $session_id = $sessionId;
                     } else {
                         $row = Database::query("SELECT id FROM {$tbl_session} WHERE name = '{$session_name}'");
                         list($session_id) = Database::fetch_array($row);
                     }
                     if ($session_id) {
                         if ($debug) {
                             $logger->addError("Sessions - Session to be updated #{$session_id}");
                         }
                         $sessionInfo = api_get_session_info($session_id);
                         $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
                         if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
                             if (empty($sessionInfo['nb_days_access_before_beginning']) || !empty($sessionInfo['nb_days_access_before_beginning']) && $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning) {
                                 $params['nb_days_access_before_beginning'] = intval($daysCoachAccessBeforeBeginning);
                             }
                             if (empty($sessionInfo['nb_days_access_after_end']) || !empty($sessionInfo['nb_days_access_after_end']) && $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning) {
                                 $params['nb_days_access_after_end'] = intval($daysCoachAccessAfterBeginning);
                             }
                         }
                         Database::update($tbl_session, $params, array('id = ?' => $session_id));
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         // Delete session-user relation only for students
                         $sql = "DELETE FROM {$tbl_session_user}\n                                    WHERE session_id = '{$session_id}' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
                         Database::query($sql);
                         $sql = "DELETE FROM {$tbl_session_course} WHERE session_id = '{$session_id}'";
                         Database::query($sql);
                         // Delete session-course-user relationships students and coaches.
                         if ($updateCourseCoaches) {
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status in ('0', '2')";
                             Database::query($sql);
                         } else {
                             // Delete session-course-user relation ships *only* for students.
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status <> 2";
                             Database::query($sql);
                         }
                     } else {
                         if ($debug) {
                             $logger->addError("Sessions - Session not found");
                         }
                     }
                 }
                 $session_counter++;
             }
             $sessionList[] = $session_id;
             $users = explode('|', $enreg['Users']);
             // Adding the relationship "Session - User" for students
             $userList = array();
             if (is_array($users)) {
                 foreach ($users as $user) {
                     $user_id = UserManager::get_user_id_from_username($user);
                     if ($user_id !== false) {
                         $userList[] = $user_id;
                         // Insert new users.
                         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                    user_id = '{$user_id}',\n                                    session_id = '{$session_id}',\n                                    registered_at = '" . api_get_utc_datetime() . "'";
                         Database::query($sql);
                         if ($debug) {
                             $logger->addInfo("Sessions - Adding User #{$user_id} ({$user}) to session #{$session_id}");
                         }
                         $user_counter++;
                     }
                 }
             }
             if ($deleteUsersNotInList) {
                 // Getting user in DB in order to compare to the new list.
                 $usersListInDatabase = self::get_users_by_session($session_id, 0);
                 if (!empty($usersListInDatabase)) {
                     if (empty($userList)) {
                         foreach ($usersListInDatabase as $userInfo) {
                             self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
                         }
                     } else {
                         foreach ($usersListInDatabase as $userInfo) {
                             if (!in_array($userInfo['user_id'], $userList)) {
                                 self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
                             }
                         }
                     }
                 }
             }
             $courses = explode('|', $enreg['Courses']);
             // See BT#6449
             $onlyAddFirstCoachOrTeacher = false;
             if ($sessionWithCoursesModifier) {
                 if (count($courses) >= 2) {
                     // Only first teacher in course session;
                     $onlyAddFirstCoachOrTeacher = true;
                     // Remove all teachers from course.
                     $removeAllTeachersFromCourse = false;
                 }
             }
             foreach ($courses as $course) {
                 $courseArray = bracketsToArray($course);
                 $course_code = $courseArray[0];
                 if (CourseManager::course_exists($course_code)) {
                     $courseInfo = api_get_course_info($course_code);
                     $courseId = $courseInfo['real_id'];
                     // Adding the course to a session.
                     $sql = "INSERT IGNORE INTO {$tbl_session_course}\n                                SET c_id = '{$courseId}', session_id='{$session_id}'";
                     Database::query($sql);
                     SessionManager::installCourse($session_id, $courseInfo['real_id']);
                     if ($debug) {
                         $logger->addInfo("Sessions - Adding course '{$course_code}' to session #{$session_id}");
                     }
                     $course_counter++;
                     $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
                     $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
                     $course_users = explode(',', $course_users);
                     $course_coaches = explode(',', $course_coaches);
                     // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
                     $addTeachersToSession = true;
                     if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
                         $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
                     }
                     // If any user provided for a course, use the users array.
                     if (empty($course_users)) {
                         if (!empty($userList)) {
                             SessionManager::subscribe_users_to_session_course($userList, $session_id, $course_code);
                             if ($debug) {
                                 $msg = "Sessions - Adding student list " . implode(', #', $userList) . " to course: '{$course_code}' and session #{$session_id}";
                                 $logger->addInfo($msg);
                             }
                         }
                     }
                     // Adding coaches to session course user.
                     if (!empty($course_coaches)) {
                         $savedCoaches = array();
                         // only edit if add_teachers_to_sessions_courses is set.
                         if ($addTeachersToSession) {
                             if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
                                 // Adding course teachers as course session teachers.
                                 $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
                                 if (!empty($alreadyAddedTeachers)) {
                                     $teachersToAdd = array();
                                     foreach ($alreadyAddedTeachers as $user) {
                                         $teachersToAdd[] = $user['username'];
                                     }
                                     $course_coaches = array_merge($course_coaches, $teachersToAdd);
                                 }
                             }
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     // Just insert new coaches
                                     SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
                                     if ($debug) {
                                         $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                     }
                                     $savedCoaches[] = $coach_id;
                                 } else {
                                     $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                                 }
                             }
                         }
                         // Custom courses/session coaches
                         $teacherToAdd = null;
                         // Only one coach is added.
                         if ($onlyAddFirstCoachOrTeacher == true) {
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $teacherToAdd = $coach_id;
                                     break;
                                 }
                             }
                             // Un subscribe everyone that's not in the list.
                             $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
                             if (!empty($teacherList)) {
                                 foreach ($teacherList as $teacher) {
                                     if ($teacherToAdd != $teacher['user_id']) {
                                         CourseManager::unsubscribe_user($teacher['user_id'], $course_code);
                                     }
                                 }
                             }
                             if (!empty($teacherToAdd)) {
                                 SessionManager::updateCoaches($session_id, $courseId, array($teacherToAdd), true);
                                 CourseManager::subscribe_user($teacherToAdd, $course_code, COURSEMANAGER);
                             }
                         }
                         // See BT#6449#note-195
                         // All coaches are added.
                         if ($removeAllTeachersFromCourse) {
                             $teacherToAdd = null;
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $teacherToAdd[] = $coach_id;
                                 }
                             }
                             if (!empty($teacherToAdd)) {
                                 // Deleting all course teachers and adding the only coach as teacher.
                                 $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
                                 if (!empty($teacherList)) {
                                     foreach ($teacherList as $teacher) {
                                         if (!in_array($teacher['user_id'], $teacherToAdd)) {
                                             CourseManager::unsubscribe_user($teacher['user_id'], $course_code);
                                         }
                                     }
                                 }
                                 foreach ($teacherToAdd as $teacherId) {
                                     CourseManager::subscribe_user($teacherId, $course_code, COURSEMANAGER);
                                 }
                             }
                         }
                         // Continue default behaviour.
                         if ($onlyAddFirstCoachOrTeacher == false) {
                             // Checking one more time see BT#6449#note-149
                             $coaches = SessionManager::getCoachesByCourseSession($session_id, $courseId);
                             // Update coaches if only there's 1 course see BT#6449#note-189
                             if (empty($coaches) || count($courses) == 1) {
                                 foreach ($course_coaches as $course_coach) {
                                     $course_coach = trim($course_coach);
                                     $coach_id = UserManager::get_user_id_from_username($course_coach);
                                     if ($coach_id !== false) {
                                         // Just insert new coaches
                                         SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
                                         if ($debug) {
                                             $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                         }
                                         $savedCoaches[] = $coach_id;
                                     } else {
                                         $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                                     }
                                 }
                             }
                         }
                     }
                     // Adding Students, updating relationship "Session - Course - User".
                     $course_users = array_filter($course_users);
                     if (!empty($course_users)) {
                         foreach ($course_users as $user) {
                             $user_id = UserManager::get_user_id_from_username($user);
                             if ($user_id !== false) {
                                 SessionManager::subscribe_users_to_session_course(array($user_id), $session_id, $course_code);
                                 if ($debug) {
                                     $logger->addInfo("Sessions - Adding student: user #{$user_id} ({$user}) to course: '{$course_code}' and session #{$session_id}");
                                 }
                             } else {
                                 $error_message .= get_lang('UserDoesNotExist') . ': ' . $user . $eol;
                             }
                         }
                     }
                     $inserted_in_course[$course_code] = $courseInfo['title'];
                 }
             }
             $access_url_id = api_get_current_access_url_id();
             UrlManager::add_session_to_url($session_id, $access_url_id);
             $sql = "UPDATE {$tbl_session} SET nbr_users = '{$user_counter}', nbr_courses = '{$course_counter}' WHERE id = '{$session_id}'";
             Database::query($sql);
         }
     }
     return array('error_message' => $error_message, 'session_counter' => $session_counter, 'session_list' => $sessionList);
 }
Пример #3
0
         $rs_session = Database::query($sql_session);
         $session_id = Database::query("SELECT id FROM {$tbl_session} WHERE name='{$session_name}'");
         list($session_id) = Database::fetch_array($session_id);
         Database::query("DELETE FROM {$tbl_session_user} WHERE id_session='{$session_id}'");
         Database::query("DELETE FROM {$tbl_session_course} WHERE id_session='{$session_id}'");
         Database::query("DELETE FROM {$tbl_session_course_user} WHERE id_session='{$session_id}'");
     }
 }
 // Associate the session with access_url.
 global $_configuration;
 if ($_configuration['multiple_access_urls']) {
     $access_url_id = api_get_current_access_url_id();
     UrlManager::add_session_to_url($session_id, $access_url_id);
 } else {
     // We fill by default the access_url_rel_session table.
     UrlManager::add_session_to_url($session_id, 1);
 }
 // Adding users to the new session.
 foreach ($node_session->User as $node_user) {
     $username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
     $user_id = UserManager::get_user_id_from_username($username);
     if ($user_id !== false) {
         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                        id_user='******',\n                                        id_session = '{$session_id}'";
         $rs_user = Database::query($sql);
         $user_counter++;
     }
 }
 // Adding courses to a session.
 foreach ($node_session->Course as $node_course) {
     $course_code = Database::escape_string(trim(api_utf8_decode($node_course->CourseCode)));
     // Verify that the course pointed by the course code node exists.
Пример #4
0
 /**
  * Updates the access_url_rel_session table with a given user list
  * @author Julio Montoya
  * @param array user list
  * @param int access_url_id
  * */
 public static function update_urls_rel_session($session_list, $access_url_id)
 {
     $table_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
     $sql = "SELECT session_id FROM {$table_url_rel_session} WHERE access_url_id=" . intval($access_url_id);
     $result = Database::query($sql);
     $existing_sessions = array();
     while ($row = Database::fetch_array($result)) {
         $existing_sessions[] = $row['session_id'];
     }
     // Adding users
     foreach ($session_list as $session) {
         if (!in_array($session, $existing_sessions)) {
             if (!empty($session) && !empty($access_url_id)) {
                 UrlManager::add_session_to_url($session, $access_url_id);
             }
         }
     }
     // Deleting old users
     foreach ($existing_sessions as $existing_session) {
         if (!in_array($existing_session, $session_list)) {
             if (!empty($existing_session) && !empty($access_url_id)) {
                 UrlManager::delete_url_rel_session($existing_session, $access_url_id);
             }
         }
     }
 }