Passed
Push — master ( 254001...bfc3ee )
by Julito
14:11
created

Agenda::get_personal_agenda_items_between_dates()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\PersonalAgenda;
6
use Chamilo\CoreBundle\Entity\SysCalendar;
7
use Chamilo\CoreBundle\Framework\Container;
8
use Chamilo\CourseBundle\Entity\CCalendarEvent;
9
use Chamilo\CourseBundle\Entity\CCalendarEventAttachment;
10
use Chamilo\CourseBundle\Entity\CGroup;
11
use Symfony\Component\HttpFoundation\File\UploadedFile;
12
13
/**
14
 * Class Agenda.
15
 *
16
 * @author: Julio Montoya <[email protected]>
17
 */
18
class Agenda
19
{
20
    public $events = [];
21
    /** @var string Current type */
22
    public $type = 'personal';
23
    public $types = ['personal', 'admin', 'course'];
24
    public $sessionId = 0;
25
    public $senderId;
26
    /** @var array */
27
    public $course;
28
    /** @var string */
29
    public $comment;
30
    public $eventStudentPublicationColor;
31
    /** @var array */
32
    private $sessionInfo;
33
    /** @var bool */
34
    private $isAllowedToEdit;
35
36
    /**
37
     * Constructor.
38
     *
39
     * @param string $type
40
     * @param int    $senderId  Optional The user sender ID
41
     * @param int    $courseId  Optional. The course ID
42
     * @param int    $sessionId Optional The session ID
43
     */
44
    public function __construct(
45
        $type,
46
        $senderId = 0,
47
        $courseId = 0,
48
        $sessionId = 0
49
    ) {
50
        // Table definitions
51
        $this->tbl_global_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
52
        $this->tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
53
        $this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
54
        $this->table_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
55
56
        $this->setType($type);
57
        $this->setSenderId($senderId ?: api_get_user_id());
58
        $isAllowToEdit = false;
59
60
        switch ($type) {
61
            case 'course':
62
                $sessionId = $sessionId ?: api_get_session_id();
63
                $sessionInfo = api_get_session_info($sessionId);
64
                $this->setSessionId($sessionId);
65
                $this->setSessionInfo($sessionInfo);
66
67
                // Setting the course object if we are in a course
68
                $courseInfo = api_get_course_info_by_id($courseId);
69
                if (!empty($courseInfo)) {
70
                    $this->set_course($courseInfo);
71
                }
72
73
                // Check if teacher/admin rights.
74
                $isAllowToEdit = api_is_allowed_to_edit(false, true);
75
                // Check course setting.
76
                if ('1' === api_get_course_setting('allow_user_edit_agenda')
77
                    && api_is_allowed_in_course()
78
                ) {
79
                    $isAllowToEdit = true;
80
                }
81
82
                $groupId = api_get_group_id();
83
                if (!empty($groupId)) {
84
                    $groupInfo = GroupManager::get_group_properties($groupId);
85
                    $userHasAccess = GroupManager::user_has_access(
86
                        api_get_user_id(),
87
                        $groupInfo['iid'],
88
                        GroupManager::GROUP_TOOL_CALENDAR
89
                    );
90
                    $isTutor = GroupManager::is_tutor_of_group(
91
                        api_get_user_id(),
92
                        $groupInfo
93
                    );
94
95
                    $isGroupAccess = $userHasAccess || $isTutor;
96
                    $isAllowToEdit = false;
97
                    if ($isGroupAccess) {
98
                        $isAllowToEdit = true;
99
                    }
100
                }
101
102
                if (!empty($sessionId)) {
103
                    $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
104
                    if ($allowDhrToEdit) {
105
                        $isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, api_get_user_id());
106
                        if ($isHrm) {
107
                            $isAllowToEdit = true;
108
                        }
109
                    }
110
                }
111
                break;
112
            case 'admin':
113
                $isAllowToEdit = api_is_platform_admin();
114
                break;
115
            case 'personal':
116
                $isAllowToEdit = !api_is_anonymous();
117
                break;
118
        }
119
120
        $this->setIsAllowedToEdit($isAllowToEdit);
121
        $this->events = [];
122
        $agendaColors = array_merge(
123
            [
124
                'platform' => 'red', //red
125
                'course' => '#458B00', //green
126
                'group' => '#A0522D', //siena
127
                'session' => '#00496D', // kind of green
128
                'other_session' => '#999', // kind of green
129
                'personal' => 'steel blue', //steel blue
130
                'student_publication' => '#FF8C00', //DarkOrange
131
            ],
132
            api_get_configuration_value('agenda_colors') ?: []
133
        );
134
135
        // Event colors
136
        $this->event_platform_color = $agendaColors['platform'];
137
        $this->event_course_color = $agendaColors['course'];
138
        $this->event_group_color = $agendaColors['group'];
139
        $this->event_session_color = $agendaColors['session'];
140
        $this->eventOtherSessionColor = $agendaColors['other_session'];
141
        $this->event_personal_color = $agendaColors['personal'];
142
        $this->eventStudentPublicationColor = $agendaColors['student_publication'];
143
    }
144
145
    /**
146
     * @param int $senderId
147
     */
148
    public function setSenderId($senderId)
149
    {
150
        $this->senderId = (int) $senderId;
151
    }
152
153
    /**
154
     * @return int
155
     */
156
    public function getSenderId()
157
    {
158
        return $this->senderId;
159
    }
160
161
    /**
162
     * @param string $type can be 'personal', 'admin'  or  'course'
163
     */
164
    public function setType($type)
165
    {
166
        $typeList = $this->getTypes();
167
        if (in_array($type, $typeList)) {
168
            $this->type = $type;
169
        }
170
    }
171
172
    /**
173
     * Returns the type previously set (and filtered) through setType
174
     * If setType() was not called, then type defaults to "personal" as
175
     * set in the class definition.
176
     */
177
    public function getType()
178
    {
179
        if (isset($this->type)) {
180
            return $this->type;
181
        }
182
    }
183
184
    /**
185
     * @param int $id
186
     */
187
    public function setSessionId($id)
188
    {
189
        $this->sessionId = (int) $id;
190
    }
191
192
    /**
193
     * @param array $sessionInfo
194
     */
195
    public function setSessionInfo($sessionInfo)
196
    {
197
        $this->sessionInfo = $sessionInfo;
198
    }
199
200
    /**
201
     * @return int $id
202
     */
203
    public function getSessionId()
204
    {
205
        return $this->sessionId;
206
    }
207
208
    /**
209
     * @param array $courseInfo
210
     */
211
    public function set_course($courseInfo)
212
    {
213
        $this->course = $courseInfo;
214
    }
215
216
    /**
217
     * @return array
218
     */
219
    public function getTypes()
220
    {
221
        return $this->types;
222
    }
223
224
    /**
225
     * Adds an event to the calendar.
226
     *
227
     * @param string         $start                 datetime format: 2012-06-14 09:00:00 in local time
228
     * @param string         $end                   datetime format: 2012-06-14 09:00:00 in local time
229
     * @param string         $allDay                (true, false)
230
     * @param string         $title
231
     * @param string         $content
232
     * @param array          $usersToSend           array('everyone') or a list of user/group ids
233
     * @param bool           $addAsAnnouncement     event as a *course* announcement
234
     * @param int            $parentEventId
235
     * @param UploadedFile[] $attachmentArray       array of $_FILES['']
236
     * @param array          $attachmentCommentList
237
     * @param string         $eventComment
238
     * @param string         $color
239
     *
240
     * @return int
241
     */
242
    public function addEvent(
243
        $start,
244
        $end,
245
        $allDay,
246
        $title,
247
        $content,
248
        $usersToSend = [],
249
        $addAsAnnouncement = false,
250
        $parentEventId = null,
251
        $attachmentArray = [],
252
        $attachmentCommentList = [],
253
        $eventComment = null,
254
        $color = ''
255
    ) {
256
        $start = api_get_utc_datetime($start, false, true);
257
        $end = api_get_utc_datetime($end, false, true);
258
        $allDay = isset($allDay) && 'true' === $allDay ? 1 : 0;
259
        $id = null;
260
261
        $em = Database::getManager();
262
        switch ($this->type) {
263
            case 'personal':
264
                $event = new PersonalAgenda();
265
                $event
266
                    ->setTitle($title)
267
                    ->setText($content)
268
                    ->setDate($start)
269
                    ->setEndDate($end)
270
                    ->setAllDay($allDay)
271
                    ->setColor($color)
272
                    ->setUser(api_get_user_entity())
273
                ;
274
                $em->persist($event);
275
                $em->flush();
276
                $id = $event->getId();
277
                break;
278
            case 'course':
279
                $sessionId = $this->getSessionId();
280
                $sessionEntity = api_get_session_entity($sessionId);
281
                $courseEntity = api_get_course_entity($this->course['real_id']);
282
                $groupEntity = api_get_group_entity(api_get_group_id());
283
284
                $event = new CCalendarEvent();
285
                $event
286
                    ->setTitle($title)
287
                    ->setContent($content)
288
                    ->setStartDate($start)
289
                    ->setEndDate($end)
290
                    ->setAllDay($allDay)
291
                    ->setColor($color)
292
                    ->setComment($eventComment)
293
                    ->setCId($this->course['real_id'])
294
                    ->setSessionId($this->getSessionId())
295
                ;
296
297
                if (!empty($parentEventId)) {
298
                    $event->setParentEventId($parentEventId);
299
                }
300
301
                $event->setParent($courseEntity);
302
303
                if (!empty($usersToSend)) {
304
                    $sendTo = $this->parseSendToArray($usersToSend);
305
                    if ($sendTo['everyone']) {
306
                        $event->addCourseLink($courseEntity, $sessionEntity, $groupEntity);
307
                    /*api_item_property_update(
308
                        $this->course,
309
                        TOOL_CALENDAR_EVENT,
310
                        $id,
311
                        'AgendaAdded',
312
                        $senderId,
313
                        $groupInfo,
314
                        '',
315
                        $start,
316
                        $end,
317
                        $sessionId
318
                    );
319
                    api_item_property_update(
320
                        $this->course,
321
                        TOOL_CALENDAR_EVENT,
322
                        $id,
323
                        'visible',
324
                        $senderId,
325
                        $groupInfo,
326
                        '',
327
                        $start,
328
                        $end,
329
                        $sessionId
330
                    );*/
331
                    } else {
332
                        // Storing the selected groups
333
                        if (!empty($sendTo['groups'])) {
334
                            foreach ($sendTo['groups'] as $group) {
335
                                $groupInfo = null;
336
                                if ($group) {
337
                                    $groupInfo = api_get_group_entity($group);
338
                                    $event->addCourseLink($courseEntity, $sessionEntity, $groupInfo);
339
                                }
340
341
                                /*api_item_property_update(
342
                                    $this->course,
343
                                    TOOL_CALENDAR_EVENT,
344
                                    $id,
345
                                    'AgendaAdded',
346
                                    $senderId,
347
                                    $groupInfoItem,
348
                                    0,
349
                                    $start,
350
                                    $end,
351
                                    $sessionId
352
                                );
353
354
                                api_item_property_update(
355
                                    $this->course,
356
                                    TOOL_CALENDAR_EVENT,
357
                                    $id,
358
                                    'visible',
359
                                    $senderId,
360
                                    $groupInfoItem,
361
                                    0,
362
                                    $start,
363
                                    $end,
364
                                    $sessionId
365
                                );*/
366
                            }
367
                        }
368
369
                        // storing the selected users
370
                        if (!empty($sendTo['users'])) {
371
                            foreach ($sendTo['users'] as $userId) {
372
                                $event->addUserLink(
373
                                    api_get_user_entity($userId),
374
                                    $courseEntity,
375
                                    $sessionEntity,
376
                                    $groupEntity
377
                                );
378
379
                                /*api_item_property_update(
380
                                    $this->course,
381
                                    TOOL_CALENDAR_EVENT,
382
                                    $id,
383
                                    'AgendaAdded',
384
                                    $senderId,
385
                                    $groupInfo,
386
                                    $userId,
387
                                    $start,
388
                                    $end,
389
                                    $sessionId
390
                                );
391
392
                                api_item_property_update(
393
                                    $this->course,
394
                                    TOOL_CALENDAR_EVENT,
395
                                    $id,
396
                                    'visible',
397
                                    $senderId,
398
                                    $groupInfo,
399
                                    $userId,
400
                                    $start,
401
                                    $end,
402
                                    $sessionId
403
                                );*/
404
                            }
405
                        }
406
                    }
407
                }
408
409
                $em->persist($event);
410
                $em->flush();
411
                $id = $event->getIid();
412
413
                if ($id) {
414
                    // Add announcement.
415
                    if ($addAsAnnouncement) {
416
                        $this->storeAgendaEventAsAnnouncement($id, $usersToSend);
417
                    }
418
419
                    // Add attachment.
420
                    if (!empty($attachmentArray)) {
421
                        $counter = 0;
422
                        foreach ($attachmentArray as $attachmentItem) {
423
                            $this->addAttachment(
424
                                $event,
425
                                $attachmentItem,
426
                                $attachmentCommentList[$counter],
427
                                $this->course
428
                            );
429
                            $counter++;
430
                        }
431
                    }
432
                }
433
                break;
434
            case 'admin':
435
                if (api_is_platform_admin()) {
436
                    $event = new SysCalendar();
437
                    $event
438
                        ->setTitle($title)
439
                        ->setContent($content)
440
                        ->setStartDate($start)
441
                        ->setEndDate($end)
442
                        ->setAllDay($allDay)
443
                        ->setAccessUrlId(api_get_current_access_url_id())
444
                    ;
445
                    $em->persist($event);
446
                    $em->flush();
447
                    $id = $event->getId();
448
                }
449
                break;
450
        }
451
452
        return $id;
453
    }
454
455
    /**
456
     * @param int $eventId
457
     * @param int $courseId
458
     *
459
     * @return array
460
     */
461
    public function getRepeatedInfoByEvent($eventId, $courseId)
462
    {
463
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
464
        $eventId = (int) $eventId;
465
        $courseId = (int) $courseId;
466
        $sql = "SELECT * FROM $repeatTable
467
                WHERE c_id = $courseId AND cal_id = $eventId";
468
        $res = Database::query($sql);
469
        $repeatInfo = [];
470
        if (Database::num_rows($res) > 0) {
471
            $repeatInfo = Database::fetch_array($res, 'ASSOC');
472
        }
473
474
        return $repeatInfo;
475
    }
476
477
    /**
478
     * @param string $type
479
     * @param string $startEvent      in UTC
480
     * @param string $endEvent        in UTC
481
     * @param string $repeatUntilDate in UTC
482
     *
483
     * @throws Exception
484
     *
485
     * @return array
486
     */
487
    public function generateDatesByType($type, $startEvent, $endEvent, $repeatUntilDate)
488
    {
489
        $continue = true;
490
        $repeatUntilDate = new DateTime($repeatUntilDate, new DateTimeZone('UTC'));
491
        $loopMax = 365;
492
        $counter = 0;
493
        $list = [];
494
495
        switch ($type) {
496
            case 'daily':
497
                $interval = 'P1D';
498
                break;
499
            case 'weekly':
500
                $interval = 'P1W';
501
                break;
502
            case 'monthlyByDate':
503
                $interval = 'P1M';
504
                break;
505
            case 'monthlyByDay':
506
            case 'monthlyByDayR':
507
                // not yet implemented
508
                break;
509
            case 'yearly':
510
                $interval = 'P1Y';
511
                break;
512
        }
513
514
        if (empty($interval)) {
515
            return [];
516
        }
517
        $timeZone = api_get_timezone();
518
519
        while ($continue) {
520
            $startDate = new DateTime($startEvent, new DateTimeZone('UTC'));
521
            $endDate = new DateTime($endEvent, new DateTimeZone('UTC'));
522
523
            $startDate->add(new DateInterval($interval));
524
            $endDate->add(new DateInterval($interval));
525
526
            $newStartDate = $startDate->format('Y-m-d H:i:s');
527
            $newEndDate = $endDate->format('Y-m-d H:i:s');
528
529
            $startEvent = $newStartDate;
530
            $endEvent = $newEndDate;
531
532
            if ($endDate > $repeatUntilDate) {
533
                break;
534
            }
535
536
            // @todo remove comment code
537
            $startDateInLocal = new DateTime($newStartDate, new DateTimeZone($timeZone));
538
            if (0 == $startDateInLocal->format('I')) {
539
                // Is saving time? Then fix UTC time to add time
540
                $seconds = $startDateInLocal->getOffset();
541
                $startDate->add(new DateInterval("PT".$seconds."S"));
542
                $startDateFixed = $startDate->format('Y-m-d H:i:s');
543
                $startDateInLocalFixed = new DateTime($startDateFixed, new DateTimeZone($timeZone));
544
                $newStartDate = $startDateInLocalFixed->format('Y-m-d H:i:s');
545
            }
546
547
            $endDateInLocal = new DateTime($newEndDate, new DateTimeZone($timeZone));
548
            if (0 == $endDateInLocal->format('I')) {
549
                // Is saving time? Then fix UTC time to add time
550
                $seconds = $endDateInLocal->getOffset();
551
                $endDate->add(new DateInterval("PT".$seconds."S"));
552
                $endDateFixed = $endDate->format('Y-m-d H:i:s');
553
                $endDateInLocalFixed = new DateTime($endDateFixed, new DateTimeZone($timeZone));
554
                $newEndDate = $endDateInLocalFixed->format('Y-m-d H:i:s');
555
            }
556
            $list[] = ['start' => $newStartDate, 'end' => $newEndDate, 'i' => $startDateInLocal->format('I')];
557
            $counter++;
558
559
            // just in case stop if more than $loopMax
560
            if ($counter > $loopMax) {
561
                break;
562
            }
563
        }
564
565
        return $list;
566
    }
