Passed
Push — master ( 43f231...6078d3 )
by Julito
08:55
created

Agenda::getAttachment()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 3
nop 3
dl 0
loc 25
rs 9.4222
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\Resource\ResourceLink;
7
use Chamilo\CoreBundle\Entity\SysCalendar;
8
use Chamilo\CoreBundle\Framework\Container;
9
use Chamilo\CourseBundle\Entity\CCalendarEvent;
10
use Chamilo\CourseBundle\Entity\CCalendarEventAttachment;
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_id())
273
                ;
274
                $em->persist($event);
275
                $em->flush();
276
                $id = $event->getId();
277
                break;
278
            case 'course':
279
                $senderId = $this->getSenderId();
280
                $sessionId = $this->getSessionId();
281
                $userEntity = api_get_user_entity(api_get_user_id());
282
                $sessionEntity = api_get_session_entity($sessionId);
283
                $courseEntity = api_get_course_entity($this->course['real_id']);
284
                $groupEntity = api_get_group_entity(api_get_group_id());
285
286
                $event = new CCalendarEvent();
287
                $event
288
                    ->setTitle($title)
289
                    ->setContent($content)
290
                    ->setStartDate($start)
291
                    ->setEndDate($end)
292
                    ->setAllDay($allDay)
293
                    ->setColor($color)
294
                    ->setComment($eventComment)
295
                    ->setCId($this->course['real_id'])
296
                    ->setSessionId($this->getSessionId())
297
                ;
298
299
                if (!empty($parentEventId)) {
300
                    $event->setParentEventId($parentEventId);
301
                }
302
303
                $repo = Container::getCalendarEventRepository();
304
305
                // Node added.
306
                $resourceNode = $repo->createNodeForResource(
307
                    $event,
308
                    $userEntity,
309
                    $courseEntity->getResourceNode()
310
                );
311
312
                if (!empty($usersToSend)) {
313
                    $sendTo = $this->parseSendToArray($usersToSend);
314
                    if ($sendTo['everyone']) {
315
                        $repo->addResourceNodeToCourse(
316
                            $resourceNode,
317
                            ResourceLink::VISIBILITY_PUBLISHED,
318
                            $courseEntity,
319
                            $sessionEntity,
320
                            $groupEntity
321
                        );
322
323
                    /*api_item_property_update(
324
                        $this->course,
325
                        TOOL_CALENDAR_EVENT,
326
                        $id,
327
                        'AgendaAdded',
328
                        $senderId,
329
                        $groupInfo,
330
                        '',
331
                        $start,
332
                        $end,
333
                        $sessionId
334
                    );
335
                    api_item_property_update(
336
                        $this->course,
337
                        TOOL_CALENDAR_EVENT,
338
                        $id,
339
                        'visible',
340
                        $senderId,
341
                        $groupInfo,
342
                        '',
343
                        $start,
344
                        $end,
345
                        $sessionId
346
                    );*/
347
                    } else {
348
                        // Storing the selected groups
349
                        if (!empty($sendTo['groups'])) {
350
                            foreach ($sendTo['groups'] as $group) {
351
                                $groupInfo = null;
352
                                if ($group) {
353
                                    $groupInfo = api_get_group_entity($group);
354
                                }
355
356
                                $repo->addResourceNodeToCourse(
357
                                    $resourceNode,
358
                                    ResourceLink::VISIBILITY_PUBLISHED,
359
                                    $courseEntity,
360
                                    $sessionEntity,
361
                                    $groupInfo
362
                                );
363
364
                                /*api_item_property_update(
365
                                    $this->course,
366
                                    TOOL_CALENDAR_EVENT,
367
                                    $id,
368
                                    'AgendaAdded',
369
                                    $senderId,
370
                                    $groupInfoItem,
371
                                    0,
372
                                    $start,
373
                                    $end,
374
                                    $sessionId
375
                                );
376
377
                                api_item_property_update(
378
                                    $this->course,
379
                                    TOOL_CALENDAR_EVENT,
380
                                    $id,
381
                                    'visible',
382
                                    $senderId,
383
                                    $groupInfoItem,
384
                                    0,
385
                                    $start,
386
                                    $end,
387
                                    $sessionId
388
                                );*/
389
                            }
390
                        }
391
392
                        // storing the selected users
393
                        if (!empty($sendTo['users'])) {
394
                            foreach ($sendTo['users'] as $userId) {
395
                                $repo->addResourceNodeToCourse(
396
                                    $resourceNode,
397
                                    ResourceLink::VISIBILITY_PUBLISHED,
398
                                    $courseEntity,
399
                                    $sessionEntity,
400
                                    $groupEntity,
401
                                    api_get_user_entity($userId)
402
                                );
403
                                /*api_item_property_update(
404
                                    $this->course,
405
                                    TOOL_CALENDAR_EVENT,
406
                                    $id,
407
                                    'AgendaAdded',
408
                                    $senderId,
409
                                    $groupInfo,
410
                                    $userId,
411
                                    $start,
412
                                    $end,
413
                                    $sessionId
414
                                );
415
416
                                api_item_property_update(
417
                                    $this->course,
418
                                    TOOL_CALENDAR_EVENT,
419
                                    $id,
420
                                    'visible',
421
                                    $senderId,
422
                                    $groupInfo,
423
                                    $userId,
424
                                    $start,
425
                                    $end,
426
                                    $sessionId
427
                                );*/
428
                            }
429
                        }
430
                    }
431
                }
432
433
                $em->flush();
434
                $id = $event->getIid();
435
436
                if ($id) {
437
                    $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
438
                    Database::query($sql);
439
440
                    // Add announcement.
441
                    if ($addAsAnnouncement) {
442
                        $this->storeAgendaEventAsAnnouncement($id, $usersToSend);
443
                    }
444
445
                    // Add attachment.
446
                    if (!empty($attachmentArray)) {
447
                        $counter = 0;
448
                        foreach ($attachmentArray as $attachmentItem) {
449
                            $this->addAttachment(
450
                                $event,
451
                                $attachmentItem,
452
                                $attachmentCommentList[$counter],
453
                                $this->course
454
                            );
455
                            $counter++;
456
                        }
457
                    }
458
                }
459
                break;
460
            case 'admin':
461
                if (api_is_platform_admin()) {
462
                    $event = new SysCalendar();
463
                    $event
464
                        ->setTitle($title)
465
                        ->setContent($content)
466
                        ->setStartDate($start)
467
                        ->setEndDate($end)
468
                        ->setAllDay($allDay)
469
                        ->setAccessUrlId(api_get_current_access_url_id())
470
                    ;
471
                    $em->persist($event);
472
                    $em->flush();
473
                    $id = $event->getId();
474
                }
475
                break;
476
        }
477
478
        return $id;
479
    }
480
481
    /**
482
     * @param int $eventId
483
     * @param int $courseId
484
     *
485
     * @return array
486
     */
487
    public function getRepeatedInfoByEvent($eventId, $courseId)
488
    {
489
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
490
        $eventId = (int) $eventId;
491
        $courseId = (int) $courseId;
492
        $sql = "SELECT * FROM $repeatTable
493
                WHERE c_id = $courseId AND cal_id = $eventId";
494
        $res = Database::query($sql);
495
        $repeatInfo = [];
496
        if (Database::num_rows($res) > 0) {
497
            $repeatInfo = Database::fetch_array($res, 'ASSOC');
498
        }
499
500
        return $repeatInfo;
501
    }
502
503
    /**
504
     * @param string $type
505
     * @param string $startEvent      in UTC
506
     * @param string $endEvent        in UTC
507
     * @param string $repeatUntilDate in UTC
508
     *
509
     * @throws Exception
510
     *
511
     * @return array
512
     */
513
    public function generateDatesByType($type, $startEvent, $endEvent, $repeatUntilDate)
514
    {
515
        $continue = true;
516
        $repeatUntilDate = new DateTime($repeatUntilDate, new DateTimeZone('UTC'));
517
        $loopMax = 365;
518
        $counter = 0;
519
        $list = [];
520
521
        switch ($type) {
522
            case 'daily':
523
                $interval = 'P1D';
524
                break;
525
            case 'weekly':
526
                $interval = 'P1W';
527
                break;
528
            case 'monthlyByDate':
529
                $interval = 'P1M';
530
                break;
531
            case 'monthlyByDay':
532
            case 'monthlyByDayR':
533
                // not yet implemented
534
                break;
535
            case 'yearly':
536
                $interval = 'P1Y';
537
                break;
538
        }
539
540
        if (empty($interval)) {
541
            return [];
542
        }
543
        $timeZone = api_get_timezone();
544
545
        while ($continue) {
546
            $startDate = new DateTime($startEvent, new DateTimeZone('UTC'));
547
            $endDate = new DateTime($endEvent, new DateTimeZone('UTC'));
548
549
            $startDate->add(new DateInterval($interval));
550
            $endDate->add(new DateInterval($interval));
551
552
            $newStartDate = $startDate->format('Y-m-d H:i:s');
553
            $newEndDate = $endDate->format('Y-m-d H:i:s');
554
555
            $startEvent = $newStartDate;
556
            $endEvent = $newEndDate;
557
558
            if ($endDate > $repeatUntilDate) {
559
                break;
560
            }
561
562
            // @todo remove comment code
563
            $startDateInLocal = new DateTime($newStartDate, new DateTimeZone($timeZone));
564
            if (0 == $startDateInLocal->format('I')) {
565
                // Is saving time? Then fix UTC time to add time
566
                $seconds = $startDateInLocal->getOffset();
567
                $startDate->add(new DateInterval("PT".$seconds."S"));
568
                $startDateFixed = $startDate->format('Y-m-d H:i:s');
569
                $startDateInLocalFixed = new DateTime($startDateFixed, new DateTimeZone($timeZone));
570
                $newStartDate = $startDateInLocalFixed->format('Y-m-d H:i:s');
571
            }
572
573
            $endDateInLocal = new DateTime($newEndDate, new DateTimeZone($timeZone));
574
            if (0 == $endDateInLocal->format('I')) {
575
                // Is saving time? Then fix UTC time to add time
576
                $seconds = $endDateInLocal->getOffset();
577
                $endDate->add(new DateInterval("PT".$seconds."S"));
578
                $endDateFixed = $endDate->format('Y-m-d H:i:s');
579
                $endDateInLocalFixed = new DateTime($endDateFixed, new DateTimeZone($timeZone));
580
                $newEndDate = $endDateInLocalFixed->format('Y-m-d H:i:s');
581
            }
582
            $list[] = ['start' => $newStartDate, 'end' => $newEndDate, 'i' => $startDateInLocal->format('I')];
583
            $counter++;
584
585
            // just in case stop if more than $loopMax
586
            if ($counter > $loopMax) {
587
                break;
588
            }
589
        }
590
591
        return $list;
592
    }
593
594
    /**
595
     * @param int    $eventId
596
     * @param string $type
597
     * @param string $end     in UTC
598
     * @param array  $sentTo
599
     *
600
     * @return bool
601
     */
602
    public function addRepeatedItem($eventId, $type, $end, $sentTo = [])
603
    {
604
        $t_agenda = Database::get_course_table(TABLE_AGENDA);
605
        $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
606
607
        if (empty($this->course)) {
608
            return false;
609
        }
610
611
        $courseId = $this->course['real_id'];
612
        $eventId = (int) $eventId;
613
614
        $sql = "SELECT title, content, start_date, end_date, all_day
615
                FROM $t_agenda
616
                WHERE c_id = $courseId AND id = $eventId";
617
        $res = Database::query($sql);
618
619
        if (1 !== Database::num_rows($res)) {
620
            return false;
621
        }
622
623
        $typeList = [
624
            'daily',
625
            'weekly',
626
            'monthlyByDate',
627
            'monthlyByDay',
628
            'monthlyByDayR',
629
            'yearly',
630
        ];
631
632
        if (!in_array($type, $typeList)) {
633
            return false;
634
        }
635
636
        $now = time();
637
638
        // The event has to repeat *in the future*. We don't allow repeated
639
        // events in the past
640
        if ($end > $now) {
641
            return false;
642
        }
643
644
        $row = Database::fetch_array($res);
645
646
        $title = $row['title'];
647
        $content = $row['content'];
648
        $allDay = $row['all_day'];
649
650
        $type = Database::escape_string($type);
651
        $end = Database::escape_string($end);
652
        $endTimeStamp = api_strtotime($end, 'UTC');
653
        $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
654
                VALUES ($courseId, '$eventId', '$type', '$endTimeStamp')";
655
        Database::query($sql);
656
657
        $generatedDates = $this->generateDatesByType($type, $row['start_date'], $row['end_date'], $end);
658
659
        if (empty($generatedDates)) {
660
            return false;
661
        }
662
663
        foreach ($generatedDates as $dateInfo) {
664
            $start = api_get_local_time($dateInfo['start']);
665
            $end = api_get_local_time($dateInfo['end']);
666
            $this->addEvent(
667
                $start,
668
                $end,
669
                $allDay,
670
                $title,
671
                $content,
672
                $sentTo,
673
                false,
674
                $eventId
675
            );
676
        }
677
678
        return true;
679
    }
680
681
    /**
682
     * @param int   $item_id
683
     * @param array $sentTo
684
     *
685
     * @return int
686
     */
687
    public function storeAgendaEventAsAnnouncement($item_id, $sentTo = [])
688
    {
689
        $table_agenda = Database::get_course_table(TABLE_AGENDA);
690
        $courseId = api_get_course_int_id();
691
692
        // Get the agenda item.
693
        $item_id = (int) $item_id;
694
        $sql = "SELECT * FROM $table_agenda
695
                WHERE c_id = $courseId AND id = ".$item_id;
696
        $res = Database::query($sql);
697
698
        if (Database::num_rows($res) > 0) {
699
            $row = Database::fetch_array($res, 'ASSOC');
700
701
            // Sending announcement
702
            if (!empty($sentTo)) {
703
                $id = AnnouncementManager::add_announcement(
704
                    api_get_course_info(),
705
                    api_get_session_id(),
706
                    $row['title'],
707
                    $row['content'],
708
                    $sentTo,
709
                    null,
710
                    null,
711
                    $row['end_date']
712
                );
713
714
                AnnouncementManager::sendEmail(
715
                    api_get_course_info(),
716
                    api_get_session_id(),
717
                    $id
718
                );
719
720
                return $id;
721
            }
722
        }
723
724
        return -1;
725
    }
726
727
    /**
728
     * Edits an event.
729
     *
730
     * @param int    $id
731
     * @param string $start                 datetime format: 2012-06-14 09:00:00
732
     * @param string $end                   datetime format: 2012-06-14 09:00:00
733
     * @param int    $allDay                is all day 'true' or 'false'
734
     * @param string $title
735
     * @param string $content
736
     * @param array  $usersToSend
737
     * @param array  $attachmentArray
738
     * @param array  $attachmentCommentList
739
     * @param string $comment
740
     * @param string $color
741
     * @param bool   $addAnnouncement
742
     * @param bool   $updateContent
743
     * @param int    $authorId
744
     *
745
     * @return bool
746
     */
