Passed
Push — 1.10.x ( aa83c1...10729d )
by
unknown
479:23 queued 434:42
created

Agenda::getAttachmentList()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 13

Duplication

Lines 19
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 19
loc 19
rs 9.4285
cc 2
eloc 13
nc 2
nop 2
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 = array();
12
    /** @var string Current type */
13
    public $type = 'personal';
14
    public $types = array('personal', 'admin', 'course');
15
    public $sessionId = 0;
16
    public $senderId;
17
    /** @var array */
18
    public $course;
19
    public $comment;
20
    private $isAllowedToEdit;
21
22
    /**
23
     * Constructor
24
     */
25
    public function __construct()
26
    {
27
        //Table definitions
28
        $this->tbl_global_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
29
        $this->tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
30
        $this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
31
        $this->table_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
32
33
        //Setting the course object if we are in a course
34
        $this->course = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $course.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
35
        $courseInfo = api_get_course_info();
36
        if (!empty($courseInfo)) {
37
            $this->course = $courseInfo;
38
        }
39
        $this->setSessionId(api_get_session_id());
40
        $this->setSenderId(api_get_user_id());
41
        $this->setIsAllowedToEdit(api_is_allowed_to_edit(null, true));
42
        $this->events = array();
43
44
        // Event colors
45
        $this->event_platform_color = 'red'; //red
46
        $this->event_course_color = '#458B00'; //green
47
        $this->event_group_color = '#A0522D'; //siena
48
        $this->event_session_color = '#00496D'; // kind of green
49
        $this->eventOtherSessionColor = '#999';
50
        $this->event_personal_color = 'steel blue'; //steel blue
51
52
    }
53
54
    /**
55
     * @param int $senderId
56
     */
57
    public function setSenderId($senderId)
58
    {
59
        $this->senderId = intval($senderId);
60
    }
61
62
    /**
63
     * @return int
64
     */
65
    public function getSenderId()
66
    {
67
        return $this->senderId;
68
    }
69
70
    /**
71
     * @param string $type can be 'personal', 'admin'  or  'course'
72
     */
73
    public function setType($type)
74
    {
75
        $typeList = $this->getTypes();
76
77
        if (in_array($type, $typeList)) {
78
            $this->type = $type;
79
        }
80
    }
81
82
    /**
83
     * @param int $id
84
     */
85
    public function setSessionId($id)
86
    {
87
        $this->sessionId = intval($id);
88
    }
89
90
    /**
91
     * @return int $id
92
     */
93
    public function getSessionId()
94
    {
95
        return $this->sessionId;
96
    }
97
98
    /**
99
     * @param array $courseInfo
100
     */
101
    public function set_course($courseInfo)
102
    {
103
        $this->course = $courseInfo;
104
    }
105
106
    /**
107
     * @return array
108
     */
109
    public function getTypes()
110
    {
111
        return $this->types;
112
    }
113
114
    /**
115
     * Adds an event to the calendar
116
     * @param string  $start datetime format: 2012-06-14 09:00:00
117
     * @param string  $end datetime format: 2012-06-14 09:00:00
118
     * @param string  $allDay (true, false)
119
     * @param string  $title
120
     * @param string  $content
121
     * @param array   $usersToSend array('everyone') or a list of user/group ids
122
     * @param bool    $addAsAnnouncement event as a *course* announcement
123
     * @param int $parentEventId
124
     * @param array $attachmentArray array of $_FILES['']
125
     * @param array $attachmentCommentList
126
     * @param string $eventComment
127
     * @param string $color
128
     *
129
     * @return int
130
     */
131
    public function addEvent(
132
        $start,
133
        $end,
134
        $allDay,
135
        $title,
136
        $content,
137
        $usersToSend = array(),
138
        $addAsAnnouncement = false,
139
        $parentEventId = null,
140
        $attachmentArray = array(),
141
        $attachmentCommentList = array(),
142
        $eventComment = null,
143
        $color = ''
144
    ) {
145
        $start = api_get_utc_datetime($start);
146
        $end = api_get_utc_datetime($end);
147
        $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
148
        $id = null;
149
        $content = Security::remove_XSS($content);
150
        $eventComment = nl2br($eventComment);
151
152
        switch ($this->type) {
153
            case 'personal':
154
                $attributes = array(
155
                    'user' => api_get_user_id(),
156
                    'title' => $title,
157
                    'text' => $content,
158
                    'date' => $start,
159
                    'enddate' => $end,
160
                    'all_day' => $allDay,
161
                    'color' => $color
162
                );
163
164
                $id = Database::insert(
165
                    $this->tbl_personal_agenda,
166
                    $attributes
167
                );
168
                break;
169
            case 'course':
170
                $attributes = array(
171
                    'title' => $title,
172
                    'content' => $content,
173
                    'start_date' => $start,
174
                    'end_date' => $end,
175
                    'all_day' => $allDay,
176
                    'session_id' => $this->getSessionId(),
177
                    'c_id' => $this->course['real_id'],
178
                    'comment' => $eventComment,
179
                    'color' => $color
180
                );
181
182
                if (!empty($parentEventId)) {
183
                    $attributes['parent_event_id'] = $parentEventId;
184
                }
185
186
                $senderId = $this->getSenderId();
187
                $sessionId = $this->getSessionId();
188
189
                // Simple course event.
190
                $id = Database::insert($this->tbl_course_agenda, $attributes);
191
192
                if ($id) {
193
                    $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
194
                    Database::query($sql);
195
196
                    $groupId = api_get_group_id();
197
198
                    if (!empty($usersToSend)) {
199
                        $sendTo = $this->parseSendToArray($usersToSend);
200
201
                        if ($sendTo['everyone']) {
202
                            api_item_property_update(
203
                                $this->course,
204
                                TOOL_CALENDAR_EVENT,
205
                                $id,
206
                                "AgendaAdded",
207
                                $senderId,
208
                                $groupId,
209
                                '',
210
                                $start,
211
                                $end,
212
                                $sessionId
213
                            );
214
                            api_item_property_update(
215
                                $this->course,
216
                                TOOL_CALENDAR_EVENT,
217
                                $id,
218
                                "visible",
219
                                $senderId,
220
                                $groupId,
221
                                '',
222
                                $start,
223
                                $end,
224
                                $sessionId
225
                            );
226
                        } else {
227
                            // Storing the selected groups
228 View Code Duplication
                            if (!empty($sendTo['groups'])) {
229
                                foreach ($sendTo['groups'] as $group) {
230
                                    api_item_property_update(
231
                                        $this->course,
232
                                        TOOL_CALENDAR_EVENT,
233
                                        $id,
234
                                        "AgendaAdded",
235
                                        $senderId,
236
                                        $group,
237
                                        0,
238
                                        $start,
239
                                        $end,
240
                                        $sessionId
241
                                    );
242
243
                                    api_item_property_update(
244
                                        $this->course,
245
                                        TOOL_CALENDAR_EVENT,
246
                                        $id,
247
                                        "visible",
248
                                        $senderId,
249
                                        $group,
250
                                        0,
251
                                        $start,
252
                                        $end,
253
                                        $sessionId
254
                                    );
255
                                }
256
                            }
257
258
                            // storing the selected users
259 View Code Duplication
                            if (!empty($sendTo['users'])) {
260
                                foreach ($sendTo['users'] as $userId) {
261
                                    api_item_property_update(
262
                                        $this->course,
263
                                        TOOL_CALENDAR_EVENT,
264
                                        $id,
265
                                        "AgendaAdded",
266
                                        $senderId,
267
                                        $groupId,
268
                                        $userId,
269
                                        $start,
270
                                        $end,
271
                                        $sessionId
272
                                    );
273
274
                                    api_item_property_update(
275
                                        $this->course,
276
                                        TOOL_CALENDAR_EVENT,
277
                                        $id,
278
                                        "visible",
279
                                        $senderId,
280
                                        $groupId,
281
                                        $userId,
282
                                        $start,
283
                                        $end,
284
                                        $sessionId
285
                                    );
286
                                }
287
                            }
288
                        }
289
                    }
290
291
                    // Add announcement.
292
                    if ($addAsAnnouncement) {
293
                        $this->storeAgendaEventAsAnnouncement($id, $usersToSend);
294
                    }
295
296
                    // Add attachment.
297 View Code Duplication
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
298
                        $counter = 0;
299
                        foreach ($attachmentArray as $attachmentItem) {
300
                            $this->addAttachment(
301
                                $id,
302
                                $attachmentItem,
303
                                $attachmentCommentList[$counter],
304
                                $this->course
305
                            );
306
                            $counter++;
307
                        }
308
                    }
309
                }
310
                break;
311 View Code Duplication
            case 'admin':
312
                if (api_is_platform_admin()) {
313
                    $attributes = array(
314
                        'title' => $title,
315
                        'content' => $content,
316
                        'start_date' => $start,
317
                        'end_date' => $end,
318
                        'all_day' => $allDay,
319
                        'access_url_id' => api_get_current_access_url_id()
320
                    );
321
322
                    $id = Database::insert($this->tbl_global_agenda, $attributes);
323
                }
324
                break;
325
        }
326
327
        return $id;
328
    }
329
330
    /**
331
     * @param int $eventId
332
     * @param int $courseId
333
     *
334
     * @return array
335
     */
336
    public function getRepeatedInfoByEvent($eventId, $courseId)
337
    {
338
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
339
        $eventId = intval($eventId);
340
        $courseId = intval($courseId);
341
        $sql = "SELECT * FROM $repeatTable
342
                WHERE c_id = $courseId AND cal_id = $eventId";
343
        $res = Database::query($sql);
344
        $repeatInfo = array();
345
        if (Database::num_rows($res) > 0) {
346
            $repeatInfo = Database::fetch_array($res, 'ASSOC');
347
        }
348
349
        return $repeatInfo;
350
    }
351
352
    /**
353
     * @param int $eventId
354
     * @param string $type
355
     * @param string $end in local time
356
     * @param array $sentTo
357
     *
358
     * @return bool
359
     */
360
    public function addRepeatedItem($eventId, $type, $end, $sentTo = array())
361
    {
362
        $t_agenda = Database::get_course_table(TABLE_AGENDA);
363
        $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
364
365
        if (empty($this->course)) {
366
            return false;
367
        }
368
369
        $course_id = $this->course['real_id'];
370
        $eventId = intval($eventId);
371
372
        $sql = "SELECT title, content, start_date, end_date, all_day
373
                FROM $t_agenda
374
                WHERE c_id = $course_id AND id = $eventId";
375
        $res = Database::query($sql);
376
377
        if (Database::num_rows($res) !== 1) {
378
            return false;
379
        }
380
381
        $row = Database::fetch_array($res);
382
        $origStartDate = api_strtotime($row['start_date'], 'UTC');
383
        $origEndDate = api_strtotime($row['end_date'], 'UTC');
384
        $diff = $origEndDate - $origStartDate;
385
386
        $title = $row['title'];
387
        $content = $row['content'];
388
        $allDay = $row['all_day'];
389
390
        $now = time();
391
        $type = Database::escape_string($type);
392
        $end = api_strtotime($end);
393
394
        if (1 <= $end && $end <= 500) {
395
            // We assume that, with this type of value, the user actually gives a count of repetitions
396
            //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
397
            switch ($type) {
398
                case 'daily':
399
                    $end = $origStartDate + (86400 * $end);
400
                    break;
401
                case 'weekly':
402
                    $end = $this->addWeek($origStartDate, $end);
403
                    break;
404
                case 'monthlyByDate':
405
                    $end = $this->addMonth($origStartDate, $end);
406
                    break;
407
                case 'monthlyByDay':
408
                    //TODO
409
                    break;
410
                case 'monthlyByDayR':
411
                    //TODO
412
                    break;
413
                case 'yearly':
414
                    $end = $this->addYear($origStartDate, $end);
415
                    break;
416
            }
417
        }
418
419
        $typeList = array('daily', 'weekly', 'monthlyByDate', 'monthlyByDay', 'monthlyByDayR', 'yearly');
420
421
        // The event has to repeat *in the future*. We don't allow repeated
422
        // events in the past
423
        if ($end > $now && in_array($type, $typeList)) {
424
            $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
425
                    VALUES ($course_id, '$eventId', '$type', '$end')";
426
            Database::query($sql);
427
428
            switch ($type) {
429
                // @todo improve loop.
430 View Code Duplication
                case 'daily':
431
                    for ($i = $origStartDate + 86400; $i <= $end; $i += 86400) {
432
                        $start = date('Y-m-d H:i:s', $i);
433
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
434
                        $this->addEvent(
435
                            $start,
436
                            $repeatEnd,
437
                            $allDay,
438
                            $title,
439
                            $content,
440
                            $sentTo,
441
                            false,
442
                            $eventId
443
                        );
444
                    }
445
                    break;
446 View Code Duplication
                case 'weekly':
447
                    for ($i = $origStartDate + 604800; $i <= $end; $i += 604800) {
448
                        $start = date('Y-m-d H:i:s', $i);
449
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
450
                        $this->addEvent(
451
                            $start,
452
                            $repeatEnd,
453
                            $allDay,
454
                            $title,
455
                            $content,
456
                            $sentTo,
457
                            false,
458
                            $eventId
459
                        );
460
                    }
461
                    break;
462 View Code Duplication
                case 'monthlyByDate':
463
                    $next_start = $this->addMonth($origStartDate);
464
                    while ($next_start <= $end) {
465
                        $start = date('Y-m-d H:i:s', $next_start);
466
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
467
                        $this->addEvent(
468
                            $start,
469
                            $repeatEnd,
470
                            $allDay,
471
                            $title,
472
                            $content,
473
                            $sentTo,
474
                            false,
475
                            $eventId
476
                        );
477
                        $next_start = $this->addMonth($next_start);
478
                    }
479
                    break;
480
                case 'monthlyByDay':
481
                    //not yet implemented
482
                    break;
483
                case 'monthlyByDayR':
484
                    //not yet implemented
485
                    break;
486 View Code Duplication
                case 'yearly':
487
                    $next_start = $this->addYear($origStartDate);
488
                    while ($next_start <= $end) {
489
                        $start = date('Y-m-d H:i:s', $next_start);
490
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
491
                        $this->addEvent(
492
                            $start,
493
                            $repeatEnd,
494
                            $allDay,
495
                            $title,
496
                            $content,
497
                            $sentTo,
498
                            false,
499
                            $eventId
500
                        );
501
                        $next_start = $this->addYear($next_start);
502
                    }
503
                    break;
504
            }
505
        }
506
507
        return true;
508
    }
509
510
    /**
511
     * @param int $item_id
512
     * @param array $sentTo
513
     * @return int
514
     */
515
    public function storeAgendaEventAsAnnouncement($item_id, $sentTo = array())
