Passed
Push — 1.10.x ( 70be1b...a0d9ce )
by
unknown
44:24
created

Agenda::resizeEvent()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 25

Duplication

Lines 18
Ratio 58.06 %
Metric Value
dl 18
loc 31
rs 8.439
cc 5
eloc 25
nc 5
nop 3
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
     * @param int $senderId
55
     */
56
    public function setSenderId($senderId)
57
    {
58
        $this->senderId = intval($senderId);
59
    }
60
61
    /**
62
     * @return int
63
     */
64
    public function getSenderId()
65
    {
66
        return $this->senderId;
67
    }
68
69
    /**
70
     * @param string $type can be 'personal', 'admin'  or  'course'
71
     */
72
    public function setType($type)
73
    {
74
        $typeList = $this->getTypes();
75
76
        if (in_array($type, $typeList)) {
77
            $this->type = $type;
78
        }
79
    }
80
81
    /**
82
     * @param int $id
83
     */
84
    public function setSessionId($id)
85
    {
86
        $this->sessionId = intval($id);
87
    }
88
89
    /**
90
     * @return int $id
91
     */
92
    public function getSessionId()
93
    {
94
        return $this->sessionId;
95
    }
96
97
    /**
98
     * @param array $courseInfo
99
     */
100
    public function set_course($courseInfo)
101
    {
102
        $this->course = $courseInfo;
103
    }
104
105
    /**
106
     * @return array
107
     */
108
    public function getTypes()
109
    {
110
        return $this->types;
111
    }
112
113
    /**
114
     * Adds an event to the calendar
115
     * @param string  $start datetime format: 2012-06-14 09:00:00
116
     * @param string  $end datetime format: 2012-06-14 09:00:00
117
     * @param string  $allDay (true, false)
118
     * @param string  $title
119
     * @param string  $content
120
     * @param array   $usersToSend array('everyone') or a list of user/group ids
121
     * @param bool    $addAsAnnouncement event as a *course* announcement
122
     * @param int $parentEventId
123
     * @param array $attachmentArray $_FILES['']
124
     * @param string $attachmentComment
125
     * @param string $eventComment
126
     * @param string $color
127
     *
128
     * @return int
129
     */
130
    public function addEvent(
131
        $start,
132
        $end,
133
        $allDay,
134
        $title,
135
        $content,
136
        $usersToSend = array(),
137
        $addAsAnnouncement = false,
138
        $parentEventId = null,
139
        $attachmentArray = array(),
140
        $attachmentComment = '',
141
        $eventComment = '',
142
        $color = ''
143
    ) {
144
        $start = api_get_utc_datetime($start);
145
        $end = api_get_utc_datetime($end);
146
        $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
147
        $id = null;
148
        $content = Security::remove_XSS($content);
149
        $eventComment = nl2br($eventComment);
150
151
        switch ($this->type) {
152
            case 'personal':
153
                $attributes = array(
154
                    'user' => api_get_user_id(),
155
                    'title' => $title,
156
                    'text' => $content,
157
                    'date' => $start,
158
                    'enddate' => $end,
159
                    'all_day' => $allDay,
160
                    'color' => $color
161
                );
162
163
                $id = Database::insert(
164
                    $this->tbl_personal_agenda,
165
                    $attributes
166
                );
167
                break;
168
            case 'course':
169
                $attributes = array(
170
                    'title' => $title,
171
                    'content' => $content,
172
                    'start_date' => $start,
173
                    'end_date' => $end,
174
                    'all_day' => $allDay,
175
                    'session_id' => $this->getSessionId(),
176
                    'c_id' => $this->course['real_id'],
177
                    'comment' => $eventComment,
178
                    'color' => $color
179
                );
180
181
                if (!empty($parentEventId)) {
182
                    $attributes['parent_event_id'] = $parentEventId;
183
                }
184
185
                $senderId = $this->getSenderId();
186
                $sessionId = $this->getSessionId();
187
188
                // Simple course event.
189
                $id = Database::insert($this->tbl_course_agenda, $attributes);
190
191
                if ($id) {
192
                    $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
193
                    Database::query($sql);
194
195
                    $groupId = api_get_group_id();
196
197
                    if (!empty($usersToSend)) {
198
                        $sendTo = $this->parseSendToArray($usersToSend);
199
200
                        if ($sendTo['everyone']) {
201
                            api_item_property_update(
202
                                $this->course,
203
                                TOOL_CALENDAR_EVENT,
204
                                $id,
205
                                "AgendaAdded",
206
                                $senderId,
207
                                $groupId,
208
                                '',
209
                                $start,
210
                                $end,
211
                                $sessionId
212
                            );
213
                            api_item_property_update(
214
                                $this->course,
215
                                TOOL_CALENDAR_EVENT,
216
                                $id,
217
                                "visible",
218
                                $senderId,
219
                                $groupId,
220
                                '',
221
                                $start,
222
                                $end,
223
                                $sessionId
224
                            );
225
                        } else {
226
                            // Storing the selected groups
227 View Code Duplication
                            if (!empty($sendTo['groups'])) {
228
                                foreach ($sendTo['groups'] as $group) {
229
                                    api_item_property_update(
230
                                        $this->course,
231
                                        TOOL_CALENDAR_EVENT,
232
                                        $id,
233
                                        "AgendaAdded",
234
                                        $senderId,
235
                                        $group,
236
                                        0,
237
                                        $start,
238
                                        $end,
239
                                        $sessionId
240
                                    );
241
242
                                    api_item_property_update(
243
                                        $this->course,
244
                                        TOOL_CALENDAR_EVENT,
245
                                        $id,
246
                                        "visible",
247
                                        $senderId,
248
                                        $group,
249
                                        0,
250
                                        $start,
251
                                        $end,
252
                                        $sessionId
253
                                    );
254
                                }
255
                            }
256
257
                            // storing the selected users
258 View Code Duplication
                            if (!empty($sendTo['users'])) {
259
                                foreach ($sendTo['users'] as $userId) {
260
                                    api_item_property_update(
261
                                        $this->course,
262
                                        TOOL_CALENDAR_EVENT,
263
                                        $id,
264
                                        "AgendaAdded",
265
                                        $senderId,
266
                                        $groupId,
267
                                        $userId,
268
                                        $start,
269
                                        $end,
270
                                        $sessionId
271
                                    );
272
273
                                    api_item_property_update(
274
                                        $this->course,
275
                                        TOOL_CALENDAR_EVENT,
276
                                        $id,
277
                                        "visible",
278
                                        $senderId,
279
                                        $groupId,
280
                                        $userId,
281
                                        $start,
282
                                        $end,
283
                                        $sessionId
284
                                    );
285
                                }
286
                            }
287
                        }
288
                    }
289
290
                    // Add announcement.
291
                    if ($addAsAnnouncement) {
292
                        $this->storeAgendaEventAsAnnouncement($id, $usersToSend);
293
                    }
294
295
                    // Add attachment.
296
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
297
                        $this->addAttachment(
298
                            $id,
299
                            $attachmentArray,
300
                            $attachmentComment,
301
                            $this->course
302
                        );
303
                    }
304
                }
305
                break;
306 View Code Duplication
            case 'admin':
307
                if (api_is_platform_admin()) {
308
                    $attributes = array(
309
                        'title' => $title,
310
                        'content' => $content,
311
                        'start_date' => $start,
312
                        'end_date' => $end,
313
                        'all_day' => $allDay,
314
                        'access_url_id' => api_get_current_access_url_id()
315
                    );
316
317
                    $id = Database::insert($this->tbl_global_agenda, $attributes);
318
                }
319
                break;
320
        }
321
322
        return $id;
323
    }
324
325
    /**
326
     * @param int $eventId
327
     * @param int $courseId
328
     *
329
     * @return array
330
     */
331
    public function getRepeatedInfoByEvent($eventId, $courseId)
332
    {
333
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
334
        $eventId = intval($eventId);
335
        $courseId = intval($courseId);
336
        $sql = "SELECT * FROM $repeatTable
337
                WHERE c_id = $courseId AND cal_id = $eventId";
338
        $res = Database::query($sql);
339
        $repeatInfo = array();
340
        if (Database::num_rows($res) > 0) {
341
            $repeatInfo = Database::fetch_array($res, 'ASSOC');
342
        }
343
344
        return $repeatInfo;
345
    }
346
347
    /**
348
     * @param int $eventId
349
     * @param string $type
350
     * @param string $end in local time
351
     * @param array $sentTo
352
     *
353
     * @return bool
354
     */
355
    public function addRepeatedItem($eventId, $type, $end, $sentTo = array())
356
    {
357
        $t_agenda = Database::get_course_table(TABLE_AGENDA);
358
        $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
359
360
        if (empty($this->course)) {
361
            return false;
362
        }
363
364
        $course_id = $this->course['real_id'];
365
        $eventId = intval($eventId);
366
367
        $sql = "SELECT title, content, start_date, end_date, all_day
368
                FROM $t_agenda
369
                WHERE c_id = $course_id AND id = $eventId";
370
        $res = Database::query($sql);
371
372
        if (Database::num_rows($res) !== 1) {
373
            return false;
374
        }
375
376
        $row = Database::fetch_array($res);
377
        $origStartDate = api_strtotime($row['start_date'], 'UTC');
378
        $origEndDate = api_strtotime($row['end_date'], 'UTC');
379
        $diff = $origEndDate - $origStartDate;
380
381
        $title = $row['title'];
382
        $content = $row['content'];
383
        $allDay = $row['all_day'];
384
385
        $now = time();
386
        $type = Database::escape_string($type);
387
        $end = api_strtotime($end);
388
389
        if (1 <= $end && $end <= 500) {
390
            // We assume that, with this type of value, the user actually gives a count of repetitions
391
            //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
392
            switch ($type) {
393
                case 'daily':
394
                    $end = $origStartDate + (86400 * $end);
395
                    break;
396
                case 'weekly':
397
                    $end = $this->addWeek($origStartDate, $end);
398
                    break;
399
                case 'monthlyByDate':
400
                    $end = $this->addMonth($origStartDate, $end);
401
                    break;
402
                case 'monthlyByDay':
403
                    //TODO
404
                    break;
405
                case 'monthlyByDayR':
406
                    //TODO
407
                    break;
408
                case 'yearly':
409
                    $end = $this->addYear($origStartDate, $end);
410
                    break;
411
            }
412
        }
413
414
        $typeList = array('daily', 'weekly', 'monthlyByDate', 'monthlyByDay', 'monthlyByDayR', 'yearly');
415
416
        // The event has to repeat *in the future*. We don't allow repeated
417
        // events in the past
418
        if ($end > $now && in_array($type, $typeList)) {
419
            $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
420
                    VALUES ($course_id, '$eventId', '$type', '$end')";
421
            Database::query($sql);
422
423
            switch ($type) {
424
                // @todo improve loop.
425 View Code Duplication
                case 'daily':
426
                    for ($i = $origStartDate + 86400; $i <= $end; $i += 86400) {
427
                        $start = date('Y-m-d H:i:s', $i);
428
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
429
                        $this->addEvent(
430
                            $start,
431
                            $repeatEnd,
432
                            $allDay,
433
                            $title,
434
                            $content,
435
                            $sentTo,
436
                            false,
437
                            $eventId
438
                        );
439
                    }
440
                    break;
441 View Code Duplication
                case 'weekly':
442
                    for ($i = $origStartDate + 604800; $i <= $end; $i += 604800) {
443
                        $start = date('Y-m-d H:i:s', $i);
444
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
445
                        $this->addEvent(
446
                            $start,
447
                            $repeatEnd,
448
                            $allDay,
449
                            $title,
450
                            $content,
451
                            $sentTo,
452
                            false,
453
                            $eventId
454
                        );
455
                    }
456
                    break;
457 View Code Duplication
                case 'monthlyByDate':
458
                    $next_start = $this->addMonth($origStartDate);
459
                    while ($next_start <= $end) {
460
                        $start = date('Y-m-d H:i:s', $next_start);
461
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
462
                        $this->addEvent(
463
                            $start,
464
                            $repeatEnd,
465
                            $allDay,
466
                            $title,
467
                            $content,
468
                            $sentTo,
469
                            false,
470
                            $eventId
471
                        );
472
                        $next_start = $this->addMonth($next_start);
473
                    }
474
                    break;
475
                case 'monthlyByDay':
476
                    //not yet implemented
477
                    break;
478
                case 'monthlyByDayR':
479
                    //not yet implemented
480
                    break;
481 View Code Duplication
                case 'yearly':
482
                    $next_start = $this->addYear($origStartDate);
483
                    while ($next_start <= $end) {
484
                        $start = date('Y-m-d H:i:s', $next_start);
485
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
486
                        $this->addEvent(
487
                            $start,
488
                            $repeatEnd,
489
                            $allDay,
490
                            $title,
491
                            $content,
492
                            $sentTo,
493
                            false,
494
                            $eventId
495
                        );
496
                        $next_start = $this->addYear($next_start);
497
                    }
498
                    break;
499
            }
500
        }
501
502
        return true;
503
    }
504
505
    /**
506
     * @param int $item_id
507
     * @param array $sentTo
508
     * @return int
509
     */
510
    public function storeAgendaEventAsAnnouncement($item_id, $sentTo = array())
511
    {
512
        $table_agenda = Database::get_course_table(TABLE_AGENDA);
513
        $course_id = api_get_course_int_id();
514
515
        // Check params
516
        if (empty($item_id) or $item_id != strval(intval($item_id))) {
517
            return -1;
518
        }
519
520
        // Get the agenda item.
521
        $item_id = intval($item_id);
522
        $sql = "SELECT * FROM $table_agenda
523
                WHERE c_id = $course_id AND id = ".$item_id;
524
        $res = Database::query($sql);
525
526
        if (Database::num_rows($res) > 0) {
527
            $row = Database::fetch_array($res, 'ASSOC');
528
            // Sending announcement
529
            if (!empty($sentTo)) {
530
                $id = AnnouncementManager::add_announcement(
531
                    $row['title'],
532
                    $row['content'],
533
                    $sentTo,
534
                    null,
535
                    null,
536
                    $row['end_date']
537
                );
538
                AnnouncementManager::send_email($id);
539
540
                return $id;
541
            }
542
        }
543
544
        return -1;
545
    }
