*/
class Agenda
{
public $events = [];
/** @var string Current type */
public $type = 'personal';
public $types = ['personal', 'admin', 'course'];
public $sessionId = 0;
public $senderId;
/** @var array */
public $course;
/** @var string */
public $comment;
public $eventStudentPublicationColor;
/** @var array */
private $sessionInfo;
/** @var bool */
private $isAllowedToEdit;
/**
* Constructor.
*
* @param string $type
* @param int $senderId Optional The user sender ID
* @param int $courseId Optional. The course ID
* @param int $sessionId Optional The session ID
*/
public function __construct(
$type,
$senderId = 0,
$courseId = 0,
$sessionId = 0
) {
// Table definitions
$this->tbl_global_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
$this->tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
$this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
$this->table_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
$this->setType($type);
$this->setSenderId($senderId ?: api_get_user_id());
$isAllowToEdit = false;
switch ($type) {
case 'course':
$sessionId = $sessionId ?: api_get_session_id();
$sessionInfo = api_get_session_info($sessionId);
$this->setSessionId($sessionId);
$this->setSessionInfo($sessionInfo);
// Setting the course object if we are in a course
$courseInfo = api_get_course_info_by_id($courseId);
if (!empty($courseInfo)) {
$this->set_course($courseInfo);
}
// Check if teacher/admin rights.
$isAllowToEdit = api_is_allowed_to_edit(false, true);
// Check course setting.
if (api_get_course_setting('allow_user_edit_agenda') == '1'
&& api_is_allowed_in_course()
) {
$isAllowToEdit = true;
}
$groupId = api_get_group_id();
if (!empty($groupId)) {
$groupInfo = GroupManager::get_group_properties($groupId);
$userHasAccess = GroupManager::user_has_access(
api_get_user_id(),
$groupInfo['iid'],
GroupManager::GROUP_TOOL_CALENDAR
);
$isTutor = GroupManager::is_tutor_of_group(
api_get_user_id(),
$groupInfo
);
$isGroupAccess = $userHasAccess || $isTutor;
$isAllowToEdit = false;
if ($isGroupAccess) {
$isAllowToEdit = true;
}
}
if (false === $isAllowToEdit && !empty($sessionId)) {
$allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
if ($allowDhrToEdit) {
$isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, api_get_user_id());
if ($isHrm) {
$isAllowToEdit = true;
}
}
}
break;
case 'admin':
$isAllowToEdit = api_is_platform_admin();
break;
case 'personal':
$isAllowToEdit = !api_is_anonymous();
break;
}
$this->setIsAllowedToEdit($isAllowToEdit);
$this->events = [];
$agendaColors = array_merge(
[
'platform' => 'red', //red
'course' => '#458B00', //green
'group' => '#A0522D', //siena
'session' => '#00496D', // kind of green
'other_session' => '#999', // kind of green
'personal' => 'steel blue', //steel blue
'student_publication' => '#FF8C00', //DarkOrange
],
api_get_configuration_value('agenda_colors') ?: []
);
// Event colors
$this->event_platform_color = $agendaColors['platform'];
$this->event_course_color = $agendaColors['course'];
$this->event_group_color = $agendaColors['group'];
$this->event_session_color = $agendaColors['session'];
$this->eventOtherSessionColor = $agendaColors['other_session'];
$this->event_personal_color = $agendaColors['personal'];
$this->eventStudentPublicationColor = $agendaColors['student_publication'];
}
/**
* @param int $senderId
*/
public function setSenderId($senderId)
{
$this->senderId = (int) $senderId;
}
/**
* @return int
*/
public function getSenderId()
{
return $this->senderId;
}
/**
* @param string $type can be 'personal', 'admin' or 'course'
*/
public function setType($type)
{
$type = (string) trim($type);
$typeList = $this->getTypes();
if (in_array($type, $typeList, true)) {
$this->type = $type;
}
}
/**
* Returns the type previously set (and filtered) through setType
* If setType() was not called, then type defaults to "personal" as
* set in the class definition.
*/
public function getType()
{
if (isset($this->type)) {
return $this->type;
}
}
/**
* @param int $id
*/
public function setSessionId($id)
{
$this->sessionId = (int) $id;
}
/**
* @param array $sessionInfo
*/
public function setSessionInfo($sessionInfo)
{
$this->sessionInfo = $sessionInfo;
}
/**
* @return int $id
*/
public function getSessionId()
{
return $this->sessionId;
}
/**
* @param array $courseInfo
*/
public function set_course($courseInfo)
{
$this->course = $courseInfo;
}
/**
* @return array
*/
public function getTypes()
{
return $this->types;
}
/**
* Adds an event to the calendar.
*
* @param string $start datetime format: 2012-06-14 09:00:00 in local time
* @param string $end datetime format: 2012-06-14 09:00:00 in local time
* @param string $allDay (true, false)
* @param string $title
* @param string $content
* @param array $usersToSend array('everyone') or a list of user/group ids
* @param bool $addAsAnnouncement event as a *course* announcement
* @param int $parentEventId
* @param array $attachmentArray array of $_FILES['']
* @param array $attachmentCommentList
* @param string $eventComment
* @param string $color
*
* @return int
*/
public function addEvent(
$start,
$end,
$allDay,
$title,
$content,
$usersToSend = [],
$addAsAnnouncement = false,
$parentEventId = null,
$attachmentArray = [],
$attachmentCommentList = [],
$eventComment = null,
$color = '',
array $inviteesList = [],
bool $isCollective = false,
array $reminders = [],
int $careerId = 0,
int $promotionId = 0,
int $subscriptionVisibility = 0,
?int $subscriptionItemId = null,
int $maxSubscriptions = 0
) {
$start = api_get_utc_datetime($start);
$end = api_get_utc_datetime($end);
$allDay = isset($allDay) && ($allDay === 'true' || $allDay == 1) ? 1 : 0;
$id = null;
$em = Database::getManager();
switch ($this->type) {
case 'personal':
$attributes = [
'user' => api_get_user_id(),
'title' => $title,
'text' => $content,
'date' => $start,
'enddate' => $end,
'all_day' => $allDay,
'color' => $color,
];
$id = Database::insert(
$this->tbl_personal_agenda,
$attributes
);
if (api_get_configuration_value('agenda_collective_invitations')) {
Agenda::saveCollectiveProperties($inviteesList, $isCollective, $id);
}
if (api_get_configuration_value('agenda_event_subscriptions') && api_is_platform_admin()) {
$personalEvent = $em->find(PersonalAgenda::class, $id);
$personalEvent
->setSubscriptionVisibility($subscriptionVisibility)
->setSubscriptionItemId($subscriptionItemId ?: null)
;
$subscription = (new AgendaEventSubscription())
->setCreator(api_get_user_entity(api_get_user_id()))
->setMaxAttendees($subscriptionVisibility > 0 ? $maxSubscriptions : 0)
;
$personalEvent
->setCollective(false)
->setInvitation($subscription)
;
$em->flush();
}
break;
case 'course':
$attributes = [
'title' => $title,
'content' => $content,
'start_date' => $start,
'end_date' => $end,
'all_day' => $allDay,
'session_id' => $this->getSessionId(),
'c_id' => $this->course['real_id'],
'comment' => $eventComment,
'color' => $color,
];
if (!empty($parentEventId)) {
$attributes['parent_event_id'] = $parentEventId;
}
$senderId = $this->getSenderId();
$sessionId = $this->getSessionId();
// Simple course event.
$id = Database::insert($this->tbl_course_agenda, $attributes);
if ($id) {
$sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
Database::query($sql);
$groupId = api_get_group_id();
$groupInfo = [];
if ($groupId) {
$groupInfo = GroupManager::get_group_properties(
$groupId
);
}
if (!empty($usersToSend)) {
$sendTo = $this->parseSendToArray($usersToSend);
if ($sendTo['everyone']) {
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'AgendaAdded',
$senderId,
$groupInfo,
'',
$start,
$end,
$sessionId
);
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'visible',
$senderId,
$groupInfo,
'',
$start,
$end,
$sessionId
);
} else {
// Storing the selected groups
if (!empty($sendTo['groups'])) {
foreach ($sendTo['groups'] as $group) {
$groupInfoItem = [];
if ($group) {
$groupInfoItem = GroupManager::get_group_properties($group);
}
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'AgendaAdded',
$senderId,
$groupInfoItem,
0,
$start,
$end,
$sessionId
);
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'visible',
$senderId,
$groupInfoItem,
0,
$start,
$end,
$sessionId
);
}
}
// storing the selected users
if (!empty($sendTo['users'])) {
foreach ($sendTo['users'] as $userId) {
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'AgendaAdded',
$senderId,
$groupInfo,
$userId,
$start,
$end,
$sessionId
);
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'visible',
$senderId,
$groupInfo,
$userId,
$start,
$end,
$sessionId
);
}
}
}
}
// Add announcement.
if ($addAsAnnouncement) {
$this->storeAgendaEventAsAnnouncement(
$id,
$usersToSend
);
}
// Add attachment.
if (isset($attachmentArray) && !empty($attachmentArray)) {
$counter = 0;
foreach ($attachmentArray as $attachmentItem) {
$this->addAttachment(
$id,
$attachmentItem,
$attachmentCommentList[$counter],
$this->course
);
$counter++;
}
}
}
break;
case 'admin':
if (api_is_platform_admin()) {
$attributes = [
'title' => $title,
'content' => $content,
'start_date' => $start,
'end_date' => $end,
'all_day' => $allDay,
'access_url_id' => api_get_current_access_url_id(),
];
if (api_get_configuration_value('allow_careers_in_global_agenda')) {
$attributes['career_id'] = $careerId;
$attributes['promotion_id'] = $promotionId;
}
$id = Database::insert(
$this->tbl_global_agenda,
$attributes
);
}
break;
}
if (api_get_configuration_value('agenda_reminders')) {
foreach ($reminders as $reminder) {
$this->addReminder($id, $reminder[0], $reminder[1]);
}
}
return $id;
}
/**
* @throws Exception
*/
public function addReminder($eventId, $count, $period)
{
switch ($period) {
case 'i':
$dateInterval = DateInterval::createFromDateString("$count minutes");
break;
case 'h':
$dateInterval = DateInterval::createFromDateString("$count hours");
break;
case 'd':
$dateInterval = DateInterval::createFromDateString("$count days");
break;
default:
return null;
}
$agendaReminder = new AgendaReminder();
$agendaReminder
->setType($this->type)
->setEventId($eventId)
->setDateInterval($dateInterval)
;
$em = Database::getManager();
$em->persist($agendaReminder);
$em->flush();
}
public function removeReminders(int $eventId, int $count, string $period)
{
switch ($period) {
case 'i':
$dateInterval = DateInterval::createFromDateString("$count minutes");
break;
case 'h':
$dateInterval = DateInterval::createFromDateString("$count hours");
break;
case 'd':
$dateInterval = DateInterval::createFromDateString("$count days");
break;
default:
return null;
}
Database::getManager()
->createQuery(
'DELETE FROM ChamiloCoreBundle:AgendaReminder ar
WHERE ar.eventId = :eventId AND ar.type = :type AND ar.dateInterval = :dateInterval'
)
->setParameters(
[
'eventId' => $eventId,
'type' => $this->type,
'dateInterval' => $dateInterval,
]
)
->execute();
}
public function getReminder(int $eventId, int $count, string $period)
{
switch ($period) {
case 'i':
$dateInterval = DateInterval::createFromDateString("$count minutes");
break;
case 'h':
$dateInterval = DateInterval::createFromDateString("$count hours");
break;
case 'd':
$dateInterval = DateInterval::createFromDateString("$count days");
break;
default:
return null;
}
$em = Database::getManager();
$remindersRepo = $em->getRepository('ChamiloCoreBundle:AgendaReminder');
return $remindersRepo->findOneBy(
[
'type' => $this->type,
'dateInterval' => $dateInterval,
'eventId' => $eventId,
]
);
}
/**
* @param int $eventId
* @param int $courseId
*
* @return array
*/
public function getRepeatedInfoByEvent($eventId, $courseId)
{
$repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
$eventId = (int) $eventId;
$courseId = (int) $courseId;
$sql = "SELECT * FROM $repeatTable
WHERE c_id = $courseId AND cal_id = $eventId";
$res = Database::query($sql);
$repeatInfo = [];
if (Database::num_rows($res) > 0) {
$repeatInfo = Database::fetch_array($res, 'ASSOC');
}
return $repeatInfo;
}
/**
* @param string $type
* @param string $startEvent in UTC
* @param string $endEvent in UTC
* @param string $repeatUntilDate in UTC
*
* @throws Exception
*
* @return array with local times
*/
public function generateDatesByType($type, $startEvent, $endEvent, $repeatUntilDate)
{
$continue = true;
$repeatUntilDate = new DateTime($repeatUntilDate, new DateTimeZone('UTC'));
$loopMax = 365;
$counter = 0;
$list = [];
switch ($type) {
case 'daily':
$interval = 'P1D';
break;
case 'weekly':
$interval = 'P1W';
break;
case 'monthlyByDate':
$interval = 'P1M';
break;
case 'monthlyByDay':
// not yet implemented
break;
case 'monthlyByDayR':
// not yet implemented
break;
case 'yearly':
$interval = 'P1Y';
break;
}
if (empty($interval)) {
return [];
}
$timeZone = api_get_timezone();
while ($continue) {
$startDate = new DateTime($startEvent, new DateTimeZone('UTC'));
$endDate = new DateTime($endEvent, new DateTimeZone('UTC'));
$startDate->add(new DateInterval($interval));
$endDate->add(new DateInterval($interval));
$newStartDate = $startDate->format('Y-m-d H:i:s');
$newEndDate = $endDate->format('Y-m-d H:i:s');
$startEvent = $newStartDate;
$endEvent = $newEndDate;
if ($endDate > $repeatUntilDate) {
break;
}
// @todo remove comment code
// The code below was not adpating to saving light time but was doubling the difference with UTC time.
// Might be necessary to adapt to update saving light time difference.
/* $startDateInLocal = new DateTime($newStartDate, new DateTimeZone($timeZone));
if ($startDateInLocal->format('I') == 0) {
// Is saving time? Then fix UTC time to add time
$seconds = $startDateInLocal->getOffset();
$startDate->add(new DateInterval("PT".$seconds."S"));
//$startDateFixed = $startDate->format('Y-m-d H:i:s');
//$startDateInLocalFixed = new DateTime($startDateFixed, new DateTimeZone($timeZone));
//$newStartDate = $startDateInLocalFixed->format('Y-m-d H:i:s');
//$newStartDate = $startDate->setTimezone(new DateTimeZone($timeZone))->format('Y-m-d H:i:s');
}
$endDateInLocal = new DateTime($newEndDate, new DateTimeZone($timeZone));
if ($endDateInLocal->format('I') == 0) {
// Is saving time? Then fix UTC time to add time
$seconds = $endDateInLocal->getOffset();
$endDate->add(new DateInterval("PT".$seconds."S"));
//$endDateFixed = $endDate->format('Y-m-d H:i:s');
//$endDateInLocalFixed = new DateTime($endDateFixed, new DateTimeZone($timeZone));
//$newEndDate = $endDateInLocalFixed->format('Y-m-d H:i:s');
}
*/
$newStartDate = $startDate->setTimezone(new DateTimeZone($timeZone))->format('Y-m-d H:i:s');
$newEndDate = $endDate->setTimezone(new DateTimeZone($timeZone))->format('Y-m-d H:i:s');
$list[] = ['start' => $newStartDate, 'end' => $newEndDate];
$counter++;
// just in case stop if more than $loopMax
if ($counter > $loopMax) {
break;
}
}
return $list;
}
/**
* @param int $eventId
* @param string $type
* @param string $end in UTC
* @param array $sentTo
*
* @return bool
*/
public function addRepeatedItem($eventId, $type, $end, $sentTo = [])
{
$t_agenda = Database::get_course_table(TABLE_AGENDA);
$t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
if (empty($this->course)) {
return false;
}
$courseId = $this->course['real_id'];
$eventId = (int) $eventId;
$sql = "SELECT title, content, start_date, end_date, all_day
FROM $t_agenda
WHERE c_id = $courseId AND id = $eventId";
$res = Database::query($sql);
if (Database::num_rows($res) !== 1) {
return false;
}
$typeList = [
'daily',
'weekly',
'monthlyByDate',
'monthlyByDay',
'monthlyByDayR',
'yearly',
];
if (!in_array($type, $typeList)) {
return false;
}
$now = time();
// The event has to repeat *in the future*. We don't allow repeated
// events in the past.
$endTimeStamp = api_strtotime($end, 'UTC');
if ($endTimeStamp < $now) {
return false;
}
$row = Database::fetch_array($res);
$title = $row['title'];
$content = $row['content'];
$allDay = $row['all_day'];
$type = Database::escape_string($type);
$end = Database::escape_string($end);
$sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
VALUES ($courseId, '$eventId', '$type', '$endTimeStamp')";
Database::query($sql);
$generatedDates = $this->generateDatesByType($type, $row['start_date'], $row['end_date'], $end);
if (empty($generatedDates)) {
return false;
}
foreach ($generatedDates as $dateInfo) {
// $start = api_get_local_time($dateInfo['start']);
// $end = api_get_local_time($dateInfo['end']);
// On line 529 in function generateDatesByType there is a @todo remove comment code
// just before the part updating the date in local time so keep both synchronised
$start = $dateInfo['start'];
$end = $dateInfo['end'];
$this->addEvent(
$start,
$end,
$allDay,
$title,
$content,
$sentTo,
false,
$eventId
);
}
return true;
}
/**
* @param int $item_id
* @param array $sentTo
*
* @return int
*/
public function storeAgendaEventAsAnnouncement($item_id, $sentTo = [])
{
$table_agenda = Database::get_course_table(TABLE_AGENDA);
$courseId = api_get_course_int_id();
// Check params
if (empty($item_id) || $item_id != strval(intval($item_id))) {
return -1;
}
// Get the agenda item.
$item_id = intval($item_id);
$sql = "SELECT * FROM $table_agenda
WHERE c_id = $courseId AND id = ".$item_id;
$res = Database::query($sql);
if (Database::num_rows($res) > 0) {
$row = Database::fetch_array($res, 'ASSOC');
// Sending announcement
if (!empty($sentTo)) {
$id = AnnouncementManager::add_announcement(
api_get_course_info(),
api_get_session_id(),
$row['title'],
$row['content'],
$sentTo,
null,
null,
$row['end_date']
);
AnnouncementManager::sendEmail(
api_get_course_info(),
api_get_session_id(),
$id
);
return $id;
}
}
return -1;
}
/**
* Edits an event.
*
* @param int $id
* @param string $start datetime format: 2012-06-14 09:00:00
* @param string $end datetime format: 2012-06-14 09:00:00
* @param int $allDay is all day 'true' or 'false'
* @param string $title
* @param string $content
* @param array $usersToSend
* @param array $attachmentArray
* @param array $attachmentCommentList
* @param string $comment
* @param string $color
* @param bool $addAnnouncement
* @param bool $updateContent
* @param int $authorId
*
* @return bool
*/
public function editEvent(
$id,
$start,
$end,
$allDay,
$title,
$content,
$usersToSend = [],
$attachmentArray = [],
$attachmentCommentList = [],
$comment = null,
$color = '',
$addAnnouncement = false,
$updateContent = true,
$authorId = 0,
array $inviteesList = [],
bool $isCollective = false,
array $remindersList = [],
int $careerId = 0,
int $promotionId = 0,
int $subscriptionVisibility = 0,
?int $subscriptionItemId = null,
int $maxSubscriptions = 0,
array $subscribers = []
) {
$id = (int) $id;
$start = api_get_utc_datetime($start);
$end = api_get_utc_datetime($end);
$allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
$currentUserId = api_get_user_id();
$authorId = empty($authorId) ? $currentUserId : (int) $authorId;
$em = Database::getManager();
switch ($this->type) {
case 'personal':
$eventInfo = $this->get_event($id);
if ($eventInfo['user'] != $currentUserId
&& (
api_get_configuration_value('agenda_collective_invitations')
&& !self::isUserInvitedInEvent($id, $currentUserId)
)
) {
break;
}
$attributes = [
'title' => $title,
'date' => $start,
'enddate' => $end,
'all_day' => $allDay,
];
if ($updateContent) {
$attributes['text'] = $content;
}
if (!empty($color)) {
$attributes['color'] = $color;
}
Database::update(
$this->tbl_personal_agenda,
$attributes,
['id = ?' => $id]
);
if (api_get_configuration_value('agenda_collective_invitations')) {
Agenda::saveCollectiveProperties($inviteesList, $isCollective, $id);
}
if (api_get_configuration_value('agenda_event_subscriptions') && api_is_platform_admin()) {
$personalEvent = $em->find(PersonalAgenda::class, $id);
$personalEvent->setSubscriptionVisibility($subscriptionVisibility);
/** @var AgendaEventSubscription $subscription */
$subscription = $personalEvent->getInvitation();
$subscription->setMaxAttendees($subscriptionVisibility > 0 ? $maxSubscriptions : 0);
if ($personalEvent->getSubscriptionItemId() != $subscriptionItemId) {
$personalEvent->setSubscriptionItemId($subscriptionItemId ?: null);
$subscription->removeInvitees();
} else {
$subscription->removeInviteesNotInIdList($subscribers);
}
$em->flush();
}
break;
case 'course':
$eventInfo = $this->get_event($id);
if (empty($eventInfo)) {
return false;
}
$groupId = api_get_group_id();
$groupIid = 0;
$groupInfo = [];
if ($groupId) {
$groupInfo = GroupManager::get_group_properties($groupId);
if ($groupInfo) {
$groupIid = $groupInfo['iid'];
}
}
$courseId = $this->course['real_id'];
if (empty($courseId)) {
return false;
}
if (!$this->getIsAllowedToEdit()) {
return false;
}
$attributes = [
'title' => $title,
'start_date' => $start,
'end_date' => $end,
'all_day' => $allDay,
'comment' => $comment,
];
if ($updateContent) {
$attributes['content'] = $content;
}
if (!empty($color)) {
$attributes['color'] = $color;
}
Database::update(
$this->tbl_course_agenda,
$attributes,
[
'id = ? AND c_id = ? AND session_id = ? ' => [
$id,
$courseId,
$this->sessionId,
],
]
);
if (!empty($usersToSend)) {
$sendTo = $this->parseSendToArray($usersToSend);
$usersToDelete = array_diff(
$eventInfo['send_to']['users'],
$sendTo['users']
);
$usersToAdd = array_diff(
$sendTo['users'],
$eventInfo['send_to']['users']
);
$groupsToDelete = array_diff(
$eventInfo['send_to']['groups'],
$sendTo['groups']
);
$groupToAdd = array_diff(
$sendTo['groups'],
$eventInfo['send_to']['groups']
);
if ($sendTo['everyone']) {
// Delete all from group
if (isset($eventInfo['send_to']['groups']) &&
!empty($eventInfo['send_to']['groups'])
) {
foreach ($eventInfo['send_to']['groups'] as $group) {
$groupIidItem = 0;
if ($group) {
$groupInfoItem = GroupManager::get_group_properties(
$group
);
if ($groupInfoItem) {
$groupIidItem = $groupInfoItem['iid'];
}
}
api_item_property_delete(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
0,
$groupIidItem,
$this->sessionId
);
}
}
// Storing the selected users.
if (isset($eventInfo['send_to']['users']) &&
!empty($eventInfo['send_to']['users'])
) {
foreach ($eventInfo['send_to']['users'] as $userId) {
api_item_property_delete(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
$userId,
$groupIid,
$this->sessionId
);
}
}
// Add to everyone only.
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'visible',
$authorId,
$groupInfo,
null,
$start,
$end,
$this->sessionId
);
} else {
// Delete "everyone".
api_item_property_delete(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
0,
0,
$this->sessionId
);
// Add groups
if (!empty($groupToAdd)) {
foreach ($groupToAdd as $group) {
$groupInfoItem = [];
if ($group) {
$groupInfoItem = GroupManager::get_group_properties(
$group
);
}
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'visible',
$authorId,
$groupInfoItem,
0,
$start,
$end,
$this->sessionId
);
}
}
// Delete groups.
if (!empty($groupsToDelete)) {
foreach ($groupsToDelete as $group) {
$groupIidItem = 0;
$groupInfoItem = [];
if ($group) {
$groupInfoItem = GroupManager::get_group_properties(
$group
);
if ($groupInfoItem) {
$groupIidItem = $groupInfoItem['iid'];
}
}
api_item_property_delete(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
0,
$groupIidItem,
$this->sessionId
);
}
}
// Add users.
if (!empty($usersToAdd)) {
foreach ($usersToAdd as $userId) {
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'visible',
$authorId,
$groupInfo,
$userId,
$start,
$end,
$this->sessionId
);
}
}
// Delete users.
if (!empty($usersToDelete)) {
foreach ($usersToDelete as $userId) {
api_item_property_delete(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
$userId,
$groupInfo,
$this->sessionId
);
}
}
}
}
// Add announcement.
if (isset($addAnnouncement) && !empty($addAnnouncement)) {
$this->storeAgendaEventAsAnnouncement(
$id,
$usersToSend
);
}
// Add attachment.
if (isset($attachmentArray) && !empty($attachmentArray)) {
$counter = 0;
foreach ($attachmentArray as $attachmentItem) {
if (empty($attachmentItem['id'])) {
$this->addAttachment(
$id,
$attachmentItem,
$attachmentCommentList[$counter],
$this->course
);
} else {
$this->updateAttachment(
$attachmentItem['id'],
$id,
$attachmentItem,
$attachmentCommentList[$counter],
$this->course
);
}
$counter++;
}
}
break;
case 'admin':
case 'platform':
if (api_is_platform_admin()) {
$attributes = [
'title' => $title,
'start_date' => $start,
'end_date' => $end,
'all_day' => $allDay,
];
if (api_get_configuration_value('allow_careers_in_global_agenda')) {
$attributes['career_id'] = $careerId;
$attributes['promotion_id'] = $promotionId;
}
if ($updateContent) {
$attributes['content'] = $content;
}
Database::update(
$this->tbl_global_agenda,
$attributes,
['id = ?' => $id]
);
}
break;
}
$this->editReminders($id, $remindersList);
return true;
}
/**
* @param int $id
* @param bool $deleteAllItemsFromSerie
*
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function deleteEvent($id, $deleteAllItemsFromSerie = false)
{
$em = Database::getManager();
switch ($this->type) {
case 'personal':
$eventInfo = $this->get_event($id);
if ($eventInfo['user'] == api_get_user_id()) {
Database::delete(
$this->tbl_personal_agenda,
['id = ?' => $id]
);
} elseif (api_get_configuration_value('agenda_collective_invitations')) {
$currentUser = api_get_user_entity(api_get_user_id());
$eventRepo = $em->getRepository('ChamiloCoreBundle:PersonalAgenda');
$event = $eventRepo->findOneByIdAndInvitee($id, $currentUser);
$invitation = $event ? $event->getInvitation() : null;
if ($invitation) {
$invitation->removeInviteeUser($currentUser);
$em->persist($invitation);
$em->flush();
}
}
break;
case 'course':
$courseId = api_get_course_int_id();
$isAllowToEdit = $this->getIsAllowedToEdit();
if (!empty($courseId) && $isAllowToEdit) {
$eventInfo = $this->get_event($id);
if ($deleteAllItemsFromSerie) {
/* This is one of the children.
Getting siblings and delete 'Em all + the father! */
if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
// Removing items.
$events = $this->getAllRepeatEvents($eventInfo['parent_event_id']);
if (!empty($events)) {
foreach ($events as $event) {
$this->deleteEvent($event['id']);
}
}
// Removing parent.
$this->deleteEvent($eventInfo['parent_event_id']);
} else {
// This is the father looking for the children.
$events = $this->getAllRepeatEvents($id);
if (!empty($events)) {
foreach ($events as $event) {
$this->deleteEvent($event['id']);
}
}
}
}
// Removing from events.
Database::delete(
$this->tbl_course_agenda,
['id = ? AND c_id = ?' => [$id, $courseId]]
);
api_item_property_update(
$this->course,
TOOL_CALENDAR_EVENT,
$id,
'delete',
api_get_user_id()
);
// Removing from series.
Database::delete(
$this->table_repeat,
[
'cal_id = ? AND c_id = ?' => [
$id,
$courseId,
],
]
);
if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
foreach ($eventInfo['attachment'] as $attachment) {
self::deleteAttachmentFile(
$attachment['id'],
$this->course
);
}
}
}
break;
case 'admin':
if (api_is_platform_admin()) {
Database::delete(
$this->tbl_global_agenda,
['id = ?' => $id]
);
}
break;
}
}
public function subscribeCurrentUserToEvent(int $id)
{
if (false === api_get_configuration_value('agenda_event_subscriptions')) {
return;
}
if ('personal' !== $this->type) {
return;
}
$em = Database::getManager();
$currentUser = api_get_user_entity(api_get_user_id());
$personalEvent = $em->find(PersonalAgenda::class, $id);
/** @var AgendaEventSubscription $subscription */
$subscription = $personalEvent ? $personalEvent->getInvitation() : null;
if (!$subscription) {
return;
}
if ($subscription->getInvitees()->count() >= $subscription->getMaxAttendees()
&& $subscription->getMaxAttendees() > 0
) {
return;
}
if (AgendaEventSubscription::SUBSCRIPTION_CLASS === $personalEvent->getSubscriptionVisibility()) {
$objGroup = new UserGroup();
$groupList = $objGroup->getUserGroupListByUser($currentUser->getId(), UserGroup::NORMAL_CLASS);
$groupIdList = array_column($groupList, 'id');
if (!in_array($personalEvent->getSubscriptionItemId(), $groupIdList)) {
return;
}
}
$subscriber = (new AgendaEventSubscriber())
->setUser($currentUser)
;
$subscription->addInvitee($subscriber);
$em->flush();
}
public function unsubscribeCurrentUserToEvent(int $id)
{
if (false === api_get_configuration_value('agenda_event_subscriptions')) {
return;
}
if ('personal' !== $this->type) {
return;
}
$em = Database::getManager();
$currentUser = api_get_user_entity(api_get_user_id());
$personalEvent = $em->find(PersonalAgenda::class, $id);
/** @var AgendaEventSubscription $subscription */
$subscription = $personalEvent ? $personalEvent->getInvitation() : null;
if (!$subscription) {
return;
}
$subscription->removeInviteeUser($currentUser);
$em->flush();
}
/**
* Get agenda events.
*
* @param int $start
* @param int $end
* @param int $courseId
* @param int $groupId
* @param int $user_id
* @param string $format
*
* @return array|string
*/
public function getEvents(
$start,
$end,
$courseId = null,
$groupId = null,
$user_id = 0,
$format = 'json'
) {
switch ($this->type) {
case 'admin':
$this->getPlatformEvents($start, $end);
break;
case 'course':
$courseInfo = api_get_course_info_by_id($courseId);
// Session coach can see all events inside a session.
if (api_is_coach()) {
// Own course
$this->getCourseEvents(
$start,
$end,
$courseInfo,
$groupId,
$this->sessionId,
$user_id
);
// Others
$this->getSessionEvents(
$start,
$end,
$this->sessionId,
$user_id,
$this->eventOtherSessionColor
);
} else {
$this->getCourseEvents(
$start,
$end,
$courseInfo,
$groupId,
$this->sessionId,
$user_id
);
}
break;
case 'personal':
default:
$sessionFilterActive = false;
if (!empty($this->sessionId)) {
$sessionFilterActive = true;
}
if ($sessionFilterActive == false) {
// Getting personal events
$this->getPersonalEvents($start, $end);
// Getting platform/admin events
$this->getPlatformEvents($start, $end);
}
$ignoreVisibility = api_get_configuration_value('personal_agenda_show_all_session_events');
$session_list = [];
// Getting course events
$my_course_list = [];
if (!api_is_anonymous()) {
$session_list = SessionManager::get_sessions_by_user(
api_get_user_id(),
$ignoreVisibility
);
$my_course_list = CourseManager::get_courses_list_by_user_id(
api_get_user_id(),
false
);
}
if (api_is_drh()) {
if (api_drh_can_access_all_session_content()) {
$session_list = [];
$sessionList = SessionManager::get_sessions_followed_by_drh(
api_get_user_id(),
null,
null,
null,
true,
false
);
if (!empty($sessionList)) {
foreach ($sessionList as $sessionItem) {
$sessionId = $sessionItem['id'];
$courses = SessionManager::get_course_list_by_session_id($sessionId);
$sessionInfo = [
'session_id' => $sessionId,
'courses' => $courses,
];
$session_list[] = $sessionInfo;
}
}
}
}
if (!empty($session_list)) {
foreach ($session_list as $session_item) {
if ($sessionFilterActive) {
if ($this->sessionId != $session_item['session_id']) {
continue;
}
}
$my_courses = $session_item['courses'];
$my_session_id = $session_item['session_id'];
if (!empty($my_courses)) {
foreach ($my_courses as $course_item) {
$courseInfo = api_get_course_info_by_id(
$course_item['real_id']
);
$this->getCourseEvents(
$start,
$end,
$courseInfo,
0,
$my_session_id
);
}
}
}
}
if (!empty($my_course_list) && $sessionFilterActive == false) {
foreach ($my_course_list as $courseInfoItem) {
$courseInfo = api_get_course_info_by_id(
$courseInfoItem['real_id']
);
if (isset($courseId) && !empty($courseId)) {
if ($courseInfo['real_id'] == $courseId) {
$this->getCourseEvents(
$start,
$end,
$courseInfo,
0,
0,
$user_id
);
}
} else {
$this->getCourseEvents(
$start,
$end,
$courseInfo,
0,
0,
$user_id
);
}
}
}
if ($start && $end) {
$this->loadSessionsAsEvents($start, $end);
}
break;
}
if (api_get_configuration_value('agenda_reminders')) {
$this->events = array_map(
function (array $eventInfo) {
$id = str_replace(['personal_', 'course_', 'session_'], '', $eventInfo['id']);
$eventInfo['reminders'] = $this->parseEventReminders(
$this->getEventReminders(
$id,
'session' === $eventInfo['type'] ? 'course' : $eventInfo['type']
)
);
return $eventInfo;
},
$this->events
);
}
$this->cleanEvents();
switch ($format) {
case 'json':
if (empty($this->events)) {
return '[]';
}
return json_encode($this->events);
break;
case 'array':
if (empty($this->events)) {
return [];
}
return $this->events;
break;
}
}
/**
* Clean events.
*
* @return bool
*/
public function cleanEvents()
{
if (empty($this->events)) {
return false;
}
foreach ($this->events as &$event) {
$event['description'] = Security::remove_XSS($event['description']);
$event['title'] = Security::remove_XSS($event['title']);
}
return true;
}
/**
* @param int $id
* @param int $minute_delta
*
* @return int
*/
public function resizeEvent($id, $minute_delta)
{
$id = (int) $id;
$delta = (int) $minute_delta;
$event = $this->get_event($id);
if (!empty($event)) {
switch ($this->type) {
case 'personal':
$sql = "UPDATE $this->tbl_personal_agenda SET
enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
WHERE id = ".$id;
Database::query($sql);
break;
case 'course':
$sql = "UPDATE $this->tbl_course_agenda SET
end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
WHERE
c_id = ".$this->course['real_id']." AND
id = ".$id;
Database::query($sql);
break;
case 'admin':
$sql = "UPDATE $this->tbl_global_agenda SET
end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
WHERE id = ".$id;
Database::query($sql);
break;
}
}
return 1;
}
/**
* @param int $id
* @param int $minute_delta minutes
* @param int $allDay
*
* @return int
*/
public function move_event($id, $minute_delta, $allDay)
{
$id = (int) $id;
$event = $this->get_event($id);
if (empty($event)) {
return false;
}
// we convert the hour delta into minutes and add the minute delta
$delta = (int) $minute_delta;
$allDay = (int) $allDay;
if (!empty($event)) {
switch ($this->type) {
case 'personal':
$sql = "UPDATE $this->tbl_personal_agenda SET
all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
WHERE id=".$id;
Database::query($sql);
break;
case 'course':
$sql = "UPDATE $this->tbl_course_agenda SET
all_day = $allDay,
start_date = DATE_ADD(start_date, INTERVAL $delta MINUTE),
end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
WHERE
c_id = ".$this->course['real_id']." AND
id=".$id;
Database::query($sql);
break;
case 'admin':
$sql = "UPDATE $this->tbl_global_agenda SET
all_day = $allDay,
start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
WHERE id=".$id;
Database::query($sql);
break;
}
}
return 1;
}
/**
* Gets a single event.
*
* @param int $id event id
*
* @return array
*/
public function get_event($id)
{
// make sure events of the personal agenda can only be seen by the user himself
$id = (int) $id;
$event = null;
$agendaCollectiveInvitations = api_get_configuration_value('agenda_collective_invitations');
switch ($this->type) {
case 'personal':
$user = api_get_user_entity(api_get_user_id());
$sql = "SELECT * FROM ".$this->tbl_personal_agenda."
WHERE id = $id AND user = ".$user->getId();
$result = Database::query($sql);
if (Database::num_rows($result)) {
$event = Database::fetch_array($result, 'ASSOC');
$event['description'] = $event['text'];
$event['content'] = $event['text'];
$event['start_date'] = $event['date'];
$event['end_date'] = $event['enddate'];
}
if (null !== $event) {
return $event;
}
if ($agendaCollectiveInvitations) {
$eventRepo = Database::getManager()->getRepository('ChamiloCoreBundle:PersonalAgenda');
$event = $eventRepo->findOneByIdAndInvitee($id, $user);
if ($event && $event->isCollective()) {
return [
'id' => $event->getId(),
'user' => $event->getUser(),
'title' => $event->getTitle(),
'text' => $event->getText(),
'date' => $event->getDate()->format('Y-m-d H:i:s'),
'enddate' => $event->getEndDate()->format('Y-m-d H:i:s'),
'course' => null,
'parent_event_id' => $event->getParentEventId(),
'all_day' => $event->getAllDay(),
'color' => $event->getColor(),
'agenda_event_invitation_id' => $event->getInvitation()->getId(),
'collective' => $event->isCollective(),
'description' => $event->getText(),
'content' => $event->getText(),
'start_date' => $event->getDate()->format('Y-m-d H:i:s'),
'end_date' => $event->getEndDate()->format('Y-m-d H:i:s'),
];
}
}
return null;
case 'course':
if (!empty($this->course['real_id'])) {
$sql = "SELECT * FROM ".$this->tbl_course_agenda."
WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
$result = Database::query($sql);
if (Database::num_rows($result)) {
$event = Database::fetch_array($result, 'ASSOC');
$event['description'] = $event['content'];
// Getting send to array
$event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
$id,
$this->course['real_id'],
$this->sessionId
);
// Getting repeat info
$event['repeat_info'] = $this->getRepeatedInfoByEvent(
$id,
$this->course['real_id']
);
if (!empty($event['parent_event_id'])) {
$event['parent_info'] = $this->get_event($event['parent_event_id']);
}
$event['attachment'] = $this->getAttachmentList(
$id,
$this->course
);
}
}
break;
case 'admin':
case 'platform':
$sql = "SELECT * FROM ".$this->tbl_global_agenda."
WHERE id = $id";
$result = Database::query($sql);
if (Database::num_rows($result)) {
$event = Database::fetch_array($result, 'ASSOC');
$event['description'] = $event['content'];
}
break;
}
return $event;
}
/**
* Gets personal events.
*
* @param int $start
* @param int $end
*
* @return array
*/
public function getPersonalEvents($start, $end)
{
$start = (int) $start;
$end = (int) $end;
$startDate = null;
$endDate = null;
$startCondition = '';
$endCondition = '';
$agendaCollectiveInvitations = api_get_configuration_value('agenda_collective_invitations');
$agendaEventSubscriptions = api_get_configuration_value('agenda_event_subscriptions');
$userIsAdmin = api_is_platform_admin();
$queryParams = [];
if ($start !== 0) {
$queryParams['start_date'] = api_get_utc_datetime($start, true, true);
$startCondition = "AND pa.date >= :start_date";
}
if ($end !== 0) {
$queryParams['end_date'] = api_get_utc_datetime($end, false, true);
$endCondition = "AND (pa.enddate <= :end_date OR pa.enddate IS NULL)";
}
$user_id = api_get_user_id();
$queryParams['user_id'] = $user_id;
$userCondition = "pa.user = :user_id";
$objGroup = new UserGroup();
if ($agendaEventSubscriptions) {
$groupList = $objGroup->getUserGroupListByUser($user_id, UserGroup::NORMAL_CLASS);
$userCondition = "(
$userCondition
OR (
pa.subscriptionVisibility = ".AgendaEventSubscription::SUBSCRIPTION_ALL;
if ($groupList) {
$userCondition .= "
OR (
pa.subscriptionVisibility = ".AgendaEventSubscription::SUBSCRIPTION_CLASS."
AND pa.subscriptionItemId IN (".implode(', ', array_column($groupList, 'id')).")
)
";
}
$userCondition .= "
)
)
";
}
$sql = "SELECT pa FROM ChamiloCoreBundle:PersonalAgenda AS pa WHERE $userCondition $startCondition $endCondition";
$result = Database::getManager()
->createQuery($sql)
->setParameters($queryParams)
->getResult();
$my_events = [];
/** @var PersonalAgenda $row */
foreach ($result as $row) {
$event = [];
$event['id'] = 'personal_'.$row->getId();
$event['title'] = $row->getTitle();
$event['className'] = 'personal';
$event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
$event['editable'] = $user_id === (int) $row->getUser();
$event['sent_to'] = get_lang('Me');
$event['type'] = 'personal';
if (!empty($row->getDate())) {
$event['start'] = $this->formatEventDate($row->getDate());
$event['start_date_localtime'] = api_get_local_time($row->getDate());
}
if (!empty($row->getEnddate())) {
$event['end'] = $this->formatEventDate($row->getEnddate());
$event['end_date_localtime'] = api_get_local_time($row->getEnddate());
}
$event['description'] = $row->getText();
$event['allDay'] = $row->getAllDay();
$event['parent_event_id'] = 0;
$event['has_children'] = 0;
if ($agendaCollectiveInvitations || $agendaEventSubscriptions) {
$subscription = $row->getInvitation();
if ($subscription instanceof AgendaEventSubscription) {
$subscribers = $subscription->getInvitees();
$event['subscription_visibility'] = $row->getSubscriptionVisibility();
$event['max_subscriptions'] = $subscription->getMaxAttendees();
$event['can_subscribe'] = $subscribers->count() < $subscription->getMaxAttendees()
|| $subscription->getMaxAttendees() === 0;
$event['user_is_subscribed'] = $subscription->hasUserAsInvitee(api_get_user_entity($user_id));
$event['count_subscribers'] = $subscribers->count();
if ($userIsAdmin) {
$event['subscribers'] = self::getInviteesForPersonalEvent($row->getId(), AgendaEventSubscriber::class);
}
if (AgendaEventSubscription::SUBSCRIPTION_CLASS === $row->getSubscriptionVisibility()) {
$groupInfo = $objGroup->get($row->getSubscriptionItemId());
$event['usergroup'] = $groupInfo['name'];
}
} else {
$event['collective'] = $row->isCollective();
$event['invitees'] = self::getInviteesForPersonalEvent($row->getId());
}
}
$my_events[] = $event;
$this->events[] = $event;
}
if ($agendaCollectiveInvitations) {
$this->loadEventsAsInvitee(
api_get_user_entity($user_id),
$startDate,
$endDate
);
}
// Add plugin personal events
$this->plugin = new AppPlugin();
$plugins = $this->plugin->getInstalledPluginListObject();
/** @var Plugin $plugin */
foreach ($plugins as $plugin) {
if ($plugin->hasPersonalEvents && method_exists($plugin, 'getPersonalEvents')) {
$pluginEvents = $plugin->getPersonalEvents($this, $start, $end);
if (!empty($pluginEvents)) {
$this->events = array_merge($this->events, $pluginEvents);
}
}
}
return $my_events;
}
public static function getInviteesForPersonalEvent($eventId, $type = AgendaEventInvitee::class): array
{
$em = Database::getManager();
$event = $em->find('ChamiloCoreBundle:PersonalAgenda', $eventId);
$invitation = $event->getInvitation();
if ($invitation instanceof AgendaEventSubscription
&& AgendaEventInvitee::class === $type
) {
return [];
}
$inviteeRepo = $em->getRepository($type);
$invitees = $inviteeRepo->findByInvitation($invitation);
$inviteeList = [];
foreach ($invitees as $invitee) {
$inviteeUser = $invitee->getUser();
$inviteeList[] = [
'id' => $inviteeUser->getId(),
'name' => $inviteeUser->getCompleteNameWithUsername(),
];
}
return $inviteeList;
}
/**
* Get user/group list per event.
*
* @param int $eventId
* @param int $courseId
* @param int $sessionId
* @paraù int $sessionId
*
* @return array
*/
public function getUsersAndGroupSubscribedToEvent(
$eventId,
$courseId,
$sessionId
) {
$eventId = (int) $eventId;
$courseId = (int) $courseId;
$sessionId = (int) $sessionId;
$sessionCondition = "ip.session_id = $sessionId";
if (empty($sessionId)) {
$sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
}
$tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
$tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
// Get sent_tos
$sql = "SELECT DISTINCT to_user_id, to_group_id
FROM $tbl_property ip
INNER JOIN $tlb_course_agenda agenda
ON (
ip.ref = agenda.id AND
ip.c_id = agenda.c_id AND
ip.tool = '".TOOL_CALENDAR_EVENT."'
)
WHERE
ref = $eventId AND
ip.visibility = '1' AND
ip.c_id = $courseId AND
$sessionCondition
";
$result = Database::query($sql);
$users = [];
$groups = [];
$everyone = false;
while ($row = Database::fetch_array($result, 'ASSOC')) {
if (!empty($row['to_group_id'])) {
$groups[] = $row['to_group_id'];
}
if (!empty($row['to_user_id'])) {
$users[] = $row['to_user_id'];
}
if (empty($groups) && empty($users)) {
if ($row['to_group_id'] == 0) {
$everyone = true;
}
}
}
return [
'everyone' => $everyone,
'users' => $users,
'groups' => $groups,
];
}
/**
* @param int $start
* @param int $end
* @param int $sessionId
* @param int $userId
* @param string $color
*
* @return array
*/
public function getSessionEvents(
$start,
$end,
$sessionId = 0,
$userId = 0,
$color = ''
) {
$courses = SessionManager::get_course_list_by_session_id($sessionId);
if (!empty($courses)) {
foreach ($courses as $course) {
$this->getCourseEvents(
$start,
$end,
$course,
0,
$sessionId,
0,
$color
);
}
}
}
/**
* @param int $start
* @param int $end
* @param array $courseInfo
* @param int $groupId
* @param int $sessionId
* @param int $user_id
* @param string $color
*
* @return array
*/
public function getCourseEvents(
$start,
$end,
$courseInfo,
$groupId = 0,
$sessionId = 0,
$user_id = 0,
$color = ''
) {
$start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
$end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
if (empty($courseInfo)) {
return [];
}
$courseId = $courseInfo['real_id'];
if (empty($courseId)) {
return [];
}
$sessionId = (int) $sessionId;
$user_id = (int) $user_id;
$groupList = GroupManager::get_group_list(
null,
$courseInfo,
null,
$sessionId
);
$groupNameList = [];
if (!empty($groupList)) {
foreach ($groupList as $group) {
$groupNameList[$group['iid']] = $group['name'];
}
}
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$isAllowToEdit = true;
} else {
$isAllowToEdit = CourseManager::is_course_teacher(
api_get_user_id(),
$courseInfo['code']
);
}
$isAllowToEditByHrm = false;
if (!empty($sessionId)) {
$allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
if ($allowDhrToEdit) {
$isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, api_get_user_id());
if ($isHrm) {
$isAllowToEdit = $isAllowToEditByHrm = true;
}
}
}
$groupMemberships = [];
if (!empty($groupId)) {
$groupMemberships = [$groupId];
} else {
if ($isAllowToEdit) {
if (!empty($groupList)) {
// c_item_property.to_group_id field was migrated to use
// c_group_info.iid
$groupMemberships = array_column($groupList, 'iid');
}
} else {
// get only related groups from user
$groupMemberships = GroupManager::get_group_ids(
$courseId,
api_get_user_id()
);
}
}
$tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
$tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
$shareEventsInSessions = 1 == api_get_course_setting('agenda_share_events_in_sessions', $courseInfo);
$agendaSessionCondition = str_replace(
' AND ',
'',
api_get_session_condition($sessionId, true, $shareEventsInSessions, 'agenda.session_id')
);
$ipSessionCondition = api_get_session_condition($sessionId, true, $shareEventsInSessions, 'ip.session_id');
$sessionCondition = "($agendaSessionCondition $ipSessionCondition)";
if ($isAllowToEdit) {
// No group filter was asked
if (empty($groupId)) {
if (empty($user_id)) {
// Show all events not added in group
$userCondition = ' (ip.to_group_id IS NULL OR ip.to_group_id = 0) ';
// admin see only his stuff
if ($this->type === 'personal') {
$userCondition = " (ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ) ";
$userCondition .= " OR ( (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ) ";
}
if (!empty($groupMemberships)) {
// Show events sent to selected groups
$userCondition .= " OR (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
}
} else {
// Show events of requested user in no group
$userCondition = " (ip.to_user_id = $user_id AND (ip.to_group_id IS NULL OR ip.to_group_id = 0)) ";
// Show events sent to selected groups
if (!empty($groupMemberships)) {
$userCondition .= " OR (ip.to_user_id = $user_id) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
}
}
} else {
// Show only selected groups (depending of user status)
$userCondition = " (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
if (!empty($groupMemberships)) {
// Show send to $user_id in selected groups
$userCondition .= " OR (ip.to_user_id = $user_id) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
}
}
} else {
// No group filter was asked
if (empty($groupId)) {
// Show events sent to everyone and no group
$userCondition = ' ( (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ';
// Show events sent to selected groups
if (!empty($groupMemberships)) {
$userCondition .= " OR (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships)."))) ";
} else {
$userCondition .= " ) ";
}
$userCondition .= " OR (ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id IS NULL OR ip.to_group_id = 0)) ";
} else {
if (!empty($groupMemberships)) {
// Show send to everyone - and only selected groups
$userCondition = " (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
}
}
// Show sent to only me and no group
if (!empty($groupMemberships)) {
$userCondition .= " OR (ip.to_user_id = ".api_get_user_id().") AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
} else {
// Show sent to only me and selected groups
}
}
if (api_is_allowed_to_edit()) {
$visibilityCondition = " (ip.visibility IN ('1', '0')) ";
} else {
$visibilityCondition = " (ip.visibility = '1') ";
}
$sql = "SELECT DISTINCT
agenda.*,
ip.visibility,
ip.to_group_id,
ip.insert_user_id,
ip.ref,
to_user_id
FROM $tlb_course_agenda agenda
INNER JOIN $tbl_property ip
ON (
agenda.id = ip.ref AND
agenda.c_id = ip.c_id AND
ip.tool = '".TOOL_CALENDAR_EVENT."'
)
WHERE
$sessionCondition AND
($userCondition) AND
$visibilityCondition AND
agenda.c_id = $courseId
";
$dateCondition = '';
if (!empty($start) && !empty($end)) {
$dateCondition .= "AND (
agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
(
agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
)
)";
}
$sql .= $dateCondition;
$result = Database::query($sql);
$coachCanEdit = false;
if (!empty($sessionId)) {
$coachCanEdit = api_is_coach($sessionId, $courseId) || api_is_platform_admin();
}
if (Database::num_rows($result)) {
$eventsAdded = array_column($this->events, 'unique_id');
while ($row = Database::fetch_array($result, 'ASSOC')) {
$event = [];
$event['id'] = 'course_'.$row['id'];
$event['unique_id'] = $row['iid'];
// To avoid doubles
if (in_array($event['unique_id'], $eventsAdded)) {
continue;
}
$eventsAdded[] = $event['unique_id'];
$eventId = $row['ref'];
$items = $this->getUsersAndGroupSubscribedToEvent(
$eventId,
$courseId,
$this->sessionId
);
$group_to_array = $items['groups'];
$user_to_array = $items['users'];
$attachmentList = $this->getAttachmentList(
$row['id'],
$courseInfo
);
$event['attachment'] = '';
if (!empty($attachmentList)) {
foreach ($attachmentList as $attachment) {
$has_attachment = Display::return_icon(
'attachment.gif',
get_lang('Attachment')
);
$user_filename = $attachment['filename'];
$url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$courseId.'&'.api_get_cidreq();
$event['attachment'] .= $has_attachment.
Display::url(
$user_filename,
$url
).'
';
}
}
$event['title'] = $row['title'];
$event['className'] = 'course';
$event['allDay'] = 'false';
$event['course_id'] = $courseId;
$event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
$sessionInfo = [];
if (isset($row['session_id']) && !empty($row['session_id'])) {
$sessionInfo = api_get_session_info($sessionId);
$event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
}
$event['session_name'] = isset($sessionInfo['name']) ? $sessionInfo['name'] : '';
$event['course_name'] = isset($courseInfo['title']) ? $courseInfo['title'] : '';
if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
$event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
}
if (!empty($color)) {
$event['borderColor'] = $event['backgroundColor'] = $color;
}
if (isset($row['color']) && !empty($row['color'])) {
$event['borderColor'] = $event['backgroundColor'] = $row['color'];
}
$event['editable'] = false;
if ($this->getIsAllowedToEdit() && $this->type == 'course') {
$event['editable'] = true;
if (!empty($sessionId)) {
if ($coachCanEdit == false) {
$event['editable'] = false;
}
if ($isAllowToEditByHrm) {
$event['editable'] = true;
}
if ($sessionId != $row['session_id']) {
$event['editable'] = false;
}
}
// if user is author then he can edit the item
if (api_get_user_id() == $row['insert_user_id']) {
$event['editable'] = true;
}
}
if (!empty($row['start_date'])) {
$event['start'] = $this->formatEventDate($row['start_date']);
$event['start_date_localtime'] = api_get_local_time($row['start_date']);
}
if (!empty($row['end_date'])) {
$event['end'] = $this->formatEventDate($row['end_date']);
$event['end_date_localtime'] = api_get_local_time($row['end_date']);
}
$event['sent_to'] = '';
$event['type'] = 'course';
if ($row['session_id'] != 0) {
$event['type'] = 'session';
}
// Event Sent to a group?
if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
$sent_to = [];
if (!empty($group_to_array)) {
foreach ($group_to_array as $group_item) {
$sent_to[] = $groupNameList[$group_item];
}
}
$sent_to = implode('@@', $sent_to);
$sent_to = str_replace(
'@@',
'
'.get_lang('Before').'
'.$monthName." ".$year.'
| '.$DaysShort[$ii % 7].' | '; } $html .= '|
| ".$dayheader;
if (!empty($agendaitems[$curday])) {
$items = $agendaitems[$curday];
$items = msort($items, 'start_date_tms');
foreach ($items as $value) {
$value['title'] = Security::remove_XSS(
$value['title']
);
$start_time = api_format_date(
$value['start_date'],
TIME_NO_SEC_FORMAT
);
$end_time = '';
if (!empty($value['end_date'])) {
$end_time = '- '.api_format_date(
$value['end_date'],
DATE_TIME_FORMAT_LONG
).'';
}
$complete_time = ''.api_format_date(
$value['start_date'],
DATE_TIME_FORMAT_LONG
).' '.$end_time;
$time = ''.$start_time.'';
switch ($value['calendar_type']) {
case 'personal':
$bg_color = '#D0E7F4';
$icon = Display::return_icon(
'user.png',
get_lang('MyAgenda'),
[],
ICON_SIZE_SMALL
);
break;
case 'global':
$bg_color = '#FFBC89';
$icon = Display::return_icon(
'view_remove.png',
get_lang('GlobalEvent'),
[],
ICON_SIZE_SMALL
);
break;
case 'course':
$bg_color = '#CAFFAA';
$icon_name = 'course.png';
if (!empty($value['session_id'])) {
$icon_name = 'session.png';
}
if ($show_content) {
$icon = Display::url(
Display::return_icon(
$icon_name,
$value['course_name'].' '.get_lang(
'Course'
),
[],
ICON_SIZE_SMALL
),
$value['url']
);
} else {
$icon = Display::return_icon(
$icon_name,
$value['course_name'].' '.get_lang(
'Course'
),
[],
ICON_SIZE_SMALL
);
}
break;
default:
break;
}
$result = ' ';
if ($show_content) {
//Setting a personal event to green
$icon = Display::div(
$icon,
['style' => 'float:right']
);
$link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
//Link to bubble
$url = Display::url(
cut($value['title'], 40),
'#',
['id' => $link, 'class' => 'opener']
);
$result .= $time.' '.$icon.' '.Display::div(
$url
);
//Hidden content
$content = Display::div(
$icon.Display::tag(
'h2',
$value['course_name']
).' ';
$html .= $result;
} else {
$html .= $result .= $icon.'';
}
}
}
$html .= "'.Display::tag( 'h3', $value['title'] ).$complete_time.' '.Security::remove_XSS( $value['content'] ) ); //Main div $result .= Display::div( $content, [ 'id' => 'main_'.$link, 'class' => 'dialog', 'style' => 'display:none', ] ); $result .= ' | ";
$curday++;
} else {
$html .= ""; } } $html .= " |
'.get_lang('Before').'