516
    {
517
        $table_agenda = Database::get_course_table(TABLE_AGENDA);
518
        $course_id = api_get_course_int_id();
519
520
        // Check params
521
        if (empty($item_id) or $item_id != strval(intval($item_id))) {
522
            return -1;
523
        }
524
525
        // Get the agenda item.
526
        $item_id = intval($item_id);
527
        $sql = "SELECT * FROM $table_agenda
528
                WHERE c_id = $course_id AND id = ".$item_id;
529
        $res = Database::query($sql);
530
531
        if (Database::num_rows($res) > 0) {
532
            $row = Database::fetch_array($res, 'ASSOC');
533
            // Sending announcement
534
            if (!empty($sentTo)) {
535
                $id = AnnouncementManager::add_announcement(
536
                    $row['title'],
537
                    $row['content'],
538
                    $sentTo,
539
                    null,
540
                    null,
541
                    $row['end_date']
542
                );
543
                AnnouncementManager::send_email($id);
544
545
                return $id;
546
            }
547
        }
548
549
        return -1;
550
    }
551
552
    /**
553
     * Edits an event
554
     *
555
     * @param int $id
556
     * @param string $start datetime format: 2012-06-14 09:00:00
557
     * @param string $end datetime format: 2012-06-14 09:00:00
558
     * @param int $allDay is all day 'true' or 'false'
559
     * @param string $title
560
     * @param string $content
561
     * @param array $usersToSend
562
     * @param array $attachmentArray
563
     * @param array $attachmentCommentList
564
     * @param string $comment
565
     * @param string $color
566
     * @param bool $addAnnouncement
567
     *
568
     * @return bool
569
     */
570
    public function editEvent(
571
        $id,
572
        $start,
573
        $end,
574
        $allDay,
575
        $title,
576
        $content,
577
        $usersToSend = array(),
578
        $attachmentArray = array(),
579
        $attachmentCommentList = array(),
580
        $comment = null,
581
        $color = '',
582
        $addAnnouncement = false
583
    ) {
584
        $start = api_get_utc_datetime($start);
585
        $end = api_get_utc_datetime($end);
586
        $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
587
        $content = nl2br($content);
588
        $comment = nl2br($comment);
589
590
        switch ($this->type) {
591
            case 'personal':
592
                $eventInfo = $this->get_event($id);
593
                if ($eventInfo['user'] != api_get_user_id()) {
594
                    break;
595
                }
596
                $attributes = array(
597
                    'title' => $title,
598
                    'text' => $content,
599
                    'date' => $start,
600
                    'enddate' => $end,
601
                    'all_day' => $allDay,
602
                    'color' => $color
603
                );
604
                Database::update(
605
                    $this->tbl_personal_agenda,
606
                    $attributes,
607
                    array('id = ?' => $id)
608
                );
609
                break;
610
            case 'course':
611
                $eventInfo = $this->get_event($id);
612
613
                if (empty($eventInfo)) {
614
                    return false;
615
                }
616
617
                $groupId = api_get_group_id();
618
                $course_id = $this->course['real_id'];
619
620
                if (empty($course_id)) {
621
                    return false;
622
                }
623
624
                if ($this->getIsAllowedToEdit()) {
625
626
                    $attributes = array(
627
                        'title' => $title,
628
                        'content' => $content,
629
                        'start_date' => $start,
630
                        'end_date' => $end,
631
                        'all_day' => $allDay,
632
                        'comment' => $comment,
633
                        'color' => $color
634
                    );
635
636
                    Database::update(
637
                        $this->tbl_course_agenda,
638
                        $attributes,
639
                        array(
640
                            'id = ? AND c_id = ? AND session_id = ? ' => array(
641
                                $id,
642
                                $course_id,
643
                                $this->sessionId
644
                            )
645
                        )
646
                    );
647
648
                    if (!empty($usersToSend)) {
649
                        $sendTo = $this->parseSendToArray($usersToSend);
650
651
                        $usersToDelete = array_diff($eventInfo['send_to']['users'], $sendTo['users']);
652
                        $usersToAdd = array_diff($sendTo['users'], $eventInfo['send_to']['users']);
653
654
                        $groupsToDelete = array_diff($eventInfo['send_to']['groups'], $sendTo['groups']);
655
                        $groupToAdd = array_diff($sendTo['groups'], $eventInfo['send_to']['groups']);
656
657
                        if ($sendTo['everyone']) {
658
659
                            // Delete all from group
660 View Code Duplication
                            if (isset($eventInfo['send_to']['groups']) &&
661
                                !empty($eventInfo['send_to']['groups'])
662
                            ) {
663
                                foreach ($eventInfo['send_to']['groups'] as $group) {
664
                                    api_item_property_delete(
665
                                        $this->course,
666
                                        TOOL_CALENDAR_EVENT,
667
                                        $id,
668
                                        0,
669
                                        $group,
670
                                        $this->sessionId
671
                                    );
672
                                }
673
                            }
674
675
                            // Storing the selected users.
676 View Code Duplication
                            if (isset($eventInfo['send_to']['users']) &&
677
                                !empty($eventInfo['send_to']['users'])
678
                            ) {
679
                                foreach ($eventInfo['send_to']['users'] as $userId) {
680
                                    api_item_property_delete(
681
                                        $this->course,
682
                                        TOOL_CALENDAR_EVENT,
683
                                        $id,
684
                                        $userId,
685
                                        $groupId,
686
                                        $this->sessionId
687
                                    );
688
                                }
689
                            }
690
691
                            // Add to everyone only.
692
                            api_item_property_update(
693
                                $this->course,
694
                                TOOL_CALENDAR_EVENT,
695
                                $id,
696
                                "visible",
697
                                api_get_user_id(),
698
                                $groupId,
699
                                null,
700
                                $start,
701
                                $end,
702
                                $this->sessionId
703
                            );
704
                        } else {
705
706
                            // Delete "everyone".
707
                            api_item_property_delete(
708
                                $this->course,
709
                                TOOL_CALENDAR_EVENT,
710
                                $id,
711
                                0,
712
                                0,
713
                                $this->sessionId
714
                            );
715
716
                            // Add groups
717 View Code Duplication
                            if (!empty($groupToAdd)) {
718
                                foreach ($groupToAdd as $group) {
719
                                    api_item_property_update(
720
                                        $this->course,
721
                                        TOOL_CALENDAR_EVENT,
722
                                        $id,
723
                                        "visible",
724
                                        api_get_user_id(),
725
                                        $group,
726
                                        0,
727
                                        $start,
728
                                        $end,
729
                                        $this->sessionId
730
                                    );
731
                                }
732
                            }
733
734
                            // Delete groups.
735 View Code Duplication
                            if (!empty($groupsToDelete)) {
736
                                foreach ($groupsToDelete as $group) {
737
                                    api_item_property_delete(
738
                                        $this->course,
739
                                        TOOL_CALENDAR_EVENT,
740
                                        $id,
741
                                        0,
742
                                        $group,
743
                                        $this->sessionId
744
                                    );
745
                                }
746
                            }
747
748
                            // Add users.
749 View Code Duplication
                            if (!empty($usersToAdd)) {
750
                                foreach ($usersToAdd as $userId) {
751
                                    api_item_property_update(
752
                                        $this->course,
753
                                        TOOL_CALENDAR_EVENT,
754
                                        $id,
755
                                        "visible",
756
                                        api_get_user_id(),
757
                                        $groupId,
758
                                        $userId,
759
                                        $start,
760
                                        $end,
761
                                        $this->sessionId
762
                                    );
763
                                }
764
                            }
765
766
                            // Delete users.
767 View Code Duplication
                            if (!empty($usersToDelete)) {
768
                                foreach ($usersToDelete as $userId) {
769
                                    api_item_property_delete(
770
                                        $this->course,
771
                                        TOOL_CALENDAR_EVENT,
772
                                        $id,
773
                                        $userId,
774
                                        $groupId,
775
                                        $this->sessionId
776
                                    );
777
                                }
778
                            }
779
                        }
780
                    }
781
782
                    // Add announcement.
783
                    if (isset($addAnnouncement) && !empty($addAnnouncement)) {
784
                        $this->storeAgendaEventAsAnnouncement($id, $usersToSend);
785
                    }
786
787
                    // Add attachment.
788 View Code Duplication
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
789
                        $counter = 0;
790
                        foreach ($attachmentArray as $attachmentItem) {
791
                            $this->updateAttachment(
792
                                $attachmentItem['id'],
793
                                $id,
794
                                $attachmentItem,
795
                                $attachmentCommentList[$counter],
796
                                $this->course
797
                            );
798
                            $counter++;
799
                        }
800
                    }
801
                }
802
                break;
803
            case 'admin':
804 View Code Duplication
            case 'platform':
805
                if (api_is_platform_admin()) {
806
                    $attributes = array(
807
                        'title' => $title,
808
                        'content' => $content,
809
                        'start_date' => $start,
810
                        'end_date' => $end,
811
                        'all_day' => $allDay
812
                    );
813
                    Database::update(
814
                        $this->tbl_global_agenda,
815
                        $attributes,
816
                        array('id = ?' => $id)
817
                    );
818
                }
819
                break;
820
        }
821
    }
822
823
    /**
824
     * @param int $id
825
     * @param bool $deleteAllItemsFromSerie
826
     */
827
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
828
    {
829
        switch ($this->type) {
830
            case 'personal':
831
                $eventInfo = $this->get_event($id);
832
                if ($eventInfo['user'] == api_get_user_id()) {
833
                    Database::delete(
834
                        $this->tbl_personal_agenda,
835
                        array('id = ?' => $id)
836
                    );
837
                }
838
                break;
839
            case 'course':
840
                $course_id = api_get_course_int_id();
841
842
                if (!empty($course_id) && api_is_allowed_to_edit(null, true)) {
843
                    // Delete
844
                    $eventInfo = $this->get_event($id);
845
                    if ($deleteAllItemsFromSerie) {
846
                        /* This is one of the children.
847
                           Getting siblings and delete 'Em all + the father! */
848
                        if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
849
                            // Removing items.
850
                            $events = $this->getAllRepeatEvents($eventInfo['parent_event_id']);
851
                            if (!empty($events)) {
852
                                foreach ($events as $event) {
853
                                    $this->deleteEvent($event['id']);
854
                                }
855
                            }
856
                            // Removing parent.
857
                            $this->deleteEvent($eventInfo['parent_event_id']);
858
                        } else {
859
                            // This is the father looking for the children.
860
                            $events = $this->getAllRepeatEvents($id);
861
                            if (!empty($events)) {
862
                                foreach ($events as $event) {
863
                                    $this->deleteEvent($event['id']);
864
                                }
865
                            }
866
                        }
867
                    }
868
869
                    // Removing from events.
870
                    Database::delete(
871
                        $this->tbl_course_agenda,
872
                        array('id = ? AND c_id = ?' => array($id, $course_id))
873
                    );
874
875
                    api_item_property_update(
876
                        $this->course,
877
                        TOOL_CALENDAR_EVENT,
878
                        $id,
879
                        'delete',
880
                        api_get_user_id()
881
                    );
882
883
                    // Removing from series.
884
                    Database::delete(
885
                        $this->table_repeat,
886
                        array('cal_id = ? AND c_id = ?' => array($id, $course_id))
887
                    );
888
889
                    if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
890
                        foreach ($eventInfo['attachment'] as $attachment) {
891
                            self::deleteAttachmentFile($attachment['id'], $this->course);
892
                        }
893
                    }
894
                }
895
                break;
896
            case 'admin':
897
                if (api_is_platform_admin()) {
898
                    Database::delete(
899
                        $this->tbl_global_agenda,
900
                        array('id = ?' => $id)
901
                    );
902
                }
903
                break;
904
        }
905
    }
906
907
    /**
908
     * Get agenda events
909
     * @param int $start
910
     * @param int $end
911
     * @param int $course_id
912
     * @param int $groupId
913
     * @param int $user_id
914
     * @param string $format
915
     *
916
     * @return array|string
917
     */
918
    public function getEvents(
919
        $start,
920
        $end,
921
        $course_id = null,
922
        $groupId = null,
923
        $user_id = 0,
924
        $format = 'json'
925
    ) {
926
        switch ($this->type) {
927
            case 'admin':
928
                $this->getPlatformEvents($start, $end);
929
                break;
930
            case 'course':
931
                $session_id = $this->sessionId;
932
                $courseInfo = api_get_course_info_by_id($course_id);
933
934
                // Session coach can see all events inside a session.
935
                if (api_is_coach()) {
936
937
                    // Own course
938
                    $this->getCourseEvents(
939
                        $start,
940
                        $end,
941
                        $courseInfo,
942
                        $groupId,
943
                        $session_id,
944
                        $user_id
945
                    );
946
947
                    // Others
948
                    $this->getSessionEvents(
949
                        $start,
950
                        $end,
951
                        api_get_session_id(),
952
                        $user_id,
953
                        $this->eventOtherSessionColor
954
                    );
955
                } else {
956
                    $this->getCourseEvents(
957
                        $start,
958
                        $end,
959
                        $courseInfo,
960
                        $groupId,
961
                        $session_id,
962
                        $user_id
963
                    );
964
                }
965
                break;
966
            case 'personal':
967
            default:
968
                $sessionFilterActive = false;
969
970
                if (!empty($this->sessionId)) {
971
                    $sessionFilterActive = true;
972
                }
973
974
                if ($sessionFilterActive == false) {
975
                    // Getting personal events
976
                    $this->getPersonalEvents($start, $end);
977
978
                    // Getting platform/admin events
979
                    $this->getPlatformEvents($start, $end);
980
                }
981
982
                // Getting course events
983
                $my_course_list = array();
984
985
                if (!api_is_anonymous()) {
986
                    $session_list = SessionManager::get_sessions_by_user(
987
                        api_get_user_id()
988
                    );
989
                    $my_course_list = CourseManager::get_courses_list_by_user_id(
990
                        api_get_user_id(),
991
                        false
992
                    );
993
                }
994
995
                if (api_is_drh()) {
996
                    if (api_drh_can_access_all_session_content()) {
997
                        $session_list = array();
998
                        $sessionList = SessionManager::get_sessions_followed_by_drh(
999
                            api_get_user_id(),
1000
                            null,
1001
                            null,
1002
                            null,
1003
                            true,
1004
                            false
1005
                        );
1006
1007
                        if (!empty($sessionList)) {
1008
                            foreach ($sessionList as $sessionItem) {
1009
                                $sessionId = $sessionItem['id'];
1010
                                $courses = SessionManager::get_course_list_by_session_id(
1011
                                    $sessionId
1012
                                );
1013
                                $sessionInfo = array(
1014
                                    'session_id' => $sessionId,
1015
                                    'courses' => $courses
1016
                                );
1017
                                $session_list[] = $sessionInfo;
1018
                            }
1019
                        }
1020
                    }
1021
                }
1022
1023
                if (!empty($session_list)) {
1024
                    foreach ($session_list as $session_item) {
1025
                        if ($sessionFilterActive) {
1026
                            if ($this->sessionId != $session_item['session_id']) {
1027
                                continue;
1028
                            }
1029
                        }
1030
1031
                        $my_courses = $session_item['courses'];
1032
                        $my_session_id = $session_item['session_id'];
1033
1034
                        if (!empty($my_courses)) {
1035
                            foreach ($my_courses as $course_item) {
1036
                                $courseInfo = api_get_course_info_by_id($course_item['real_id']);
1037
                                $this->getCourseEvents(
1038
                                    $start,
1039
                                    $end,
1040
                                    $courseInfo,
1041
                                    0,
1042
                                    $my_session_id
1043
                                );
1044
                            }
1045
                        }
1046
1047
                        $this->getSessionEvents(
1048
                            $start,
1049
                            $end,
1050
                            $my_session_id,
1051
                            $user_id,
1052
                            $this->eventOtherSessionColor
1053
                        );
1054
                    }
1055
                }
1056
1057
                if (!empty($my_course_list) && $sessionFilterActive == false) {
1058
                    foreach ($my_course_list as $courseInfoItem) {
1059
                        $courseInfo = api_get_course_info_by_id($courseInfoItem['real_id']);
1060
                        if (isset($course_id) && !empty($course_id)) {
1061
                            if ($courseInfo['real_id'] == $course_id) {
1062
                                $this->getCourseEvents($start, $end, $courseInfo);
1063
                            }
1064
                        } else {
1065
                            $this->getCourseEvents(
1066
                                $start,
1067
                                $end,
1068
                                $courseInfo
1069
                            );
1070
                        }
1071
                    }
1072
                }
1073
1074
                break;
1075
        }
1076
1077
        if (!empty($this->events)) {
1078
            switch ($format) {
1079
                case 'json':
1080
                    return json_encode($this->events);
1081
                    break;
1082
                case 'array':
1083
                    return $this->events;
1084
                    break;
1085
            }
1086
1087
        }
1088
        return '';
1089
    }
