Completed
Push — master ( 1fcdba...966b12 )
by Julito
12:06
created

Agenda::move_event()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 44
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 33
nc 6
nop 3
dl 0
loc 44
rs 8.7697
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\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
                $event
304
//                    ->addCourseLink($courseEntity, $groupEntity, $sessionEntity)
305
                    ->setParent($courseEntity)
306
                    ;
307
308
                if (!empty($usersToSend)) {
309
                    $sendTo = $this->parseSendToArray($usersToSend);
310
                    if ($sendTo['everyone']) {
311
                        $event->addCourseLink($courseEntity, $sessionEntity, $groupEntity);
312
                    /*api_item_property_update(
313
                        $this->course,
314
                        TOOL_CALENDAR_EVENT,
315
                        $id,
316
                        'AgendaAdded',
317
                        $senderId,
318
                        $groupInfo,
319
                        '',
320
                        $start,
321
                        $end,
322
                        $sessionId
323
                    );
324
                    api_item_property_update(
325
                        $this->course,
326
                        TOOL_CALENDAR_EVENT,
327
                        $id,
328
                        'visible',
329
                        $senderId,
330
                        $groupInfo,
331
                        '',
332
                        $start,
333
                        $end,
334
                        $sessionId
335
                    );*/
336
                    } else {
337
                        // Storing the selected groups
338
                        if (!empty($sendTo['groups'])) {
339
                            foreach ($sendTo['groups'] as $group) {
340
                                $groupInfo = null;
341
                                if ($group) {
342
                                    $groupInfo = api_get_group_entity($group);
343
                                    $event->addCourseLink($courseEntity, $sessionEntity, $groupInfo);
344
                                }
345
346
                                /*api_item_property_update(
347
                                    $this->course,
348
                                    TOOL_CALENDAR_EVENT,
349
                                    $id,
350
                                    'AgendaAdded',
351
                                    $senderId,
352
                                    $groupInfoItem,
353
                                    0,
354
                                    $start,
355
                                    $end,
356
                                    $sessionId
357
                                );
358
359
                                api_item_property_update(
360
                                    $this->course,
361
                                    TOOL_CALENDAR_EVENT,
362
                                    $id,
363
                                    'visible',
364
                                    $senderId,
365
                                    $groupInfoItem,
366
                                    0,
367
                                    $start,
368
                                    $end,
369
                                    $sessionId
370
                                );*/
371
                            }
372
                        }
373
374
                        // storing the selected users
375
                        if (!empty($sendTo['users'])) {
376
                            foreach ($sendTo['users'] as $userId) {
377
                                $event->addUserLink(
378
                                    api_get_user_entity($userId),
379
                                    $courseEntity,
380
                                    $sessionEntity,
381
                                    $groupEntity
382
                                );
383
384
                                /*$repo->addResourceNodeToCourse(
385
                                    $resourceNode,
386
                                    ResourceLink::VISIBILITY_PUBLISHED,
387
                                    $courseEntity,
388
                                    $sessionEntity,
389
                                    $groupEntity,
390
                                    api_get_user_entity($userId)
391
                                );*/
392
393
                                /*api_item_property_update(
394
                                    $this->course,
395
                                    TOOL_CALENDAR_EVENT,
396
                                    $id,
397
                                    'AgendaAdded',
398
                                    $senderId,
399
                                    $groupInfo,
400
                                    $userId,
401
                                    $start,
402
                                    $end,
403
                                    $sessionId
404
                                );
405
406
                                api_item_property_update(
407
                                    $this->course,
408
                                    TOOL_CALENDAR_EVENT,
409
                                    $id,
410
                                    'visible',
411
                                    $senderId,
412
                                    $groupInfo,
413
                                    $userId,
414
                                    $start,
415
                                    $end,
416
                                    $sessionId
417
                                );*/
418
                            }
419
                        }
420
                    }
421
                }
422
423
                $em->persist($event);
424
                $em->flush();
425
                $id = $event->getIid();
426
427
                if ($id) {
428
                    $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
429
                    Database::query($sql);
430
431
                    // Add announcement.
432
                    if ($addAsAnnouncement) {
433
                        $this->storeAgendaEventAsAnnouncement($id, $usersToSend);
434
                    }
435
436
                    // Add attachment.
437
                    if (!empty($attachmentArray)) {
438
                        $counter = 0;
439
                        foreach ($attachmentArray as $attachmentItem) {
440
                            $this->addAttachment(
441
                                $event,
442
                                $attachmentItem,
443
                                $attachmentCommentList[$counter],
444
                                $this->course
445
                            );
446
                            $counter++;
447
                        }
448
                    }
449
                }
450
                break;
451
            case 'admin':
452
                if (api_is_platform_admin()) {
453
                    $event = new SysCalendar();
454
                    $event
455
                        ->setTitle($title)
456
                        ->setContent($content)
457
                        ->setStartDate($start)
458
                        ->setEndDate($end)
459
                        ->setAllDay($allDay)
460
                        ->setAccessUrlId(api_get_current_access_url_id())
461
                    ;
462
                    $em->persist($event);
463
                    $em->flush();
464
                    $id = $event->getId();
465
                }
466
                break;
467
        }
468
469
        return $id;
470
    }
471
472
    /**
473
     * @param int $eventId
474
     * @param int $courseId
475
     *
476
     * @return array
477
     */
478
    public function getRepeatedInfoByEvent($eventId, $courseId)
479
    {
480
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
481
        $eventId = (int) $eventId;
482
        $courseId = (int) $courseId;
483
        $sql = "SELECT * FROM $repeatTable
484
                WHERE c_id = $courseId AND cal_id = $eventId";
485
        $res = Database::query($sql);
486
        $repeatInfo = [];
487
        if (Database::num_rows($res) > 0) {
488
            $repeatInfo = Database::fetch_array($res, 'ASSOC');
489
        }
490
491
        return $repeatInfo;
492
    }
493
494
    /**
495
     * @param string $type
496
     * @param string $startEvent      in UTC
497
     * @param string $endEvent        in UTC
498
     * @param string $repeatUntilDate in UTC
499
     *
500
     * @throws Exception
501
     *
502
     * @return array
503
     */
504
    public function generateDatesByType($type, $startEvent, $endEvent, $repeatUntilDate)
505
    {
506
        $continue = true;
507
        $repeatUntilDate = new DateTime($repeatUntilDate, new DateTimeZone('UTC'));
508
        $loopMax = 365;
509
        $counter = 0;
510
        $list = [];
511
512
        switch ($type) {
513
            case 'daily':
514
                $interval = 'P1D';
515
                break;
516
            case 'weekly':
517
                $interval = 'P1W';
518
                break;
519
            case 'monthlyByDate':
520
                $interval = 'P1M';
521
                break;
522
            case 'monthlyByDay':
523
            case 'monthlyByDayR':
524
                // not yet implemented
525
                break;
526
            case 'yearly':
527
                $interval = 'P1Y';
528
                break;
529
        }
530
531
        if (empty($interval)) {
532
            return [];
533
        }
534
        $timeZone = api_get_timezone();
535
536
        while ($continue) {
537
            $startDate = new DateTime($startEvent, new DateTimeZone('UTC'));
538
            $endDate = new DateTime($endEvent, new DateTimeZone('UTC'));
539
540
            $startDate->add(new DateInterval($interval));
541
            $endDate->add(new DateInterval($interval));
542
543
            $newStartDate = $startDate->format('Y-m-d H:i:s');
544
            $newEndDate = $endDate->format('Y-m-d H:i:s');
545
546
            $startEvent = $newStartDate;
547
            $endEvent = $newEndDate;
548
549
            if ($endDate > $repeatUntilDate) {
550
                break;
551
            }
552
553
            // @todo remove comment code
554
            $startDateInLocal = new DateTime($newStartDate, new DateTimeZone($timeZone));
555
            if (0 == $startDateInLocal->format('I')) {
556
                // Is saving time? Then fix UTC time to add time
557
                $seconds = $startDateInLocal->getOffset();
558
                $startDate->add(new DateInterval("PT".$seconds."S"));
559
                $startDateFixed = $startDate->format('Y-m-d H:i:s');
560
                $startDateInLocalFixed = new DateTime($startDateFixed, new DateTimeZone($timeZone));
561
                $newStartDate = $startDateInLocalFixed->format('Y-m-d H:i:s');
562
            }
563
564
            $endDateInLocal = new DateTime($newEndDate, new DateTimeZone($timeZone));
565
            if (0 == $endDateInLocal->format('I')) {
566
                // Is saving time? Then fix UTC time to add time
567
                $seconds = $endDateInLocal->getOffset();
568
                $endDate->add(new DateInterval("PT".$seconds."S"));
569
                $endDateFixed = $endDate->format('Y-m-d H:i:s');
570
                $endDateInLocalFixed = new DateTime($endDateFixed, new DateTimeZone($timeZone));
571
                $newEndDate = $endDateInLocalFixed->format('Y-m-d H:i:s');
572
            }
573
            $list[] = ['start' => $newStartDate, 'end' => $newEndDate, 'i' => $startDateInLocal->format('I')];
574
            $counter++;
575
576
            // just in case stop if more than $loopMax
577
            if ($counter > $loopMax) {
578
                break;
579
            }
580
        }
581
582
        return $list;
583
    }
584
585
    /**
586
     * @param int    $eventId
587
     * @param string $type
588
     * @param string $end     in UTC
589
     * @param array  $sentTo
590
     *
591
     * @return bool
592
     */
593
    public function addRepeatedItem($eventId, $type, $end, $sentTo = [])
594
    {
595
        $t_agenda = Database::get_course_table(TABLE_AGENDA);
596
        $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
597
598
        if (empty($this->course)) {
599
            return false;
600
        }
601
602
        $courseId = $this->course['real_id'];
603
        $eventId = (int) $eventId;
604
605
        $sql = "SELECT title, content, start_date, end_date, all_day
606
                FROM $t_agenda
607
                WHERE c_id = $courseId AND id = $eventId";
608
        $res = Database::query($sql);
609
610
        if (1 !== Database::num_rows($res)) {
611
            return false;
612
        }
613
614
        $typeList = [
615
            'daily',
616
            'weekly',
617
            'monthlyByDate',
618
            'monthlyByDay',
619
            'monthlyByDayR',
620
            'yearly',
621
        ];
622
623
        if (!in_array($type, $typeList)) {
624
            return false;
625
        }
626
627
        $now = time();
628
629
        // The event has to repeat *in the future*. We don't allow repeated
630
        // events in the past
631
        if ($end > $now) {
632
            return false;
633
        }
634
635
        $row = Database::fetch_array($res);
636
637
        $title = $row['title'];
638
        $content = $row['content'];
639
        $allDay = $row['all_day'];
640
641
        $type = Database::escape_string($type);
642
        $end = Database::escape_string($end);
643
        $endTimeStamp = api_strtotime($end, 'UTC');
644
        $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
645
                VALUES ($courseId, '$eventId', '$type', '$endTimeStamp')";
646
        Database::query($sql);
647
648
        $generatedDates = $this->generateDatesByType($type, $row['start_date'], $row['end_date'], $end);
649
650
        if (empty($generatedDates)) {
651
            return false;
652
        }
653
654
        foreach ($generatedDates as $dateInfo) {
655
            $start = api_get_local_time($dateInfo['start']);
656
            $end = api_get_local_time($dateInfo['end']);
657
            $this->addEvent(
658
                $start,
659
                $end,
660
                $allDay,
661
                $title,
662
                $content,
663
                $sentTo,
664
                false,
665
                $eventId
666
            );
667
        }
668
669
        return true;
670
    }
671
672
    /**
673
     * @param int   $item_id
674
     * @param array $sentTo
675
     *
676
     * @return int
677
     */
678
    public function storeAgendaEventAsAnnouncement($item_id, $sentTo = [])
679
    {
680
        $table_agenda = Database::get_course_table(TABLE_AGENDA);
681
        $courseId = api_get_course_int_id();
682
683
        // Get the agenda item.
684
        $item_id = (int) $item_id;
685
        $sql = "SELECT * FROM $table_agenda
686
                WHERE c_id = $courseId AND id = ".$item_id;
687
        $res = Database::query($sql);
688
689
        if (Database::num_rows($res) > 0) {
690
            $row = Database::fetch_array($res, 'ASSOC');
691
692
            // Sending announcement
693
            if (!empty($sentTo)) {
694
                $id = AnnouncementManager::add_announcement(
695
                    api_get_course_info(),
696
                    api_get_session_id(),
697
                    $row['title'],
698
                    $row['content'],
699
                    $sentTo,
700
                    null,
701
                    null,
702
                    $row['end_date']
703
                );
704
705
                AnnouncementManager::sendEmail(
706
                    api_get_course_info(),
707
                    api_get_session_id(),
708
                    $id
709
                );
710
711
                return $id;
712
            }
713
        }
714
715
        return -1;
716
    }
717
718
    /**
719
     * Edits an event.
720
     *
721
     * @param int    $id
722
     * @param string $start                 datetime format: 2012-06-14 09:00:00
723
     * @param string $end                   datetime format: 2012-06-14 09:00:00
724
     * @param int    $allDay                is all day 'true' or 'false'
725
     * @param string $title
726
     * @param string $content
727
     * @param array  $usersToSend
728
     * @param array  $attachmentArray
729
     * @param array  $attachmentCommentList
730
     * @param string $comment
731
     * @param string $color
732
     * @param bool   $addAnnouncement
733
     * @param bool   $updateContent
734
     * @param int    $authorId
735
     *
736
     * @return bool
737
     */