567
568
    /**
569
     * @param int    $eventId
570
     * @param string $type
571
     * @param string $end     in UTC
572
     * @param array  $sentTo
573
     *
574
     * @return bool
575
     */
576
    public function addRepeatedItem($eventId, $type, $end, $sentTo = [])
577
    {
578
        $t_agenda = Database::get_course_table(TABLE_AGENDA);
579
        $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
580
581
        if (empty($this->course)) {
582
            return false;
583
        }
584
585
        $courseId = $this->course['real_id'];
586
        $eventId = (int) $eventId;
587
588
        $sql = "SELECT title, content, start_date, end_date, all_day
589
                FROM $t_agenda
590
                WHERE c_id = $courseId AND id = $eventId";
591
        $res = Database::query($sql);
592
593
        if (1 !== Database::num_rows($res)) {
594
            return false;
595
        }
596
597
        $typeList = [
598
            'daily',
599
            'weekly',
600
            'monthlyByDate',
601
            'monthlyByDay',
602
            'monthlyByDayR',
603
            'yearly',
604
        ];
605
606
        if (!in_array($type, $typeList)) {
607
            return false;
608
        }
609
610
        $now = time();
611
612
        // The event has to repeat *in the future*. We don't allow repeated
613
        // events in the past
614
        if ($end > $now) {
615
            return false;
616
        }
617
618
        $row = Database::fetch_array($res);
619
620
        $title = $row['title'];
621
        $content = $row['content'];
622
        $allDay = $row['all_day'];
623
624
        $type = Database::escape_string($type);
625
        $end = Database::escape_string($end);
626
        $endTimeStamp = api_strtotime($end, 'UTC');
627
        $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
628
                VALUES ($courseId, '$eventId', '$type', '$endTimeStamp')";
629
        Database::query($sql);
630
631
        $generatedDates = $this->generateDatesByType($type, $row['start_date'], $row['end_date'], $end);
632
633
        if (empty($generatedDates)) {
634
            return false;
635
        }
636
637
        foreach ($generatedDates as $dateInfo) {
638
            $start = api_get_local_time($dateInfo['start']);
639
            $end = api_get_local_time($dateInfo['end']);
640
            $this->addEvent(
641
                $start,
642
                $end,
643
                $allDay,
644
                $title,
645
                $content,
646
                $sentTo,
647
                false,
648
                $eventId
649
            );
650
        }
651
652
        return true;
653
    }
654
655
    /**
656
     * @param int   $item_id
657
     * @param array $sentTo
658
     *
659
     * @return int
660
     */
661
    public function storeAgendaEventAsAnnouncement($item_id, $sentTo = [])
662
    {
663
        $table_agenda = Database::get_course_table(TABLE_AGENDA);
664
        $courseId = api_get_course_int_id();
665
666
        // Get the agenda item.
667
        $item_id = (int) $item_id;
668
        $sql = "SELECT * FROM $table_agenda
669
                WHERE c_id = $courseId AND id = ".$item_id;
670
        $res = Database::query($sql);
671
672
        if (Database::num_rows($res) > 0) {
673
            $row = Database::fetch_array($res, 'ASSOC');
674
675
            // Sending announcement
676
            if (!empty($sentTo)) {
677
                $id = AnnouncementManager::add_announcement(
678
                    api_get_course_info(),
679
                    api_get_session_id(),
680
                    $row['title'],
681
                    $row['content'],
682
                    $sentTo,
683
                    null,
684
                    null,
685
                    $row['end_date']
686
                );
687
688
                AnnouncementManager::sendEmail(
689
                    api_get_course_info(),
690
                    api_get_session_id(),
691
                    $id
692
                );
693
694
                return $id;
695
            }
696
        }
697
698
        return -1;
699
    }
700
701
    /**
702
     * Edits an event.
703
     *
704
     * @param int    $id
705
     * @param string $start                 datetime format: 2012-06-14 09:00:00
706
     * @param string $end                   datetime format: 2012-06-14 09:00:00
707
     * @param int    $allDay                is all day 'true' or 'false'
708
     * @param string $title
709
     * @param string $content
710
     * @param array  $usersToSend
711
     * @param array  $attachmentArray
712
     * @param array  $attachmentCommentList
713
     * @param string $comment
714
     * @param string $color
715
     * @param bool   $addAnnouncement
716
     * @param bool   $updateContent
717
     * @param int    $authorId
718
     *
719
     * @return bool
720
     */
721
    public function editEvent(
722
        $id,
723
        $start,
724
        $end,
725
        $allDay,
726
        $title,
727
        $content,
728
        $usersToSend = [],
729
        $attachmentArray = [],
730
        $attachmentCommentList = [],
731
        $comment = null,
732
        $color = '',
733
        $addAnnouncement = false,
734
        $updateContent = true,
735
        $authorId = 0
736
    ) {
737
        $start = api_get_utc_datetime($start);
738
        $end = api_get_utc_datetime($end);
739
        $allDay = isset($allDay) && 'true' == $allDay ? 1 : 0;
740
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
741
742
        switch ($this->type) {
743
            case 'personal':
744
                $eventInfo = $this->get_event($id);
745
                if ($eventInfo['user'] != api_get_user_id()) {
746
                    break;
747
                }
748
                $attributes = [
749
                    'title' => $title,
750
                    'date' => $start,
751
                    'enddate' => $end,
752
                    'all_day' => $allDay,
753
                ];
754
755
                if ($updateContent) {
756
                    $attributes['text'] = $content;
757
                }
758
759
                if (!empty($color)) {
760
                    $attributes['color'] = $color;
761
                }
762
763
                Database::update(
764
                    $this->tbl_personal_agenda,
765
                    $attributes,
766
                    ['id = ?' => $id]
767
                );
768
                break;
769
            case 'course':
770
                $eventInfo = $this->get_event($id);
771
772
                if (empty($eventInfo)) {
773
                    return false;
774
                }
775
776
                $groupId = api_get_group_id();
777
                $groupIid = 0;
778
                $groupInfo = [];
779
                if ($groupId) {
780
                    $groupInfo = GroupManager::get_group_properties($groupId);
781
                    if ($groupInfo) {
782
                        $groupIid = $groupInfo['iid'];
783
                    }
784
                }
785
786
                $courseId = $this->course['real_id'];
787
788
                if (empty($courseId)) {
789
                    return false;
790
                }
791
792
                if ($this->getIsAllowedToEdit()) {
793
                    $attributes = [
794
                        'title' => $title,
795
                        'start_date' => $start,
796
                        'end_date' => $end,
797
                        'all_day' => $allDay,
798
                        'comment' => $comment,
799
                    ];
800
801
                    if ($updateContent) {
802
                        $attributes['content'] = $content;
803
                    }
804
805
                    if (!empty($color)) {
806
                        $attributes['color'] = $color;
807
                    }
808
809
                    Database::update(
810
                        $this->tbl_course_agenda,
811
                        $attributes,
812
                        [
813
                            'id = ? AND c_id = ? AND session_id = ? ' => [
814
                                $id,
815
                                $courseId,
816
                                $this->sessionId,
817
                            ],
818
                        ]
819
                    );
820
821
                    if (!empty($usersToSend)) {
822
                        $sendTo = $this->parseSendToArray($usersToSend);
823
824
                        $usersToDelete = array_diff(
825
                            $eventInfo['send_to']['users'],
826
                            $sendTo['users']
827
                        );
828
                        $usersToAdd = array_diff(
829
                            $sendTo['users'],
830
                            $eventInfo['send_to']['users']
831
                        );
832
833
                        $groupsToDelete = array_diff(
834
                            $eventInfo['send_to']['groups'],
835
                            $sendTo['groups']
836
                        );
837
                        $groupToAdd = array_diff(
838
                            $sendTo['groups'],
839
                            $eventInfo['send_to']['groups']
840
                        );
841
842
                        if ($sendTo['everyone']) {
843
                            // Delete all from group
844
                            if (isset($eventInfo['send_to']['groups']) &&
845
                                !empty($eventInfo['send_to']['groups'])
846
                            ) {
847
                                foreach ($eventInfo['send_to']['groups'] as $group) {
848
                                    $groupIidItem = 0;
849
                                    if ($group) {
850
                                        $groupInfoItem = GroupManager::get_group_properties(
851
                                            $group
852
                                        );
853
                                        if ($groupInfoItem) {
854
                                            $groupIidItem = $groupInfoItem['iid'];
855
                                        }
856
                                    }
857
858
                                    api_item_property_delete(
859
                                        $this->course,
860
                                        TOOL_CALENDAR_EVENT,
861
                                        $id,
862
                                        0,
863
                                        $groupIidItem,
864
                                        $this->sessionId
865
                                    );
866
                                }
867
                            }
868
869
                            // Storing the selected users.
870
                            if (isset($eventInfo['send_to']['users']) &&
871
                                !empty($eventInfo['send_to']['users'])
872
                            ) {
873
                                foreach ($eventInfo['send_to']['users'] as $userId) {
874
                                    api_item_property_delete(
875
                                        $this->course,
876
                                        TOOL_CALENDAR_EVENT,
877
                                        $id,
878
                                        $userId,
879
                                        $groupIid,
880
                                        $this->sessionId
881
                                    );
882
                                }
883
                            }
884
885
                            // Add to everyone only.
886
                            api_item_property_update(
887
                                $this->course,
888
                                TOOL_CALENDAR_EVENT,
889
                                $id,
890
                                'visible',
891
                                $authorId,
892
                                $groupInfo,
893
                                null,
894
                                $start,
895
                                $end,
896
                                $this->sessionId
897
                            );
898
                        } else {
899
                            // Delete "everyone".
900
                            api_item_property_delete(
901
                                $this->course,
902
                                TOOL_CALENDAR_EVENT,
903
                                $id,
904
                                0,
905
                                0,
906
                                $this->sessionId
907
                            );
908
909
                            // Add groups
910
                            if (!empty($groupToAdd)) {
911
                                foreach ($groupToAdd as $group) {
912
                                    $groupInfoItem = [];
913
                                    if ($group) {
914
                                        $groupInfoItem = GroupManager::get_group_properties(
915
                                            $group
916
                                        );
917
                                    }
918
919
                                    api_item_property_update(
920
                                        $this->course,
921
                                        TOOL_CALENDAR_EVENT,
922
                                        $id,
923
                                        'visible',
924
                                        $authorId,
925
                                        $groupInfoItem,
926
                                        0,
927
                                        $start,
928
                                        $end,
929
                                        $this->sessionId
930
                                    );
931
                                }
932
                            }
933
934
                            // Delete groups.
935
                            if (!empty($groupsToDelete)) {
936
                                foreach ($groupsToDelete as $group) {
937
                                    $groupIidItem = 0;
938
                                    if ($group) {
939
                                        $groupInfoItem = GroupManager::get_group_properties(
940
                                            $group
941
                                        );
942
                                        if ($groupInfoItem) {
943
                                            $groupIidItem = $groupInfoItem['iid'];
944
                                        }
945
                                    }
946
947
                                    api_item_property_delete(
948
                                        $this->course,
949
                                        TOOL_CALENDAR_EVENT,
950
                                        $id,
951
                                        0,
952
                                        $groupIidItem,
953
                                        $this->sessionId
954
                                    );
955
                                }
956
                            }
957
958
                            // Add users.
959
                            if (!empty($usersToAdd)) {
960
                                foreach ($usersToAdd as $userId) {
961
                                    api_item_property_update(
962
                                        $this->course,
963
                                        TOOL_CALENDAR_EVENT,
964
                                        $id,
965
                                        'visible',
966
                                        $authorId,
967
                                        $groupInfo,
968
                                        $userId,
969
                                        $start,
970
                                        $end,
971
                                        $this->sessionId
972
                                    );
973
                                }
974
                            }
975
976
                            // Delete users.
977
                            if (!empty($usersToDelete)) {
978
                                foreach ($usersToDelete as $userId) {
979
                                    api_item_property_delete(
980
                                        $this->course,
981
                                        TOOL_CALENDAR_EVENT,
982
                                        $id,
983
                                        $userId,
984
                                        $groupInfo,
985
                                        $this->sessionId
986
                                    );
987
                                }
988
                            }
989
                        }
990
                    }
991
992
                    // Add announcement.
993
                    if (isset($addAnnouncement) && !empty($addAnnouncement)) {
994
                        $this->storeAgendaEventAsAnnouncement(
995
                            $id,
996
                            $usersToSend
997
                        );
998
                    }
999
1000
                    // Add attachment.
1001
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
1002
                        $counter = 0;
1003
                        foreach ($attachmentArray as $attachmentItem) {
1004
                            $this->updateAttachment(
1005
                                $attachmentItem['id'],
1006
                                $id,
1007
                                $attachmentItem,
1008
                                $attachmentCommentList[$counter],
1009
                                $this->course
1010
                            );
1011
                            $counter++;
1012
                        }
1013
                    }
1014
1015
                    return true;
1016
                } else {
1017
                    return false;
1018
                }
1019
                break;
1020
            case 'admin':
1021
            case 'platform':
1022
                if (api_is_platform_admin()) {
1023
                    $attributes = [
1024
                        'title' => $title,
1025
                        'start_date' => $start,
1026
                        'end_date' => $end,
1027
                        'all_day' => $allDay,
1028
                    ];
1029
1030
                    if ($updateContent) {
1031
                        $attributes['content'] = $content;
1032
                    }
1033
                    Database::update(
1034
                        $this->tbl_global_agenda,
1035
                        $attributes,
1036
                        ['id = ?' => $id]
1037
                    );
1038
                }
1039
                break;
1040
        }
1041
    }
1042
1043
    /**
1044
     * @param int  $id
1045
     * @param bool $deleteAllItemsFromSerie
1046
     */
1047
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
1048
    {
1049
        switch ($this->type) {
1050
            case 'personal':
1051
                $eventInfo = $this->get_event($id);
1052
                if ($eventInfo['user'] == api_get_user_id()) {
1053
                    Database::delete(
1054
                        $this->tbl_personal_agenda,
1055
                        ['id = ?' => $id]
1056
                    );
1057
                }
1058
                break;
1059
            case 'course':
1060
                $courseId = api_get_course_int_id();
1061
                $isAllowToEdit = $this->getIsAllowedToEdit();
1062
1063
                if (!empty($courseId) && $isAllowToEdit) {
1064
                    // Delete
1065
                    $eventInfo = $this->get_event($id);
1066
                    if ($deleteAllItemsFromSerie) {
1067
                        /* This is one of the children.
1068
                           Getting siblings and delete 'Em all + the father! */
1069
                        if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
1070
                            // Removing items.
1071
                            $events = $this->getAllRepeatEvents($eventInfo['parent_event_id']);
1072
                            if (!empty($events)) {
1073
                                foreach ($events as $event) {
1074
                                    $this->deleteEvent($event['id']);
1075
                                }
1076
                            }
1077
                            // Removing parent.
1078
                            $this->deleteEvent($eventInfo['parent_event_id']);
1079
                        } else {
1080
                            // This is the father looking for the children.
1081
                            $events = $this->getAllRepeatEvents($id);
1082
                            if (!empty($events)) {
1083
                                foreach ($events as $event) {
1084
                                    $this->deleteEvent($event['id']);
1085
                                }
1086
                            }
1087
                        }
1088
                    }
1089
1090
                    $repo = Container::getCalendarEventRepository();
1091
                    $event = $repo->find($id);
1092
1093
                    if ($event) {
1094
                        $repo->getEntityManager()->remove($event);
1095
                        $repo->getEntityManager()->flush();
1096
1097
                        // Removing from events.
1098
                        /*Database::delete(
1099
                            $this->tbl_course_agenda,
1100
                            ['id = ? AND c_id = ?' => [$id, $courseId]]
1101
                        );*/
1102
1103
                        /*api_item_property_update(
1104
                            $this->course,
1105
                            TOOL_CALENDAR_EVENT,
1106
                            $id,
1107
                            'delete',
1108
                            api_get_user_id()
1109
                        );*/
1110
1111
                        // Removing from series.
1112
                        Database::delete(
1113
                            $this->table_repeat,
1114
                            [
1115
                                'cal_id = ? AND c_id = ?' => [
1116
                                    $id,
1117
                                    $courseId,
1118
                                ],
1119
                            ]
1120
                        );
1121
                        // Attachments are already deleted using the doctrine remove() function.
1122
                        /*if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
1123
                            foreach ($eventInfo['attachment'] as $attachment) {
1124
                                self::deleteAttachmentFile(
1125
                                    $attachment['id'],
1126
                                    $this->course
1127
                                );
1128
                            }
1129
                        }*/
1130
                    }
1131
                }
1132
                break;
1133
            case 'admin':
1134
                if (api_is_platform_admin()) {
1135
                    Database::delete(
1136
                        $this->tbl_global_agenda,
1137
                        ['id = ?' => $id]
1138
                    );
1139
                }
1140
                break;
1141
        }