1090
1091
    /**
1092
     * @param int $id
1093
     * @param int $day_delta
1094
     * @param int $minute_delta
1095
     * @return int
1096
     */
1097
    public function resizeEvent($id, $day_delta, $minute_delta)
1098
    {
1099
        // we convert the hour delta into minutes and add the minute delta
1100
        $delta = ($day_delta * 60 * 24) + $minute_delta;
1101
        $delta = intval($delta);
1102
1103
        $event = $this->get_event($id);
1104
        if (!empty($event)) {
1105
            switch ($this->type) {
1106 View Code Duplication
                case 'personal':
1107
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1108
                            all_day = 0, enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1109
							WHERE id=".intval($id);
1110
                    Database::query($sql);
1111
                    break;
1112 View Code Duplication
                case 'course':
1113
                    $sql = "UPDATE $this->tbl_course_agenda SET
1114
                            all_day = 0,  end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1115
							WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
1116
                    Database::query($sql);
1117
                    break;
1118 View Code Duplication
                case 'admin':
1119
                    $sql = "UPDATE $this->tbl_global_agenda SET
1120
                            all_day = 0, end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1121
							WHERE id=".intval($id);
1122
                    Database::query($sql);
1123
                    break;
1124
            }
1125
        }
1126
        return 1;
1127
    }
1128
1129
    /**
1130
     * @param $id
1131
     * @param $day_delta
1132
     * @param $minute_delta
1133
     * @return int
1134
     */
1135
    public function move_event($id, $day_delta, $minute_delta)
1136
    {
1137
        // we convert the hour delta into minutes and add the minute delta
1138
        $delta = ($day_delta * 60 * 24) + $minute_delta;
1139
        $delta = intval($delta);
1140
1141
        $event = $this->get_event($id);
1142
1143
        $allDay = 0;
1144
        if ($day_delta == 0 && $minute_delta == 0) {
1145
            $allDay = 1;
1146
        }
1147
1148
        if (!empty($event)) {
1149
            switch ($this->type) {
1150 View Code Duplication
                case 'personal':
1151
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1152
                            all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
1153
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1154
							WHERE id=".intval($id);
1155
                    Database::query($sql);
1156
                    break;
1157 View Code Duplication
                case 'course':
1158
                    $sql = "UPDATE $this->tbl_course_agenda SET
1159
                            all_day = $allDay, start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1160
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1161
							WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
1162
                    Database::query($sql);
1163
                    break;
1164 View Code Duplication
                case 'admin':
1165
                    $sql = "UPDATE $this->tbl_global_agenda SET
1166
                            all_day = $allDay,
1167
                            start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1168
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1169
							WHERE id=".intval($id);
1170
                    Database::query($sql);
1171
                    break;
1172
            }
1173
        }
1174
        return 1;
1175
    }
1176
1177
    /**
1178
     * Gets a single event
1179
     *
1180
     * @param int event id
1181
     * @return array
1182
     */
1183
    public function get_event($id)
1184
    {
1185
        // make sure events of the personal agenda can only be seen by the user himself
1186
        $id = intval($id);
1187
        $event = null;
1188
        switch ($this->type) {
1189
            case 'personal':
1190
                $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1191
                        WHERE id = $id AND user = ".api_get_user_id();
1192
                $result = Database::query($sql);
1193
                if (Database::num_rows($result)) {
1194
                    $event = Database::fetch_array($result, 'ASSOC');
1195
                    $event['description'] = $event['text'];
1196
                    $event['content'] = $event['text'];
1197
                    $event['start_date'] = $event['date'];
1198
                    $event['end_date'] = $event['enddate'];
1199
                }
1200
                break;
1201
            case 'course':
1202
                if (!empty($this->course['real_id'])) {
1203
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
1204
                            WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
1205
                    $result = Database::query($sql);
1206
                    if (Database::num_rows($result)) {
1207
                        $event = Database::fetch_array($result, 'ASSOC');
1208
                        $event['description'] = $event['content'];
1209
1210
                        // Getting send to array
1211
                        $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
1212
                            $id,
1213
                            $this->course['real_id'],
1214
                            $this->sessionId
1215
                        );
1216
1217
                        // Getting repeat info
1218
                        $event['repeat_info'] = $this->getRepeatedInfoByEvent(
1219
                            $id,
1220
                            $this->course['real_id']
1221
                        );
1222
1223
                        if (!empty($event['parent_event_id'])) {
1224
                            $event['parent_info'] = $this->get_event($event['parent_event_id']);
1225
                        }
1226
1227
                        $event['attachment'] = $this->getAttachmentList($id, $this->course);
1228
                    }
1229
                }
1230
                break;
1231
            case 'admin':
1232
            case 'platform':
1233
                $sql = "SELECT * FROM ".$this->tbl_global_agenda."
1234
                        WHERE id = $id";
1235
                $result = Database::query($sql);
1236
                if (Database::num_rows($result)) {
1237
                    $event = Database::fetch_array($result, 'ASSOC');
1238
                    $event['description'] = $event['content'];
1239
                }
1240
                break;
1241
        }
1242
        return $event;
1243
    }
1244
1245
    /**
1246
     * Gets personal events
1247
     * @param int $start
1248
     * @param int $end
1249
     * @return array
1250
     */
1251
    public function getPersonalEvents($start, $end)
1252
    {
1253
        $start = intval($start);
1254
        $end = intval($end);
1255
        $startCondition = '';
1256
        $endCondition = '';
1257
1258
        if ($start !== 0) {
1259
            $start = api_get_utc_datetime($start);
1260
            $startCondition = "AND date >= '".$start."'";
1261
        }
1262
        if ($start !== 0) {
1263
            $end = api_get_utc_datetime($end);
1264
            $endCondition = "AND (enddate <= '".$end."' OR enddate IS NULL)";
1265
        }
1266
        $user_id = api_get_user_id();
1267
1268
        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1269
                WHERE user = $user_id $startCondition $endCondition";
1270
1271
        $result = Database::query($sql);
1272
        $my_events = array();
1273
        if (Database::num_rows($result)) {
1274
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1275
                $event = array();
1276
                $event['id'] = 'personal_'.$row['id'];
1277
                $event['title'] = $row['title'];
1278
                $event['className'] = 'personal';
1279
                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
1280
                $event['editable'] = true;
1281
                $event['sent_to'] = get_lang('Me');
1282
                $event['type'] = 'personal';
1283
1284 View Code Duplication
                if (!empty($row['date']) && $row['date'] != '0000-00-00 00:00:00') {
1285
                    $event['start'] = $this->formatEventDate($row['date']);
1286
                    $event['start_date_localtime'] = api_get_local_time($row['date']);
1287
                }
1288
1289 View Code Duplication
                if (!empty($row['enddate']) && $row['enddate'] != '0000-00-00 00:00:00') {
1290
                    $event['end'] = $this->formatEventDate($row['enddate']);
1291
                    $event['end_date_localtime'] = api_get_local_time($row['enddate']);
1292
                }
1293
                $event['description'] = $row['text'];
1294
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1295
1296
                $event['parent_event_id'] = 0;
1297
                $event['has_children'] = 0;
1298
1299
                $my_events[] = $event;
1300
                $this->events[] = $event;
1301
            }
1302
        }
1303
        return $my_events;
1304
    }
1305
1306
    /**
1307
     * Get user/group list per event.
1308
     *
1309
     * @param int $eventId
1310
     * @param int $courseId
1311
     * @paraù int $sessionId
1312
     *
1313
     * @return array
1314
     */
1315
    public function getUsersAndGroupSubscribedToEvent($eventId, $courseId, $sessionId)
1316
    {
1317
        $eventId = intval($eventId);
1318
        $courseId = intval($courseId);
1319
        $sessionId = intval($sessionId);
1320
1321
        $sessionCondition = "ip.session_id = $sessionId";
1322
        if (empty($sessionId)) {
1323
            $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
1324
        }
1325
1326
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1327
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1328
1329
        // Get sent_tos
1330
        $sql = "SELECT DISTINCT to_user_id, to_group_id
1331
                FROM $tbl_property ip
1332
                INNER JOIN $tlb_course_agenda agenda
1333
                ON (
1334
                  ip.ref = agenda.id AND
1335
                  ip.c_id = agenda.c_id AND
1336
                  ip.tool = '".TOOL_CALENDAR_EVENT."'
1337
                )
1338
                WHERE
1339
                    ref = $eventId AND
1340
                    ip.visibility = '1' AND
1341
                    ip.c_id = $courseId AND
1342
                    $sessionCondition
1343
                ";
1344
1345
        $result = Database::query($sql);
1346
        $users = array();
1347
        $groups = array();
1348
        $everyone = false;
1349
1350
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1351
            if (!empty($row['to_group_id'])) {
1352
                $groups[] = $row['to_group_id'];
1353
            }
1354
            if (!empty($row['to_user_id'])) {
1355
                $users[] = $row['to_user_id'];
1356
            }
1357
1358
            if (empty($groups) && empty($users)) {
1359
                if ($row['to_group_id'] == 0) {
1360
                    $everyone = true;
1361
                }
1362
            }
1363
        }
1364
1365
        return array(
1366
            'everyone' => $everyone,
1367
            'users' => $users,
1368
            'groups' => $groups
1369
        );
1370
    }
1371
1372
    /**
1373
     * @param int $start
1374
     * @param int $end
1375
     * @param int $sessionId
1376
     * @param int $userId
1377
     * @param string $color
1378
     *
1379
     * @return array
1380
     */
1381
    public function getSessionEvents($start, $end, $sessionId = 0, $userId = 0, $color = '')
1382
    {
1383
        $courses = SessionManager::get_course_list_by_session_id($sessionId);
1384
1385
        if (!empty($courses)) {
1386
            foreach ($courses as $course) {
0 ignored issues
show
Bug introduced by
The expression $courses of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1387
                //if (api_is_coach($sessionId, $course['real_id'])) {
1388
                $this->getCourseEvents(
1389
                    $start,
1390
                    $end,
1391
                    $course,
1392
                    0,
1393
                    $sessionId,
1394
                    0,
1395
                    $color
1396
                );
1397
                //}
1398
            }
1399
        }
1400
1401
    }
1402
1403
    /**
1404
     * @param int $start
1405
     * @param int $end
1406
     * @param array $courseInfo
1407
     * @param int $groupId
1408
     * @param int $session_id
1409
     * @param int $user_id
1410
     * @param string $color
1411
     *
1412
     * @return array
1413
     */
1414
    public function getCourseEvents(
1415
        $start,
1416
        $end,
1417
        $courseInfo,
1418
        $groupId = 0,
1419
        $session_id = 0,
1420
        $user_id = 0,
1421
        $color = ''
1422
    ) {
1423
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
1424
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
1425
1426
        if (empty($courseInfo)) {
1427
            return array();
1428
        }
1429
        $course_id = $courseInfo['real_id'];
1430
1431
        if (empty($course_id)) {
1432
            return array();
1433
        }
1434
1435
        $session_id = intval($session_id);
1436
        $user_id = intval($user_id);
1437
        $groupList = GroupManager::get_group_list(null, $courseInfo['code']);
1438
1439
        $group_name_list = array();
1440
        if (!empty($groupList)) {
1441
            foreach ($groupList as $group) {
1442
                $group_name_list[$group['id']] = $group['name'];
1443
            }
1444
        }
1445
1446
        if (!empty($groupId)) {
1447 View Code Duplication
            if (!api_is_allowed_to_edit()) {
1448
                $user_id = api_get_user_id();
1449
                $group_memberships = GroupManager::get_group_ids(
1450
                    $course_id,
1451
                    $user_id
1452
                );
1453
            } else {
1454
                $group_memberships = GroupManager::get_group_ids(
1455
                    $course_id,
1456
                    $user_id
1457
                );
1458
            }
1459 View Code Duplication
        } else {
1460
            // if no group was defined but I am a student reviewing his agenda,
1461
            // group events should show, so we should fetch those groups to which
1462
            // I belong
1463
            if (!api_is_allowed_to_edit()) {
1464
                $user_id = api_get_user_id();
1465
                $group_memberships = GroupManager::get_group_ids(
1466
                    $course_id,
1467
                    $user_id
1468
                );
1469
            } else {
1470
                // If no group was defined and I am a teacher/admin reviewing
1471
                // someone else's agenda, we should fetch this person's groups
1472
                $group_memberships = GroupManager::get_group_ids(
1473
                    $course_id,
1474
                    $user_id
1475
                );
1476
            }
1477
        }
1478
1479
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1480
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1481
1482
        if (!empty($groupId)) {
1483
            $group_memberships = array($groupId);
1484
        }
1485
1486
        if (is_array($group_memberships) && count($group_memberships) > 0) {
1487
            if (api_is_allowed_to_edit()) {
1488
                if (!empty($groupId)) {
1489
                    $where_condition = "( ip.to_group_id IN (".implode(", ", $group_memberships).") ) ";
1490 View Code Duplication
                } else {
1491
                    if (!empty($user_id)) {
1492
                        $where_condition = "( ip.to_user_id = $user_id OR ip.to_user_id IS NULL OR (ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) ) ";
1493
                    } else {
1494
                        $where_condition = "( ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
1495
                    }
1496
                }
1497
            } else {
1498
                $where_condition = "( ip.to_user_id = $user_id OR ip.to_user_id IS NULL OR (ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) ) ";
1499
            }
1500
1501
            if (empty($session_id)) {
1502
                $sessionCondition =  "
1503
                (
1504
                    agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
1505
                ) ";
1506
            } else {
1507
                $sessionCondition =  "
1508
                (
1509
                    agenda.session_id = $session_id AND
1510
                    ip.session_id = $session_id
1511
                ) ";
1512
            }
1513
1514
            $sql = "SELECT DISTINCT
1515
                        agenda.*,
1516
                        ip.visibility,
1517
                        ip.to_group_id,
1518
                        ip.insert_user_id,
1519
                        ip.ref,
1520
                        to_user_id
1521
                    FROM $tlb_course_agenda agenda
1522
                    INNER JOIN $tbl_property ip
1523
                    ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id AND ip.tool = '".TOOL_CALENDAR_EVENT."')
1524
                    WHERE
1525
                        $where_condition AND
1526
                        ip.visibility = '1' AND
1527
                        agenda.c_id = $course_id AND
1528
                        ip.c_id = agenda.c_id AND
1529
                        $sessionCondition
1530
                    ";
1531
        } else {
1532
            $visibilityCondition = " ip.visibility='1' AND ";
1533
1534
            if (api_is_allowed_to_edit()) {
1535
                if ($user_id == 0) {
1536
                    $where_condition = "";
1537
                } else {
1538
                    $where_condition = " (ip.to_user_id = ".$user_id." OR ip.to_user_id IS NULL) AND ip.to_group_id IS NULL AND ";
1539
                }
1540
                $visibilityCondition = " (ip.visibility IN ('1', '0')) AND ";
1541
            } else {
1542
                $where_condition = " ( (ip.to_user_id = ".api_get_user_id()." OR ip.to_user_id IS NULL) AND ip.to_group_id IS NULL) AND ";
1543
            }
1544
1545
            if (empty($session_id)) {
1546
                $sessionCondition =  "
1547
                (
1548
                    agenda.session_id = 0 AND
1549
                    (ip.session_id IS NULL OR ip.session_id = 0)
1550
                ) ";
1551
            } else {
1552
                $sessionCondition =  "
1553
                (
1554
                    agenda.session_id = $session_id AND
1555
                    ip.session_id = $session_id
1556
                ) ";
1557
            }
1558
1559
            $sql = "SELECT DISTINCT
1560
                        agenda.*,
1561
                        ip.visibility,
1562
                        ip.to_group_id,
1563
                        ip.insert_user_id,
1564
                        ip.ref,
1565
                        to_user_id
1566
                    FROM $tlb_course_agenda agenda
1567
                    INNER JOIN $tbl_property ip
1568
                    ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id AND ip.tool='".TOOL_CALENDAR_EVENT."' )