738
    public function editEvent(
739
        $id,
740
        $start,
741
        $end,
742
        $allDay,
743
        $title,
744
        $content,
745
        $usersToSend = [],
746
        $attachmentArray = [],
747
        $attachmentCommentList = [],
748
        $comment = null,
749
        $color = '',
750
        $addAnnouncement = false,
751
        $updateContent = true,
752
        $authorId = 0
753
    ) {
754
        $start = api_get_utc_datetime($start);
755
        $end = api_get_utc_datetime($end);
756
        $allDay = isset($allDay) && 'true' == $allDay ? 1 : 0;
757
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
758
759
        switch ($this->type) {
760
            case 'personal':
761
                $eventInfo = $this->get_event($id);
762
                if ($eventInfo['user'] != api_get_user_id()) {
763
                    break;
764
                }
765
                $attributes = [
766
                    'title' => $title,
767
                    'date' => $start,
768
                    'enddate' => $end,
769
                    'all_day' => $allDay,
770
                ];
771
772
                if ($updateContent) {
773
                    $attributes['text'] = $content;
774
                }
775
776
                if (!empty($color)) {
777
                    $attributes['color'] = $color;
778
                }
779
780
                Database::update(
781
                    $this->tbl_personal_agenda,
782
                    $attributes,
783
                    ['id = ?' => $id]
784
                );
785
                break;
786
            case 'course':
787
                $eventInfo = $this->get_event($id);
788
789
                if (empty($eventInfo)) {
790
                    return false;
791
                }
792
793
                $groupId = api_get_group_id();
794
                $groupIid = 0;
795
                $groupInfo = [];
796
                if ($groupId) {
797
                    $groupInfo = GroupManager::get_group_properties($groupId);
798
                    if ($groupInfo) {
799
                        $groupIid = $groupInfo['iid'];
800
                    }
801
                }
802
803
                $courseId = $this->course['real_id'];
804
805
                if (empty($courseId)) {
806
                    return false;
807
                }
808
809
                if ($this->getIsAllowedToEdit()) {
810
                    $attributes = [
811
                        'title' => $title,
812
                        'start_date' => $start,
813
                        'end_date' => $end,
814
                        'all_day' => $allDay,
815
                        'comment' => $comment,
816
                    ];
817
818
                    if ($updateContent) {
819
                        $attributes['content'] = $content;
820
                    }
821
822
                    if (!empty($color)) {
823
                        $attributes['color'] = $color;
824
                    }
825
826
                    Database::update(
827
                        $this->tbl_course_agenda,
828
                        $attributes,
829
                        [
830
                            'id = ? AND c_id = ? AND session_id = ? ' => [
831
                                $id,
832
                                $courseId,
833
                                $this->sessionId,
834
                            ],
835
                        ]
836
                    );
837
838
                    if (!empty($usersToSend)) {
839
                        $sendTo = $this->parseSendToArray($usersToSend);
840
841
                        $usersToDelete = array_diff(
842
                            $eventInfo['send_to']['users'],
843
                            $sendTo['users']
844
                        );
845
                        $usersToAdd = array_diff(
846
                            $sendTo['users'],
847
                            $eventInfo['send_to']['users']
848
                        );
849
850
                        $groupsToDelete = array_diff(
851
                            $eventInfo['send_to']['groups'],
852
                            $sendTo['groups']
853
                        );
854
                        $groupToAdd = array_diff(
855
                            $sendTo['groups'],
856
                            $eventInfo['send_to']['groups']
857
                        );
858
859
                        if ($sendTo['everyone']) {
860
                            // Delete all from group
861
                            if (isset($eventInfo['send_to']['groups']) &&
862
                                !empty($eventInfo['send_to']['groups'])
863
                            ) {
864
                                foreach ($eventInfo['send_to']['groups'] as $group) {
865
                                    $groupIidItem = 0;
866
                                    if ($group) {
867
                                        $groupInfoItem = GroupManager::get_group_properties(
868
                                            $group
869
                                        );
870
                                        if ($groupInfoItem) {
871
                                            $groupIidItem = $groupInfoItem['iid'];
872
                                        }
873
                                    }
874
875
                                    api_item_property_delete(
876
                                        $this->course,
877
                                        TOOL_CALENDAR_EVENT,
878
                                        $id,
879
                                        0,
880
                                        $groupIidItem,
881
                                        $this->sessionId
882
                                    );
883
                                }
884
                            }
885
886
                            // Storing the selected users.
887
                            if (isset($eventInfo['send_to']['users']) &&
888
                                !empty($eventInfo['send_to']['users'])
889
                            ) {
890
                                foreach ($eventInfo['send_to']['users'] as $userId) {
891
                                    api_item_property_delete(
892
                                        $this->course,
893
                                        TOOL_CALENDAR_EVENT,
894
                                        $id,
895
                                        $userId,
896
                                        $groupIid,
897
                                        $this->sessionId
898
                                    );
899
                                }
900
                            }
901
902
                            // Add to everyone only.
903
                            api_item_property_update(
904
                                $this->course,
905
                                TOOL_CALENDAR_EVENT,
906
                                $id,
907
                                'visible',
908
                                $authorId,
909
                                $groupInfo,
910
                                null,
911
                                $start,
912
                                $end,
913
                                $this->sessionId
914
                            );
915
                        } else {
916
                            // Delete "everyone".
917
                            api_item_property_delete(
918
                                $this->course,
919
                                TOOL_CALENDAR_EVENT,
920
                                $id,
921
                                0,
922
                                0,
923
                                $this->sessionId
924
                            );
925
926
                            // Add groups
927
                            if (!empty($groupToAdd)) {
928
                                foreach ($groupToAdd as $group) {
929
                                    $groupInfoItem = [];
930
                                    if ($group) {
931
                                        $groupInfoItem = GroupManager::get_group_properties(
932
                                            $group
933
                                        );
934
                                    }
935
936
                                    api_item_property_update(
937
                                        $this->course,
938
                                        TOOL_CALENDAR_EVENT,
939
                                        $id,
940
                                        'visible',
941
                                        $authorId,
942
                                        $groupInfoItem,
943
                                        0,
944
                                        $start,
945
                                        $end,
946
                                        $this->sessionId
947
                                    );
948
                                }
949
                            }
950
951
                            // Delete groups.
952
                            if (!empty($groupsToDelete)) {
953
                                foreach ($groupsToDelete as $group) {
954
                                    $groupIidItem = 0;
955
                                    if ($group) {
956
                                        $groupInfoItem = GroupManager::get_group_properties(
957
                                            $group
958
                                        );
959
                                        if ($groupInfoItem) {
960
                                            $groupIidItem = $groupInfoItem['iid'];
961
                                        }
962
                                    }
963
964
                                    api_item_property_delete(
965
                                        $this->course,
966
                                        TOOL_CALENDAR_EVENT,
967
                                        $id,
968
                                        0,
969
                                        $groupIidItem,
970
                                        $this->sessionId
971
                                    );
972
                                }
973
                            }
974
975
                            // Add users.
976
                            if (!empty($usersToAdd)) {
977
                                foreach ($usersToAdd as $userId) {
978
                                    api_item_property_update(
979
                                        $this->course,
980
                                        TOOL_CALENDAR_EVENT,
981
                                        $id,
982
                                        'visible',
983
                                        $authorId,
984
                                        $groupInfo,
985
                                        $userId,
986
                                        $start,
987
                                        $end,
988
                                        $this->sessionId
989
                                    );
990
                                }
991
                            }
992
993
                            // Delete users.
994
                            if (!empty($usersToDelete)) {
995
                                foreach ($usersToDelete as $userId) {
996
                                    api_item_property_delete(
997
                                        $this->course,
998
                                        TOOL_CALENDAR_EVENT,
999
                                        $id,
1000
                                        $userId,
1001
                                        $groupInfo,
1002
                                        $this->sessionId
1003
                                    );
1004
                                }
1005
                            }
1006
                        }
1007
                    }
1008
1009
                    // Add announcement.
1010
                    if (isset($addAnnouncement) && !empty($addAnnouncement)) {
1011
                        $this->storeAgendaEventAsAnnouncement(
1012
                            $id,
1013
                            $usersToSend
1014
                        );
1015
                    }
1016
1017
                    // Add attachment.
1018
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
1019
                        $counter = 0;
1020
                        foreach ($attachmentArray as $attachmentItem) {
1021
                            $this->updateAttachment(
1022
                                $attachmentItem['id'],
1023
                                $id,
1024
                                $attachmentItem,
1025
                                $attachmentCommentList[$counter],
1026
                                $this->course
1027
                            );
1028
                            $counter++;
1029
                        }
1030
                    }
1031
1032
                    return true;
1033
                } else {
1034
                    return false;
1035
                }
1036
                break;
1037
            case 'admin':
1038
            case 'platform':
1039
                if (api_is_platform_admin()) {
1040
                    $attributes = [
1041
                        'title' => $title,
1042
                        'start_date' => $start,
1043
                        'end_date' => $end,
1044
                        'all_day' => $allDay,
1045
                    ];
1046
1047
                    if ($updateContent) {
1048
                        $attributes['content'] = $content;
1049
                    }
1050
                    Database::update(
1051
                        $this->tbl_global_agenda,
1052
                        $attributes,
1053
                        ['id = ?' => $id]
1054
                    );
1055
                }
1056
                break;
1057
        }
1058
    }
1059
1060
    /**
1061
     * @param int  $id
1062
     * @param bool $deleteAllItemsFromSerie
1063
     */
1064
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
1065
    {
1066
        switch ($this->type) {
1067
            case 'personal':
1068
                $eventInfo = $this->get_event($id);
1069
                if ($eventInfo['user'] == api_get_user_id()) {
1070
                    Database::delete(
1071
                        $this->tbl_personal_agenda,
1072
                        ['id = ?' => $id]
1073
                    );
1074
                }
1075
                break;
1076
            case 'course':
1077
                $courseId = api_get_course_int_id();
1078
                $isAllowToEdit = $this->getIsAllowedToEdit();
1079
1080
                if (!empty($courseId) && $isAllowToEdit) {
1081
                    // Delete
1082
                    $eventInfo = $this->get_event($id);
1083
                    if ($deleteAllItemsFromSerie) {
1084
                        /* This is one of the children.
1085
                           Getting siblings and delete 'Em all + the father! */
1086
                        if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
1087
                            // Removing items.
1088
                            $events = $this->getAllRepeatEvents($eventInfo['parent_event_id']);
1089
                            if (!empty($events)) {
1090
                                foreach ($events as $event) {
1091
                                    $this->deleteEvent($event['id']);
1092
                                }
1093
                            }
1094
                            // Removing parent.
1095
                            $this->deleteEvent($eventInfo['parent_event_id']);
1096
                        } else {
1097
                            // This is the father looking for the children.
1098
                            $events = $this->getAllRepeatEvents($id);
1099
                            if (!empty($events)) {
1100
                                foreach ($events as $event) {
1101
                                    $this->deleteEvent($event['id']);
1102
                                }
1103
                            }
1104
                        }
1105
                    }
1106
1107
                    $repo = Container::getCalendarEventRepository();
1108
                    $event = $repo->find($id);
1109
1110
                    if ($event) {
1111
                        $repo->getEntityManager()->remove($event);
1112
                        $repo->getEntityManager()->flush();
1113
1114
                        // Removing from events.
1115
                        /*Database::delete(
1116
                            $this->tbl_course_agenda,
1117
                            ['id = ? AND c_id = ?' => [$id, $courseId]]
1118
                        );*/
1119
1120
                        /*api_item_property_update(
1121
                            $this->course,
1122
                            TOOL_CALENDAR_EVENT,
1123
                            $id,
1124
                            'delete',
1125
                            api_get_user_id()
1126
                        );*/
1127
1128
                        // Removing from series.
1129
                        Database::delete(
1130
                            $this->table_repeat,
1131
                            [
1132
                                'cal_id = ? AND c_id = ?' => [
1133
                                    $id,
1134
                                    $courseId,
1135
                                ],
1136
                            ]
1137
                        );
1138
                        // Attachments are already deleted using the doctrine remove() function.
1139
                        /*if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
1140
                            foreach ($eventInfo['attachment'] as $attachment) {
1141
                                self::deleteAttachmentFile(
1142
                                    $attachment['id'],
1143
                                    $this->course
1144
                                );
1145
                            }
1146
                        }*/
1147
                    }
1148
                }
1149
                break;
1150
            case 'admin':
1151
                if (api_is_platform_admin()) {
1152
                    Database::delete(
1153
                        $this->tbl_global_agenda,
1154
                        ['id = ?' => $id]
1155
                    );
1156
                }
1157
                break;
1158
        }
1159
    }
1160
1161
    /**
1162
     * Get agenda events.
1163
     *
1164
     * @param int    $start
1165
     * @param int    $end
1166
     * @param int    $courseId
1167
     * @param int    $groupId
1168
     * @param int    $user_id
1169
     * @param string $format
1170
     *
1171
     * @return array|string
1172
     */
1173
    public function getEvents(
1174
        $start,
1175
        $end,
1176
        $courseId = null,
1177
        $groupId = null,
1178
        $user_id = 0,
1179
        $format = 'json'
1180
    ) {
1181
        switch ($this->type) {
1182
            case 'admin':
1183
                $this->getPlatformEvents($start, $end);
1184
                break;
1185
            case 'course':
1186
                $courseInfo = api_get_course_info_by_id($courseId);
1187
1188
                // Session coach can see all events inside a session.
1189
                if (api_is_coach()) {
1190
                    // Own course
1191
                    $this->getCourseEvents(
1192
                        $start,
1193
                        $end,
1194
                        $courseInfo,
1195
                        $groupId,
1196
                        $this->sessionId,
1197
                        $user_id
1198
                    );
1199
1200
                    // Others
1201
                    $this->getSessionEvents(
1202
                        $start,
1203
                        $end,
1204
                        $this->sessionId,
1205
                        $user_id,
1206
                        $this->eventOtherSessionColor
1207
                    );
1208
                } else {
1209
                    $this->getCourseEvents(
1210
                        $start,
1211
                        $end,
1212
                        $courseInfo,
1213
                        $groupId,
1214
                        $this->sessionId,
1215
                        $user_id
1216
                    );
1217
                }
1218
                break;
1219
            case 'personal':
1220
            default:
1221
                $sessionFilterActive = false;
1222
                if (!empty($this->sessionId)) {
1223
                    $sessionFilterActive = true;
1224
                }
1225
1226
                if (false == $sessionFilterActive) {
1227
                    // Getting personal events
1228
                    $this->getPersonalEvents($start, $end);
1229
1230
                    // Getting platform/admin events
1231
                    $this->getPlatformEvents($start, $end);
1232
                }
1233
1234
                $ignoreVisibility = api_get_configuration_value('personal_agenda_show_all_session_events');
1235
1236
                // Getting course events
1237
                $my_course_list = [];
1238
                if (!api_is_anonymous()) {
1239
                    $session_list = SessionManager::get_sessions_by_user(
1240
                        api_get_user_id(),
1241
                        $ignoreVisibility
1242
                    );
1243
                    $my_course_list = CourseManager::get_courses_list_by_user_id(
1244
                        api_get_user_id(),
1245
                        false
1246
                    );
1247
                }
1248
1249
                if (api_is_drh()) {
1250
                    if (api_drh_can_access_all_session_content()) {
1251
                        $session_list = [];
1252
                        $sessionList = SessionManager::get_sessions_followed_by_drh(
1253
                            api_get_user_id(),
1254
                            null,
1255
                            null,
1256
                            null,
1257
                            true,
1258
                            false
1259
                        );
1260
1261
                        if (!empty($sessionList)) {
1262
                            foreach ($sessionList as $sessionItem) {
1263
                                $sessionId = $sessionItem['id'];
1264
                                $courses = SessionManager::get_course_list_by_session_id(
1265
                                    $sessionId
1266
                                );
1267
                                $sessionInfo = [
1268
                                    'session_id' => $sessionId,
1269
                                    'courses' => $courses,
1270
                                ];
1271
                                $session_list[] = $sessionInfo;
1272
                            }
1273
                        }
1274
                    }
1275
                }
1276
1277
                if (!empty($session_list)) {
1278
                    foreach ($session_list as $session_item) {
1279
                        if ($sessionFilterActive) {
1280
                            if ($this->sessionId != $session_item['session_id']) {
1281
                                continue;
1282
                            }
1283
                        }
1284
1285
                        $my_courses = $session_item['courses'];
1286
                        $my_session_id = $session_item['session_id'];
1287
1288
                        if (!empty($my_courses)) {
1289
                            foreach ($my_courses as $course_item) {
1290
                                $courseInfo = api_get_course_info_by_id(
1291
                                    $course_item['real_id']
1292
                                );
1293
                                $this->getCourseEvents(
1294
                                    $start,
1295
                                    $end,
1296
                                    $courseInfo,
1297
                                    0,
1298
                                    $my_session_id
1299
                                );
1300
                            }
1301
                        }
1302
                    }
1303
                }
1304
1305
                if (!empty($my_course_list) && false == $sessionFilterActive) {
1306
                    foreach ($my_course_list as $courseInfoItem) {
1307
                        $courseInfo = api_get_course_info_by_id(
1308
                            $courseInfoItem['real_id']
1309
                        );
1310
                        if (isset($courseId) && !empty($courseId)) {
1311
                            if ($courseInfo['real_id'] == $courseId) {
1312
                                $this->getCourseEvents(
1313
                                    $start,
1314
                                    $end,
1315
                                    $courseInfo,
1316
                                    0,
1317
                                    0,
1318
                                    $user_id
1319
                                );
1320
                            }
1321
                        } else {
1322
                            $this->getCourseEvents(
1323
                                $start,
1324
                                $end,
1325
                                $courseInfo,
1326
                                0,
1327
                                0,
1328
                                $user_id
1329
                            );
1330
                        }
1331
                    }
1332
                }
1333
                break;
1334
        }
1335
1336
        $this->cleanEvents();
1337
1338
        switch ($format) {
1339
            case 'json':
1340
                if (empty($this->events)) {
1341
                    return '[]';
1342
                }
1343
1344
                return json_encode($this->events);
1345
                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...
1346
            case 'array':
1347
                if (empty($this->events)) {
1348
                    return [];
1349
                }
1350
1351
                return $this->events;
1352
                break;
1353
        }
1354
    }