546
547
    /**
548
     * Edits an event
549
     *
550
     * @param int $id
551
     * @param string $start datetime format: 2012-06-14 09:00:00
552
     * @param string $end datetime format: 2012-06-14 09:00:00
553
     * @param int $allDay is all day 'true' or 'false'
554
     * @param string $title
555
     * @param string $content
556
     * @param array $usersToSend
557
     * @param array $attachmentArray
558
     * @param string $attachmentComment
559
     * @param string $comment
560
     * @param string $color
561
     * @param bool $addAnnouncement
562
     *
563
     * @return bool
564
     */
565
    public function editEvent(
566
        $id,
567
        $start,
568
        $end,
569
        $allDay,
570
        $title,
571
        $content,
572
        $usersToSend = array(),
573
        $attachmentArray = array(),
574
        $attachmentComment = '',
575
        $comment = '',
576
        $color = '',
577
        $addAnnouncement = false
578
    ) {
579
        $start = api_get_utc_datetime($start);
580
        $end = api_get_utc_datetime($end);
581
        $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
582
        $content = nl2br($content);
583
        $comment = nl2br($comment);
584
585
        switch ($this->type) {
586
            case 'personal':
587
                $eventInfo = $this->get_event($id);
588
                if ($eventInfo['user'] != api_get_user_id()) {
589
                    break;
590
                }
591
                $attributes = array(
592
                    'title' => $title,
593
                    'text' => $content,
594
                    'date' => $start,
595
                    'enddate' => $end,
596
                    'all_day' => $allDay,
597
                    'color' => $color
598
                );
599
                Database::update(
600
                    $this->tbl_personal_agenda,
601
                    $attributes,
602
                    array('id = ?' => $id)
603
                );
604
                break;
605
            case 'course':
606
                $eventInfo = $this->get_event($id);
607
608
                if (empty($eventInfo)) {
609
                    return false;
610
                }
611
612
                $groupId = api_get_group_id();
613
                $course_id = $this->course['real_id'];
614
615
                if (empty($course_id)) {
616
                    return false;
617
                }
618
619
                if ($this->getIsAllowedToEdit()) {
620
621
                    $attributes = array(
622
                        'title' => $title,
623
                        'content' => $content,
624
                        'start_date' => $start,
625
                        'end_date' => $end,
626
                        'all_day' => $allDay,
627
                        'comment' => $comment,
628
                        'color' => $color
629
                    );
630
631
                    Database::update(
632
                        $this->tbl_course_agenda,
633
                        $attributes,
634
                        array(
635
                            'id = ? AND c_id = ? AND session_id = ? ' => array(
636
                                $id,
637
                                $course_id,
638
                                $this->sessionId
639
                            )
640
                        )
641
                    );
642
643
                    if (!empty($usersToSend)) {
644
                        $sendTo = $this->parseSendToArray($usersToSend);
645
646
                        $usersToDelete = array_diff($eventInfo['send_to']['users'], $sendTo['users']);
647
                        $usersToAdd = array_diff($sendTo['users'], $eventInfo['send_to']['users']);
648
649
                        $groupsToDelete = array_diff($eventInfo['send_to']['groups'], $sendTo['groups']);
650
                        $groupToAdd = array_diff($sendTo['groups'], $eventInfo['send_to']['groups']);
651
652
                        if ($sendTo['everyone']) {
653
654
                            // Delete all from group
655 View Code Duplication
                            if (isset($eventInfo['send_to']['groups']) &&
656
                                !empty($eventInfo['send_to']['groups'])
657
                            ) {
658
                                foreach ($eventInfo['send_to']['groups'] as $group) {
659
                                    api_item_property_delete(
660
                                        $this->course,
661
                                        TOOL_CALENDAR_EVENT,
662
                                        $id,
663
                                        0,
664
                                        $group,
665
                                        $this->sessionId
666
                                    );
667
                                }
668
                            }
669
670
                            // Storing the selected users.
671 View Code Duplication
                            if (isset($eventInfo['send_to']['users']) &&
672
                                !empty($eventInfo['send_to']['users'])
673
                            ) {
674
                                foreach ($eventInfo['send_to']['users'] as $userId) {
675
                                    api_item_property_delete(
676
                                        $this->course,
677
                                        TOOL_CALENDAR_EVENT,
678
                                        $id,
679
                                        $userId,
680
                                        $groupId,
681
                                        $this->sessionId
682
                                    );
683
                                }
684
                            }
685
686
                            // Add to everyone only.
687
                            api_item_property_update(
688
                                $this->course,
689
                                TOOL_CALENDAR_EVENT,
690
                                $id,
691
                                "visible",
692
                                api_get_user_id(),
693
                                $groupId,
694
                                null,
695
                                $start,
696
                                $end,
697
                                $this->sessionId
698
                            );
699
                        } else {
700
701
                            // Delete "everyone".
702
                            api_item_property_delete(
703
                                $this->course,
704
                                TOOL_CALENDAR_EVENT,
705
                                $id,
706
                                0,
707
                                0,
708
                                $this->sessionId
709
                            );
710
711
                            // Add groups
712 View Code Duplication
                            if (!empty($groupToAdd)) {
713
                                foreach ($groupToAdd as $group) {
714
                                    api_item_property_update(
715
                                        $this->course,
716
                                        TOOL_CALENDAR_EVENT,
717
                                        $id,
718
                                        "visible",
719
                                        api_get_user_id(),
720
                                        $group,
721
                                        0,
722
                                        $start,
723
                                        $end,
724
                                        $this->sessionId
725
                                    );
726
                                }
727
                            }
728
729
                            // Delete groups.
730 View Code Duplication
                            if (!empty($groupsToDelete)) {
731
                                foreach ($groupsToDelete as $group) {
732
                                    api_item_property_delete(
733
                                        $this->course,
734
                                        TOOL_CALENDAR_EVENT,
735
                                        $id,
736
                                        0,
737
                                        $group,
738
                                        $this->sessionId
739
                                    );
740
                                }
741
                            }
742
743
                            // Add users.
744 View Code Duplication
                            if (!empty($usersToAdd)) {
745
                                foreach ($usersToAdd as $userId) {
746
                                    api_item_property_update(
747
                                        $this->course,
748
                                        TOOL_CALENDAR_EVENT,
749
                                        $id,
750
                                        "visible",
751
                                        api_get_user_id(),
752
                                        $groupId,
753
                                        $userId,
754
                                        $start,
755
                                        $end,
756
                                        $this->sessionId
757
                                    );
758
                                }
759
                            }
760
761
                            // Delete users.
762 View Code Duplication
                            if (!empty($usersToDelete)) {
763
                                foreach ($usersToDelete as $userId) {
764
                                    api_item_property_delete(
765
                                        $this->course,
766
                                        TOOL_CALENDAR_EVENT,
767
                                        $id,
768
                                        $userId,
769
                                        $groupId,
770
                                        $this->sessionId
771
                                    );
772
                                }
773
                            }
774
                        }
775
                    }
776
777
                    // Add announcement.
778
                    if (isset($addAnnouncement) && !empty($addAnnouncement)) {
779
                        $this->storeAgendaEventAsAnnouncement($id, $usersToSend);
780
                    }
781
782
                    // Add attachment.
783
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
784
                        $this->updateAttachment(
785
                            $id,
786
                            $attachmentArray,
787
                            $attachmentComment,
788
                            $this->course
789
                        );
790
                    }
791
                }
792
                break;
793
            case 'admin':
794 View Code Duplication
            case 'platform':
795
                if (api_is_platform_admin()) {
796
                    $attributes = array(
797
                        'title' => $title,
798
                        'content' => $content,
799
                        'start_date' => $start,
800
                        'end_date' => $end,
801
                        'all_day' => $allDay
802
                    );
803
                    Database::update(
804
                        $this->tbl_global_agenda,
805
                        $attributes,
806
                        array('id = ?' => $id)
807
                    );
808
                }
809
                break;
810
        }
811
    }
812
813
    /**
814
     * @param int $id
815
     * @param bool $deleteAllItemsFromSerie
816
     */
817
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
818
    {
819
        switch ($this->type) {
820
            case 'personal':
821
                $eventInfo = $this->get_event($id);
822
                if ($eventInfo['user'] == api_get_user_id()) {
823
                    Database::delete(
824
                        $this->tbl_personal_agenda,
825
                        array('id = ?' => $id)
826
                    );
827
                }
828
                break;
829
            case 'course':
830
                $course_id = api_get_course_int_id();
831
                if (!empty($course_id) && api_is_allowed_to_edit(null, true)) {
832
                    // Delete
833
                    if ($deleteAllItemsFromSerie) {
834
                        $eventInfo = $this->get_event($id);
835
                        /* This is one of the children.
836
                           Getting siblings and delete 'Em all + the father! */
837
                        if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
838
                            // Removing items.
839
                            $events = $this->getAllRepeatEvents($eventInfo['parent_event_id']);
840
                            if (!empty($events)) {
841
                                foreach ($events as $event) {
842
                                    $this->deleteEvent($event['id']);
843
                                }
844
                            }
845
                            // Removing parent.
846
                            $this->deleteEvent($eventInfo['parent_event_id']);
847
                        } else {
848
                            // This is the father looking for the children.
849
                            $events = $this->getAllRepeatEvents($id);
850
                            if (!empty($events)) {
851
                                foreach ($events as $event) {
852
                                    $this->deleteEvent($event['id']);
853
                                }
854
                            }
855
                        }
856
                    }
857
858
                    // Removing from events.
859
                    Database::delete(
860
                        $this->tbl_course_agenda,
861
                        array('id = ? AND c_id = ?' => array($id, $course_id))
862
                    );
863
864
                    api_item_property_update(
865
                        $this->course,
866
                        TOOL_CALENDAR_EVENT,
867
                        $id,
868
                        'delete',
869
                        api_get_user_id()
870
                    );
871
872
                    // Removing from series.
873
                    Database::delete(
874
                        $this->table_repeat,
875
                        array('cal_id = ? AND c_id = ?' => array($id, $course_id))
876
                    );
877
                }
878
                break;
879
            case 'admin':
880
                if (api_is_platform_admin()) {
881
                    Database::delete(
882
                        $this->tbl_global_agenda,
883
                        array('id = ?' => $id)
884
                    );
885
                }
886
                break;
887
        }
888
    }
889
890
    /**
891
     * Get agenda events
892
     * @param int $start
893
     * @param int $end
894
     * @param int $course_id
895
     * @param int $groupId
896
     * @param int $user_id
897
     * @param string $format
898
     *
899
     * @return array|string
900
     */
901
    public function getEvents(
902
        $start,
903
        $end,
904
        $course_id = null,
905
        $groupId = null,
906
        $user_id = 0,
907
        $format = 'json'
908
    ) {
909
        switch ($this->type) {
910
            case 'admin':
911
                $this->getPlatformEvents($start, $end);
912
                break;
913
            case 'course':
914
                $session_id = $this->sessionId;
915
                $courseInfo = api_get_course_info_by_id($course_id);
916
917
                // Session coach can see all events inside a session.
918
                if (api_is_coach()) {
919
920
                    // Own course
921
                    $this->getCourseEvents(
922
                        $start,
923
                        $end,
924
                        $courseInfo,
925
                        $groupId,
926
                        $session_id,
927
                        $user_id
928
                    );
929
930
                    // Others
931
                    $this->getSessionEvents(
932
                        $start,
933
                        $end,
934
                        api_get_session_id(),
935
                        $user_id,
936
                        $this->eventOtherSessionColor
937
                    );
938
                } else {
939
                    $this->getCourseEvents(
940
                        $start,
941
                        $end,
942
                        $courseInfo,
943
                        $groupId,
944
                        $session_id,
945
                        $user_id
946
                    );
947
                }
948
                break;
949
            case 'personal':
950
            default:
951
                $sessionFilterActive = false;
952
953
                if (!empty($this->sessionId)) {
954
                    $sessionFilterActive = true;
955
                }
956
957
                if ($sessionFilterActive == false) {
958
                    // Getting personal events
959
                    $this->getPersonalEvents($start, $end);
960
961
                    // Getting platform/admin events
962
                    $this->getPlatformEvents($start, $end);
963
                }
964
965
                // Getting course events
966
                $my_course_list = array();
967
968
                if (!api_is_anonymous()) {
969
                    $session_list = SessionManager::get_sessions_by_user(
970
                        api_get_user_id()
971
                    );
972
                    $my_course_list = CourseManager::get_courses_list_by_user_id(
973
                        api_get_user_id(),
974
                        false
975
                    );
976
                }
977
978
                if (api_is_drh()) {
979
                    if (api_drh_can_access_all_session_content()) {
980
                        $session_list = array();
981
                        $sessionList = SessionManager::get_sessions_followed_by_drh(
982
                            api_get_user_id(),
983
                            null,
984
                            null,
985
                            null,
986
                            true,
987
                            false
988
                        );
989
990
                        if (!empty($sessionList)) {
991
                            foreach ($sessionList as $sessionItem) {
992
                                $sessionId = $sessionItem['id'];
993
                                $courses = SessionManager::get_course_list_by_session_id(
994
                                    $sessionId
995
                                );
996
                                $sessionInfo = array(
997
                                    'session_id' => $sessionId,
998
                                    'courses' => $courses
999
                                );
1000
                                $session_list[] = $sessionInfo;
1001
                            }
1002
                        }
1003
                    }
1004
                }
1005
1006
                if (!empty($session_list)) {
1007
                    foreach ($session_list as $session_item) {
1008
                        if ($sessionFilterActive) {
1009
                            if ($this->sessionId != $session_item['session_id']) {
1010
                                continue;
1011
                            }
1012
                        }
1013
1014
                        $my_courses = $session_item['courses'];
1015
                        $my_session_id = $session_item['session_id'];
1016
1017
                        if (!empty($my_courses)) {
1018
                            foreach ($my_courses as $course_item) {
1019
                                $courseInfo = api_get_course_info_by_id($course_item['real_id']);
1020
                                $this->getCourseEvents(
1021
                                    $start,
1022
                                    $end,
1023
                                    $courseInfo,
1024
                                    0,
1025
                                    $my_session_id
1026
                                );
1027
                            }
1028
                        }
1029
1030
                        $this->getSessionEvents(
1031
                            $start,
1032
                            $end,
1033
                            $my_session_id,
1034
                            $user_id,
1035
                            $this->eventOtherSessionColor
1036
                        );
1037
                    }
1038
                }
1039
1040
                if (!empty($my_course_list) && $sessionFilterActive == false) {
1041
                    foreach ($my_course_list as $courseInfoItem) {
1042
                        $courseInfo = api_get_course_info_by_id($courseInfoItem['real_id']);
1043
                        if (isset($course_id) && !empty($course_id)) {
1044
                            if ($courseInfo['real_id'] == $course_id) {
1045
                                $this->getCourseEvents($start, $end, $courseInfo);
1046
                            }
1047
                        } else {
1048
                            $this->getCourseEvents(
1049
                                $start,
1050
                                $end,
1051
                                $courseInfo
1052
                            );
1053
                        }
1054
                    }
1055
                }
1056
1057
                break;
1058
        }
1059
1060
        if (!empty($this->events)) {
1061
            switch ($format) {
1062
                case 'json':
1063
                    return json_encode($this->events);
1064
                    break;
1065
                case 'array':
1066
                    return $this->events;
1067
                    break;
1068
            }
1069
1070
        }
1071
        return '';
1072
    }
