Passed
Push — 1.11.x ( 544dff...c8ebac )
by
unknown
10:59
created

Agenda::generateDatesByType()   B

Complexity

Conditions 11
Paths 35

Size

Total Lines 87
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 11
eloc 43
c 2
b 0
f 0
nc 35
nop 4
dl 0
loc 87
rs 7.3166

How to fix   Long Method    Complexity   

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:

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