1355
1356
    /**
1357
     * Clean events.
1358
     *
1359
     * @return bool
1360
     */
1361
    public function cleanEvents()
1362
    {
1363
        if (empty($this->events)) {
1364
            return false;
1365
        }
1366
1367
        foreach ($this->events as &$event) {
1368
            $event['description'] = Security::remove_XSS($event['description']);
1369
            $event['title'] = Security::remove_XSS($event['title']);
1370
        }
1371
1372
        return true;
1373
    }
1374
1375
    /**
1376
     * @param int $id
1377
     * @param int $minute_delta
1378
     *
1379
     * @return int
1380
     */
1381
    public function resizeEvent($id, $minute_delta)
1382
    {
1383
        $id = (int) $id;
1384
        $delta = (int) $minute_delta;
1385
        $event = $this->get_event($id);
1386
        if (!empty($event)) {
1387
            switch ($this->type) {
1388
                case 'personal':
1389
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1390
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1391
							WHERE id = ".$id;
1392
                    Database::query($sql);
1393
                    break;
1394
                case 'course':
1395
                    $sql = "UPDATE $this->tbl_course_agenda SET
1396
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1397
							WHERE
1398
							    c_id = ".$this->course['real_id']." AND
1399
							    id = ".$id;
1400
                    Database::query($sql);
1401
                    break;
1402
                case 'admin':
1403
                    $sql = "UPDATE $this->tbl_global_agenda SET
1404
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1405
							WHERE id = ".$id;
1406
                    Database::query($sql);
1407
                    break;
1408
            }
1409
        }
1410
1411
        return 1;
1412
    }
1413
1414
    /**
1415
     * @param int $id
1416
     * @param int $minute_delta minutes
1417
     * @param int $allDay
1418
     *
1419
     * @return int
1420
     */
1421
    public function move_event($id, $minute_delta, $allDay)
1422
    {
1423
        $id = (int) $id;
1424
        $event = $this->get_event($id);
1425
1426
        if (empty($event)) {
1427
            return false;
1428
        }
1429
1430
        // we convert the hour delta into minutes and add the minute delta
1431
        $delta = (int) $minute_delta;
1432
        $allDay = (int) $allDay;
1433
1434
        if (!empty($event)) {
1435
            switch ($this->type) {
1436
                case 'personal':
1437
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1438
                            all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
1439
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1440
							WHERE id=".$id;
1441
                    Database::query($sql);
1442
                    break;
1443
                case 'course':
1444
                    $sql = "UPDATE $this->tbl_course_agenda SET
1445
                            all_day = $allDay,
1446
                            start_date = DATE_ADD(start_date, INTERVAL $delta MINUTE),
1447
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1448
							WHERE
1449
							    c_id = ".$this->course['real_id']." AND
1450
							    id=".$id;
1451
                    Database::query($sql);
1452
                    break;
1453
                case 'admin':
1454
                    $sql = "UPDATE $this->tbl_global_agenda SET
1455
                            all_day = $allDay,
1456
                            start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1457
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1458
							WHERE id=".$id;
1459
                    Database::query($sql);
1460
                    break;
1461
            }
1462
        }
1463
1464
        return 1;
1465
    }
1466
1467
    /**
1468
     * Gets a single event.
1469
     *
1470
     * @param int $id event id
1471
     *
1472
     * @return array
1473
     */
1474
    public function get_event($id)
1475
    {
1476
        // make sure events of the personal agenda can only be seen by the user himself
1477
        $id = (int) $id;
1478
        $event = null;
1479
        switch ($this->type) {
1480
            case 'personal':
1481
                $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1482
                        WHERE id = $id AND user = ".api_get_user_id();
1483
                $result = Database::query($sql);
1484
                if (Database::num_rows($result)) {
1485
                    $event = Database::fetch_array($result, 'ASSOC');
1486
                    $event['description'] = $event['text'];
1487
                    $event['content'] = $event['text'];
1488
                    $event['start_date'] = $event['date'];
1489
                    $event['end_date'] = $event['enddate'];
1490
                }
1491
                break;
1492
            case 'course':
1493
                if (!empty($this->course['real_id'])) {
1494
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
1495
                            WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
1496
                    $result = Database::query($sql);
1497
                    if (Database::num_rows($result)) {
1498
                        $event = Database::fetch_array($result, 'ASSOC');
1499
                        $event['description'] = $event['content'];
1500
1501
                        // Getting send to array
1502
                        $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
1503
                            $id,
1504
                            $this->course['real_id'],
1505
                            $this->sessionId
1506
                        );
1507
1508
                        // Getting repeat info
1509
                        $event['repeat_info'] = $this->getRepeatedInfoByEvent(
1510
                            $id,
1511
                            $this->course['real_id']
1512
                        );
1513
1514
                        if (!empty($event['parent_event_id'])) {
1515
                            $event['parent_info'] = $this->get_event(
1516
                                $event['parent_event_id']
1517
                            );
1518
                        }
1519
1520
                        $event['attachment'] = $this->getAttachmentList($id, $this->course);
1521
                    }
1522
                }
1523
                break;
1524
            case 'admin':
1525
            case 'platform':
1526
                $sql = "SELECT * FROM ".$this->tbl_global_agenda."
1527
                        WHERE id = $id";
1528
                $result = Database::query($sql);
1529
                if (Database::num_rows($result)) {
1530
                    $event = Database::fetch_array($result, 'ASSOC');
1531
                    $event['description'] = $event['content'];
1532
                }
1533
                break;
1534
        }
1535
1536
        return $event;
1537
    }
1538
1539
    /**
1540
     * Gets personal events.
1541
     *
1542
     * @param int $start
1543
     * @param int $end
1544
     *
1545
     * @return array
1546
     */
1547
    public function getPersonalEvents($start, $end)
1548
    {
1549
        $start = (int) $start;
1550
        $end = (int) $end;
1551
        $startCondition = '';
1552
        $endCondition = '';
1553
1554
        if (0 !== $start) {
1555
            $startCondition = "AND date >= '".api_get_utc_datetime($start)."'";
1556
        }
1557
        if (0 !== $start) {
1558
            $endCondition = "AND (enddate <= '".api_get_utc_datetime($end)."' OR enddate IS NULL)";
1559
        }
1560
        $user_id = api_get_user_id();
1561
1562
        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1563
                WHERE user = $user_id $startCondition $endCondition";
1564
1565
        $result = Database::query($sql);
1566
        $my_events = [];
1567
        if (Database::num_rows($result)) {
1568
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1569
                $event = [];
1570
                $event['id'] = 'personal_'.$row['id'];
1571
                $event['title'] = $row['title'];
1572
                $event['className'] = 'personal';
1573
                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
1574
                $event['editable'] = true;
1575
                $event['sent_to'] = get_lang('Me');
1576
                $event['type'] = 'personal';
1577
1578
                if (!empty($row['date'])) {
1579
                    $event['start'] = $this->formatEventDate($row['date']);
1580
                    $event['start_date_localtime'] = api_get_local_time($row['date']);
1581
                }
1582
1583
                if (!empty($row['enddate'])) {
1584
                    $event['end'] = $this->formatEventDate($row['enddate']);
1585
                    $event['end_date_localtime'] = api_get_local_time($row['enddate']);
1586
                }
1587
1588
                $event['description'] = $row['text'];
1589
                $event['allDay'] = isset($row['all_day']) && 1 == $row['all_day'] ? $row['all_day'] : 0;
1590
                $event['parent_event_id'] = 0;
1591
                $event['has_children'] = 0;
1592
1593
                $my_events[] = $event;
1594
                $this->events[] = $event;
1595
            }
1596
        }
1597
1598
        // Add plugin personal events
1599
        $this->plugin = new AppPlugin();
1600
        $plugins = $this->plugin->getInstalledPluginListObject();
1601
        /** @var Plugin $plugin */
1602
        foreach ($plugins as $plugin) {
1603
            if ($plugin->hasPersonalEvents && method_exists($plugin, 'getPersonalEvents')) {
1604
                $pluginEvents = $plugin->getPersonalEvents($this, $start, $end);
1605
1606
                if (!empty($pluginEvents)) {
1607
                    $this->events = array_merge($this->events, $pluginEvents);
1608
                }
1609
            }
1610
        }
1611
1612
        return $my_events;
1613
    }
1614
1615
    /**
1616
     * Get user/group list per event.
1617
     *
1618
     * @param int $eventId
1619
     * @param int $courseId
1620
     * @param int $sessionId
1621
     * @paraù int $sessionId
1622
     *
1623
     * @return array
1624
     */
1625
    public function getUsersAndGroupSubscribedToEvent(
1626
        $eventId,
1627
        $courseId,
1628
        $sessionId
1629
    ) {
1630
        $eventId = (int) $eventId;
1631
        $courseId = (int) $courseId;
1632
        $sessionId = (int) $sessionId;
1633
1634
        $repo = Container::getCalendarEventRepository();
1635
        /** @var CCalendarEvent $event */
1636
        $event = $repo->find($eventId);
1637
1638
        if (null === $event) {
1639
            return [];
1640
        }
1641
1642
        $course = api_get_course_entity($courseId);
1643
        $session = api_get_session_entity($sessionId);
1644
1645
        $users = [];
1646
        $groups = [];
1647
        $everyone = false;
1648
        $links = $event->getResourceNode()->getResourceLinks();
1649
        foreach ($links as $link) {
1650
            if ($link->getUser()) {
1651
                $users[] = $link->getUser()->getId();
1652
            }
1653
            if ($link->getGroup()) {
1654
                $groups[] = $link->getGroup()->getId();
1655
            }
1656
        }
1657
1658
        if (empty($users) && empty($groups)) {
1659
            $everyone = true;
1660
        }
1661
1662
        return [
1663
            'everyone' => $everyone,
1664
            'users' => $users,
1665
            'groups' => $groups,
1666
        ];
1667
1668
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

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

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

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

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

    return false;
}

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

Loading history...
1669
1670
        $sessionCondition = "ip.session_id = $sessionId";
1671
        if (empty($sessionId)) {
1672
            $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
1673
        }
1674
1675
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1676
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1677
1678
        // Get sent_tos
1679
        $sql = "SELECT DISTINCT to_user_id, to_group_id
1680
                FROM $tbl_property ip
1681
                INNER JOIN $tlb_course_agenda agenda
1682
                ON (
1683
                  ip.ref = agenda.id AND
1684
                  ip.c_id = agenda.c_id AND
1685
                  ip.tool = '".TOOL_CALENDAR_EVENT."'
1686
                )
1687
                WHERE
1688
                    ref = $eventId AND
1689
                    ip.visibility = '1' AND
1690
                    ip.c_id = $courseId AND
1691
                    $sessionCondition
1692
                ";
1693
1694
        $result = Database::query($sql);
1695
        $users = [];
1696
        $groups = [];
1697
        $everyone = false;
1698
1699
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1700
            if (!empty($row['to_group_id'])) {
1701
                $groups[] = $row['to_group_id'];
1702
            }
1703
            if (!empty($row['to_user_id'])) {
1704
                $users[] = $row['to_user_id'];
1705
            }
1706
1707
            if (empty($groups) && empty($users)) {
1708
                if (0 == $row['to_group_id']) {
1709
                    $everyone = true;
1710
                }
1711
            }
1712
        }
1713
1714
        return [
1715
            'everyone' => $everyone,
1716
            'users' => $users,
1717
            'groups' => $groups,
1718
        ];
1719
    }
1720
1721
    /**
1722
     * @param int    $start
1723
     * @param int    $end
1724
     * @param int    $sessionId
1725
     * @param int    $userId
1726
     * @param string $color
1727
     *
1728
     * @return array
1729
     */
1730
    public function getSessionEvents(
1731
        $start,
1732
        $end,
1733
        $sessionId = 0,
1734
        $userId = 0,
1735
        $color = ''
1736
    ) {
1737
        $courses = SessionManager::get_course_list_by_session_id($sessionId);
1738
1739
        if (!empty($courses)) {
1740
            foreach ($courses as $course) {
1741
                $this->getCourseEvents(
1742
                    $start,
1743
                    $end,
1744
                    $course,
1745
                    0,
1746
                    $sessionId,
1747
                    0,
1748
                    $color
1749
                );
1750
            }
1751
        }
1752
    }
1753
1754
    /**
1755
     * @param int    $start
1756
     * @param int    $end
1757
     * @param array  $courseInfo
1758
     * @param int    $groupId
1759
     * @param int    $sessionId
1760
     * @param int    $user_id
1761
     * @param string $color
1762
     *
1763
     * @return array
1764
     */
1765
    public function getCourseEvents(
1766
        $start,
1767
        $end,
1768
        $courseInfo,
1769
        $groupId = 0,
1770
        $sessionId = 0,
1771
        $user_id = 0,
1772
        $color = ''
1773
    ) {
1774
        $start = (int) $start;
1775
        $end = (int) $end;
1776
1777
        $start = !empty($start) ? api_get_utc_datetime($start) : null;
1778
        $end = !empty($end) ? api_get_utc_datetime($end) : null;
1779
1780
        if (empty($courseInfo)) {
1781
            return [];
1782
        }
1783
1784
        $courseId = $courseInfo['real_id'];
1785
1786
        if (empty($courseId)) {
1787
            return [];
1788
        }
1789
1790
        $userId = api_get_user_id();
1791
        $sessionId = (int) $sessionId;
1792
        $user_id = (int) $user_id;
1793
1794
        $groupList = GroupManager::get_group_list(
1795
            null,
1796
            $courseInfo,
1797
            null,
1798
            $sessionId
1799
        );
1800
1801
        $groupNameList = [];
1802
        if (!empty($groupList)) {
1803
            foreach ($groupList as $group) {
1804
                $groupNameList[$group['iid']] = $group['name'];
1805
            }
1806
        }
1807
1808
        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
1809
            $isAllowToEdit = true;
1810
        } else {
1811
            $isAllowToEdit = CourseManager::is_course_teacher(
1812
                $userId,
1813
                $courseInfo['code']
1814
            );
1815
        }
1816
1817
        $isAllowToEditByHrm = false;
1818
        if (!empty($sessionId)) {
1819
            $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
1820
            if ($allowDhrToEdit) {
1821
                $isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, $userId);
1822
                if ($isHrm) {
1823
                    $isAllowToEdit = $isAllowToEditByHrm = true;
1824
                }
1825
            }
1826
        }
1827
1828
        $groupMemberships = [];
1829
        if (!empty($groupId)) {
1830
            $groupMemberships = [$groupId];
1831
        } else {
1832
            if ($isAllowToEdit) {
1833
                if (!empty($groupList)) {
1834
                    // c_item_property.to_group_id field was migrated to use
1835
                    // c_group_info.iid
1836
                    $groupMemberships = array_column($groupList, 'iid');
1837
                }
1838
            } else {
1839
                // get only related groups from user
1840
                $groupMemberships = GroupManager::get_group_ids($courseId, $userId);
1841
            }
1842
        }
1843
1844
        $repo = Container::getCalendarEventRepository();
1845
        $courseEntity = api_get_course_entity($courseId);
1846
        $session = api_get_session_entity($sessionId);
1847
        $qb = $repo->getResourcesByCourseOnly($courseEntity, $courseEntity->getResourceNode());
1848
        $userCondition = '';