747
    public function editEvent(
748
        $id,
749
        $start,
750
        $end,
751
        $allDay,
752
        $title,
753
        $content,
754
        $usersToSend = [],
755
        $attachmentArray = [],
756
        $attachmentCommentList = [],
757
        $comment = null,
758
        $color = '',
759
        $addAnnouncement = false,
760
        $updateContent = true,
761
        $authorId = 0
762
    ) {
763
        $start = api_get_utc_datetime($start);
764
        $end = api_get_utc_datetime($end);
765
        $allDay = isset($allDay) && 'true' == $allDay ? 1 : 0;
766
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
767
768
        switch ($this->type) {
769
            case 'personal':
770
                $eventInfo = $this->get_event($id);
771
                if ($eventInfo['user'] != api_get_user_id()) {
772
                    break;
773
                }
774
                $attributes = [
775
                    'title' => $title,
776
                    'date' => $start,
777
                    'enddate' => $end,
778
                    'all_day' => $allDay,
779
                ];
780
781
                if ($updateContent) {
782
                    $attributes['text'] = $content;
783
                }
784
785
                if (!empty($color)) {
786
                    $attributes['color'] = $color;
787
                }
788
789
                Database::update(
790
                    $this->tbl_personal_agenda,
791
                    $attributes,
792
                    ['id = ?' => $id]
793
                );
794
                break;
795
            case 'course':
796
                $eventInfo = $this->get_event($id);
797
798
                if (empty($eventInfo)) {
799
                    return false;
800
                }
801
802
                $groupId = api_get_group_id();
803
                $groupIid = 0;
804
                $groupInfo = [];
805
                if ($groupId) {
806
                    $groupInfo = GroupManager::get_group_properties($groupId);
807
                    if ($groupInfo) {
808
                        $groupIid = $groupInfo['iid'];
809
                    }
810
                }
811
812
                $courseId = $this->course['real_id'];
813
814
                if (empty($courseId)) {
815
                    return false;
816
                }
817
818
                if ($this->getIsAllowedToEdit()) {
819
                    $attributes = [
820
                        'title' => $title,
821
                        'start_date' => $start,
822
                        'end_date' => $end,
823
                        'all_day' => $allDay,
824
                        'comment' => $comment,
825
                    ];
826
827
                    if ($updateContent) {
828
                        $attributes['content'] = $content;
829
                    }
830
831
                    if (!empty($color)) {
832
                        $attributes['color'] = $color;
833
                    }
834
835
                    Database::update(
836
                        $this->tbl_course_agenda,
837
                        $attributes,
838
                        [
839
                            'id = ? AND c_id = ? AND session_id = ? ' => [
840
                                $id,
841
                                $courseId,
842
                                $this->sessionId,
843
                            ],
844
                        ]
845
                    );
846
847
                    if (!empty($usersToSend)) {
848
                        $sendTo = $this->parseSendToArray($usersToSend);
849
850
                        $usersToDelete = array_diff(
851
                            $eventInfo['send_to']['users'],
852
                            $sendTo['users']
853
                        );
854
                        $usersToAdd = array_diff(
855
                            $sendTo['users'],
856
                            $eventInfo['send_to']['users']
857
                        );
858
859
                        $groupsToDelete = array_diff(
860
                            $eventInfo['send_to']['groups'],
861
                            $sendTo['groups']
862
                        );
863
                        $groupToAdd = array_diff(
864
                            $sendTo['groups'],
865
                            $eventInfo['send_to']['groups']
866
                        );
867
868
                        if ($sendTo['everyone']) {
869
                            // Delete all from group
870
                            if (isset($eventInfo['send_to']['groups']) &&
871
                                !empty($eventInfo['send_to']['groups'])
872
                            ) {
873
                                foreach ($eventInfo['send_to']['groups'] as $group) {
874
                                    $groupIidItem = 0;
875
                                    if ($group) {
876
                                        $groupInfoItem = GroupManager::get_group_properties(
877
                                            $group
878
                                        );
879
                                        if ($groupInfoItem) {
880
                                            $groupIidItem = $groupInfoItem['iid'];
881
                                        }
882
                                    }
883
884
                                    api_item_property_delete(
885
                                        $this->course,
886
                                        TOOL_CALENDAR_EVENT,
887
                                        $id,
888
                                        0,
889
                                        $groupIidItem,
890
                                        $this->sessionId
891
                                    );
892
                                }
893
                            }
894
895
                            // Storing the selected users.
896
                            if (isset($eventInfo['send_to']['users']) &&
897
                                !empty($eventInfo['send_to']['users'])
898
                            ) {
899
                                foreach ($eventInfo['send_to']['users'] as $userId) {
900
                                    api_item_property_delete(
901
                                        $this->course,
902
                                        TOOL_CALENDAR_EVENT,
903
                                        $id,
904
                                        $userId,
905
                                        $groupIid,
906
                                        $this->sessionId
907
                                    );
908
                                }
909
                            }
910
911
                            // Add to everyone only.
912
                            api_item_property_update(
913
                                $this->course,
914
                                TOOL_CALENDAR_EVENT,
915
                                $id,
916
                                'visible',
917
                                $authorId,
918
                                $groupInfo,
919
                                null,
920
                                $start,
921
                                $end,
922
                                $this->sessionId
923
                            );
924
                        } else {
925
                            // Delete "everyone".
926
                            api_item_property_delete(
927
                                $this->course,
928
                                TOOL_CALENDAR_EVENT,
929
                                $id,
930
                                0,
931
                                0,
932
                                $this->sessionId
933
                            );
934
935
                            // Add groups
936
                            if (!empty($groupToAdd)) {
937
                                foreach ($groupToAdd as $group) {
938
                                    $groupInfoItem = [];
939
                                    if ($group) {
940
                                        $groupInfoItem = GroupManager::get_group_properties(
941
                                            $group
942
                                        );
943
                                    }
944
945
                                    api_item_property_update(
946
                                        $this->course,
947
                                        TOOL_CALENDAR_EVENT,
948
                                        $id,
949
                                        'visible',
950
                                        $authorId,
951
                                        $groupInfoItem,
952
                                        0,
953
                                        $start,
954
                                        $end,
955
                                        $this->sessionId
956
                                    );
957
                                }
958
                            }
959
960
                            // Delete groups.
961
                            if (!empty($groupsToDelete)) {
962
                                foreach ($groupsToDelete as $group) {
963
                                    $groupIidItem = 0;
964
                                    if ($group) {
965
                                        $groupInfoItem = GroupManager::get_group_properties(
966
                                            $group
967
                                        );
968
                                        if ($groupInfoItem) {
969
                                            $groupIidItem = $groupInfoItem['iid'];
970
                                        }
971
                                    }
972
973
                                    api_item_property_delete(
974
                                        $this->course,
975
                                        TOOL_CALENDAR_EVENT,
976
                                        $id,
977
                                        0,
978
                                        $groupIidItem,
979
                                        $this->sessionId
980
                                    );
981
                                }
982
                            }
983
984
                            // Add users.
985
                            if (!empty($usersToAdd)) {
986
                                foreach ($usersToAdd as $userId) {
987
                                    api_item_property_update(
988
                                        $this->course,
989
                                        TOOL_CALENDAR_EVENT,
990
                                        $id,
991
                                        'visible',
992
                                        $authorId,
993
                                        $groupInfo,
994
                                        $userId,
995
                                        $start,
996
                                        $end,
997
                                        $this->sessionId
998
                                    );
999
                                }
1000
                            }
1001
1002
                            // Delete users.
1003
                            if (!empty($usersToDelete)) {
1004
                                foreach ($usersToDelete as $userId) {
1005
                                    api_item_property_delete(
1006
                                        $this->course,
1007
                                        TOOL_CALENDAR_EVENT,
1008
                                        $id,
1009
                                        $userId,
1010
                                        $groupInfo,
1011
                                        $this->sessionId
1012
                                    );
1013
                                }
1014
                            }
1015
                        }
1016
                    }
1017
1018
                    // Add announcement.
1019
                    if (isset($addAnnouncement) && !empty($addAnnouncement)) {
1020
                        $this->storeAgendaEventAsAnnouncement(
1021
                            $id,
1022
                            $usersToSend
1023
                        );
1024
                    }
1025
1026
                    // Add attachment.
1027
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
1028
                        $counter = 0;
1029
                        foreach ($attachmentArray as $attachmentItem) {
1030
                            $this->updateAttachment(
1031
                                $attachmentItem['id'],
1032
                                $id,
1033
                                $attachmentItem,
1034
                                $attachmentCommentList[$counter],
1035
                                $this->course
1036
                            );
1037
                            $counter++;
1038
                        }
1039
                    }
1040
1041
                    return true;
1042
                } else {
1043
                    return false;
1044
                }
1045
                break;
1046
            case 'admin':
1047
            case 'platform':
1048
                if (api_is_platform_admin()) {
1049
                    $attributes = [
1050
                        'title' => $title,
1051
                        'start_date' => $start,
1052
                        'end_date' => $end,
1053
                        'all_day' => $allDay,
1054
                    ];
1055
1056
                    if ($updateContent) {
1057
                        $attributes['content'] = $content;
1058
                    }
1059
                    Database::update(
1060
                        $this->tbl_global_agenda,
1061
                        $attributes,
1062
                        ['id = ?' => $id]
1063
                    );
1064
                }
1065
                break;
1066
        }
1067
    }
1068
1069
    /**
1070
     * @param int  $id
1071
     * @param bool $deleteAllItemsFromSerie
1072
     */
1073
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
1074
    {
1075
        switch ($this->type) {
1076
            case 'personal':
1077
                $eventInfo = $this->get_event($id);
1078
                if ($eventInfo['user'] == api_get_user_id()) {
1079
                    Database::delete(
1080
                        $this->tbl_personal_agenda,
1081
                        ['id = ?' => $id]
1082
                    );
1083
                }
1084
                break;
1085
            case 'course':
1086
                $courseId = api_get_course_int_id();
1087
                $sessionId = api_get_session_id();
1088
                $isAllowToEdit = api_is_allowed_to_edit(null, true);
1089
1090
                if (false == $isAllowToEdit && !empty($sessionId)) {
1091
                    $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
1092
                    if ($allowDhrToEdit) {
1093
                        $isHrm = SessionManager::isUserSubscribedAsHRM(
1094
                            $sessionId,
1095
                            api_get_user_id()
1096
                        );
1097
                        if ($isHrm) {
1098
                            $isAllowToEdit = true;
1099
                        }
1100
                    }
1101
                }
1102
1103
                if (!empty($courseId) && $isAllowToEdit) {
1104
                    // Delete
1105
                    $eventInfo = $this->get_event($id);
1106
                    if ($deleteAllItemsFromSerie) {
1107
                        /* This is one of the children.
1108
                           Getting siblings and delete 'Em all + the father! */
1109
                        if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
1110
                            // Removing items.
1111
                            $events = $this->getAllRepeatEvents($eventInfo['parent_event_id']);
1112
                            if (!empty($events)) {
1113
                                foreach ($events as $event) {
1114
                                    $this->deleteEvent($event['id']);
1115
                                }
1116
                            }
1117
                            // Removing parent.
1118
                            $this->deleteEvent($eventInfo['parent_event_id']);
1119
                        } else {
1120
                            // This is the father looking for the children.
1121
                            $events = $this->getAllRepeatEvents($id);
1122
                            if (!empty($events)) {
1123
                                foreach ($events as $event) {
1124
                                    $this->deleteEvent($event['id']);
1125
                                }
1126
                            }
1127
                        }
1128
                    }
1129
1130
                    $repo = Container::getCalendarEventRepository();
1131
                    $event = $repo->find($id);
1132
1133
                    if ($event) {
1134
                        $repo->getEntityManager()->remove($event);
1135
                        $repo->getEntityManager()->flush();
1136
1137
                        // Removing from events.
1138
                        /*Database::delete(
1139
                            $this->tbl_course_agenda,
1140
                            ['id = ? AND c_id = ?' => [$id, $courseId]]
1141
                        );*/
1142
1143
                        /*api_item_property_update(
1144
                            $this->course,
1145
                            TOOL_CALENDAR_EVENT,
1146
                            $id,
1147
                            'delete',
1148
                            api_get_user_id()
1149
                        );*/
1150
1151
                        // Removing from series.
1152
                        Database::delete(
1153
                            $this->table_repeat,
1154
                            [
1155
                                'cal_id = ? AND c_id = ?' => [
1156
                                    $id,
1157
                                    $courseId,
1158
                                ],
1159
                            ]
1160
                        );
1161
                        // Attachments are already deleted using the doctrine remove() function.
1162
                        /*if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
1163
                            foreach ($eventInfo['attachment'] as $attachment) {
1164
                                self::deleteAttachmentFile(
1165
                                    $attachment['id'],
1166
                                    $this->course
1167
                                );
1168
                            }
1169
                        }*/
1170
                    }
1171
                }
1172
                break;
1173
            case 'admin':
1174
                if (api_is_platform_admin()) {
1175
                    Database::delete(
1176
                        $this->tbl_global_agenda,
1177
                        ['id = ?' => $id]
1178
                    );
1179
                }
1180
                break;
1181
        }
1182
    }
1183
1184
    /**
1185
     * Get agenda events.
1186
     *
1187
     * @param int    $start
1188
     * @param int    $end
1189
     * @param int    $courseId
1190
     * @param int    $groupId
1191
     * @param int    $user_id
1192
     * @param string $format
1193
     *
1194
     * @return array|string
1195
     */
1196
    public function getEvents(
1197
        $start,
1198
        $end,
1199
        $courseId = null,
1200
        $groupId = null,
1201
        $user_id = 0,
1202
        $format = 'json'
1203
    ) {
1204
        switch ($this->type) {
1205
            case 'admin':
1206
                $this->getPlatformEvents($start, $end);
1207
                break;
1208
            case 'course':
1209
                $courseInfo = api_get_course_info_by_id($courseId);
1210
1211
                // Session coach can see all events inside a session.
1212
                if (api_is_coach()) {
1213
                    // Own course
1214
                    $this->getCourseEvents(
1215
                        $start,
1216
                        $end,
1217
                        $courseInfo,
1218
                        $groupId,
1219
                        $this->sessionId,
1220
                        $user_id
1221
                    );
1222
1223
                    // Others
1224
                    $this->getSessionEvents(
1225
                        $start,
1226
                        $end,
1227
                        $this->sessionId,
1228
                        $user_id,
1229
                        $this->eventOtherSessionColor
1230
                    );
1231
                } else {
1232
                    $this->getCourseEvents(
1233
                        $start,
1234
                        $end,
1235
                        $courseInfo,
1236
                        $groupId,
1237
                        $this->sessionId,
1238
                        $user_id
1239
                    );
1240
                }
1241
                break;
1242
            case 'personal':
1243
            default:
1244
                $sessionFilterActive = false;
1245
                if (!empty($this->sessionId)) {
1246
                    $sessionFilterActive = true;
1247
                }
1248
1249
                if (false == $sessionFilterActive) {
1250
                    // Getting personal events
1251
                    $this->getPersonalEvents($start, $end);
1252
1253
                    // Getting platform/admin events
1254
                    $this->getPlatformEvents($start, $end);
1255
                }
1256
1257
                $ignoreVisibility = api_get_configuration_value('personal_agenda_show_all_session_events');
1258
1259
                // Getting course events
1260
                $my_course_list = [];
1261
                if (!api_is_anonymous()) {
1262
                    $session_list = SessionManager::get_sessions_by_user(
1263
                        api_get_user_id(),
1264
                        $ignoreVisibility
1265
                    );
1266
                    $my_course_list = CourseManager::get_courses_list_by_user_id(
1267
                        api_get_user_id(),
1268
                        false
1269
                    );
1270
                }
1271
1272
                if (api_is_drh()) {
1273
                    if (api_drh_can_access_all_session_content()) {
1274
                        $session_list = [];
1275
                        $sessionList = SessionManager::get_sessions_followed_by_drh(
1276
                            api_get_user_id(),
1277
                            null,
1278
                            null,
1279
                            null,
1280
                            true,
1281
                            false
1282
                        );
1283
1284
                        if (!empty($sessionList)) {
1285
                            foreach ($sessionList as $sessionItem) {
1286
                                $sessionId = $sessionItem['id'];
1287
                                $courses = SessionManager::get_course_list_by_session_id(
1288
                                    $sessionId
1289
                                );
1290
                                $sessionInfo = [
1291
                                    'session_id' => $sessionId,
1292
                                    'courses' => $courses,
1293
                                ];
1294
                                $session_list[] = $sessionInfo;
1295
                            }
1296
                        }
1297
                    }
1298
                }
1299
1300
                if (!empty($session_list)) {
1301
                    foreach ($session_list as $session_item) {
1302
                        if ($sessionFilterActive) {
1303
                            if ($this->sessionId != $session_item['session_id']) {
1304
                                continue;
1305
                            }
1306
                        }
1307
1308
                        $my_courses = $session_item['courses'];
1309
                        $my_session_id = $session_item['session_id'];
1310
1311
                        if (!empty($my_courses)) {
1312
                            foreach ($my_courses as $course_item) {
1313
                                $courseInfo = api_get_course_info_by_id(
1314
                                    $course_item['real_id']
1315
                                );
1316
                                $this->getCourseEvents(
1317
                                    $start,
1318
                                    $end,
1319
                                    $courseInfo,
1320
                                    0,
1321
                                    $my_session_id
1322
                                );
1323
                            }
1324
                        }
1325
                    }
1326
                }
1327
1328
                if (!empty($my_course_list) && false == $sessionFilterActive) {
1329
                    foreach ($my_course_list as $courseInfoItem) {
1330
                        $courseInfo = api_get_course_info_by_id(
1331
                            $courseInfoItem['real_id']
1332
                        );
1333
                        if (isset($courseId) && !empty($courseId)) {
1334
                            if ($courseInfo['real_id'] == $courseId) {
1335
                                $this->getCourseEvents(
1336
                                    $start,
1337
                                    $end,
1338
                                    $courseInfo,
1339
                                    0,
1340
                                    0,
1341
                                    $user_id
1342
                                );
1343
                            }
1344
                        } else {
1345
                            $this->getCourseEvents(
1346
                                $start,
1347
                                $end,
1348
                                $courseInfo,
1349
                                0,
1350
                                0,
1351
                                $user_id
1352
                            );
1353
                        }
1354
                    }
1355
                }
1356
                break;
1357
        }
1358
1359
        $this->cleanEvents();
1360
1361
        switch ($format) {
1362
            case 'json':
1363
                if (empty($this->events)) {
1364
                    return '[]';
1365
                }
1366
1367
                return json_encode($this->events);
1368
                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...
1369
            case 'array':
1370
                if (empty($this->events)) {
1371
                    return [];
1372
                }
1373
1374
                return $this->events;
1375
                break;
1376
        }
1377
    }