1073
1074
    /**
1075
     * @param int $id
1076
     * @param int $day_delta
1077
     * @param int $minute_delta
1078
     * @return int
1079
     */
1080
    public function resizeEvent($id, $day_delta, $minute_delta)
1081
    {
1082
        // we convert the hour delta into minutes and add the minute delta
1083
        $delta = ($day_delta * 60 * 24) + $minute_delta;
1084
        $delta = intval($delta);
1085
1086
        $event = $this->get_event($id);
1087
        if (!empty($event)) {
1088
            switch ($this->type) {
1089 View Code Duplication
                case 'personal':
1090
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1091
                            all_day = 0, enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1092
							WHERE id=".intval($id);
1093
                    Database::query($sql);
1094
                    break;
1095 View Code Duplication
                case 'course':
1096
                    $sql = "UPDATE $this->tbl_course_agenda SET
1097
                            all_day = 0,  end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1098
							WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
1099
                    Database::query($sql);
1100
                    break;
1101 View Code Duplication
                case 'admin':
1102
                    $sql = "UPDATE $this->tbl_global_agenda SET
1103
                            all_day = 0, end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1104
							WHERE id=".intval($id);
1105
                    Database::query($sql);
1106
                    break;
1107
            }
1108
        }
1109
        return 1;
1110
    }
1111
1112
    /**
1113
     * @param $id
1114
     * @param $day_delta
1115
     * @param $minute_delta
1116
     * @return int
1117
     */
1118
    public function move_event($id, $day_delta, $minute_delta)
1119
    {
1120
        // we convert the hour delta into minutes and add the minute delta
1121
        $delta = ($day_delta * 60 * 24) + $minute_delta;
1122
        $delta = intval($delta);
1123
1124
        $event = $this->get_event($id);
1125
1126
        $allDay = 0;
1127
        if ($day_delta == 0 && $minute_delta == 0) {
1128
            $allDay = 1;
1129
        }
1130
1131
        if (!empty($event)) {
1132
            switch ($this->type) {
1133 View Code Duplication
                case 'personal':
1134
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1135
                            all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
1136
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1137
							WHERE id=".intval($id);
1138
                    Database::query($sql);
1139
                    break;
1140 View Code Duplication
                case 'course':
1141
                    $sql = "UPDATE $this->tbl_course_agenda SET
1142
                            all_day = $allDay, start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1143
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1144
							WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
1145
                    Database::query($sql);
1146
                    break;
1147 View Code Duplication
                case 'admin':
1148
                    $sql = "UPDATE $this->tbl_global_agenda SET
1149
                            all_day = $allDay,
1150
                            start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1151
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1152
							WHERE id=".intval($id);
1153
                    Database::query($sql);
1154
                    break;
1155
            }
1156
        }
1157
        return 1;
1158
    }
1159
1160
    /**
1161
     * Gets a single event
1162
     *
1163
     * @param int event id
1164
     * @return array
1165
     */
1166
    public function get_event($id)
1167
    {
1168
        // make sure events of the personal agenda can only be seen by the user himself
1169
        $id = intval($id);
1170
        $event = null;
1171
        switch ($this->type) {
1172
            case 'personal':
1173
                $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1174
                        WHERE id = $id AND user = ".api_get_user_id();
1175
                $result = Database::query($sql);
1176
                if (Database::num_rows($result)) {
1177
                    $event = Database::fetch_array($result, 'ASSOC');
1178
                    $event['description'] = $event['text'];
1179
                    $event['content'] = $event['text'];
1180
                    $event['start_date'] = $event['date'];
1181
                    $event['end_date'] = $event['enddate'];
1182
                }
1183
                break;
1184
            case 'course':
1185
                if (!empty($this->course['real_id'])) {
1186
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
1187
                            WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
1188
                    $result = Database::query($sql);
1189
                    if (Database::num_rows($result)) {
1190
                        $event = Database::fetch_array($result, 'ASSOC');
1191
                        $event['description'] = $event['content'];
1192
1193
                        // Getting send to array
1194
                        $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
1195
                            $id,
1196
                            $this->course['real_id'],
1197
                            $this->sessionId
1198
                        );
1199
1200
                        // Getting repeat info
1201
                        $event['repeat_info'] = $this->getRepeatedInfoByEvent(
1202
                            $id,
1203
                            $this->course['real_id']
1204
                        );
1205
1206
                        if (!empty($event['parent_event_id'])) {
1207
                            $event['parent_info'] = $this->get_event($event['parent_event_id']);
1208
                        }
1209
1210
                        $event['attachment'] = $this->getAttachment($id, $this->course);
1211
                    }
1212
                }
1213
                break;
1214
            case 'admin':
1215
            case 'platform':
1216
                $sql = "SELECT * FROM ".$this->tbl_global_agenda."
1217
                        WHERE id = $id";
1218
                $result = Database::query($sql);
1219
                if (Database::num_rows($result)) {
1220
                    $event = Database::fetch_array($result, 'ASSOC');
1221
                    $event['description'] = $event['content'];
1222
                }
1223
                break;
1224
        }
1225
        return $event;
1226
    }
1227
1228
    /**
1229
     * Gets personal events
1230
     * @param int $start
1231
     * @param int $end
1232
     * @return array
1233
     */
1234
    public function getPersonalEvents($start, $end)
1235
    {
1236
        $start = intval($start);
1237
        $end = intval($end);
1238
        $startCondition = '';
1239
        $endCondition = '';
1240
1241
        if ($start !== 0) {
1242
            $start = api_get_utc_datetime($start);
1243
            $startCondition = "AND date >= '".$start."'";
1244
        }
1245
        if ($start !== 0) {
1246
            $end = api_get_utc_datetime($end);
1247
            $endCondition = "AND (enddate <= '".$end."' OR enddate IS NULL)";
1248
        }
1249
        $user_id = api_get_user_id();
1250
1251
        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1252
                WHERE user = $user_id $startCondition $endCondition";
1253
1254
        $result = Database::query($sql);
1255
        $my_events = array();
1256
        if (Database::num_rows($result)) {
1257
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1258
                $event = array();
1259
                $event['id'] = 'personal_'.$row['id'];
1260
                $event['title'] = $row['title'];
1261
                $event['className'] = 'personal';
1262
                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
1263
                $event['editable'] = true;
1264
                $event['sent_to'] = get_lang('Me');
1265
                $event['type'] = 'personal';
1266
1267 View Code Duplication
                if (!empty($row['date']) && $row['date'] != '0000-00-00 00:00:00') {
1268
                    $event['start'] = $this->formatEventDate($row['date']);
1269
                    $event['start_date_localtime'] = api_get_local_time($row['date']);
1270
                }
1271
1272 View Code Duplication
                if (!empty($row['enddate']) && $row['enddate'] != '0000-00-00 00:00:00') {
1273
                    $event['end'] = $this->formatEventDate($row['enddate']);
1274
                    $event['end_date_localtime'] = api_get_local_time($row['enddate']);
1275
                }
1276
                $event['description'] = $row['text'];
1277
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1278
1279
                $event['parent_event_id'] = 0;
1280
                $event['has_children'] = 0;
1281
1282
                $my_events[] = $event;
1283
                $this->events[] = $event;
1284
            }
1285
        }
1286
        return $my_events;
1287
    }
1288
1289
    /**
1290
     * Get user/group list per event.
1291
     *
1292
     * @param int $eventId
1293
     * @param int $courseId
1294
     * @paraù int $sessionId
1295
     *
1296
     * @return array
1297
     */
1298
    public function getUsersAndGroupSubscribedToEvent($eventId, $courseId, $sessionId)
1299
    {
1300
        $eventId = intval($eventId);
1301
        $courseId = intval($courseId);
1302
        $sessionId = intval($sessionId);
1303
1304
        $sessionCondition = "ip.session_id = $sessionId";
1305
        if (empty($sessionId)) {
1306
            $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
1307
        }
1308
1309
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1310
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1311
1312
        // Get sent_tos
1313
        $sql = "SELECT DISTINCT to_user_id, to_group_id
1314
                FROM $tbl_property ip
1315
                INNER JOIN $tlb_course_agenda agenda
1316
                ON (
1317
                  ip.ref = agenda.id AND
1318
                  ip.c_id = agenda.c_id AND
1319
                  ip.tool = '".TOOL_CALENDAR_EVENT."'
1320
                )
1321
                WHERE
1322
                    ref = $eventId AND
1323
                    ip.visibility = '1' AND
1324
                    ip.c_id = $courseId AND
1325
                    $sessionCondition
1326
                ";
1327
1328
        $result = Database::query($sql);
1329
        $users = array();
1330
        $groups = array();
1331
        $everyone = false;
1332
1333
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1334
            if (!empty($row['to_group_id'])) {
1335
                $groups[] = $row['to_group_id'];
1336
            }
1337
            if (!empty($row['to_user_id'])) {
1338
                $users[] = $row['to_user_id'];
1339
            }
1340
1341
            if (empty($groups) && empty($users)) {
1342
                if ($row['to_group_id'] == 0) {
1343
                    $everyone = true;
1344
                }
1345
            }
1346
        }
1347
1348
        return array(
1349
            'everyone' => $everyone,
1350
            'users' => $users,
1351
            'groups' => $groups
1352
        );
1353
    }
1354
1355
    /**
1356
     * @param int $start
1357
     * @param int $end
1358
     * @param int $sessionId
1359
     * @param int $userId
1360
     * @param string $color
1361
     *
1362
     * @return array
1363
     */
1364
    public function getSessionEvents($start, $end, $sessionId = 0, $userId = 0, $color = '')
1365
    {
1366
        $courses = SessionManager::get_course_list_by_session_id($sessionId);
1367
1368
        if (!empty($courses)) {
1369
            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...
1370
                //if (api_is_coach($sessionId, $course['real_id'])) {
1371
                    $this->getCourseEvents(
1372
                        $start,
1373
                        $end,
1374
                        $course,
1375
                        0,
1376
                        $sessionId,
1377
                        0,
1378
                        $color
1379
                    );
1380
                //}
1381
            }
1382
        }
1383
1384
    }
1385
1386
    /**
1387
     * @param int $start
1388
     * @param int $end
1389
     * @param array $courseInfo
1390
     * @param int $groupId
1391
     * @param int $session_id
1392
     * @param int $user_id
1393
     * @param string $color
1394
     *
1395
     * @return array
1396
     */
1397
    public function getCourseEvents(
1398
        $start,
1399
        $end,
1400
        $courseInfo,
1401
        $groupId = 0,
1402
        $session_id = 0,
1403
        $user_id = 0,
1404
        $color = ''
1405
    ) {
1406
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
1407
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
1408
1409
        if (empty($courseInfo)) {
1410
            return array();
1411
        }
1412
        $course_id = $courseInfo['real_id'];
1413
1414
        if (empty($course_id)) {
1415
            return array();
1416
        }
1417
1418
        $session_id = intval($session_id);
1419
        $user_id = intval($user_id);
1420
        $groupList = GroupManager::get_group_list(null, $courseInfo['code']);
1421
1422
        $group_name_list = array();
1423
        if (!empty($groupList)) {
1424
            foreach ($groupList as $group) {
1425
                $group_name_list[$group['id']] = $group['name'];
1426
            }
1427
        }
1428
1429
        if (!empty($groupId)) {
1430 View Code Duplication
            if (!api_is_allowed_to_edit()) {
1431
                $user_id = api_get_user_id();
1432
                $group_memberships = GroupManager::get_group_ids(
1433
                    $course_id,
1434
                    $user_id
1435
                );
1436
            } else {
1437
                $group_memberships = GroupManager::get_group_ids(
1438
                    $course_id,
1439
                    $user_id
1440
                );
1441
            }
1442 View Code Duplication
        } else {
1443
            // if no group was defined but I am a student reviewing his agenda,
1444
            // group events should show, so we should fetch those groups to which
1445
            // I belong
1446
            if (!api_is_allowed_to_edit()) {
1447
                $user_id = api_get_user_id();
1448
                $group_memberships = GroupManager::get_group_ids(
1449
                    $course_id,
1450
                    $user_id
1451
                );
1452
            } else {
1453
                // If no group was defined and I am a teacher/admin reviewing
1454
                // someone else's agenda, we should fetch this person's groups
1455
                $group_memberships = GroupManager::get_group_ids(
1456
                    $course_id,
1457
                    $user_id
1458
                );
1459
            }
1460
        }
1461
1462
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1463
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1464
1465
        if (!empty($groupId)) {
1466
            $group_memberships = array($groupId);
1467
        }
1468
1469
        if (is_array($group_memberships) && count($group_memberships) > 0) {
1470
            if (api_is_allowed_to_edit()) {
1471
                if (!empty($groupId)) {
1472
                    $where_condition = "( ip.to_group_id IN (".implode(", ", $group_memberships).") ) ";
1473 View Code Duplication
                } else {
1474
                    if (!empty($user_id)) {
1475
                        $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).")) ) ";
1476
                    } else {
1477
                        $where_condition = "( ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
1478
                    }
1479
                }
1480
            } else {
1481
                $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).")) ) ";
1482
            }
1483
1484
            if (empty($session_id)) {
1485
                $sessionCondition =  "
1486
                (
1487
                    agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
1488
                ) ";
1489
            } else {
1490
                $sessionCondition =  "
1491
                (
1492
                    agenda.session_id = $session_id AND
1493
                    ip.session_id = $session_id
1494
                ) ";
1495
            }
1496
1497
            $sql = "SELECT DISTINCT
1498
                        agenda.*,
1499
                        ip.visibility,
1500
                        ip.to_group_id,
1501
                        ip.insert_user_id,
1502
                        ip.ref,
1503
                        to_user_id
1504
                    FROM $tlb_course_agenda agenda
1505
                    INNER JOIN $tbl_property ip
1506
                    ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id AND ip.tool = '".TOOL_CALENDAR_EVENT."')