1849
1850
        if ($isAllowToEdit) {
1851
            // No group filter was asked
1852
            if (empty($groupId)) {
1853
                if (empty($user_id)) {
1854
                    // Show all events not added in group
1855
                    $userCondition = ' (links.group IS NULL) ';
1856
                    // admin see only his stuff
1857
                    if ('personal' === $this->type) {
1858
                        $userCondition = " (links.user = ".api_get_user_id()." AND (links.group IS NULL) ";
1859
                        //$userCondition = " (ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ) ";
1860
                        $userCondition .= " OR ( (links.user IS NULL)  AND (links.group IS NULL ))) ";
1861
                        //$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) ) ";
1862
                    }
1863
1864
                    if (!empty($groupMemberships)) {
1865
                        // Show events sent to selected groups
1866
                        $userCondition .= " OR (links.user IS NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1867
                    }
1868
                } else {
1869
                    // Show events of requested user in no group
1870
                    $userCondition = " (links.user = $user_id AND links.group IS NULL) ";
1871
                    // Show events sent to selected groups
1872
                    if (!empty($groupMemberships)) {
1873
                        $userCondition .= " OR (links.user = $user_id) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1874
                    }
1875
                }
1876
            } else {
1877
                // Show only selected groups (depending of user status)
1878
                $userCondition = " (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1879
1880
                if (!empty($groupMemberships)) {
1881
                    // Show send to $user_id in selected groups
1882
                    $userCondition .= " OR (links.user = $user_id) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1883
                }
1884
            }
1885
        } else {
1886
            // No group filter was asked
1887
            if (empty($groupId)) {
1888
                // Show events sent to everyone and no group
1889
                $userCondition = ' ( (links.user is NULL) AND (links.group IS NULL) ';
1890
                // Show events sent to selected groups
1891
                if (!empty($groupMemberships)) {
1892
                    $userCondition .= " OR (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships)."))) ";
1893
                } else {
1894
                    $userCondition .= " ) ";
1895
                }
1896
                $userCondition .= " OR (links.user = ".api_get_user_id()." AND (links.group IS NULL )) ";
1897
            } else {
1898
                if (!empty($groupMemberships)) {
1899
                    // Show send to everyone - and only selected groups
1900
                    $userCondition = " (links.user is NULL) AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1901
                }
1902
            }
1903
1904
            // Show sent to only me and no group
1905
            if (!empty($groupMemberships)) {
1906
                $userCondition .= " OR (links.user = ".api_get_user_id().") AND (links.group IN (".implode(", ", $groupMemberships).")) ";
1907
            }
1908
        }
1909
1910
        if (!empty($userCondition)) {
1911
            $qb->andWhere($userCondition);
1912
        }
1913
1914
        /*if (!empty($groupMemberships)) {
1915
            $orX = $qb->expr()->orX();
1916
            foreach ($groupMemberships as $groupId) {
1917
                $group = api_get_group_entity($groupId);
1918
                $orX->add("links.group = :group$groupId");
1919
                $qb->setParameter("group$groupId", $group);
1920
            }
1921
            $qb->andWhere($orX);
1922
        }*/
1923
1924
        //$dateCondition = '';
1925
        if (!empty($start) && !empty($end)) {
1926
            $qb->andWhere(
1927
                $qb->expr()->orX(
1928
                    'resource.startDate BETWEEN :start AND :end',
1929
                    'resource.endDate BETWEEN :start AND :end',
1930
                    $qb->expr()->orX(
1931
                        'resource.startDate IS NOT NULL AND resource.endDate IS NOT NULL AND
1932
                            YEAR(resource.startDate) = YEAR(resource.endDate) AND
1933
                            MONTH(:start) BETWEEN MONTH(resource.startDate) AND MONTH(resource.endDate)
1934
                        '
1935
                    )
1936
                )
1937
            )
1938
            ->setParameter('start', $start)
1939
            ->setParameter('end', $end);
1940
1941
            /*
1942
            $dateCondition .= "AND (
1943
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1944
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1945
                 (
1946
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1947
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1948
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1949
                 )
1950
            )";*/
1951
        }
1952
1953
        /*
1954
        if (empty($sessionId)) {
1955
            $sessionCondition = "
1956
            (
1957
                agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
1958
            ) ";
1959
        } else {
1960
            $sessionCondition = "
1961
            (
1962
                agenda.session_id = $sessionId AND
1963
                ip.session_id = $sessionId
1964
            ) ";
1965
        }
1966
1967
        if (api_is_allowed_to_edit()) {
1968
            $visibilityCondition = " (ip.visibility IN ('1', '0'))  ";
1969
        } else {
1970
            $visibilityCondition = " (ip.visibility = '1') ";
1971
        }
1972
1973
        $sql = "SELECT DISTINCT
1974
                    agenda.*,
1975
                    ip.visibility,
1976
                    ip.to_group_id,
1977
                    ip.insert_user_id,
1978
                    ip.ref,
1979
                    to_user_id
1980
                FROM $tlb_course_agenda agenda
1981
                INNER JOIN $tbl_property ip
1982
                ON (
1983
                    agenda.id = ip.ref AND
1984
                    agenda.c_id = ip.c_id AND
1985
                    ip.tool = '".TOOL_CALENDAR_EVENT."'
1986
                )
1987
                WHERE
1988
                    $sessionCondition AND
1989
                    ($userCondition) AND
1990
                    $visibilityCondition AND
1991
                    agenda.c_id = $courseId
1992
        ";
1993
        $dateCondition = '';
1994
        if (!empty($start) && !empty($end)) {
1995
            $dateCondition .= "AND (
1996
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1997
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1998
                 (
1999
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
2000
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
2001
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
2002
                 )
2003
            )";
2004
        }
2005
2006
        $sql .= $dateCondition;
2007
        $result = Database::query($sql);*/
2008
        $coachCanEdit = false;
2009
        if (!empty($sessionId)) {
2010
            $coachCanEdit = api_is_coach($sessionId, $courseId) || api_is_platform_admin();
2011
        }
2012
        //var_dump($groupMemberships, $courseId);        echo $qb->getQuery()->getSQL();exit;
2013
        $events = $qb->getQuery()->getResult();
2014
        //$eventsAdded = array_column($this->events, 'unique_id');
2015
        /** @var CCalendarEvent $row */
2016
        foreach ($events as $row) {
2017
            $eventId = $row->getIid();
2018
            $event = [];
2019
            $event['id'] = 'course_'.$eventId;
2020
            $event['unique_id'] = $eventId;
2021
            // To avoid doubles
2022
            /*if (in_array($event['unique_id'], $eventsAdded)) {
2023
                continue;
2024
            }*/
2025
2026
            $eventsAdded[] = $eventId;
2027
            //$eventId = $row['ref'];
2028
            /*$items = $this->getUsersAndGroupSubscribedToEvent(
2029
                $eventId,
2030
                $courseId,
2031
                $this->sessionId
2032
            );
2033
            $group_to_array = $items['groups'];
2034
            $user_to_array = $items['users'];*/
2035
            /*$attachmentList = $this->getAttachmentList(
2036
                $eventId,
2037
                $courseInfo
2038
            );*/
2039
            $attachmentList = $row->getAttachments();
2040
            $event['attachment'] = '';
2041
            if (!empty($attachmentList)) {
2042
                $icon = Display::returnFontAwesomeIcon(
2043
                    'paperclip',
2044
                    '1'
2045
                );
2046
                $repo = Container::getCalendarEventAttachmentRepository();
2047
                foreach ($attachmentList as $attachment) {
2048
                    //$url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$courseId.'&'.api_get_cidreq();
2049
                    $url = $repo->getResourceFileDownloadUrl($attachment);
2050
                    $event['attachment'] .= $icon.
2051
                        Display::url(
2052
                            $attachment->getFilename(),
2053
                            $url
2054
                        ).'<br />';
2055
                }
2056
            }
2057
2058
            $event['title'] = $row->getTitle();
2059
            $event['className'] = 'course';
2060
            $event['allDay'] = 'false';
2061
            $event['course_id'] = $courseId;
2062
            $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
2063
2064
            $sessionInfo = [];
2065
            if (!empty($row->getSessionId())) {
2066
                $sessionInfo = api_get_session_info($row->getSessionId());
2067
                $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
2068
            }
2069
2070
            $event['session_name'] = $sessionInfo['name'] ?? '';
2071
            $event['course_name'] = $courseInfo['title'] ?? '';
2072
2073
            /*if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
2074
                $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
2075
            }*/
2076
2077
            if (!empty($color)) {
2078
                $event['borderColor'] = $event['backgroundColor'] = $color;
2079
            }
2080
2081
            if ($row->getColor()) {
2082
                $event['borderColor'] = $event['backgroundColor'] = $row->getColor();
2083
            }
2084
2085
            $event['editable'] = false;
2086
            if ($this->getIsAllowedToEdit() && 'course' === $this->type) {
2087
                $event['editable'] = true;
2088
                if (!empty($sessionId)) {
2089
                    if (false == $coachCanEdit) {
2090
                        $event['editable'] = false;
2091
                    }
2092
                    if ($isAllowToEditByHrm) {
2093
                        $event['editable'] = true;
2094
                    }
2095
                }
2096
                // if user is author then he can edit the item
2097
                if (api_get_user_id() == $row->getResourceNode()->getCreator()->getId()) {
2098
                    $event['editable'] = true;
2099
                }
2100
            }
2101
2102
            if (!empty($row->getStartDate())) {
2103
                $event['start'] = $this->formatEventDate($row->getStartDate()->format('Y-m-d H:i:s'));
2104
                $event['start_date_localtime'] = api_get_local_time($row->getStartDate()->format('Y-m-d H:i:s'));
2105
            }
2106
            if (!empty($row->getEndDate())) {
2107
                $event['end'] = $this->formatEventDate($row->getEndDate()->format('Y-m-d H:i:s'));
2108
                $event['end_date_localtime'] = api_get_local_time($row->getEndDate()->format('Y-m-d H:i:s'));
2109
            }
2110
2111
            $event['sent_to'] = '';
2112
            $event['type'] = 'course';
2113
            if (0 != $row->getSessionId()) {
2114
                $event['type'] = 'session';
2115
            }
2116
2117
            $everyone = false;
2118
            $links = $row->getResourceNode()->getResourceLinks();
2119
            $sentTo = [];
2120
            foreach ($links as $link) {
2121
                if ($link->getUser()) {
2122
                    $sentTo[] = $link->getUser()->getFirstname();
2123
                }
2124
                if ($link->getCourse()) {
2125
                    $sentTo[] = $link->getCourse()->getName();
2126
                }
2127
                if ($link->getSession()) {
2128
                    $sentTo[] = $link->getSession()->getName();
2129
                }
2130
                if ($link->getGroup()) {
2131
                    $sentTo[] = $link->getGroup()->getName();
2132
                }
2133
            }
2134
2135
            // Event Sent to a group?
2136
            /*if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
2137
                $sent_to = [];
2138
                if (!empty($group_to_array)) {
2139
                    foreach ($group_to_array as $group_item) {
2140
                        $sent_to[] = $groupNameList[$group_item];
2141
                    }
2142
                }
2143
                $sent_to = implode('@@', $sent_to);
2144
                $sent_to = str_replace(
2145
                    '@@',
2146
                    '</div><div class="label_tag notice">',
2147
                    $sent_to
2148
                );
2149
                $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
2150
                $event['type'] = 'group';
2151
            }*/
2152
2153
            // Event sent to a user?
2154
            /*if (isset($row['to_user_id'])) {
2155
                $sent_to = [];
2156
                if (!empty($user_to_array)) {
2157
                    foreach ($user_to_array as $item) {
2158
                        $user_info = api_get_user_info($item);
2159
                        // Add username as tooltip for $event['sent_to'] - ref #4226
2160
                        $username = api_htmlentities(
2161
                            sprintf(
2162
                                get_lang('Login: %s'),
2163
                                $user_info['username']
2164
                            ),
2165
                            ENT_QUOTES
2166
                        );
2167
                        $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
2168
                    }
2169
                }
2170
                $sent_to = implode('@@', $sent_to);
2171
                $sent_to = str_replace(
2172
                    '@@',
2173
                    '</div><div class="label_tag notice">',
2174
                    $sent_to
2175
                );
2176
                $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
2177
            }*/
2178
2179
            //Event sent to everyone!
2180
            /*if (empty($event['sent_to'])) {
2181
                $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
2182
            }*/
2183
            $event['sent_to'] = implode('<br />', $sentTo);
2184
            $event['description'] = $row->getContent();
2185
            $event['visibility'] = $row->isVisible($courseEntity, $session) ? 1 : 0;
2186
            $event['real_id'] = $eventId;
2187
            $event['allDay'] = $row->getAllDay();
2188
            $event['parent_event_id'] = $row->getParentEventId();
2189
            $event['has_children'] = $this->hasChildren($eventId, $courseId) ? 1 : 0;
2190
            $event['comment'] = $row->getComment();
2191
            $this->events[] = $event;
2192
        }
2193
2194
        return $this->events;
2195
    }
2196
2197
    /**
2198
     * @param int $start tms
2199
     * @param int $end   tms
2200
     *
2201
     * @return array
2202
     */
2203
    public function getPlatformEvents($start, $end)
2204
    {
2205
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
2206
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
2207
        $dateCondition = '';
2208
2209
        if (!empty($start) && !empty($end)) {
2210
            $dateCondition .= "AND (
2211
                 start_date BETWEEN '".$start."' AND '".$end."' OR
2212
                 end_date BETWEEN '".$start."' AND '".$end."' OR
2213
                 (
2214
                     start_date IS NOT NULL AND end_date IS NOT NULL AND
2215
                     YEAR(start_date) = YEAR(end_date) AND
2216
                     MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
2217
                 )
2218
            )";
2219
        }
2220
2221
        $access_url_id = api_get_current_access_url_id();
2222
2223
        $sql = "SELECT *
2224
                FROM ".$this->tbl_global_agenda."
2225
                WHERE access_url_id = $access_url_id
2226
                $dateCondition";
2227
        $result = Database::query($sql);
2228
        $my_events = [];
2229
        if (Database::num_rows($result)) {
2230
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2231
                $event = [];
2232
                $event['id'] = 'platform_'.$row['id'];
2233
                $event['title'] = $row['title'];
2234
                $event['className'] = 'platform';
2235
                $event['allDay'] = 'false';
2236
                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
2237
                $event['editable'] = false;
2238
                $event['type'] = 'admin';
2239
2240
                if (api_is_platform_admin() && 'admin' === $this->type) {
2241
                    $event['editable'] = true;
2242
                }
2243
2244
                if (!empty($row['start_date'])) {
2245
                    $event['start'] = $this->formatEventDate($row['start_date']);
2246
                    $event['start_date_localtime'] = api_get_local_time($row['start_date']);
2247
                }
2248
2249
                if (!empty($row['end_date'])) {
2250
                    $event['end'] = $this->formatEventDate($row['end_date']);
2251
                    $event['end_date_localtime'] = api_get_local_time($row['end_date']);
2252
                }
2253
                $event['allDay'] = isset($row['all_day']) && 1 == $row['all_day'] ? $row['all_day'] : 0;
2254
                $event['parent_event_id'] = 0;
2255
                $event['has_children'] = 0;
2256
                $event['description'] = $row['content'];
2257
2258
                $my_events[] = $event;
2259
                $this->events[] = $event;
2260
            }
2261
        }
2262
2263
        return $my_events;
2264
    }
2265
2266
    /**
2267
     * @param FormValidator $form
2268
     * @param array         $groupList
2269
     * @param array         $userList
2270
     * @param array         $sendTo               array('users' => [1, 2], 'groups' => [3, 4])
2271
     * @param array         $attributes
2272
     * @param bool          $addOnlyItemsInSendTo
2273
     * @param bool          $required
2274
     */