1378
1379
    /**
1380
     * Clean events.
1381
     *
1382
     * @return bool
1383
     */
1384
    public function cleanEvents()
1385
    {
1386
        if (empty($this->events)) {
1387
            return false;
1388
        }
1389
1390
        foreach ($this->events as &$event) {
1391
            $event['description'] = Security::remove_XSS($event['description']);
1392
            $event['title'] = Security::remove_XSS($event['title']);
1393
        }
1394
1395
        return true;
1396
    }
1397
1398
    /**
1399
     * @param int $id
1400
     * @param int $minute_delta
1401
     *
1402
     * @return int
1403
     */
1404
    public function resizeEvent($id, $minute_delta)
1405
    {
1406
        $id = (int) $id;
1407
        $delta = (int) $minute_delta;
1408
        $event = $this->get_event($id);
1409
        if (!empty($event)) {
1410
            switch ($this->type) {
1411
                case 'personal':
1412
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1413
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1414
							WHERE id = ".$id;
1415
                    Database::query($sql);
1416
                    break;
1417
                case 'course':
1418
                    $sql = "UPDATE $this->tbl_course_agenda SET
1419
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1420
							WHERE
1421
							    c_id = ".$this->course['real_id']." AND
1422
							    id = ".$id;
1423
                    Database::query($sql);
1424
                    break;
1425
                case 'admin':
1426
                    $sql = "UPDATE $this->tbl_global_agenda SET
1427
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1428
							WHERE id = ".$id;
1429
                    Database::query($sql);
1430
                    break;
1431
            }
1432
        }
1433
1434
        return 1;
1435
    }
1436
1437
    /**
1438
     * @param int $id
1439
     * @param int $minute_delta minutes
1440
     * @param int $allDay
1441
     *
1442
     * @return int
1443
     */
1444
    public function move_event($id, $minute_delta, $allDay)
1445
    {
1446
        $id = (int) $id;
1447
        $event = $this->get_event($id);
1448
1449
        if (empty($event)) {
1450
            return false;
1451
        }
1452
1453
        // we convert the hour delta into minutes and add the minute delta
1454
        $delta = (int) $minute_delta;
1455
        $allDay = (int) $allDay;
1456
1457
        if (!empty($event)) {
1458
            switch ($this->type) {
1459
                case 'personal':
1460
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1461
                            all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
1462
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1463
							WHERE id=".$id;
1464
                    Database::query($sql);
1465
                    break;
1466
                case 'course':
1467
                    $sql = "UPDATE $this->tbl_course_agenda SET
1468
                            all_day = $allDay,
1469
                            start_date = DATE_ADD(start_date, INTERVAL $delta MINUTE),
1470
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1471
							WHERE
1472
							    c_id = ".$this->course['real_id']." AND
1473
							    id=".$id;
1474
                    Database::query($sql);
1475
                    break;
1476
                case 'admin':
1477
                    $sql = "UPDATE $this->tbl_global_agenda SET
1478
                            all_day = $allDay,
1479
                            start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1480
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1481
							WHERE id=".$id;
1482
                    Database::query($sql);
1483
                    break;
1484
            }
1485
        }
1486
1487
        return 1;
1488
    }
1489
1490
    /**
1491
     * Gets a single event.
1492
     *
1493
     * @param int $id event id
1494
     *
1495
     * @return array
1496
     */
1497
    public function get_event($id)
1498
    {
1499
        // make sure events of the personal agenda can only be seen by the user himself
1500
        $id = (int) $id;
1501
        $event = null;
1502
        switch ($this->type) {
1503
            case 'personal':
1504
                $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1505
                        WHERE id = $id AND user = ".api_get_user_id();
1506
                $result = Database::query($sql);
1507
                if (Database::num_rows($result)) {
1508
                    $event = Database::fetch_array($result, 'ASSOC');
1509
                    $event['description'] = $event['text'];
1510
                    $event['content'] = $event['text'];
1511
                    $event['start_date'] = $event['date'];
1512
                    $event['end_date'] = $event['enddate'];
1513
                }
1514
                break;
1515
            case 'course':
1516
                if (!empty($this->course['real_id'])) {
1517
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
1518
                            WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
1519
                    $result = Database::query($sql);
1520
                    if (Database::num_rows($result)) {
1521
                        $event = Database::fetch_array($result, 'ASSOC');
1522
                        $event['description'] = $event['content'];
1523
1524
                        // Getting send to array
1525
                        $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
1526
                            $id,
1527
                            $this->course['real_id'],
1528
                            $this->sessionId
1529
                        );
1530
1531
                        // Getting repeat info
1532
                        $event['repeat_info'] = $this->getRepeatedInfoByEvent(
1533
                            $id,
1534
                            $this->course['real_id']
1535
                        );
1536
1537
                        if (!empty($event['parent_event_id'])) {
1538
                            $event['parent_info'] = $this->get_event(
1539
                                $event['parent_event_id']
1540
                            );
1541
                        }
1542
1543
                        $event['attachment'] = $this->getAttachmentList($id, $this->course);
1544
                    }
1545
                }
1546
                break;
1547
            case 'admin':
1548
            case 'platform':
1549
                $sql = "SELECT * FROM ".$this->tbl_global_agenda."
1550
                        WHERE id = $id";
1551
                $result = Database::query($sql);
1552
                if (Database::num_rows($result)) {
1553
                    $event = Database::fetch_array($result, 'ASSOC');
1554
                    $event['description'] = $event['content'];
1555
                }
1556
                break;
1557
        }
1558
1559
        return $event;
1560
    }
1561
1562
    /**
1563
     * Gets personal events.
1564
     *
1565
     * @param int $start
1566
     * @param int $end
1567
     *
1568
     * @return array
1569
     */
1570
    public function getPersonalEvents($start, $end)
1571
    {
1572
        $start = (int) $start;
1573
        $end = (int) $end;
1574
        $startCondition = '';
1575
        $endCondition = '';
1576
1577
        if (0 !== $start) {
1578
            $startCondition = "AND date >= '".api_get_utc_datetime($start)."'";
1579
        }
1580
        if (0 !== $start) {
1581
            $endCondition = "AND (enddate <= '".api_get_utc_datetime($end)."' OR enddate IS NULL)";
1582
        }
1583
        $user_id = api_get_user_id();
1584
1585
        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1586
                WHERE user = $user_id $startCondition $endCondition";
1587
1588
        $result = Database::query($sql);
1589
        $my_events = [];
1590
        if (Database::num_rows($result)) {
1591
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1592
                $event = [];
1593
                $event['id'] = 'personal_'.$row['id'];
1594
                $event['title'] = $row['title'];
1595
                $event['className'] = 'personal';
1596
                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
1597
                $event['editable'] = true;
1598
                $event['sent_to'] = get_lang('Me');
1599
                $event['type'] = 'personal';
1600
1601
                if (!empty($row['date'])) {
1602
                    $event['start'] = $this->formatEventDate($row['date']);
1603
                    $event['start_date_localtime'] = api_get_local_time($row['date']);
1604
                }
1605
1606
                if (!empty($row['enddate'])) {
1607
                    $event['end'] = $this->formatEventDate($row['enddate']);
1608
                    $event['end_date_localtime'] = api_get_local_time($row['enddate']);
1609
                }
1610
1611
                $event['description'] = $row['text'];
1612
                $event['allDay'] = isset($row['all_day']) && 1 == $row['all_day'] ? $row['all_day'] : 0;
1613
                $event['parent_event_id'] = 0;
1614
                $event['has_children'] = 0;
1615
1616
                $my_events[] = $event;
1617
                $this->events[] = $event;
1618
            }
1619
        }
1620
1621
        // Add plugin personal events
1622
        $this->plugin = new AppPlugin();
1623
        $plugins = $this->plugin->getInstalledPluginListObject();
1624
        /** @var Plugin $plugin */
1625
        foreach ($plugins as $plugin) {
1626
            if ($plugin->hasPersonalEvents && method_exists($plugin, 'getPersonalEvents')) {
1627
                $pluginEvents = $plugin->getPersonalEvents($this, $start, $end);
1628
1629
                if (!empty($pluginEvents)) {
1630
                    $this->events = array_merge($this->events, $pluginEvents);
1631
                }
1632
            }
1633
        }
1634
1635
        return $my_events;
1636
    }
1637
1638
    /**
1639
     * Get user/group list per event.
1640
     *
1641
     * @param int $eventId
1642
     * @param int $courseId
1643
     * @param int $sessionId
1644
     * @paraù int $sessionId
1645
     *
1646
     * @return array
1647
     */
1648
    public function getUsersAndGroupSubscribedToEvent(
1649
        $eventId,
1650
        $courseId,
1651
        $sessionId
1652
    ) {
1653
        $eventId = (int) $eventId;
1654
        $courseId = (int) $courseId;
1655
        $sessionId = (int) $sessionId;
1656
1657
        $repo = Container::getCalendarEventRepository();
1658
        /** @var CCalendarEvent $event */
1659
        $event = $repo->find($eventId);
1660
1661
        if (null === $event) {
1662
            return [];
1663
        }
1664
1665
        $course = api_get_course_entity($courseId);
1666
        $session = api_get_session_entity($sessionId);
1667
1668
        $users = [];
1669
        $groups = [];
1670
        $everyone = false;
1671
        $links = $event->getResourceNode()->getResourceLinks();
1672
        foreach ($links as $link) {
1673
            if ($link->getUser()) {
1674
                $users[] = $link->getUser()->getId();
1675
            }
1676
            if ($link->getGroup()) {
1677
                $groups[] = $link->getGroup()->getId();
1678
            }
1679
        }
1680
1681
        if (empty($users) && empty($groups)) {
1682
            $everyone = true;
1683
        }
1684
1685
        return [
1686
            'everyone' => $everyone,
1687
            'users' => $users,
1688
            'groups' => $groups,
1689
        ];
1690
1691
        exit;
0 ignored issues
show
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...
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...
1692
1693
        $sessionCondition = "ip.session_id = $sessionId";
1694
        if (empty($sessionId)) {
1695
            $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
1696
        }
1697
1698
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1699
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1700
1701
        // Get sent_tos
1702
        $sql = "SELECT DISTINCT to_user_id, to_group_id
1703
                FROM $tbl_property ip
1704
                INNER JOIN $tlb_course_agenda agenda
1705
                ON (
1706
                  ip.ref = agenda.id AND
1707
                  ip.c_id = agenda.c_id AND
1708
                  ip.tool = '".TOOL_CALENDAR_EVENT."'
1709
                )
1710
                WHERE
1711
                    ref = $eventId AND
1712
                    ip.visibility = '1' AND
1713
                    ip.c_id = $courseId AND
1714
                    $sessionCondition
1715
                ";
1716
1717
        $result = Database::query($sql);
1718
        $users = [];
1719
        $groups = [];
1720
        $everyone = false;
1721
1722
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1723
            if (!empty($row['to_group_id'])) {
1724
                $groups[] = $row['to_group_id'];
1725
            }
1726
            if (!empty($row['to_user_id'])) {
1727
                $users[] = $row['to_user_id'];
1728
            }
1729
1730
            if (empty($groups) && empty($users)) {
1731
                if (0 == $row['to_group_id']) {
1732
                    $everyone = true;
1733
                }
1734
            }
1735
        }
1736
1737
        return [
1738
            'everyone' => $everyone,
1739
            'users' => $users,
1740
            'groups' => $groups,
1741
        ];
1742
    }
1743
1744
    /**
1745
     * @param int    $start
1746
     * @param int    $end
1747
     * @param int    $sessionId
1748
     * @param int    $userId
1749
     * @param string $color
1750
     *
1751
     * @return array
1752
     */
1753
    public function getSessionEvents(
1754
        $start,
1755
        $end,
1756
        $sessionId = 0,
1757
        $userId = 0,
1758
        $color = ''
1759
    ) {
1760
        $courses = SessionManager::get_course_list_by_session_id($sessionId);
1761
1762
        if (!empty($courses)) {
1763
            foreach ($courses as $course) {
1764
                $this->getCourseEvents(
1765
                    $start,
1766
                    $end,
1767
                    $course,
1768
                    0,
1769
                    $sessionId,
1770
                    0,
1771
                    $color
1772
                );
1773
            }
1774
        }
1775
    }
1776
1777
    /**
1778
     * @param int    $start
1779
     * @param int    $end
1780
     * @param array  $courseInfo
1781
     * @param int    $groupId
1782
     * @param int    $sessionId
1783
     * @param int    $user_id
1784
     * @param string $color
1785
     *
1786
     * @return array
1787
     */
1788
    public function getCourseEvents(
1789
        $start,
1790
        $end,
1791
        $courseInfo,
1792
        $groupId = 0,
1793
        $sessionId = 0,
1794
        $user_id = 0,
1795
        $color = ''
1796
    ) {
1797
        $start = (int) $start;
1798
        $end = (int) $end;
1799
1800
        $start = !empty($start) ? api_get_utc_datetime($start) : null;
1801
        $end = !empty($end) ? api_get_utc_datetime($end) : null;
1802
1803
        if (empty($courseInfo)) {
1804
            return [];
1805
        }
1806
1807
        $courseId = $courseInfo['real_id'];
1808
1809
        if (empty($courseId)) {
1810
            return [];
1811
        }
1812
1813
        $userId = api_get_user_id();
1814
        $sessionId = (int) $sessionId;
1815
        $user_id = (int) $user_id;
1816
1817
        $groupList = GroupManager::get_group_list(
1818
            null,
1819
            $courseInfo,
1820
            null,
1821
            $sessionId
1822
        );
1823
1824
        $groupNameList = [];
1825
        if (!empty($groupList)) {
1826
            foreach ($groupList as $group) {
1827
                $groupNameList[$group['iid']] = $group['name'];
1828
            }
1829
        }
1830
1831
        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
1832
            $isAllowToEdit = true;
1833
        } else {
1834
            $isAllowToEdit = CourseManager::is_course_teacher(
1835
                $userId,
1836
                $courseInfo['code']
1837
            );
1838
        }
1839
1840
        $isAllowToEditByHrm = false;
1841
        if (!empty($sessionId)) {
1842
            $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
1843
            if ($allowDhrToEdit) {
1844
                $isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, $userId);
1845
                if ($isHrm) {
1846
                    $isAllowToEdit = $isAllowToEditByHrm = true;
1847
                }
1848
            }
1849
        }
