Passed
Push — preprodparkur ( 722cd4...1e15da )
by Angel Fernando Quiroz
14:47
created

Agenda::editEvent()   F

Complexity

Conditions 46
Paths 8216

Size

Total Lines 320
Code Lines 198

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 46
eloc 198
nc 8216
nop 14
dl 0
loc 320
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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