1142
    }
1143
1144
    /**
1145
     * Get agenda events.
1146
     *
1147
     * @param int    $start
1148
     * @param int    $end
1149
     * @param int    $courseId
1150
     * @param int    $groupId
1151
     * @param int    $user_id
1152
     * @param string $format
1153
     *
1154
     * @return array|string
1155
     */
1156
    public function getEvents(
1157
        $start,
1158
        $end,
1159
        $courseId = null,
1160
        $groupId = null,
1161
        $user_id = 0,
1162
        $format = 'json'
1163
    ) {
1164
        switch ($this->type) {
1165
            case 'admin':
1166
                $this->getPlatformEvents($start, $end);
1167
                break;
1168
            case 'course':
1169
                $courseInfo = api_get_course_info_by_id($courseId);
1170
1171
                // Session coach can see all events inside a session.
1172
                if (api_is_coach()) {
1173
                    // Own course
1174
                    $this->getCourseEvents(
1175
                        $start,
1176
                        $end,
1177
                        $courseInfo,
1178
                        $groupId,
1179
                        $this->sessionId,
1180
                        $user_id
1181
                    );
1182
1183
                    // Others
1184
                    $this->getSessionEvents(
1185
                        $start,
1186
                        $end,
1187
                        $this->sessionId,
1188
                        $user_id,
1189
                        $this->eventOtherSessionColor
1190
                    );
1191
                } else {
1192
                    $this->getCourseEvents(
1193
                        $start,
1194
                        $end,
1195
                        $courseInfo,
1196
                        $groupId,
1197
                        $this->sessionId,
1198
                        $user_id
1199
                    );
1200
                }
1201
                break;
1202
            case 'personal':
1203
            default:
1204
                $sessionFilterActive = false;
1205
                if (!empty($this->sessionId)) {
1206
                    $sessionFilterActive = true;
1207
                }
1208
1209
                if (false == $sessionFilterActive) {
1210
                    // Getting personal events
1211
                    $this->getPersonalEvents($start, $end);
1212
1213
                    // Getting platform/admin events
1214
                    $this->getPlatformEvents($start, $end);
1215
                }
1216
1217
                $ignoreVisibility = api_get_configuration_value('personal_agenda_show_all_session_events');
1218
1219
                // Getting course events
1220
                $my_course_list = [];
1221
                if (!api_is_anonymous()) {
1222
                    $session_list = SessionManager::get_sessions_by_user(
1223
                        api_get_user_id(),
1224
                        $ignoreVisibility
1225
                    );
1226
                    $my_course_list = CourseManager::get_courses_list_by_user_id(
1227
                        api_get_user_id(),
1228
                        false
1229
                    );
1230
                }
1231
1232
                if (api_is_drh()) {
1233
                    if (api_drh_can_access_all_session_content()) {
1234
                        $session_list = [];
1235
                        $sessionList = SessionManager::get_sessions_followed_by_drh(
1236
                            api_get_user_id(),
1237
                            null,
1238
                            null,
1239
                            null,
1240
                            true,
1241
                            false
1242
                        );
1243
1244
                        if (!empty($sessionList)) {
1245
                            foreach ($sessionList as $sessionItem) {
1246
                                $sessionId = $sessionItem['id'];
1247
                                $courses = SessionManager::get_course_list_by_session_id(
1248
                                    $sessionId
1249
                                );
1250
                                $sessionInfo = [
1251
                                    'session_id' => $sessionId,
1252
                                    'courses' => $courses,
1253
                                ];
1254
                                $session_list[] = $sessionInfo;
1255
                            }
1256
                        }
1257
                    }
1258
                }
1259
1260
                if (!empty($session_list)) {
1261
                    foreach ($session_list as $session_item) {
1262
                        if ($sessionFilterActive) {
1263
                            if ($this->sessionId != $session_item['session_id']) {
1264
                                continue;
1265
                            }
1266
                        }
1267
1268
                        $my_courses = $session_item['courses'];
1269
                        $my_session_id = $session_item['session_id'];
1270
1271
                        if (!empty($my_courses)) {
1272
                            foreach ($my_courses as $course_item) {
1273
                                $courseInfo = api_get_course_info_by_id(
1274
                                    $course_item['real_id']
1275
                                );
1276
                                $this->getCourseEvents(
1277
                                    $start,
1278
                                    $end,
1279
                                    $courseInfo,
1280
                                    0,
1281
                                    $my_session_id
1282
                                );
1283
                            }
1284
                        }
1285
                    }
1286
                }
1287
1288
                if (!empty($my_course_list) && false == $sessionFilterActive) {
1289
                    foreach ($my_course_list as $courseInfoItem) {
1290
                        $courseInfo = api_get_course_info_by_id(
1291
                            $courseInfoItem['real_id']
1292
                        );
1293
                        if (isset($courseId) && !empty($courseId)) {
1294
                            if ($courseInfo['real_id'] == $courseId) {
1295
                                $this->getCourseEvents(
1296
                                    $start,
1297
                                    $end,
1298
                                    $courseInfo,
1299
                                    0,
1300
                                    0,
1301
                                    $user_id
1302
                                );
1303
                            }
1304
                        } else {
1305
                            $this->getCourseEvents(
1306
                                $start,
1307
                                $end,
1308
                                $courseInfo,
1309
                                0,
1310
                                0,
1311
                                $user_id
1312
                            );
1313
                        }
1314
                    }
1315
                }
1316
                break;
1317
        }
1318
1319
        $this->cleanEvents();
1320
1321
        switch ($format) {
1322
            case 'json':
1323
                if (empty($this->events)) {
1324
                    return '[]';
1325
                }
1326
1327
                return json_encode($this->events);
1328
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1329
            case 'array':
1330
                if (empty($this->events)) {
1331
                    return [];
1332
                }
1333
1334
                return $this->events;
1335
                break;
1336
        }
1337
    }
1338
1339
    /**
1340
     * Clean events.
1341
     *
1342
     * @return bool
1343
     */
1344
    public function cleanEvents()
1345
    {
1346
        if (empty($this->events)) {
1347
            return false;
1348
        }
1349
1350
        foreach ($this->events as &$event) {
1351
            $event['description'] = Security::remove_XSS($event['description']);
1352
            $event['title'] = Security::remove_XSS($event['title']);
1353
        }
1354
1355
        return true;
1356
    }
1357
1358
    /**
1359
     * @param int $id
1360
     * @param int $minute_delta
1361
     *
1362
     * @return int
1363
     */
1364
    public function resizeEvent($id, $minute_delta)
1365
    {
1366
        $id = (int) $id;
1367
        $delta = (int) $minute_delta;
1368
        $event = $this->get_event($id);
1369
        if (!empty($event)) {
1370
            switch ($this->type) {
1371
                case 'personal':
1372
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1373
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1374
							WHERE id = ".$id;
1375
                    Database::query($sql);
1376
                    break;
1377
                case 'course':
1378
                    $sql = "UPDATE $this->tbl_course_agenda SET
1379
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1380
							WHERE
1381
							    c_id = ".$this->course['real_id']." AND
1382
							    id = ".$id;
1383
                    Database::query($sql);
1384
                    break;
1385
                case 'admin':
1386
                    $sql = "UPDATE $this->tbl_global_agenda SET
1387
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1388
							WHERE id = ".$id;
1389
                    Database::query($sql);
1390
                    break;
1391
            }
1392
        }
1393
1394
        return 1;
1395
    }
1396
1397
    /**
1398
     * @param int $id
1399
     * @param int $minute_delta minutes
1400
     * @param int $allDay
1401
     *
1402
     * @return int
1403
     */
1404
    public function move_event($id, $minute_delta, $allDay)
1405
    {
1406
        $id = (int) $id;
1407
        $event = $this->get_event($id);
1408
1409
        if (empty($event)) {
1410
            return false;
1411
        }
1412
1413
        // we convert the hour delta into minutes and add the minute delta
1414
        $delta = (int) $minute_delta;
1415
        $allDay = (int) $allDay;
1416
1417
        if (!empty($event)) {
1418
            switch ($this->type) {
1419
                case 'personal':
1420
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1421
                            all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
1422
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1423
							WHERE id=".$id;
1424
                    Database::query($sql);
1425
                    break;
1426
                case 'course':
1427
                    $sql = "UPDATE $this->tbl_course_agenda SET
1428
                            all_day = $allDay,
1429
                            start_date = DATE_ADD(start_date, INTERVAL $delta MINUTE),
1430
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1431
							WHERE
1432
							    c_id = ".$this->course['real_id']." AND
1433
							    id=".$id;
1434
                    Database::query($sql);
1435
                    break;
1436
                case 'admin':
1437
                    $sql = "UPDATE $this->tbl_global_agenda SET
1438
                            all_day = $allDay,
1439
                            start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1440
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1441
							WHERE id=".$id;
1442
                    Database::query($sql);
1443
                    break;
1444
            }
1445
        }
1446
1447
        return 1;
1448
    }
1449
1450
    /**
1451
     * Gets a single event.
1452
     *
1453
     * @param int $id event id
1454
     *
1455
     * @return array
1456
     */
1457
    public function get_event($id)
1458
    {
1459
        // make sure events of the personal agenda can only be seen by the user himself
1460
        $id = (int) $id;
1461
        $event = null;
1462
        switch ($this->type) {
1463
            case 'personal':
1464
                $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1465
                        WHERE id = $id AND user = ".api_get_user_id();
1466
                $result = Database::query($sql);
1467
                if (Database::num_rows($result)) {
1468
                    $event = Database::fetch_array($result, 'ASSOC');
1469
                    $event['description'] = $event['text'];
1470
                    $event['content'] = $event['text'];
1471
                    $event['start_date'] = $event['date'];
1472
                    $event['end_date'] = $event['enddate'];
1473
                }
1474
                break;
1475
            case 'course':
1476
                if (!empty($this->course['real_id'])) {
1477
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
1478
                            WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
1479
                    $result = Database::query($sql);
1480
                    if (Database::num_rows($result)) {
1481
                        $event = Database::fetch_array($result, 'ASSOC');
1482
                        $event['description'] = $event['content'];
1483
1484
                        // Getting send to array
1485
                        $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
1486
                            $id,
1487
                            $this->course['real_id'],
1488
                            $this->sessionId
1489
                        );
1490
1491
                        // Getting repeat info
1492
                        $event['repeat_info'] = $this->getRepeatedInfoByEvent(
1493
                            $id,
1494
                            $this->course['real_id']
1495
                        );
1496
1497
                        if (!empty($event['parent_event_id'])) {
1498
                            $event['parent_info'] = $this->get_event(
1499
                                $event['parent_event_id']
1500
                            );
1501
                        }
1502
1503
                        $event['attachment'] = $this->getAttachmentList($id, $this->course);
1504
                    }
1505
                }
1506
                break;
1507
            case 'admin':
1508
            case 'platform':
1509
                $sql = "SELECT * FROM ".$this->tbl_global_agenda."
1510
                        WHERE id = $id";
1511
                $result = Database::query($sql);
1512
                if (Database::num_rows($result)) {
1513
                    $event = Database::fetch_array($result, 'ASSOC');
1514
                    $event['description'] = $event['content'];
1515
                }
1516
                break;
1517
        }
1518
1519
        return $event;
1520
    }
1521
1522
    /**
1523
     * Gets personal events.
1524
     *
1525
     * @param int $start
1526
     * @param int $end
1527
     *
1528
     * @return array
1529
     */
1530
    public function getPersonalEvents($start, $end)
1531
    {
1532
        $start = (int) $start;
1533
        $end = (int) $end;
1534
        $startCondition = '';
1535
        $endCondition = '';
1536
1537
        if (0 !== $start) {
1538
            $startCondition = "AND date >= '".api_get_utc_datetime($start)."'";
1539
        }
1540
        if (0 !== $start) {
1541
            $endCondition = "AND (enddate <= '".api_get_utc_datetime($end)."' OR enddate IS NULL)";
1542
        }
1543
        $user_id = api_get_user_id();
1544
1545
        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1546
                WHERE user = $user_id $startCondition $endCondition";
1547
1548
        $result = Database::query($sql);
1549
        $my_events = [];
1550
        if (Database::num_rows($result)) {
1551
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1552
                $event = [];
1553
                $event['id'] = 'personal_'.$row['id'];
1554
                $event['title'] = $row['title'];
1555
                $event['className'] = 'personal';
1556
                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
1557
                $event['editable'] = true;
1558
                $event['sent_to'] = get_lang('Me');
1559
                $event['type'] = 'personal';
1560
1561
                if (!empty($row['date'])) {
1562
                    $event['start'] = $this->formatEventDate($row['date']);
1563
                    $event['start_date_localtime'] = api_get_local_time($row['date']);
1564
                }
1565
1566
                if (!empty($row['enddate'])) {
1567
                    $event['end'] = $this->formatEventDate($row['enddate']);
1568
                    $event['end_date_localtime'] = api_get_local_time($row['enddate']);
1569
                }
1570
1571
                $event['description'] = $row['text'];
1572
                $event['allDay'] = isset($row['all_day']) && 1 == $row['all_day'] ? $row['all_day'] : 0;
1573
                $event['parent_event_id'] = 0;
1574
                $event['has_children'] = 0;
1575
1576
                $my_events[] = $event;
1577
                $this->events[] = $event;
1578
            }
1579
        }
1580
1581
        // Add plugin personal events
1582
        $this->plugin = new AppPlugin();
1583
        $plugins = $this->plugin->getInstalledPluginListObject();
1584
        /** @var Plugin $plugin */
1585
        foreach ($plugins as $plugin) {
1586
            if ($plugin->hasPersonalEvents && method_exists($plugin, 'getPersonalEvents')) {
1587
                $pluginEvents = $plugin->getPersonalEvents($this, $start, $end);
1588
1589
                if (!empty($pluginEvents)) {
1590
                    $this->events = array_merge($this->events, $pluginEvents);
1591
                }
1592
            }
1593
        }
1594
1595
        return $my_events;
1596
    }
1597
1598
    /**
1599
     * Get user/group list per event.
1600
     *
1601
     * @param int $eventId
1602
     * @param int $courseId
1603
     * @param int $sessionId
1604
     * @paraù int $sessionId
1605
     *
1606
     * @return array
1607
     */
1608
    public function getUsersAndGroupSubscribedToEvent(
1609
        $eventId,
1610
        $courseId,
1611
        $sessionId
1612
    ) {
1613
        $eventId = (int) $eventId;
1614
        $courseId = (int) $courseId;
1615
        $sessionId = (int) $sessionId;
1616
1617
        $repo = Container::getCalendarEventRepository();
1618
        /** @var CCalendarEvent $event */
1619
        $event = $repo->find($eventId);
1620
1621
        if (null === $event) {
1622
            return [];
1623
        }
1624
1625
        $course = api_get_course_entity($courseId);
1626
        $session = api_get_session_entity($sessionId);
1627
1628
        $users = [];
1629
        $groups = [];
1630
        $everyone = false;
1631
        $links = $event->getResourceNode()->getResourceLinks();
1632
        foreach ($links as $link) {
1633
            if ($link->getUser()) {
1634
                $users[] = $link->getUser()->getId();
1635
            }
1636
            if ($link->getGroup()) {
1637
                $groups[] = $link->getGroup()->getId();
1638
            }
1639
        }
1640
1641
        if (empty($users) && empty($groups)) {
1642
            $everyone = true;
1643
        }
1644
1645
        return [
1646
            'everyone' => $everyone,
1647
            'users' => $users,
1648
            'groups' => $groups,
1649
        ];
1650
1651
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
Unused Code introduced by
ExitNode is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1652
1653
        $sessionCondition = "ip.session_id = $sessionId";
1654
        if (empty($sessionId)) {
1655
            $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
1656
        }
1657
1658
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1659
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1660
1661
        // Get sent_tos
1662
        $sql = "SELECT DISTINCT to_user_id, to_group_id
1663
                FROM $tbl_property ip
1664
                INNER JOIN $tlb_course_agenda agenda
1665
                ON (
1666
                  ip.ref = agenda.iid AND
1667
                  ip.c_id = agenda.c_id AND
1668
                  ip.tool = '".TOOL_CALENDAR_EVENT."'
1669
                )
1670
                WHERE
1671
                    ref = $eventId AND
1672
                    ip.visibility = '1' AND
1673
                    ip.c_id = $courseId AND
1674
                    $sessionCondition
1675
                ";
1676
1677
        $result = Database::query($sql);
1678
        $users = [];
1679
        $groups = [];
1680
        $everyone = false;
1681
1682
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1683
            if (!empty($row['to_group_id'])) {
1684
                $groups[] = $row['to_group_id'];
1685
            }
1686
            if (!empty($row['to_user_id'])) {
1687
                $users[] = $row['to_user_id'];
1688
            }
1689
1690
            if (empty($groups) && empty($users)) {
1691
                if (0 == $row['to_group_id']) {
1692
                    $everyone = true;
1693
                }
1694
            }
1695
        }