1850
1851
        $groupMemberships = [];
1852
        if (!empty($groupId)) {
1853
            $groupMemberships = [$groupId];
1854
        } else {
1855
            if ($isAllowToEdit) {
1856
                if (!empty($groupList)) {
1857
                    // c_item_property.to_group_id field was migrated to use
1858
                    // c_group_info.iid
1859
                    $groupMemberships = array_column($groupList, 'iid');
1860
                }
1861
            } else {
1862
                // get only related groups from user
1863
                $groupMemberships = GroupManager::get_group_ids($courseId, $userId);
1864
            }
1865
        }
1866
1867
        $repo = Container::getCalendarEventRepository();
1868
        $courseEntity = api_get_course_entity($courseId);
1869
        $session = api_get_session_entity($sessionId);
1870
        $qb = $repo->getResourcesByCourseOnly($courseEntity, $courseEntity->getResourceNode());
1871
        $userCondition = '';
1872
1873
        if ($isAllowToEdit) {
1874
            // No group filter was asked
1875
            if (empty($groupId)) {
1876
                if (empty($user_id)) {
1877
                    // Show all events not added in group
1878
                    $userCondition = ' (links.group IS NULL) ';
1879
                    // admin see only his stuff
1880
                    if ('personal' === $this->type) {
1881
                        $userCondition = " (links.user = ".api_get_user_id()." AND (links.group IS NULL) ";
1882
                        //$userCondition = " (ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ) ";
1883
                        $userCondition .= " OR ( (links.user IS NULL)  AND (links.group IS NULL ))) ";
1884
                        //$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) ) ";
1885
                    }
1886
1887
                    if (!empty($groupMemberships)) {
1888
                        // Show events sent to selected groups
1889
                        $userCondition .= " OR (links.user IS NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1890
                    }
1891
                } else {
1892
                    // Show events of requested user in no group
1893
                    $userCondition = " (links.user = $user_id AND links.group IS NULL) ";
1894
                    // Show events sent to selected groups
1895
                    if (!empty($groupMemberships)) {
1896
                        $userCondition .= " OR (links.user = $user_id) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1897
                    }
1898
                }
1899
            } else {
1900
                // Show only selected groups (depending of user status)
1901
                $userCondition = " (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1902
1903
                if (!empty($groupMemberships)) {
1904
                    // Show send to $user_id in selected groups
1905
                    $userCondition .= " OR (links.user = $user_id) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1906
                }
1907
            }
1908
        } else {
1909
            // No group filter was asked
1910
            if (empty($groupId)) {
1911
                // Show events sent to everyone and no group
1912
                $userCondition = ' ( (links.user is NULL) AND (links.group IS NULL) ';
1913
                // Show events sent to selected groups
1914
                if (!empty($groupMemberships)) {
1915
                    $userCondition .= " OR (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships)."))) ";
1916
                } else {
1917
                    $userCondition .= " ) ";
1918
                }
1919
                $userCondition .= " OR (links.user = ".api_get_user_id()." AND (links.group IS NULL )) ";
1920
            } else {
1921
                if (!empty($groupMemberships)) {
1922
                    // Show send to everyone - and only selected groups
1923
                    $userCondition = " (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1924
                }
1925
            }
1926
1927
            // Show sent to only me and no group
1928
            if (!empty($groupMemberships)) {
1929
                $userCondition .= " OR (links.user = ".api_get_user_id().") AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1930
            }
1931
        }
1932
1933
        if (!empty($userCondition)) {
1934
            $qb->andWhere($userCondition);
1935
        }
1936
1937
        /*if (!empty($groupMemberships)) {
1938
            $orX = $qb->expr()->orX();
1939
            foreach ($groupMemberships as $groupId) {
1940
                $group = api_get_group_entity($groupId);
1941
                $orX->add("links.group = :group$groupId");
1942
                $qb->setParameter("group$groupId", $group);
1943
            }
1944
            $qb->andWhere($orX);
1945
        }*/
1946
1947
        //$dateCondition = '';
1948
        if (!empty($start) && !empty($end)) {
1949
            $qb->andWhere(
1950
                $qb->expr()->orX(
1951
                    'resource.startDate BETWEEN :start AND :end',
1952
                    'resource.endDate BETWEEN :start AND :end',
1953
                    $qb->expr()->orX(
1954
                        'resource.startDate IS NOT NULL AND resource.endDate IS NOT NULL AND
1955
                            YEAR(resource.startDate) = YEAR(resource.endDate) AND
1956
                            MONTH(:start) BETWEEN MONTH(resource.startDate) AND MONTH(resource.endDate)
1957
                        '
1958
                    )
1959
                )
1960
            )
1961
            ->setParameter('start', $start)
1962
            ->setParameter('end', $end);
1963
1964
            /*
1965
            $dateCondition .= "AND (
1966
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1967
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1968
                 (
1969
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1970
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1971
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1972
                 )
1973
            )";*/
1974
        }
1975
1976
        /*
1977
        if (empty($sessionId)) {
1978
            $sessionCondition = "
1979
            (
1980
                agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
1981
            ) ";
1982
        } else {
1983
            $sessionCondition = "
1984
            (
1985
                agenda.session_id = $sessionId AND
1986
                ip.session_id = $sessionId
1987
            ) ";
1988
        }
1989
1990
        if (api_is_allowed_to_edit()) {
1991
            $visibilityCondition = " (ip.visibility IN ('1', '0'))  ";
1992
        } else {
1993
            $visibilityCondition = " (ip.visibility = '1') ";
1994
        }
1995
1996
        $sql = "SELECT DISTINCT
1997
                    agenda.*,
1998
                    ip.visibility,
1999
                    ip.to_group_id,
2000
                    ip.insert_user_id,
2001
                    ip.ref,
2002
                    to_user_id
2003
                FROM $tlb_course_agenda agenda
2004
                INNER JOIN $tbl_property ip
2005
                ON (
2006
                    agenda.id = ip.ref AND
2007
                    agenda.c_id = ip.c_id AND
2008
                    ip.tool = '".TOOL_CALENDAR_EVENT."'
2009
                )
2010
                WHERE
2011
                    $sessionCondition AND
2012
                    ($userCondition) AND
2013
                    $visibilityCondition AND
2014
                    agenda.c_id = $courseId
2015
        ";
2016
        $dateCondition = '';
2017
        if (!empty($start) && !empty($end)) {
2018
            $dateCondition .= "AND (
2019
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
2020
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
2021
                 (
2022
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
2023
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
2024
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
2025
                 )
2026
            )";
2027
        }
2028
2029
        $sql .= $dateCondition;
2030
        $result = Database::query($sql);*/
2031
        $coachCanEdit = false;
2032
        if (!empty($sessionId)) {
2033
            $coachCanEdit = api_is_coach($sessionId, $courseId) || api_is_platform_admin();
2034
        }
2035
        //var_dump($groupMemberships, $courseId);        echo $qb->getQuery()->getSQL();exit;
2036
        $events = $qb->getQuery()->getResult();
2037
        //$eventsAdded = array_column($this->events, 'unique_id');
2038
        /** @var CCalendarEvent $row */
2039
        foreach ($events as $row) {
2040
            $eventId = $row->getIid();
2041
            $event = [];
2042
            $event['id'] = 'course_'.$eventId;
2043
            $event['unique_id'] = $eventId;
2044
            // To avoid doubles
2045
            /*if (in_array($event['unique_id'], $eventsAdded)) {
2046
                continue;
2047
            }*/
2048
2049
            $eventsAdded[] = $eventId;
2050
            //$eventId = $row['ref'];
2051
            /*$items = $this->getUsersAndGroupSubscribedToEvent(
2052
                $eventId,
2053
                $courseId,
2054
                $this->sessionId
2055
            );
2056
            $group_to_array = $items['groups'];
2057
            $user_to_array = $items['users'];*/
2058
            /*$attachmentList = $this->getAttachmentList(
2059
                $eventId,
2060
                $courseInfo
2061
            );*/
2062
            $attachmentList = $row->getAttachments();
2063
            $event['attachment'] = '';
2064
            if (!empty($attachmentList)) {
2065
                $icon = Display::returnFontAwesomeIcon(
2066
                    'paperclip',
2067
                    '1'
2068
                );
2069
                $repo = Container::getCalendarEventAttachmentRepository();
2070
                foreach ($attachmentList as $attachment) {
2071
                    //$url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$courseId.'&'.api_get_cidreq();
2072
                    $url = $repo->getResourceFileDownloadUrl($attachment);
2073
                    $event['attachment'] .= $icon.
2074
                        Display::url(
2075
                            $attachment->getFilename(),
2076
                            $url
2077
                        ).'<br />';
2078
                }
2079
            }
2080
2081
            $event['title'] = $row->getTitle();
2082
            $event['className'] = 'course';
2083
            $event['allDay'] = 'false';
2084
            $event['course_id'] = $courseId;
2085
            $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
2086
2087
            $sessionInfo = [];
2088
            if (!empty($row->getSessionId())) {
2089
                $sessionInfo = api_get_session_info($row->getSessionId());
2090
                $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
2091
            }
2092
2093
            $event['session_name'] = $sessionInfo['name'] ?? '';
2094
            $event['course_name'] = $courseInfo['title'] ?? '';
2095
2096
            /*if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
2097
                $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
2098
            }*/
2099
2100
            if (!empty($color)) {
2101
                $event['borderColor'] = $event['backgroundColor'] = $color;
2102
            }
2103
2104
            if ($row->getColor()) {
2105
                $event['borderColor'] = $event['backgroundColor'] = $row->getColor();
2106
            }
2107
2108
            $event['editable'] = false;
2109
            if ($this->getIsAllowedToEdit() && 'course' === $this->type) {
2110
                $event['editable'] = true;
2111
                if (!empty($sessionId)) {
2112
                    if (false == $coachCanEdit) {
2113
                        $event['editable'] = false;
2114
                    }
2115
                    if ($isAllowToEditByHrm) {
2116
                        $event['editable'] = true;
2117
                    }
2118
                }
2119
                // if user is author then he can edit the item
2120
                if (api_get_user_id() == $row->getResourceNode()->getCreator()->getId()) {
2121
                    $event['editable'] = true;
2122
                }
2123
            }
2124
2125
            if (!empty($row->getStartDate())) {
2126
                $event['start'] = $this->formatEventDate($row->getStartDate()->format('Y-m-d H:i:s'));
2127
                $event['start_date_localtime'] = api_get_local_time($row->getStartDate()->format('Y-m-d H:i:s'));
2128
            }
2129
            if (!empty($row->getEndDate())) {
2130
                $event['end'] = $this->formatEventDate($row->getEndDate()->format('Y-m-d H:i:s'));
2131
                $event['end_date_localtime'] = api_get_local_time($row->getEndDate()->format('Y-m-d H:i:s'));
2132
            }
2133
2134
            $event['sent_to'] = '';
2135
            $event['type'] = 'course';
2136
            if (0 != $row->getSessionId()) {
2137
                $event['type'] = 'session';
2138
            }
2139
2140
            // Event Sent to a group?
2141
            /*if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
2142
                $sent_to = [];
2143
                if (!empty($group_to_array)) {
2144
                    foreach ($group_to_array as $group_item) {
2145
                        $sent_to[] = $groupNameList[$group_item];
2146
                    }
2147
                }
2148
                $sent_to = implode('@@', $sent_to);
2149
                $sent_to = str_replace(
2150
                    '@@',
2151
                    '</div><div class="label_tag notice">',
2152
                    $sent_to
2153
                );
2154
                $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
2155
                $event['type'] = 'group';
2156
            }*/
2157
2158
            // Event sent to a user?
2159
            /*if (isset($row['to_user_id'])) {
2160
                $sent_to = [];
2161
                if (!empty($user_to_array)) {
2162
                    foreach ($user_to_array as $item) {
2163
                        $user_info = api_get_user_info($item);
2164
                        // Add username as tooltip for $event['sent_to'] - ref #4226
2165
                        $username = api_htmlentities(
2166
                            sprintf(
2167
                                get_lang('Login: %s'),
2168
                                $user_info['username']
2169
                            ),
2170
                            ENT_QUOTES
2171
                        );
2172
                        $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
2173
                    }
2174
                }
2175
                $sent_to = implode('@@', $sent_to);
2176
                $sent_to = str_replace(
2177
                    '@@',
2178
                    '</div><div class="label_tag notice">',
2179
                    $sent_to
2180
                );
2181
                $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
2182
            }*/
2183
2184
            //Event sent to everyone!
2185
            /*if (empty($event['sent_to'])) {
2186
                $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
2187
            }*/
2188
            $event['description'] = $row->getContent();
2189
            $event['visibility'] = $row->isVisible($courseEntity, $session) ? 1 : 0;
2190
            $event['real_id'] = $eventId;
2191
            $event['allDay'] = $row->getAllDay();
2192
            $event['parent_event_id'] = $row->getParentEventId();
2193
            $event['has_children'] = $this->hasChildren($eventId, $courseId) ? 1 : 0;
2194
            $event['comment'] = $row->getComment();
2195
            $this->events[] = $event;
2196
        }
2197
2198
        return $this->events;
2199
    }
2200
2201
    /**
2202
     * @param int $start tms
2203
     * @param int $end   tms
2204
     *
2205
     * @return array
2206
     */
2207
    public function getPlatformEvents($start, $end)
2208
    {
2209
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
2210
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
2211
        $dateCondition = '';
2212
2213
        if (!empty($start) && !empty($end)) {
2214
            $dateCondition .= "AND (
2215
                 start_date BETWEEN '".$start."' AND '".$end."' OR
2216
                 end_date BETWEEN '".$start."' AND '".$end."' OR
2217
                 (
2218
                     start_date IS NOT NULL AND end_date IS NOT NULL AND
2219
                     YEAR(start_date) = YEAR(end_date) AND
2220
                     MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
2221
                 )
2222
            )";
2223
        }
2224
2225
        $access_url_id = api_get_current_access_url_id();
2226
2227
        $sql = "SELECT *
2228
                FROM ".$this->tbl_global_agenda."
2229
                WHERE access_url_id = $access_url_id
2230
                $dateCondition";
2231
        $result = Database::query($sql);
2232
        $my_events = [];
2233
        if (Database::num_rows($result)) {
2234
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2235
                $event = [];
2236
                $event['id'] = 'platform_'.$row['id'];
2237
                $event['title'] = $row['title'];
2238
                $event['className'] = 'platform';
2239
                $event['allDay'] = 'false';
2240
                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
2241
                $event['editable'] = false;
2242
                $event['type'] = 'admin';
2243
2244
                if (api_is_platform_admin() && 'admin' === $this->type) {
2245
                    $event['editable'] = true;
2246
                }
2247
2248
                if (!empty($row['start_date'])) {
2249
                    $event['start'] = $this->formatEventDate($row['start_date']);
2250
                    $event['start_date_localtime'] = api_get_local_time($row['start_date']);
2251
                }
2252
2253
                if (!empty($row['end_date'])) {
2254
                    $event['end'] = $this->formatEventDate($row['end_date']);
2255
                    $event['end_date_localtime'] = api_get_local_time($row['end_date']);
2256
                }
2257
                $event['allDay'] = isset($row['all_day']) && 1 == $row['all_day'] ? $row['all_day'] : 0;
2258
                $event['parent_event_id'] = 0;
2259
                $event['has_children'] = 0;
2260
                $event['description'] = $row['content'];
2261
2262
                $my_events[] = $event;
2263
                $this->events[] = $event;
2264
            }
2265
        }
2266
2267
        return $my_events;
2268
    }
2269
2270
    /**
2271
     * @param FormValidator $form
2272
     * @param array         $groupList
2273
     * @param array         $userList
2274
     * @param array         $sendTo               array('users' => [1, 2], 'groups' => [3, 4])
2275
     * @param array         $attributes
2276
     * @param bool          $addOnlyItemsInSendTo
2277
     * @param bool          $required
2278
     */