1507
                    WHERE
1508
                        $where_condition AND
1509
                        ip.visibility = '1' AND
1510
                        agenda.c_id = $course_id AND
1511
                        ip.c_id = agenda.c_id AND
1512
                        $sessionCondition
1513
                    ";
1514
        } else {
1515
            $visibilityCondition = " ip.visibility='1' AND ";
1516
1517
            if (api_is_allowed_to_edit()) {
1518
                if ($user_id == 0) {
1519
                    $where_condition = "";
1520
                } else {
1521
                    $where_condition = " (ip.to_user_id = ".$user_id." OR ip.to_user_id IS NULL) AND ip.to_group_id IS NULL AND ";
1522
                }
1523
                $visibilityCondition = " (ip.visibility IN ('1', '0')) AND ";
1524
            } else {
1525
                $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 ";
1526
            }
1527
1528
            if (empty($session_id)) {
1529
                $sessionCondition =  "
1530
                (
1531
                    agenda.session_id = 0 AND
1532
                    (ip.session_id IS NULL OR ip.session_id = 0)
1533
                ) ";
1534
            } else {
1535
                $sessionCondition =  "
1536
                (
1537
                    agenda.session_id = $session_id AND
1538
                    ip.session_id = $session_id
1539
                ) ";
1540
            }
1541
1542
            $sql = "SELECT DISTINCT
1543
                        agenda.*,
1544
                        ip.visibility,
1545
                        ip.to_group_id,
1546
                        ip.insert_user_id,
1547
                        ip.ref,
1548
                        to_user_id
1549
                    FROM $tlb_course_agenda agenda
1550
                    INNER JOIN $tbl_property ip
1551
                    ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id AND ip.tool='".TOOL_CALENDAR_EVENT."' )
1552
                    WHERE
1553
                        $where_condition
1554
                        $visibilityCondition
1555
                        agenda.c_id = $course_id AND
1556
                        $sessionCondition
1557
                    ";
1558
        }
1559
1560
        $dateCondition = null;
1561
1562 View Code Duplication
        if (!empty($start) && !empty($end)) {
1563
            $dateCondition .= "AND (
1564
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1565
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1566
                 (
1567
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1568
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1569
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1570
                 )
1571
            )";
1572
        }
1573
1574
        $sql .= $dateCondition;
1575
        $result = Database::query($sql);
1576
1577
        $coachCanEdit = false;
1578
        if (!empty($session_id)) {
1579
            $coachCanEdit = api_is_coach($session_id, $course_id);
1580
        }
1581
1582
        if (Database::num_rows($result)) {
1583
            $eventsAdded = array_column($this->events, 'unique_id');
1584
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1585
                $event = array();
1586
                $event['id'] = 'course_'.$row['id'];
1587
                $event['unique_id']  = $row['iid'];
1588
                // To avoid doubles
1589
                if (in_array($event['unique_id'], $eventsAdded)) {
1590
                    continue;
1591
                }
1592
1593
                $eventsAdded[] = $event['unique_id'];
1594
1595
                $eventId = $row['ref'];
1596
                $items = $this->getUsersAndGroupSubscribedToEvent(
1597
                    $eventId,
1598
                    $course_id,
1599
                    $this->sessionId
1600
                );
1601
                $group_to_array = $items['groups'];
1602
                $user_to_array = $items['users'];
1603
                $attachment = $this->getAttachment($row['id'], $courseInfo);
1604
1605
                if (!empty($attachment)) {
1606
                    $has_attachment = Display::return_icon('attachment.gif', get_lang('Attachment'));
1607
                    $user_filename = $attachment['filename'];
1608
                    $url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$course_id.'&'.api_get_cidreq();
1609
                    $event['attachment'] = $has_attachment.Display::url($user_filename, $url);
1610
                } else {
1611
                    $event['attachment'] = '';
1612
                }
1613
1614
                $event['title'] = $row['title'];
1615
                $event['className'] = 'course';
1616
                $event['allDay'] = 'false';
1617
                $event['course_id'] = $course_id;
1618
                $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
1619
1620
                $sessionInfo = [];
1621 View Code Duplication
                if (isset($row['session_id']) && !empty($row['session_id'])) {
1622
                    $sessionInfo = api_get_session_info($session_id);
1623
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
1624
                }
1625
1626
                $event['session_name'] = isset($sessionInfo['name']) ? $sessionInfo['name'] : '';
1627
                $event['course_name'] = isset($courseInfo['title']) ? $courseInfo['title'] : '';
1628
1629 View Code Duplication
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1630
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
1631
                }
1632
1633
                if (!empty($color)) {
1634
                    $event['borderColor'] = $event['backgroundColor'] = $color;
1635
                }
1636
1637 View Code Duplication
                if (isset($row['color']) && !empty($row['color'])) {
1638
                    $event['borderColor'] = $event['backgroundColor'] = $row['color'];
1639
                }
1640
1641
                $event['editable'] = false;
1642
1643
                if (api_is_allowed_to_edit() && $this->type == 'course') {
1644
                    $event['editable'] = true;
1645
                    if (!empty($session_id)) {
1646
                        if ($coachCanEdit == false) {
1647
                            $event['editable'] = false;
1648
                        }
1649
                    }
1650
                }
1651
1652 View Code Duplication
                if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
1653
                    $event['start'] = $this->formatEventDate($row['start_date']);
1654
                    $event['start_date_localtime'] = api_get_local_time($row['start_date']);
1655
                }
1656 View Code Duplication
                if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
1657
                    $event['end'] = $this->formatEventDate($row['end_date']);
1658
                    $event['end_date_localtime'] = api_get_local_time($row['end_date']);
1659
                }
1660
1661
                $event['sent_to'] = '';
1662
                $event['type'] = 'course';
1663
                if ($row['session_id'] != 0) {
1664
                    $event['type'] = 'session';
1665
                }
1666
1667
                // Event Sent to a group?
1668
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1669
                    $sent_to = array();
1670
                    if (!empty($group_to_array)) {
1671
                        foreach ($group_to_array as $group_item) {
1672
                            $sent_to[] = $group_name_list[$group_item];
1673
                        }
1674
                    }
1675
                    $sent_to = implode('@@', $sent_to);
1676
                    $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
1677
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1678
                    $event['type'] = 'group';
1679
                }
1680
1681
                // Event sent to a user?
1682
                if (isset($row['to_user_id'])) {
1683
                    $sent_to = array();
1684
                    if (!empty($user_to_array)) {
1685
                        foreach ($user_to_array as $item) {
1686
                            $user_info = api_get_user_info($item);
1687
                            // Add username as tooltip for $event['sent_to'] - ref #4226
1688
                            $username = api_htmlentities(sprintf(get_lang('LoginX'), $user_info['username']), ENT_QUOTES);
1689
                            $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
1690
                        }
1691
                    }
1692
                    $sent_to = implode('@@', $sent_to);
1693
                    $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
1694
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1695
                }
1696
1697
                //Event sent to everyone!
1698
                if (empty($event['sent_to'])) {
1699
                    $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
1700
                }
1701
1702
                $event['description'] = $row['content'];
1703
                $event['visibility'] = $row['visibility'];
1704
                $event['real_id'] = $row['id'];
1705
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1706
                $event['parent_event_id'] = $row['parent_event_id'];
1707
                $event['has_children'] = $this->hasChildren($row['id'], $course_id) ? 1 : 0;
1708
                $event['comment'] = $row['comment'];
1709
1710
                $this->events[] = $event;
1711
            }
1712
        }
1713
1714
        return $this->events;
1715
    }
1716
1717
    /**
1718
     * @param int $start tms
1719
     * @param int $end tms
1720
     * @return array
1721
     */
1722
    public function getPlatformEvents($start, $end)
1723
    {
1724
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
1725
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
1726
1727
        $dateCondition = '';
1728
1729 View Code Duplication
        if (!empty($start) && !empty($end)) {
1730
            $dateCondition .= "AND (
1731
                 start_date BETWEEN '".$start."' AND '".$end."' OR
1732
                 end_date BETWEEN '".$start."' AND '".$end."' OR
1733
                 (
1734
                     start_date IS NOT NULL AND end_date IS NOT NULL AND
1735
                     YEAR(start_date) = YEAR(end_date) AND
1736
                     MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
1737
                 )
1738
            )";
1739
        }
1740
1741
        $access_url_id = api_get_current_access_url_id();
1742
1743
        $sql = "SELECT *
1744
                FROM ".$this->tbl_global_agenda."
1745
                WHERE access_url_id = $access_url_id
1746
                $dateCondition";
1747
        $result = Database::query($sql);
1748
        $my_events = array();
1749
        if (Database::num_rows($result)) {
1750
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1751
                $event = array();
1752
                $event['id'] = 'platform_'.$row['id'];
1753
                $event['title'] = $row['title'];
1754
                $event['className'] = 'platform';
1755
                $event['allDay'] = 'false';
1756
                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
1757
                $event['editable'] = false;
1758
                $event['type'] = 'admin';
1759
1760
                if (api_is_platform_admin() && $this->type == 'admin') {
1761
                    $event['editable'] = true;
1762
                }
1763
1764 View Code Duplication
                if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
1765
                    $event['start'] = $this->formatEventDate($row['start_date']);
1766
                    $event['start_date_localtime'] = api_get_local_time($row['start_date']);
1767
                }
1768 View Code Duplication
                if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
1769
                    $event['end'] = $this->formatEventDate($row['end_date']);
1770
                    $event['end_date_localtime'] = api_get_local_time($row['end_date']);
1771
                }
1772
1773
                $event['description'] = $row['content'];
1774
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1775
1776
                $event['parent_event_id'] = 0;
1777
                $event['has_children'] = 0;
1778
1779
                $my_events[] = $event;
1780
                $this->events[] = $event;
1781
            }
1782
        }
1783
1784
        return $my_events;
1785
    }
1786
1787
    /**
1788
     * Format needed for the Fullcalendar js lib
1789
     *
1790
     * @param string $utcTime
1791
     * @return bool|string
1792
     */
1793
    private function formatEventDate($utcTime)
1794
    {
1795
        $utcTimeZone = new DateTimeZone('UTC');
1796
        $platformTimeZone = new DateTimeZone(_api_get_timezone());
1797
1798
        $eventDate = new DateTime($utcTime, $utcTimeZone);
1799
        $eventDate->setTimezone($platformTimeZone);
1800
1801
        return $eventDate->format(DateTime::ISO8601);
1802
    }
1803
1804
    /**
1805
     * this function shows the form with the user that were not selected
1806
     * @author: Patrick Cool <[email protected]>, Ghent University
1807
     * @return string code
1808
     */
1809
    public static function construct_not_selected_select_form($group_list = null, $user_list = null, $to_already_selected = array())
1810
    {
1811
        $html = '<select id="users_to_send_id" data-placeholder="'.get_lang('Select').'" name="users_to_send[]" multiple="multiple">';
1812
        if ($to_already_selected == 'everyone') {
1813
            $html .= '<option value="everyone" checked="checked">'.get_lang('Everyone').'</option>';
1814
        } else {
1815
            $html .= '<option value="everyone">'.get_lang('Everyone').'</option>';
1816
        }
1817
1818
        if (is_array($group_list)) {
1819
            $html .= '<optgroup label="'.get_lang('Groups').'">';
1820
            foreach ($group_list as $this_group) {
1821
                if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'], $to_already_selected)) {
1822
                    // $to_already_selected is the array containing the groups (and users) that are already selected
1823
                    $count_users = isset($this_group['count_users']) ? $this_group['count_users'] : $this_group['userNb'];
1824
                    $count_users = " &ndash; $count_users ".get_lang('Users');
1825
1826
                    $html .= '<option value="GROUP:'.$this_group['id'].'"> '.$this_group['name'].$count_users.'</option>';
1827
                }
1828
            }
1829
            $html .= '</optgroup>';
1830
        }
1831
1832
        // adding the individual users to the select form
1833
        if (is_array($group_list)) {
1834
            $html .= '<optgroup label="'.get_lang('Users').'">';
1835
        }
1836
        foreach ($user_list as $this_user) {
1837
            // $to_already_selected is the array containing the users (and groups) that are already selected
1838
            if (!is_array($to_already_selected) || !in_array("USER:".$this_user['user_id'], $to_already_selected)) {
1839
                $username = api_htmlentities(sprintf(get_lang('LoginX'), $this_user['username']), ENT_QUOTES);
1840
                // @todo : add title attribute $username in the jqdialog window. wait for a chosen version to inherit title attribute
1841
                $html .= '<option title="'.$username.'" value="USER:'.$this_user['user_id'].'">'.api_get_person_name($this_user['firstname'], $this_user['lastname']).' ('.$this_user['username'].') </option>';
1842
            }
1843
        }
1844
        if (is_array($group_list)) {
1845
            $html .= '</optgroup>';
1846
            $html .= "</select>";
1847
        }
1848
        return $html;
1849
    }
1850
1851
    /**
1852
     * @param FormValidator $form
1853
     * @param array $groupList
1854
     * @param array $userList
1855
     * @param array $sendTo array('users' => [1, 2], 'groups' => [3, 4])
1856
     * @param array $attributes
1857
     * @param bool $addOnlyItemsInSendTo
1858
     * @param bool $required
1859
     */