1569
                    WHERE
1570
                        $where_condition
1571
                        $visibilityCondition
1572
                        agenda.c_id = $course_id AND
1573
                        $sessionCondition
1574
                    ";
1575
        }
1576
1577
        $dateCondition = null;
1578
1579 View Code Duplication
        if (!empty($start) && !empty($end)) {
1580
            $dateCondition .= "AND (
1581
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1582
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1583
                 (
1584
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1585
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1586
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1587
                 )
1588
            )";
1589
        }
1590
1591
        $sql .= $dateCondition;
1592
        $result = Database::query($sql);
1593
1594
        $coachCanEdit = false;
1595
        if (!empty($session_id)) {
1596
            $coachCanEdit = api_is_coach($session_id, $course_id);
1597
        }
1598
1599
        if (Database::num_rows($result)) {
1600
            $eventsAdded = array_column($this->events, 'unique_id');
1601
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1602
                $event = array();
1603
                $event['id'] = 'course_'.$row['id'];
1604
                $event['unique_id']  = $row['iid'];
1605
                // To avoid doubles
1606
                if (in_array($event['unique_id'], $eventsAdded)) {
1607
                    continue;
1608
                }
1609
1610
                $eventsAdded[] = $event['unique_id'];
1611
1612
                $eventId = $row['ref'];
1613
                $items = $this->getUsersAndGroupSubscribedToEvent(
1614
                    $eventId,
1615
                    $course_id,
1616
                    $this->sessionId
1617
                );
1618
                $group_to_array = $items['groups'];
1619
                $user_to_array = $items['users'];
1620
                $attachmentList = $this->getAttachmentList($row['id'], $courseInfo);
1621
                $event['attachment'] = '';
1622
1623
                if (!empty($attachmentList)) {
1624
                    foreach ($attachmentList as $attachment) {
1625
                        $has_attachment = Display::return_icon('attachment.gif', get_lang('Attachment'));
1626
                        $user_filename = $attachment['filename'];
1627
                        $url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$course_id.'&'.api_get_cidreq();
1628
                        $event['attachment'] .= $has_attachment.Display::url($user_filename, $url).'<br />';
1629
                    }
1630
                }
1631
1632
                $event['title'] = $row['title'];
1633
                $event['className'] = 'course';
1634
                $event['allDay'] = 'false';
1635
                $event['course_id'] = $course_id;
1636
                $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
1637
1638
                $sessionInfo = [];
1639 View Code Duplication
                if (isset($row['session_id']) && !empty($row['session_id'])) {
1640
                    $sessionInfo = api_get_session_info($session_id);
1641
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
1642
                }
1643
1644
                $event['session_name'] = isset($sessionInfo['name']) ? $sessionInfo['name'] : '';
1645
                $event['course_name'] = isset($courseInfo['title']) ? $courseInfo['title'] : '';
1646
1647 View Code Duplication
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1648
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
1649
                }
1650
1651
                if (!empty($color)) {
1652
                    $event['borderColor'] = $event['backgroundColor'] = $color;
1653
                }
1654
1655 View Code Duplication
                if (isset($row['color']) && !empty($row['color'])) {
1656
                    $event['borderColor'] = $event['backgroundColor'] = $row['color'];
1657
                }
1658
1659
                $event['editable'] = false;
1660
1661
                if (api_is_allowed_to_edit() && $this->type == 'course') {
1662
                    $event['editable'] = true;
1663
                    if (!empty($session_id)) {
1664
                        if ($coachCanEdit == false) {
1665
                            $event['editable'] = false;
1666
                        }
1667
                    }
1668
                }
1669
1670 View Code Duplication
                if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
1671
                    $event['start'] = $this->formatEventDate($row['start_date']);
1672
                    $event['start_date_localtime'] = api_get_local_time($row['start_date']);
1673
                }
1674 View Code Duplication
                if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
1675
                    $event['end'] = $this->formatEventDate($row['end_date']);
1676
                    $event['end_date_localtime'] = api_get_local_time($row['end_date']);
1677
                }
1678
1679
                $event['sent_to'] = '';
1680
                $event['type'] = 'course';
1681
                if ($row['session_id'] != 0) {
1682
                    $event['type'] = 'session';
1683
                }
1684
1685
                // Event Sent to a group?
1686
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1687
                    $sent_to = array();
1688
                    if (!empty($group_to_array)) {
1689
                        foreach ($group_to_array as $group_item) {
1690
                            $sent_to[] = $group_name_list[$group_item];
1691
                        }
1692
                    }
1693
                    $sent_to = implode('@@', $sent_to);
1694
                    $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
1695
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1696
                    $event['type'] = 'group';
1697
                }
1698
1699
                // Event sent to a user?
1700
                if (isset($row['to_user_id'])) {
1701
                    $sent_to = array();
1702
                    if (!empty($user_to_array)) {
1703
                        foreach ($user_to_array as $item) {
1704
                            $user_info = api_get_user_info($item);
1705
                            // Add username as tooltip for $event['sent_to'] - ref #4226
1706
                            $username = api_htmlentities(sprintf(get_lang('LoginX'), $user_info['username']), ENT_QUOTES);
1707
                            $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
1708
                        }
1709
                    }
1710
                    $sent_to = implode('@@', $sent_to);
1711
                    $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
1712
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1713
                }
1714
1715
                //Event sent to everyone!
1716
                if (empty($event['sent_to'])) {
1717
                    $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
1718
                }
1719
1720
                $event['description'] = $row['content'];
1721
                $event['visibility'] = $row['visibility'];
1722
                $event['real_id'] = $row['id'];
1723
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1724
                $event['parent_event_id'] = $row['parent_event_id'];
1725
                $event['has_children'] = $this->hasChildren($row['id'], $course_id) ? 1 : 0;
1726
                $event['comment'] = $row['comment'];
1727
1728
                $this->events[] = $event;
1729
            }
1730
        }
1731
1732
        return $this->events;
1733
    }
1734
1735
    /**
1736
     * @param int $start tms
1737
     * @param int $end tms
1738
     * @return array
1739
     */
1740
    public function getPlatformEvents($start, $end)
1741
    {
1742
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
1743
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
1744
1745
        $dateCondition = '';
1746
1747 View Code Duplication
        if (!empty($start) && !empty($end)) {
1748
            $dateCondition .= "AND (
1749
                 start_date BETWEEN '".$start."' AND '".$end."' OR
1750
                 end_date BETWEEN '".$start."' AND '".$end."' OR
1751
                 (
1752
                     start_date IS NOT NULL AND end_date IS NOT NULL AND
1753
                     YEAR(start_date) = YEAR(end_date) AND
1754
                     MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
1755
                 )
1756
            )";
1757
        }
1758
1759
        $access_url_id = api_get_current_access_url_id();
1760
1761
        $sql = "SELECT *
1762
                FROM ".$this->tbl_global_agenda."
1763
                WHERE access_url_id = $access_url_id
1764
                $dateCondition";
1765
        $result = Database::query($sql);
1766
        $my_events = array();
1767
        if (Database::num_rows($result)) {
1768
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1769
                $event = array();
1770
                $event['id'] = 'platform_'.$row['id'];
1771
                $event['title'] = $row['title'];
1772
                $event['className'] = 'platform';
1773
                $event['allDay'] = 'false';
1774
                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
1775
                $event['editable'] = false;
1776
                $event['type'] = 'admin';
1777
1778
                if (api_is_platform_admin() && $this->type == 'admin') {
1779
                    $event['editable'] = true;
1780
                }
1781
1782 View Code Duplication
                if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
1783
                    $event['start'] = $this->formatEventDate($row['start_date']);
1784
                    $event['start_date_localtime'] = api_get_local_time($row['start_date']);
1785
                }
1786 View Code Duplication
                if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
1787
                    $event['end'] = $this->formatEventDate($row['end_date']);
1788
                    $event['end_date_localtime'] = api_get_local_time($row['end_date']);
1789
                }
1790
1791
                $event['description'] = $row['content'];
1792
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1793
1794
                $event['parent_event_id'] = 0;
1795
                $event['has_children'] = 0;
1796
1797
                $my_events[] = $event;
1798
                $this->events[] = $event;
1799
            }
1800
        }
1801
1802
        return $my_events;
1803
    }
1804
1805
    /**
1806
     * Format needed for the Fullcalendar js lib
1807
     *
1808
     * @param string $utcTime
1809
     * @return bool|string
1810
     */
1811
    private function formatEventDate($utcTime)
1812
    {
1813
        $utcTimeZone = new DateTimeZone('UTC');
1814
        $platformTimeZone = new DateTimeZone(_api_get_timezone());
1815
1816
        $eventDate = new DateTime($utcTime, $utcTimeZone);
1817
        $eventDate->setTimezone($platformTimeZone);
1818
1819
        return $eventDate->format(DateTime::ISO8601);
1820
    }
1821
1822
    /**
1823
     * this function shows the form with the user that were not selected
1824
     * @author: Patrick Cool <[email protected]>, Ghent University
1825
     * @return string code
1826
     */
1827
    public static function construct_not_selected_select_form($group_list = null, $user_list = null, $to_already_selected = array())
1828
    {
1829
        $html = '<select id="users_to_send_id" data-placeholder="'.get_lang('Select').'" name="users_to_send[]" multiple="multiple">';
1830
        if ($to_already_selected == 'everyone') {
1831
            $html .= '<option value="everyone" checked="checked">'.get_lang('Everyone').'</option>';
1832
        } else {
1833
            $html .= '<option value="everyone">'.get_lang('Everyone').'</option>';
1834
        }
1835
1836
        if (is_array($group_list)) {
1837
            $html .= '<optgroup label="'.get_lang('Groups').'">';
1838
            foreach ($group_list as $this_group) {
1839
                if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'], $to_already_selected)) {
1840
                    // $to_already_selected is the array containing the groups (and users) that are already selected
1841
                    $count_users = isset($this_group['count_users']) ? $this_group['count_users'] : $this_group['userNb'];
1842
                    $count_users = " &ndash; $count_users ".get_lang('Users');
1843
1844
                    $html .= '<option value="GROUP:'.$this_group['id'].'"> '.$this_group['name'].$count_users.'</option>';
1845
                }
1846
            }
1847
            $html .= '</optgroup>';
1848
        }
1849
1850
        // adding the individual users to the select form
1851
        if (is_array($group_list)) {
1852
            $html .= '<optgroup label="'.get_lang('Users').'">';
1853
        }
1854
        foreach ($user_list as $this_user) {
1855
            // $to_already_selected is the array containing the users (and groups) that are already selected
1856
            if (!is_array($to_already_selected) || !in_array("USER:".$this_user['user_id'], $to_already_selected)) {
1857
                $username = api_htmlentities(sprintf(get_lang('LoginX'), $this_user['username']), ENT_QUOTES);
1858
                // @todo : add title attribute $username in the jqdialog window. wait for a chosen version to inherit title attribute
1859
                $html .= '<option title="'.$username.'" value="USER:'.$this_user['user_id'].'">'.api_get_person_name($this_user['firstname'], $this_user['lastname']).' ('.$this_user['username'].') </option>';
1860
            }
1861
        }
1862
        if (is_array($group_list)) {
1863
            $html .= '</optgroup>';
1864
            $html .= "</select>";
1865
        }
1866
        return $html;
1867
    }
1868
1869
    /**
1870
     * @param FormValidator $form
1871
     * @param array $groupList
1872
     * @param array $userList
1873
     * @param array $sendTo array('users' => [1, 2], 'groups' => [3, 4])
1874
     * @param array $attributes
1875
     * @param bool $addOnlyItemsInSendTo
1876
     * @param bool $required
1877
     */