2279
    public function setSendToSelect(
2280
        $form,
2281
        $groupList = [],
2282
        $userList = [],
2283
        $sendTo = [],
2284
        $attributes = [],
2285
        $addOnlyItemsInSendTo = false,
2286
        $required = false
2287
    ) {
2288
        $params = [
2289
            'id' => 'users_to_send_id',
2290
            'data-placeholder' => get_lang('Select'),
2291
            'multiple' => 'multiple',
2292
            'class' => 'multiple-select',
2293
        ];
2294
2295
        if (!empty($attributes)) {
2296
            $params = array_merge($params, $attributes);
2297
            if (empty($params['multiple'])) {
2298
                unset($params['multiple']);
2299
            }
2300
        }
2301
2302
        $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : [];
2303
        $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : [];
2304
2305
        /** @var HTML_QuickForm_select $select */
2306
        $select = $form->addSelect(
2307
            'users_to_send',
2308
            get_lang('To'),
2309
            null,
2310
            $params
2311
        );
2312
2313
        if ($required) {
2314
            $form->setRequired($select);
2315
        }
2316
2317
        $selectedEveryoneOptions = [];
2318
        if (isset($sendTo['everyone']) && $sendTo['everyone']) {
2319
            $selectedEveryoneOptions = ['selected'];
2320
            $sendToUsers = [];
2321
        }
2322
2323
        $select->addOption(
2324
            get_lang('Everyone'),
2325
            'everyone',
2326
            $selectedEveryoneOptions
2327
        );
2328
2329
        $options = [];
2330
        if (is_array($groupList)) {
2331
            foreach ($groupList as $group) {
2332
                $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
2333
                $count_users = " &ndash; $count_users ".get_lang('Users');
2334
                $option = [
2335
                    'text' => $group['name'].$count_users,
2336
                    'value' => "GROUP:".$group['id'],
2337
                ];
2338
                $selected = in_array(
2339
                    $group['id'],
2340
                    $sendToGroups
2341
                ) ? true : false;
2342
                if ($selected) {
2343
                    $option['selected'] = 'selected';
2344
                }
2345
2346
                if ($addOnlyItemsInSendTo) {
2347
                    if ($selected) {
2348
                        $options[] = $option;
2349
                    }
2350
                } else {
2351
                    $options[] = $option;
2352
                }
2353
            }
2354
            $select->addOptGroup($options, get_lang('Groups'));
2355
        }
2356
2357
        // adding the individual users to the select form
2358
        if (is_array($userList)) {
2359
            $options = [];
2360
            foreach ($userList as $user) {
2361
                if (ANONYMOUS == $user['status']) {
2362
                    continue;
2363
                }
2364
                $option = [
2365
                    'text' => api_get_person_name(
2366
                            $user['firstname'],
2367
                            $user['lastname']
2368
                        ).' ('.$user['username'].')',
2369
                    'value' => "USER:".$user['user_id'],
2370
                ];
2371
2372
                $selected = in_array(
2373
                    $user['user_id'],
2374
                    $sendToUsers
2375
                ) ? true : false;
2376
2377
                if ($selected) {
2378
                    $option['selected'] = 'selected';
2379
                }
2380
2381
                if ($addOnlyItemsInSendTo) {
2382
                    if ($selected) {
2383
                        $options[] = $option;
2384
                    }
2385
                } else {
2386
                    $options[] = $option;
2387
                }
2388
            }
2389
2390
            $select->addOptGroup($options, get_lang('Users'));
2391
        }
2392
    }
2393
2394
    /**
2395
     * Separates the users and groups array
2396
     * users have a value USER:XXX (with XXX the user id
2397
     * groups have a value GROUP:YYY (with YYY the group id)
2398
     * use the 'everyone' key.
2399
     *
2400
     * @author Julio Montoya based in separate_users_groups in agenda.inc.php
2401
     *
2402
     * @param array $to
2403
     *
2404
     * @return array
2405
     */
2406
    public function parseSendToArray($to)
2407
    {
2408
        $groupList = [];
2409
        $userList = [];
2410
        $sendTo = null;
2411
2412
        $sendTo['everyone'] = false;
2413
        if (is_array($to) && count($to) > 0) {
2414
            foreach ($to as $item) {
2415
                if ('everyone' == $item) {
2416
                    $sendTo['everyone'] = true;
2417
                } else {
2418
                    list($type, $id) = explode(':', $item);
2419
                    switch ($type) {
2420
                        case 'GROUP':
2421
                            $groupList[] = $id;
2422
                            break;
2423
                        case 'USER':
2424
                            $userList[] = $id;
2425
                            break;
2426
                    }
2427
                }
2428
            }
2429
            $sendTo['groups'] = $groupList;
2430
            $sendTo['users'] = $userList;
2431
        }
2432
2433
        return $sendTo;
2434
    }
2435
2436
    /**
2437
     * @param array $params
2438
     *
2439
     * @return FormValidator
2440
     */
2441
    public function getForm($params = [])
2442
    {
2443
        $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
2444
        $id = isset($params['id']) ? (int) $params['id'] : 0;
2445
2446
        $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
2447
        if ('course' == $this->type) {
2448
            $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
2449
        }
2450
2451
        $form = new FormValidator(
2452
            'add_event',
2453
            'post',
2454
            $url,
2455
            null,
2456
            ['enctype' => 'multipart/form-data']
2457
        );
2458
2459
        $idAttach = isset($params['id_attach']) ? (int) $params['id_attach'] : null;
2460
        $groupId = api_get_group_id();
2461
        $form_Title = get_lang('Add event to agenda');
2462
        if (!empty($id)) {
2463
            $form_Title = get_lang('Edit event');
2464
        }
2465
2466
        $form->addHeader($form_Title);
2467
        $form->addElement('hidden', 'id', $id);
2468
        $form->addElement('hidden', 'action', $action);
2469
        $form->addElement('hidden', 'id_attach', $idAttach);
2470
2471
        $isSubEventEdition = false;
2472
        $isParentFromSerie = false;
2473
        $showAttachmentForm = true;
2474
2475
        if ('course' == $this->type) {
2476
            // Edition mode.
2477
            if (!empty($id)) {
2478
                $showAttachmentForm = false;
2479
                if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
2480
                    $isSubEventEdition = true;
2481
                }
2482
                if (!empty($params['repeat_info'])) {
2483
                    $isParentFromSerie = true;
2484
                }
2485
            }
2486
        }
2487
2488
        if ($isSubEventEdition) {
2489
            $form->addElement(
2490
                'label',
2491
                null,
2492
                Display::return_message(
2493
                    get_lang('Editing this event will remove it from the serie of events it is currently part of'),
2494
                    'warning'
2495
                )
2496
            );
2497
        }
2498
2499
        $form->addElement('text', 'title', get_lang('Event name'));
2500
2501
        if (isset($groupId) && !empty($groupId)) {
2502
            $form->addElement(
2503
                'hidden',
2504
                'users_to_send[]',
2505
                "GROUP:$groupId"
2506
            );
2507
            $form->addElement('hidden', 'to', 'true');
2508
        } else {
2509
            $sendTo = isset($params['send_to']) ? $params['send_to'] : ['everyone' => true];
2510
            if ('course' == $this->type) {
2511
                $this->showToForm($form, $sendTo, [], false, true);
2512
            }
2513
        }
2514
2515
        $form->addDateRangePicker(
2516
            'date_range',
2517
            get_lang('Date range'),
2518
            false,
2519
            ['id' => 'date_range']
2520
        );
2521
        $form->addElement('checkbox', 'all_day', null, get_lang('All day'));
2522
2523
        if ('course' == $this->type) {
2524
            $repeat = $form->addElement(
2525
                'checkbox',
2526
                'repeat',
2527
                null,
2528
                get_lang('Repeat event'),
2529
                ['onclick' => 'return plus_repeated_event();']
2530
            );
2531
            $form->addElement(
2532
                'html',
2533
                '<div id="options2" style="display:none">'
2534
            );
2535
            $form->addElement(
2536
                'select',
2537
                'repeat_type',
2538
                get_lang('Repeat type'),
2539
                self::getRepeatTypes()
2540
            );
2541
            $form->addElement(
2542
                'date_picker',
2543
                'repeat_end_day',
2544
                get_lang('Repeat end date'),
2545
                ['id' => 'repeat_end_date_form']
2546
            );
2547
2548
            if ($isSubEventEdition || $isParentFromSerie) {
2549
                $repeatInfo = $params['repeat_info'];
2550
                if ($isSubEventEdition) {
2551
                    $parentEvent = $params['parent_info'];
2552
                    $repeatInfo = $parentEvent['repeat_info'];
2553
                }
2554
                $params['repeat'] = 1;
2555
                $params['repeat_type'] = $repeatInfo['cal_type'];
2556
                $params['repeat_end_day'] = substr(
2557
                    api_get_local_time($repeatInfo['cal_end']),
2558
                    0,
2559
                    10
2560
                );
2561
2562
                $form->freeze(['repeat_type', 'repeat_end_day']);
2563
                $repeat->_attributes['disabled'] = 'disabled';
2564
            }
2565
            $form->addElement('html', '</div>');
2566
        }
2567
2568
        if (!empty($id)) {
2569
            if (empty($params['end_date'])) {
2570
                $params['date_range'] = $params['end_date'];
2571
            }
2572
2573
            $params['date_range'] =
2574
                substr(api_get_local_time($params['start_date']), 0, 16).' / '.
2575
                substr(api_get_local_time($params['end_date']), 0, 16);
2576
        }
2577
2578
        $toolbar = 'Agenda';
2579
        if (!api_is_allowed_to_edit(null, true)) {
2580
            $toolbar = 'AgendaStudent';
2581
        }
2582
2583
        $form->addElement(
2584
            'html_editor',
2585
            'content',
2586
            get_lang('Description'),
2587
            null,
2588
            [
2589
                'ToolbarSet' => $toolbar,
2590
                'Width' => '100%',
2591
                'Height' => '200',
2592
            ]
2593
        );
2594
2595
        if ('course' == $this->type) {
2596
            $form->addElement('textarea', 'comment', get_lang('Comment'));
2597
            $form->addLabel(
2598
                get_lang('Files attachments'),
2599
                '<div id="filepaths" class="file-upload-event">
2600
2601
                        <div id="filepath_1">
2602
                            <input type="file" name="attach_1"/>
2603
2604
                            <label>'.get_lang('Description').'</label>
2605
                            <input class="form-control" type="text" name="legend[]" />
2606
                        </div>
2607
2608
                    </div>'
2609
            );
2610
2611
            $form->addLabel(
2612
                '',
2613
                '<span id="link-more-attach">
2614
                    <a href="javascript://" onclick="return add_image_form()">'.
2615
                get_lang('Add one more file').'</a>
2616
                 </span>&nbsp;('.sprintf(
2617
                    get_lang('Maximun file size: %s'),
2618
                    format_file_size(
2619
                        api_get_setting('message_max_upload_filesize')
2620
                    )
2621
                ).')'
2622
            );
2623
2624
            if (isset($params['attachment']) && !empty($params['attachment'])) {
2625
                $attachmentList = $params['attachment'];
2626
                foreach ($attachmentList as $attachment) {
2627
                    $params['file_comment'] = $attachment['comment'];
2628
                    if (!empty($attachment['path'])) {
2629
                        $form->addElement(
2630
                            'checkbox',
2631
                            'delete_attachment['.$attachment['id'].']',
2632
                            null,
2633
                            get_lang(
2634
                                'DeleteAttachment'
2635
                            ).': '.$attachment['filename']
2636
                        );
2637
                    }
2638
                }
2639
            }
2640
2641
            $form->addElement(
2642
                'textarea',
2643
                'file_comment',
2644
                get_lang('File comment')
2645
            );
2646
        }
2647
2648
        if (empty($id)) {
2649
            $form->addElement(
2650
                'checkbox',
2651
                'add_announcement',
2652
                null,
2653
                get_lang('Add an announcement').'&nbsp('.get_lang('Send mail').')'
2654
            );
2655
        }
2656
2657
        if ($id) {
2658
            $form->addButtonUpdate(get_lang('Edit event'));
2659
        } else {
2660
            $form->addButtonSave(get_lang('Add event'));
2661
        }
2662
2663
        $form->setDefaults($params);
2664
        $form->addRule(
2665
            'date_range',
2666
            get_lang('Required field'),
2667
            'required'
2668
        );
2669
        $form->addRule('title', get_lang('Required field'), 'required');
2670
2671
        return $form;
2672
    }
2673
2674
    /**
2675
     * @param FormValidator $form
2676
     * @param array         $sendTo               array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
2677
     * @param array         $attributes
2678
     * @param bool          $addOnlyItemsInSendTo
2679
     * @param bool          $required
2680
     *
2681
     * @return bool
2682
     */
2683
    public function showToForm(
2684
        $form,
2685
        $sendTo = [],
2686
        $attributes = [],
2687
        $addOnlyItemsInSendTo = false,
2688
        $required = false
2689
    ) {
2690
        if ('course' != $this->type) {
2691
            return false;
2692
        }
2693
2694
        $order = 'lastname';
2695
        if (api_is_western_name_order()) {
2696
            $order = 'firstname';
2697
        }
2698
2699
        $userList = CourseManager::get_user_list_from_course_code(
2700
            api_get_course_id(),
2701
            $this->sessionId,
2702
            null,
2703
            $order
2704
        );
2705
2706
        $groupList = CourseManager::get_group_list_of_course(
2707
            api_get_course_id(),
2708
            $this->sessionId
2709
        );
2710
2711
        $this->setSendToSelect(
2712
            $form,
2713
            $groupList,
2714
            $userList,
2715
            $sendTo,
2716
            $attributes,
2717
            $addOnlyItemsInSendTo,
2718
            $required
2719
        );
2720
2721
        return true;
2722
    }
2723
2724
    /**
2725
     * @param int   $id
2726
     * @param int   $visibility 0= invisible, 1 visible
2727
     * @param array $courseInfo
2728
     * @param int   $userId
2729
     */
2730
    public static function changeVisibility(
2731
        $id,
2732
        $visibility,
2733
        $courseInfo,
2734
        $userId = null
2735
    ) {
2736
        $id = (int) $id;
2737
2738
        $repo = Container::getCalendarEventRepository();
2739
        /** @var CCalendarEvent $event */
2740
        $event = $repo->find($id);
2741
        $visibility = (int) $visibility;
2742
2743
        if ($event) {
2744
            if (0 === $visibility) {
2745
                $repo->setVisibilityDraft($event);
2746
            } else {
2747
                $repo->setVisibilityPublished($event);
2748
            }
2749
        }
2750
2751
        return true;
2752
2753
        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...
2754
            $userId = api_get_user_id();
2755
        } else {
2756
            $userId = (int) $userId;
2757
        }
2758
2759
        if (0 === $visibility) {
2760
            api_item_property_update(
2761
                $courseInfo,
2762
                TOOL_CALENDAR_EVENT,
2763
                $id,
2764
                'invisible',
2765
                $userId
2766
            );
2767
        } else {
2768
            api_item_property_update(
2769
                $courseInfo,
2770
                TOOL_CALENDAR_EVENT,
2771
                $id,
2772
                'visible',
2773
                $userId
2774
            );
2775
        }
2776
    }
2777
2778
    /**
2779
     * Get repeat types.
2780
     */
2781
    public static function getRepeatTypes(): array
2782
    {
2783
        return [
2784
            'daily' => get_lang('Daily'),
2785
            'weekly' => get_lang('Weekly'),
2786
            'monthlyByDate' => get_lang('Monthly, by date'),
2787
            //monthlyByDay"> get_lang('Monthly, by day');
2788
            //monthlyByDayR' => get_lang('Monthly, by dayR'),
2789
            'yearly' => get_lang('Yearly'),
2790
        ];
2791
    }
2792
2793
    /**
2794
     * Show a list with all the attachments according to the post's id.
2795
     *
2796
     * @param int   $eventId
2797
     * @param array $courseInfo
2798
     *
2799
     * @return array with the post info
2800
     */
2801
    public function getAttachmentList($eventId, $courseInfo)