1860
    public function setSendToSelect(
1861
        $form,
1862
        $groupList = null,
1863
        $userList = null,
1864
        $sendTo = array(),
1865
        $attributes = array(),
1866
        $addOnlyItemsInSendTo = false,
1867
        $required = false
1868
    ) {
1869
        $params = array(
1870
            'id' => 'users_to_send_id',
1871
            'data-placeholder' => get_lang('Select'),
1872
            'multiple' => 'multiple',
1873
            'class' => 'multiple-select'
1874
        );
1875
1876
        if (!empty($attributes)) {
1877
            $params = array_merge($params, $attributes);
1878
            if (empty($params['multiple'])) {
1879
                unset($params['multiple']);
1880
            }
1881
        }
1882
1883
        $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : array();
1884
        $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : array();
1885
1886
        /** @var HTML_QuickForm_select $select */
1887
        $select = $form->addSelect('users_to_send', get_lang('To'), null, $params);
1888
1889
        if ($required) {
1890
            $form->setRequired($select);
1891
        }
1892
1893
        $selectedEveryoneOptions = array();
1894
        if (isset($sendTo['everyone']) && $sendTo['everyone']) {
1895
            $selectedEveryoneOptions = array('selected');
1896
            $sendToUsers = array();
1897
        }
1898
1899
        $select->addOption(get_lang('Everyone'), 'everyone', $selectedEveryoneOptions);
1900
1901
        $options = array();
1902
        if (is_array($groupList)) {
1903
            foreach ($groupList as $group) {
1904
                $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
1905
                $count_users = " &ndash; $count_users ".get_lang('Users');
1906
                $option = array(
1907
                    'text' => $group['name'].$count_users,
1908
                    'value' => "GROUP:".$group['id']
1909
                );
1910
                $selected = in_array($group['id'], $sendToGroups) ? true : false;
1911
                if ($selected) {
1912
                    $option['selected'] = 'selected';
1913
                }
1914
1915
                if ($addOnlyItemsInSendTo) {
1916
                    if ($selected) {
1917
                        $options[] = $option;
1918
                    }
1919
                } else {
1920
                    $options[] = $option;
1921
                }
1922
            }
1923
            $select->addOptGroup($options, get_lang('Groups'));
1924
        }
1925
1926
        // adding the individual users to the select form
1927
        if (is_array($userList)) {
1928
            $options = array();
1929
            foreach ($userList as $user) {
1930
                if ($user['status'] == ANONYMOUS) {
1931
                    continue;
1932
                }
1933
                $option = array(
1934
                    'text' => api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')',
1935
                    'value' => "USER:".$user['user_id']
1936
                );
1937
1938
                $selected = in_array($user['user_id'], $sendToUsers) ? true : false;
1939
1940
                if ($selected) {
1941
                    $option['selected'] = 'selected';
1942
                }
1943
1944
                if ($addOnlyItemsInSendTo) {
1945
                    if ($selected) {
1946
                        $options[] = $option;
1947
                    }
1948
                } else {
1949
                    $options[] = $option;
1950
                }
1951
            }
1952
1953
            $select->addOptGroup($options, get_lang('Users'));
1954
        }
1955
    }
1956
1957
    /**
1958
     * Separates the users and groups array
1959
     * users have a value USER:XXX (with XXX the user id
1960
     * groups have a value GROUP:YYY (with YYY the group id)
1961
     * use the 'everyone' key
1962
     * @author Julio Montoya based in separate_users_groups in agenda.inc.php
1963
     * @param array $to
1964
     * @return array
1965
     */
1966
    public function parseSendToArray($to)
1967
    {
1968
        $groupList = array();
1969
        $userList = array();
1970
        $sendTo = null;
1971
1972
        $sendTo['everyone'] = false;
1973
        if (is_array($to) && count($to) > 0) {
1974
            foreach ($to as $item) {
1975
                if ($item == 'everyone') {
1976
                    $sendTo['everyone'] = true;
1977
                } else {
1978
                    list($type, $id) = explode(':', $item);
1979
                    switch ($type) {
1980
                        case 'GROUP':
1981
                            $groupList[] = $id;
1982
                            break;
1983
                        case 'USER':
1984
                            $userList[] = $id;
1985
                            break;
1986
                    }
1987
                }
1988
            }
1989
            $sendTo['groups'] = $groupList;
1990
            $sendTo['users'] = $userList;
1991
        }
1992
1993
        return $sendTo;
1994
    }
1995
1996
    /**
1997
     * @param array $params
1998
     * @return FormValidator
1999
     */
2000
    public function getForm($params = array())
2001
    {
2002
        $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
2003
        $id = isset($params['id']) ? intval($params['id']) : null;
2004
        if ($this->type == 'course') {
2005
            $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
2006
        } else {
2007
            $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
2008
        }
2009
2010
        if (isset($params['content'])) {
2011
            $params['content'] = nl2br($params['content']);
2012
        }
2013
2014
        $form = new FormValidator(
2015
            'add_event',
2016
            'post',
2017
            $url,
2018
            null,
2019
            array('enctype' => 'multipart/form-data')
2020
        );
2021
2022
        $idAttach = isset($params['id_attach']) ? intval($params['id_attach']) : null;
2023
        $groupId = api_get_group_id();
2024
2025
        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...
2026
            $form_title = get_lang('ModifyCalendarItem');
2027
        } else {
2028
            $form_title = get_lang('AddCalendarItem');
2029
        }
2030
2031
        $form->addElement('header', $form_title);
2032
        $form->addElement('hidden', 'id', $id);
2033
        $form->addElement('hidden', 'action', $action);
2034
        $form->addElement('hidden', 'id_attach', $idAttach);
2035
2036
        $isSubEventEdition = false;
2037
        $isParentFromSerie = false;
2038
        $showAttachmentForm = true;
2039
2040
        if ($this->type == 'course') {
2041
            // Edition mode.
2042
            if (!empty($id)) {
2043
                $showAttachmentForm = false;
2044
                if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
2045
                    $isSubEventEdition = true;
2046
                }
2047
                if (!empty($params['repeat_info'])) {
2048
                    $isParentFromSerie = true;
2049
                }
2050
            }
2051
        }
2052
2053
        if ($isSubEventEdition) {
2054
            $form->addElement(
2055
                'label',
2056
                null,
2057
                Display::return_message(get_lang('EditingThisEventWillRemoveItFromTheSerie'), 'warning')
2058
            );
2059
        }
2060
2061
        $form->addElement('text', 'title', get_lang('ItemTitle'));
2062
2063
        if (isset($groupId) && !empty($groupId)) {
2064
            $form->addElement('hidden', 'selected_form[0]', "GROUP:'.$groupId.'");
2065
            $form->addElement('hidden', 'to', 'true');
2066
        } else {
2067
            $sendTo = isset($params['send_to']) ? $params['send_to'] : null;
2068
            if ($this->type == 'course') {
2069
                $this->showToForm($form, $sendTo, array(), false, true);
2070
            }
2071
        }
2072
2073
        $form->addDateRangePicker('date_range', get_lang('StartDate'), false, array('id' => 'date_range'));
2074
        $form->addElement('checkbox', 'all_day', null, get_lang('AllDay'));
2075
2076
        if ($this->type == 'course') {
2077
            $repeat = $form->addElement('checkbox', 'repeat', null, get_lang('RepeatEvent'), array('onclick' => 'return plus_repeated_event();'));
2078
            $form->addElement('html', '<div id="options2" style="display:none">');
2079
            $form->addElement('select', 'repeat_type', get_lang('RepeatType'), self::getRepeatTypes());
2080
            $form->addElement('date_picker', 'repeat_end_day', get_lang('RepeatEnd'), array('id' => 'repeat_end_date_form'));
2081
2082
            if ($isSubEventEdition || $isParentFromSerie) {
2083
                if ($isSubEventEdition) {
2084
                    $parentEvent = $params['parent_info'];
2085
                    $repeatInfo = $parentEvent['repeat_info'];
2086
                } else {
2087
                    $repeatInfo = $params['repeat_info'];
2088
                }
2089
                $params['repeat'] = 1;
2090
                $params['repeat_type'] = $repeatInfo['cal_type'];
2091
                $params['repeat_end_day'] = substr(api_get_local_time($repeatInfo['cal_end']), 0, 10);
2092
2093
                $form->freeze(array('repeat_type', 'repeat_end_day'));
2094
                $repeat->_attributes['disabled'] = 'disabled';
2095
            }
2096
            $form->addElement('html', '</div>');
2097
        }
2098
2099
        if (!empty($id)) {
2100
            if (empty($params['end_date'])) {
2101
                $params['date_range'] = $params['end_date'];
2102
            }
2103
2104
            $params['date_range'] =
2105
                substr(api_get_local_time($params['start_date']), 0, 16).' / '.
2106
                substr(api_get_local_time($params['end_date']), 0, 16);
2107
        }
2108
2109
        if (!api_is_allowed_to_edit(null, true)) {
2110
            $toolbar = 'AgendaStudent';
2111
        } else {
2112
            $toolbar = 'Agenda';
2113
        }
2114
2115
        $form->addElement(
2116
            'html_editor',
2117
            'content',
2118
            get_lang('Description'),
2119
            null,
2120
            array('ToolbarSet' => $toolbar, 'Width' => '100%', 'Height' => '200')
2121
        );
2122
2123
        if ($this->type == 'course') {
2124
            $form->addElement('textarea', 'comment', get_lang('Comment'));
2125
            $form->addElement('file', 'user_upload', get_lang('AddAnAttachment'));
2126
            if ($showAttachmentForm) {
2127
                if (isset($params['attachment']) && !empty($params['attachment'])) {
2128
                    $attachment = $params['attachment'];
2129
                    $params['file_comment'] = $attachment['comment'];
2130
                    if (!empty($attachment['path'])) {
2131
                        $form->addElement(
2132
                            'checkbox',
2133
                            'delete_attachment',
2134
                            null,
2135
                            get_lang('DeleteAttachment').' '.$attachment['filename']
2136
                        );
2137
                    }
2138
                }
2139
            }
2140
2141
            $form->addElement('textarea', 'file_comment', get_lang('FileComment'));
2142
        }
2143
2144
        if (empty($id)) {
2145
            $form->addElement(
2146
                'checkbox',
2147
                'add_announcement',
2148
                null,
2149
                get_lang('AddAnnouncement').'&nbsp('.get_lang('SendMail').')'
2150
            );
2151
        }
2152
2153
2154
        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...
2155
            $form->addButtonUpdate(get_lang('ModifyEvent'));
2156
        } else {
2157
            $form->addButtonSave(get_lang('AgendaAdd'));
2158
        }
2159
2160
        $form->setDefaults($params);
2161
2162
        $form->addRule('date_range', get_lang('ThisFieldIsRequired'), 'required');
2163
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
2164
2165
        return $form;
2166
    }
2167
2168
    /**
2169
     * @param FormValidator $form
2170
     * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
2171
     * @param array $attributes
2172
     * @param bool $addOnlyItemsInSendTo
2173
     * @param bool $required
2174
     * @return bool
2175
     */
2176
    public function showToForm(
2177
        $form,
2178
        $sendTo = array(),
2179
        $attributes = array(),
2180
        $addOnlyItemsInSendTo = false,
2181
        $required = false
2182
    ) {
2183
        if ($this->type != 'course') {
2184
            return false;
2185
        }
2186
2187
        $order = 'lastname';
2188
        if (api_is_western_name_order()) {
2189
            $order = 'firstname';
2190
        }
2191
2192
        $userList = CourseManager::get_user_list_from_course_code(
2193
            api_get_course_id(),
2194
            $this->sessionId,
2195
            null,
2196
            $order
2197
        );
2198
        $groupList = CourseManager::get_group_list_of_course(
2199
            api_get_course_id(),
2200
            $this->sessionId
2201
        );
2202
2203
        $this->setSendToSelect(
2204
            $form,
2205
            $groupList,
2206
            $userList,
0 ignored issues
show
Bug introduced by
It seems like $userList defined by \CourseManager::get_user...essionId, null, $order) on line 2192 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...
2207
            $sendTo,
2208
            $attributes,
2209
            $addOnlyItemsInSendTo,
2210
            $required
2211
        );
2212
2213
        return true;
2214
2215
    }
2216
2217
    /**
2218
     * @param int $id
2219
     * @param int $visibility 0= invisible, 1 visible
2220
     * @param array $courseInfo
2221
     * @param int $userId
2222
     */
2223
    public static function changeVisibility($id, $visibility, $courseInfo, $userId = null)
2224
    {
2225
        $id = intval($id);
2226
        if (empty($userId)) {
2227
            $userId = api_get_user_id();
2228
        } else {
2229
            $userId = intval($userId);
2230
        }
2231
2232
        if ($visibility == 0) {
2233
            api_item_property_update($courseInfo, TOOL_CALENDAR_EVENT, $id, "invisible", $userId);
2234
        } else {
2235
            api_item_property_update($courseInfo, TOOL_CALENDAR_EVENT, $id, "visible", $userId);
2236
        }
2237
    }
2238
2239
    /**
2240
     * Get repeat types
2241
     * @return array
2242
     */
2243
    public static function getRepeatTypes()
2244
    {
2245
        return array(
2246
            'daily' => get_lang('RepeatDaily'),
2247
            'weekly'  => get_lang('RepeatWeekly'),
2248
            'monthlyByDate'  => get_lang('RepeatMonthlyByDate'),
2249
            //monthlyByDay"> get_lang('RepeatMonthlyByDay');
2250
            //monthlyByDayR' => get_lang('RepeatMonthlyByDayR'),
2251
            'yearly' => get_lang('RepeatYearly')
2252
        );
2253
    }
2254
2255
    /**
2256
     * Show a list with all the attachments according to the post's id
2257
     * @param int $eventId
2258
     * @param array $courseInfo
2259
     * @return array with the post info
2260
     */
2261 View Code Duplication
    public function getAttachment($eventId, $courseInfo)
2262
    {
2263
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2264
        $courseId = intval($courseInfo['real_id']);
2265
        $eventId = intval($eventId);
2266
        $row = array();
2267
        $sql = "SELECT id, path, filename, comment
2268
                FROM $tableAttachment
2269
                WHERE
2270
                    c_id = $courseId AND
2271
                    agenda_id = $eventId";
2272
        $result = Database::query($sql);
2273
        if (Database::num_rows($result) != 0) {
2274
            $row = Database::fetch_array($result, 'ASSOC');
2275
        }
2276
2277
        return $row;
2278
    }
2279
2280
    /**
2281
     * Add an attachment file into agenda
2282
     * @param int $eventId
2283
     * @param array $fileUserUpload ($_FILES['user_upload'])
2284
     * @param string comment about file
2285
     * @param array $courseInfo
2286
     * @return string
2287
     */
2288
    public function addAttachment($eventId, $fileUserUpload, $comment, $courseInfo)