2275
    public function setSendToSelect(
2276
        $form,
2277
        $groupList = [],
2278
        $userList = [],
2279
        $sendTo = [],
2280
        $attributes = [],
2281
        $addOnlyItemsInSendTo = false,
2282
        $required = false
2283
    ) {
2284
        $params = [
2285
            'id' => 'users_to_send_id',
2286
            'data-placeholder' => get_lang('Select'),
2287
            'multiple' => 'multiple',
2288
            'class' => 'multiple-select',
2289
        ];
2290
2291
        if (!empty($attributes)) {
2292
            $params = array_merge($params, $attributes);
2293
            if (empty($params['multiple'])) {
2294
                unset($params['multiple']);
2295
            }
2296
        }
2297
2298
        $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : [];
2299
        $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : [];
2300
2301
        /** @var HTML_QuickForm_select $select */
2302
        $select = $form->addSelect(
2303
            'users_to_send',
2304
            get_lang('To'),
2305
            null,
2306
            $params
2307
        );
2308
2309
        if ($required) {
2310
            $form->setRequired($select);
2311
        }
2312
2313
        $selectedEveryoneOptions = [];
2314
        if (isset($sendTo['everyone']) && $sendTo['everyone']) {
2315
            $selectedEveryoneOptions = ['selected'];
2316
            $sendToUsers = [];
2317
        }
2318
2319
        $select->addOption(
2320
            get_lang('Everyone'),
2321
            'everyone',
2322
            $selectedEveryoneOptions
2323
        );
2324
2325
        $options = [];
2326
        if (is_array($groupList)) {
2327
            foreach ($groupList as $group) {
2328
                $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
2329
                $count_users = " &ndash; $count_users ".get_lang('Users');
2330
                $option = [
2331
                    'text' => $group['name'].$count_users,
2332
                    'value' => "GROUP:".$group['id'],
2333
                ];
2334
                $selected = in_array(
2335
                    $group['id'],
2336
                    $sendToGroups
2337
                ) ? true : false;
2338
                if ($selected) {
2339
                    $option['selected'] = 'selected';
2340
                }
2341
2342
                if ($addOnlyItemsInSendTo) {
2343
                    if ($selected) {
2344
                        $options[] = $option;
2345
                    }
2346
                } else {
2347
                    $options[] = $option;
2348
                }
2349
            }
2350
            $select->addOptGroup($options, get_lang('Groups'));
2351
        }
2352
2353
        // adding the individual users to the select form
2354
        if (is_array($userList)) {
2355
            $options = [];
2356
            foreach ($userList as $user) {
2357
                if (ANONYMOUS == $user['status']) {
2358
                    continue;
2359
                }
2360
                $option = [
2361
                    'text' => api_get_person_name(
2362
                            $user['firstname'],
2363
                            $user['lastname']
2364
                        ).' ('.$user['username'].')',
2365
                    'value' => "USER:".$user['user_id'],
2366
                ];
2367
2368
                $selected = in_array(
2369
                    $user['user_id'],
2370
                    $sendToUsers
2371
                ) ? true : false;
2372
2373
                if ($selected) {
2374
                    $option['selected'] = 'selected';
2375
                }
2376
2377
                if ($addOnlyItemsInSendTo) {
2378
                    if ($selected) {
2379
                        $options[] = $option;
2380
                    }
2381
                } else {
2382
                    $options[] = $option;
2383
                }
2384
            }
2385
2386
            $select->addOptGroup($options, get_lang('Users'));
2387
        }
2388
    }
2389
2390
    /**
2391
     * Separates the users and groups array
2392
     * users have a value USER:XXX (with XXX the user id
2393
     * groups have a value GROUP:YYY (with YYY the group id)
2394
     * use the 'everyone' key.
2395
     *
2396
     * @author Julio Montoya based in separate_users_groups in agenda.inc.php
2397
     *
2398
     * @param array $to
2399
     *
2400
     * @return array
2401
     */
2402
    public function parseSendToArray($to)
2403
    {
2404
        $groupList = [];
2405
        $userList = [];
2406
        $sendTo = null;
2407
2408
        $sendTo['everyone'] = false;
2409
        if (is_array($to) && count($to) > 0) {
2410
            foreach ($to as $item) {
2411
                if ('everyone' == $item) {
2412
                    $sendTo['everyone'] = true;
2413
                } else {
2414
                    list($type, $id) = explode(':', $item);
2415
                    switch ($type) {
2416
                        case 'GROUP':
2417
                            $groupList[] = $id;
2418
                            break;
2419
                        case 'USER':
2420
                            $userList[] = $id;
2421
                            break;
2422
                    }
2423
                }
2424
            }
2425
            $sendTo['groups'] = $groupList;
2426
            $sendTo['users'] = $userList;
2427
        }
2428
2429
        return $sendTo;
2430
    }
2431
2432
    /**
2433
     * @param array $params
2434
     *
2435
     * @return FormValidator
2436
     */
2437
    public function getForm($params = [])
2438
    {
2439
        $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
2440
        $id = isset($params['id']) ? (int) $params['id'] : 0;
2441
2442
        $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
2443
        if ('course' == $this->type) {
2444
            $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
2445
        }
2446
2447
        $form = new FormValidator(
2448
            'add_event',
2449
            'post',
2450
            $url,
2451
            null,
2452
            ['enctype' => 'multipart/form-data']
2453
        );
2454
2455
        $idAttach = isset($params['id_attach']) ? (int) $params['id_attach'] : null;
2456
        $groupId = api_get_group_id();
2457
        $form_Title = get_lang('Add event to agenda');
2458
        if (!empty($id)) {
2459
            $form_Title = get_lang('Edit event');
2460
        }
2461
2462
        $form->addHeader($form_Title);
2463
        $form->addElement('hidden', 'id', $id);
2464
        $form->addElement('hidden', 'action', $action);
2465
        $form->addElement('hidden', 'id_attach', $idAttach);
2466
2467
        $isSubEventEdition = false;
2468
        $isParentFromSerie = false;
2469
        $showAttachmentForm = true;
2470
2471
        if ('course' == $this->type) {
2472
            // Edition mode.
2473
            if (!empty($id)) {
2474
                $showAttachmentForm = false;
2475
                if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
2476
                    $isSubEventEdition = true;
2477
                }
2478
                if (!empty($params['repeat_info'])) {
2479
                    $isParentFromSerie = true;
2480
                }
2481
            }
2482
        }
2483
2484
        if ($isSubEventEdition) {
2485
            $form->addElement(
2486
                'label',
2487
                null,
2488
                Display::return_message(
2489
                    get_lang('Editing this event will remove it from the serie of events it is currently part of'),
2490
                    'warning'
2491
                )
2492
            );
2493
        }
2494
2495
        $form->addElement('text', 'title', get_lang('Event name'));
2496
2497
        if (isset($groupId) && !empty($groupId)) {
2498
            $form->addElement(
2499
                'hidden',
2500
                'users_to_send[]',
2501
                "GROUP:$groupId"
2502
            );
2503
            $form->addElement('hidden', 'to', 'true');
2504
        } else {
2505
            $sendTo = isset($params['send_to']) ? $params['send_to'] : ['everyone' => true];
2506
            if ('course' == $this->type) {
2507
                $this->showToForm($form, $sendTo, [], false, true);
2508
            }
2509
        }
2510
2511
        $form->addDateRangePicker(
2512
            'date_range',
2513
            get_lang('Date range'),
2514
            false,
2515
            ['id' => 'date_range']
2516
        );
2517
        $form->addElement('checkbox', 'all_day', null, get_lang('All day'));
2518
2519
        if ('course' == $this->type) {
2520
            $repeat = $form->addElement(
2521
                'checkbox',
2522
                'repeat',
2523
                null,
2524
                get_lang('Repeat event'),
2525
                ['onclick' => 'return plus_repeated_event();']
2526
            );
2527
            $form->addElement(
2528
                'html',
2529
                '<div id="options2" style="display:none">'
2530
            );
2531
            $form->addElement(
2532
                'select',
2533
                'repeat_type',
2534
                get_lang('Repeat type'),
2535
                self::getRepeatTypes()
2536
            );
2537
            $form->addElement(
2538
                'date_picker',
2539
                'repeat_end_day',
2540
                get_lang('Repeat end date'),
2541
                ['id' => 'repeat_end_date_form']
2542
            );
2543
2544
            if ($isSubEventEdition || $isParentFromSerie) {
2545
                $repeatInfo = $params['repeat_info'];
2546
                if ($isSubEventEdition) {
2547
                    $parentEvent = $params['parent_info'];
2548
                    $repeatInfo = $parentEvent['repeat_info'];
2549
                }
2550
                $params['repeat'] = 1;
2551
                $params['repeat_type'] = $repeatInfo['cal_type'];
2552
                $params['repeat_end_day'] = substr(
2553
                    api_get_local_time($repeatInfo['cal_end']),
2554
                    0,
2555
                    10
2556
                );
2557
2558
                $form->freeze(['repeat_type', 'repeat_end_day']);
2559
                $repeat->_attributes['disabled'] = 'disabled';
2560
            }
2561
            $form->addElement('html', '</div>');
2562
        }
2563
2564
        if (!empty($id)) {
2565
            if (empty($params['end_date'])) {
2566
                $params['date_range'] = $params['end_date'];
2567
            }
2568
2569
            $params['date_range'] =
2570
                substr(api_get_local_time($params['start_date']), 0, 16).' / '.
2571
                substr(api_get_local_time($params['end_date']), 0, 16);
2572
        }
2573
2574
        $toolbar = 'Agenda';
2575
        if (!api_is_allowed_to_edit(null, true)) {
2576
            $toolbar = 'AgendaStudent';
2577
        }
2578
2579
        $form->addElement(
2580
            'html_editor',
2581
            'content',
2582
            get_lang('Description'),
2583
            null,
2584
            [
2585
                'ToolbarSet' => $toolbar,
2586
                'Width' => '100%',
2587
                'Height' => '200',
2588
            ]
2589
        );
2590
2591
        if ('course' == $this->type) {
2592
            $form->addElement('textarea', 'comment', get_lang('Comment'));
2593
            $form->addLabel(
2594
                get_lang('Files attachments'),
2595
                '<div id="filepaths" class="file-upload-event">
2596
2597
                        <div id="filepath_1">
2598
                            <input type="file" name="attach_1"/>
2599
2600
                            <label>'.get_lang('Description').'</label>
2601
                            <input class="form-control" type="text" name="legend[]" />
2602
                        </div>
2603
2604
                    </div>'
2605
            );
2606
2607
            $form->addLabel(
2608
                '',
2609
                '<span id="link-more-attach">
2610
                    <a href="javascript://" onclick="return add_image_form()">'.
2611
                get_lang('Add one more file').'</a>
2612
                 </span>&nbsp;('.sprintf(
2613
                    get_lang('Maximun file size: %s'),
2614
                    format_file_size(
2615
                        api_get_setting('message_max_upload_filesize')
2616
                    )
2617
                ).')'
2618
            );
2619
2620
            if (isset($params['attachment']) && !empty($params['attachment'])) {
2621
                $attachmentList = $params['attachment'];
2622
                foreach ($attachmentList as $attachment) {
2623
                    $params['file_comment'] = $attachment['comment'];
2624
                    if (!empty($attachment['path'])) {
2625
                        $form->addElement(
2626
                            'checkbox',
2627
                            'delete_attachment['.$attachment['id'].']',
2628
                            null,
2629
                            get_lang(
2630
                                'DeleteAttachment'
2631
                            ).': '.$attachment['filename']
2632
                        );
2633
                    }
2634
                }
2635
            }
2636
2637
            $form->addElement(
2638
                'textarea',
2639
                'file_comment',
2640
                get_lang('File comment')
2641
            );
2642
        }
2643
2644
        if (empty($id)) {
2645
            $form->addElement(
2646
                'checkbox',
2647
                'add_announcement',
2648
                null,
2649
                get_lang('Add an announcement').'&nbsp('.get_lang('Send mail').')'
2650
            );
2651
        }
2652
2653
        if ($id) {
2654
            $form->addButtonUpdate(get_lang('Edit event'));
2655
        } else {
2656
            $form->addButtonSave(get_lang('Add event'));
2657
        }
2658
2659
        $form->setDefaults($params);
2660
        $form->addRule(
2661
            'date_range',
2662
            get_lang('Required field'),
2663
            'required'
2664
        );
2665
        $form->addRule('title', get_lang('Required field'), 'required');
2666
2667
        return $form;
2668
    }
2669
2670
    /**
2671
     * @param FormValidator $form
2672
     * @param array         $sendTo               array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
2673
     * @param array         $attributes
2674
     * @param bool          $addOnlyItemsInSendTo
2675
     * @param bool          $required
2676
     *
2677
     * @return bool
2678
     */
2679
    public function showToForm(
2680
        $form,
2681
        $sendTo = [],
2682
        $attributes = [],
2683
        $addOnlyItemsInSendTo = false,
2684
        $required = false
2685
    ) {
2686
        if ('course' != $this->type) {
2687
            return false;
2688
        }
2689
2690
        $order = 'lastname';
2691
        if (api_is_western_name_order()) {
2692
            $order = 'firstname';
2693
        }
2694
2695
        $userList = CourseManager::get_user_list_from_course_code(
2696
            api_get_course_id(),
2697
            $this->sessionId,
2698
            null,
2699
            $order
2700
        );
2701
2702
        $groupList = CourseManager::get_group_list_of_course(
2703
            api_get_course_id(),
2704
            $this->sessionId
2705
        );
2706
2707
        $this->setSendToSelect(
2708
            $form,
2709
            $groupList,
2710
            $userList,
2711
            $sendTo,
2712
            $attributes,
2713
            $addOnlyItemsInSendTo,
2714
            $required
2715
        );
2716
2717
        return true;
2718
    }
2719
2720
    /**
2721
     * @param int   $id
2722
     * @param int   $visibility 0= invisible, 1 visible
2723
     * @param array $courseInfo
2724
     * @param int   $userId
2725
     */
2726
    public static function changeVisibility(
2727
        $id,
2728
        $visibility,
2729
        $courseInfo,
2730
        $userId = null
2731
    ) {
2732
        $id = (int) $id;
2733
2734
        $repo = Container::getCalendarEventRepository();
2735
        /** @var CCalendarEvent $event */
2736
        $event = $repo->find($id);
2737
        $visibility = (int) $visibility;
2738
2739
        if ($event) {
2740
            if (0 === $visibility) {
2741
                $repo->setVisibilityDraft($event);
2742
            } else {
2743
                $repo->setVisibilityPublished($event);
2744
            }
2745
        }
2746
2747
        return true;
2748
2749
        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...
2750
            $userId = api_get_user_id();
2751
        } else {
2752
            $userId = (int) $userId;
2753
        }
2754
2755
        if (0 === $visibility) {
2756
            api_item_property_update(
2757
                $courseInfo,
2758
                TOOL_CALENDAR_EVENT,
2759
                $id,
2760
                'invisible',
2761
                $userId
2762
            );
2763
        } else {
2764
            api_item_property_update(
2765
                $courseInfo,
2766
                TOOL_CALENDAR_EVENT,
2767
                $id,
2768
                'visible',
2769
                $userId
2770
            );
2771
        }
2772
    }
2773
2774
    /**
2775
     * Get repeat types.
2776
     */
2777
    public static function getRepeatTypes(): array
2778
    {
2779
        return [
2780
            'daily' => get_lang('Daily'),
2781
            'weekly' => get_lang('Weekly'),
2782
            'monthlyByDate' => get_lang('Monthly, by date'),
2783
            //monthlyByDay"> get_lang('Monthly, by day');
2784
            //monthlyByDayR' => get_lang('Monthly, by dayR'),
2785
            'yearly' => get_lang('Yearly'),
2786
        ];
2787
    }
2788
2789
    /**
2790
     * Show a list with all the attachments according to the post's id.
2791
     *
2792
     * @param int   $eventId
2793
     * @param array $courseInfo
2794
     *
2795
     * @return array with the post info
2796
     */
2797
    public function getAttachmentList($eventId, $courseInfo)
2798
    {
2799
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2800
        $courseId = (int) $courseInfo['real_id'];
2801
        $eventId = (int) $eventId;
2802
2803
        $sql = "SELECT id, path, filename, comment
2804
                FROM $tableAttachment
2805
                WHERE
2806
                    c_id = $courseId AND
2807
                    agenda_id = $eventId";
2808
        $result = Database::query($sql);
2809
        $list = [];
2810
        if (0 != Database::num_rows($result)) {
2811
            $list = Database::store_result($result, 'ASSOC');
2812
        }
2813
2814
        return $list;
2815
    }
2816
2817
    /**
2818
     * Show a list with all the attachments according to the post's id.
2819
     *
2820
     * @param int   $attachmentId
2821
     * @param int   $eventId
2822
     * @param array $courseInfo
2823
     *
2824
     * @return array with the post info
2825
     */