2802
    {
2803
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2804
        $courseId = (int) $courseInfo['real_id'];
2805
        $eventId = (int) $eventId;
2806
2807
        $sql = "SELECT id, path, filename, comment
2808
                FROM $tableAttachment
2809
                WHERE
2810
                    c_id = $courseId AND
2811
                    agenda_id = $eventId";
2812
        $result = Database::query($sql);
2813
        $list = [];
2814
        if (0 != Database::num_rows($result)) {
2815
            $list = Database::store_result($result, 'ASSOC');
2816
        }
2817
2818
        return $list;
2819
    }
2820
2821
    /**
2822
     * Show a list with all the attachments according to the post's id.
2823
     *
2824
     * @param int   $attachmentId
2825
     * @param int   $eventId
2826
     * @param array $courseInfo
2827
     *
2828
     * @return array with the post info
2829
     */
2830
    public function getAttachment($attachmentId, $eventId, $courseInfo)
2831
    {
2832
        if (empty($courseInfo) || empty($attachmentId) || empty($eventId)) {
2833
            return [];
2834
        }
2835
2836
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2837
        $courseId = (int) $courseInfo['real_id'];
2838
        $eventId = (int) $eventId;
2839
        $attachmentId = (int) $attachmentId;
2840
2841
        $row = [];
2842
        $sql = "SELECT id, path, filename, comment
2843
                FROM $tableAttachment
2844
                WHERE
2845
                    c_id = $courseId AND
2846
                    agenda_id = $eventId AND
2847
                    id = $attachmentId
2848
                ";
2849
        $result = Database::query($sql);
2850
        if (0 != Database::num_rows($result)) {
2851
            $row = Database::fetch_array($result, 'ASSOC');
2852
        }
2853
2854
        return $row;
2855
    }
2856
2857
    /**
2858
     * Add an attachment file into agenda.
2859
     *
2860
     * @param CCalendarEvent $event
2861
     * @param UploadedFile   $file
2862
     * @param string         $comment
2863
     * @param array          $courseInfo
2864
     *
2865
     * @return string
2866
     */
2867
    public function addAttachment(
2868
        $event,
2869
        $file,
2870
        $comment,
2871
        $courseInfo
2872
    ) {
2873
        // Storing the attachments
2874
        $valid = false;
2875
        if ($file) {
2876
            $valid = process_uploaded_file($file);
2877
        }
2878
2879
        if ($valid) {
2880
            /*$courseDir = $courseInfo['directory'].'/upload/calendar';
2881
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2882
            $uploadDir = $sys_course_path.$courseDir;*/
2883
2884
            // Try to add an extension to the file if it hasn't one
2885
            /*$new_file_name = add_ext_on_mime(
2886
                stripslashes($fileUserUpload['name']),
2887
                $fileUserUpload['type']
2888
            );*/
2889
2890
            // user's file name
2891
            $fileName = $file->getClientOriginalName();
2892
            $courseId = api_get_course_int_id();
2893
            /*$new_file_name = uniqid('');
2894
            $new_path = $uploadDir.'/'.$new_file_name;
2895
            $result = @move_uploaded_file(
2896
                $fileUserUpload['tmp_name'],
2897
                $new_path
2898
            );
2899
            $courseId = api_get_course_int_id();
2900
            $size = intval($fileUserUpload['size']);*/
2901
            // Storing the attachments if any
2902
            //if ($result) {
2903
            $attachment = new CCalendarEventAttachment();
2904
            $attachment
2905
                ->setCId($courseId)
2906
                ->setFilename($fileName)
2907
                ->setComment($comment)
2908
                ->setPath($fileName)
2909
                ->setEvent($event)
2910
                ->setSize($file->getSize())
2911
            ;
2912
2913
            $repo = Container::getCalendarEventAttachmentRepository();
2914
2915
            $repo->addResourceToCourseWithParent(
2916
                $attachment,
2917
                $event->getResourceNode(),
2918
                ResourceLink::VISIBILITY_PUBLISHED,
2919
                api_get_user_entity(api_get_user_id()),
2920
                api_get_course_entity(),
2921
                api_get_session_entity(),
2922
                api_get_group_entity(),
2923
                $file
2924
            );
2925
2926
            $repo->getEntityManager()->flush();
2927
2928
            $id = $attachment->getIid();
2929
            if ($id) {
2930
                $table = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2931
                $sql = "UPDATE $table
2932
                        SET id = iid WHERE iid = $id";
2933
                Database::query($sql);
2934
2935
                /*api_item_property_update(
2936
                    $courseInfo,
2937
                    'calendar_event_attachment',
2938
                    $id,
2939
                    'AgendaAttachmentAdded',
2940
                    api_get_user_id()
2941
                );*/
2942
            }
2943
2944
        }
2945
    }
2946
2947
    /**
2948
     * @param int    $attachmentId
2949
     * @param int    $eventId
2950
     * @param array  $fileUserUpload
2951
     * @param string $comment
2952
     * @param array  $courseInfo
2953
     */
2954
    public function updateAttachment(
2955
        $attachmentId,
2956
        $eventId,
2957
        $fileUserUpload,
2958
        $comment,
2959
        $courseInfo
2960
    ) {
2961
        $attachment = $this->getAttachment(
2962
            $attachmentId,
2963
            $eventId,
2964
            $courseInfo
2965
        );
2966
        if (!empty($attachment)) {
2967
            $this->deleteAttachmentFile($attachmentId, $courseInfo);
2968
        }
2969
        $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
2970
    }
2971
2972
    /**
2973
     * This function delete a attachment file by id.
2974
     *
2975
     * @param int   $attachmentId
2976
     * @param array $courseInfo
2977
     *
2978
     * @return string
2979
     */
2980
    public function deleteAttachmentFile($attachmentId, $courseInfo)
2981
    {
2982
        $table = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2983
        $attachmentId = (int) $attachmentId;
2984
        $courseId = $courseInfo['real_id'];
2985
2986
        if (empty($courseId) || empty($attachmentId)) {
2987
            return false;
2988
        }
2989
2990
        $sql = "DELETE FROM $table
2991
                WHERE c_id = $courseId AND id = ".$attachmentId;
2992
        $result = Database::query($sql);
2993
2994
        // update item_property
2995
        api_item_property_update(
2996
            $courseInfo,
2997
            'calendar_event_attachment',
2998
            $attachmentId,
2999
            'AgendaAttachmentDeleted',
3000
            api_get_user_id()
3001
        );
3002
3003
        if (!empty($result)) {
3004
            return Display::return_message(
3005
                get_lang("The attached file has been deleted"),
3006
                'confirmation'
3007
            );
3008
        }
3009
    }
3010
3011
    /**
3012
     * @param int $eventId
3013
     *
3014
     * @return array
3015
     */
3016
    public function getAllRepeatEvents($eventId)
3017
    {
3018
        $events = [];
3019
        $eventId = (int) $eventId;
3020
3021
        switch ($this->type) {
3022
            case 'personal':
3023
                break;
3024
            case 'course':
3025
                if (!empty($this->course['real_id'])) {
3026
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
3027
                            WHERE
3028
                                c_id = ".$this->course['real_id']." AND
3029
                                parent_event_id = ".$eventId;
3030
                    $result = Database::query($sql);
3031
                    if (Database::num_rows($result)) {
3032
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
3033
                            $events[] = $row;
3034
                        }
3035
                    }
3036
                }
3037
                break;
3038
        }
3039
3040
        return $events;
3041
    }
3042
3043
    /**
3044
     * @param int $eventId
3045
     * @param int $courseId
3046
     *
3047
     * @return bool
3048
     */
3049
    public function hasChildren($eventId, $courseId)
3050
    {
3051
        $eventId = (int) $eventId;
3052
        $courseId = (int) $courseId;
3053
3054
        $sql = "SELECT count(DISTINCT(id)) as count
3055
                FROM ".$this->tbl_course_agenda."
3056
                WHERE
3057
                    c_id = $courseId AND
3058
                    parent_event_id = $eventId";
3059
        $result = Database::query($sql);
3060
        if (Database::num_rows($result)) {
3061
            $row = Database::fetch_array($result, 'ASSOC');
3062
3063
            return $row['count'] > 0;
3064
        }
3065
3066
        return false;
3067
    }
3068
3069
    /**
3070
     * @param int    $filter
3071
     * @param string $view
3072
     *
3073
     * @return string
3074
     */
3075
    public function displayActions($view, $filter = 0)
3076
    {
3077
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
3078
        $groupIid = isset($groupInfo['iid']) ? $groupInfo['iid'] : 0;
3079
3080
        $codePath = api_get_path(WEB_CODE_PATH);
3081
3082
        $currentUserId = api_get_user_id();
3083
        $cidReq = api_get_cidreq();
3084
3085
        $actionsLeft = '';
3086
        $actionsLeft .= Display::url(
3087
            Display::return_icon('calendar.png', get_lang('Calendar'), [], ICON_SIZE_MEDIUM),
3088
            $codePath."calendar/agenda_js.php?type={$this->type}&$cidReq"
3089
        );
3090
        $actionsLeft .= Display::url(
3091
            Display::return_icon('week.png', get_lang('Agenda list'), [], ICON_SIZE_MEDIUM),
3092
            $codePath."calendar/agenda_list.php?type={$this->type}&$cidReq"
3093
        );
3094
3095
        $form = '';
3096
        if (api_is_allowed_to_edit(false, true) ||
3097
            ('1' == api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) &&
3098
            api_is_allowed_to_session_edit(false, true)
3099
            || (
3100
                GroupManager::user_has_access($currentUserId, $groupIid, GroupManager::GROUP_TOOL_CALENDAR)
3101
                && GroupManager::is_tutor_of_group($currentUserId, $groupInfo)
3102
            )
3103
        ) {
3104
            $actionsLeft .= Display::url(
3105
                Display::return_icon('new_event.png', get_lang('Add event'), [], ICON_SIZE_MEDIUM),
3106
                $codePath."calendar/agenda.php?action=add&type={$this->type}&$cidReq"
3107
            );
3108
3109
            $actionsLeft .= Display::url(
3110
                Display::return_icon('import_calendar.png', get_lang('Outlook import'), [], ICON_SIZE_MEDIUM),
3111
                $codePath."calendar/agenda.php?action=importical&type={$this->type}&$cidReq"
3112
            );
3113
3114
            if ('course' === $this->type) {
3115
                if (!isset($_GET['action'])) {
3116
                    $form = new FormValidator(
3117
                        'form-search',
3118
                        'post',
3119
                        '',
3120
                        '',
3121
                        [],
3122
                        FormValidator::LAYOUT_INLINE
3123
                    );
3124
                    $attributes = [
3125
                        'multiple' => false,
3126
                        'id' => 'select_form_id_search',
3127
                    ];
3128
                    $selectedValues = $this->parseAgendaFilter($filter);
3129
                    $this->showToForm($form, $selectedValues, $attributes);
3130
                    $form = $form->returnForm();
3131
                }
3132
            }
3133
        }
3134
3135
        if ('personal' == $this->type && !api_is_anonymous()) {
3136
            $actionsLeft .= Display::url(
3137
                Display::return_icon('1day.png', get_lang('Sessions plan calendar'), [], ICON_SIZE_MEDIUM),
3138
                $codePath."calendar/planification.php"
3139
            );
3140
        }
3141
3142
        if (api_is_platform_admin() ||
3143
            api_is_teacher() ||
3144
            api_is_student_boss() ||
3145
            api_is_drh() ||
3146
            api_is_session_admin() ||
3147
            api_is_coach()
3148
        ) {
3149
            if ('personal' == $this->type) {
3150
                $form = null;
3151
                if (!isset($_GET['action'])) {
3152
                    $form = new FormValidator(
3153
                        'form-search',
3154
                        'get',
3155
                        api_get_self().'?type=personal&',
3156
                        '',
3157
                        [],
3158
                        FormValidator::LAYOUT_INLINE
3159
                    );
3160
3161
                    $sessions = [];
3162
3163
                    if (api_is_drh()) {
3164
                        $sessionList = SessionManager::get_sessions_followed_by_drh($currentUserId);
3165
                        if (!empty($sessionList)) {
3166
                            foreach ($sessionList as $sessionItem) {
3167
                                $sessions[$sessionItem['id']] = strip_tags($sessionItem['name']);
3168
                            }
3169
                        }
3170
                    } else {
3171
                        $sessions = SessionManager::get_sessions_by_user($currentUserId);
3172
                        $sessions = array_column($sessions, 'session_name', 'session_id');
3173
                    }
3174
3175
                    $form->addHidden('type', 'personal');
3176
                    $sessions = ['0' => get_lang('Please select an option')] + $sessions;
3177
3178
                    $form->addSelect(
3179
                        'session_id',
3180
                        get_lang('Session'),
3181
                        $sessions,
3182
                        ['id' => 'session_id', 'onchange' => 'submit();']
3183
                    );
3184
3185
                    $form->addButtonReset(get_lang('Reset'));
3186
                    $form = $form->returnForm();
3187
                }
3188
            }
3189
        }
3190
3191
        $actionsRight = '';
3192
        if ('calendar' == $view) {
3193
            $actionsRight .= $form;
3194
        }
3195
3196
        $toolbar = Display::toolbarAction(
3197
            'toolbar-agenda',
3198
            [$actionsLeft, $actionsRight]
3199
        );
3200
3201
        return $toolbar;
3202
    }
3203
3204
    /**
3205
     * @return FormValidator
3206
     */
3207
    public function getImportCalendarForm()
3208
    {
3209
        $form = new FormValidator(
3210
            'frm_import_ical',
3211
            'post',
3212
            api_get_self().'?action=importical&type='.$this->type,
3213
            ['enctype' => 'multipart/form-data']
3214
        );
3215
        $form->addHeader(get_lang('Outlook import'));
3216
        $form->addElement('file', 'ical_import', get_lang('Outlook import'));
3217
        $form->addRule(
3218
            'ical_import',
3219
            get_lang('Required field'),
3220
            'required'
3221
        );
3222
        $form->addButtonImport(get_lang('Import'), 'ical_submit');
3223
3224
        return $form;
3225
    }
3226
3227
    /**
3228
     * @param array $courseInfo
3229
     * @param $file
3230
     *
3231
     * @return false|string
3232
     */
3233
    public function importEventFile($courseInfo, $file)
3234
    {
3235
        $charset = api_get_system_encoding();
3236
        $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
3237
        $messages = [];
3238
3239
        if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
3240
            error_log(
3241
                'Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__
3242
            );
3243
3244
            return false;
3245
        }
3246
3247
        $data = file_get_contents($filepath);
3248
3249
        $trans = [
3250
            'DAILY' => 'daily',
3251
            'WEEKLY' => 'weekly',
3252
            'MONTHLY' => 'monthlyByDate',
3253
            'YEARLY' => 'yearly',
3254
        ];
3255
        $sentTo = ['everyone' => true];
3256
        $calendar = Sabre\VObject\Reader::read($data);
3257
        $currentTimeZone = api_get_timezone();
3258
        if (!empty($calendar->VEVENT)) {
3259
            foreach ($calendar->VEVENT as $event) {
3260
                $start = $event->DTSTART->getDateTime();
3261
                $end = $event->DTEND->getDateTime();
3262
                //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
3263
3264
                $startDateTime = api_get_local_time(
3265
                    $start->format('Y-m-d H:i:s'),
3266
                    $currentTimeZone,
3267
                    $start->format('e')
3268
                );
3269
                $endDateTime = api_get_local_time(
3270
                    $end->format('Y-m-d H:i'),
3271
                    $currentTimeZone,
3272
                    $end->format('e')
3273
                );
3274
                $title = api_convert_encoding(
3275
                    (string) $event->summary,
3276
                    $charset,
3277
                    'UTF-8'
3278
                );
3279
                $description = api_convert_encoding(
3280
                    (string) $event->description,
3281
                    $charset,
3282
                    'UTF-8'
3283
                );
3284
3285
                $id = $this->addEvent(
3286
                    $startDateTime,
3287
                    $endDateTime,
3288
                    'false',
3289
                    $title,
3290
                    $description,
3291
                    $sentTo
3292
                );
3293
3294
                $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
3295
3296
                //$attendee = (string)$event->attendee;
3297
                /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
3298
                $repeat = $event->RRULE;
3299
                if ($id && !empty($repeat)) {
3300
                    $repeat = $repeat->getParts();
3301
                    $freq = $trans[$repeat['FREQ']];
3302
3303
                    if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
3304
                        // Check if datetime or just date (strlen == 8)
3305
                        if (8 == strlen($repeat['UNTIL'])) {
3306
                            // Fix the datetime format to avoid exception in the next step
3307
                            $repeat['UNTIL'] .= 'T000000';
3308
                        }
3309
                        $until = Sabre\VObject\DateTimeParser::parseDateTime(
3310
                            $repeat['UNTIL'],
3311
                            new DateTimeZone($currentTimeZone)
3312
                        );
3313
                        $until = $until->format('Y-m-d H:i:s');
3314
                        $this->addRepeatedItem(
3315
                            $id,
3316
                            $freq,
3317
                            $until,
3318
                            $sentTo
3319
                        );
3320
                    }
3321
                }
3322
            }
