Completed
Push — 1.10.x ( 9bb86d...118208 )
by
unknown
118:22 queued 63:22
created

Agenda::getIsAllowedToEdit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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