2289
    {
2290
        $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2291
        $eventId = intval($eventId);
2292
2293
        // Storing the attachments
2294
        $upload_ok = false;
2295
        if (!empty($fileUserUpload['name'])) {
2296
            $upload_ok = process_uploaded_file($fileUserUpload);
2297
        }
2298
        if (!empty($upload_ok)) {
2299
2300
            $courseDir = $courseInfo['directory'].'/upload/calendar';
2301
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2302
            $uploadDir = $sys_course_path.$courseDir;
2303
2304
            // Try to add an extension to the file if it hasn't one
2305
            $new_file_name = add_ext_on_mime(
2306
                stripslashes($fileUserUpload['name']),
2307
                $fileUserUpload['type']
2308
            );
2309
            // user's file name
2310
            $file_name = $fileUserUpload['name'];
2311
2312
            if (!filter_extension($new_file_name)) {
2313
                return Display::return_message(
2314
                    get_lang('UplUnableToSaveFileFilteredExtension'),
2315
                    'error'
2316
                );
2317
            } else {
2318
                $new_file_name = uniqid('');
2319
                $new_path = $uploadDir.'/'.$new_file_name;
2320
                $result = @move_uploaded_file($fileUserUpload['tmp_name'], $new_path);
2321
                $course_id = api_get_course_int_id();
2322
                $size = intval($fileUserUpload['size']);
2323
                // Storing the attachments if any
2324
                if ($result) {
2325
                    $params = [
2326
                        'c_id' => $course_id,
2327
                        'filename' => $file_name,
2328
                        'comment' => $comment,
2329
                        'path' => $new_file_name,
2330
                        'agenda_id' => $eventId,
2331
                        'size' => $size
2332
                    ];
2333
                    $id = Database::insert($agenda_table_attachment, $params);
2334
                    if ($id) {
2335
                        $sql = "UPDATE $agenda_table_attachment
2336
                                SET id = iid WHERE iid = $id";
2337
                        Database::query($sql);
2338
2339
                        api_item_property_update(
2340
                            $courseInfo,
2341
                            'calendar_event_attachment',
2342
                            $id,
2343
                            'AgendaAttachmentAdded',
2344
                            api_get_user_id()
2345
                        );
2346
                    }
2347
                }
2348
            }
2349
        }
2350
    }
2351
2352
    /**
2353
     * @param int $eventId
2354
     * @param array $fileUserUpload
2355
     * @param string $comment
2356
     * @param array $courseInfo
2357
     */
2358
    public function updateAttachment($eventId, $fileUserUpload, $comment, $courseInfo)
2359
    {
2360
        $attachment = $this->getAttachment($eventId, $courseInfo);
2361
        if (!empty($attachment)) {
2362
            $this->deleteAttachmentFile($attachment['id'], $courseInfo);
2363
        }
2364
        $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
2365
    }
2366
2367
    /**
2368
     * This function delete a attachment file by id
2369
     * @param int $attachmentId
2370
     * @param array $courseInfo
2371
     * @return string
2372
     */
2373
    public function deleteAttachmentFile($attachmentId, $courseInfo)
2374
    {
2375
        $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2376
        $attachmentId = intval($attachmentId);
2377
        $courseId = $courseInfo['real_id'];
2378
2379
        if (empty($courseId) || empty($attachmentId)) {
2380
            return false;
2381
        }
2382
2383
        $sql = "DELETE FROM $agenda_table_attachment
2384
                WHERE c_id = $courseId AND id = ".$attachmentId;
2385
        $result = Database::query($sql);
2386
2387
        // update item_property
2388
        api_item_property_update(
2389
            $courseInfo,
2390
            'calendar_event_attachment',
2391
            $attachmentId,
2392
            'AgendaAttachmentDeleted',
2393
            api_get_user_id()
2394
        );
2395
2396
        if (!empty($result)) {
2397
            return Display::return_message(get_lang("AttachmentFileDeleteSuccess"), 'confirmation');
2398
        }
2399
    }
2400
2401
    /**
2402
     * Adds x weeks to a UNIX timestamp
2403
     * @param   int     The timestamp
2404
     * @param   int     The number of weeks to add
2405
     * @return  int     The new timestamp
2406
     */
2407
    function addWeek($timestamp, $num = 1)
2408
    {
2409
        return $timestamp + $num * 604800;
2410
    }
2411
2412
    /**
2413
     * Adds x months to a UNIX timestamp
2414
     * @param   int     The timestamp
2415
     * @param   int     The number of years to add
2416
     * @return  int     The new timestamp
2417
     */
2418
    function addMonth($timestamp, $num = 1)
2419
    {
2420
        list($y, $m, $d, $h, $n, $s) = split('/', date('Y/m/d/h/i/s', $timestamp));
2421 View Code Duplication
        if ($m + $num > 12) {
2422
            $y += floor($num / 12);
2423
            $m += $num % 12;
2424
        } else {
2425
            $m += $num;
2426
        }
2427
        return mktime($h, $n, $s, $m, $d, $y);
2428
    }
2429
2430
    /**
2431
     * Adds x years to a UNIX timestamp
2432
     * @param   int     The timestamp
2433
     * @param   int     The number of years to add
2434
     * @return  int     The new timestamp
2435
     */
2436
    function addYear($timestamp, $num = 1)
2437
    {
2438
        list($y, $m, $d, $h, $n, $s) = split('/', date('Y/m/d/h/i/s', $timestamp));
2439
        return mktime($h, $n, $s, $m, $d, $y + $num);
2440
    }
2441
2442
    /**
2443
     * @param int $eventId
2444
     * @return array
2445
     */
2446
    public function getAllRepeatEvents($eventId)
2447
    {
2448
        $events = array();
2449
        switch ($this->type) {
2450
            case 'personal':
2451
                break;
2452
            case 'course':
2453
                if (!empty($this->course['real_id'])) {
2454
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
2455
                            WHERE
2456
                                c_id = ".$this->course['real_id']." AND
2457
                                parent_event_id = ".$eventId;
2458
                    $result = Database::query($sql);
2459
                    if (Database::num_rows($result)) {
2460
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
2461
                            $events[] = $row;
2462
                        }
2463
                    }
2464
                }
2465
                break;
2466
        }
2467
2468
        return $events;
2469
    }
2470
2471
    /**
2472
     * @param int $eventId
2473
     * @param int $courseId
2474
     *
2475
     * @return bool
2476
     */
2477
    public function hasChildren($eventId, $courseId)
2478
    {
2479
        $eventId = intval($eventId);
2480
        $courseId = intval($courseId);
2481
2482
        $sql = "SELECT count(DISTINCT(id)) as count
2483
                FROM ".$this->tbl_course_agenda."
2484
                WHERE
2485
                    c_id = ".$courseId." AND
2486
                    parent_event_id = ".$eventId;
2487
        $result = Database::query($sql);
2488
        if (Database::num_rows($result)) {
2489
            $row = Database::fetch_array($result, 'ASSOC');
2490
            return $row['count'] > 0;
2491
        }
2492
        return false;
2493
    }
2494
2495
    /**
2496
     * @param int $filter
2497
     * @param string $view
2498
     * @return string
2499
     */
2500
    public function displayActions($view, $filter = 0)
2501
    {
2502
        $courseInfo = api_get_course_info();
2503
2504
        $actionsLeft = '';
2505
        $actionsLeft .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_js.php?type={$this->type}'>".
2506
            Display::return_icon('calendar.png', get_lang('Calendar'), '', ICON_SIZE_MEDIUM)."</a>";
2507
2508
        $courseCondition = '';
2509
        if (!empty($courseInfo)) {
2510
            $courseCondition = api_get_cidreq();
2511
        }
2512
2513
        $actionsLeft .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_list.php?type={$this->type}&".$courseCondition."'>".
2514
            Display::return_icon('week.png', get_lang('AgendaList'), '', ICON_SIZE_MEDIUM)."</a>";
2515
2516
        $form = '';
2517
2518
        if (api_is_allowed_to_edit(false, true) ||
2519
            (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false, true) ||
2520
            GroupManager::user_has_access(api_get_user_id(), api_get_group_id(), GroupManager::GROUP_TOOL_CALENDAR) &&
2521
            GroupManager::is_tutor_of_group(api_get_user_id(), api_get_group_id())
2522
        ) {
2523
            $actionsLeft .= Display::url(
2524
                Display::return_icon('new_event.png', get_lang('AgendaAdd'), '', ICON_SIZE_MEDIUM),
2525
                api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=add&type=".$this->type
2526
            );
2527
2528
            $actionsLeft .= Display::url(
2529
                Display::return_icon('import_calendar.png', get_lang('ICalFileImport'), '', ICON_SIZE_MEDIUM),
2530
                api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=importical&type=".$this->type
2531
            );
2532
2533
            if ($this->type == 'course') {
2534
2535
                if (!isset($_GET['action'])) {
2536
2537
                    $form = new FormValidator(
2538
                        'form-search',
2539
                        'post',
2540
                        '',
2541
                        '',
2542
                        array(),
2543
                        FormValidator::LAYOUT_INLINE
2544
                    );
2545
                    $attributes = array(
2546
                        'multiple' => false,
2547
                        'id' => 'select_form_id_search'
2548
                    );
2549
                    $selectedValues = $this->parseAgendaFilter($filter);
2550
                    $this->showToForm($form, $selectedValues, $attributes);
2551
                    $form = $form->returnForm();
2552
                }
2553
            }
2554
        }
2555
2556
        if (api_is_platform_admin() ||
2557
            api_is_teacher() ||
2558
            api_is_student_boss() ||
2559
            api_is_drh() ||
2560
            api_is_session_admin() ||
2561
            api_is_coach()
2562
        ) {
2563
            if ($this->type == 'personal') {
2564
                $form = null;
2565
                if (!isset($_GET['action'])) {
2566
2567
                    $form = new FormValidator(
2568
                        'form-search',
2569
                        'get',
2570
                        api_get_self().'?type=personal&',
2571
                        '',
2572
                        array(),
2573
                        FormValidator::LAYOUT_INLINE
2574
                    );
2575
2576
                    $sessions = SessionManager::get_sessions_by_user(api_get_user_id());
2577
                    $form->addHidden('type', 'personal');
2578
                    $sessions = array_column($sessions, 'session_name', 'session_id');
2579
                    $sessions = ['0' => get_lang('SelectAnOption')] + $sessions;
2580
2581
                    $form->addSelect(
2582
                        'session_id',
2583
                        get_lang('Session'),
2584
                        $sessions,
2585
                        ['id' => 'session_id', 'onchange' => 'submit();']
2586
                    );
2587
                    //$form->addButtonFilter(get_lang('Filter'));
2588
                    //$renderer = $form->defaultRenderer();
2589
                    //$renderer->setCustomElementTemplate('<div class="col-md-6">{element}</div>');
2590
2591
                    $form->addButtonReset(get_lang('Reset'));
2592
                    $form = $form->returnForm();
2593
                }
2594
            }
2595
        }
2596
2597
        $actionsRight = '';
2598
        if ($view == 'calendar') {
2599
            $actionsRight .= $form;
2600
        }
2601
2602
        $toolbar = Display::toolbarAction(
2603
            'toolbar-agenda',
2604
            array(0 => $actionsLeft, 1 => $actionsRight),
2605
            2,
2606
            false
2607
        );
2608
        return $toolbar;
2609
    }
2610
2611
    /**
2612
     * @return FormValidator
2613
     */
2614
    public function getImportCalendarForm()
2615
    {
2616
        $form = new FormValidator(
2617
            'frm_import_ical',
2618
            'post',
2619
            api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&type='.$this->type,
2620
            array('enctype' => 'multipart/form-data')
2621
        );
2622
        $form->addElement('header', get_lang('ICalFileImport'));
2623
        $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
2624
        $form->addRule('ical_import', get_lang('ThisFieldIsRequired'), 'required');
2625
        $form->addButtonImport(get_lang('Import'), 'ical_submit');
2626
2627
        return $form;
2628
    }
2629
2630
    /**
2631
     * @param array $courseInfo
2632
     * @param $file
2633
     * @return array|bool|string
2634
     */
2635
    public function importEventFile($courseInfo, $file)
2636
    {
2637
        $charset = api_get_system_encoding();
2638
        $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
2639
        $messages = array();
2640
2641
        if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
2642
            error_log('Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__);
2643
            return false;
2644
        }
2645
2646
        $data = file_get_contents($filepath);
2647
2648
        $trans = array(
2649
            'DAILY' => 'daily',
2650
            'WEEKLY' => 'weekly',
2651
            'MONTHLY' => 'monthlyByDate',
2652
            'YEARLY' => 'yearly'
2653
        );
2654
        $sentTo = array('everyone' => true);
2655
        $calendar = Sabre\VObject\Reader::read($data);
2656
        $currentTimeZone = _api_get_timezone();
2657
        if (!empty($calendar->VEVENT)) {
2658
            foreach ($calendar->VEVENT as $event) {
2659
                $start = $event->DTSTART->getDateTime();
2660
                $end = $event->DTEND->getDateTime();
2661
                //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
2662
2663
                $startDateTime = api_get_local_time($start->format('Y-m-d H:i:s'), $currentTimeZone, $start->format('e'));
2664
                $endDateTime = api_get_local_time($end->format('Y-m-d H:i'), $currentTimeZone, $end->format('e'));
2665
                $title = api_convert_encoding((string)$event->summary, $charset, 'UTF-8');
2666
                $description = api_convert_encoding((string)$event->description, $charset, 'UTF-8');
2667
2668
                $id = $this->addEvent(
2669
                    $startDateTime,
2670
                    $endDateTime,
2671
                    'false',
2672
                    $title,
2673
                    $description,
2674
                    $sentTo
2675
                );
2676
2677
                $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
2678
2679
                //$attendee = (string)$event->attendee;
2680
                /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
2681
                $repeat = $event->RRULE;
2682
                if ($id && !empty($repeat)) {
2683
2684
                    $repeat = $repeat->getParts();
2685
                    $freq = $trans[$repeat['FREQ']];
2686
2687
                    if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
2688
                        // Check if datetime or just date (strlen == 8)
2689
                        if (strlen($repeat['UNTIL']) == 8) {
2690
                            // Fix the datetime format to avoid exception in the next step
2691
                            $repeat['UNTIL'] .= 'T000000';
2692
                        }
2693
                        $until = Sabre\VObject\DateTimeParser::parseDateTime($repeat['UNTIL'], new DateTimeZone($currentTimeZone));
2694
                        $until = $until->format('Y-m-d H:i');
2695
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $until, $attendee);
2696
                        $this->addRepeatedItem(
2697
                            $id,
2698
                            $freq,
2699
                            $until,
2700
                            $sentTo
2701
                        );
2702
                    }
2703
2704
                    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...
2705
                        /*$count = $repeat['COUNT'];
2706
                        $interval = $repeat['INTERVAL'];
2707
                        $endDate = null;
2708
                        switch($freq) {
2709
                            case 'daily':
2710
                                $start = api_strtotime($startDateTime);
2711
                                $date = new DateTime($startDateTime);
2712
                                $days = $count * $interval;
2713
                                var_dump($days);
2714
                                $date->add(new DateInterval("P".$days."D"));
2715
                                $endDate = $date->format('Y-m-d H:i');
2716
                                //$endDate = $count *
2717
                                for ($i = 0; $i < $count; $i++) {
2718
                                    $days = 86400 * 7
2719
                                }
2720
                            }
2721
                        }*/
2722
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
2723
                        /*$this->addRepeatedItem(
2724
                            $id,
2725
                            $freq,
2726
                            $endDate,
2727
                            $sentTo
2728
                        );*/
2729
                    }
2730
                }