3323
        }
3324
3325
        if (!empty($messages)) {
3326
            $messages = implode('<br /> ', $messages);
3327
        } else {
3328
            $messages = get_lang('There are no events');
3329
        }
3330
3331
        return $messages;
3332
    }
3333
3334
    /**
3335
     * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]].
3336
     *
3337
     * @param int $filter
3338
     *
3339
     * @return array
3340
     */
3341
    public function parseAgendaFilter($filter)
3342
    {
3343
        $everyone = false;
3344
        $groupId = null;
3345
        $userId = null;
3346
3347
        if ('everyone' === $filter) {
3348
            $everyone = true;
3349
        } else {
3350
            if ('G' === substr($filter, 0, 1)) {
3351
                $groupId = str_replace('GROUP:', '', $filter);
3352
            } else {
3353
                $userId = str_replace('USER:', '', $filter);
3354
            }
3355
        }
3356
        if (empty($userId) && empty($groupId)) {
3357
            $everyone = true;
3358
        }
3359
3360
        return [
3361
            'everyone' => $everyone,
3362
            'users' => [$userId],
3363
            'groups' => [$groupId],
3364
        ];
3365
    }
3366
3367
    /**
3368
     *    This function retrieves all the agenda items of all the courses the user is subscribed to.
3369
     */
3370
    public static function get_myagendaitems(
3371
        $user_id,
3372
        $courses_dbs,
3373
        $month,
3374
        $year
3375
    ) {
3376
        $user_id = (int) $user_id;
3377
3378
        $items = [];
3379
        $my_list = [];
3380
3381
        // get agenda-items for every course
3382
        foreach ($courses_dbs as $key => $array_course_info) {
3383
            //databases of the courses
3384
            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
3385
            $TABLE_ITEMPROPERTY = Database::get_course_table(
3386
                TABLE_ITEM_PROPERTY
3387
            );
3388
3389
            $group_memberships = GroupManager::get_group_ids(
3390
                $array_course_info['real_id'],
3391
                $user_id
3392
            );
3393
            $course_user_status = CourseManager::getUserInCourseStatus(
3394
                $user_id,
3395
                $array_course_info['real_id']
3396
            );
3397
            // if the user is administrator of that course we show all the agenda items
3398
            if ('1' == $course_user_status) {
3399
                //echo "course admin";
3400
                $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3401
							FROM ".$TABLEAGENDA." agenda,
3402
								 ".$TABLE_ITEMPROPERTY." ip
3403
							WHERE agenda.id = ip.ref
3404
							AND MONTH(agenda.start_date)='".$month."'
3405
							AND YEAR(agenda.start_date)='".$year."'
3406
							AND ip.tool='".TOOL_CALENDAR_EVENT."'
3407
							AND ip.visibility='1'
3408
							GROUP BY agenda.id
3409
							ORDER BY start_date ";
3410
            } else {
3411
                // if the user is not an administrator of that course
3412
                if (is_array($group_memberships) && count(
3413
                        $group_memberships
3414
                    ) > 0
3415
                ) {
3416
                    $sqlquery = "SELECT	agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3417
								FROM ".$TABLEAGENDA." agenda,
3418
									".$TABLE_ITEMPROPERTY." ip
3419
								WHERE agenda.id = ip.ref
3420
								AND MONTH(agenda.start_date)='".$month."'
3421
								AND YEAR(agenda.start_date)='".$year."'
3422
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3423
								AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
3424
                            ", ",
3425
                            $group_memberships
3426
                        ).")) )
3427
								AND ip.visibility='1'
3428
								ORDER BY start_date ";
3429
                } else {
3430
                    $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3431
								FROM ".$TABLEAGENDA." agenda,
3432
									".$TABLE_ITEMPROPERTY." ip
3433
								WHERE agenda.id = ip.ref
3434
								AND MONTH(agenda.start_date)='".$month."'
3435
								AND YEAR(agenda.start_date)='".$year."'
3436
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3437
								AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
3438
								AND ip.visibility='1'
3439
								ORDER BY start_date ";
3440
                }
3441
            }
3442
            $result = Database::query($sqlquery);
3443
3444
            while ($item = Database::fetch_array($result, 'ASSOC')) {
3445
                $agendaday = -1;
3446
                if (!empty($item['start_date'])) {
3447
                    $item['start_date'] = api_get_local_time(
3448
                        $item['start_date']
3449
                    );
3450
                    $item['start_date_tms'] = api_strtotime(
3451
                        $item['start_date']
3452
                    );
3453
                    $agendaday = date("j", $item['start_date_tms']);
3454
                }
3455
                if (!empty($item['end_date'])) {
3456
                    $item['end_date'] = api_get_local_time($item['end_date']);
3457
                }
3458
3459
                $url = api_get_path(
3460
                        WEB_CODE_PATH
3461
                    )."calendar/agenda.php?cidReq=".urlencode(
3462
                        $array_course_info["code"]
3463
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
3464
3465
                $item['url'] = $url;
3466
                $item['course_name'] = $array_course_info['title'];
3467
                $item['calendar_type'] = 'course';
3468
                $item['course_id'] = $array_course_info['course_id'];
3469
3470
                $my_list[$agendaday][] = $item;
3471
            }
3472
        }
3473
3474
        // sorting by hour for every day
3475
        $agendaitems = [];
3476
        foreach ($items as $agendaday => $tmpitems) {
3477
            if (!isset($agendaitems[$agendaday])) {
3478
                $agendaitems[$agendaday] = '';
3479
            }
3480
            sort($tmpitems);
3481
            foreach ($tmpitems as $val) {
3482
                $agendaitems[$agendaday] .= $val;
3483
            }
3484
        }
3485
3486
        return $my_list;
3487
    }
3488
3489
    /**
3490
     * This function retrieves one personal agenda item returns it.
3491
     *
3492
     * @param    array    The array containing existing events. We add to this array.
3493
     * @param    int        Day
3494
     * @param    int        Month
3495
     * @param    int        Year (4 digits)
3496
     * @param    int        Week number
3497
     * @param    string    Type of view (month_view, week_view, day_view)
3498
     *
3499
     * @return array The results of the database query, or null if not found
3500
     */
3501
    public static function get_global_agenda_items(
3502
        $agendaitems,
3503
        $day = "",
3504
        $month = "",
3505
        $year = "",
3506
        $week = "",
3507
        $type
3508
    ) {
3509
        $tbl_global_agenda = Database::get_main_table(
3510
            TABLE_MAIN_SYSTEM_CALENDAR
3511
        );
3512
        $month = intval($month);
3513
        $year = intval($year);
3514
        $week = intval($week);
3515
        $day = intval($day);
3516
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3517
3518
        $current_access_url_id = api_get_current_access_url_id();
3519
3520
        if ("month_view" == $type or "" == $type) {
3521
            // We are in month view
3522
            $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";
3523
        }
3524
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3525
        if ("week_view" == $type) { // we are in week view
3526
            $start_end_day_of_week = self::calculate_start_end_of_week(
3527
                $week,
3528
                $year
3529
            );
3530
            $start_day = $start_end_day_of_week['start']['day'];
3531
            $start_month = $start_end_day_of_week['start']['month'];
3532
            $start_year = $start_end_day_of_week['start']['year'];
3533
            $end_day = $start_end_day_of_week['end']['day'];
3534
            $end_month = $start_end_day_of_week['end']['month'];
3535
            $end_year = $start_end_day_of_week['end']['year'];
3536
            // in sql statements you have to use year-month-day for date calculations
3537
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3538
            $start_filter = api_get_utc_datetime($start_filter);
3539
3540
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3541
            $end_filter = api_get_utc_datetime($end_filter);
3542
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND  access_url_id = $current_access_url_id ";
3543
        }
3544
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3545
        if ("day_view" == $type) { // we are in day view
3546
            // we could use mysql date() function but this is only available from 4.1 and higher
3547
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3548
            $start_filter = api_get_utc_datetime($start_filter);
3549
3550
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3551
            $end_filter = api_get_utc_datetime($end_filter);
3552
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'  AND  access_url_id = $current_access_url_id";
3553
        }
3554
3555
        $result = Database::query($sql);
3556
3557
        while ($item = Database::fetch_array($result)) {
3558
            if (!empty($item['start_date'])) {
3559
                $item['start_date'] = api_get_local_time($item['start_date']);
3560
                $item['start_date_tms'] = api_strtotime($item['start_date']);
3561
            }
3562
            if (!empty($item['end_date'])) {
3563
                $item['end_date'] = api_get_local_time($item['end_date']);
3564
            }
3565
3566
            // we break the date field in the database into a date and a time part
3567
            $agenda_db_date = explode(" ", $item['start_date']);
3568
            $date = $agenda_db_date[0];
3569
            $time = $agenda_db_date[1];
3570
            // we divide the date part into a day, a month and a year
3571
            $agendadate = explode("-", $date);
3572
            $year = intval($agendadate[0]);
3573
            $month = intval($agendadate[1]);
3574
            $day = intval($agendadate[2]);
3575
            // we divide the time part into hour, minutes, seconds
3576
            $agendatime = explode(":", $time);
3577
            $hour = $agendatime[0];
3578
            $minute = $agendatime[1];
3579
            $second = $agendatime[2];
3580
3581
            if ('month_view' == $type) {
3582
                $item['calendar_type'] = 'global';
3583
                $agendaitems[$day][] = $item;
3584
                continue;
3585
            }
3586
3587
            $start_time = api_format_date(
3588
                $item['start_date'],
3589
                TIME_NO_SEC_FORMAT
3590
            );
3591
            $end_time = '';
3592
            if (!empty($item['end_date'])) {
3593
                $end_time = ' - '.api_format_date(
3594
                        $item['end_date'],
3595
                        DATE_TIME_FORMAT_LONG
3596
                    );
3597
            }
3598
3599
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3600
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3601
            if ("day_view" !== $type) {
3602
                // This is the array construction for the WEEK or MONTH view
3603
                //Display the Agenda global in the tab agenda (administrator)
3604
                $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
3605
                $agendaitems[$day] .= "<b>".get_lang('Platform event')."</b>";
3606
                $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
3607
            } else {
3608
                // this is the array construction for the DAY view
3609
                $halfhour = 2 * $agendatime['0'];
3610
                if ($agendatime['1'] >= '30') {
3611
                    $halfhour = $halfhour + 1;
3612
                }
3613
                if (!is_array($agendaitems[$halfhour])) {
3614
                    $content = $agendaitems[$halfhour];
3615
                }
3616
                $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
3617
                        'Platform event'
3618
                    ).":  </b>".$item['title']."</div>";
3619
            }
3620
        }
3621
3622
        return $agendaitems;
3623
    }
3624
3625
    /**
3626
     * This function retrieves all the personal agenda items and add them to the agenda items found by the other
3627
     * functions.
3628
     */
3629
    public static function get_personal_agenda_items(
3630
        $user_id,
3631
        $agendaitems,
3632
        $day = "",
3633
        $month = "",
3634
        $year = "",
3635
        $week = "",
3636
        $type
3637
    ) {
3638
        $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
3639
        $user_id = intval($user_id);
3640
3641
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3642
        if ("month_view" == $type or "" == $type) {
3643
            // we are in month view
3644
            $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."'  ORDER BY date ASC";
3645
        }
3646
3647
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3648
        // we are in week view
3649
        if ("week_view" == $type) {
3650
            $start_end_day_of_week = self::calculate_start_end_of_week(
3651
                $week,
3652
                $year
3653
            );
3654
            $start_day = $start_end_day_of_week['start']['day'];
3655
            $start_month = $start_end_day_of_week['start']['month'];
3656
            $start_year = $start_end_day_of_week['start']['year'];
3657
            $end_day = $start_end_day_of_week['end']['day'];
3658
            $end_month = $start_end_day_of_week['end']['month'];
3659
            $end_year = $start_end_day_of_week['end']['year'];
3660
            // in sql statements you have to use year-month-day for date calculations
3661
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3662
            $start_filter = api_get_utc_datetime($start_filter);
3663
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3664
            $end_filter = api_get_utc_datetime($end_filter);
3665
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3666
        }
3667
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3668
        if ("day_view" == $type) {
3669
            // we are in day view
3670
            // we could use mysql date() function but this is only available from 4.1 and higher
3671
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3672
            $start_filter = api_get_utc_datetime($start_filter);
3673
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3674
            $end_filter = api_get_utc_datetime($end_filter);
3675
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3676
        }
3677
3678
        $result = Database::query($sql);
3679
        while ($item = Database::fetch_array($result, 'ASSOC')) {
3680
            $time_minute = api_convert_and_format_date(
3681
                $item['date'],
3682
                TIME_NO_SEC_FORMAT
3683
            );
3684
            $item['date'] = api_get_local_time($item['date']);
3685
            $item['start_date_tms'] = api_strtotime($item['date']);
3686
            $item['content'] = $item['text'];
3687
3688
            // we break the date field in the database into a date and a time part
3689
            $agenda_db_date = explode(" ", $item['date']);
3690
            $date = $agenda_db_date[0];
3691
            $time = $agenda_db_date[1];
3692
            // we divide the date part into a day, a month and a year
3693
            $agendadate = explode("-", $item['date']);
3694
            $year = intval($agendadate[0]);
3695
            $month = intval($agendadate[1]);
3696
            $day = intval($agendadate[2]);
3697
            // we divide the time part into hour, minutes, seconds
3698
            $agendatime = explode(":", $time);
3699
3700
            $hour = $agendatime[0];
3701
            $minute = $agendatime[1];
3702
            $second = $agendatime[2];
3703
3704
            if ('month_view' == $type) {
3705
                $item['calendar_type'] = 'personal';
3706
                $item['start_date'] = $item['date'];
3707
                $agendaitems[$day][] = $item;
3708
                continue;
3709
            }
3710
3711
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3712
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3713
            if ("day_view" !== $type) {
3714
                // This is the array construction for the WEEK or MONTH view
3715
3716
                //Display events in agenda
3717
                $agendaitems[$day] .= "<div><i>$time_minute</i> $course_link <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><br />";
3718
            } else {
3719
                // this is the array construction for the DAY view
3720
                $halfhour = 2 * $agendatime['0'];
3721
                if ($agendatime['1'] >= '30') {
3722
                    $halfhour = $halfhour + 1;
3723
                }
3724
3725
                //Display events by list
3726
                $agendaitems[$halfhour] .= "<div><i>$time_minute</i> $course_link <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>";
3727
            }
3728
        }
3729
3730
        return $agendaitems;
3731
    }
3732
3733
    /**
3734
     * Show the monthcalender of the given month.
3735
     *
3736
     * @param    array    Agendaitems
3737
     * @param    int    Month number
3738
     * @param    int    Year number
3739
     * @param    array    Array of strings containing long week day names (deprecated, you can send an empty array
3740
     *                          instead)
3741
     * @param    string    The month name
3742
     */