1696
1697
        return [
1698
            'everyone' => $everyone,
1699
            'users' => $users,
1700
            'groups' => $groups,
1701
        ];
1702
    }
1703
1704
    /**
1705
     * @param int    $start
1706
     * @param int    $end
1707
     * @param int    $sessionId
1708
     * @param int    $userId
1709
     * @param string $color
1710
     *
1711
     * @return array
1712
     */
1713
    public function getSessionEvents(
1714
        $start,
1715
        $end,
1716
        $sessionId = 0,
1717
        $userId = 0,
1718
        $color = ''
1719
    ) {
1720
        $courses = SessionManager::get_course_list_by_session_id($sessionId);
1721
1722
        if (!empty($courses)) {
1723
            foreach ($courses as $course) {
1724
                $this->getCourseEvents(
1725
                    $start,
1726
                    $end,
1727
                    $course,
1728
                    0,
1729
                    $sessionId,
1730
                    0,
1731
                    $color
1732
                );
1733
            }
1734
        }
1735
    }
1736
1737
    /**
1738
     * @param int    $start
1739
     * @param int    $end
1740
     * @param array  $courseInfo
1741
     * @param int    $groupId
1742
     * @param int    $sessionId
1743
     * @param int    $user_id
1744
     * @param string $color
1745
     *
1746
     * @return array
1747
     */
1748
    public function getCourseEvents(
1749
        $start,
1750
        $end,
1751
        $courseInfo,
1752
        $groupId = 0,
1753
        $sessionId = 0,
1754
        $user_id = 0,
1755
        $color = ''
1756
    ) {
1757
        $start = (int) $start;
1758
        $end = (int) $end;
1759
1760
        $start = !empty($start) ? api_get_utc_datetime($start) : null;
1761
        $end = !empty($end) ? api_get_utc_datetime($end) : null;
1762
1763
        if (empty($courseInfo)) {
1764
            return [];
1765
        }
1766
1767
        $courseId = $courseInfo['real_id'];
1768
1769
        if (empty($courseId)) {
1770
            return [];
1771
        }
1772
1773
        $userId = api_get_user_id();
1774
        $sessionId = (int) $sessionId;
1775
        $user_id = (int) $user_id;
1776
1777
        $groupList = GroupManager::get_group_list(
1778
            null,
1779
            $courseInfo,
1780
            null,
1781
            $sessionId
1782
        );
1783
1784
        $groupNameList = [];
1785
        if (!empty($groupList)) {
1786
            foreach ($groupList as $group) {
1787
                $groupNameList[$group['iid']] = $group['name'];
1788
            }
1789
        }
1790
1791
        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
1792
            $isAllowToEdit = true;
1793
        } else {
1794
            $isAllowToEdit = CourseManager::isCourseTeacher(
1795
                $userId,
1796
                $courseId
1797
            );
1798
        }
1799
1800
        $isAllowToEditByHrm = false;
1801
        if (!empty($sessionId)) {
1802
            $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
1803
            if ($allowDhrToEdit) {
1804
                $isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, $userId);
1805
                if ($isHrm) {
1806
                    $isAllowToEdit = $isAllowToEditByHrm = true;
1807
                }
1808
            }
1809
        }
1810
1811
        $groupMemberships = [];
1812
        if (!empty($groupId)) {
1813
            $groupMemberships = [$groupId];
1814
        } else {
1815
            if ($isAllowToEdit) {
1816
                if (!empty($groupList)) {
1817
                    // c_item_property.to_group_id field was migrated to use
1818
                    // c_group_info.iid
1819
                    $groupMemberships = array_column($groupList, 'iid');
1820
                }
1821
            } else {
1822
                // get only related groups from user
1823
                $groupMemberships = GroupManager::get_group_ids($courseId, $userId);
1824
            }
1825
        }
1826
1827
        $repo = Container::getCalendarEventRepository();
1828
        $courseEntity = api_get_course_entity($courseId);
1829
        $session = api_get_session_entity($sessionId);
1830
        $qb = $repo->getResourcesByCourseOnly($courseEntity, $courseEntity->getResourceNode());
1831
        $userCondition = '';
1832
1833
        if ($isAllowToEdit) {
1834
            // No group filter was asked
1835
            if (empty($groupId)) {
1836
                if (empty($user_id)) {
1837
                    // Show all events not added in group
1838
                    $userCondition = ' (links.group IS NULL) ';
1839
                    // admin see only his stuff
1840
                    if ('personal' === $this->type) {
1841
                        $userCondition = " (links.user = ".api_get_user_id()." AND (links.group IS NULL) ";
1842
                        //$userCondition = " (ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ) ";
1843
                        $userCondition .= " OR ( (links.user IS NULL)  AND (links.group IS NULL ))) ";
1844
                        //$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) ) ";
1845
                    }
1846
1847
                    if (!empty($groupMemberships)) {
1848
                        // Show events sent to selected groups
1849
                        $userCondition .= " OR (links.user IS NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1850
                    }
1851
                } else {
1852
                    // Show events of requested user in no group
1853
                    $userCondition = " (links.user = $user_id AND links.group IS NULL) ";
1854
                    // Show events sent to selected groups
1855
                    if (!empty($groupMemberships)) {
1856
                        $userCondition .= " OR (links.user = $user_id) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1857
                    }
1858
                }
1859
            } else {
1860
                // Show only selected groups (depending of user status)
1861
                $userCondition = " (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1862
1863
                if (!empty($groupMemberships)) {
1864
                    // Show send to $user_id in selected groups
1865
                    $userCondition .= " OR (links.user = $user_id) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1866
                }
1867
            }
1868
        } else {
1869
            // No group filter was asked
1870
            if (empty($groupId)) {
1871
                // Show events sent to everyone and no group
1872
                $userCondition = ' ( (links.user is NULL) AND (links.group IS NULL) ';
1873
                // Show events sent to selected groups
1874
                if (!empty($groupMemberships)) {
1875
                    $userCondition .= " OR (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships)."))) ";
1876
                } else {
1877
                    $userCondition .= " ) ";
1878
                }
1879
                $userCondition .= " OR (links.user = ".api_get_user_id()." AND (links.group IS NULL )) ";
1880
            } else {
1881
                if (!empty($groupMemberships)) {
1882
                    // Show send to everyone - and only selected groups
1883
                    $userCondition = " (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1884
                }
1885
            }
1886
1887
            // Show sent to only me and no group
1888
            if (!empty($groupMemberships)) {
1889
                $userCondition .= " OR (links.user = ".api_get_user_id().") AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1890
            }
1891
        }
1892
1893
        if (!empty($userCondition)) {
1894
            $qb->andWhere($userCondition);
1895
        }
1896
1897
        /*if (!empty($groupMemberships)) {
1898
            $orX = $qb->expr()->orX();
1899
            foreach ($groupMemberships as $groupId) {
1900
                $group = api_get_group_entity($groupId);
1901
                $orX->add("links.group = :group$groupId");
1902
                $qb->setParameter("group$groupId", $group);
1903
            }
1904
            $qb->andWhere($orX);
1905
        }*/
1906
1907
        //$dateCondition = '';
1908
        if (!empty($start) && !empty($end)) {
1909
            $qb->andWhere(
1910
                $qb->expr()->orX(
1911
                    'resource.startDate BETWEEN :start AND :end',
1912
                    'resource.endDate BETWEEN :start AND :end',
1913
                    $qb->expr()->orX(
1914
                        'resource.startDate IS NOT NULL AND resource.endDate IS NOT NULL AND
1915
                            YEAR(resource.startDate) = YEAR(resource.endDate) AND
1916
                            MONTH(:start) BETWEEN MONTH(resource.startDate) AND MONTH(resource.endDate)
1917
                        '
1918
                    )
1919
                )
1920
            )
1921
            ->setParameter('start', $start)
1922
            ->setParameter('end', $end);
1923
1924
            /*
1925
            $dateCondition .= "AND (
1926
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1927
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1928
                 (
1929
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1930
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1931
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1932
                 )
1933
            )";*/
1934
        }
1935
1936
        /*
1937
        if (empty($sessionId)) {
1938
            $sessionCondition = "
1939
            (
1940
                agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
1941
            ) ";
1942
        } else {
1943
            $sessionCondition = "
1944
            (
1945
                agenda.session_id = $sessionId AND
1946
                ip.session_id = $sessionId
1947
            ) ";
1948
        }
1949
1950
        if (api_is_allowed_to_edit()) {
1951
            $visibilityCondition = " (ip.visibility IN ('1', '0'))  ";
1952
        } else {
1953
            $visibilityCondition = " (ip.visibility = '1') ";
1954
        }
1955
1956
        $sql = "SELECT DISTINCT
1957
                    agenda.*,
1958
                    ip.visibility,
1959
                    ip.to_group_id,
1960
                    ip.insert_user_id,
1961
                    ip.ref,
1962
                    to_user_id
1963
                FROM $tlb_course_agenda agenda
1964
                INNER JOIN $tbl_property ip
1965
                ON (
1966
                    agenda.id = ip.ref AND
1967
                    agenda.c_id = ip.c_id AND
1968
                    ip.tool = '".TOOL_CALENDAR_EVENT."'
1969
                )
1970
                WHERE
1971
                    $sessionCondition AND
1972
                    ($userCondition) AND
1973
                    $visibilityCondition AND
1974
                    agenda.c_id = $courseId
1975
        ";
1976
        $dateCondition = '';
1977
        if (!empty($start) && !empty($end)) {
1978
            $dateCondition .= "AND (
1979
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1980
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1981
                 (
1982
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1983
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1984
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1985
                 )
1986
            )";
1987
        }
1988
1989
        $sql .= $dateCondition;
1990
        $result = Database::query($sql);*/
1991
        $coachCanEdit = false;
1992
        if (!empty($sessionId)) {
1993
            $coachCanEdit = api_is_coach($sessionId, $courseId) || api_is_platform_admin();
1994
        }
1995
        //var_dump($groupMemberships, $courseId);        echo $qb->getQuery()->getSQL();exit;
1996
        $events = $qb->getQuery()->getResult();
1997
        //$eventsAdded = array_column($this->events, 'unique_id');
1998
        /** @var CCalendarEvent $row */
1999
        foreach ($events as $row) {
2000
            $eventId = $row->getIid();
2001
            $event = [];
2002
            $event['id'] = 'course_'.$eventId;
2003
            $event['unique_id'] = $eventId;
2004
            // To avoid doubles
2005
            /*if (in_array($event['unique_id'], $eventsAdded)) {
2006
                continue;
2007
            }*/
2008
2009
            $eventsAdded[] = $eventId;
2010
            //$eventId = $row['ref'];
2011
            /*$items = $this->getUsersAndGroupSubscribedToEvent(
2012
                $eventId,
2013
                $courseId,
2014
                $this->sessionId
2015
            );
2016
            $group_to_array = $items['groups'];
2017
            $user_to_array = $items['users'];*/
2018
            /*$attachmentList = $this->getAttachmentList(
2019
                $eventId,
2020
                $courseInfo
2021
            );*/
2022
            $attachmentList = $row->getAttachments();
2023
            $event['attachment'] = '';
2024
            if (!empty($attachmentList)) {
2025
                $icon = Display::returnFontAwesomeIcon(
2026
                    'paperclip',
2027
                    '1'
2028
                );
2029
                $repo = Container::getCalendarEventAttachmentRepository();
2030
                foreach ($attachmentList as $attachment) {
2031
                    //$url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$courseId.'&'.api_get_cidreq();
2032
                    $url = $repo->getResourceFileDownloadUrl($attachment);
2033
                    $event['attachment'] .= $icon.
2034
                        Display::url(
2035
                            $attachment->getFilename(),
2036
                            $url
2037
                        ).'<br />';
2038
                }
2039
            }
2040
2041
            $event['title'] = $row->getTitle();
2042
            $event['className'] = 'course';
2043
            $event['allDay'] = 'false';
2044
            $event['course_id'] = $courseId;
2045
            $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
2046
2047
            $sessionInfo = [];
2048
            if (!empty($row->getSessionId())) {
2049
                $sessionInfo = api_get_session_info($row->getSessionId());
2050
                $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
2051
            }
2052
2053
            $event['session_name'] = $sessionInfo['name'] ?? '';
2054
            $event['course_name'] = $courseInfo['title'] ?? '';
2055
2056
            /*if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
2057
                $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
2058
            }*/
2059
2060
            if (!empty($color)) {
2061
                $event['borderColor'] = $event['backgroundColor'] = $color;
2062
            }
2063
2064
            if ($row->getColor()) {
2065
                $event['borderColor'] = $event['backgroundColor'] = $row->getColor();
2066
            }
2067
2068
            $event['editable'] = false;
2069
            if ($this->getIsAllowedToEdit() && 'course' === $this->type) {
2070
                $event['editable'] = true;
2071
                if (!empty($sessionId)) {
2072
                    if (false == $coachCanEdit) {
2073
                        $event['editable'] = false;
2074
                    }
2075
                    if ($isAllowToEditByHrm) {
2076
                        $event['editable'] = true;
2077
                    }
2078
                }
2079
                // if user is author then he can edit the item
2080
                if (api_get_user_id() == $row->getResourceNode()->getCreator()->getId()) {
2081
                    $event['editable'] = true;
2082
                }
2083
            }
2084
2085
            if (!empty($row->getStartDate())) {
2086
                $event['start'] = $this->formatEventDate($row->getStartDate()->format('Y-m-d H:i:s'));
2087
                $event['start_date_localtime'] = api_get_local_time($row->getStartDate()->format('Y-m-d H:i:s'));
2088
            }
2089
            if (!empty($row->getEndDate())) {
2090
                $event['end'] = $this->formatEventDate($row->getEndDate()->format('Y-m-d H:i:s'));
2091
                $event['end_date_localtime'] = api_get_local_time($row->getEndDate()->format('Y-m-d H:i:s'));
2092
            }
2093
2094
            $event['sent_to'] = '';
2095
            $event['type'] = 'course';
2096
            if (0 != $row->getSessionId()) {
2097
                $event['type'] = 'session';
2098
            }
2099
2100
            $everyone = false;
2101
            $links = $row->getResourceNode()->getResourceLinks();
2102
            $sentTo = [];
2103
            foreach ($links as $link) {
2104
                if ($link->getUser()) {
2105
                    $sentTo[] = $link->getUser()->getFirstname();
2106
                }
2107
                if ($link->getCourse()) {
2108
                    $sentTo[] = $link->getCourse()->getName();
2109
                }
2110
                if ($link->getSession()) {
2111
                    $sentTo[] = $link->getSession()->getName();
2112
                }
2113
                if ($link->getGroup()) {
2114
                    $sentTo[] = $link->getGroup()->getName();
2115
                }
2116
            }
2117
2118
            // Event Sent to a group?
2119
            /*if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
2120
                $sent_to = [];
2121
                if (!empty($group_to_array)) {
2122
                    foreach ($group_to_array as $group_item) {
2123
                        $sent_to[] = $groupNameList[$group_item];
2124
                    }
2125
                }
2126
                $sent_to = implode('@@', $sent_to);
2127
                $sent_to = str_replace(
2128
                    '@@',
2129
                    '</div><div class="label_tag notice">',
2130
                    $sent_to
2131
                );
2132
                $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
2133
                $event['type'] = 'group';
2134
            }*/
2135
2136
            // Event sent to a user?
2137
            /*if (isset($row['to_user_id'])) {
2138
                $sent_to = [];
2139
                if (!empty($user_to_array)) {
2140
                    foreach ($user_to_array as $item) {
2141
                        $user_info = api_get_user_info($item);
2142
                        // Add username as tooltip for $event['sent_to'] - ref #4226
2143
                        $username = api_htmlentities(
2144
                            sprintf(
2145
                                get_lang('Login: %s'),
2146
                                $user_info['username']
2147
                            ),
2148
                            ENT_QUOTES
2149
                        );
2150
                        $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
2151
                    }
2152
                }
2153
                $sent_to = implode('@@', $sent_to);
2154
                $sent_to = str_replace(
2155
                    '@@',
2156
                    '</div><div class="label_tag notice">',
2157
                    $sent_to
2158
                );
2159
                $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
2160
            }*/
2161
2162
            //Event sent to everyone!
2163
            /*if (empty($event['sent_to'])) {
2164
                $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
2165
            }*/
2166
            $event['sent_to'] = implode('<br />', $sentTo);
2167
            $event['description'] = $row->getContent();
2168
            $event['visibility'] = $row->isVisible($courseEntity, $session) ? 1 : 0;
2169
            $event['real_id'] = $eventId;
2170
            $event['allDay'] = $row->getAllDay();
2171
            $event['parent_event_id'] = $row->getParentEventId();
2172
            $event['has_children'] = $this->hasChildren($eventId, $courseId) ? 1 : 0;
2173
            $event['comment'] = $row->getComment();
2174
            $this->events[] = $event;
2175
        }