2826
    public function getAttachment($attachmentId, $eventId, $courseInfo)
2827
    {
2828
        if (empty($courseInfo) || empty($attachmentId) || empty($eventId)) {
2829
            return [];
2830
        }
2831
2832
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2833
        $courseId = (int) $courseInfo['real_id'];
2834
        $eventId = (int) $eventId;
2835
        $attachmentId = (int) $attachmentId;
2836
2837
        $row = [];
2838
        $sql = "SELECT id, path, filename, comment
2839
                FROM $tableAttachment
2840
                WHERE
2841
                    c_id = $courseId AND
2842
                    agenda_id = $eventId AND
2843
                    id = $attachmentId
2844
                ";
2845
        $result = Database::query($sql);
2846
        if (0 != Database::num_rows($result)) {
2847
            $row = Database::fetch_array($result, 'ASSOC');
2848
        }
2849
2850
        return $row;
2851
    }
2852
2853
    /**
2854
     * Add an attachment file into agenda.
2855
     *
2856
     * @param CCalendarEvent $event
2857
     * @param UploadedFile   $file
2858
     * @param string         $comment
2859
     * @param array          $courseInfo
2860
     *
2861
     * @return string
2862
     */
2863
    public function addAttachment(
2864
        $event,
2865
        $file,
2866
        $comment,
2867
        $courseInfo
2868
    ) {
2869
        // Storing the attachments
2870
        $valid = false;
2871
        if ($file) {
2872
            $valid = process_uploaded_file($file);
2873
        }
2874
2875
        if ($valid) {
2876
            /*$courseDir = $courseInfo['directory'].'/upload/calendar';
2877
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2878
            $uploadDir = $sys_course_path.$courseDir;*/
2879
2880
            // Try to add an extension to the file if it hasn't one
2881
            /*$new_file_name = add_ext_on_mime(
2882
                stripslashes($fileUserUpload['name']),
2883
                $fileUserUpload['type']
2884
            );*/
2885
2886
            // user's file name
2887
            $fileName = $file->getClientOriginalName();
2888
            $courseId = api_get_course_int_id();
2889
            /*$new_file_name = uniqid('');
2890
            $new_path = $uploadDir.'/'.$new_file_name;
2891
            $result = @move_uploaded_file(
2892
                $fileUserUpload['tmp_name'],
2893
                $new_path
2894
            );
2895
            $courseId = api_get_course_int_id();
2896
            $size = intval($fileUserUpload['size']);*/
2897
            // Storing the attachments if any
2898
            //if ($result) {
2899
            $attachment = new CCalendarEventAttachment();
2900
            $attachment
2901
                ->setCId($courseId)
2902
                ->setFilename($fileName)
2903
                ->setComment($comment)
2904
                ->setPath($fileName)
2905
                ->setEvent($event)
2906
                ->setSize($file->getSize())
2907
            ;
2908
2909
            $repo = Container::getCalendarEventAttachmentRepository();
2910
2911
            $repo->addResourceToCourseWithParent(
2912
                $attachment,
2913
                $event->getResourceNode(),
2914
                ResourceLink::VISIBILITY_PUBLISHED,
2915
                api_get_user_entity(api_get_user_id()),
2916
                api_get_course_entity(),
2917
                api_get_session_entity(),
2918
                api_get_group_entity(),
2919
                $file
2920
            );
2921
2922
            $repo->getEntityManager()->flush();
2923
2924
            $id = $attachment->getIid();
2925
            if ($id) {
2926
                $table = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2927
                $sql = "UPDATE $table
2928
                        SET id = iid WHERE iid = $id";
2929
                Database::query($sql);
2930
2931
                /*api_item_property_update(
2932
                    $courseInfo,
2933
                    'calendar_event_attachment',
2934
                    $id,
2935
                    'AgendaAttachmentAdded',
2936
                    api_get_user_id()
2937
                );*/
2938
            }
2939
        }
2940
    }
2941
2942
    /**
2943
     * @param int    $attachmentId
2944
     * @param int    $eventId
2945
     * @param array  $fileUserUpload
2946
     * @param string $comment
2947
     * @param array  $courseInfo
2948
     */
2949
    public function updateAttachment(
2950
        $attachmentId,
2951
        $eventId,
2952
        $fileUserUpload,
2953
        $comment,
2954
        $courseInfo
2955
    ) {
2956
        $attachment = $this->getAttachment(
2957
            $attachmentId,
2958
            $eventId,
2959
            $courseInfo
2960
        );
2961
        if (!empty($attachment)) {
2962
            $this->deleteAttachmentFile($attachmentId, $courseInfo);
2963
        }
2964
        $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
2965
    }
2966
2967
    /**
2968
     * This function delete a attachment file by id.
2969
     *
2970
     * @param int   $attachmentId
2971
     * @param array $courseInfo
2972
     *
2973
     * @return string
2974
     */
2975
    public function deleteAttachmentFile($attachmentId, $courseInfo)
2976
    {
2977
        $table = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2978
        $attachmentId = (int) $attachmentId;
2979
        $courseId = $courseInfo['real_id'];
2980
2981
        if (empty($courseId) || empty($attachmentId)) {
2982
            return false;
2983
        }
2984
2985
        $sql = "DELETE FROM $table
2986
                WHERE c_id = $courseId AND id = ".$attachmentId;
2987
        $result = Database::query($sql);
2988
2989
        // update item_property
2990
        api_item_property_update(
2991
            $courseInfo,
2992
            'calendar_event_attachment',
2993
            $attachmentId,
2994
            'AgendaAttachmentDeleted',
2995
            api_get_user_id()
2996
        );
2997
2998
        if (!empty($result)) {
2999
            return Display::return_message(
3000
                get_lang("The attached file has been deleted"),
3001
                'confirmation'
3002
            );
3003
        }
3004
    }
3005
3006
    /**
3007
     * @param int $eventId
3008
     *
3009
     * @return array
3010
     */
3011
    public function getAllRepeatEvents($eventId)
3012
    {
3013
        $events = [];
3014
        $eventId = (int) $eventId;
3015
3016
        switch ($this->type) {
3017
            case 'personal':
3018
                break;
3019
            case 'course':
3020
                if (!empty($this->course['real_id'])) {
3021
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
3022
                            WHERE
3023
                                c_id = ".$this->course['real_id']." AND
3024
                                parent_event_id = ".$eventId;
3025
                    $result = Database::query($sql);
3026
                    if (Database::num_rows($result)) {
3027
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
3028
                            $events[] = $row;
3029
                        }
3030
                    }
3031
                }
3032
                break;
3033
        }
3034
3035
        return $events;
3036
    }
3037
3038
    /**
3039
     * @param int $eventId
3040
     * @param int $courseId
3041
     *
3042
     * @return bool
3043
     */
3044
    public function hasChildren($eventId, $courseId)
3045
    {
3046
        $eventId = (int) $eventId;
3047
        $courseId = (int) $courseId;
3048
3049
        $sql = "SELECT count(DISTINCT(id)) as count
3050
                FROM ".$this->tbl_course_agenda."
3051
                WHERE
3052
                    c_id = $courseId AND
3053
                    parent_event_id = $eventId";
3054
        $result = Database::query($sql);
3055
        if (Database::num_rows($result)) {
3056
            $row = Database::fetch_array($result, 'ASSOC');
3057
3058
            return $row['count'] > 0;
3059
        }
3060
3061
        return false;
3062
    }
3063
3064
    /**
3065
     * @param int    $filter
3066
     * @param string $view
3067
     *
3068
     * @return string
3069
     */
3070
    public function displayActions($view, $filter = 0)
3071
    {
3072
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
3073
        $groupIid = isset($groupInfo['iid']) ? $groupInfo['iid'] : 0;
3074
3075
        $codePath = api_get_path(WEB_CODE_PATH);
3076
3077
        $currentUserId = api_get_user_id();
3078
        $cidReq = api_get_cidreq();
3079
3080
        $actionsLeft = '';
3081
        $actionsLeft .= Display::url(
3082
            Display::return_icon('calendar.png', get_lang('Calendar'), [], ICON_SIZE_MEDIUM),
3083
            $codePath."calendar/agenda_js.php?type={$this->type}&$cidReq"
3084
        );
3085
        $actionsLeft .= Display::url(
3086
            Display::return_icon('week.png', get_lang('Agenda list'), [], ICON_SIZE_MEDIUM),
3087
            $codePath."calendar/agenda_list.php?type={$this->type}&$cidReq"
3088
        );
3089
3090
        $form = '';
3091
        if (api_is_allowed_to_edit(false, true) ||
3092
            ('1' == api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) &&
3093
            api_is_allowed_to_session_edit(false, true)
3094
            || (
3095
                GroupManager::user_has_access($currentUserId, $groupIid, GroupManager::GROUP_TOOL_CALENDAR)
3096
                && GroupManager::is_tutor_of_group($currentUserId, $groupInfo)
3097
            )
3098
        ) {
3099
            $actionsLeft .= Display::url(
3100
                Display::return_icon('new_event.png', get_lang('Add event'), [], ICON_SIZE_MEDIUM),
3101
                $codePath."calendar/agenda.php?action=add&type={$this->type}&$cidReq"
3102
            );
3103
3104
            $actionsLeft .= Display::url(
3105
                Display::return_icon('import_calendar.png', get_lang('Outlook import'), [], ICON_SIZE_MEDIUM),
3106
                $codePath."calendar/agenda.php?action=importical&type={$this->type}&$cidReq"
3107
            );
3108
3109
            if ('course' === $this->type) {
3110
                if (!isset($_GET['action'])) {
3111
                    $form = new FormValidator(
3112
                        'form-search',
3113
                        'post',
3114
                        '',
3115
                        '',
3116
                        [],
3117
                        FormValidator::LAYOUT_INLINE
3118
                    );
3119
                    $attributes = [
3120
                        'multiple' => false,
3121
                        'id' => 'select_form_id_search',
3122
                    ];
3123
                    $selectedValues = $this->parseAgendaFilter($filter);
3124
                    $this->showToForm($form, $selectedValues, $attributes);
3125
                    $form = $form->returnForm();
3126
                }
3127
            }
3128
        }
3129
3130
        if ('personal' == $this->type && !api_is_anonymous()) {
3131
            $actionsLeft .= Display::url(
3132
                Display::return_icon('1day.png', get_lang('Sessions plan calendar'), [], ICON_SIZE_MEDIUM),
3133
                $codePath."calendar/planification.php"
3134
            );
3135
3136
            if (api_is_student_boss() || api_is_platform_admin()) {
3137
                $actionsLeft .= Display::url(
3138
                    Display::return_icon('calendar-user.png', get_lang('MyStudentsSchedule'), [], ICON_SIZE_MEDIUM),
3139
                    $codePath.'mySpace/calendar_plan.php'
3140
                );
3141
            }
3142
        }
3143
3144
        if (api_is_platform_admin() ||
3145
            api_is_teacher() ||
3146
            api_is_student_boss() ||
3147
            api_is_drh() ||
3148
            api_is_session_admin() ||
3149
            api_is_coach()
3150
        ) {
3151
            if ('personal' == $this->type) {
3152
                $form = null;
3153
                if (!isset($_GET['action'])) {
3154
                    $form = new FormValidator(
3155
                        'form-search',
3156
                        'get',
3157
                        api_get_self().'?type=personal&',
3158
                        '',
3159
                        [],
3160
                        FormValidator::LAYOUT_INLINE
3161
                    );
3162
3163
                    $sessions = [];
3164
3165
                    if (api_is_drh()) {
3166
                        $sessionList = SessionManager::get_sessions_followed_by_drh($currentUserId);
3167
                        if (!empty($sessionList)) {
3168
                            foreach ($sessionList as $sessionItem) {
3169
                                $sessions[$sessionItem['id']] = strip_tags($sessionItem['name']);
3170
                            }
3171
                        }
3172
                    } else {
3173
                        $sessions = SessionManager::get_sessions_by_user($currentUserId);
3174
                        $sessions = array_column($sessions, 'session_name', 'session_id');
3175
                    }
3176
3177
                    $form->addHidden('type', 'personal');
3178
                    $sessions = ['0' => get_lang('Please select an option')] + $sessions;
3179
3180
                    $form->addSelect(
3181
                        'session_id',
3182
                        get_lang('Session'),
3183
                        $sessions,
3184
                        ['id' => 'session_id', 'onchange' => 'submit();']
3185
                    );
3186
3187
                    $form->addButtonReset(get_lang('Reset'));
3188
                    $form = $form->returnForm();
3189
                }
3190
            }
3191
        }
3192
3193
        $actionsRight = '';
3194
        if ('calendar' == $view) {
3195
            $actionsRight .= $form;
3196
        }
3197
3198
        $toolbar = Display::toolbarAction(
3199
            'toolbar-agenda',
3200
            [$actionsLeft, $actionsRight]
3201
        );
3202
3203
        return $toolbar;
3204
    }
3205
3206
    /**
3207
     * @return FormValidator
3208
     */
3209
    public function getImportCalendarForm()
3210
    {
3211
        $form = new FormValidator(
3212
            'frm_import_ical',
3213
            'post',
3214
            api_get_self().'?action=importical&type='.$this->type,
3215
            ['enctype' => 'multipart/form-data']
3216
        );
3217
        $form->addHeader(get_lang('Outlook import'));
3218
        $form->addElement('file', 'ical_import', get_lang('Outlook import'));
3219
        $form->addRule(
3220
            'ical_import',
3221
            get_lang('Required field'),
3222
            'required'
3223
        );
3224
        $form->addButtonImport(get_lang('Import'), 'ical_submit');
3225
3226
        return $form;
3227
    }
3228
3229
    /**
3230
     * @param array $courseInfo
3231
     * @param $file
3232
     *
3233
     * @return false|string
3234
     */
3235
    public function importEventFile($courseInfo, $file)
3236
    {
3237
        $charset = api_get_system_encoding();
3238
        $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
3239
        $messages = [];
3240
3241
        if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
3242
            error_log(
3243
                'Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__
3244
            );
3245
3246
            return false;
3247
        }
3248
3249
        $data = file_get_contents($filepath);
3250
3251
        $trans = [
3252
            'DAILY' => 'daily',
3253
            'WEEKLY' => 'weekly',
3254
            'MONTHLY' => 'monthlyByDate',
3255
            'YEARLY' => 'yearly',
3256
        ];
3257
        $sentTo = ['everyone' => true];
3258
        $calendar = Sabre\VObject\Reader::read($data);
3259
        $currentTimeZone = api_get_timezone();
3260
        if (!empty($calendar->VEVENT)) {
3261
            foreach ($calendar->VEVENT as $event) {
3262
                $start = $event->DTSTART->getDateTime();
3263
                $end = $event->DTEND->getDateTime();
3264
                //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
3265
3266
                $startDateTime = api_get_local_time(
3267
                    $start->format('Y-m-d H:i:s'),
3268
                    $currentTimeZone,
3269
                    $start->format('e')
3270
                );
3271
                $endDateTime = api_get_local_time(
3272
                    $end->format('Y-m-d H:i'),
3273
                    $currentTimeZone,
3274
                    $end->format('e')
3275
                );
3276
                $title = api_convert_encoding(
3277
                    (string) $event->summary,
3278
                    $charset,
3279
                    'UTF-8'
3280
                );
3281
                $description = api_convert_encoding(
3282
                    (string) $event->description,
3283
                    $charset,
3284
                    'UTF-8'
3285
                );
3286
3287
                $id = $this->addEvent(
3288
                    $startDateTime,
3289
                    $endDateTime,
3290
                    'false',
3291
                    $title,
3292
                    $description,
3293
                    $sentTo
3294
                );
3295
3296
                $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
3297
3298
                //$attendee = (string)$event->attendee;
3299
                /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
3300
                $repeat = $event->RRULE;
3301
                if ($id && !empty($repeat)) {
3302
                    $repeat = $repeat->getParts();
3303
                    $freq = $trans[$repeat['FREQ']];
3304
3305
                    if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
3306
                        // Check if datetime or just date (strlen == 8)
3307
                        if (8 == strlen($repeat['UNTIL'])) {
3308
                            // Fix the datetime format to avoid exception in the next step
3309
                            $repeat['UNTIL'] .= 'T000000';
3310
                        }
3311
                        $until = Sabre\VObject\DateTimeParser::parseDateTime(
3312
                            $repeat['UNTIL'],
3313
                            new DateTimeZone($currentTimeZone)
3314
                        );
3315
                        $until = $until->format('Y-m-d H:i:s');
3316
                        $this->addRepeatedItem(
3317
                            $id,
3318
                            $freq,
3319
                            $until,
3320
                            $sentTo
3321
                        );
3322
                    }
3323
                }
3324
            }