1878
    public function setSendToSelect(
1879
        $form,
1880
        $groupList = null,
1881
        $userList = null,
1882
        $sendTo = array(),
1883
        $attributes = array(),
1884
        $addOnlyItemsInSendTo = false,
1885
        $required = false
1886
    ) {
1887
        $params = array(
1888
            'id' => 'users_to_send_id',
1889
            'data-placeholder' => get_lang('Select'),
1890
            'multiple' => 'multiple',
1891
            'class' => 'multiple-select'
1892
        );
1893
1894
        if (!empty($attributes)) {
1895
            $params = array_merge($params, $attributes);
1896
            if (empty($params['multiple'])) {
1897
                unset($params['multiple']);
1898
            }
1899
        }
1900
1901
        $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : array();
1902
        $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : array();
1903
1904
        /** @var HTML_QuickForm_select $select */
1905
        $select = $form->addSelect('users_to_send', get_lang('To'), null, $params);
1906
1907
        if ($required) {
1908
            $form->setRequired($select);
1909
        }
1910
1911
        $selectedEveryoneOptions = array();
1912
        if (isset($sendTo['everyone']) && $sendTo['everyone']) {
1913
            $selectedEveryoneOptions = array('selected');
1914
            $sendToUsers = array();
1915
        }
1916
1917
        $select->addOption(get_lang('Everyone'), 'everyone', $selectedEveryoneOptions);
1918
1919
        $options = array();
1920
        if (is_array($groupList)) {
1921
            foreach ($groupList as $group) {
1922
                $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
1923
                $count_users = " &ndash; $count_users ".get_lang('Users');
1924
                $option = array(
1925
                    'text' => $group['name'].$count_users,
1926
                    'value' => "GROUP:".$group['id']
1927
                );
1928
                $selected = in_array($group['id'], $sendToGroups) ? true : false;
1929
                if ($selected) {
1930
                    $option['selected'] = 'selected';
1931
                }
1932
1933
                if ($addOnlyItemsInSendTo) {
1934
                    if ($selected) {
1935
                        $options[] = $option;
1936
                    }
1937
                } else {
1938
                    $options[] = $option;
1939
                }
1940
            }
1941
            $select->addOptGroup($options, get_lang('Groups'));
1942
        }
1943
1944
        // adding the individual users to the select form
1945
        if (is_array($userList)) {
1946
            $options = array();
1947
            foreach ($userList as $user) {
1948
                if ($user['status'] == ANONYMOUS) {
1949
                    continue;
1950
                }
1951
                $option = array(
1952
                    'text' => api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')',
1953
                    'value' => "USER:".$user['user_id']
1954
                );
1955
1956
                $selected = in_array($user['user_id'], $sendToUsers) ? true : false;
1957
1958
                if ($selected) {
1959
                    $option['selected'] = 'selected';
1960
                }
1961
1962
                if ($addOnlyItemsInSendTo) {
1963
                    if ($selected) {
1964
                        $options[] = $option;
1965
                    }
1966
                } else {
1967
                    $options[] = $option;
1968
                }
1969
            }
1970
1971
            $select->addOptGroup($options, get_lang('Users'));
1972
        }
1973
    }
1974
1975
    /**
1976
     * Separates the users and groups array
1977
     * users have a value USER:XXX (with XXX the user id
1978
     * groups have a value GROUP:YYY (with YYY the group id)
1979
     * use the 'everyone' key
1980
     * @author Julio Montoya based in separate_users_groups in agenda.inc.php
1981
     * @param array $to
1982
     * @return array
1983
     */
1984
    public function parseSendToArray($to)
1985
    {
1986
        $groupList = array();
1987
        $userList = array();
1988
        $sendTo = null;
1989
1990
        $sendTo['everyone'] = false;
1991
        if (is_array($to) && count($to) > 0) {
1992
            foreach ($to as $item) {
1993
                if ($item == 'everyone') {
1994
                    $sendTo['everyone'] = true;
1995
                } else {
1996
                    list($type, $id) = explode(':', $item);
1997
                    switch ($type) {
1998
                        case 'GROUP':
1999
                            $groupList[] = $id;
2000
                            break;
2001
                        case 'USER':
2002
                            $userList[] = $id;
2003
                            break;
2004
                    }
2005
                }
2006
            }
2007
            $sendTo['groups'] = $groupList;
2008
            $sendTo['users'] = $userList;
2009
        }
2010
2011
        return $sendTo;
2012
    }
2013
2014
    /**
2015
     * @param array $params
2016
     * @return FormValidator
2017
     */
2018
    public function getForm($params = array())
2019
    {
2020
        $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
2021
        $id = isset($params['id']) ? intval($params['id']) : null;
2022
        if ($this->type == 'course') {
2023
            $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
2024
        } else {
2025
            $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
2026
        }
2027
2028
        if (isset($params['content'])) {
2029
            $params['content'] = nl2br($params['content']);
2030
        }
2031
2032
        $form = new FormValidator(
2033
            'add_event',
2034
            'post',
2035
            $url,
2036
            null,
2037
            array('enctype' => 'multipart/form-data')
2038
        );
2039
2040
        $idAttach = isset($params['id_attach']) ? intval($params['id_attach']) : null;
2041
        $groupId = api_get_group_id();
2042
2043
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
2044
            $form_title = get_lang('ModifyCalendarItem');
2045
        } else {
2046
            $form_title = get_lang('AddCalendarItem');
2047
        }
2048
2049
        $form->addElement('header', $form_title);
2050
        $form->addElement('hidden', 'id', $id);
2051
        $form->addElement('hidden', 'action', $action);
2052
        $form->addElement('hidden', 'id_attach', $idAttach);
2053
2054
        $isSubEventEdition = false;
2055
        $isParentFromSerie = false;
2056
        $showAttachmentForm = true;
2057
2058
        if ($this->type == 'course') {
2059
            // Edition mode.
2060
            if (!empty($id)) {
2061
                $showAttachmentForm = false;
2062
                if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
2063
                    $isSubEventEdition = true;
2064
                }
2065
                if (!empty($params['repeat_info'])) {
2066
                    $isParentFromSerie = true;
2067
                }
2068
            }
2069
        }
2070
2071
        if ($isSubEventEdition) {
2072
            $form->addElement(
2073
                'label',
2074
                null,
2075
                Display::return_message(get_lang('EditingThisEventWillRemoveItFromTheSerie'), 'warning')
2076
            );
2077
        }
2078
2079
        $form->addElement('text', 'title', get_lang('ItemTitle'));
2080
2081
        if (isset($groupId) && !empty($groupId)) {
2082
            $form->addElement('hidden', 'selected_form[0]', "GROUP:'.$groupId.'");
2083
            $form->addElement('hidden', 'to', 'true');
2084
        } else {
2085
            $sendTo = isset($params['send_to']) ? $params['send_to'] : null;
2086
            if ($this->type == 'course') {
2087
                $this->showToForm($form, $sendTo, array(), false, true);
2088
            }
2089
        }
2090
2091
        $form->addDateRangePicker('date_range', get_lang('StartDate'), false, array('id' => 'date_range'));
2092
        $form->addElement('checkbox', 'all_day', null, get_lang('AllDay'));
2093
2094
        if ($this->type == 'course') {
2095
            $repeat = $form->addElement('checkbox', 'repeat', null, get_lang('RepeatEvent'), array('onclick' => 'return plus_repeated_event();'));
2096
            $form->addElement('html', '<div id="options2" style="display:none">');
2097
            $form->addElement('select', 'repeat_type', get_lang('RepeatType'), self::getRepeatTypes());
2098
            $form->addElement('date_picker', 'repeat_end_day', get_lang('RepeatEnd'), array('id' => 'repeat_end_date_form'));
2099
2100
            if ($isSubEventEdition || $isParentFromSerie) {
2101
                if ($isSubEventEdition) {
2102
                    $parentEvent = $params['parent_info'];
2103
                    $repeatInfo = $parentEvent['repeat_info'];
2104
                } else {
2105
                    $repeatInfo = $params['repeat_info'];
2106
                }
2107
                $params['repeat'] = 1;
2108
                $params['repeat_type'] = $repeatInfo['cal_type'];
2109
                $params['repeat_end_day'] = substr(api_get_local_time($repeatInfo['cal_end']), 0, 10);
2110
2111
                $form->freeze(array('repeat_type', 'repeat_end_day'));
2112
                $repeat->_attributes['disabled'] = 'disabled';
2113
            }
2114
            $form->addElement('html', '</div>');
2115
        }
2116
2117
        if (!empty($id)) {
2118
            if (empty($params['end_date'])) {
2119
                $params['date_range'] = $params['end_date'];
2120
            }
2121
2122
            $params['date_range'] =
2123
                substr(api_get_local_time($params['start_date']), 0, 16).' / '.
2124
                substr(api_get_local_time($params['end_date']), 0, 16);
2125
        }
2126
2127
        if (!api_is_allowed_to_edit(null, true)) {
2128
            $toolbar = 'AgendaStudent';
2129
        } else {
2130
            $toolbar = 'Agenda';
2131
        }
2132
2133
        $form->addElement(
2134
            'html_editor',
2135
            'content',
2136
            get_lang('Description'),
2137
            null,
2138
            array('ToolbarSet' => $toolbar, 'Width' => '100%', 'Height' => '200')
2139
        );
2140
2141
        if ($this->type == 'course') {
2142
            $form->addElement('textarea', 'comment', get_lang('Comment'));
2143
            $form->addLabel(
2144
                get_lang('FilesAttachment'),
2145
                '<span id="filepaths">
2146
                        <div id="filepath_1">
2147
                            <input type="file" name="attach_1"/><br />
2148
                            '.get_lang('Description').'&nbsp;&nbsp;<input type="text" name="legend[]" /><br /><br />
2149
                        </div>
2150
                    </span>'
2151
            );
2152
2153
            $form->addLabel('',
2154
                '<span id="link-more-attach"><a href="javascript://" onclick="return add_image_form()">'.get_lang('AddOneMoreFile').'</a></span>&nbsp;('.sprintf(get_lang('MaximunFileSizeX'),format_file_size(api_get_setting('message_max_upload_filesize'))).')');
2155
2156
2157
            //if ($showAttachmentForm) {
2158
2159
            if (isset($params['attachment']) && !empty($params['attachment'])) {
2160
                $attachmentList = $params['attachment'];
2161
                foreach ($attachmentList as $attachment) {
2162
                    $params['file_comment'] = $attachment['comment'];
2163
                    if (!empty($attachment['path'])) {
2164
                        $form->addElement(
2165
                            'checkbox',
2166
                            'delete_attachment['.$attachment['id'].']',
2167
                            null,
2168
                            get_lang('DeleteAttachment').': '.$attachment['filename']
2169
                        );
2170
                    }
2171
                }
2172
2173
            }
2174
            // }
2175
2176
            $form->addElement('textarea', 'file_comment', get_lang('FileComment'));
2177
        }
2178
2179
        if (empty($id)) {
2180
            $form->addElement(
2181
                'checkbox',
2182
                'add_announcement',
2183
                null,
2184
                get_lang('AddAnnouncement').'&nbsp('.get_lang('SendMail').')'
2185
            );
2186
        }
2187
2188
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
2189
            $form->addButtonUpdate(get_lang('ModifyEvent'));
2190
        } else {
2191
            $form->addButtonSave(get_lang('AgendaAdd'));
2192
        }
2193
2194
        $form->setDefaults($params);
2195
2196
        $form->addRule('date_range', get_lang('ThisFieldIsRequired'), 'required');
2197
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
2198
2199
        return $form;
2200
    }
2201
2202
    /**
2203
     * @param FormValidator $form
2204
     * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
2205
     * @param array $attributes
2206
     * @param bool $addOnlyItemsInSendTo
2207
     * @param bool $required
2208
     * @return bool
2209
     */
2210
    public function showToForm(
2211
        $form,
2212
        $sendTo = array(),
2213
        $attributes = array(),
2214
        $addOnlyItemsInSendTo = false,
2215
        $required = false
2216
    ) {
2217
        if ($this->type != 'course') {
2218
            return false;
2219
        }
2220
2221
        $order = 'lastname';
2222
        if (api_is_western_name_order()) {
2223
            $order = 'firstname';
2224
        }
2225
2226
        $userList = CourseManager::get_user_list_from_course_code(
2227
            api_get_course_id(),
2228
            $this->sessionId,
2229
            null,
2230
            $order
2231
        );
2232
        $groupList = CourseManager::get_group_list_of_course(
2233
            api_get_course_id(),
2234
            $this->sessionId
2235
        );
2236
2237
        $this->setSendToSelect(
2238
            $form,
2239
            $groupList,
2240
            $userList,
0 ignored issues
show
Bug introduced by
It seems like $userList defined by \CourseManager::get_user...essionId, null, $order) on line 2226 can also be of type integer; however, Agenda::setSendToSelect() does only seem to accept array|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2241
            $sendTo,
2242
            $attributes,
2243
            $addOnlyItemsInSendTo,
2244
            $required
2245
        );
2246
2247
        return true;
2248
2249
    }
2250
2251
    /**
2252
     * @param int $id
2253
     * @param int $visibility 0= invisible, 1 visible
2254
     * @param array $courseInfo
2255
     * @param int $userId
2256
     */
2257
    public static function changeVisibility($id, $visibility, $courseInfo, $userId = null)
2258
    {
2259
        $id = intval($id);
2260
        if (empty($userId)) {
2261
            $userId = api_get_user_id();
2262
        } else {
2263
            $userId = intval($userId);
2264
        }
2265
2266
        if ($visibility == 0) {
2267
            api_item_property_update($courseInfo, TOOL_CALENDAR_EVENT, $id, "invisible", $userId);
2268
        } else {
2269
            api_item_property_update($courseInfo, TOOL_CALENDAR_EVENT, $id, "visible", $userId);
2270
        }
2271
    }
2272
2273
    /**
2274
     * Get repeat types
2275
     * @return array
2276
     */
2277
    public static function getRepeatTypes()
2278
    {
2279
        return array(
2280
            'daily' => get_lang('RepeatDaily'),
2281
            'weekly'  => get_lang('RepeatWeekly'),
2282
            'monthlyByDate'  => get_lang('RepeatMonthlyByDate'),
2283
            //monthlyByDay"> get_lang('RepeatMonthlyByDay');
2284
            //monthlyByDayR' => get_lang('RepeatMonthlyByDayR'),
2285
            'yearly' => get_lang('RepeatYearly')
2286
        );
2287
    }
2288
2289
    /**
2290
     * Show a list with all the attachments according to the post's id
2291
     * @param int $eventId
2292
     * @param array $courseInfo
2293
     * @return array with the post info
2294
     */
2295 View Code Duplication
    public function getAttachmentList($eventId, $courseInfo)
2296
    {
2297
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2298
        $courseId = intval($courseInfo['real_id']);
2299
        $eventId = intval($eventId);
2300
2301
        $sql = "SELECT id, path, filename, comment
2302
                FROM $tableAttachment
2303
                WHERE
2304
                    c_id = $courseId AND
2305
                    agenda_id = $eventId";
2306
        $result = Database::query($sql);
2307
        $list = array();
2308
        if (Database::num_rows($result) != 0) {
2309
            $list = Database::store_result($result, 'ASSOC');
2310
        }
2311
2312
        return $list;
2313
    }
2314
2315
2316
    /**
2317
     * Show a list with all the attachments according to the post's id
2318
     * @param int $attachmentId
2319
     * @param int $eventId
2320
     * @param array $courseInfo
2321
     * @return array with the post info
2322
     */
2323 View Code Duplication
    public function getAttachment($attachmentId, $eventId, $courseInfo)
2324
    {
2325
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2326
        $courseId = intval($courseInfo['real_id']);
2327
        $eventId = intval($eventId);
2328
        $attachmentId = intval($attachmentId);
2329
2330
        $row = array();
2331
        $sql = "SELECT id, path, filename, comment
2332
                FROM $tableAttachment
2333
                WHERE
2334
                    c_id = $courseId AND
2335
                    agenda_id = $eventId AND
2336
                    id = $attachmentId
2337
                ";
2338
        $result = Database::query($sql);
2339
        if (Database::num_rows($result) != 0) {
2340
            $row = Database::fetch_array($result, 'ASSOC');
2341
        }
2342
2343
        return $row;
2344
    }
2345
2346
    /**
2347
     * Add an attachment file into agenda
2348
     * @param int $eventId
2349
     * @param array $fileUserUpload ($_FILES['user_upload'])
2350
     * @param string comment about file
2351
     * @param array $courseInfo
2352
     * @return string
2353
     */