2176
2177
        return $this->events;
2178
    }
2179
2180
    /**
2181
     * @param int $start tms
2182
     * @param int $end   tms
2183
     *
2184
     * @return array
2185
     */
2186
    public function getPlatformEvents($start, $end)
2187
    {
2188
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
2189
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
2190
        $dateCondition = '';
2191
2192
        if (!empty($start) && !empty($end)) {
2193
            $dateCondition .= "AND (
2194
                 start_date BETWEEN '".$start."' AND '".$end."' OR
2195
                 end_date BETWEEN '".$start."' AND '".$end."' OR
2196
                 (
2197
                     start_date IS NOT NULL AND end_date IS NOT NULL AND
2198
                     YEAR(start_date) = YEAR(end_date) AND
2199
                     MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
2200
                 )
2201
            )";
2202
        }
2203
2204
        $access_url_id = api_get_current_access_url_id();
2205
2206
        $sql = "SELECT *
2207
                FROM ".$this->tbl_global_agenda."
2208
                WHERE access_url_id = $access_url_id
2209
                $dateCondition";
2210
        $result = Database::query($sql);
2211
        $my_events = [];
2212
        if (Database::num_rows($result)) {
2213
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2214
                $event = [];
2215
                $event['id'] = 'platform_'.$row['id'];
2216
                $event['title'] = $row['title'];
2217
                $event['className'] = 'platform';
2218
                $event['allDay'] = 'false';
2219
                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
2220
                $event['editable'] = false;
2221
                $event['type'] = 'admin';
2222
2223
                if (api_is_platform_admin() && 'admin' === $this->type) {
2224
                    $event['editable'] = true;
2225
                }
2226
2227
                if (!empty($row['start_date'])) {
2228
                    $event['start'] = $this->formatEventDate($row['start_date']);
2229
                    $event['start_date_localtime'] = api_get_local_time($row['start_date']);
2230
                }
2231
2232
                if (!empty($row['end_date'])) {
2233
                    $event['end'] = $this->formatEventDate($row['end_date']);
2234
                    $event['end_date_localtime'] = api_get_local_time($row['end_date']);
2235
                }
2236
                $event['allDay'] = isset($row['all_day']) && 1 == $row['all_day'] ? $row['all_day'] : 0;
2237
                $event['parent_event_id'] = 0;
2238
                $event['has_children'] = 0;
2239
                $event['description'] = $row['content'];
2240
2241
                $my_events[] = $event;
2242
                $this->events[] = $event;
2243
            }
2244
        }
2245
2246
        return $my_events;
2247
    }
2248
2249
    /**
2250
     * @param CGroup[] $groupList
2251
     * @param array    $userList
2252
     * @param array    $sendTo               array('users' => [1, 2], 'groups' => [3, 4])
2253
     * @param array    $attributes
2254
     * @param bool     $addOnlyItemsInSendTo
2255
     * @param bool     $required
2256
     */
2257
    public function setSendToSelect(
2258
        FormValidator $form,
2259
        $groupList = [],
2260
        $userList = [],
2261
        $sendTo = [],
2262
        $attributes = [],
2263
        $addOnlyItemsInSendTo = false,
2264
        $required = false
2265
    ) {
2266
        $params = [
2267
            'id' => 'users_to_send_id',
2268
            'data-placeholder' => get_lang('Select'),
2269
            'multiple' => 'multiple',
2270
            'class' => 'multiple-select',
2271
        ];
2272
2273
        if (!empty($attributes)) {
2274
            $params = array_merge($params, $attributes);
2275
            if (empty($params['multiple'])) {
2276
                unset($params['multiple']);
2277
            }
2278
        }
2279
2280
        $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : [];
2281
        $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : [];
2282
2283
        /** @var HTML_QuickForm_select $select */
2284
        $select = $form->addSelect(
2285
            'users_to_send',
2286
            get_lang('To'),
2287
            null,
2288
            $params
2289
        );
2290
2291
        if ($required) {
2292
            $form->setRequired($select);
2293
        }
2294
2295
        $selectedEveryoneOptions = [];
2296
        if (isset($sendTo['everyone']) && $sendTo['everyone']) {
2297
            $selectedEveryoneOptions = ['selected'];
2298
            $sendToUsers = [];
2299
        }
2300
2301
        $select->addOption(
2302
            get_lang('Everyone'),
2303
            'everyone',
2304
            $selectedEveryoneOptions
2305
        );
2306
2307
        $options = [];
2308
        if (is_array($groupList)) {
2309
            foreach ($groupList as $group) {
2310
                $groupId = $group->getIid();
2311
                $count = $group->getMembers()->count();
2312
                $countUsers = " &ndash; $count ".get_lang('Users');
2313
                $option = [
2314
                    'text' => $group->getName().$countUsers,
2315
                    'value' => "GROUP:".$groupId,
2316
                ];
2317
2318
                $selected = in_array(
2319
                    $groupId,
2320
                    $sendToGroups
2321
                ) ? true : false;
2322
                if ($selected) {
2323
                    $option['selected'] = 'selected';
2324
                }
2325
2326
                if ($addOnlyItemsInSendTo) {
2327
                    if ($selected) {
2328
                        $options[] = $option;
2329
                    }
2330
                } else {
2331
                    $options[] = $option;
2332
                }
2333
            }
2334
            $select->addOptGroup($options, get_lang('Groups'));
2335
        }
2336
2337
        // adding the individual users to the select form
2338
        if (is_array($userList)) {
2339
            $options = [];
2340
            foreach ($userList as $user) {
2341
                if (ANONYMOUS == $user['status']) {
2342
                    continue;
2343
                }
2344
                $option = [
2345
                    'text' => api_get_person_name(
2346
                            $user['firstname'],
2347
                            $user['lastname']
2348
                        ).' ('.$user['username'].')',
2349
                    'value' => "USER:".$user['user_id'],
2350
                ];
2351
2352
                $selected = in_array(
2353
                    $user['user_id'],
2354
                    $sendToUsers
2355
                ) ? true : false;
2356
2357
                if ($selected) {
2358
                    $option['selected'] = 'selected';
2359
                }
2360
2361
                if ($addOnlyItemsInSendTo) {
2362
                    if ($selected) {
2363
                        $options[] = $option;
2364
                    }
2365
                } else {
2366
                    $options[] = $option;
2367
                }
2368
            }
2369
2370
            $select->addOptGroup($options, get_lang('Users'));
2371
        }
2372
    }
2373
2374
    /**
2375
     * Separates the users and groups array
2376
     * users have a value USER:XXX (with XXX the user id
2377
     * groups have a value GROUP:YYY (with YYY the group id)
2378
     * use the 'everyone' key.
2379
     *
2380
     * @author Julio Montoya based in separate_users_groups in agenda.inc.php
2381
     *
2382
     * @param array $to
2383
     *
2384
     * @return array
2385
     */
2386
    public function parseSendToArray($to)
2387
    {
2388
        $groupList = [];
2389
        $userList = [];
2390
        $sendTo = null;
2391
2392
        $sendTo['everyone'] = false;
2393
        if (is_array($to) && count($to) > 0) {
2394
            foreach ($to as $item) {
2395
                if ('everyone' == $item) {
2396
                    $sendTo['everyone'] = true;
2397
                } else {
2398
                    [$type, $id] = explode(':', $item);
2399
                    switch ($type) {
2400
                        case 'GROUP':
2401
                            $groupList[] = $id;
2402
                            break;
2403
                        case 'USER':
2404
                            $userList[] = $id;
2405
                            break;
2406
                    }
2407
                }
2408
            }
2409
            $sendTo['groups'] = $groupList;
2410
            $sendTo['users'] = $userList;
2411
        }
2412
2413
        return $sendTo;
2414
    }
2415
2416
    /**
2417
     * @param array $params
2418
     *
2419
     * @return FormValidator
2420
     */
2421
    public function getForm($params = [])
2422
    {
2423
        $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
2424
        $id = isset($params['id']) ? (int) $params['id'] : 0;
2425
2426
        $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
2427
        if ('course' == $this->type) {
2428
            $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
2429
        }
2430
2431
        $form = new FormValidator(
2432
            'add_event',
2433
            'post',
2434
            $url,
2435
            null,
2436
            ['enctype' => 'multipart/form-data']
2437
        );
2438
2439
        $idAttach = isset($params['id_attach']) ? (int) $params['id_attach'] : null;
2440
        $groupId = api_get_group_id();
2441
        $form_Title = get_lang('Add event to agenda');
2442
        if (!empty($id)) {
2443
            $form_Title = get_lang('Edit event');
2444
        }
2445
2446
        $form->addHeader($form_Title);
2447
        $form->addElement('hidden', 'id', $id);
2448
        $form->addElement('hidden', 'action', $action);
2449
        $form->addElement('hidden', 'id_attach', $idAttach);
2450
2451
        $isSubEventEdition = false;
2452
        $isParentFromSerie = false;
2453
        $showAttachmentForm = true;
2454
2455
        if ('course' == $this->type) {
2456
            // Edition mode.
2457
            if (!empty($id)) {
2458
                $showAttachmentForm = false;
2459
                if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
2460
                    $isSubEventEdition = true;
2461
                }
2462
                if (!empty($params['repeat_info'])) {
2463
                    $isParentFromSerie = true;
2464
                }
2465
            }
2466
        }
2467
2468
        if ($isSubEventEdition) {
2469
            $form->addElement(
2470
                'label',
2471
                null,
2472
                Display::return_message(
2473
                    get_lang('Editing this event will remove it from the serie of events it is currently part of'),
2474
                    'warning'
2475
                )
2476
            );
2477
        }
2478
2479
        $form->addElement('text', 'title', get_lang('Event name'));
2480
2481
        if (isset($groupId) && !empty($groupId)) {
2482
            $form->addElement(
2483
                'hidden',
2484
                'users_to_send[]',
2485
                "GROUP:$groupId"
2486
            );
2487
            $form->addElement('hidden', 'to', 'true');
2488
        } else {
2489
            $sendTo = isset($params['send_to']) ? $params['send_to'] : ['everyone' => true];
2490
            if ('course' == $this->type) {
2491
                $this->showToForm($form, $sendTo, [], false, true);
2492
            }
2493
        }
2494
2495
        $form->addDateRangePicker(
2496
            'date_range',
2497
            get_lang('Date range'),
2498
            false,
2499
            ['id' => 'date_range']
2500
        );
2501
        $form->addElement('checkbox', 'all_day', null, get_lang('All day'));
2502
2503
        if ('course' == $this->type) {
2504
            $repeat = $form->addElement(
2505
                'checkbox',
2506
                'repeat',
2507
                null,
2508
                get_lang('Repeat event'),
2509
                ['onclick' => 'return plus_repeated_event();']
2510
            );
2511
            $form->addElement(
2512
                'html',
2513
                '<div id="options2" style="display:none">'
2514
            );
2515
            $form->addElement(
2516
                'select',
2517
                'repeat_type',
2518
                get_lang('Repeat type'),
2519
                self::getRepeatTypes()
2520
            );
2521
            $form->addElement(
2522
                'date_picker',
2523
                'repeat_end_day',
2524
                get_lang('Repeat end date'),
2525
                ['id' => 'repeat_end_date_form']
2526
            );
2527
2528
            if ($isSubEventEdition || $isParentFromSerie) {
2529
                $repeatInfo = $params['repeat_info'];
2530
                if ($isSubEventEdition) {
2531
                    $parentEvent = $params['parent_info'];
2532
                    $repeatInfo = $parentEvent['repeat_info'];
2533
                }
2534
                $params['repeat'] = 1;
2535
                $params['repeat_type'] = $repeatInfo['cal_type'];
2536
                $params['repeat_end_day'] = substr(
2537
                    api_get_local_time($repeatInfo['cal_end']),
2538
                    0,
2539
                    10
2540
                );
2541
2542
                $form->freeze(['repeat_type', 'repeat_end_day']);
2543
                $repeat->_attributes['disabled'] = 'disabled';
2544
            }
2545
            $form->addElement('html', '</div>');
2546
        }
2547
2548
        if (!empty($id)) {
2549
            if (empty($params['end_date'])) {
2550
                $params['date_range'] = $params['end_date'];
2551
            }
2552
2553
            $params['date_range'] =
2554
                substr(api_get_local_time($params['start_date']), 0, 16).' / '.
2555
                substr(api_get_local_time($params['end_date']), 0, 16);
2556
        }
2557
2558
        $toolbar = 'Agenda';
2559
        if (!api_is_allowed_to_edit(null, true)) {
2560
            $toolbar = 'AgendaStudent';
2561
        }
2562
2563
        $form->addElement(
2564
            'html_editor',
2565
            'content',
2566
            get_lang('Description'),
2567
            null,
2568
            [
2569
                'ToolbarSet' => $toolbar,
2570
                'Width' => '100%',
2571
                'Height' => '200',
2572
            ]
2573
        );
2574
2575
        if ('course' == $this->type) {
2576
            $form->addElement('textarea', 'comment', get_lang('Comment'));
2577
            $form->addLabel(
2578
                get_lang('Files attachments'),
2579
                '<div id="filepaths" class="file-upload-event">
2580
2581
                        <div id="filepath_1">
2582
                            <input type="file" name="attach_1"/>
2583
2584
                            <label>'.get_lang('Description').'</label>
2585
                            <input class="form-control" type="text" name="legend[]" />
2586
                        </div>
2587
2588
                    </div>'
2589
            );
2590
2591
            $form->addLabel(
2592
                '',
2593
                '<span id="link-more-attach">
2594
                    <a href="javascript://" onclick="return add_image_form()">'.
2595
                get_lang('Add one more file').'</a>
2596
                 </span>&nbsp;('.sprintf(
2597
                    get_lang('Maximun file size: %s'),
2598
                    format_file_size(
2599
                        api_get_setting('message_max_upload_filesize')
2600
                    )
2601
                ).')'
2602
            );
2603
2604
            if (isset($params['attachment']) && !empty($params['attachment'])) {
2605
                $attachmentList = $params['attachment'];
2606
                foreach ($attachmentList as $attachment) {
2607
                    $params['file_comment'] = $attachment['comment'];
2608
                    if (!empty($attachment['path'])) {
2609
                        $form->addElement(
2610
                            'checkbox',
2611
                            'delete_attachment['.$attachment['id'].']',
2612
                            null,
2613
                            get_lang(
2614
                                'DeleteAttachment'
2615
                            ).': '.$attachment['filename']
2616
                        );
2617
                    }
2618
                }
2619
            }
2620
2621
            $form->addElement(
2622
                'textarea',
2623
                'file_comment',
2624
                get_lang('File comment')
2625
            );
2626
        }
2627
2628
        if (empty($id)) {
2629
            $form->addElement(
2630
                'checkbox',
2631
                'add_announcement',
2632
                null,
2633
                get_lang('Add an announcement').'&nbsp('.get_lang('Send mail').')'
2634
            );
2635
        }
2636
2637
        if ($id) {
2638
            $form->addButtonUpdate(get_lang('Edit event'));
2639
        } else {
2640
            $form->addButtonSave(get_lang('Add event'));
2641
        }
2642
2643
        $form->setDefaults($params);
2644
        $form->addRule(
2645
            'date_range',
2646
            get_lang('Required field'),
2647
            'required'
2648
        );
2649
        $form->addRule('title', get_lang('Required field'), 'required');
2650
2651
        return $form;
2652
    }
2653
2654
    /**
2655
     * @param FormValidator $form
2656
     * @param array         $sendTo               array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
2657
     * @param array         $attributes
2658
     * @param bool          $addOnlyItemsInSendTo
2659
     * @param bool          $required
2660
     *
2661
     * @return bool
2662
     */
2663
    public function showToForm(
2664
        $form,
2665
        $sendTo = [],
2666
        $attributes = [],
2667
        $addOnlyItemsInSendTo = false,
2668
        $required = false
2669
    ) {
2670
        if ('course' != $this->type) {
2671
            return false;
2672
        }
2673
2674
        $order = 'lastname';
2675
        if (api_is_western_name_order()) {
2676
            $order = 'firstname';
2677
        }
2678
2679
        $userList = CourseManager::get_user_list_from_course_code(
2680
            api_get_course_id(),
2681
            $this->sessionId,
2682
            null,
2683
            $order
2684
        );
2685
2686
        $groupList = CourseManager::get_group_list_of_course(
2687
            api_get_course_id(),
2688
            $this->sessionId
2689
        );
2690
2691
        $this->setSendToSelect(
2692
            $form,
2693
            $groupList,
2694
            $userList,
2695
            $sendTo,
2696
            $attributes,
2697
            $addOnlyItemsInSendTo,
2698
            $required
2699
        );
2700
2701
        return true;
2702
    }
2703
2704
    /**
2705
     * @param int   $id
2706
     * @param int   $visibility 0= invisible, 1 visible
2707
     * @param array $courseInfo
2708
     * @param int   $userId
2709
     */