3325
        }
3326
3327
        if (!empty($messages)) {
3328
            $messages = implode('<br /> ', $messages);
3329
        } else {
3330
            $messages = get_lang('There are no events');
3331
        }
3332
3333
        return $messages;
3334
    }
3335
3336
    /**
3337
     * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]].
3338
     *
3339
     * @param int $filter
3340
     *
3341
     * @return array
3342
     */
3343
    public function parseAgendaFilter($filter)
3344
    {
3345
        $everyone = false;
3346
        $groupId = null;
3347
        $userId = null;
3348
3349
        if ('everyone' === $filter) {
3350
            $everyone = true;
3351
        } else {
3352
            if ('G' === substr($filter, 0, 1)) {
3353
                $groupId = str_replace('GROUP:', '', $filter);
3354
            } else {
3355
                $userId = str_replace('USER:', '', $filter);
3356
            }
3357
        }
3358
        if (empty($userId) && empty($groupId)) {
3359
            $everyone = true;
3360
        }
3361
3362
        return [
3363
            'everyone' => $everyone,
3364
            'users' => [$userId],
3365
            'groups' => [$groupId],
3366
        ];
3367
    }
3368
3369
    /**
3370
     *    This function retrieves all the agenda items of all the courses the user is subscribed to.
3371
     */
3372
    public static function get_myagendaitems(
3373
        $user_id,
3374
        $courses_dbs,
3375
        $month,
3376
        $year
3377
    ) {
3378
        $user_id = (int) $user_id;
3379
3380
        $items = [];
3381
        $my_list = [];
3382
3383
        // get agenda-items for every course
3384
        foreach ($courses_dbs as $key => $array_course_info) {
3385
            //databases of the courses
3386
            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
3387
            $TABLE_ITEMPROPERTY = Database::get_course_table(
3388
                TABLE_ITEM_PROPERTY
3389
            );
3390
3391
            $group_memberships = GroupManager::get_group_ids(
3392
                $array_course_info['real_id'],
3393
                $user_id
3394
            );
3395
            $course_user_status = CourseManager::getUserInCourseStatus(
3396
                $user_id,
3397
                $array_course_info['real_id']
3398
            );
3399
            // if the user is administrator of that course we show all the agenda items
3400
            if ('1' == $course_user_status) {
3401
                //echo "course admin";
3402
                $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3403
							FROM ".$TABLEAGENDA." agenda,
3404
								 ".$TABLE_ITEMPROPERTY." ip
3405
							WHERE agenda.id = ip.ref
3406
							AND MONTH(agenda.start_date)='".$month."'
3407
							AND YEAR(agenda.start_date)='".$year."'
3408
							AND ip.tool='".TOOL_CALENDAR_EVENT."'
3409
							AND ip.visibility='1'
3410
							GROUP BY agenda.id
3411
							ORDER BY start_date ";
3412
            } else {
3413
                // if the user is not an administrator of that course
3414
                if (is_array($group_memberships) && count(
3415
                        $group_memberships
3416
                    ) > 0
3417
                ) {
3418
                    $sqlquery = "SELECT	agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3419
								FROM ".$TABLEAGENDA." agenda,
3420
									".$TABLE_ITEMPROPERTY." ip
3421
								WHERE agenda.id = ip.ref
3422
								AND MONTH(agenda.start_date)='".$month."'
3423
								AND YEAR(agenda.start_date)='".$year."'
3424
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3425
								AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
3426
                            ", ",
3427
                            $group_memberships
3428
                        ).")) )
3429
								AND ip.visibility='1'
3430
								ORDER BY start_date ";
3431
                } else {
3432
                    $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3433
								FROM ".$TABLEAGENDA." agenda,
3434
									".$TABLE_ITEMPROPERTY." ip
3435
								WHERE agenda.id = ip.ref
3436
								AND MONTH(agenda.start_date)='".$month."'
3437
								AND YEAR(agenda.start_date)='".$year."'
3438
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3439
								AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
3440
								AND ip.visibility='1'
3441
								ORDER BY start_date ";
3442
                }
3443
            }
3444
            $result = Database::query($sqlquery);
3445
3446
            while ($item = Database::fetch_array($result, 'ASSOC')) {
3447
                $agendaday = -1;
3448
                if (!empty($item['start_date'])) {
3449
                    $item['start_date'] = api_get_local_time(
3450
                        $item['start_date']
3451
                    );
3452
                    $item['start_date_tms'] = api_strtotime(
3453
                        $item['start_date']
3454
                    );
3455
                    $agendaday = date("j", $item['start_date_tms']);
3456
                }
3457
                if (!empty($item['end_date'])) {
3458
                    $item['end_date'] = api_get_local_time($item['end_date']);
3459
                }
3460
3461
                $url = api_get_path(
3462
                        WEB_CODE_PATH
3463
                    )."calendar/agenda.php?cidReq=".urlencode(
3464
                        $array_course_info["code"]
3465
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
3466
3467
                $item['url'] = $url;
3468
                $item['course_name'] = $array_course_info['title'];
3469
                $item['calendar_type'] = 'course';
3470
                $item['course_id'] = $array_course_info['course_id'];
3471
3472
                $my_list[$agendaday][] = $item;
3473
            }
3474
        }
3475
3476
        // sorting by hour for every day
3477
        $agendaitems = [];
3478
        foreach ($items as $agendaday => $tmpitems) {
3479
            if (!isset($agendaitems[$agendaday])) {
3480
                $agendaitems[$agendaday] = '';
3481
            }
3482
            sort($tmpitems);
3483
            foreach ($tmpitems as $val) {
3484
                $agendaitems[$agendaday] .= $val;
3485
            }
3486
        }
3487
3488
        return $my_list;
3489
    }
3490
3491
    /**
3492
     * This function retrieves one personal agenda item returns it.
3493
     *
3494
     * @param    array    The array containing existing events. We add to this array.
3495
     * @param    int        Day
3496
     * @param    int        Month
3497
     * @param    int        Year (4 digits)
3498
     * @param    int        Week number
3499
     * @param    string    Type of view (month_view, week_view, day_view)
3500
     *
3501
     * @return array The results of the database query, or null if not found
3502
     */
3503
    public static function get_global_agenda_items(
3504
        $agendaitems,
3505
        $day = "",
3506
        $month = "",
3507
        $year = "",
3508
        $week = "",
3509
        $type
3510
    ) {
3511
        $tbl_global_agenda = Database::get_main_table(
3512
            TABLE_MAIN_SYSTEM_CALENDAR
3513
        );
3514
        $month = intval($month);
3515
        $year = intval($year);
3516
        $week = intval($week);
3517
        $day = intval($day);
3518
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3519
3520
        $current_access_url_id = api_get_current_access_url_id();
3521
3522
        if ("month_view" == $type or "" == $type) {
3523
            // We are in month view
3524
            $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";
3525
        }
3526
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3527
        if ("week_view" == $type) { // we are in week view
3528
            $start_end_day_of_week = self::calculate_start_end_of_week(
3529
                $week,
3530
                $year
3531
            );
3532
            $start_day = $start_end_day_of_week['start']['day'];
3533
            $start_month = $start_end_day_of_week['start']['month'];
3534
            $start_year = $start_end_day_of_week['start']['year'];
3535
            $end_day = $start_end_day_of_week['end']['day'];
3536
            $end_month = $start_end_day_of_week['end']['month'];
3537
            $end_year = $start_end_day_of_week['end']['year'];
3538
            // in sql statements you have to use year-month-day for date calculations
3539
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3540
            $start_filter = api_get_utc_datetime($start_filter);
3541
3542
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3543
            $end_filter = api_get_utc_datetime($end_filter);
3544
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND  access_url_id = $current_access_url_id ";
3545
        }
3546
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3547
        if ("day_view" == $type) { // we are in day view
3548
            // we could use mysql date() function but this is only available from 4.1 and higher
3549
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3550
            $start_filter = api_get_utc_datetime($start_filter);
3551
3552
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3553
            $end_filter = api_get_utc_datetime($end_filter);
3554
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'  AND  access_url_id = $current_access_url_id";
3555
        }
3556
3557
        $result = Database::query($sql);
3558
3559
        while ($item = Database::fetch_array($result)) {
3560
            if (!empty($item['start_date'])) {
3561
                $item['start_date'] = api_get_local_time($item['start_date']);
3562
                $item['start_date_tms'] = api_strtotime($item['start_date']);
3563
            }
3564
            if (!empty($item['end_date'])) {
3565
                $item['end_date'] = api_get_local_time($item['end_date']);
3566
            }
3567
3568
            // we break the date field in the database into a date and a time part
3569
            $agenda_db_date = explode(" ", $item['start_date']);
3570
            $date = $agenda_db_date[0];
3571
            $time = $agenda_db_date[1];
3572
            // we divide the date part into a day, a month and a year
3573
            $agendadate = explode("-", $date);
3574
            $year = intval($agendadate[0]);
3575
            $month = intval($agendadate[1]);
3576
            $day = intval($agendadate[2]);
3577
            // we divide the time part into hour, minutes, seconds
3578
            $agendatime = explode(":", $time);
3579
            $hour = $agendatime[0];
3580
            $minute = $agendatime[1];
3581
            $second = $agendatime[2];
3582
3583
            if ('month_view' == $type) {
3584
                $item['calendar_type'] = 'global';
3585
                $agendaitems[$day][] = $item;
3586
                continue;
3587
            }
3588
3589
            $start_time = api_format_date(
3590
                $item['start_date'],
3591
                TIME_NO_SEC_FORMAT
3592
            );
3593
            $end_time = '';
3594
            if (!empty($item['end_date'])) {
3595
                $end_time = ' - '.api_format_date(
3596
                        $item['end_date'],
3597
                        DATE_TIME_FORMAT_LONG
3598
                    );
3599
            }
3600
3601
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3602
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3603
            if ("day_view" !== $type) {
3604
                // This is the array construction for the WEEK or MONTH view
3605
                //Display the Agenda global in the tab agenda (administrator)
3606
                $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
3607
                $agendaitems[$day] .= "<b>".get_lang('Platform event')."</b>";
3608
                $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
3609
            } else {
3610
                // this is the array construction for the DAY view
3611
                $halfhour = 2 * $agendatime['0'];
3612
                if ($agendatime['1'] >= '30') {
3613
                    $halfhour = $halfhour + 1;
3614
                }
3615
                if (!is_array($agendaitems[$halfhour])) {
3616
                    $content = $agendaitems[$halfhour];
3617
                }
3618
                $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
3619
                        'Platform event'
3620
                    ).":  </b>".$item['title']."</div>";
3621
            }
3622
        }
3623
3624
        return $agendaitems;
3625
    }
3626
3627
    /**
3628
     * This function retrieves all the personal agenda items and add them to the agenda items found by the other
3629
     * functions.
3630
     */
3631
    public static function get_personal_agenda_items(
3632
        $user_id,
3633
        $agendaitems,
3634
        $day = "",
3635
        $month = "",
3636
        $year = "",
3637
        $week = "",
3638
        $type
3639
    ) {
3640
        $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
3641
        $user_id = intval($user_id);
3642
3643
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3644
        if ("month_view" == $type or "" == $type) {
3645
            // we are in month view
3646
            $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."'  ORDER BY date ASC";
3647
        }
3648
3649
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3650
        // we are in week view
3651
        if ("week_view" == $type) {
3652
            $start_end_day_of_week = self::calculate_start_end_of_week(
3653
                $week,
3654
                $year
3655
            );
3656
            $start_day = $start_end_day_of_week['start']['day'];
3657
            $start_month = $start_end_day_of_week['start']['month'];
3658
            $start_year = $start_end_day_of_week['start']['year'];
3659
            $end_day = $start_end_day_of_week['end']['day'];
3660
            $end_month = $start_end_day_of_week['end']['month'];
3661
            $end_year = $start_end_day_of_week['end']['year'];
3662
            // in sql statements you have to use year-month-day for date calculations
3663
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3664
            $start_filter = api_get_utc_datetime($start_filter);
3665
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3666
            $end_filter = api_get_utc_datetime($end_filter);
3667
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3668
        }
3669
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3670
        if ("day_view" == $type) {
3671
            // we are in day view
3672
            // we could use mysql date() function but this is only available from 4.1 and higher
3673
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3674
            $start_filter = api_get_utc_datetime($start_filter);
3675
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3676
            $end_filter = api_get_utc_datetime($end_filter);
3677
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3678
        }
3679
3680
        $result = Database::query($sql);
3681
        while ($item = Database::fetch_array($result, 'ASSOC')) {
3682
            $time_minute = api_convert_and_format_date(
3683
                $item['date'],
3684
                TIME_NO_SEC_FORMAT
3685
            );
3686
            $item['date'] = api_get_local_time($item['date']);
3687
            $item['start_date_tms'] = api_strtotime($item['date']);
3688
            $item['content'] = $item['text'];
3689
3690
            // we break the date field in the database into a date and a time part
3691
            $agenda_db_date = explode(" ", $item['date']);
3692
            $date = $agenda_db_date[0];
3693
            $time = $agenda_db_date[1];
3694
            // we divide the date part into a day, a month and a year
3695
            $agendadate = explode("-", $item['date']);
3696
            $year = intval($agendadate[0]);
3697
            $month = intval($agendadate[1]);
3698
            $day = intval($agendadate[2]);
3699
            // we divide the time part into hour, minutes, seconds
3700
            $agendatime = explode(":", $time);
3701
3702
            $hour = $agendatime[0];
3703
            $minute = $agendatime[1];
3704
            $second = $agendatime[2];
3705
3706
            if ('month_view' == $type) {
3707
                $item['calendar_type'] = 'personal';
3708
                $item['start_date'] = $item['date'];
3709
                $agendaitems[$day][] = $item;
3710
                continue;
3711
            }
3712
3713
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3714
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3715
            if ("day_view" !== $type) {
3716
                // This is the array construction for the WEEK or MONTH view
3717
3718
                //Display events in agenda
3719
                $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 />";
3720
            } else {
3721
                // this is the array construction for the DAY view
3722
                $halfhour = 2 * $agendatime['0'];
3723
                if ($agendatime['1'] >= '30') {
3724
                    $halfhour = $halfhour + 1;
3725
                }
3726
3727
                //Display events by list
3728
                $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>";
3729
            }
3730
        }
3731
3732
        return $agendaitems;
3733
    }
3734
3735
    /**
3736
     * Show the monthcalender of the given month.
3737
     *
3738
     * @param    array    Agendaitems
3739
     * @param    int    Month number
3740
     * @param    int    Year number
3741
     * @param    array    Array of strings containing long week day names (deprecated, you can send an empty array
3742
     *                          instead)
3743
     * @param    string    The month name
3744
     */