2354
    public function addAttachment($eventId, $fileUserUpload, $comment, $courseInfo)
2355
    {
2356
        $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2357
        $eventId = intval($eventId);
2358
2359
        // Storing the attachments
2360
        $upload_ok = false;
2361
        if (!empty($fileUserUpload['name'])) {
2362
            $upload_ok = process_uploaded_file($fileUserUpload);
2363
        }
2364
        if (!empty($upload_ok)) {
2365
2366
            $courseDir = $courseInfo['directory'].'/upload/calendar';
2367
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2368
            $uploadDir = $sys_course_path.$courseDir;
2369
2370
            // Try to add an extension to the file if it hasn't one
2371
            $new_file_name = add_ext_on_mime(
2372
                stripslashes($fileUserUpload['name']),
2373
                $fileUserUpload['type']
2374
            );
2375
            // user's file name
2376
            $file_name = $fileUserUpload['name'];
2377
2378
            if (!filter_extension($new_file_name)) {
2379
                return Display::return_message(
2380
                    get_lang('UplUnableToSaveFileFilteredExtension'),
2381
                    'error'
2382
                );
2383
            } else {
2384
                $new_file_name = uniqid('');
2385
                $new_path = $uploadDir.'/'.$new_file_name;
2386
                $result = @move_uploaded_file($fileUserUpload['tmp_name'], $new_path);
2387
                $course_id = api_get_course_int_id();
2388
                $size = intval($fileUserUpload['size']);
2389
                // Storing the attachments if any
2390
                if ($result) {
2391
                    $params = [
2392
                        'c_id' => $course_id,
2393
                        'filename' => $file_name,
2394
                        'comment' => $comment,
2395
                        'path' => $new_file_name,
2396
                        'agenda_id' => $eventId,
2397
                        'size' => $size
2398
                    ];
2399
                    $id = Database::insert($agenda_table_attachment, $params);
2400
                    if ($id) {
2401
                        $sql = "UPDATE $agenda_table_attachment
2402
                                SET id = iid WHERE iid = $id";
2403
                        Database::query($sql);
2404
2405
                        api_item_property_update(
2406
                            $courseInfo,
2407
                            'calendar_event_attachment',
2408
                            $id,
2409
                            'AgendaAttachmentAdded',
2410
                            api_get_user_id()
2411
                        );
2412
                    }
2413
                }
2414
            }
2415
        }
2416
    }
2417
2418
    /**
2419
     * @param int $attachmentId
2420
     * @param int $eventId
2421
     * @param array $fileUserUpload
2422
     * @param string $comment
2423
     * @param array $courseInfo
2424
     */
2425
    public function updateAttachment($attachmentId, $eventId, $fileUserUpload, $comment, $courseInfo)
2426
    {
2427
        $attachment = $this->getAttachment($attachmentId, $eventId, $courseInfo);
2428
        if (!empty($attachment)) {
2429
            $this->deleteAttachmentFile($attachmentId, $courseInfo);
2430
        }
2431
        $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
2432
    }
2433
2434
    /**
2435
     * This function delete a attachment file by id
2436
     * @param int $attachmentId
2437
     * @param array $courseInfo
2438
     * @return string
2439
     */
2440
    public function deleteAttachmentFile($attachmentId, $courseInfo)
2441
    {
2442
        $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2443
        $attachmentId = intval($attachmentId);
2444
        $courseId = $courseInfo['real_id'];
2445
2446
        if (empty($courseId) || empty($attachmentId)) {
2447
            return false;
2448
        }
2449
2450
        $sql = "DELETE FROM $agenda_table_attachment
2451
                WHERE c_id = $courseId AND id = ".$attachmentId;
2452
        $result = Database::query($sql);
2453
2454
        // update item_property
2455
        api_item_property_update(
2456
            $courseInfo,
2457
            'calendar_event_attachment',
2458
            $attachmentId,
2459
            'AgendaAttachmentDeleted',
2460
            api_get_user_id()
2461
        );
2462
2463
        if (!empty($result)) {
2464
            return Display::return_message(get_lang("AttachmentFileDeleteSuccess"), 'confirmation');
2465
        }
2466
    }
2467
2468
    /**
2469
     * Adds x weeks to a UNIX timestamp
2470
     * @param   int     The timestamp
2471
     * @param   int     The number of weeks to add
2472
     * @return  int     The new timestamp
2473
     */
2474
    function addWeek($timestamp, $num = 1)
2475
    {
2476
        return $timestamp + $num * 604800;
2477
    }
2478
2479
    /**
2480
     * Adds x months to a UNIX timestamp
2481
     * @param   int     The timestamp
2482
     * @param   int     The number of years to add
2483
     * @return  int     The new timestamp
2484
     */
2485
    function addMonth($timestamp, $num = 1)
2486
    {
2487
        list($y, $m, $d, $h, $n, $s) = split('/', date('Y/m/d/h/i/s', $timestamp));
2488 View Code Duplication
        if ($m + $num > 12) {
2489
            $y += floor($num / 12);
2490
            $m += $num % 12;
2491
        } else {
2492
            $m += $num;
2493
        }
2494
        return mktime($h, $n, $s, $m, $d, $y);
2495
    }
2496
2497
    /**
2498
     * Adds x years to a UNIX timestamp
2499
     * @param   int     The timestamp
2500
     * @param   int     The number of years to add
2501
     * @return  int     The new timestamp
2502
     */
2503
    function addYear($timestamp, $num = 1)
2504
    {
2505
        list($y, $m, $d, $h, $n, $s) = split('/', date('Y/m/d/h/i/s', $timestamp));
2506
        return mktime($h, $n, $s, $m, $d, $y + $num);
2507
    }
2508
2509
    /**
2510
     * @param int $eventId
2511
     * @return array
2512
     */
2513
    public function getAllRepeatEvents($eventId)
2514
    {
2515
        $events = array();
2516
        switch ($this->type) {
2517
            case 'personal':
2518
                break;
2519
            case 'course':
2520
                if (!empty($this->course['real_id'])) {
2521
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
2522
                            WHERE
2523
                                c_id = ".$this->course['real_id']." AND
2524
                                parent_event_id = ".$eventId;
2525
                    $result = Database::query($sql);
2526
                    if (Database::num_rows($result)) {
2527
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
2528
                            $events[] = $row;
2529
                        }
2530
                    }
2531
                }
2532
                break;
2533
        }
2534
2535
        return $events;
2536
    }
2537
2538
    /**
2539
     * @param int $eventId
2540
     * @param int $courseId
2541
     *
2542
     * @return bool
2543
     */
2544
    public function hasChildren($eventId, $courseId)
2545
    {
2546
        $eventId = intval($eventId);
2547
        $courseId = intval($courseId);
2548
2549
        $sql = "SELECT count(DISTINCT(id)) as count
2550
                FROM ".$this->tbl_course_agenda."
2551
                WHERE
2552
                    c_id = ".$courseId." AND
2553
                    parent_event_id = ".$eventId;
2554
        $result = Database::query($sql);
2555
        if (Database::num_rows($result)) {
2556
            $row = Database::fetch_array($result, 'ASSOC');
2557
            return $row['count'] > 0;
2558
        }
2559
        return false;
2560
    }
2561
2562
    /**
2563
     * @param int $filter
2564
     * @param string $view
2565
     * @return string
2566
     */
2567
    public function displayActions($view, $filter = 0)
2568
    {
2569
        $courseInfo = api_get_course_info();
2570
2571
        $actionsLeft = '';
2572
        $actionsLeft .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_js.php?type={$this->type}'>".
2573
            Display::return_icon('calendar.png', get_lang('Calendar'), '', ICON_SIZE_MEDIUM)."</a>";
2574
2575
        $courseCondition = '';
2576
        if (!empty($courseInfo)) {
2577
            $courseCondition = api_get_cidreq();
2578
        }
2579
2580
        $actionsLeft .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_list.php?type={$this->type}&".$courseCondition."'>".
2581
            Display::return_icon('week.png', get_lang('AgendaList'), '', ICON_SIZE_MEDIUM)."</a>";
2582
2583
        $form = '';
2584
2585
        if (api_is_allowed_to_edit(false, true) ||
2586
            (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false, true) ||
2587
            GroupManager::user_has_access(api_get_user_id(), api_get_group_id(), GroupManager::GROUP_TOOL_CALENDAR) &&
2588
            GroupManager::is_tutor_of_group(api_get_user_id(), api_get_group_id())
2589
        ) {
2590
            $actionsLeft .= Display::url(
2591
                Display::return_icon('new_event.png', get_lang('AgendaAdd'), '', ICON_SIZE_MEDIUM),
2592
                api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=add&type=".$this->type
2593
            );
2594
2595
            $actionsLeft .= Display::url(
2596
                Display::return_icon('import_calendar.png', get_lang('ICalFileImport'), '', ICON_SIZE_MEDIUM),
2597
                api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=importical&type=".$this->type
2598
            );
2599
2600
            if ($this->type == 'course') {
2601
2602
                if (!isset($_GET['action'])) {
2603
2604
                    $form = new FormValidator(
2605
                        'form-search',
2606
                        'post',
2607
                        '',
2608
                        '',
2609
                        array(),
2610
                        FormValidator::LAYOUT_INLINE
2611
                    );
2612
                    $attributes = array(
2613
                        'multiple' => false,
2614
                        'id' => 'select_form_id_search'
2615
                    );
2616
                    $selectedValues = $this->parseAgendaFilter($filter);
2617
                    $this->showToForm($form, $selectedValues, $attributes);
2618
                    $form = $form->returnForm();
2619
                }
2620
            }
2621
        }
2622
2623
        if (api_is_platform_admin() ||
2624
            api_is_teacher() ||
2625
            api_is_student_boss() ||
2626
            api_is_drh() ||
2627
            api_is_session_admin() ||
2628
            api_is_coach()
2629
        ) {
2630
            if ($this->type == 'personal') {
2631
                $form = null;
2632
                if (!isset($_GET['action'])) {
2633
2634
                    $form = new FormValidator(
2635
                        'form-search',
2636
                        'get',
2637
                        api_get_self().'?type=personal&',
2638
                        '',
2639
                        array(),
2640
                        FormValidator::LAYOUT_INLINE
2641
                    );
2642
2643
                    $sessions = SessionManager::get_sessions_by_user(api_get_user_id());
2644
                    $form->addHidden('type', 'personal');
2645
                    $sessions = array_column($sessions, 'session_name', 'session_id');
2646
                    $sessions = ['0' => get_lang('SelectAnOption')] + $sessions;
2647
2648
                    $form->addSelect(
2649
                        'session_id',
2650
                        get_lang('Session'),
2651
                        $sessions,
2652
                        ['id' => 'session_id', 'onchange' => 'submit();']
2653
                    );
2654
                    //$form->addButtonFilter(get_lang('Filter'));
2655
                    //$renderer = $form->defaultRenderer();
2656
                    //$renderer->setCustomElementTemplate('<div class="col-md-6">{element}</div>');
2657
2658
                    $form->addButtonReset(get_lang('Reset'));
2659
                    $form = $form->returnForm();
2660
                }
2661
            }
2662
        }
2663
2664
        $actionsRight = '';
2665
        if ($view == 'calendar') {
2666
            $actionsRight .= $form;
2667
        }
2668
2669
        $toolbar = Display::toolbarAction(
2670
            'toolbar-agenda',
2671
            array(0 => $actionsLeft, 1 => $actionsRight),
2672
            2,
2673
            false
2674
        );
2675
        return $toolbar;
2676
    }
2677
2678
    /**
2679
     * @return FormValidator
2680
     */
2681
    public function getImportCalendarForm()
2682
    {
2683
        $form = new FormValidator(
2684
            'frm_import_ical',
2685
            'post',
2686
            api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&type='.$this->type,
2687
            array('enctype' => 'multipart/form-data')
2688
        );
2689
        $form->addElement('header', get_lang('ICalFileImport'));
2690
        $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
2691
        $form->addRule('ical_import', get_lang('ThisFieldIsRequired'), 'required');
2692
        $form->addButtonImport(get_lang('Import'), 'ical_submit');
2693
2694
        return $form;
2695
    }
2696
2697
    /**
2698
     * @param array $courseInfo
2699
     * @param $file
2700
     * @return array|bool|string
2701
     */
2702
    public function importEventFile($courseInfo, $file)
2703
    {
2704
        $charset = api_get_system_encoding();
2705
        $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
2706
        $messages = array();
2707
2708
        if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
2709
            error_log('Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__);
2710
            return false;
2711
        }
2712
2713
        $data = file_get_contents($filepath);
2714
2715
        $trans = array(
2716
            'DAILY' => 'daily',
2717
            'WEEKLY' => 'weekly',
2718
            'MONTHLY' => 'monthlyByDate',
2719
            'YEARLY' => 'yearly'
2720
        );
2721
        $sentTo = array('everyone' => true);
2722
        $calendar = Sabre\VObject\Reader::read($data);
2723
        $currentTimeZone = _api_get_timezone();
2724
        if (!empty($calendar->VEVENT)) {
2725
            foreach ($calendar->VEVENT as $event) {
2726
                $start = $event->DTSTART->getDateTime();
2727
                $end = $event->DTEND->getDateTime();
2728
                //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
2729
2730
                $startDateTime = api_get_local_time($start->format('Y-m-d H:i:s'), $currentTimeZone, $start->format('e'));
2731
                $endDateTime = api_get_local_time($end->format('Y-m-d H:i'), $currentTimeZone, $end->format('e'));
2732
                $title = api_convert_encoding((string)$event->summary, $charset, 'UTF-8');
2733
                $description = api_convert_encoding((string)$event->description, $charset, 'UTF-8');
2734
2735
                $id = $this->addEvent(
2736
                    $startDateTime,
2737
                    $endDateTime,
2738
                    'false',
2739
                    $title,
2740
                    $description,
2741
                    $sentTo
2742
                );
2743
2744
                $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
2745
2746
                //$attendee = (string)$event->attendee;
2747
                /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
2748
                $repeat = $event->RRULE;
2749
                if ($id && !empty($repeat)) {
2750
2751
                    $repeat = $repeat->getParts();
2752
                    $freq = $trans[$repeat['FREQ']];
2753
2754
                    if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
2755
                        // Check if datetime or just date (strlen == 8)
2756
                        if (strlen($repeat['UNTIL']) == 8) {
2757
                            // Fix the datetime format to avoid exception in the next step
2758
                            $repeat['UNTIL'] .= 'T000000';
2759
                        }
2760
                        $until = Sabre\VObject\DateTimeParser::parseDateTime($repeat['UNTIL'], new DateTimeZone($currentTimeZone));
2761
                        $until = $until->format('Y-m-d H:i');
2762
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $until, $attendee);
2763
                        $this->addRepeatedItem(
2764
                            $id,
2765
                            $freq,
2766
                            $until,
2767
                            $sentTo
2768
                        );
2769
                    }
2770
2771
                    if (!empty($repeat['COUNT'])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
2772
                        /*$count = $repeat['COUNT'];
2773
                        $interval = $repeat['INTERVAL'];
2774
                        $endDate = null;
2775
                        switch($freq) {
2776
                            case 'daily':
2777
                                $start = api_strtotime($startDateTime);
2778
                                $date = new DateTime($startDateTime);
2779
                                $days = $count * $interval;
2780
                                var_dump($days);
2781
                                $date->add(new DateInterval("P".$days."D"));
2782
                                $endDate = $date->format('Y-m-d H:i');
2783
                                //$endDate = $count *
2784
                                for ($i = 0; $i < $count; $i++) {
2785
                                    $days = 86400 * 7
2786
                                }
2787
                            }
2788
                        }*/
2789
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
2790
                        /*$this->addRepeatedItem(
2791
                            $id,
2792
                            $freq,
2793
                            $endDate,
2794
                            $sentTo
2795
                        );*/
2796
                    }
2797
                }
2798
            }