2731
            }
2732
        }
2733
2734
        if (!empty($messages)) {
2735
            $messages = implode('<br /> ', $messages);
2736
        } else {
2737
            $messages = get_lang('NoAgendaItems');
2738
2739
        }
2740
2741
        return $messages;
2742
    }
2743
2744
    /**
2745
     * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]]
2746
     * @param $filter
2747
     * @return array
2748
     */
2749
    public function parseAgendaFilter($filter)
2750
    {
2751
        $everyone = false;
2752
        $groupId = null;
2753
        $userId = null;
2754
2755
        if ($filter == 'everyone') {
2756
            $everyone = true;
2757
        } else {
2758
            if (substr($filter, 0, 1) == 'G') {
2759
                $groupId = str_replace('GROUP:', '', $filter);
2760
            } else {
2761
                $userId = str_replace('USER:', '', $filter);
2762
            }
2763
        }
2764
        if (empty($userId) && empty($groupId)) {
2765
            $everyone = true;
2766
        }
2767
2768
        return array(
2769
            'everyone' => $everyone,
2770
            'users' => array($userId),
2771
            'groups' => array($groupId)
2772
        );
2773
    }
2774
2775
    /**
2776
     *	This function retrieves all the agenda items of all the courses the user is subscribed to
2777
     */
2778
    public static function get_myagendaitems($user_id, $courses_dbs, $month, $year)
2779
    {
2780
        $user_id = intval($user_id);
2781
2782
        $items = array();
2783
        $my_list = array();
2784
2785
        // get agenda-items for every course
2786
        foreach ($courses_dbs as $key => $array_course_info) {
2787
            //databases of the courses
2788
            $TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA);
2789
            $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
2790
2791
            $group_memberships = GroupManager :: get_group_ids($array_course_info["real_id"], $user_id);
2792
            $course_user_status = CourseManager::get_user_in_course_status($user_id, $array_course_info["code"]);
2793
            // if the user is administrator of that course we show all the agenda items
2794
            if ($course_user_status == '1') {
2795
                //echo "course admin";
2796
                $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
2797
							FROM ".$TABLEAGENDA." agenda,
2798
								 ".$TABLE_ITEMPROPERTY." ip
2799
							WHERE agenda.id = ip.ref
2800
							AND MONTH(agenda.start_date)='".$month."'
2801
							AND YEAR(agenda.start_date)='".$year."'
2802
							AND ip.tool='".TOOL_CALENDAR_EVENT."'
2803
							AND ip.visibility='1'
2804
							GROUP BY agenda.id
2805
							ORDER BY start_date ";
2806
            } else {
2807
                // if the user is not an administrator of that course
2808
                if (is_array($group_memberships) && count($group_memberships)>0) {
2809
                    $sqlquery = "SELECT	agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
2810
								FROM ".$TABLEAGENDA." agenda,
2811
									".$TABLE_ITEMPROPERTY." ip
2812
								WHERE agenda.id = ip.ref
2813
								AND MONTH(agenda.start_date)='".$month."'
2814
								AND YEAR(agenda.start_date)='".$year."'
2815
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
2816
								AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) )
2817
								AND ip.visibility='1'
2818
								ORDER BY start_date ";
2819
                } else {
2820
                    $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
2821
								FROM ".$TABLEAGENDA." agenda,
2822
									".$TABLE_ITEMPROPERTY." ip
2823
								WHERE agenda.id = ip.ref
2824
								AND MONTH(agenda.start_date)='".$month."'
2825
								AND YEAR(agenda.start_date)='".$year."'
2826
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
2827
								AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2828
								AND ip.visibility='1'
2829
								ORDER BY start_date ";
2830
                }
2831
            }
2832
            $result = Database::query($sqlquery);
2833
2834
            while ($item = Database::fetch_array($result, 'ASSOC')) {
2835
                $agendaday = -1;
2836
                if ($item['start_date'] != '0000-00-00 00:00:00') {
2837
                    $item['start_date'] = api_get_local_time($item['start_date']);
2838
                    $item['start_date_tms']  = api_strtotime($item['start_date']);
2839
                    $agendaday = date("j", $item['start_date_tms']);
2840
                }
2841
                if ($item['end_date'] != '0000-00-00 00:00:00') {
2842
                    $item['end_date'] = api_get_local_time($item['end_date']);
2843
                }
2844
2845
                $url  = api_get_path(WEB_CODE_PATH)."calendar/agenda.php?cidReq=".urlencode($array_course_info["code"])."&day=$agendaday&month=$month&year=$year#$agendaday";
2846
2847
                $item['url'] = $url;
2848
                $item['course_name'] = $array_course_info['title'];
2849
                $item['calendar_type'] = 'course';
2850
                $item['course_id'] = $array_course_info['course_id'];
2851
2852
                $my_list[$agendaday][] = $item;
2853
            }
2854
        }
2855
2856
        // sorting by hour for every day
2857
        $agendaitems = array ();
2858
        while (list ($agendaday, $tmpitems) = each($items)) {
2859
            if(!isset($agendaitems[$agendaday])) {
2860
                $agendaitems[$agendaday] = '';
2861
            }
2862
            sort($tmpitems);
2863
            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...
2864
                $agendaitems[$agendaday] .= $val;
2865
            }
2866
        }
2867
        return $my_list;
2868
    }
2869
2870
    /**
2871
     * This function retrieves one personal agenda item returns it.
2872
     * @param	array	The array containing existing events. We add to this array.
2873
     * @param	int		Day
2874
     * @param	int		Month
2875
     * @param	int		Year (4 digits)
2876
     * @param	int		Week number
2877
     * @param	string	Type of view (month_view, week_view, day_view)
2878
     * @return 	array	The results of the database query, or null if not found
2879
     */
2880
    public static function get_global_agenda_items($agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
2881
    {
2882
        $tbl_global_agenda = Database::get_main_table(
2883
            TABLE_MAIN_SYSTEM_CALENDAR
2884
        );
2885
        $month = intval($month);
2886
        $year = intval($year);
2887
        $week = intval($week);
2888
        $day = intval($day);
2889
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
2890
2891
        $current_access_url_id = api_get_current_access_url_id();
2892
2893
        if ($type == "month_view" or $type == "") {
2894
            // We are in month view
2895
            $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";
2896
        }
2897
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
2898 View Code Duplication
        if ($type == "week_view") { // we are in week view
2899
            $start_end_day_of_week = self::calculate_start_end_of_week($week, $year);
2900
            $start_day = $start_end_day_of_week['start']['day'];
2901
            $start_month = $start_end_day_of_week['start']['month'];
2902
            $start_year = $start_end_day_of_week['start']['year'];
2903
            $end_day = $start_end_day_of_week['end']['day'];
2904
            $end_month = $start_end_day_of_week['end']['month'];
2905
            $end_year = $start_end_day_of_week['end']['year'];
2906
            // in sql statements you have to use year-month-day for date calculations
2907
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
2908
            $start_filter = api_get_utc_datetime($start_filter);
2909
2910
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
2911
            $end_filter = api_get_utc_datetime($end_filter);
2912
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND  access_url_id = $current_access_url_id ";
2913
        }
2914
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
2915 View Code Duplication
        if ($type == "day_view") { // we are in day view
2916
            // we could use mysql date() function but this is only available from 4.1 and higher
2917
            $start_filter = $year."-".$month."-".$day." 00:00:00";
2918
            $start_filter = api_get_utc_datetime($start_filter);
2919
2920
            $end_filter = $year."-".$month."-".$day." 23:59:59";
2921
            $end_filter = api_get_utc_datetime($end_filter);
2922
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'  AND  access_url_id = $current_access_url_id";
2923
        }
2924
2925
        $result = Database::query($sql);
2926
2927
        while ($item = Database::fetch_array($result)) {
2928
2929
            if ($item['start_date'] != '0000-00-00 00:00:00') {
2930
                $item['start_date'] = api_get_local_time($item['start_date']);
2931
                $item['start_date_tms'] = api_strtotime($item['start_date']);
2932
            }
2933
            if ($item['end_date'] != '0000-00-00 00:00:00') {
2934
                $item['end_date'] = api_get_local_time($item['end_date']);
2935
            }
2936
2937
            // we break the date field in the database into a date and a time part
2938
            $agenda_db_date = explode(" ", $item['start_date']);
2939
            $date = $agenda_db_date[0];
2940
            $time = $agenda_db_date[1];
2941
            // we divide the date part into a day, a month and a year
2942
            $agendadate = explode("-", $date);
2943
            $year = intval($agendadate[0]);
2944
            $month = intval($agendadate[1]);
2945
            $day = intval($agendadate[2]);
2946
            // we divide the time part into hour, minutes, seconds
2947
            $agendatime = explode(":", $time);
2948
            $hour = $agendatime[0];
2949
            $minute = $agendatime[1];
2950
            $second = $agendatime[2];
2951
2952
            if ($type == 'month_view') {
2953
                $item['calendar_type'] = 'global';
2954
                $agendaitems[$day][] = $item;
2955
                continue;
2956
            }
2957
2958
            $start_time = api_format_date(
2959
                $item['start_date'],
2960
                TIME_NO_SEC_FORMAT
2961
            );
2962
            $end_time = '';
2963
            if ($item['end_date'] != '0000-00-00 00:00:00') {
2964
                $end_time = ' - '.api_format_date(
2965
                        $item['end_date'],
2966
                        DATE_TIME_FORMAT_LONG
2967
                    );
2968
            }
2969
2970
            // if the student has specified a course we a add a link to that course
2971 View Code Duplication
            if ($item['course'] <> "") {
2972
                $url = api_get_path(
2973
                        WEB_CODE_PATH
2974
                    )."admin/agenda.php?cidReq=".urlencode(
2975
                        $item['course']
2976
                    )."&day=$day&month=$month&year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
2977
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
2978
            } else {
2979
                $course_link = "";
2980
            }
2981
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
2982
            // if we have a day_view we use a half hour as index => key 33 = 16h30
2983
            if ($type !== "day_view") {
2984
                // This is the array construction for the WEEK or MONTH view
2985
                //Display the Agenda global in the tab agenda (administrator)
2986
                $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
2987
                $agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
2988
                $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
2989
            } else {
2990
                // this is the array construction for the DAY view
2991
                $halfhour = 2 * $agendatime['0'];
2992
                if ($agendatime['1'] >= '30') {
2993
                    $halfhour = $halfhour + 1;
2994
                }
2995
                if (!is_array($agendaitems[$halfhour])) {
2996
                    $content = $agendaitems[$halfhour];
2997
                }
2998
                $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
2999
                        'GlobalEvent'
3000
                    ).":  </b>".$item['title']."</div>";
3001
            }
3002
        }
3003
3004
        return $agendaitems;
3005
    }
3006
3007
    /**
3008
     * This function retrieves all the personal agenda items and add them to the agenda items found by the other functions.
3009
     */
3010
    public static function get_personal_agenda_items($user_id, $agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
3011
    {
3012
        $tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
3013
        $user_id = intval($user_id);
3014
3015
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3016
        if ($type == "month_view" or $type == "") {
3017
            // we are in month view
3018
            $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."'  ORDER BY date ASC";
3019
        }
3020
3021
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3022
        // we are in week view
3023 View Code Duplication
        if ($type == "week_view") {
3024
            $start_end_day_of_week = self::calculate_start_end_of_week($week, $year);
3025
            $start_day = $start_end_day_of_week['start']['day'];
3026
            $start_month = $start_end_day_of_week['start']['month'];
3027
            $start_year = $start_end_day_of_week['start']['year'];
3028
            $end_day = $start_end_day_of_week['end']['day'];
3029
            $end_month = $start_end_day_of_week['end']['month'];
3030
            $end_year = $start_end_day_of_week['end']['year'];
3031
            // in sql statements you have to use year-month-day for date calculations
3032
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3033
            $start_filter  = api_get_utc_datetime($start_filter);
3034
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3035
            $end_filter  = api_get_utc_datetime($end_filter);
3036
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3037
        }
3038
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3039 View Code Duplication
        if ($type == "day_view") {
3040
            // we are in day view
3041
            // we could use mysql date() function but this is only available from 4.1 and higher
3042
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3043
            $start_filter  = api_get_utc_datetime($start_filter);
3044
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3045
            $end_filter  = api_get_utc_datetime($end_filter);
3046
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3047
        }
3048
3049
        $result = Database::query($sql);
3050
        while ($item = Database::fetch_array($result, 'ASSOC')) {
3051
3052
            $time_minute 	= api_convert_and_format_date($item['date'], TIME_NO_SEC_FORMAT);
3053
            $item['date']   = api_get_local_time($item['date']);
3054
            $item['start_date_tms']  = api_strtotime($item['date']);
3055
            $item['content'] = $item['text'];
3056
3057
            // we break the date field in the database into a date and a time part
3058
            $agenda_db_date = explode(" ", $item['date']);
3059
            $date = $agenda_db_date[0];
3060
            $time = $agenda_db_date[1];
3061
            // we divide the date part into a day, a month and a year
3062
            $agendadate = explode("-", $item['date']);
3063
            $year = intval($agendadate[0]);
3064
            $month = intval($agendadate[1]);
3065
            $day = intval($agendadate[2]);
3066
            // we divide the time part into hour, minutes, seconds
3067
            $agendatime = explode(":", $time);
3068
3069
            $hour = $agendatime[0];
3070
            $minute = $agendatime[1];
3071
            $second = $agendatime[2];
3072
3073
            if ($type == 'month_view') {
3074
                $item['calendar_type']  = 'personal';
3075
                $item['start_date']  	= $item['date'];
3076
                $agendaitems[$day][] 	= $item;
3077
                continue;
3078
            }
3079
3080
            // if the student has specified a course we a add a link to that course
3081 View Code Duplication
            if ($item['course'] <> "") {
3082
                $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
3083
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
3084
            } else {
3085
                $course_link = "";
3086
            }
3087
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3088
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3089
            if ($type !== "day_view") {
3090
                // This is the array construction for the WEEK or MONTH view
3091
3092
                //Display events in agenda
3093
                $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 />";
3094
3095
            } else {
3096
                // this is the array construction for the DAY view
3097
                $halfhour = 2 * $agendatime['0'];
3098
                if ($agendatime['1'] >= '30') {
3099
                    $halfhour = $halfhour +1;
3100
                }
3101
3102
                //Display events by list
3103
                $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>";
3104
            }
3105
        }
3106
        return $agendaitems;
3107
    }
3108
3109
3110
    /**
3111
     * Show the monthcalender of the given month
3112
     * @param	array	Agendaitems
3113
     * @param	int	Month number
3114
     * @param	int	Year number
3115
     * @param	array	Array of strings containing long week day names (deprecated, you can send an empty array instead)
3116
     * @param	string	The month name
3117
     * @return	void	Direct output
3118
     */
3119
    public static function display_mymonthcalendar($user_id, $agendaitems, $month, $year, $weekdaynames = array(), $monthName, $show_content = true)
3120
    {
3121
        global $DaysShort, $course_path;
3122
        //Handle leap year
3123
        $numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
3124 View Code Duplication
        if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0))
