*/
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 array */
    private $sessionInfo;
    /** @var string */
    public $comment;
    /** @var bool */
    private $isAllowedToEdit;
    public $eventStudentPublicationColor;
    /**
     * Constructor
     * @param string $type
     * @param int $senderId Optional The user sender ID
     * @param int $courseId Opitonal. 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;
                    if ($isGroupAccess) {
                        $isAllowToEdit = true;
                    } else {
                        $isAllowToEdit = 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 = 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 = intval($senderId);
    }
    /**
     * @return int
     */
    public function getSenderId()
    {
        return $this->senderId;
    }
    /**
     * @param string $type can be 'personal', 'admin'  or  'course'
     */
    public function setType($type)
    {
        $typeList = $this->getTypes();
        if (in_array($type, $typeList)) {
            $this->type = $type;
        }
    }
    /**
     * @param int $id
     */
    public function setSessionId($id)
    {
        $this->sessionId = intval($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
     * @param string $end datetime format: 2012-06-14 09:00:00
     * @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 = ''
    ) {
        $start = api_get_utc_datetime($start);
        $end = api_get_utc_datetime($end);
        $allDay = isset($allDay) && $allDay === 'true' ? 1 : 0;
        $id = null;
        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
                );
                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
                                        );
                                        if ($groupInfoItem) {
                                            $groupIidItem = $groupInfoItem['iid'];
                                        }
                                    }
                                    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()
                    ];
                    $id = Database::insert(
                        $this->tbl_global_agenda,
                        $attributes
                    );
                }
                break;
        }
        return $id;
    }
    /**
     * @param int $eventId
     * @param int $courseId
     *
     * @return array
     */
    public function getRepeatedInfoByEvent($eventId, $courseId)
    {
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
        $eventId = intval($eventId);
        $courseId = intval($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 int $eventId
     * @param string $type
     * @param string $end in local time
     * @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;
        }
        $course_id = $this->course['real_id'];
        $eventId = intval($eventId);
        $sql = "SELECT title, content, start_date, end_date, all_day
                FROM $t_agenda
                WHERE c_id = $course_id AND id = $eventId";
        $res = Database::query($sql);
        if (Database::num_rows($res) !== 1) {
            return false;
        }
        $row = Database::fetch_array($res);
        $origStartDate = api_strtotime($row['start_date'], 'UTC');
        $origEndDate = api_strtotime($row['end_date'], 'UTC');
        $diff = $origEndDate - $origStartDate;
        $title = $row['title'];
        $content = $row['content'];
        $allDay = $row['all_day'];
        $now = time();
        $type = Database::escape_string($type);
        $end = api_strtotime($end);
        if (1 <= $end && $end <= 500) {
            // We assume that, with this type of value, the user actually gives a count of repetitions
            //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
            switch ($type) {
                case 'daily':
                    $end = $origStartDate + (86400 * $end);
                    break;
                case 'weekly':
                    $end = $this->addWeek($origStartDate, $end);
                    break;
                case 'monthlyByDate':
                    $end = $this->addMonth($origStartDate, $end);
                    break;
                case 'monthlyByDay':
                    //TODO
                    break;
                case 'monthlyByDayR':
                    //TODO
                    break;
                case 'yearly':
                    $end = $this->addYear($origStartDate, $end);
                    break;
            }
        }
        $typeList = [
            'daily',
            'weekly',
            'monthlyByDate',
            'monthlyByDay',
            'monthlyByDayR',
            'yearly'
        ];
        // The event has to repeat *in the future*. We don't allow repeated
        // events in the past
        if ($end > $now && in_array($type, $typeList)) {
            $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
                    VALUES ($course_id, '$eventId', '$type', '$end')";
            Database::query($sql);
            switch ($type) {
                // @todo improve loop.
                case 'daily':
                    for ($i = $origStartDate + 86400; $i <= $end; $i += 86400) {
                        $start = date('Y-m-d H:i:s', $i);
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
                        $this->addEvent(
                            $start,
                            $repeatEnd,
                            $allDay,
                            $title,
                            $content,
                            $sentTo,
                            false,
                            $eventId
                        );
                    }
                    break;
                case 'weekly':
                    for ($i = $origStartDate + 604800; $i <= $end; $i += 604800) {
                        $start = date('Y-m-d H:i:s', $i);
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
                        $this->addEvent(
                            $start,
                            $repeatEnd,
                            $allDay,
                            $title,
                            $content,
                            $sentTo,
                            false,
                            $eventId
                        );
                    }
                    break;
                case 'monthlyByDate':
                    $next_start = $this->addMonth($origStartDate);
                    while ($next_start <= $end) {
                        $start = date('Y-m-d H:i:s', $next_start);
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
                        $this->addEvent(
                            $start,
                            $repeatEnd,
                            $allDay,
                            $title,
                            $content,
                            $sentTo,
                            false,
                            $eventId
                        );
                        $next_start = $this->addMonth($next_start);
                    }
                    break;
                case 'monthlyByDay':
                    //not yet implemented
                    break;
                case 'monthlyByDayR':
                    //not yet implemented
                    break;
                case 'yearly':
                    $next_start = $this->addYear($origStartDate);
                    while ($next_start <= $end) {
                        $start = date('Y-m-d H:i:s', $next_start);
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
                        $this->addEvent(
                            $start,
                            $repeatEnd,
                            $allDay,
                            $title,
                            $content,
                            $sentTo,
                            false,
                            $eventId
                        );
                        $next_start = $this->addYear($next_start);
                    }
                    break;
            }
        }
        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);
        $course_id = 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 = $course_id 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
    ) {
        $start = api_get_utc_datetime($start);
        $end = api_get_utc_datetime($end);
        $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
        switch ($this->type) {
            case 'personal':
                $eventInfo = $this->get_event($id);
                if ($eventInfo['user'] != api_get_user_id()) {
                    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]
                );
                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'];
                    }
                }
                $course_id = $this->course['real_id'];
                if (empty($course_id)) {
                    return false;
                }
                if ($this->getIsAllowedToEdit()) {
                    $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,
                                $course_id,
                                $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) {
                            $this->updateAttachment(
                                $attachmentItem['id'],
                                $id,
                                $attachmentItem,
                                $attachmentCommentList[$counter],
                                $this->course
                            );
                            $counter++;
                        }
                    }
                    return true;
                } else {
                    return false;
                }
                break;
            case 'admin':
            case 'platform':
                if (api_is_platform_admin()) {
                    $attributes = [
                        'title' => $title,
                        'start_date' => $start,
                        'end_date' => $end,
                        'all_day' => $allDay
                    ];
                    if ($updateContent) {
                        $attributes['content'] = $content;
                    }
                    Database::update(
                        $this->tbl_global_agenda,
                        $attributes,
                        ['id = ?' => $id]
                    );
                }
                break;
        }
    }
    /**
     * @param int $id
     * @param bool $deleteAllItemsFromSerie
     */
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
    {
        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]
                    );
                }
                break;
            case 'course':
                $course_id = api_get_course_int_id();
                $sessionId = api_get_session_id();
                $isAllowToEdit = api_is_allowed_to_edit(null, true);
                if ($isAllowToEdit == false && !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;
                        }
                    }
                }
                if (!empty($course_id) && $isAllowToEdit) {
                    // Delete
                    $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, $course_id]]
                    );
                    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,
                                $course_id
                            ]
                        ]
                    );
                    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;
        }
    }
    /**
     * Get agenda events
     * @param int $start
     * @param int $end
     * @param int $course_id
     * @param int $groupId
     * @param int $user_id
     * @param string $format
     *
     * @return array|string
     */
    public function getEvents(
        $start,
        $end,
        $course_id = 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($course_id);
                // 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');
                // 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($course_id) && !empty($course_id)) {
                            if ($courseInfo['real_id'] == $course_id) {
                                $this->getCourseEvents(
                                    $start,
                                    $end,
                                    $courseInfo,
                                    0,
                                    0,
                                    $user_id
                                );
                            }
                        } else {
                            $this->getCourseEvents(
                                $start,
                                $end,
                                $courseInfo,
                                0,
                                0,
                                $user_id
                            );
                        }
                    }
                }
                break;
        }
        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;
        }
    }
    /**
     * @param int $id
     * @param int $minute_delta
     * @return int
     */
    public function resizeEvent($id, $minute_delta)
    {
        $id = (int) $id;
        $delta = intval($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 = intval($minute_delta);
        $allDay = intval($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 = intval($id);
        $event = null;
        switch ($this->type) {
            case 'personal':
                $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
                        WHERE id = $id AND user = ".api_get_user_id();
                $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'];
                }
                break;
            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 = intval($start);
        $end = intval($end);
        $startCondition = '';
        $endCondition = '';
        if ($start !== 0) {
            $start = api_get_utc_datetime($start);
            $startCondition = "AND date >= '".$start."'";
        }
        if ($start !== 0) {
            $end = api_get_utc_datetime($end);
            $endCondition = "AND (enddate <= '".$end."' OR enddate IS NULL)";
        }
        $user_id = api_get_user_id();
        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
                WHERE user = $user_id $startCondition $endCondition";
        $result = Database::query($sql);
        $my_events = [];
        if (Database::num_rows($result)) {
            while ($row = Database::fetch_array($result, 'ASSOC')) {
                $event = [];
                $event['id'] = 'personal_'.$row['id'];
                $event['title'] = $row['title'];
                $event['className'] = 'personal';
                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
                $event['editable'] = true;
                $event['sent_to'] = get_lang('Me');
                $event['type'] = 'personal';
                if (!empty($row['date'])) {
                    $event['start'] = $this->formatEventDate($row['date']);
                    $event['start_date_localtime'] = api_get_local_time(
                        $row['date']
                    );
                }
                if (!empty($row['enddate'])) {
                    $event['end'] = $this->formatEventDate($row['enddate']);
                    $event['end_date_localtime'] = api_get_local_time(
                        $row['enddate']
                    );
                }
                $event['description'] = $row['text'];
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
                $event['parent_event_id'] = 0;
                $event['has_children'] = 0;
                $my_events[] = $event;
                $this->events[] = $event;
            }
        }
        return $my_events;
    }
    /**
     * Get user/group list per event.
     *
     * @param int $eventId
     * @param int $courseId
     * @param integer $sessionId
     * @paraù int $sessionId
     *
     * @return array
     */
    public function getUsersAndGroupSubscribedToEvent(
        $eventId,
        $courseId,
        $sessionId
    ) {
        $eventId = intval($eventId);
        $courseId = intval($courseId);
        $sessionId = intval($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 $session_id
     * @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 = intval($sessionId);
        $user_id = intval($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);
        if (empty($sessionId)) {
            $sessionCondition = "
            (
                agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
            ) ";
        } else {
            $sessionCondition = "
            (
                agenda.session_id = $sessionId AND
                ip.session_id = $sessionId
            ) ";
        }
        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 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(
                        '@@',
                        '
'.$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;
                            //echo Display::div($content, array('id'=>'main_'.$value['calendar_type'].'_'.$value['id'], 'class' => 'dialog'));
                            } 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 .= " |