2710
    public static function changeVisibility(
2711
        $id,
2712
        $visibility,
2713
        $courseInfo,
2714
        $userId = null
2715
    ) {
2716
        $id = (int) $id;
2717
2718
        $repo = Container::getCalendarEventRepository();
2719
        /** @var CCalendarEvent $event */
2720
        $event = $repo->find($id);
2721
        $visibility = (int) $visibility;
2722
2723
        if ($event) {
2724
            if (0 === $visibility) {
2725
                $repo->setVisibilityDraft($event);
2726
            } else {
2727
                $repo->setVisibilityPublished($event);
2728
            }
2729
        }
2730
2731
        return true;
2732
2733
        if (empty($userId)) {
0 ignored issues
show
Unused Code introduced by
IfNode is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
2734
            $userId = api_get_user_id();
2735
        } else {
2736
            $userId = (int) $userId;
2737
        }
2738
2739
        if (0 === $visibility) {
2740
            api_item_property_update(
2741
                $courseInfo,
2742
                TOOL_CALENDAR_EVENT,
2743
                $id,
2744
                'invisible',
2745
                $userId
2746
            );
2747
        } else {
2748
            api_item_property_update(
2749
                $courseInfo,
2750
                TOOL_CALENDAR_EVENT,
2751
                $id,
2752
                'visible',
2753
                $userId
2754
            );
2755
        }
2756
    }
2757
2758
    /**
2759
     * Get repeat types.
2760
     */
2761
    public static function getRepeatTypes(): array
2762
    {
2763
        return [
2764
            'daily' => get_lang('Daily'),
2765
            'weekly' => get_lang('Weekly'),
2766
            'monthlyByDate' => get_lang('Monthly, by date'),
2767
            //monthlyByDay"> get_lang('Monthly, by day');
2768
            //monthlyByDayR' => get_lang('Monthly, by dayR'),
2769
            'yearly' => get_lang('Yearly'),
2770
        ];
2771
    }
2772
2773
    /**
2774
     * Show a list with all the attachments according to the post's id.
2775
     *
2776
     * @param int   $eventId
2777
     * @param array $courseInfo
2778
     *
2779
     * @return array with the post info
2780
     */
2781
    public function getAttachmentList($eventId, $courseInfo)
2782
    {
2783
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2784
        $courseId = (int) $courseInfo['real_id'];
2785
        $eventId = (int) $eventId;
2786
2787
        $sql = "SELECT id, path, filename, comment
2788
                FROM $tableAttachment
2789
                WHERE
2790
                    c_id = $courseId AND
2791
                    agenda_id = $eventId";
2792
        $result = Database::query($sql);
2793
        $list = [];
2794
        if (0 != Database::num_rows($result)) {
2795
            $list = Database::store_result($result, 'ASSOC');
2796
        }
2797
2798
        return $list;
2799
    }
2800
2801
    /**
2802
     * Show a list with all the attachments according to the post's id.
2803
     *
2804
     * @param int   $attachmentId
2805
     * @param int   $eventId
2806
     * @param array $courseInfo
2807
     *
2808
     * @return array with the post info
2809
     */
2810
    public function getAttachment($attachmentId, $eventId, $courseInfo)
2811
    {
2812
        if (empty($courseInfo) || empty($attachmentId) || empty($eventId)) {
2813
            return [];
2814
        }
2815
2816
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2817
        $courseId = (int) $courseInfo['real_id'];
2818
        $eventId = (int) $eventId;
2819
        $attachmentId = (int) $attachmentId;
2820
2821
        $row = [];
2822
        $sql = "SELECT id, path, filename, comment
2823
                FROM $tableAttachment
2824
                WHERE
2825
                    c_id = $courseId AND
2826
                    agenda_id = $eventId AND
2827
                    id = $attachmentId
2828
                ";
2829
        $result = Database::query($sql);
2830
        if (0 != Database::num_rows($result)) {
2831
            $row = Database::fetch_array($result, 'ASSOC');
2832
        }
2833
2834
        return $row;
2835
    }
2836
2837
    /**
2838
     * Add an attachment file into agenda.
2839
     *
2840
     * @param CCalendarEvent $event
2841
     * @param UploadedFile   $file
2842
     * @param string         $comment
2843
     * @param array          $courseInfo
2844
     *
2845
     * @return string
2846
     */
2847
    public function addAttachment(
2848
        $event,
2849
        $file,
2850
        $comment,
2851
        $courseInfo
2852
    ) {
2853
        // Storing the attachments
2854
        $valid = false;
2855
        if ($file) {
2856
            $valid = process_uploaded_file($file);
2857
        }
2858
2859
        if ($valid) {
2860
            /*$courseDir = $courseInfo['directory'].'/upload/calendar';
2861
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2862
            $uploadDir = $sys_course_path.$courseDir;*/
2863
2864
            // Try to add an extension to the file if it hasn't one
2865
            /*$new_file_name = add_ext_on_mime(
2866
                stripslashes($fileUserUpload['name']),
2867
                $fileUserUpload['type']
2868
            );*/
2869
2870
            // user's file name
2871
            $fileName = $file->getClientOriginalName();
2872
            $courseId = api_get_course_int_id();
2873
            /*$new_file_name = uniqid('');
2874
            $new_path = $uploadDir.'/'.$new_file_name;
2875
            $result = @move_uploaded_file(
2876
                $fileUserUpload['tmp_name'],
2877
                $new_path
2878
            );
2879
            $courseId = api_get_course_int_id();
2880
            $size = intval($fileUserUpload['size']);*/
2881
            // Storing the attachments if any
2882
            //if ($result) {
2883
            $attachment = new CCalendarEventAttachment();
2884
            $attachment
2885
                ->setCId($courseId)
2886
                ->setFilename($fileName)
2887
                ->setComment($comment)
2888
                ->setPath($fileName)
2889
                ->setEvent($event)
2890
                ->setSize($file->getSize())
2891
                ->setParent($event)
2892
                ->addCourseLink(
2893
                    api_get_course_entity(),
2894
                    api_get_session_entity(),
2895
                    api_get_group_entity()
2896
                );
2897
2898
            $repo = Container::getCalendarEventAttachmentRepository();
2899
            $repo->getEntityManager()->persist($attachment);
2900
            $repo->getEntityManager()->flush();
2901
2902
            $id = $attachment->getIid();
2903
            if ($id) {
2904
                /*api_item_property_update(
2905
                    $courseInfo,
2906
                    'calendar_event_attachment',
2907
                    $id,
2908
                    'AgendaAttachmentAdded',
2909
                    api_get_user_id()
2910
                );*/
2911
            }
2912
        }
2913
    }
2914
2915
    /**
2916
     * @param int    $attachmentId
2917
     * @param int    $eventId
2918
     * @param array  $fileUserUpload
2919
     * @param string $comment
2920
     * @param array  $courseInfo
2921
     */
2922
    public function updateAttachment(
2923
        $attachmentId,
2924
        $eventId,
2925
        $fileUserUpload,
2926
        $comment,
2927
        $courseInfo
2928
    ) {
2929
        $attachment = $this->getAttachment(
2930
            $attachmentId,
2931
            $eventId,
2932
            $courseInfo
2933
        );
2934
        if (!empty($attachment)) {
2935
            $this->deleteAttachmentFile($attachmentId);
2936
        }
2937
        $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
2938
    }
2939
2940
    /**
2941
     * This function delete a attachment file by id.
2942
     *
2943
     * @param int   $attachmentId
2944
     *
2945
     * @return string
2946
     */
2947
    public function deleteAttachmentFile($attachmentId)
2948
    {
2949
        $repo = Container::getCalendarEventAttachmentRepository();
2950
        /** @var CCalendarEventAttachment $attachment */
2951
        $attachment = $repo->find($attachmentId);
2952
2953
        if (empty($attachment)) {
2954
            return false;
2955
        }
2956
2957
        $repo->getEntityManager()->remove($attachment);
2958
        $repo->getEntityManager()->flush();
2959
2960
        return Display::return_message(
2961
            get_lang("The attached file has been deleted"),
2962
            'confirmation'
2963
        );
2964
    }
2965
2966
    /**
2967
     * @param int $eventId
2968
     *
2969
     * @return array
2970
     */
2971
    public function getAllRepeatEvents($eventId)
2972
    {
2973
        $events = [];
2974
        $eventId = (int) $eventId;
2975
2976
        switch ($this->type) {
2977
            case 'personal':
2978
                break;
2979
            case 'course':
2980
                if (!empty($this->course['real_id'])) {
2981
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
2982
                            WHERE
2983
                                c_id = ".$this->course['real_id']." AND
2984
                                parent_event_id = ".$eventId;
2985
                    $result = Database::query($sql);
2986
                    if (Database::num_rows($result)) {
2987
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
2988
                            $events[] = $row;
2989
                        }
2990
                    }
2991
                }
2992
                break;
2993
        }
2994
2995
        return $events;
2996
    }
2997
2998
    /**
2999
     * @param int $eventId
3000
     * @param int $courseId
3001
     *
3002
     * @return bool
3003
     */
3004
    public function hasChildren($eventId, $courseId)
3005
    {
3006
        $eventId = (int) $eventId;
3007
        $courseId = (int) $courseId;
3008
3009
        $sql = "SELECT count(DISTINCT(iid)) as count
3010
                FROM ".$this->tbl_course_agenda."
3011
                WHERE
3012
                    c_id = $courseId AND
3013
                    parent_event_id = $eventId";
3014
        $result = Database::query($sql);
3015
        if (Database::num_rows($result)) {
3016
            $row = Database::fetch_array($result, 'ASSOC');
3017
3018
            return $row['count'] > 0;
3019
        }
3020
3021
        return false;
3022
    }
3023
3024
    /**
3025
     * @param int    $filter
3026
     * @param string $view
3027
     *
3028
     * @return string
3029
     */
3030
    public function displayActions($view, $filter = 0)
3031
    {
3032
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
3033
        $groupIid = isset($groupInfo['iid']) ? $groupInfo['iid'] : 0;
3034
3035
        $codePath = api_get_path(WEB_CODE_PATH);
3036
3037
        $currentUserId = api_get_user_id();
3038
        $cidReq = api_get_cidreq();
3039
3040
        $actionsLeft = '';
3041
        $actionsLeft .= Display::url(
3042
            Display::return_icon('calendar.png', get_lang('Calendar'), [], ICON_SIZE_MEDIUM),
3043
            $codePath."calendar/agenda_js.php?type={$this->type}&$cidReq"
3044
        );
3045
        $actionsLeft .= Display::url(
3046
            Display::return_icon('week.png', get_lang('Agenda list'), [], ICON_SIZE_MEDIUM),
3047
            $codePath."calendar/agenda_list.php?type={$this->type}&$cidReq"
3048
        );
3049
3050
        $form = '';
3051
        if (api_is_allowed_to_edit(false, true) ||
3052
            ('1' == api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) &&
3053
            api_is_allowed_to_session_edit(false, true)
3054
            || (
3055
                GroupManager::user_has_access($currentUserId, $groupIid, GroupManager::GROUP_TOOL_CALENDAR)
3056
                && GroupManager::is_tutor_of_group($currentUserId, $groupInfo)
3057
            )
3058
        ) {
3059
            $actionsLeft .= Display::url(
3060
                Display::return_icon('new_event.png', get_lang('Add event'), [], ICON_SIZE_MEDIUM),
3061
                $codePath."calendar/agenda.php?action=add&type={$this->type}&$cidReq"
3062
            );
3063
3064
            $actionsLeft .= Display::url(
3065
                Display::return_icon('import_calendar.png', get_lang('Outlook import'), [], ICON_SIZE_MEDIUM),
3066
                $codePath."calendar/agenda.php?action=importical&type={$this->type}&$cidReq"
3067
            );
3068
3069
            if ('course' === $this->type) {
3070
                if (!isset($_GET['action'])) {
3071
                    $form = new FormValidator(
3072
                        'form-search',
3073
                        'post',
3074
                        '',
3075
                        '',
3076
                        [],
3077
                        FormValidator::LAYOUT_INLINE
3078
                    );
3079
                    $attributes = [
3080
                        'multiple' => false,
3081
                        'id' => 'select_form_id_search',
3082
                    ];
3083
                    $selectedValues = $this->parseAgendaFilter($filter);
3084
                    $this->showToForm($form, $selectedValues, $attributes);
3085
                    $form = $form->returnForm();
3086
                }
3087
            }
3088
        }
3089
3090
        if ('personal' == $this->type && !api_is_anonymous()) {
3091
            $actionsLeft .= Display::url(
3092
                Display::return_icon('1day.png', get_lang('Sessions plan calendar'), [], ICON_SIZE_MEDIUM),
3093
                $codePath."calendar/planification.php"
3094
            );
3095
3096
            if (api_is_student_boss() || api_is_platform_admin()) {
3097
                $actionsLeft .= Display::url(
3098
                    Display::return_icon('calendar-user.png', get_lang('MyStudentsSchedule'), [], ICON_SIZE_MEDIUM),
3099
                    $codePath.'mySpace/calendar_plan.php'
3100
                );
3101
            }
3102
        }
3103
3104
        if (api_is_platform_admin() ||
3105
            api_is_teacher() ||
3106
            api_is_student_boss() ||
3107
            api_is_drh() ||
3108
            api_is_session_admin() ||
3109
            api_is_coach()
3110
        ) {
3111
            if ('personal' == $this->type) {
3112
                $form = null;
3113
                if (!isset($_GET['action'])) {
3114
                    $form = new FormValidator(
3115
                        'form-search',
3116
                        'get',
3117
                        api_get_self().'?type=personal&',
3118
                        '',
3119
                        [],
3120
                        FormValidator::LAYOUT_INLINE
3121
                    );
3122
3123
                    $sessions = [];
3124
3125
                    if (api_is_drh()) {
3126
                        $sessionList = SessionManager::get_sessions_followed_by_drh($currentUserId);
3127
                        if (!empty($sessionList)) {
3128
                            foreach ($sessionList as $sessionItem) {
3129
                                $sessions[$sessionItem['id']] = strip_tags($sessionItem['name']);
3130
                            }
3131
                        }
3132
                    } else {
3133
                        $sessions = SessionManager::get_sessions_by_user($currentUserId);
3134
                        $sessions = array_column($sessions, 'session_name', 'session_id');
3135
                    }
3136
3137
                    $form->addHidden('type', 'personal');
3138
                    $sessions = ['0' => get_lang('Please select an option')] + $sessions;
3139
3140
                    $form->addSelect(
3141
                        'session_id',
3142
                        get_lang('Session'),
3143
                        $sessions,
3144
                        ['id' => 'session_id', 'onchange' => 'submit();']
3145
                    );
3146
3147
                    $form->addButtonReset(get_lang('Reset'));
3148
                    $form = $form->returnForm();
3149
                }
3150
            }
3151
        }
3152
3153
        $actionsRight = '';
3154
        if ('calendar' == $view) {
3155
            $actionsRight .= $form;
3156
        }
3157
3158
        $toolbar = Display::toolbarAction(
3159
            'toolbar-agenda',
3160
            [$actionsLeft, $actionsRight]
3161
        );
3162
3163
        return $toolbar;
3164
    }
3165
3166
    /**
3167
     * @return FormValidator
3168
     */
3169
    public function getImportCalendarForm()
3170
    {
3171
        $form = new FormValidator(
3172
            'frm_import_ical',
3173
            'post',
3174
            api_get_self().'?action=importical&type='.$this->type,
3175
            ['enctype' => 'multipart/form-data']
3176
        );
3177
        $form->addHeader(get_lang('Outlook import'));
3178
        $form->addElement('file', 'ical_import', get_lang('Outlook import'));
3179
        $form->addRule(
3180
            'ical_import',
3181
            get_lang('Required field'),
3182
            'required'
3183
        );
3184
        $form->addButtonImport(get_lang('Import'), 'ical_submit');
3185
3186
        return $form;
3187
    }
3188
3189
    /**
3190
     * @param array $courseInfo
3191
     * @param $file
3192
     *
3193
     * @return false|string
3194
     */
3195
    public function importEventFile($courseInfo, $file)
3196
    {
3197
        $charset = api_get_system_encoding();
3198
        $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
3199
        $messages = [];
3200
3201
        if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
3202
            error_log(
3203
                'Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__
3204
            );
3205
3206
            return false;
3207
        }
3208
3209
        $data = file_get_contents($filepath);
3210
3211
        $trans = [
3212
            'DAILY' => 'daily',
3213
            'WEEKLY' => 'weekly',
3214
            'MONTHLY' => 'monthlyByDate',
3215
            'YEARLY' => 'yearly',
3216
        ];
3217
        $sentTo = ['everyone' => true];
3218
        $calendar = Sabre\VObject\Reader::read($data);
3219
        $currentTimeZone = api_get_timezone();