2799
        }
2800
2801
        if (!empty($messages)) {
2802
            $messages = implode('<br /> ', $messages);
2803
        } else {
2804
            $messages = get_lang('NoAgendaItems');
2805
2806
        }
2807
2808
        return $messages;
2809
    }
2810
2811
    /**
2812
     * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]]
2813
     * @param $filter
2814
     * @return array
2815
     */
2816
    public function parseAgendaFilter($filter)
2817
    {
2818
        $everyone = false;
2819
        $groupId = null;
2820
        $userId = null;
2821
2822
        if ($filter == 'everyone') {
2823
            $everyone = true;
2824
        } else {
2825
            if (substr($filter, 0, 1) == 'G') {
2826
                $groupId = str_replace('GROUP:', '', $filter);
2827
            } else {
2828
                $userId = str_replace('USER:', '', $filter);
2829
            }
2830
        }
2831
        if (empty($userId) && empty($groupId)) {
2832
            $everyone = true;
2833
        }
2834
2835
        return array(
2836
            'everyone' => $everyone,
2837
            'users' => array($userId),
2838
            'groups' => array($groupId)
2839
        );
2840
    }
2841
2842
    /**
2843
     *	This function retrieves all the agenda items of all the courses the user is subscribed to
2844
     */
2845
    public static function get_myagendaitems($user_id, $courses_dbs, $month, $year)
2846
    {
2847
        $user_id = intval($user_id);
2848
2849
        $items = array();
2850
        $my_list = array();
2851
2852
        // get agenda-items for every course
2853
        foreach ($courses_dbs as $key => $array_course_info) {
2854
            //databases of the courses
2855
            $TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA);
2856
            $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
2857
2858
            $group_memberships = GroupManager :: get_group_ids($array_course_info["real_id"], $user_id);
2859
            $course_user_status = CourseManager::get_user_in_course_status($user_id, $array_course_info["code"]);
2860
            // if the user is administrator of that course we show all the agenda items
2861
            if ($course_user_status == '1') {
2862
                //echo "course admin";
2863
                $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
2864
							FROM ".$TABLEAGENDA." agenda,
2865
								 ".$TABLE_ITEMPROPERTY." ip
2866
							WHERE agenda.id = ip.ref
2867
							AND MONTH(agenda.start_date)='".$month."'
2868
							AND YEAR(agenda.start_date)='".$year."'
2869
							AND ip.tool='".TOOL_CALENDAR_EVENT."'
2870
							AND ip.visibility='1'
2871
							GROUP BY agenda.id
2872
							ORDER BY start_date ";
2873
            } else {
2874
                // if the user is not an administrator of that course
2875
                if (is_array($group_memberships) && count($group_memberships)>0) {
2876
                    $sqlquery = "SELECT	agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
2877
								FROM ".$TABLEAGENDA." agenda,
2878
									".$TABLE_ITEMPROPERTY." ip
2879
								WHERE agenda.id = ip.ref
2880
								AND MONTH(agenda.start_date)='".$month."'
2881
								AND YEAR(agenda.start_date)='".$year."'
2882
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
2883
								AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) )
2884
								AND ip.visibility='1'
2885
								ORDER BY start_date ";
2886
                } else {
2887
                    $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
2888
								FROM ".$TABLEAGENDA." agenda,
2889
									".$TABLE_ITEMPROPERTY." ip
2890
								WHERE agenda.id = ip.ref
2891
								AND MONTH(agenda.start_date)='".$month."'
2892
								AND YEAR(agenda.start_date)='".$year."'
2893
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
2894
								AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2895
								AND ip.visibility='1'
2896
								ORDER BY start_date ";
2897
                }
2898
            }
2899
            $result = Database::query($sqlquery);
2900
2901
            while ($item = Database::fetch_array($result, 'ASSOC')) {
2902
                $agendaday = -1;
2903
                if ($item['start_date'] != '0000-00-00 00:00:00') {
2904
                    $item['start_date'] = api_get_local_time($item['start_date']);
2905
                    $item['start_date_tms']  = api_strtotime($item['start_date']);
2906
                    $agendaday = date("j", $item['start_date_tms']);
2907
                }
2908
                if ($item['end_date'] != '0000-00-00 00:00:00') {
2909
                    $item['end_date'] = api_get_local_time($item['end_date']);
2910
                }
2911
2912
                $url  = api_get_path(WEB_CODE_PATH)."calendar/agenda.php?cidReq=".urlencode($array_course_info["code"])."&day=$agendaday&month=$month&year=$year#$agendaday";
2913
2914
                $item['url'] = $url;
2915
                $item['course_name'] = $array_course_info['title'];
2916
                $item['calendar_type'] = 'course';
2917
                $item['course_id'] = $array_course_info['course_id'];
2918
2919
                $my_list[$agendaday][] = $item;
2920
            }
2921
        }
2922
2923
        // sorting by hour for every day
2924
        $agendaitems = array ();
2925
        while (list ($agendaday, $tmpitems) = each($items)) {
2926
            if(!isset($agendaitems[$agendaday])) {
2927
                $agendaitems[$agendaday] = '';
2928
            }
2929
            sort($tmpitems);
2930
            while (list ($key, $val) = each($tmpitems)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $key is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
2931
                $agendaitems[$agendaday] .= $val;
2932
            }
2933
        }
2934
        return $my_list;
2935
    }
2936
2937
    /**
2938
     * This function retrieves one personal agenda item returns it.
2939
     * @param	array	The array containing existing events. We add to this array.
2940
     * @param	int		Day
2941
     * @param	int		Month
2942
     * @param	int		Year (4 digits)
2943
     * @param	int		Week number
2944
     * @param	string	Type of view (month_view, week_view, day_view)
2945
     * @return 	array	The results of the database query, or null if not found
2946
     */
2947
    public static function get_global_agenda_items($agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
2948
    {
2949
        $tbl_global_agenda = Database::get_main_table(
2950
            TABLE_MAIN_SYSTEM_CALENDAR
2951
        );
2952
        $month = intval($month);
2953
        $year = intval($year);
2954
        $week = intval($week);
2955
        $day = intval($day);
2956
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
2957
2958
        $current_access_url_id = api_get_current_access_url_id();
2959
2960
        if ($type == "month_view" or $type == "") {
2961
            // We are in month view
2962
            $sql = "SELECT * FROM ".$tbl_global_agenda." WHERE MONTH(start_date) = ".$month." AND YEAR(start_date) = ".$year."  AND access_url_id = $current_access_url_id ORDER BY start_date ASC";
2963
        }
2964
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
2965 View Code Duplication
        if ($type == "week_view") { // we are in week view
2966
            $start_end_day_of_week = self::calculate_start_end_of_week($week, $year);
2967
            $start_day = $start_end_day_of_week['start']['day'];
2968
            $start_month = $start_end_day_of_week['start']['month'];
2969
            $start_year = $start_end_day_of_week['start']['year'];
2970
            $end_day = $start_end_day_of_week['end']['day'];
2971
            $end_month = $start_end_day_of_week['end']['month'];
2972
            $end_year = $start_end_day_of_week['end']['year'];
2973
            // in sql statements you have to use year-month-day for date calculations
2974
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
2975
            $start_filter = api_get_utc_datetime($start_filter);
2976
2977
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
2978
            $end_filter = api_get_utc_datetime($end_filter);
2979
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND  access_url_id = $current_access_url_id ";
2980
        }
2981
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
2982 View Code Duplication
        if ($type == "day_view") { // we are in day view
2983
            // we could use mysql date() function but this is only available from 4.1 and higher
2984
            $start_filter = $year."-".$month."-".$day." 00:00:00";
2985
            $start_filter = api_get_utc_datetime($start_filter);
2986
2987
            $end_filter = $year."-".$month."-".$day." 23:59:59";
2988
            $end_filter = api_get_utc_datetime($end_filter);
2989
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'  AND  access_url_id = $current_access_url_id";
2990
        }
2991
2992
        $result = Database::query($sql);
2993
2994
        while ($item = Database::fetch_array($result)) {
2995
2996
            if ($item['start_date'] != '0000-00-00 00:00:00') {
2997
                $item['start_date'] = api_get_local_time($item['start_date']);
2998
                $item['start_date_tms'] = api_strtotime($item['start_date']);
2999
            }
3000
            if ($item['end_date'] != '0000-00-00 00:00:00') {
3001
                $item['end_date'] = api_get_local_time($item['end_date']);
3002
            }
3003
3004
            // we break the date field in the database into a date and a time part
3005
            $agenda_db_date = explode(" ", $item['start_date']);
3006
            $date = $agenda_db_date[0];
3007
            $time = $agenda_db_date[1];
3008
            // we divide the date part into a day, a month and a year
3009
            $agendadate = explode("-", $date);
3010
            $year = intval($agendadate[0]);
3011
            $month = intval($agendadate[1]);
3012
            $day = intval($agendadate[2]);
3013
            // we divide the time part into hour, minutes, seconds
3014
            $agendatime = explode(":", $time);
3015
            $hour = $agendatime[0];
3016
            $minute = $agendatime[1];
3017
            $second = $agendatime[2];
3018
3019
            if ($type == 'month_view') {
3020
                $item['calendar_type'] = 'global';
3021
                $agendaitems[$day][] = $item;
3022
                continue;
3023
            }
3024
3025
            $start_time = api_format_date(
3026
                $item['start_date'],
3027
                TIME_NO_SEC_FORMAT
3028
            );
3029
            $end_time = '';
3030
            if ($item['end_date'] != '0000-00-00 00:00:00') {
3031
                $end_time = ' - '.api_format_date(
3032
                        $item['end_date'],
3033
                        DATE_TIME_FORMAT_LONG
3034
                    );
3035
            }
3036
3037
            // if the student has specified a course we a add a link to that course
3038 View Code Duplication
            if ($item['course'] <> "") {
3039
                $url = api_get_path(
3040
                        WEB_CODE_PATH
3041
                    )."admin/agenda.php?cidReq=".urlencode(
3042
                        $item['course']
3043
                    )."&day=$day&month=$month&year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
3044
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
3045
            } else {
3046
                $course_link = "";
3047
            }
3048
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3049
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3050
            if ($type !== "day_view") {
3051
                // This is the array construction for the WEEK or MONTH view
3052
                //Display the Agenda global in the tab agenda (administrator)
3053
                $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
3054
                $agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
3055
                $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
3056
            } else {
3057
                // this is the array construction for the DAY view
3058
                $halfhour = 2 * $agendatime['0'];
3059
                if ($agendatime['1'] >= '30') {
3060
                    $halfhour = $halfhour + 1;
3061
                }
3062
                if (!is_array($agendaitems[$halfhour])) {
3063
                    $content = $agendaitems[$halfhour];
3064
                }
3065
                $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
3066
                        'GlobalEvent'
3067
                    ).":  </b>".$item['title']."</div>";
3068
            }
3069
        }
3070
3071
        return $agendaitems;
3072
    }
3073
3074
    /**
3075
     * This function retrieves all the personal agenda items and add them to the agenda items found by the other functions.
3076
     */
3077
    public static function get_personal_agenda_items($user_id, $agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
3078
    {
3079
        $tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
3080
        $user_id = intval($user_id);
3081
3082
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3083
        if ($type == "month_view" or $type == "") {
3084
            // we are in month view
3085
            $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."'  ORDER BY date ASC";
3086
        }
3087
3088
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3089
        // we are in week view
3090 View Code Duplication
        if ($type == "week_view") {
3091
            $start_end_day_of_week = self::calculate_start_end_of_week($week, $year);
3092
            $start_day = $start_end_day_of_week['start']['day'];
3093
            $start_month = $start_end_day_of_week['start']['month'];
3094
            $start_year = $start_end_day_of_week['start']['year'];
3095
            $end_day = $start_end_day_of_week['end']['day'];
3096
            $end_month = $start_end_day_of_week['end']['month'];
3097
            $end_year = $start_end_day_of_week['end']['year'];
3098
            // in sql statements you have to use year-month-day for date calculations
3099
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3100
            $start_filter  = api_get_utc_datetime($start_filter);
3101
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3102
            $end_filter  = api_get_utc_datetime($end_filter);
3103
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3104
        }
3105
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3106 View Code Duplication
        if ($type == "day_view") {
3107
            // we are in day view
3108
            // we could use mysql date() function but this is only available from 4.1 and higher
3109
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3110
            $start_filter  = api_get_utc_datetime($start_filter);
3111
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3112
            $end_filter  = api_get_utc_datetime($end_filter);
3113
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3114
        }
3115
3116
        $result = Database::query($sql);
3117
        while ($item = Database::fetch_array($result, 'ASSOC')) {
3118
3119
            $time_minute 	= api_convert_and_format_date($item['date'], TIME_NO_SEC_FORMAT);
3120
            $item['date']   = api_get_local_time($item['date']);
3121
            $item['start_date_tms']  = api_strtotime($item['date']);
3122
            $item['content'] = $item['text'];
3123
3124
            // we break the date field in the database into a date and a time part
3125
            $agenda_db_date = explode(" ", $item['date']);
3126
            $date = $agenda_db_date[0];
3127
            $time = $agenda_db_date[1];
3128
            // we divide the date part into a day, a month and a year
3129
            $agendadate = explode("-", $item['date']);
3130
            $year = intval($agendadate[0]);
3131
            $month = intval($agendadate[1]);
3132
            $day = intval($agendadate[2]);
3133
            // we divide the time part into hour, minutes, seconds
3134
            $agendatime = explode(":", $time);
3135
3136
            $hour = $agendatime[0];
3137
            $minute = $agendatime[1];
3138
            $second = $agendatime[2];
3139
3140
            if ($type == 'month_view') {
3141
                $item['calendar_type']  = 'personal';
3142
                $item['start_date']  	= $item['date'];
3143
                $agendaitems[$day][] 	= $item;
3144
                continue;
3145
            }
3146
3147
            // if the student has specified a course we a add a link to that course
3148 View Code Duplication
            if ($item['course'] <> "") {
3149
                $url = api_get_path(WEB_CODE_PATH)."calendar/agenda.php?cidReq=".urlencode($item['course'])."&day=$day&month=$month&year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
3150
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
3151
            } else {
3152
                $course_link = "";
3153
            }
3154
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3155
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3156
            if ($type !== "day_view") {
3157
                // This is the array construction for the WEEK or MONTH view
3158
3159
                //Display events in agenda
3160
                $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 />";
3161
3162
            } else {
3163
                // this is the array construction for the DAY view
3164
                $halfhour = 2 * $agendatime['0'];
3165
                if ($agendatime['1'] >= '30') {
3166
                    $halfhour = $halfhour +1;
3167
                }
3168
3169
                //Display events by list
3170
                $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>";
3171
            }
3172
        }
3173
        return $agendaitems;
3174
    }
3175
3176
3177
    /**
3178
     * Show the monthcalender of the given month
3179
     * @param	array	Agendaitems
3180
     * @param	int	Month number
3181
     * @param	int	Year number
3182
     * @param	array	Array of strings containing long week day names (deprecated, you can send an empty array instead)
3183
     * @param	string	The month name
3184
     * @return	void	Direct output
3185
     */
3186
    public static function display_mymonthcalendar($user_id, $agendaitems, $month, $year, $weekdaynames = array(), $monthName, $show_content = true)
3187
    {
3188
        global $DaysShort, $course_path;
3189
        //Handle leap year
3190
        $numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
3191
        if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0))