3743
    public static function display_mymonthcalendar(
3744
        $user_id,
3745
        $agendaitems,
3746
        $month,
3747
        $year,
3748
        $weekdaynames = [],
3749
        $monthName,
3750
        $show_content = true
3751
    ) {
3752
        global $DaysShort, $course_path;
3753
        //Handle leap year
3754
        $numberofdays = [
3755
            0,
3756
            31,
3757
            28,
3758
            31,
3759
            30,
3760
            31,
3761
            30,
3762
            31,
3763
            31,
3764
            30,
3765
            31,
3766
            30,
3767
            31,
3768
        ];
3769
        if ((0 == $year % 400) or (0 == $year % 4 and 0 != $year % 100)) {
3770
            $numberofdays[2] = 29;
3771
        }
3772
        //Get the first day of the month
3773
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
3774
        //Start the week on monday
3775
        $startdayofweek = 0 != $dayone['wday'] ? ($dayone['wday'] - 1) : 6;
3776
        $g_cc = (isset($_GET['courseCode']) ? $_GET['courseCode'] : '');
3777
3778
        $next_month = (1 == $month ? 12 : $month - 1);
3779
        $prev_month = (12 == $month ? 1 : $month + 1);
3780
3781
        $next_year = (1 == $month ? $year - 1 : $year);
3782
        $prev_year = (12 == $month ? $year + 1 : $year);
3783
3784
        if ($show_content) {
3785
            $back_url = Display::url(
3786
                get_lang('Previous'),
3787
                api_get_self()."?coursePath=".urlencode(
3788
                    $course_path
3789
                )."&courseCode=".Security::remove_XSS(
3790
                    $g_cc
3791
                )."&action=view&view=month&month=".$next_month."&year=".$next_year
3792
            );
3793
            $next_url = Display::url(
3794
                get_lang('Next'),
3795
                api_get_self()."?coursePath=".urlencode(
3796
                    $course_path
3797
                )."&courseCode=".Security::remove_XSS(
3798
                    $g_cc
3799
                )."&action=view&view=month&month=".$prev_month."&year=".$prev_year
3800
            );
3801
        } else {
3802
            $back_url = Display::url(
3803
                get_lang('Previous'),
3804
                '',
3805
                [
3806
                    'onclick' => "load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ",
3807
                    'class' => 'btn ui-button ui-widget ui-state-default',
3808
                ]
3809
            );
3810
            $next_url = Display::url(
3811
                get_lang('Next'),
3812
                '',
3813
                [
3814
                    'onclick' => "load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ",
3815
                    'class' => 'pull-right btn ui-button ui-widget ui-state-default',
3816
                ]
3817
            );
3818
        }
3819
        $html = '';
3820
        $html .= '<div class="actions">';
3821
        $html .= '<div class="row">';
3822
        $html .= '<div class="col-md-4">'.$back_url.'</div>';
3823
        $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
3824
        $html .= '<div class="col-md-4">'.$next_url.'</div>';
3825
        $html .= '</div>';
3826
        $html .= '</div>';
3827
        $html .= '<table id="agenda_list2" class="table table-bordered">';
3828
        $html .= '<tr>';
3829
        for ($ii = 1; $ii < 8; $ii++) {
3830
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
3831
        }
3832
        $html .= '</tr>';
3833
3834
        $curday = -1;
3835
        $today = getdate();
3836
        while ($curday <= $numberofdays[$month]) {
3837
            $html .= "<tr>";
3838
            for ($ii = 0; $ii < 7; $ii++) {
3839
                if ((-1 == $curday) && ($ii == $startdayofweek)) {
3840
                    $curday = 1;
3841
                }
3842
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
3843
                    $bgcolor = $class = 'class="days_week"';
3844
                    $dayheader = Display::div(
3845
                        $curday,
3846
                        ['class' => 'agenda_day']
3847
                    );
3848
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
3849
                        $class = "class=\"days_today\" style=\"width:10%;\"";
3850
                    }
3851
3852
                    $html .= "<td ".$class.">".$dayheader;
3853
3854
                    if (!empty($agendaitems[$curday])) {
3855
                        $items = $agendaitems[$curday];
3856
                        $items = msort($items, 'start_date_tms');
3857
3858
                        foreach ($items as $value) {
3859
                            $value['title'] = Security::remove_XSS(
3860
                                $value['title']
3861
                            );
3862
                            $start_time = api_format_date(
3863
                                $value['start_date'],
3864
                                TIME_NO_SEC_FORMAT
3865
                            );
3866
                            $end_time = '';
3867
3868
                            if (!empty($value['end_date'])) {
3869
                                $end_time = '-&nbsp;<i>'.api_format_date(
3870
                                        $value['end_date'],
3871
                                        DATE_TIME_FORMAT_LONG
3872
                                    ).'</i>';
3873
                            }
3874
                            $complete_time = '<i>'.api_format_date(
3875
                                    $value['start_date'],
3876
                                    DATE_TIME_FORMAT_LONG
3877
                                ).'</i>&nbsp;'.$end_time;
3878
                            $time = '<i>'.$start_time.'</i>';
3879
3880
                            switch ($value['calendar_type']) {
3881
                                case 'personal':
3882
                                    $bg_color = '#D0E7F4';
3883
                                    $icon = Display::return_icon(
3884
                                        'user.png',
3885
                                        get_lang('Personal agenda'),
3886
                                        [],
3887
                                        ICON_SIZE_SMALL
3888
                                    );
3889
                                    break;
3890
                                case 'global':
3891
                                    $bg_color = '#FFBC89';
3892
                                    $icon = Display::return_icon(
3893
                                        'view_remove.png',
3894
                                        get_lang('Platform event'),
3895
                                        [],
3896
                                        ICON_SIZE_SMALL
3897
                                    );
3898
                                    break;
3899
                                case 'course':
3900
                                    $bg_color = '#CAFFAA';
3901
                                    $icon_name = 'course.png';
3902
                                    if (!empty($value['session_id'])) {
3903
                                        $icon_name = 'session.png';
3904
                                    }
3905
                                    if ($show_content) {
3906
                                        $icon = Display::url(
3907
                                            Display::return_icon(
3908
                                                $icon_name,
3909
                                                $value['course_name'].' '.get_lang(
3910
                                                    'Course'
3911
                                                ),
3912
                                                [],
3913
                                                ICON_SIZE_SMALL
3914
                                            ),
3915
                                            $value['url']
3916
                                        );
3917
                                    } else {
3918
                                        $icon = Display::return_icon(
3919
                                            $icon_name,
3920
                                            $value['course_name'].' '.get_lang(
3921
                                                'Course'
3922
                                            ),
3923
                                            [],
3924
                                            ICON_SIZE_SMALL
3925
                                        );
3926
                                    }
3927
                                    break;
3928
                                default:
3929
                                    break;
3930
                            }
3931
3932
                            $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
3933
3934
                            if ($show_content) {
3935
                                //Setting a personal event to green
3936
                                $icon = Display::div(
3937
                                    $icon,
3938
                                    ['style' => 'float:right']
3939
                                );
3940
3941
                                $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
3942
3943
                                //Link to bubble
3944
                                $url = Display::url(
3945
                                    cut($value['title'], 40),
3946
                                    '#',
3947
                                    ['id' => $link, 'class' => 'opener']
3948
                                );
3949
                                $result .= $time.' '.$icon.' '.Display::div(
3950
                                        $url
3951
                                    );
3952
3953
                                //Hidden content
3954
                                $content = Display::div(
3955
                                    $icon.Display::tag(
3956
                                        'h2',
3957
                                        $value['course_name']
3958
                                    ).'<hr />'.Display::tag(
3959
                                        'h3',
3960
                                        $value['title']
3961
                                    ).$complete_time.'<hr />'.Security::remove_XSS(
3962
                                        $value['content']
3963
                                    )
3964
                                );
3965
3966
                                //Main div
3967
                                $result .= Display::div(
3968
                                    $content,
3969
                                    [
3970
                                        'id' => 'main_'.$link,
3971
                                        'class' => 'dialog',
3972
                                        'style' => 'display:none',
3973
                                    ]
3974
                                );
3975
                                $result .= '</div>';
3976
                                $html .= $result;
3977
                            } else {
3978
                                $html .= $result .= $icon.'</div>';
3979
                            }
3980
                        }
3981
                    }
3982
                    $html .= "</td>";
3983
                    $curday++;
3984
                } else {
3985
                    $html .= "<td></td>";
3986
                }
3987
            }
3988
            $html .= "</tr>";
3989
        }
3990
        $html .= "</table>";
3991
        echo $html;
3992
    }
3993
3994
    /**
3995
     * Get personal agenda items between two dates (=all events from all registered courses).
3996
     *
3997
     * @param int $user_id user ID of the user
3998
     * @param    string    Optional start date in datetime format (if no start date is given, uses today)
3999
     * @param    string    Optional end date in datetime format (if no date is given, uses one year from now)
4000
     *
4001
     * @return array array of events ordered by start date, in
4002
     *               [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
4003
     *               where datestart and dateend are in yyyyMMddhhmmss format
4004
     *
4005
     * @deprecated use agenda events
4006
     */
4007
    public static function get_personal_agenda_items_between_dates(
4008
        $user_id,
4009
        $date_start = '',
4010
        $date_end = ''
4011
    ) {
4012
        $items = [];
4013
        if ($user_id != strval(intval($user_id))) {
4014
            return $items;
4015
        }
4016
        if (empty($date_start)) {
4017
            $date_start = date('Y-m-d H:i:s');
4018
        }
4019
        if (empty($date_end)) {
4020
            $date_end = date(
4021
                'Y-m-d H:i:s',
4022
                mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1)
4023
            );
4024
        }
4025
        $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
4026
        if (!preg_match($expr, $date_start)) {
4027
            return $items;
4028
        }
4029
        if (!preg_match($expr, $date_end)) {
4030
            return $items;
4031
        }
4032
4033
        // get agenda-items for every course
4034
        $courses = api_get_user_courses($user_id, false);
4035
        foreach ($courses as $id => $course) {
4036
            $c = api_get_course_info_by_id($course['real_id']);
4037
            //databases of the courses
4038
            $t_a = Database::get_course_table(TABLE_AGENDA, $course['db']);
4039
            $t_ip = Database::get_course_table(
4040
                TABLE_ITEM_PROPERTY,
4041
                $course['db']
4042
            );
4043
            // get the groups to which the user belong
4044
            $group_memberships = GroupManager:: get_group_ids(
4045
                $course['db'],
4046
                $user_id
4047
            );
4048
            // if the user is administrator of that course we show all the agenda items
4049
            if ('1' == $course['status']) {
4050
                //echo "course admin";
4051
                $sqlquery = "SELECT ".
4052
                    " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4053
                    " FROM ".$t_a." agenda, ".
4054
                    $t_ip." ip ".
4055
                    " WHERE agenda.id = ip.ref ".
4056
                    " AND agenda.start_date>='$date_start' ".
4057
                    " AND agenda.end_date<='$date_end' ".
4058
                    " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4059
                    " AND ip.visibility='1' ".
4060
                    " GROUP BY agenda.id ".
4061
                    " ORDER BY start_date ";
4062
            } else {
4063
                // if the user is not an administrator of that course, then...
4064
                if (is_array($group_memberships) && count(
4065
                        $group_memberships
4066
                    ) > 0
4067
                ) {
4068
                    $sqlquery = "SELECT ".
4069
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4070
                        " FROM ".$t_a." agenda, ".
4071
                        $t_ip." ip ".
4072
                        " WHERE agenda.id = ip.ref ".
4073
                        " AND agenda.start_date>='$date_start' ".
4074
                        " AND agenda.end_date<='$date_end' ".
4075
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4076
                        " AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
4077
                            ", ",
4078
                            $group_memberships
4079
                        ).")) ) ".
4080
                        " AND ip.visibility='1' ".
4081
                        " ORDER BY start_date ";
4082
                } else {
4083
                    $sqlquery = "SELECT ".
4084
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4085
                        " FROM ".$t_a." agenda, ".
4086
                        $t_ip." ip ".
4087
                        " WHERE agenda.id = ip.ref ".
4088
                        " AND agenda.start_date>='$date_start' ".
4089
                        " AND agenda.end_date<='$date_end' ".
4090
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4091
                        " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
4092
                        " AND ip.visibility='1' ".
4093
                        " ORDER BY start_date ";
4094
                }
4095
            }
4096
4097
            $result = Database::query($sqlquery);
4098
            while ($item = Database::fetch_array($result)) {
4099
                $agendaday = date("j", strtotime($item['start_date']));
4100
                $month = date("n", strtotime($item['start_date']));
4101
                $year = date("Y", strtotime($item['start_date']));
4102
                $URL = api_get_path(
4103
                        WEB_PATH
4104
                    )."main/calendar/agenda.php?cidReq=".urlencode(
4105
                        $course["code"]
4106
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
4107
                list($year, $month, $day, $hour, $min, $sec) = explode(
4108
                    '[-: ]',
4109
                    $item['start_date']
4110
                );
4111
                $start_date = $year.$month.$day.$hour.$min;
4112
                list($year, $month, $day, $hour, $min, $sec) = explode(
4113
                    '[-: ]',
4114
                    $item['end_date']
4115
                );
4116
                $end_date = $year.$month.$day.$hour.$min;
4117
4118
                $items[] = [
4119
                    'datestart' => $start_date,
4120
                    'dateend' => $end_date,
4121
                    'title' => $item['title'],
4122
                    'link' => $URL,
4123
                    'coursetitle' => $c['name'],
4124
                ];
4125
            }
4126
        }
4127
4128
        return $items;
4129
    }
4130
4131
    /**
4132
     * This function calculates the startdate of the week (monday)
4133
     * and the enddate of the week (sunday)
4134
     * and returns it as an array.
4135
     */
4136
    public static function calculate_start_end_of_week($week_number, $year)
4137
    {
4138
        // determine the start and end date
4139
        // step 1: we calculate a timestamp for a day in this week
4140
        $random_day_in_week = mktime(
4141
                0,
4142
                0,
4143
                0,
4144
                1,
4145
                1,
4146
                $year
4147
            ) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
4148
        // step 2: we which day this is (0=sunday, 1=monday, ...)
4149
        $number_day_in_week = date('w', $random_day_in_week);
4150
        // step 3: we calculate the timestamp of the monday of the week we are in
4151
        $start_timestamp = $random_day_in_week - (($number_day_in_week - 1) * 24 * 60 * 60);
4152
        // step 4: we calculate the timestamp of the sunday of the week we are in
4153
        $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week + 1) * 24 * 60 * 60) - 3600;
4154
        // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
4155
        $start_day = date('j', $start_timestamp);
4156
        $start_month = date('n', $start_timestamp);
4157
        $start_year = date('Y', $start_timestamp);
4158
        $end_day = date('j', $end_timestamp);
4159
        $end_month = date('n', $end_timestamp);
4160
        $end_year = date('Y', $end_timestamp);
4161
        $start_end_array['start']['day'] = $start_day;
4162
        $start_end_array['start']['month'] = $start_month;
4163
        $start_end_array['start']['year'] = $start_year;
4164
        $start_end_array['end']['day'] = $end_day;
4165
        $start_end_array['end']['month'] = $end_month;
4166
        $start_end_array['end']['year'] = $end_year;
4167
4168
        return $start_end_array;
4169
    }
4170
4171
    /**
4172
     * @return bool
4173
     */
4174
    public function getIsAllowedToEdit()
4175
    {
4176
        return $this->isAllowedToEdit;
4177
    }
4178
4179
    /**
4180
     * @param bool $isAllowedToEdit
4181
     */
4182
    public function setIsAllowedToEdit($isAllowedToEdit)
4183
    {
4184
        $this->isAllowedToEdit = $isAllowedToEdit;
4185
    }
4186
4187
    /**
4188
     * Format needed for the Fullcalendar js lib.
4189
     *
4190
     * @param string $utcTime
4191
     *
4192
     * @return bool|string
4193
     */
4194
    public function formatEventDate($utcTime)
4195
    {
4196
        $utcTimeZone = new DateTimeZone('UTC');
4197
        $platformTimeZone = new DateTimeZone(api_get_timezone());
4198
4199
        $eventDate = new DateTime($utcTime, $utcTimeZone);
4200
        $eventDate->setTimezone($platformTimeZone);
4201
4202
        return $eventDate->format(DateTime::ISO8601);
4203
    }
4204
}
4205