3220
        if (!empty($calendar->VEVENT)) {
3221
            foreach ($calendar->VEVENT as $event) {
3222
                $start = $event->DTSTART->getDateTime();
3223
                $end = $event->DTEND->getDateTime();
3224
                //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
3225
3226
                $startDateTime = api_get_local_time(
3227
                    $start->format('Y-m-d H:i:s'),
3228
                    $currentTimeZone,
3229
                    $start->format('e')
3230
                );
3231
                $endDateTime = api_get_local_time(
3232
                    $end->format('Y-m-d H:i'),
3233
                    $currentTimeZone,
3234
                    $end->format('e')
3235
                );
3236
                $title = api_convert_encoding(
3237
                    (string) $event->summary,
3238
                    $charset,
3239
                    'UTF-8'
3240
                );
3241
                $description = api_convert_encoding(
3242
                    (string) $event->description,
3243
                    $charset,
3244
                    'UTF-8'
3245
                );
3246
3247
                $id = $this->addEvent(
3248
                    $startDateTime,
3249
                    $endDateTime,
3250
                    'false',
3251
                    $title,
3252
                    $description,
3253
                    $sentTo
3254
                );
3255
3256
                $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
3257
3258
                //$attendee = (string)$event->attendee;
3259
                /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
3260
                $repeat = $event->RRULE;
3261
                if ($id && !empty($repeat)) {
3262
                    $repeat = $repeat->getParts();
3263
                    $freq = $trans[$repeat['FREQ']];
3264
3265
                    if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
3266
                        // Check if datetime or just date (strlen == 8)
3267
                        if (8 == strlen($repeat['UNTIL'])) {
3268
                            // Fix the datetime format to avoid exception in the next step
3269
                            $repeat['UNTIL'] .= 'T000000';
3270
                        }
3271
                        $until = Sabre\VObject\DateTimeParser::parseDateTime(
3272
                            $repeat['UNTIL'],
3273
                            new DateTimeZone($currentTimeZone)
3274
                        );
3275
                        $until = $until->format('Y-m-d H:i:s');
3276
                        $this->addRepeatedItem(
3277
                            $id,
3278
                            $freq,
3279
                            $until,
3280
                            $sentTo
3281
                        );
3282
                    }
3283
                }
3284
            }
3285
        }
3286
3287
        if (!empty($messages)) {
3288
            $messages = implode('<br /> ', $messages);
3289
        } else {
3290
            $messages = get_lang('There are no events');
3291
        }
3292
3293
        return $messages;
3294
    }
3295
3296
    /**
3297
     * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]].
3298
     *
3299
     * @param int $filter
3300
     *
3301
     * @return array
3302
     */
3303
    public function parseAgendaFilter($filter)
3304
    {
3305
        $everyone = false;
3306
        $groupId = null;
3307
        $userId = null;
3308
3309
        if ('everyone' === $filter) {
3310
            $everyone = true;
3311
        } else {
3312
            if ('G' === substr($filter, 0, 1)) {
3313
                $groupId = str_replace('GROUP:', '', $filter);
3314
            } else {
3315
                $userId = str_replace('USER:', '', $filter);
3316
            }
3317
        }
3318
        if (empty($userId) && empty($groupId)) {
3319
            $everyone = true;
3320
        }
3321
3322
        return [
3323
            'everyone' => $everyone,
3324
            'users' => [$userId],
3325
            'groups' => [$groupId],
3326
        ];
3327
    }
3328
3329
    /**
3330
     *    This function retrieves all the agenda items of all the courses the user is subscribed to.
3331
     */
3332
    public static function get_myagendaitems(
3333
        $user_id,
3334
        $courses_dbs,
3335
        $month,
3336
        $year
3337
    ) {
3338
        $user_id = (int) $user_id;
3339
3340
        $items = [];
3341
        $my_list = [];
3342
3343
        // get agenda-items for every course
3344
        foreach ($courses_dbs as $key => $array_course_info) {
3345
            //databases of the courses
3346
            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
3347
            $TABLE_ITEMPROPERTY = Database::get_course_table(
3348
                TABLE_ITEM_PROPERTY
3349
            );
3350
3351
            $group_memberships = GroupManager::get_group_ids(
3352
                $array_course_info['real_id'],
3353
                $user_id
3354
            );
3355
            $course_user_status = CourseManager::getUserInCourseStatus(
3356
                $user_id,
3357
                $array_course_info['real_id']
3358
            );
3359
            // if the user is administrator of that course we show all the agenda items
3360
            if ('1' == $course_user_status) {
3361
                //echo "course admin";
3362
                $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3363
							FROM ".$TABLEAGENDA." agenda,
3364
								 ".$TABLE_ITEMPROPERTY." ip
3365
							WHERE agenda.id = ip.ref
3366
							AND MONTH(agenda.start_date)='".$month."'
3367
							AND YEAR(agenda.start_date)='".$year."'
3368
							AND ip.tool='".TOOL_CALENDAR_EVENT."'
3369
							AND ip.visibility='1'
3370
							GROUP BY agenda.id
3371
							ORDER BY start_date ";
3372
            } else {
3373
                // if the user is not an administrator of that course
3374
                if (is_array($group_memberships) && count(
3375
                        $group_memberships
3376
                    ) > 0
3377
                ) {
3378
                    $sqlquery = "SELECT	agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3379
								FROM ".$TABLEAGENDA." agenda,
3380
									".$TABLE_ITEMPROPERTY." ip
3381
								WHERE agenda.id = ip.ref
3382
								AND MONTH(agenda.start_date)='".$month."'
3383
								AND YEAR(agenda.start_date)='".$year."'
3384
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3385
								AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
3386
                            ", ",
3387
                            $group_memberships
3388
                        ).")) )
3389
								AND ip.visibility='1'
3390
								ORDER BY start_date ";
3391
                } else {
3392
                    $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3393
								FROM ".$TABLEAGENDA." agenda,
3394
									".$TABLE_ITEMPROPERTY." ip
3395
								WHERE agenda.id = ip.ref
3396
								AND MONTH(agenda.start_date)='".$month."'
3397
								AND YEAR(agenda.start_date)='".$year."'
3398
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3399
								AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
3400
								AND ip.visibility='1'
3401
								ORDER BY start_date ";
3402
                }
3403
            }
3404
            $result = Database::query($sqlquery);
3405
3406
            while ($item = Database::fetch_array($result, 'ASSOC')) {
3407
                $agendaday = -1;
3408
                if (!empty($item['start_date'])) {
3409
                    $item['start_date'] = api_get_local_time(
3410
                        $item['start_date']
3411
                    );
3412
                    $item['start_date_tms'] = api_strtotime(
3413
                        $item['start_date']
3414
                    );
3415
                    $agendaday = date("j", $item['start_date_tms']);
3416
                }
3417
                if (!empty($item['end_date'])) {
3418
                    $item['end_date'] = api_get_local_time($item['end_date']);
3419
                }
3420
3421
                $url = api_get_path(
3422
                        WEB_CODE_PATH
3423
                    )."calendar/agenda.php?cidReq=".urlencode(
3424
                        $array_course_info["code"]
3425
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
3426
3427
                $item['url'] = $url;
3428
                $item['course_name'] = $array_course_info['title'];
3429
                $item['calendar_type'] = 'course';
3430
                $item['course_id'] = $array_course_info['course_id'];
3431
3432
                $my_list[$agendaday][] = $item;
3433
            }
3434
        }
3435
3436
        // sorting by hour for every day
3437
        $agendaitems = [];
3438
        foreach ($items as $agendaday => $tmpitems) {
3439
            if (!isset($agendaitems[$agendaday])) {
3440
                $agendaitems[$agendaday] = '';
3441
            }
3442
            sort($tmpitems);
3443
            foreach ($tmpitems as $val) {
3444
                $agendaitems[$agendaday] .= $val;
3445
            }
3446
        }
3447
3448
        return $my_list;
3449
    }
3450
3451
    /**
3452
     * This function retrieves one personal agenda item returns it.
3453
     *
3454
     * @param    array    The array containing existing events. We add to this array.
3455
     * @param    int        Day
3456
     * @param    int        Month
3457
     * @param    int        Year (4 digits)
3458
     * @param    int        Week number
3459
     * @param    string    Type of view (month_view, week_view, day_view)
3460
     *
3461
     * @return array The results of the database query, or null if not found
3462
     */
3463
    public static function get_global_agenda_items(
3464
        $agendaitems,
3465
        $day = "",
3466
        $month = "",
3467
        $year = "",
3468
        $week = "",
3469
        $type
3470
    ) {
3471
        $tbl_global_agenda = Database::get_main_table(
3472
            TABLE_MAIN_SYSTEM_CALENDAR
3473
        );
3474
        $month = intval($month);
3475
        $year = intval($year);
3476
        $week = intval($week);
3477
        $day = intval($day);
3478
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3479
3480
        $current_access_url_id = api_get_current_access_url_id();
3481
3482
        if ("month_view" == $type or "" == $type) {
3483
            // We are in month view
3484
            $sql = "SELECT * FROM ".$tbl_global_agenda." WHERE MONTH(start_date) = ".$month." AND YEAR(start_date) = ".$year."  AND access_url_id = $current_access_url_id ORDER BY start_date ASC";
3485
        }
3486
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3487
        if ("week_view" == $type) { // we are in week view
3488
            $start_end_day_of_week = self::calculate_start_end_of_week(
3489
                $week,
3490
                $year
3491
            );
3492
            $start_day = $start_end_day_of_week['start']['day'];
3493
            $start_month = $start_end_day_of_week['start']['month'];
3494
            $start_year = $start_end_day_of_week['start']['year'];
3495
            $end_day = $start_end_day_of_week['end']['day'];
3496
            $end_month = $start_end_day_of_week['end']['month'];
3497
            $end_year = $start_end_day_of_week['end']['year'];
3498
            // in sql statements you have to use year-month-day for date calculations
3499
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3500
            $start_filter = api_get_utc_datetime($start_filter);
3501
3502
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3503
            $end_filter = api_get_utc_datetime($end_filter);
3504
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND  access_url_id = $current_access_url_id ";
3505
        }
3506
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3507
        if ("day_view" == $type) { // we are in day view
3508
            // we could use mysql date() function but this is only available from 4.1 and higher
3509
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3510
            $start_filter = api_get_utc_datetime($start_filter);
3511
3512
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3513
            $end_filter = api_get_utc_datetime($end_filter);
3514
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'  AND  access_url_id = $current_access_url_id";
3515
        }
3516
3517
        $result = Database::query($sql);
3518
3519
        while ($item = Database::fetch_array($result)) {
3520
            if (!empty($item['start_date'])) {
3521
                $item['start_date'] = api_get_local_time($item['start_date']);
3522
                $item['start_date_tms'] = api_strtotime($item['start_date']);
3523
            }
3524
            if (!empty($item['end_date'])) {
3525
                $item['end_date'] = api_get_local_time($item['end_date']);
3526
            }
3527
3528
            // we break the date field in the database into a date and a time part
3529
            $agenda_db_date = explode(" ", $item['start_date']);
3530
            $date = $agenda_db_date[0];
3531
            $time = $agenda_db_date[1];
3532
            // we divide the date part into a day, a month and a year
3533
            $agendadate = explode("-", $date);
3534
            $year = intval($agendadate[0]);
3535
            $month = intval($agendadate[1]);
3536
            $day = intval($agendadate[2]);
3537
            // we divide the time part into hour, minutes, seconds
3538
            $agendatime = explode(":", $time);
3539
            $hour = $agendatime[0];
3540
            $minute = $agendatime[1];
3541
            $second = $agendatime[2];
3542
3543
            if ('month_view' == $type) {
3544
                $item['calendar_type'] = 'global';
3545
                $agendaitems[$day][] = $item;
3546
                continue;
3547
            }
3548
3549
            $start_time = api_format_date(
3550
                $item['start_date'],
3551
                TIME_NO_SEC_FORMAT
3552
            );
3553
            $end_time = '';
3554
            if (!empty($item['end_date'])) {
3555
                $end_time = ' - '.api_format_date(
3556
                        $item['end_date'],
3557
                        DATE_TIME_FORMAT_LONG
3558
                    );
3559
            }
3560
3561
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3562
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3563
            if ("day_view" !== $type) {
3564
                // This is the array construction for the WEEK or MONTH view
3565
                //Display the Agenda global in the tab agenda (administrator)
3566
                $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
3567
                $agendaitems[$day] .= "<b>".get_lang('Platform event')."</b>";
3568
                $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
3569
            } else {
3570
                // this is the array construction for the DAY view
3571
                $halfhour = 2 * $agendatime['0'];
3572
                if ($agendatime['1'] >= '30') {
3573
                    $halfhour = $halfhour + 1;
3574
                }
3575
                if (!is_array($agendaitems[$halfhour])) {
3576
                    $content = $agendaitems[$halfhour];
3577
                }
3578
                $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
3579
                        'Platform event'
3580
                    ).":  </b>".$item['title']."</div>";
3581
            }
3582
        }
3583
3584
        return $agendaitems;
3585
    }
3586
3587
    /**
3588
     * This function retrieves all the personal agenda items and add them to the agenda items found by the other
3589
     * functions.
3590
     */
3591
    public static function get_personal_agenda_items(
3592
        $user_id,
3593
        $agendaitems,
3594
        $day = "",
3595
        $month = "",
3596
        $year = "",
3597
        $week = "",
3598
        $type
3599
    ) {
3600
        $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
3601
        $user_id = (int) $user_id;
3602
        $course_link = '';
3603
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3604
        if ("month_view" === $type || "" == $type) {
3605
            // we are in month view
3606
            $sql = "SELECT * FROM ".$tbl_personal_agenda."
3607
                    WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."'
3608
                    ORDER BY date ASC";
3609
        }
3610
3611
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3612
        // we are in week view
3613
        if ("week_view" === $type) {
3614
            $start_end_day_of_week = self::calculate_start_end_of_week(
3615
                $week,
3616
                $year
3617
            );
3618
            $start_day = $start_end_day_of_week['start']['day'];
3619
            $start_month = $start_end_day_of_week['start']['month'];
3620
            $start_year = $start_end_day_of_week['start']['year'];
3621
            $end_day = $start_end_day_of_week['end']['day'];
3622
            $end_month = $start_end_day_of_week['end']['month'];
3623
            $end_year = $start_end_day_of_week['end']['year'];
3624
            // in sql statements you have to use year-month-day for date calculations
3625
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3626
            $start_filter = api_get_utc_datetime($start_filter);
3627
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3628
            $end_filter = api_get_utc_datetime($end_filter);
3629
            $sql = "SELECT * FROM ".$tbl_personal_agenda."
3630
                    WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3631
        }
3632
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3633
        if ("day_view" === $type) {
3634
            // we are in day view
3635
            // we could use mysql date() function but this is only available from 4.1 and higher
3636
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3637
            $start_filter = api_get_utc_datetime($start_filter);
3638
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3639
            $end_filter = api_get_utc_datetime($end_filter);
3640
            $sql = "SELECT * FROM ".$tbl_personal_agenda."
3641
                    WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3642
        }
3643
3644
        $result = Database::query($sql);
3645
        while ($item = Database::fetch_array($result, 'ASSOC')) {
3646
            $time_minute = api_convert_and_format_date(
3647
                $item['date'],
3648
                TIME_NO_SEC_FORMAT
3649
            );
3650
            $item['date'] = api_get_local_time($item['date']);
3651
            $item['start_date_tms'] = api_strtotime($item['date']);
3652
            $item['content'] = $item['text'];
3653
3654
            // we break the date field in the database into a date and a time part
3655
            $agenda_db_date = explode(" ", $item['date']);
3656
            $date = $agenda_db_date[0];
3657
            $time = $agenda_db_date[1];
3658
            // we divide the date part into a day, a month and a year
3659
            $agendadate = explode("-", $item['date']);
3660
            $year = intval($agendadate[0]);
3661
            $month = intval($agendadate[1]);
3662
            $day = intval($agendadate[2]);
3663
            // we divide the time part into hour, minutes, seconds
3664
            $agendatime = explode(":", $time);
3665
3666
            $hour = $agendatime[0];
3667
            $minute = $agendatime[1];
3668
            $second = $agendatime[2];
3669
3670
            if ('month_view' === $type) {
3671
                $item['calendar_type'] = 'personal';
3672
                $item['start_date'] = $item['date'];
3673
                $agendaitems[$day][] = $item;
3674
                continue;
3675
            }
3676
3677
            // Creating the array that will be returned.
3678
            // If we have week or month view we have an array with the date as the key
3679
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3680
            if ("day_view" !== $type) {
3681
                // This is the array construction for the WEEK or MONTH view
3682
3683
                //Display events in agenda
3684
                $agendaitems[$day] .= "<div>
3685
                     <i>$time_minute</i> $course_link
3686
                     <a href=\"myagenda.php?action=view&view=personal&day=$day&month=$month&year=$year&id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".
3687
                    $item['title']."</a></div><br />";
3688
            } else {
3689
                // this is the array construction for the DAY view
3690
                $halfhour = 2 * $agendatime['0'];
3691
                if ($agendatime['1'] >= '30') {
3692
                    $halfhour = $halfhour + 1;
3693
                }
3694
3695
                //Display events by list
3696
                $agendaitems[$halfhour] .= "<div>
3697
                    <i>$time_minute</i> $course_link
3698
                    <a href=\"myagenda.php?action=view&view=personal&day=$day&month=$month&year=$year&id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".$item['title']."</a></div>";
3699
            }
3700
        }
3701
3702
        return $agendaitems;
3703
    }