3192
            $numberofdays[2] = 29;
3193
        //Get the first day of the month
3194
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
3195
        //Start the week on monday
3196
        $startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
3197
        $g_cc = (isset($_GET['courseCode'])?$_GET['courseCode']:'');
3198
3199
        $next_month = ($month == 1 ? 12 : $month -1);
3200
        $prev_month = ($month == 12 ? 1 : $month +1);
3201
3202
        $next_year = ($month == 1 ? $year -1 : $year);
3203
        $prev_year = ($month == 12 ? $year +1 : $year);
3204
3205
        if ($show_content)  {
3206
            $back_url = Display::url(get_lang('Previous'), api_get_self()."?coursePath=".urlencode($course_path)."&courseCode=".Security::remove_XSS($g_cc)."&action=view&view=month&month=".$next_month."&year=".$next_year);
3207
            $next_url = Display::url(get_lang('Next'), api_get_self()."?coursePath=".urlencode($course_path)."&courseCode=".Security::remove_XSS($g_cc)."&action=view&view=month&month=".$prev_month."&year=".$prev_year);
3208
        } else {
3209
            $back_url = Display::url(get_lang('Previous'), '', array('onclick'=>"load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ", 'class' => 'btn ui-button ui-widget ui-state-default'));
3210
            $next_url = Display::url(get_lang('Next'), '', array('onclick'=>"load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ", 'class' => 'pull-right btn ui-button ui-widget ui-state-default'));
3211
        }
3212
        $html = '';
3213
        $html .= '<div class="actions">';
3214
        $html .= '<div class="row">';
3215
        $html .= '<div class="col-md-4">'.$back_url.'</div>';
3216
        $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
3217
        $html .= '<div class="col-md-4">'.$next_url.'</div>';
3218
        $html .= '</div>';
3219
        $html .= '</div>';
3220
        $html .= '<table id="agenda_list2" class="table table-bordered">';
3221
        $html .= '<tr>';
3222
        for ($ii = 1; $ii < 8; $ii ++) {
3223
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
3224
        }
3225
        $html .= '</tr>';
3226
3227
        $curday = -1;
3228
        $today = getdate();
3229
        while ($curday <= $numberofdays[$month]) {
3230
            $html .= "<tr>";
3231
            for ($ii = 0; $ii < 7; $ii ++) {
3232
                if (($curday == -1) && ($ii == $startdayofweek)) {
3233
                    $curday = 1;
3234
                }
3235
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
3236
                    $bgcolor = $class = 'class="days_week"';
3237
                    $dayheader = Display::div($curday, array('class'=>'agenda_day'));
3238
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
3239
                        $class = "class=\"days_today\" style=\"width:10%;\"";
3240
                    }
3241
3242
                    $html .= "<td ".$class.">".$dayheader;
3243
3244
                    if (!empty($agendaitems[$curday])) {
3245
                        $items =  $agendaitems[$curday];
3246
                        $items =  msort($items, 'start_date_tms');
3247
3248
                        foreach($items  as $value) {
3249
                            $value['title'] = Security::remove_XSS($value['title']);
3250
                            $start_time = api_format_date($value['start_date'], TIME_NO_SEC_FORMAT);
3251
                            $end_time = '';
3252
3253
                            if (!empty($value['end_date']) && $value['end_date'] != '0000-00-00 00:00:00') {
3254
                                $end_time    = '-&nbsp;<i>'.api_format_date($value['end_date'], DATE_TIME_FORMAT_LONG).'</i>';
3255
                            }
3256
                            $complete_time = '<i>'.api_format_date($value['start_date'], DATE_TIME_FORMAT_LONG).'</i>&nbsp;'.$end_time;
3257
                            $time = '<i>'.$start_time.'</i>';
3258
3259
                            switch($value['calendar_type']) {
3260
                                case 'personal':
3261
                                    $bg_color = '#D0E7F4';
3262
                                    $icon = Display::return_icon('user.png', get_lang('MyAgenda'), array(), ICON_SIZE_SMALL);
3263
                                    break;
3264
                                case 'global':
3265
                                    $bg_color = '#FFBC89';
3266
                                    $icon = Display::return_icon('view_remove.png', get_lang('GlobalEvent'), array(), ICON_SIZE_SMALL);
3267
                                    break;
3268
                                case 'course':
3269
                                    $bg_color = '#CAFFAA';
3270
                                    $icon_name = 'course.png';
3271
                                    if (!empty($value['session_id'])) {
3272
                                        $icon_name = 'session.png';
3273
                                    }
3274
                                    if ($show_content) {
3275
                                        $icon = Display::url(Display::return_icon($icon_name, $value['course_name'].' '.get_lang('Course'), array(), ICON_SIZE_SMALL), $value['url']);
3276 View Code Duplication
                                    } else {
3277
                                        $icon = Display::return_icon($icon_name, $value['course_name'].' '.get_lang('Course'), array(), ICON_SIZE_SMALL);
3278
                                    }
3279
                                    break;
3280
                                default:
3281
                                    break;
3282
                            }
3283
3284
                            $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
3285
3286
                            if ($show_content) {
3287
3288
                                //Setting a personal event to green
3289
                                $icon = Display::div($icon, array('style'=>'float:right'));
3290
3291
                                $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
3292
3293
                                //Link to bubble
3294
                                $url = Display::url(cut($value['title'], 40), '#', array('id'=>$link, 'class'=>'opener'));
3295
                                $result .= $time.' '.$icon.' '.Display::div($url);
3296
3297
                                //Hidden content
3298
                                $content = Display::div($icon.Display::tag('h2', $value['course_name']).'<hr />'.Display::tag('h3', $value['title']).$complete_time.'<hr />'.Security::remove_XSS($value['content']));
3299
3300
                                //Main div
3301
                                $result .= Display::div($content, array('id'=>'main_'.$link, 'class' => 'dialog', 'style' => 'display:none'));
3302
                                $result .= '</div>';
3303
                                $html .= $result;
3304
                                //echo Display::div($content, array('id'=>'main_'.$value['calendar_type'].'_'.$value['id'], 'class' => 'dialog'));
3305
                            } else {
3306
                                $html .= $result .= $icon.'</div>';
3307
                            }
3308
                        }
3309
                    }
3310
                    $html .= "</td>";
3311
                    $curday ++;
3312
                } else {
3313
                    $html .= "<td></td>";
3314
                }
3315
            }
3316
            $html .= "</tr>";
3317
        }
3318
        $html .= "</table>";
3319
        echo $html;
3320
    }
3321
3322
    /**
3323
     * Get personal agenda items between two dates (=all events from all registered courses)
3324
     * @param	int		user ID of the user
3325
     * @param	string	Optional start date in datetime format (if no start date is given, uses today)
3326
     * @param	string	Optional end date in datetime format (if no date is given, uses one year from now)
3327
     * @return	array	Array of events ordered by start date, in
3328
     * [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
3329
     * where datestart and dateend are in yyyyMMddhhmmss format.
3330
     * @TODO Implement really personal events (from user DB) and global events (from main DB)
3331
     */
3332
    public static function get_personal_agenda_items_between_dates($user_id, $date_start='', $date_end='')
3333
    {
3334
        $items = array ();
3335
        if ($user_id != strval(intval($user_id))) { return $items; }
3336
        if (empty($date_start)) { $date_start = date('Y-m-d H:i:s');}
3337
        if (empty($date_end))   { $date_end = date('Y-m-d H:i:s',mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1));}
3338
        $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
3339
        if(!preg_match($expr,$date_start)) { return $items; }
3340
        if(!preg_match($expr,$date_end)) { return $items; }
3341
3342
        // get agenda-items for every course
3343
        $courses = api_get_user_courses($user_id,false);
3344
        foreach ($courses as $id => $course) {
3345
            $c = api_get_course_info_by_id($course['real_id']);
3346
            //databases of the courses
3347
            $t_a = Database :: get_course_table(TABLE_AGENDA, $course['db']);
3348
            $t_ip = Database :: get_course_table(TABLE_ITEM_PROPERTY, $course['db']);
3349
            // get the groups to which the user belong
3350
            $group_memberships = GroupManager :: get_group_ids($course['db'], $user_id);
3351
            // if the user is administrator of that course we show all the agenda items
3352
            if ($course['status'] == '1') {
3353
                //echo "course admin";
3354
                $sqlquery = "SELECT ".
3355
                    " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3356
                    " FROM ".$t_a." agenda, ".
3357
                    $t_ip." ip ".
3358
                    " WHERE agenda.id = ip.ref ".
3359
                    " AND agenda.start_date>='$date_start' ".
3360
                    " AND agenda.end_date<='$date_end' ".
3361
                    " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3362
                    " AND ip.visibility='1' ".
3363
                    " GROUP BY agenda.id ".
3364
                    " ORDER BY start_date ";
3365
            } else {
3366
                // if the user is not an administrator of that course, then...
3367
                if (is_array($group_memberships) && count($group_memberships)>0)
3368
                {
3369
                    $sqlquery = "SELECT " .
3370
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3371
                        " FROM ".$t_a." agenda, ".
3372
                        $t_ip." ip ".
3373
                        " WHERE agenda.id = ip.ref ".
3374
                        " AND agenda.start_date>='$date_start' ".
3375
                        " AND agenda.end_date<='$date_end' ".
3376
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3377
                        " AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) ) ".
3378
                        " AND ip.visibility='1' ".
3379
                        " ORDER BY start_date ";
3380
                } else {
3381
                    $sqlquery = "SELECT ".
3382
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3383
                        " FROM ".$t_a." agenda, ".
3384
                        $t_ip." ip ".
3385
                        " WHERE agenda.id = ip.ref ".
3386
                        " AND agenda.start_date>='$date_start' ".
3387
                        " AND agenda.end_date<='$date_end' ".
3388
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3389
                        " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
3390
                        " AND ip.visibility='1' ".
3391
                        " ORDER BY start_date ";
3392
                }
3393
            }
3394
3395
            $result = Database::query($sqlquery);
3396
            while ($item = Database::fetch_array($result)) {
3397
                $agendaday = date("j",strtotime($item['start_date']));
3398
                $month = date("n",strtotime($item['start_date']));
3399
                $year = date("Y",strtotime($item['start_date']));
3400
                $URL = api_get_path(WEB_PATH)."main/calendar/agenda.php?cidReq=".urlencode($course["code"])."&day=$agendaday&month=$month&year=$year#$agendaday";
3401
                list($year,$month,$day,$hour,$min,$sec) = split('[-: ]',$item['start_date']);
0 ignored issues
show
Unused Code introduced by
The assignment to $sec is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
3402
                $start_date = $year.$month.$day.$hour.$min;
3403
                list($year,$month,$day,$hour,$min,$sec) = split('[-: ]',$item['end_date']);
0 ignored issues
show
Unused Code introduced by
The assignment to $sec is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
3404
                $end_date = $year.$month.$day.$hour.$min;
3405
3406
                $items[] = array(
3407
                    'datestart'=>$start_date,
3408
                    'dateend'=>$end_date,
3409
                    'title'=>$item['title'],
3410
                    'link'=>$URL,
3411
                    'coursetitle'=>$c['name'],
3412
                );
3413
            }
3414
        }
3415
        return $items;
3416
    }
3417
3418
3419
    /**
3420
     * This function retrieves one personal agenda item returns it.
3421
     * @param	int	The agenda item ID
3422
     * @return 	array	The results of the database query, or null if not found
3423
     */
3424
    public static function get_personal_agenda_item($id)
3425
    {
3426
        $tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
3427
        $id = intval($id);
3428
        // make sure events of the personal agenda can only be seen by the user himself
3429
        $user = api_get_user_id();
3430
        $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE id=".$id." AND user = ".$user;
3431
        $result = Database::query($sql);
3432
        if(Database::num_rows($result)==1) {
3433
            $item = Database::fetch_array($result);
3434
        } else {
3435
            $item = null;
3436
        }
3437
        return $item;
3438
    }
3439
3440
3441
    /**
3442
     * This function calculates the startdate of the week (monday)
3443
     * and the enddate of the week (sunday)
3444
     * and returns it as an array
3445
     */
3446
    public static function calculate_start_end_of_week($week_number, $year)
3447
    {
3448
        // determine the start and end date
3449
        // step 1: we calculate a timestamp for a day in this week
3450
        $random_day_in_week = mktime(0, 0, 0, 1, 1, $year) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
3451
        // step 2: we which day this is (0=sunday, 1=monday, ...)
3452
        $number_day_in_week = date('w', $random_day_in_week);
3453
        // step 3: we calculate the timestamp of the monday of the week we are in
3454
        $start_timestamp = $random_day_in_week - (($number_day_in_week -1) * 24 * 60 * 60);
3455
        // step 4: we calculate the timestamp of the sunday of the week we are in
3456
        $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week +1) * 24 * 60 * 60) - 3600;
3457
        // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
3458
        $start_day = date('j', $start_timestamp);
3459
        $start_month = date('n', $start_timestamp);
3460
        $start_year = date('Y', $start_timestamp);
3461
        $end_day = date('j', $end_timestamp);
3462
        $end_month = date('n', $end_timestamp);
3463
        $end_year = date('Y', $end_timestamp);
3464
        $start_end_array['start']['day'] = $start_day;
3465
        $start_end_array['start']['month'] = $start_month;
3466
        $start_end_array['start']['year'] = $start_year;
3467
        $start_end_array['end']['day'] = $end_day;
3468
        $start_end_array['end']['month'] = $end_month;
3469
        $start_end_array['end']['year'] = $end_year;
3470
        return $start_end_array;
3471
    }
3472
3473
    /**
3474
     * @return bool
3475
     */
3476
    public function getIsAllowedToEdit()
3477
    {
3478
        return $this->isAllowedToEdit;
3479
    }
3480
3481
    /**
3482
     * @param bool $isAllowedToEdit
3483
     */
3484
    public function setIsAllowedToEdit($isAllowedToEdit)
3485
    {
3486
        $this->isAllowedToEdit = $isAllowedToEdit;
3487
    }
3488
}
3489