3125
            $numberofdays[2] = 29;
3126
        //Get the first day of the month
3127
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
3128
        //Start the week on monday
3129
        $startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
3130
        $g_cc = (isset($_GET['courseCode'])?$_GET['courseCode']:'');
3131
3132
        $prev_icon = Display::return_icon('action_prev.png',get_lang('Previous'));
3133
        $next_icon = Display::return_icon('action_next.png',get_lang('Next'));
3134
3135
        $next_month = ($month == 1 ? 12 : $month -1);
3136
        $prev_month = ($month == 12 ? 1 : $month +1);
3137
3138
        $next_year = ($month == 1 ? $year -1 : $year);
3139
        $prev_year = ($month == 12 ? $year +1 : $year);
3140
3141
        if ($show_content)  {
3142
            $back_url = Display::url($prev_icon, api_get_self()."?coursePath=".urlencode($course_path)."&courseCode=".Security::remove_XSS($g_cc)."&action=view&view=month&month=".$next_month."&year=".$next_year);
3143
            $next_url = Display::url($next_icon, api_get_self()."?coursePath=".urlencode($course_path)."&courseCode=".Security::remove_XSS($g_cc)."&action=view&view=month&month=".$prev_month."&year=".$prev_year);
3144
        } else {
3145
            $back_url = Display::url($prev_icon, '', array('onclick'=>"load_calendar('".$user_id."','".$next_month."', '".$next_year."'); "));
3146
            $next_url = Display::url($next_icon, '', array('onclick'=>"load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); "));
3147
        }
3148
3149
        echo '<table id="agenda_list"><tr>';
3150
        echo '<th width="10%">'.$back_url.'</th>';
3151
        echo '<th width="80%" colspan="5"><br /><h3>'.$monthName." ".$year.'</h3></th>';
3152
        echo '<th width="10%">'.$next_url.'</th>';
3153
3154
        echo '</tr>';
3155
3156
        echo '<tr>';
3157 View Code Duplication
        for ($ii = 1; $ii < 8; $ii ++) {
3158
            echo '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
3159
        }
3160
        echo '</tr>';
3161
3162
        $curday = -1;
3163
        $today = getdate();
3164
        while ($curday <= $numberofdays[$month]) {
3165
            echo "<tr>";
3166
            for ($ii = 0; $ii < 7; $ii ++) {
3167
                if (($curday == -1) && ($ii == $startdayofweek)) {
3168
                    $curday = 1;
3169
                }
3170
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
3171
                    $bgcolor = $class = 'class="days_week"';
3172
                    $dayheader = Display::div($curday, array('class'=>'agenda_day'));
3173 View Code Duplication
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
3174
                        $class = "class=\"days_today\" style=\"width:10%;\"";
3175
                    }
3176
3177
                    echo "<td ".$class.">".$dayheader;
3178
3179
                    if (!empty($agendaitems[$curday])) {
3180
                        $items =  $agendaitems[$curday];
3181
                        $items =  msort($items, 'start_date_tms');
3182
3183
                        foreach($items  as $value) {
3184
                            $value['title'] = Security::remove_XSS($value['title']);
3185
                            $start_time = api_format_date($value['start_date'], TIME_NO_SEC_FORMAT);
3186
                            $end_time = '';
3187
3188
                            if (!empty($value['end_date']) && $value['end_date'] != '0000-00-00 00:00:00') {
3189
                                $end_time    = '-&nbsp;<i>'.api_format_date($value['end_date'], DATE_TIME_FORMAT_LONG).'</i>';
3190
                            }
3191
                            $complete_time = '<i>'.api_format_date($value['start_date'], DATE_TIME_FORMAT_LONG).'</i>&nbsp;'.$end_time;
3192
                            $time = '<i>'.$start_time.'</i>';
3193
3194
                            switch($value['calendar_type']) {
3195
                                case 'personal':
3196
                                    $bg_color = '#D0E7F4';
3197
                                    $icon = Display::return_icon('user.png', get_lang('MyAgenda'), array(), ICON_SIZE_SMALL);
3198
                                    break;
3199
                                case 'global':
3200
                                    $bg_color = '#FFBC89';
3201
                                    $icon = Display::return_icon('view_remove.png', get_lang('GlobalEvent'), array(), ICON_SIZE_SMALL);
3202
                                    break;
3203
                                case 'course':
3204
                                    $bg_color = '#CAFFAA';
3205
                                    $icon_name = 'course.png';
3206
                                    if (!empty($value['session_id'])) {
3207
                                        $icon_name = 'session.png';
3208
                                    }
3209
                                    if ($show_content) {
3210
                                        $icon = Display::url(Display::return_icon($icon_name, $value['course_name'].' '.get_lang('Course'), array(), ICON_SIZE_SMALL), $value['url']);
3211 View Code Duplication
                                    } else {
3212
                                        $icon = Display::return_icon($icon_name, $value['course_name'].' '.get_lang('Course'), array(), ICON_SIZE_SMALL);
3213
                                    }
3214
                                    break;
3215
                                default:
3216
                                    break;
3217
                            }
3218
3219
                            $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
3220
3221
                            if ($show_content) {
3222
3223
                                //Setting a personal event to green
3224
                                $icon = Display::div($icon, array('style'=>'float:right'));
3225
3226
                                $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
3227
3228
                                //Link to bubble
3229
                                $url = Display::url(cut($value['title'], 40), '#', array('id'=>$link, 'class'=>'opener'));
3230
                                $result .= $time.' '.$icon.' '.Display::div($url);
3231
3232
                                //Hidden content
3233
                                $content = Display::div($icon.Display::tag('h2', $value['course_name']).'<hr />'.Display::tag('h3', $value['title']).$complete_time.'<hr />'.Security::remove_XSS($value['content']));
3234
3235
                                //Main div
3236
                                $result .= Display::div($content, array('id'=>'main_'.$link, 'class' => 'dialog', 'style' => 'display:none'));
3237
                                $result .= '</div>';
3238
                                echo $result;
3239
                                //echo Display::div($content, array('id'=>'main_'.$value['calendar_type'].'_'.$value['id'], 'class' => 'dialog'));
3240
                            } else {
3241
                                echo $result .= $icon.'</div>';
3242
                            }
3243
                        }
3244
                    }
3245
                    echo "</td>";
3246
                    $curday ++;
3247
                } else {
3248
                    echo "<td></td>";
3249
                }
3250
            }
3251
            echo "</tr>";
3252
        }
3253
        echo "</table>";
3254
    }
3255
3256
    /**
3257
     * Get personal agenda items between two dates (=all events from all registered courses)
3258
     * @param	int		user ID of the user
3259
     * @param	string	Optional start date in datetime format (if no start date is given, uses today)
3260
     * @param	string	Optional end date in datetime format (if no date is given, uses one year from now)
3261
     * @return	array	Array of events ordered by start date, in
3262
     * [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
3263
     * where datestart and dateend are in yyyyMMddhhmmss format.
3264
     * @TODO Implement really personal events (from user DB) and global events (from main DB)
3265
     */
3266
    public static function get_personal_agenda_items_between_dates($user_id, $date_start='', $date_end='')
3267
    {
3268
        $items = array ();
3269
        if ($user_id != strval(intval($user_id))) { return $items; }
3270
        if (empty($date_start)) { $date_start = date('Y-m-d H:i:s');}
3271
        if (empty($date_end))   { $date_end = date('Y-m-d H:i:s',mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1));}
3272
        $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
3273
        if(!preg_match($expr,$date_start)) { return $items; }
3274
        if(!preg_match($expr,$date_end)) { return $items; }
3275
3276
        // get agenda-items for every course
3277
        $courses = api_get_user_courses($user_id,false);
3278
        foreach ($courses as $id => $course) {
3279
            $c = api_get_course_info_by_id($course['real_id']);
3280
            //databases of the courses
3281
            $t_a = Database :: get_course_table(TABLE_AGENDA, $course['db']);
3282
            $t_ip = Database :: get_course_table(TABLE_ITEM_PROPERTY, $course['db']);
3283
            // get the groups to which the user belong
3284
            $group_memberships = GroupManager :: get_group_ids($course['db'], $user_id);
3285
            // if the user is administrator of that course we show all the agenda items
3286
            if ($course['status'] == '1') {
3287
                //echo "course admin";
3288
                $sqlquery = "SELECT ".
3289
                    " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3290
                    " FROM ".$t_a." agenda, ".
3291
                    $t_ip." ip ".
3292
                    " WHERE agenda.id = ip.ref ".
3293
                    " AND agenda.start_date>='$date_start' ".
3294
                    " AND agenda.end_date<='$date_end' ".
3295
                    " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3296
                    " AND ip.visibility='1' ".
3297
                    " GROUP BY agenda.id ".
3298
                    " ORDER BY start_date ";
3299
            } else {
3300
                // if the user is not an administrator of that course, then...
3301
                if (is_array($group_memberships) && count($group_memberships)>0)
3302
                {
3303
                    $sqlquery = "SELECT " .
3304
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3305
                        " FROM ".$t_a." agenda, ".
3306
                        $t_ip." ip ".
3307
                        " WHERE agenda.id = ip.ref ".
3308
                        " AND agenda.start_date>='$date_start' ".
3309
                        " AND agenda.end_date<='$date_end' ".
3310
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3311
                        " AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) ) ".
3312
                        " AND ip.visibility='1' ".
3313
                        " ORDER BY start_date ";
3314
                } else {
3315
                    $sqlquery = "SELECT ".
3316
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3317
                        " FROM ".$t_a." agenda, ".
3318
                        $t_ip." ip ".
3319
                        " WHERE agenda.id = ip.ref ".
3320
                        " AND agenda.start_date>='$date_start' ".
3321
                        " AND agenda.end_date<='$date_end' ".
3322
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3323
                        " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
3324
                        " AND ip.visibility='1' ".
3325
                        " ORDER BY start_date ";
3326
                }
3327
            }
3328
3329
            $result = Database::query($sqlquery);
3330
            while ($item = Database::fetch_array($result)) {
3331
                $agendaday = date("j",strtotime($item['start_date']));
3332
                $month = date("n",strtotime($item['start_date']));
3333
                $year = date("Y",strtotime($item['start_date']));
3334
                $URL = api_get_path(WEB_PATH)."main/calendar/agenda.php?cidReq=".urlencode($course["code"])."&day=$agendaday&month=$month&year=$year#$agendaday";
3335
                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...
3336
                $start_date = $year.$month.$day.$hour.$min;
3337
                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...
3338
                $end_date = $year.$month.$day.$hour.$min;
3339
3340
                $items[] = array(
3341
                    'datestart'=>$start_date,
3342
                    'dateend'=>$end_date,
3343
                    'title'=>$item['title'],
3344
                    'link'=>$URL,
3345
                    'coursetitle'=>$c['name'],
3346
                );
3347
            }
3348
        }
3349
        return $items;
3350
    }
3351
3352
3353
    /**
3354
     * This function retrieves one personal agenda item returns it.
3355
     * @param	int	The agenda item ID
3356
     * @return 	array	The results of the database query, or null if not found
3357
     */
3358
    public static function get_personal_agenda_item($id)
3359
    {
3360
        $tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
3361
        $id = intval($id);
3362
        // make sure events of the personal agenda can only be seen by the user himself
3363
        $user = api_get_user_id();
3364
        $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE id=".$id." AND user = ".$user;
3365
        $result = Database::query($sql);
3366
        if(Database::num_rows($result)==1) {
3367
            $item = Database::fetch_array($result);
3368
        } else {
3369
            $item = null;
3370
        }
3371
        return $item;
3372
    }
3373
3374
3375
    /**
3376
     * This function calculates the startdate of the week (monday)
3377
     * and the enddate of the week (sunday)
3378
     * and returns it as an array
3379
     */
3380
    public static function calculate_start_end_of_week($week_number, $year)
3381
    {
3382
        // determine the start and end date
3383
        // step 1: we calculate a timestamp for a day in this week
3384
        $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
3385
        // step 2: we which day this is (0=sunday, 1=monday, ...)
3386
        $number_day_in_week = date('w', $random_day_in_week);
3387
        // step 3: we calculate the timestamp of the monday of the week we are in
3388
        $start_timestamp = $random_day_in_week - (($number_day_in_week -1) * 24 * 60 * 60);
3389
        // step 4: we calculate the timestamp of the sunday of the week we are in
3390
        $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week +1) * 24 * 60 * 60) - 3600;
3391
        // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
3392
        $start_day = date('j', $start_timestamp);
3393
        $start_month = date('n', $start_timestamp);
3394
        $start_year = date('Y', $start_timestamp);
3395
        $end_day = date('j', $end_timestamp);
3396
        $end_month = date('n', $end_timestamp);
3397
        $end_year = date('Y', $end_timestamp);
3398
        $start_end_array['start']['day'] = $start_day;
3399
        $start_end_array['start']['month'] = $start_month;
3400
        $start_end_array['start']['year'] = $start_year;
3401
        $start_end_array['end']['day'] = $end_day;
3402
        $start_end_array['end']['month'] = $end_month;
3403
        $start_end_array['end']['year'] = $end_year;
3404
        return $start_end_array;
3405
    }
3406
3407
    /**
3408
     * @return bool
3409
     */
3410
    public function getIsAllowedToEdit()
3411
    {
3412
        return $this->isAllowedToEdit;
3413
    }
3414
3415
    /**
3416
     * @param bool $isAllowedToEdit
3417
     */
3418
    public function setIsAllowedToEdit($isAllowedToEdit)
3419
    {
3420
        $this->isAllowedToEdit = $isAllowedToEdit;
3421
    }
3422
}
3423