3704
3705
    /**
3706
     * Show the month calendar of the given month.
3707
     *
3708
     * @param    array    Agendaitems
3709
     * @param    int    Month number
3710
     * @param    int    Year number
3711
     * @param    array    Array of strings containing long week day names (deprecated, you can send an empty array
3712
     *                          instead)
3713
     * @param    string    The month name
3714
     */
3715
    public static function display_mymonthcalendar(
3716
        $user_id,
3717
        $agendaitems,
3718
        $month,
3719
        $year,
3720
        $weekdaynames = [],
3721
        $monthName,
3722
        $show_content = true
3723
    ) {
3724
        global $DaysShort, $course_path;
3725
        //Handle leap year
3726
        $numberofdays = [
3727
            0,
3728
            31,
3729
            28,
3730
            31,
3731
            30,
3732
            31,
3733
            30,
3734
            31,
3735
            31,
3736
            30,
3737
            31,
3738
            30,
3739
            31,
3740
        ];
3741
        if ((0 == $year % 400) or (0 == $year % 4 and 0 != $year % 100)) {
3742
            $numberofdays[2] = 29;
3743
        }
3744
        //Get the first day of the month
3745
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
3746
        //Start the week on monday
3747
        $startdayofweek = 0 != $dayone['wday'] ? ($dayone['wday'] - 1) : 6;
3748
        $g_cc = (isset($_GET['courseCode']) ? $_GET['courseCode'] : '');
3749
3750
        $next_month = (1 == $month ? 12 : $month - 1);
3751
        $prev_month = (12 == $month ? 1 : $month + 1);
3752
3753
        $next_year = (1 == $month ? $year - 1 : $year);
3754
        $prev_year = (12 == $month ? $year + 1 : $year);
3755
3756
        if ($show_content) {
3757
            $back_url = Display::url(
3758
                get_lang('Previous'),
3759
                api_get_self()."?coursePath=".urlencode(
3760
                    $course_path
3761
                )."&courseCode=".Security::remove_XSS(
3762
                    $g_cc
3763
                )."&action=view&view=month&month=".$next_month."&year=".$next_year
3764
            );
3765
            $next_url = Display::url(
3766
                get_lang('Next'),
3767
                api_get_self()."?coursePath=".urlencode(
3768
                    $course_path
3769
                )."&courseCode=".Security::remove_XSS(
3770
                    $g_cc
3771
                )."&action=view&view=month&month=".$prev_month."&year=".$prev_year
3772
            );
3773
        } else {
3774
            $back_url = Display::url(
3775
                get_lang('Previous'),
3776
                '',
3777
                [
3778
                    'onclick' => "load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ",
3779
                    'class' => 'btn ui-button ui-widget ui-state-default',
3780
                ]
3781
            );
3782
            $next_url = Display::url(
3783
                get_lang('Next'),
3784
                '',
3785
                [
3786
                    'onclick' => "load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ",
3787
                    'class' => 'pull-right btn ui-button ui-widget ui-state-default',
3788
                ]
3789
            );
3790
        }
3791
        $html = '';
3792
        $html .= '<div class="actions">';
3793
        $html .= '<div class="row">';
3794
        $html .= '<div class="col-md-4">'.$back_url.'</div>';
3795
        $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
3796
        $html .= '<div class="col-md-4">'.$next_url.'</div>';
3797
        $html .= '</div>';
3798
        $html .= '</div>';
3799
        $html .= '<table id="agenda_list2" class="table table-bordered">';
3800
        $html .= '<tr>';
3801
        for ($ii = 1; $ii < 8; $ii++) {
3802
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
3803
        }
3804
        $html .= '</tr>';
3805
3806
        $curday = -1;
3807
        $today = getdate();
3808
        while ($curday <= $numberofdays[$month]) {
3809
            $html .= "<tr>";
3810
            for ($ii = 0; $ii < 7; $ii++) {
3811
                if ((-1 == $curday) && ($ii == $startdayofweek)) {
3812
                    $curday = 1;
3813
                }
3814
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
3815
                    $bgcolor = $class = 'class="days_week"';
3816
                    $dayheader = Display::div(
3817
                        $curday,
3818
                        ['class' => 'agenda_day']
3819
                    );
3820
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
3821
                        $class = "class=\"days_today\" style=\"width:10%;\"";
3822
                    }
3823
3824
                    $html .= "<td ".$class.">".$dayheader;
3825
3826
                    if (!empty($agendaitems[$curday])) {
3827
                        $items = $agendaitems[$curday];
3828
                        $items = msort($items, 'start_date_tms');
3829
3830
                        foreach ($items as $value) {
3831
                            $value['title'] = Security::remove_XSS(
3832
                                $value['title']
3833
                            );
3834
                            $start_time = api_format_date(
3835
                                $value['start_date'],
3836
                                TIME_NO_SEC_FORMAT
3837
                            );
3838
                            $end_time = '';
3839
3840
                            if (!empty($value['end_date'])) {
3841
                                $end_time = '-&nbsp;<i>'.api_format_date(
3842
                                        $value['end_date'],
3843
                                        DATE_TIME_FORMAT_LONG
3844
                                    ).'</i>';
3845
                            }
3846
                            $complete_time = '<i>'.api_format_date(
3847
                                    $value['start_date'],
3848
                                    DATE_TIME_FORMAT_LONG
3849
                                ).'</i>&nbsp;'.$end_time;
3850
                            $time = '<i>'.$start_time.'</i>';
3851
3852
                            switch ($value['calendar_type']) {
3853
                                case 'personal':
3854
                                    $bg_color = '#D0E7F4';
3855
                                    $icon = Display::return_icon(
3856
                                        'user.png',
3857
                                        get_lang('Personal agenda'),
3858
                                        [],
3859
                                        ICON_SIZE_SMALL
3860
                                    );
3861
                                    break;
3862
                                case 'global':
3863
                                    $bg_color = '#FFBC89';
3864
                                    $icon = Display::return_icon(
3865
                                        'view_remove.png',
3866
                                        get_lang('Platform event'),
3867
                                        [],
3868
                                        ICON_SIZE_SMALL
3869
                                    );
3870
                                    break;
3871
                                case 'course':
3872
                                    $bg_color = '#CAFFAA';
3873
                                    $icon_name = 'course.png';
3874
                                    if (!empty($value['session_id'])) {
3875
                                        $icon_name = 'session.png';
3876
                                    }
3877
                                    if ($show_content) {
3878
                                        $icon = Display::url(
3879
                                            Display::return_icon(
3880
                                                $icon_name,
3881
                                                $value['course_name'].' '.get_lang(
3882
                                                    'Course'
3883
                                                ),
3884
                                                [],
3885
                                                ICON_SIZE_SMALL
3886
                                            ),
3887
                                            $value['url']
3888
                                        );
3889
                                    } else {
3890
                                        $icon = Display::return_icon(
3891
                                            $icon_name,
3892
                                            $value['course_name'].' '.get_lang(
3893
                                                'Course'
3894
                                            ),
3895
                                            [],
3896
                                            ICON_SIZE_SMALL
3897
                                        );
3898
                                    }
3899
                                    break;
3900
                                default:
3901
                                    break;
3902
                            }
3903
3904
                            $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
3905
3906
                            if ($show_content) {
3907
                                //Setting a personal event to green
3908
                                $icon = Display::div(
3909
                                    $icon,
3910
                                    ['style' => 'float:right']
3911
                                );
3912
3913
                                $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
3914
3915
                                //Link to bubble
3916
                                $url = Display::url(
3917
                                    cut($value['title'], 40),
3918
                                    '#',
3919
                                    ['id' => $link, 'class' => 'opener']
3920
                                );
3921
                                $result .= $time.' '.$icon.' '.Display::div(
3922
                                        $url
3923
                                    );
3924
3925
                                //Hidden content
3926
                                $content = Display::div(
3927
                                    $icon.Display::tag(
3928
                                        'h2',
3929
                                        $value['course_name']
3930
                                    ).'<hr />'.Display::tag(
3931
                                        'h3',
3932
                                        $value['title']
3933
                                    ).$complete_time.'<hr />'.Security::remove_XSS(
3934
                                        $value['content']
3935
                                    )
3936
                                );
3937
3938
                                //Main div
3939
                                $result .= Display::div(
3940
                                    $content,
3941
                                    [
3942
                                        'id' => 'main_'.$link,
3943
                                        'class' => 'dialog',
3944
                                        'style' => 'display:none',
3945
                                    ]
3946
                                );
3947
                                $result .= '</div>';
3948
                                $html .= $result;
3949
                            } else {
3950
                                $html .= $result .= $icon.'</div>';
3951
                            }
3952
                        }
3953
                    }
3954
                    $html .= "</td>";
3955
                    $curday++;
3956
                } else {
3957
                    $html .= "<td></td>";
3958
                }
3959
            }
3960
            $html .= "</tr>";
3961
        }
3962
        $html .= "</table>";
3963
        echo $html;
3964
    }
3965
3966
    /**
3967
     * Get personal agenda items between two dates (=all events from all registered courses).
3968
     *
3969
     * @param int $user_id user ID of the user
3970
     * @param    string    Optional start date in datetime format (if no start date is given, uses today)
3971
     * @param    string    Optional end date in datetime format (if no date is given, uses one year from now)
3972
     *
3973
     * @return array array of events ordered by start date, in
3974
     *               [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
3975
     *               where datestart and dateend are in yyyyMMddhhmmss format
3976
     *
3977
     * @deprecated use agenda events
3978
     */
3979
    public static function get_personal_agenda_items_between_dates($user_id, $date_start = '', $date_end = '')
3980
    {
3981
        throw new Exception('fix get_personal_agenda_items_between_dates');
3982
        /*
3983
        $items = [];
3984
        if ($user_id != strval(intval($user_id))) {
3985
            return $items;
3986
        }
3987
        if (empty($date_start)) {
3988
            $date_start = date('Y-m-d H:i:s');
3989
        }
3990
        if (empty($date_end)) {
3991
            $date_end = date(
3992
                'Y-m-d H:i:s',
3993
                mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1)
3994
            );
3995
        }
3996
        $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
3997
        if (!preg_match($expr, $date_start)) {
3998
            return $items;
3999
        }
4000
        if (!preg_match($expr, $date_end)) {
4001
            return $items;
4002
        }
4003
4004
        // get agenda-items for every course
4005
        //$courses = api_get_user_courses($user_id, false);
4006
        $courses = CourseManager::get_courses_list_by_user_id($user_id, false);
4007
        foreach ($courses as $id => $course) {
4008
            $c = api_get_course_info_by_id($course['real_id']);
4009
            $t_a = Database::get_course_table(TABLE_AGENDA, $course['db']);
4010
            $t_ip = Database::get_course_table(
4011
                TABLE_ITEM_PROPERTY,
4012
                $course['db']
4013
            );
4014
            // get the groups to which the user belong
4015
            $group_memberships = GroupManager:: get_group_ids(
4016
                $course['db'],
4017
                $user_id
4018
            );
4019
            // if the user is administrator of that course we show all the agenda items
4020
            if ('1' == $course['status']) {
4021
                //echo "course admin";
4022
                $sqlquery = "SELECT ".
4023
                    " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4024
                    " FROM ".$t_a." agenda, ".
4025
                    $t_ip." ip ".
4026
                    " WHERE agenda.id = ip.ref ".
4027
                    " AND agenda.start_date>='$date_start' ".
4028
                    " AND agenda.end_date<='$date_end' ".
4029
                    " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4030
                    " AND ip.visibility='1' ".
4031
                    " GROUP BY agenda.id ".
4032
                    " ORDER BY start_date ";
4033
            } else {
4034
                // if the user is not an administrator of that course, then...
4035
                if (is_array($group_memberships) && count(
4036
                        $group_memberships
4037
                    ) > 0
4038
                ) {
4039
                    $sqlquery = "SELECT ".
4040
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4041
                        " FROM ".$t_a." agenda, ".
4042
                        $t_ip." ip ".
4043
                        " WHERE agenda.id = ip.ref ".
4044
                        " AND agenda.start_date>='$date_start' ".
4045
                        " AND agenda.end_date<='$date_end' ".
4046
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4047
                        " AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
4048
                            ", ",
4049
                            $group_memberships
4050
                        ).")) ) ".
4051
                        " AND ip.visibility='1' ".
4052
                        " ORDER BY start_date ";
4053
                } else {
4054
                    $sqlquery = "SELECT ".
4055
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4056
                        " FROM ".$t_a." agenda, ".
4057
                        $t_ip." ip ".
4058
                        " WHERE agenda.id = ip.ref ".
4059
                        " AND agenda.start_date>='$date_start' ".
4060
                        " AND agenda.end_date<='$date_end' ".
4061
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4062
                        " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
4063
                        " AND ip.visibility='1' ".
4064
                        " ORDER BY start_date ";
4065
                }
4066
            }
4067
4068
            $result = Database::query($sqlquery);
4069
            while ($item = Database::fetch_array($result)) {
4070
                $agendaday = date("j", strtotime($item['start_date']));
4071
                $month = date("n", strtotime($item['start_date']));
4072
                $year = date("Y", strtotime($item['start_date']));
4073
                $URL = api_get_path(
4074
                        WEB_PATH
4075
                    )."main/calendar/agenda.php?cidReq=".urlencode(
4076
                        $course["code"]
4077
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
4078
                [$year, $month, $day, $hour, $min, $sec] = explode(
4079
                    '[-: ]',
4080
                    $item['start_date']
4081
                );
4082
                $start_date = $year.$month.$day.$hour.$min;
4083
                [$year, $month, $day, $hour, $min, $sec] = explode(
4084
                    '[-: ]',
4085
                    $item['end_date']
4086
                );
4087
                $end_date = $year.$month.$day.$hour.$min;
4088
4089
                $items[] = [
4090
                    'datestart' => $start_date,
4091
                    'dateend' => $end_date,
4092
                    'title' => $item['title'],
4093
                    'link' => $URL,
4094
                    'coursetitle' => $c['name'],
4095
                ];
4096
            }
4097
        }
4098
4099
        return $items;*/
4100
    }
4101
4102
    /**
4103
     * This function calculates the startdate of the week (monday)
4104
     * and the enddate of the week (sunday)
4105
     * and returns it as an array.
4106
     */
4107
    public static function calculate_start_end_of_week($week_number, $year)
4108
    {
4109
        // determine the start and end date
4110
        // step 1: we calculate a timestamp for a day in this week
4111
        $random_day_in_week = mktime(
4112
                0,
4113
                0,
4114
                0,
4115
                1,
4116
                1,
4117
                $year
4118
            ) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
4119
        // step 2: we which day this is (0=sunday, 1=monday, ...)
4120
        $number_day_in_week = date('w', $random_day_in_week);
4121
        // step 3: we calculate the timestamp of the monday of the week we are in
4122
        $start_timestamp = $random_day_in_week - (($number_day_in_week - 1) * 24 * 60 * 60);
4123
        // step 4: we calculate the timestamp of the sunday of the week we are in
4124
        $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week + 1) * 24 * 60 * 60) - 3600;
4125
        // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
4126
        $start_day = date('j', $start_timestamp);
4127
        $start_month = date('n', $start_timestamp);
4128
        $start_year = date('Y', $start_timestamp);
4129
        $end_day = date('j', $end_timestamp);
4130
        $end_month = date('n', $end_timestamp);
4131
        $end_year = date('Y', $end_timestamp);
4132
        $start_end_array['start']['day'] = $start_day;
4133
        $start_end_array['start']['month'] = $start_month;
4134
        $start_end_array['start']['year'] = $start_year;
4135
        $start_end_array['end']['day'] = $end_day;
4136
        $start_end_array['end']['month'] = $end_month;
4137
        $start_end_array['end']['year'] = $end_year;
4138
4139
        return $start_end_array;
4140
    }
4141
4142
    /**
4143
     * @return bool
4144
     */
4145
    public function getIsAllowedToEdit()
4146
    {
4147
        return $this->isAllowedToEdit;
4148
    }
4149
4150
    /**
4151
     * @param bool $isAllowedToEdit
4152
     */
4153
    public function setIsAllowedToEdit($isAllowedToEdit)
4154
    {
4155
        $this->isAllowedToEdit = $isAllowedToEdit;
4156
    }
4157
4158
    /**
4159
     * Format needed for the Fullcalendar js lib.
4160
     *
4161
     * @param string $utcTime
4162
     *
4163
     * @return bool|string
4164
     */
4165
    public function formatEventDate($utcTime)
4166
    {
4167
        $utcTimeZone = new DateTimeZone('UTC');
4168
        $platformTimeZone = new DateTimeZone(api_get_timezone());
4169
4170
        $eventDate = new DateTime($utcTime, $utcTimeZone);
4171
        $eventDate->setTimezone($platformTimeZone);
4172
4173
        return $eventDate->format(DateTime::ISO8601);
4174
    }
4175
}
4176