3745
    public static function display_mymonthcalendar(
3746
        $user_id,
3747
        $agendaitems,
3748
        $month,
3749
        $year,
3750
        $weekdaynames = [],
3751
        $monthName,
3752
        $show_content = true
3753
    ) {
3754
        global $DaysShort, $course_path;
3755
        //Handle leap year
3756
        $numberofdays = [
3757
            0,
3758
            31,
3759
            28,
3760
            31,
3761
            30,
3762
            31,
3763
            30,
3764
            31,
3765
            31,
3766
            30,
3767
            31,
3768
            30,
3769
            31,
3770
        ];
3771
        if ((0 == $year % 400) or (0 == $year % 4 and 0 != $year % 100)) {
3772
            $numberofdays[2] = 29;
3773
        }
3774
        //Get the first day of the month
3775
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
3776
        //Start the week on monday
3777
        $startdayofweek = 0 != $dayone['wday'] ? ($dayone['wday'] - 1) : 6;
3778
        $g_cc = (isset($_GET['courseCode']) ? $_GET['courseCode'] : '');
3779
3780
        $next_month = (1 == $month ? 12 : $month - 1);
3781
        $prev_month = (12 == $month ? 1 : $month + 1);
3782
3783
        $next_year = (1 == $month ? $year - 1 : $year);
3784
        $prev_year = (12 == $month ? $year + 1 : $year);
3785
3786
        if ($show_content) {
3787
            $back_url = Display::url(
3788
                get_lang('Previous'),
3789
                api_get_self()."?coursePath=".urlencode(
3790
                    $course_path
3791
                )."&courseCode=".Security::remove_XSS(
3792
                    $g_cc
3793
                )."&action=view&view=month&month=".$next_month."&year=".$next_year
3794
            );
3795
            $next_url = Display::url(
3796
                get_lang('Next'),
3797
                api_get_self()."?coursePath=".urlencode(
3798
                    $course_path
3799
                )."&courseCode=".Security::remove_XSS(
3800
                    $g_cc
3801
                )."&action=view&view=month&month=".$prev_month."&year=".$prev_year
3802
            );
3803
        } else {
3804
            $back_url = Display::url(
3805
                get_lang('Previous'),
3806
                '',
3807
                [
3808
                    'onclick' => "load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ",
3809
                    'class' => 'btn ui-button ui-widget ui-state-default',
3810
                ]
3811
            );
3812
            $next_url = Display::url(
3813
                get_lang('Next'),
3814
                '',
3815
                [
3816
                    'onclick' => "load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ",
3817
                    'class' => 'pull-right btn ui-button ui-widget ui-state-default',
3818
                ]
3819
            );
3820
        }
3821
        $html = '';
3822
        $html .= '<div class="actions">';
3823
        $html .= '<div class="row">';
3824
        $html .= '<div class="col-md-4">'.$back_url.'</div>';
3825
        $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
3826
        $html .= '<div class="col-md-4">'.$next_url.'</div>';
3827
        $html .= '</div>';
3828
        $html .= '</div>';
3829
        $html .= '<table id="agenda_list2" class="table table-bordered">';
3830
        $html .= '<tr>';
3831
        for ($ii = 1; $ii < 8; $ii++) {
3832
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
3833
        }
3834
        $html .= '</tr>';
3835
3836
        $curday = -1;
3837
        $today = getdate();
3838
        while ($curday <= $numberofdays[$month]) {
3839
            $html .= "<tr>";
3840
            for ($ii = 0; $ii < 7; $ii++) {
3841
                if ((-1 == $curday) && ($ii == $startdayofweek)) {
3842
                    $curday = 1;
3843
                }
3844
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
3845
                    $bgcolor = $class = 'class="days_week"';
3846
                    $dayheader = Display::div(
3847
                        $curday,
3848
                        ['class' => 'agenda_day']
3849
                    );
3850
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
3851
                        $class = "class=\"days_today\" style=\"width:10%;\"";
3852
                    }
3853
3854
                    $html .= "<td ".$class.">".$dayheader;
3855
3856
                    if (!empty($agendaitems[$curday])) {
3857
                        $items = $agendaitems[$curday];
3858
                        $items = msort($items, 'start_date_tms');
3859
3860
                        foreach ($items as $value) {
3861
                            $value['title'] = Security::remove_XSS(
3862
                                $value['title']
3863
                            );
3864
                            $start_time = api_format_date(
3865
                                $value['start_date'],
3866
                                TIME_NO_SEC_FORMAT
3867
                            );
3868
                            $end_time = '';
3869
3870
                            if (!empty($value['end_date'])) {
3871
                                $end_time = '-&nbsp;<i>'.api_format_date(
3872
                                        $value['end_date'],
3873
                                        DATE_TIME_FORMAT_LONG
3874
                                    ).'</i>';
3875
                            }
3876
                            $complete_time = '<i>'.api_format_date(
3877
                                    $value['start_date'],
3878
                                    DATE_TIME_FORMAT_LONG
3879
                                ).'</i>&nbsp;'.$end_time;
3880
                            $time = '<i>'.$start_time.'</i>';
3881
3882
                            switch ($value['calendar_type']) {
3883
                                case 'personal':
3884
                                    $bg_color = '#D0E7F4';
3885
                                    $icon = Display::return_icon(
3886
                                        'user.png',
3887
                                        get_lang('Personal agenda'),
3888
                                        [],
3889
                                        ICON_SIZE_SMALL
3890
                                    );
3891
                                    break;
3892
                                case 'global':
3893
                                    $bg_color = '#FFBC89';
3894
                                    $icon = Display::return_icon(
3895
                                        'view_remove.png',
3896
                                        get_lang('Platform event'),
3897
                                        [],
3898
                                        ICON_SIZE_SMALL
3899
                                    );
3900
                                    break;
3901
                                case 'course':
3902
                                    $bg_color = '#CAFFAA';
3903
                                    $icon_name = 'course.png';
3904
                                    if (!empty($value['session_id'])) {
3905
                                        $icon_name = 'session.png';
3906
                                    }
3907
                                    if ($show_content) {
3908
                                        $icon = Display::url(
3909
                                            Display::return_icon(
3910
                                                $icon_name,
3911
                                                $value['course_name'].' '.get_lang(
3912
                                                    'Course'
3913
                                                ),
3914
                                                [],
3915
                                                ICON_SIZE_SMALL
3916
                                            ),
3917
                                            $value['url']
3918
                                        );
3919
                                    } else {
3920
                                        $icon = Display::return_icon(
3921
                                            $icon_name,
3922
                                            $value['course_name'].' '.get_lang(
3923
                                                'Course'
3924
                                            ),
3925
                                            [],
3926
                                            ICON_SIZE_SMALL
3927
                                        );
3928
                                    }
3929
                                    break;
3930
                                default:
3931
                                    break;
3932
                            }
3933
3934
                            $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
3935
3936
                            if ($show_content) {
3937
                                //Setting a personal event to green
3938
                                $icon = Display::div(
3939
                                    $icon,
3940
                                    ['style' => 'float:right']
3941
                                );
3942
3943
                                $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
3944
3945
                                //Link to bubble
3946
                                $url = Display::url(
3947
                                    cut($value['title'], 40),
3948
                                    '#',
3949
                                    ['id' => $link, 'class' => 'opener']
3950
                                );
3951
                                $result .= $time.' '.$icon.' '.Display::div(
3952
                                        $url
3953
                                    );
3954
3955
                                //Hidden content
3956
                                $content = Display::div(
3957
                                    $icon.Display::tag(
3958
                                        'h2',
3959
                                        $value['course_name']
3960
                                    ).'<hr />'.Display::tag(
3961
                                        'h3',
3962
                                        $value['title']
3963
                                    ).$complete_time.'<hr />'.Security::remove_XSS(
3964
                                        $value['content']
3965
                                    )
3966
                                );
3967
3968
                                //Main div
3969
                                $result .= Display::div(
3970
                                    $content,
3971
                                    [
3972
                                        'id' => 'main_'.$link,
3973
                                        'class' => 'dialog',
3974
                                        'style' => 'display:none',
3975
                                    ]
3976
                                );
3977
                                $result .= '</div>';
3978
                                $html .= $result;
3979
                            } else {
3980
                                $html .= $result .= $icon.'</div>';
3981
                            }
3982
                        }
3983
                    }
3984
                    $html .= "</td>";
3985
                    $curday++;
3986
                } else {
3987
                    $html .= "<td></td>";
3988
                }
3989
            }
3990
            $html .= "</tr>";
3991
        }
3992
        $html .= "</table>";
3993
        echo $html;
3994
    }
3995
3996
    /**
3997
     * Get personal agenda items between two dates (=all events from all registered courses).
3998
     *
3999
     * @param int $user_id user ID of the user
4000
     * @param    string    Optional start date in datetime format (if no start date is given, uses today)
4001
     * @param    string    Optional end date in datetime format (if no date is given, uses one year from now)
4002
     *
4003
     * @return array array of events ordered by start date, in
4004
     *               [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
4005
     *               where datestart and dateend are in yyyyMMddhhmmss format
4006
     *
4007
     * @deprecated use agenda events
4008
     */
4009
    public static function get_personal_agenda_items_between_dates(
4010
        $user_id,
4011
        $date_start = '',
4012
        $date_end = ''
4013
    ) {
4014
        $items = [];
4015
        if ($user_id != strval(intval($user_id))) {
4016
            return $items;
4017
        }
4018
        if (empty($date_start)) {
4019
            $date_start = date('Y-m-d H:i:s');
4020
        }
4021
        if (empty($date_end)) {
4022
            $date_end = date(
4023
                'Y-m-d H:i:s',
4024
                mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1)
4025
            );
4026
        }
4027
        $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
4028
        if (!preg_match($expr, $date_start)) {
4029
            return $items;
4030
        }
4031
        if (!preg_match($expr, $date_end)) {
4032
            return $items;
4033
        }
4034
4035
        // get agenda-items for every course
4036
        $courses = api_get_user_courses($user_id, false);
4037
        foreach ($courses as $id => $course) {
4038
            $c = api_get_course_info_by_id($course['real_id']);
4039
            //databases of the courses
4040
            $t_a = Database::get_course_table(TABLE_AGENDA, $course['db']);
4041
            $t_ip = Database::get_course_table(
4042
                TABLE_ITEM_PROPERTY,
4043
                $course['db']
4044
            );
4045
            // get the groups to which the user belong
4046
            $group_memberships = GroupManager:: get_group_ids(
4047
                $course['db'],
4048
                $user_id
4049
            );
4050
            // if the user is administrator of that course we show all the agenda items
4051
            if ('1' == $course['status']) {
4052
                //echo "course admin";
4053
                $sqlquery = "SELECT ".
4054
                    " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4055
                    " FROM ".$t_a." agenda, ".
4056
                    $t_ip." ip ".
4057
                    " WHERE agenda.id = ip.ref ".
4058
                    " AND agenda.start_date>='$date_start' ".
4059
                    " AND agenda.end_date<='$date_end' ".
4060
                    " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4061
                    " AND ip.visibility='1' ".
4062
                    " GROUP BY agenda.id ".
4063
                    " ORDER BY start_date ";
4064
            } else {
4065
                // if the user is not an administrator of that course, then...
4066
                if (is_array($group_memberships) && count(
4067
                        $group_memberships
4068
                    ) > 0
4069
                ) {
4070
                    $sqlquery = "SELECT ".
4071
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4072
                        " FROM ".$t_a." agenda, ".
4073
                        $t_ip." ip ".
4074
                        " WHERE agenda.id = ip.ref ".
4075
                        " AND agenda.start_date>='$date_start' ".
4076
                        " AND agenda.end_date<='$date_end' ".
4077
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4078
                        " AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
4079
                            ", ",
4080
                            $group_memberships
4081
                        ).")) ) ".
4082
                        " AND ip.visibility='1' ".
4083
                        " ORDER BY start_date ";
4084
                } else {
4085
                    $sqlquery = "SELECT ".
4086
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4087
                        " FROM ".$t_a." agenda, ".
4088
                        $t_ip." ip ".
4089
                        " WHERE agenda.id = ip.ref ".
4090
                        " AND agenda.start_date>='$date_start' ".
4091
                        " AND agenda.end_date<='$date_end' ".
4092
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4093
                        " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
4094
                        " AND ip.visibility='1' ".
4095
                        " ORDER BY start_date ";
4096
                }
4097
            }
4098
4099
            $result = Database::query($sqlquery);
4100
            while ($item = Database::fetch_array($result)) {
4101
                $agendaday = date("j", strtotime($item['start_date']));
4102
                $month = date("n", strtotime($item['start_date']));
4103
                $year = date("Y", strtotime($item['start_date']));
4104
                $URL = api_get_path(
4105
                        WEB_PATH
4106
                    )."main/calendar/agenda.php?cidReq=".urlencode(
4107
                        $course["code"]
4108
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
4109
                list($year, $month, $day, $hour, $min, $sec) = explode(
4110
                    '[-: ]',
4111
                    $item['start_date']
4112
                );
4113
                $start_date = $year.$month.$day.$hour.$min;
4114
                list($year, $month, $day, $hour, $min, $sec) = explode(
4115
                    '[-: ]',
4116
                    $item['end_date']
4117
                );
4118
                $end_date = $year.$month.$day.$hour.$min;
4119
4120
                $items[] = [
4121
                    'datestart' => $start_date,
4122
                    'dateend' => $end_date,
4123
                    'title' => $item['title'],
4124
                    'link' => $URL,
4125
                    'coursetitle' => $c['name'],
4126
                ];
4127
            }
4128
        }
4129
4130
        return $items;
4131
    }
4132
4133
    /**
4134
     * This function calculates the startdate of the week (monday)
4135
     * and the enddate of the week (sunday)
4136
     * and returns it as an array.
4137
     */
4138
    public static function calculate_start_end_of_week($week_number, $year)
4139
    {
4140
        // determine the start and end date
4141
        // step 1: we calculate a timestamp for a day in this week
4142
        $random_day_in_week = mktime(
4143
                0,
4144
                0,
4145
                0,
4146
                1,
4147
                1,
4148
                $year
4149
            ) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
4150
        // step 2: we which day this is (0=sunday, 1=monday, ...)
4151
        $number_day_in_week = date('w', $random_day_in_week);
4152
        // step 3: we calculate the timestamp of the monday of the week we are in
4153
        $start_timestamp = $random_day_in_week - (($number_day_in_week - 1) * 24 * 60 * 60);
4154
        // step 4: we calculate the timestamp of the sunday of the week we are in
4155
        $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week + 1) * 24 * 60 * 60) - 3600;
4156
        // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
4157
        $start_day = date('j', $start_timestamp);
4158
        $start_month = date('n', $start_timestamp);
4159
        $start_year = date('Y', $start_timestamp);
4160
        $end_day = date('j', $end_timestamp);
4161
        $end_month = date('n', $end_timestamp);
4162
        $end_year = date('Y', $end_timestamp);
4163
        $start_end_array['start']['day'] = $start_day;
4164
        $start_end_array['start']['month'] = $start_month;
4165
        $start_end_array['start']['year'] = $start_year;
4166
        $start_end_array['end']['day'] = $end_day;
4167
        $start_end_array['end']['month'] = $end_month;
4168
        $start_end_array['end']['year'] = $end_year;
4169
4170
        return $start_end_array;
4171
    }
4172
4173
    /**
4174
     * @return bool
4175
     */
4176
    public function getIsAllowedToEdit()
4177
    {
4178
        return $this->isAllowedToEdit;
4179
    }
4180
4181
    /**
4182
     * @param bool $isAllowedToEdit
4183
     */
4184
    public function setIsAllowedToEdit($isAllowedToEdit)
4185
    {
4186
        $this->isAllowedToEdit = $isAllowedToEdit;
4187
    }
4188
4189
    /**
4190
     * Format needed for the Fullcalendar js lib.
4191
     *
4192
     * @param string $utcTime
4193
     *
4194
     * @return bool|string
4195
     */
4196
    public function formatEventDate($utcTime)
4197
    {
4198
        $utcTimeZone = new DateTimeZone('UTC');
4199
        $platformTimeZone = new DateTimeZone(api_get_timezone());
4200
4201
        $eventDate = new DateTime($utcTime, $utcTimeZone);
4202
        $eventDate->setTimezone($platformTimeZone);
4203
4204
        return $eventDate->format(DateTime::ISO8601);
4205
    }
4206
}
4207