Test Setup Failed
Push — master ( ec638a...cb9435 )
by Julito
51:10
created

Agenda::getSessionEvents()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 17
nc 3
nop 5
dl 0
loc 23
rs 9.0856
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
    /** @var array */
20
    private $sessionInfo;
21
    /** @var string */
22
    public $comment;
23
    /** @var bool */
24
    private $isAllowedToEdit;
25
    public $eventStudentPublicationColor;
26
27
    /**
28
     * Constructor
29
     * @param string $type
30
     * @param int $senderId Optional The user sender ID
31
     * @param int $courseId Opitonal. The course ID
32
     * @param int $sessionId Optional The session ID
33
     */
34
    public function __construct(
35
        $type,
36
        $senderId = 0,
37
        $courseId = 0,
38
        $sessionId = 0
39
    ) {
40
        // Table definitions
41
        $this->tbl_global_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
42
        $this->tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
43
        $this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
44
        $this->table_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
45
46
        $this->setType($type);
47
        $this->setSenderId($senderId ?: api_get_user_id());
48
        $isAllowToEdit = false;
49
50
        switch ($type) {
51
            case 'course':
52
                $sessionId = $sessionId ?: api_get_session_id();
53
                $sessionInfo = api_get_session_info($sessionId);
54
                $this->setSessionId($sessionId);
55
                $this->setSessionInfo($sessionInfo);
56
57
                // Setting the course object if we are in a course
58
                $courseInfo = api_get_course_info_by_id($courseId);
59
                if (!empty($courseInfo)) {
60
                    $this->set_course($courseInfo);
61
                }
62
63
                // Check if teacher
64
                if (empty($sessionId)) {
65
                    $isAllowToEdit = api_is_allowed_to_edit(false, true);
66
                } else {
67
                    $isAllowToEdit = api_is_allowed_to_session_edit(
68
                        false,
69
                        true
70
                    );
71
                }
72
73
                // Check
74
                if (api_get_course_setting('allow_user_edit_agenda') && api_is_allowed_in_course()) {
75
                    $isAllowToEdit = true;
76
                }
77
78
                $groupId = api_get_group_id();
79
                if (!empty($groupId)) {
80
                    $groupInfo = GroupManager::get_group_properties($groupId);
81
                    $isGroupAccess = GroupManager::user_has_access(
82
                            api_get_user_id(),
83
                            $groupInfo['iid'],
84
                            GroupManager::GROUP_TOOL_CALENDAR
85
                        ) &&
86
                        GroupManager::is_tutor_of_group(
87
                            api_get_user_id(),
88
                            $groupInfo
89
                        );
90
                    if ($isGroupAccess) {
91
                        $isAllowToEdit = true;
92
                    } else {
93
                        $isAllowToEdit = false;
94
                    }
95
                }
96
97
                break;
98
            case 'admin':
99
                $isAllowToEdit = api_is_platform_admin();
100
                break;
101
            case 'personal':
102
                $isAllowToEdit = !api_is_anonymous();
103
                break;
104
        }
105
106
        $this->setIsAllowedToEdit($isAllowToEdit);
0 ignored issues
show
Bug introduced by
It seems like $isAllowToEdit defined by api_is_allowed_to_session_edit(false, true) on line 67 can also be of type null; however, Agenda::setIsAllowedToEdit() does only seem to accept boolean, 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...
107
        $this->events = [];
108
109
        // Event colors
110
        $this->event_platform_color = 'red'; //red
111
        $this->event_course_color = '#458B00'; //green
112
        $this->event_group_color = '#A0522D'; //siena
113
        $this->event_session_color = '#00496D'; // kind of green
114
        $this->eventOtherSessionColor = '#999';
115
        $this->event_personal_color = 'steel blue'; //steel blue
116
        $this->eventStudentPublicationColor = '#FF8C00'; //DarkOrange
117
    }
118
119
    /**
120
     * @param int $senderId
121
     */
122
    public function setSenderId($senderId)
123
    {
124
        $this->senderId = intval($senderId);
125
    }
126
127
    /**
128
     * @return int
129
     */
130
    public function getSenderId()
131
    {
132
        return $this->senderId;
133
    }
134
135
    /**
136
     * @param string $type can be 'personal', 'admin'  or  'course'
137
     */
138
    public function setType($type)
139
    {
140
        $typeList = $this->getTypes();
141
        if (in_array($type, $typeList)) {
142
            $this->type = $type;
143
        }
144
    }
145
146
    /**
147
     * @param int $id
148
     */
149
    public function setSessionId($id)
150
    {
151
        $this->sessionId = intval($id);
152
    }
153
154
    /**
155
     * @param array $sessionInfo
156
     */
157
    public function setSessionInfo($sessionInfo)
158
    {
159
        $this->sessionInfo = $sessionInfo;
160
    }
161
162
    /**
163
     * @return int $id
164
     */
165
    public function getSessionId()
166
    {
167
        return $this->sessionId;
168
    }
169
170
    /**
171
     * @param array $courseInfo
172
     */
173
    public function set_course($courseInfo)
174
    {
175
        $this->course = $courseInfo;
176
    }
177
178
    /**
179
     * @return array
180
     */
181
    public function getTypes()
182
    {
183
        return $this->types;
184
    }
185
186
    /**
187
     * Adds an event to the calendar
188
     * @param string $start datetime format: 2012-06-14 09:00:00
189
     * @param string $end datetime format: 2012-06-14 09:00:00
190
     * @param string $allDay (true, false)
191
     * @param string $title
192
     * @param string $content
193
     * @param array $usersToSend array('everyone') or a list of user/group ids
194
     * @param bool $addAsAnnouncement event as a *course* announcement
195
     * @param int $parentEventId
196
     * @param array $attachmentArray array of $_FILES['']
197
     * @param array $attachmentCommentList
198
     * @param string $eventComment
199
     * @param string $color
200
     *
201
     * @return int
202
     */
203
    public function addEvent(
204
        $start,
205
        $end,
206
        $allDay,
207
        $title,
208
        $content,
209
        $usersToSend = array(),
210
        $addAsAnnouncement = false,
211
        $parentEventId = null,
212
        $attachmentArray = array(),
213
        $attachmentCommentList = array(),
214
        $eventComment = null,
215
        $color = ''
216
    ) {
217
        $start = api_get_utc_datetime($start);
218
        $end = api_get_utc_datetime($end);
219
        $allDay = isset($allDay) && $allDay === 'true' ? 1 : 0;
220
        $id = null;
221
222
        switch ($this->type) {
223
            case 'personal':
224
                $attributes = array(
225
                    'user' => api_get_user_id(),
226
                    'title' => $title,
227
                    'text' => $content,
228
                    'date' => $start,
229
                    'enddate' => $end,
230
                    'all_day' => $allDay,
231
                    'color' => $color
232
                );
233
234
                $id = Database::insert(
235
                    $this->tbl_personal_agenda,
236
                    $attributes
237
                );
238
                break;
239
            case 'course':
240
                $attributes = array(
241
                    'title' => $title,
242
                    'content' => $content,
243
                    'start_date' => $start,
244
                    'end_date' => $end,
245
                    'all_day' => $allDay,
246
                    'session_id' => $this->getSessionId(),
247
                    'c_id' => $this->course['real_id'],
248
                    'comment' => $eventComment,
249
                    'color' => $color
250
                );
251
252
                if (!empty($parentEventId)) {
253
                    $attributes['parent_event_id'] = $parentEventId;
254
                }
255
256
                $senderId = $this->getSenderId();
257
                $sessionId = $this->getSessionId();
258
259
                // Simple course event.
260
                $id = Database::insert($this->tbl_course_agenda, $attributes);
261
262
                if ($id) {
263
                    $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
264
                    Database::query($sql);
265
266
                    $groupId = api_get_group_id();
267
                    $groupIid = 0;
268
                    if ($groupId) {
269
                        $groupInfo = GroupManager::get_group_properties(
270
                            $groupId
271
                        );
272
                        if ($groupInfo) {
273
                            $groupIid = $groupInfo['iid'];
274
                        }
275
                    }
276
277
                    if (!empty($usersToSend)) {
278
                        $sendTo = $this->parseSendToArray($usersToSend);
279
280
                        if ($sendTo['everyone']) {
281
                            api_item_property_update(
282
                                $this->course,
283
                                TOOL_CALENDAR_EVENT,
284
                                $id,
285
                                'AgendaAdded',
286
                                $senderId,
287
                                $groupIid,
288
                                '',
289
                                $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 217 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
290
                                $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 218 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
291
                                $sessionId
292
                            );
293
                            api_item_property_update(
294
                                $this->course,
295
                                TOOL_CALENDAR_EVENT,
296
                                $id,
297
                                'visible',
298
                                $senderId,
299
                                $groupIid,
300
                                '',
301
                                $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 217 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
302
                                $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 218 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
303
                                $sessionId
304
                            );
305
                        } else {
306
                            // Storing the selected groups
307
                            if (!empty($sendTo['groups'])) {
308
                                foreach ($sendTo['groups'] as $group) {
309
                                    $groupIidItem = 0;
310
                                    if ($group) {
311
                                        $groupInfo = GroupManager::get_group_properties(
312
                                            $group
313
                                        );
314
                                        if ($groupInfo) {
315
                                            $groupIidItem = $groupInfo['iid'];
316
                                        }
317
                                    }
318
319
                                    api_item_property_update(
320
                                        $this->course,
321
                                        TOOL_CALENDAR_EVENT,
322
                                        $id,
323
                                        'AgendaAdded',
324
                                        $senderId,
325
                                        $groupIidItem,
326
                                        0,
327
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 217 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
328
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 218 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
329
                                        $sessionId
330
                                    );
331
332
                                    api_item_property_update(
333
                                        $this->course,
334
                                        TOOL_CALENDAR_EVENT,
335
                                        $id,
336
                                        'visible',
337
                                        $senderId,
338
                                        $groupIidItem,
339
                                        0,
340
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 217 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
341
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 218 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
342
                                        $sessionId
343
                                    );
344
                                }
345
                            }
346
347
                            // storing the selected users
348
                            if (!empty($sendTo['users'])) {
349
                                foreach ($sendTo['users'] as $userId) {
350
                                    api_item_property_update(
351
                                        $this->course,
352
                                        TOOL_CALENDAR_EVENT,
353
                                        $id,
354
                                        'AgendaAdded',
355
                                        $senderId,
356
                                        $groupIid,
357
                                        $userId,
358
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 217 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
359
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 218 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
360
                                        $sessionId
361
                                    );
362
363
                                    api_item_property_update(
364
                                        $this->course,
365
                                        TOOL_CALENDAR_EVENT,
366
                                        $id,
367
                                        'visible',
368
                                        $senderId,
369
                                        $groupIid,
370
                                        $userId,
371
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 217 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
372
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 218 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
373
                                        $sessionId
374
                                    );
375
                                }
376
                            }
377
                        }
378
                    }
379
380
                    // Add announcement.
381
                    if ($addAsAnnouncement) {
382
                        $this->storeAgendaEventAsAnnouncement(
383
                            $id,
384
                            $usersToSend
385
                        );
386
                    }
387
388
                    // Add attachment.
389 View Code Duplication
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
390
                        $counter = 0;
391
                        foreach ($attachmentArray as $attachmentItem) {
392
                            $this->addAttachment(
393
                                $id,
394
                                $attachmentItem,
395
                                $attachmentCommentList[$counter],
396
                                $this->course
397
                            );
398
                            $counter++;
399
                        }
400
                    }
401
                }
402
                break;
403
            case 'admin':
404
                if (api_is_platform_admin()) {
405
                    $attributes = array(
406
                        'title' => $title,
407
                        'content' => $content,
408
                        'start_date' => $start,
409
                        'end_date' => $end,
410
                        'all_day' => $allDay,
411
                        'access_url_id' => api_get_current_access_url_id()
412
                    );
413
414
                    $id = Database::insert(
415
                        $this->tbl_global_agenda,
416
                        $attributes
417
                    );
418
                }
419
                break;
420
        }
421
422
        return $id;
423
    }
424
425
    /**
426
     * @param int $eventId
427
     * @param int $courseId
428
     *
429
     * @return array
430
     */
431
    public function getRepeatedInfoByEvent($eventId, $courseId)
432
    {
433
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
434
        $eventId = intval($eventId);
435
        $courseId = intval($courseId);
436
        $sql = "SELECT * FROM $repeatTable
437
                WHERE c_id = $courseId AND cal_id = $eventId";
438
        $res = Database::query($sql);
439
        $repeatInfo = array();
440
        if (Database::num_rows($res) > 0) {
441
            $repeatInfo = Database::fetch_array($res, 'ASSOC');
442
        }
443
444
        return $repeatInfo;
445
    }
446
447
    /**
448
     * @param int $eventId
449
     * @param string $type
450
     * @param string $end in local time
451
     * @param array $sentTo
452
     *
453
     * @return bool
454
     */
455
    public function addRepeatedItem($eventId, $type, $end, $sentTo = array())
456
    {
457
        $t_agenda = Database::get_course_table(TABLE_AGENDA);
458
        $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
459
460
        if (empty($this->course)) {
461
            return false;
462
        }
463
464
        $course_id = $this->course['real_id'];
465
        $eventId = intval($eventId);
466
467
        $sql = "SELECT title, content, start_date, end_date, all_day
468
                FROM $t_agenda
469
                WHERE c_id = $course_id AND id = $eventId";
470
        $res = Database::query($sql);
471
472
        if (Database::num_rows($res) !== 1) {
473
            return false;
474
        }
475
476
        $row = Database::fetch_array($res);
477
        $origStartDate = api_strtotime($row['start_date'], 'UTC');
478
        $origEndDate = api_strtotime($row['end_date'], 'UTC');
479
        $diff = $origEndDate - $origStartDate;
480
481
        $title = $row['title'];
482
        $content = $row['content'];
483
        $allDay = $row['all_day'];
484
485
        $now = time();
486
        $type = Database::escape_string($type);
487
        $end = api_strtotime($end);
488
489
        if (1 <= $end && $end <= 500) {
490
            // We assume that, with this type of value, the user actually gives a count of repetitions
491
            //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
492
            switch ($type) {
493
                case 'daily':
494
                    $end = $origStartDate + (86400 * $end);
495
                    break;
496
                case 'weekly':
497
                    $end = $this->addWeek($origStartDate, $end);
498
                    break;
499
                case 'monthlyByDate':
500
                    $end = $this->addMonth($origStartDate, $end);
501
                    break;
502
                case 'monthlyByDay':
503
                    //TODO
504
                    break;
505
                case 'monthlyByDayR':
506
                    //TODO
507
                    break;
508
                case 'yearly':
509
                    $end = $this->addYear($origStartDate, $end);
510
                    break;
511
            }
512
        }
513
514
        $typeList = array(
515
            'daily',
516
            'weekly',
517
            'monthlyByDate',
518
            'monthlyByDay',
519
            'monthlyByDayR',
520
            'yearly'
521
        );
522
523
        // The event has to repeat *in the future*. We don't allow repeated
524
        // events in the past
525
        if ($end > $now && in_array($type, $typeList)) {
526
            $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
527
                    VALUES ($course_id, '$eventId', '$type', '$end')";
528
            Database::query($sql);
529
530
            switch ($type) {
531
                // @todo improve loop.
532 View Code Duplication
                case 'daily':
533
                    for ($i = $origStartDate + 86400; $i <= $end; $i += 86400) {
534
                        $start = date('Y-m-d H:i:s', $i);
535
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
536
                        $this->addEvent(
537
                            $start,
538
                            $repeatEnd,
539
                            $allDay,
540
                            $title,
541
                            $content,
542
                            $sentTo,
543
                            false,
544
                            $eventId
545
                        );
546
                    }
547
                    break;
548 View Code Duplication
                case 'weekly':
549
                    for ($i = $origStartDate + 604800; $i <= $end; $i += 604800) {
550
                        $start = date('Y-m-d H:i:s', $i);
551
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
552
                        $this->addEvent(
553
                            $start,
554
                            $repeatEnd,
555
                            $allDay,
556
                            $title,
557
                            $content,
558
                            $sentTo,
559
                            false,
560
                            $eventId
561
                        );
562
                    }
563
                    break;
564 View Code Duplication
                case 'monthlyByDate':
565
                    $next_start = $this->addMonth($origStartDate);
566
                    while ($next_start <= $end) {
567
                        $start = date('Y-m-d H:i:s', $next_start);
568
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
569
                        $this->addEvent(
570
                            $start,
571
                            $repeatEnd,
572
                            $allDay,
573
                            $title,
574
                            $content,
575
                            $sentTo,
576
                            false,
577
                            $eventId
578
                        );
579
                        $next_start = $this->addMonth($next_start);
580
                    }
581
                    break;
582
                case 'monthlyByDay':
583
                    //not yet implemented
584
                    break;
585
                case 'monthlyByDayR':
586
                    //not yet implemented
587
                    break;
588 View Code Duplication
                case 'yearly':
589
                    $next_start = $this->addYear($origStartDate);
590
                    while ($next_start <= $end) {
591
                        $start = date('Y-m-d H:i:s', $next_start);
592
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
593
                        $this->addEvent(
594
                            $start,
595
                            $repeatEnd,
596
                            $allDay,
597
                            $title,
598
                            $content,
599
                            $sentTo,
600
                            false,
601
                            $eventId
602
                        );
603
                        $next_start = $this->addYear($next_start);
604
                    }
605
                    break;
606
            }
607
        }
608
609
        return true;
610
    }
611
612
    /**
613
     * @param int $item_id
614
     * @param array $sentTo
615
     * @return int
616
     */
617
    public function storeAgendaEventAsAnnouncement($item_id, $sentTo = array())
618
    {
619
        $table_agenda = Database::get_course_table(TABLE_AGENDA);
620
        $course_id = api_get_course_int_id();
621
622
        // Check params
623
        if (empty($item_id) || $item_id != strval(intval($item_id))) {
624
            return -1;
625
        }
626
627
        // Get the agenda item.
628
        $item_id = intval($item_id);
629
        $sql = "SELECT * FROM $table_agenda
630
                WHERE c_id = $course_id AND id = ".$item_id;
631
        $res = Database::query($sql);
632
633
        if (Database::num_rows($res) > 0) {
634
            $row = Database::fetch_array($res, 'ASSOC');
635
636
            // Sending announcement
637
            if (!empty($sentTo)) {
638
                $id = AnnouncementManager::add_announcement(
639
                    api_get_course_info(),
640
                    api_get_session_id(),
641
                    $row['title'],
642
                    $row['content'],
643
                    $sentTo,
644
                    null,
645
                    null,
646
                    $row['end_date']
647
                );
648
649
                AnnouncementManager::sendEmail(
650
                    api_get_course_info(),
651
                    api_get_session_id(),
652
                    $id
653
                );
654
655
                return $id;
656
            }
657
        }
658
659
        return -1;
660
    }
661
662
    /**
663
     * Edits an event
664
     *
665
     * @param int $id
666
     * @param string $start datetime format: 2012-06-14 09:00:00
667
     * @param string $end datetime format: 2012-06-14 09:00:00
668
     * @param int $allDay is all day 'true' or 'false'
669
     * @param string $title
670
     * @param string $content
671
     * @param array $usersToSend
672
     * @param array $attachmentArray
673
     * @param array $attachmentCommentList
674
     * @param string $comment
675
     * @param string $color
676
     * @param bool $addAnnouncement
677
     * @param bool $updateContent
678
     * @param int $authorId
679
     *
680
     * @return bool
681
     */
682
    public function editEvent(
683
        $id,
684
        $start,
685
        $end,
686
        $allDay,
687
        $title,
688
        $content,
689
        $usersToSend = array(),
690
        $attachmentArray = array(),
691
        $attachmentCommentList = array(),
692
        $comment = null,
693
        $color = '',
694
        $addAnnouncement = false,
695
        $updateContent = true,
696
        $authorId = 0
697
    ) {
698
        $start = api_get_utc_datetime($start);
699
        $end = api_get_utc_datetime($end);
700
        $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
701
        $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
702
703
        switch ($this->type) {
704
            case 'personal':
705
                $eventInfo = $this->get_event($id);
706
                if ($eventInfo['user'] != api_get_user_id()) {
707
                    break;
708
                }
709
                $attributes = array(
710
                    'title' => $title,
711
                    'date' => $start,
712
                    'enddate' => $end,
713
                    'all_day' => $allDay,
714
715
                );
716
717
                if ($updateContent) {
718
                    $attributes['text'] = $content;
719
                }
720
721
                if (!empty($color)) {
722
                    $attributes['color'] = $color;
723
                }
724
725
                Database::update(
726
                    $this->tbl_personal_agenda,
727
                    $attributes,
728
                    array('id = ?' => $id)
729
                );
730
                break;
731
            case 'course':
732
                $eventInfo = $this->get_event($id);
733
734
                if (empty($eventInfo)) {
735
                    return false;
736
                }
737
738
                $groupId = api_get_group_id();
739
                $groupIid = 0;
740
                if ($groupId) {
741
                    $groupInfo = GroupManager::get_group_properties($groupId);
742
                    if ($groupInfo) {
743
                        $groupIid = $groupInfo['iid'];
744
                    }
745
                }
746
747
                $course_id = $this->course['real_id'];
748
749
                if (empty($course_id)) {
750
                    return false;
751
                }
752
753
                if ($this->getIsAllowedToEdit()) {
754
                    $attributes = array(
755
                        'title' => $title,
756
                        'start_date' => $start,
757
                        'end_date' => $end,
758
                        'all_day' => $allDay,
759
                        'comment' => $comment
760
                    );
761
762
                    if ($updateContent) {
763
                        $attributes['content'] = $content;
764
                    }
765
766
                    if (!empty($color)) {
767
                        $attributes['color'] = $color;
768
                    }
769
770
                    Database::update(
771
                        $this->tbl_course_agenda,
772
                        $attributes,
773
                        array(
774
                            'id = ? AND c_id = ? AND session_id = ? ' => array(
775
                                $id,
776
                                $course_id,
777
                                $this->sessionId
778
                            )
779
                        )
780
                    );
781
782
                    if (!empty($usersToSend)) {
783
                        $sendTo = $this->parseSendToArray($usersToSend);
784
785
                        $usersToDelete = array_diff(
786
                            $eventInfo['send_to']['users'],
787
                            $sendTo['users']
788
                        );
789
                        $usersToAdd = array_diff(
790
                            $sendTo['users'],
791
                            $eventInfo['send_to']['users']
792
                        );
793
794
                        $groupsToDelete = array_diff(
795
                            $eventInfo['send_to']['groups'],
796
                            $sendTo['groups']
797
                        );
798
                        $groupToAdd = array_diff(
799
                            $sendTo['groups'],
800
                            $eventInfo['send_to']['groups']
801
                        );
802
803
                        if ($sendTo['everyone']) {
804
                            // Delete all from group
805
                            if (isset($eventInfo['send_to']['groups']) &&
806
                                !empty($eventInfo['send_to']['groups'])
807
                            ) {
808
                                foreach ($eventInfo['send_to']['groups'] as $group) {
809
                                    $groupIidItem = 0;
810
                                    if ($group) {
811
                                        $groupInfo = GroupManager::get_group_properties(
812
                                            $group
813
                                        );
814
                                        if ($groupInfo) {
815
                                            $groupIidItem = $groupInfo['iid'];
816
                                        }
817
                                    }
818
819
                                    api_item_property_delete(
820
                                        $this->course,
821
                                        TOOL_CALENDAR_EVENT,
822
                                        $id,
823
                                        0,
824
                                        $groupIidItem,
825
                                        $this->sessionId
826
                                    );
827
                                }
828
                            }
829
830
                            // Storing the selected users.
831
                            if (isset($eventInfo['send_to']['users']) &&
832
                                !empty($eventInfo['send_to']['users'])
833
                            ) {
834
                                foreach ($eventInfo['send_to']['users'] as $userId) {
835
                                    api_item_property_delete(
836
                                        $this->course,
837
                                        TOOL_CALENDAR_EVENT,
838
                                        $id,
839
                                        $userId,
840
                                        $groupIid,
841
                                        $this->sessionId
842
                                    );
843
                                }
844
                            }
845
846
                            // Add to everyone only.
847
                            api_item_property_update(
848
                                $this->course,
849
                                TOOL_CALENDAR_EVENT,
850
                                $id,
851
                                'visible',
852
                                $authorId,
853
                                $groupIid,
854
                                null,
855
                                $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 698 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
856
                                $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 699 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
857
                                $this->sessionId
858
                            );
859
                        } else {
860
                            // Delete "everyone".
861
                            api_item_property_delete(
862
                                $this->course,
863
                                TOOL_CALENDAR_EVENT,
864
                                $id,
865
                                0,
866
                                0,
867
                                $this->sessionId
868
                            );
869
870
                            // Add groups
871
                            if (!empty($groupToAdd)) {
872
                                foreach ($groupToAdd as $group) {
873
                                    $groupIidItem = 0;
874
                                    if ($group) {
875
                                        $groupInfo = GroupManager::get_group_properties(
876
                                            $group
877
                                        );
878
                                        if ($groupInfo) {
879
                                            $groupIidItem = $groupInfo['iid'];
880
                                        }
881
                                    }
882
883
                                    api_item_property_update(
884
                                        $this->course,
885
                                        TOOL_CALENDAR_EVENT,
886
                                        $id,
887
                                        'visible',
888
                                        $authorId,
889
                                        $groupIidItem,
890
                                        0,
891
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 698 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
892
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 699 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
893
                                        $this->sessionId
894
                                    );
895
                                }
896
                            }
897
898
                            // Delete groups.
899
                            if (!empty($groupsToDelete)) {
900
                                foreach ($groupsToDelete as $group) {
901
                                    $groupIidItem = 0;
902
                                    if ($group) {
903
                                        $groupInfo = GroupManager::get_group_properties(
904
                                            $group
905
                                        );
906
                                        if ($groupInfo) {
907
                                            $groupIidItem = $groupInfo['iid'];
908
                                        }
909
                                    }
910
911
                                    api_item_property_delete(
912
                                        $this->course,
913
                                        TOOL_CALENDAR_EVENT,
914
                                        $id,
915
                                        0,
916
                                        $groupIidItem,
917
                                        $this->sessionId
918
                                    );
919
                                }
920
                            }
921
922
                            // Add users.
923
                            if (!empty($usersToAdd)) {
924
                                foreach ($usersToAdd as $userId) {
925
                                    api_item_property_update(
926
                                        $this->course,
927
                                        TOOL_CALENDAR_EVENT,
928
                                        $id,
929
                                        'visible',
930
                                        $authorId,
931
                                        $groupIid,
932
                                        $userId,
933
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 698 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
934
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 699 can also be of type null or object<DateTime>; however, api_item_property_update() does only seem to accept string, 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...
935
                                        $this->sessionId
936
                                    );
937
                                }
938
                            }
939
940
                            // Delete users.
941
                            if (!empty($usersToDelete)) {
942
                                foreach ($usersToDelete as $userId) {
943
                                    api_item_property_delete(
944
                                        $this->course,
945
                                        TOOL_CALENDAR_EVENT,
946
                                        $id,
947
                                        $userId,
948
                                        $groupIid,
949
                                        $this->sessionId
950
                                    );
951
                                }
952
                            }
953
                        }
954
                    }
955
956
                    // Add announcement.
957
                    if (isset($addAnnouncement) && !empty($addAnnouncement)) {
958
                        $this->storeAgendaEventAsAnnouncement(
959
                            $id,
960
                            $usersToSend
961
                        );
962
                    }
963
964
                    // Add attachment.
965 View Code Duplication
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
966
                        $counter = 0;
967
                        foreach ($attachmentArray as $attachmentItem) {
968
                            $this->updateAttachment(
969
                                $attachmentItem['id'],
970
                                $id,
971
                                $attachmentItem,
972
                                $attachmentCommentList[$counter],
973
                                $this->course
974
                            );
975
                            $counter++;
976
                        }
977
                    }
978
979
                    return true;
980
                } else {
981
                    return false;
982
                }
983
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
984
            case 'admin':
985
            case 'platform':
986
                if (api_is_platform_admin()) {
987
                    $attributes = array(
988
                        'title' => $title,
989
                        'start_date' => $start,
990
                        'end_date' => $end,
991
                        'all_day' => $allDay
992
                    );
993
994
                    if ($updateContent) {
995
                        $attributes['content'] = $content;
996
                    }
997
                    Database::update(
998
                        $this->tbl_global_agenda,
999
                        $attributes,
1000
                        array('id = ?' => $id)
1001
                    );
1002
                }
1003
                break;
1004
        }
1005
    }
1006
1007
    /**
1008
     * @param int $id
1009
     * @param bool $deleteAllItemsFromSerie
1010
     */
1011
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
1012
    {
1013
        switch ($this->type) {
1014
            case 'personal':
1015
                $eventInfo = $this->get_event($id);
1016
                if ($eventInfo['user'] == api_get_user_id()) {
1017
                    Database::delete(
1018
                        $this->tbl_personal_agenda,
1019
                        array('id = ?' => $id)
1020
                    );
1021
                }
1022
                break;
1023
            case 'course':
1024
                $course_id = api_get_course_int_id();
1025
1026
                if (!empty($course_id) && api_is_allowed_to_edit(null, true)) {
1027
                    // Delete
1028
                    $eventInfo = $this->get_event($id);
1029
                    if ($deleteAllItemsFromSerie) {
1030
                        /* This is one of the children.
1031
                           Getting siblings and delete 'Em all + the father! */
1032
                        if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
1033
                            // Removing items.
1034
                            $events = $this->getAllRepeatEvents(
1035
                                $eventInfo['parent_event_id']
1036
                            );
1037
                            if (!empty($events)) {
1038
                                foreach ($events as $event) {
1039
                                    $this->deleteEvent($event['id']);
1040
                                }
1041
                            }
1042
                            // Removing parent.
1043
                            $this->deleteEvent($eventInfo['parent_event_id']);
1044
                        } else {
1045
                            // This is the father looking for the children.
1046
                            $events = $this->getAllRepeatEvents($id);
1047
                            if (!empty($events)) {
1048
                                foreach ($events as $event) {
1049
                                    $this->deleteEvent($event['id']);
1050
                                }
1051
                            }
1052
                        }
1053
                    }
1054
1055
                    // Removing from events.
1056
                    Database::delete(
1057
                        $this->tbl_course_agenda,
1058
                        array('id = ? AND c_id = ?' => array($id, $course_id))
1059
                    );
1060
1061
                    api_item_property_update(
1062
                        $this->course,
1063
                        TOOL_CALENDAR_EVENT,
1064
                        $id,
1065
                        'delete',
1066
                        api_get_user_id()
1067
                    );
1068
1069
                    // Removing from series.
1070
                    Database::delete(
1071
                        $this->table_repeat,
1072
                        array(
1073
                            'cal_id = ? AND c_id = ?' => array(
1074
                                $id,
1075
                                $course_id
1076
                            )
1077
                        )
1078
                    );
1079
1080
                    if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
1081
                        foreach ($eventInfo['attachment'] as $attachment) {
1082
                            self::deleteAttachmentFile(
1083
                                $attachment['id'],
1084
                                $this->course
1085
                            );
1086
                        }
1087
                    }
1088
                }
1089
                break;
1090
            case 'admin':
1091
                if (api_is_platform_admin()) {
1092
                    Database::delete(
1093
                        $this->tbl_global_agenda,
1094
                        array('id = ?' => $id)
1095
                    );
1096
                }
1097
                break;
1098
        }
1099
    }
1100
1101
    /**
1102
     * Get agenda events
1103
     * @param int $start
1104
     * @param int $end
1105
     * @param int $course_id
1106
     * @param int $groupId
1107
     * @param int $user_id
1108
     * @param string $format
1109
     *
1110
     * @return array|string
1111
     */
1112
    public function getEvents(
1113
        $start,
1114
        $end,
1115
        $course_id = null,
1116
        $groupId = null,
1117
        $user_id = 0,
1118
        $format = 'json'
1119
    ) {
1120
        switch ($this->type) {
1121
            case 'admin':
1122
                $this->getPlatformEvents($start, $end);
1123
                break;
1124
            case 'course':
1125
                $courseInfo = api_get_course_info_by_id($course_id);
1126
1127
                // Session coach can see all events inside a session.
1128
                if (api_is_coach()) {
1129
                    // Own course
1130
                    $this->getCourseEvents(
1131
                        $start,
1132
                        $end,
1133
                        $courseInfo,
1134
                        $groupId,
1135
                        $this->sessionId,
1136
                        $user_id
1137
                    );
1138
1139
                    // Others
1140
                    $this->getSessionEvents(
1141
                        $start,
1142
                        $end,
1143
                        $this->sessionId,
1144
                        $user_id,
1145
                        $this->eventOtherSessionColor
1146
                    );
1147
                } else {
1148
                    $this->getCourseEvents(
1149
                        $start,
1150
                        $end,
1151
                        $courseInfo,
1152
                        $groupId,
1153
                        $this->sessionId,
1154
                        $user_id
1155
                    );
1156
                }
1157
                break;
1158
            case 'personal':
1159
            default:
1160
                $sessionFilterActive = false;
1161
                if (!empty($this->sessionId)) {
1162
                    $sessionFilterActive = true;
1163
                }
1164
1165
                if ($sessionFilterActive == false) {
1166
                    // Getting personal events
1167
                    $this->getPersonalEvents($start, $end);
1168
1169
                    // Getting platform/admin events
1170
                    $this->getPlatformEvents($start, $end);
1171
                }
1172
1173
                $ignoreVisibility = api_get_configuration_value('personal_agenda_show_all_session_events');
1174
1175
                // Getting course events
1176
                $my_course_list = array();
1177
                if (!api_is_anonymous()) {
1178
                    $session_list = SessionManager::get_sessions_by_user(
1179
                        api_get_user_id(),
1180
                        $ignoreVisibility
1181
1182
                    );
1183
                    $my_course_list = CourseManager::get_courses_list_by_user_id(
1184
                        api_get_user_id(),
1185
                        false
1186
                    );
1187
                }
1188
1189
                if (api_is_drh()) {
1190
                    if (api_drh_can_access_all_session_content()) {
1191
                        $session_list = array();
1192
                        $sessionList = SessionManager::get_sessions_followed_by_drh(
1193
                            api_get_user_id(),
1194
                            null,
1195
                            null,
1196
                            null,
1197
                            true,
1198
                            false
1199
                        );
1200
1201
                        if (!empty($sessionList)) {
1202
                            foreach ($sessionList as $sessionItem) {
1203
                                $sessionId = $sessionItem['id'];
1204
                                $courses = SessionManager::get_course_list_by_session_id(
1205
                                    $sessionId
1206
                                );
1207
                                $sessionInfo = array(
1208
                                    'session_id' => $sessionId,
1209
                                    'courses' => $courses
1210
                                );
1211
                                $session_list[] = $sessionInfo;
1212
                            }
1213
                        }
1214
                    }
1215
                }
1216
1217
                if (!empty($session_list)) {
1218
                    foreach ($session_list as $session_item) {
1219
                        if ($sessionFilterActive) {
1220
                            if ($this->sessionId != $session_item['session_id']) {
1221
                                continue;
1222
                            }
1223
                        }
1224
1225
                        $my_courses = $session_item['courses'];
1226
                        $my_session_id = $session_item['session_id'];
1227
1228
                        if (!empty($my_courses)) {
1229
                            foreach ($my_courses as $course_item) {
1230
                                $courseInfo = api_get_course_info_by_id(
1231
                                    $course_item['real_id']
1232
                                );
1233
                                $this->getCourseEvents(
1234
                                    $start,
1235
                                    $end,
1236
                                    $courseInfo,
1237
                                    0,
1238
                                    $my_session_id
1239
                                );
1240
                            }
1241
                        }
1242
                    }
1243
                }
1244
1245
                if (!empty($my_course_list) && $sessionFilterActive == false) {
1246
                    foreach ($my_course_list as $courseInfoItem) {
1247
                        $courseInfo = api_get_course_info_by_id(
1248
                            $courseInfoItem['real_id']
1249
                        );
1250
                        if (isset($course_id) && !empty($course_id)) {
1251
                            if ($courseInfo['real_id'] == $course_id) {
1252
                                $this->getCourseEvents(
1253
                                    $start,
1254
                                    $end,
1255
                                    $courseInfo
1256
                                );
1257
                            }
1258
                        } else {
1259
                            $this->getCourseEvents(
1260
                                $start,
1261
                                $end,
1262
                                $courseInfo
1263
                            );
1264
                        }
1265
                    }
1266
                }
1267
1268
                break;
1269
        }
1270
1271
        switch ($format) {
1272
            case 'json':
1273
                if (empty($this->events)) {
1274
                    return '';
1275
                }
1276
1277
                return json_encode($this->events);
1278
                break;
1279
            case 'array':
1280
                if (empty($this->events)) {
1281
                    return [];
1282
                }
1283
1284
                return $this->events;
1285
                break;
1286
        }
1287
    }
1288
1289
    /**
1290
     * @param int $id
1291
     * @param int $minute_delta
1292
     * @return int
1293
     */
1294
    public function resizeEvent($id, $minute_delta)
1295
    {
1296
        $id = (int) $id;
1297
        $delta = intval($minute_delta);
1298
        $event = $this->get_event($id);
1299
        if (!empty($event)) {
1300
            switch ($this->type) {
1301
                case 'personal':
1302
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1303
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1304
							WHERE id = ".$id;
1305
                    Database::query($sql);
1306
                    break;
1307 View Code Duplication
                case 'course':
1308
                    $sql = "UPDATE $this->tbl_course_agenda SET
1309
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1310
							WHERE 
1311
							    c_id = ".$this->course['real_id']." AND 
1312
							    id = ".$id;
1313
                    Database::query($sql);
1314
                    break;
1315
                case 'admin':
1316
                    $sql = "UPDATE $this->tbl_global_agenda SET
1317
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1318
							WHERE id = ".$id;
1319
                    Database::query($sql);
1320
                    break;
1321
            }
1322
        }
1323
1324
        return 1;
1325
    }
1326
1327
    /**
1328
     * @param int $id
1329
     * @param int $minute_delta minutes
1330
     * @param int $allDay
1331
     * @return int
1332
     */
1333
    public function move_event($id, $minute_delta, $allDay)
1334
    {
1335
        $id = (int) $id;
1336
        $event = $this->get_event($id);
1337
1338
        if (empty($event)) {
1339
            return false;
1340
        }
1341
1342
        // we convert the hour delta into minutes and add the minute delta
1343
        $delta = intval($minute_delta);
1344
        $allDay = intval($allDay);
1345
1346
        if (!empty($event)) {
1347
            switch ($this->type) {
1348
                case 'personal':
1349
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1350
                            all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
1351
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1352
							WHERE id=".$id;
1353
                    Database::query($sql);
1354
                    break;
1355 View Code Duplication
                case 'course':
1356
                    $sql = "UPDATE $this->tbl_course_agenda SET
1357
                            all_day = $allDay, 
1358
                            start_date = DATE_ADD(start_date, INTERVAL $delta MINUTE),
1359
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1360
							WHERE 
1361
							    c_id = ".$this->course['real_id']." AND 
1362
							    id=".$id;
1363
                    Database::query($sql);
1364
                    break;
1365
                case 'admin':
1366
                    $sql = "UPDATE $this->tbl_global_agenda SET
1367
                            all_day = $allDay,
1368
                            start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
1369
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1370
							WHERE id=".$id;
1371
                    Database::query($sql);
1372
                    break;
1373
            }
1374
        }
1375
1376
        return 1;
1377
    }
1378
1379
    /**
1380
     * Gets a single event
1381
     *
1382
     * @param int $id event id
1383
     * @return array
1384
     */
1385
    public function get_event($id)
1386
    {
1387
        // make sure events of the personal agenda can only be seen by the user himself
1388
        $id = intval($id);
1389
        $event = null;
1390
        switch ($this->type) {
1391
            case 'personal':
1392
                $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1393
                        WHERE id = $id AND user = ".api_get_user_id();
1394
                $result = Database::query($sql);
1395 View Code Duplication
                if (Database::num_rows($result)) {
1396
                    $event = Database::fetch_array($result, 'ASSOC');
1397
                    $event['description'] = $event['text'];
1398
                    $event['content'] = $event['text'];
1399
                    $event['start_date'] = $event['date'];
1400
                    $event['end_date'] = $event['enddate'];
1401
                }
1402
                break;
1403
            case 'course':
1404
                if (!empty($this->course['real_id'])) {
1405
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
1406
                            WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
1407
                    $result = Database::query($sql);
1408
                    if (Database::num_rows($result)) {
1409
                        $event = Database::fetch_array($result, 'ASSOC');
1410
                        $event['description'] = $event['content'];
1411
1412
                        // Getting send to array
1413
                        $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
1414
                            $id,
1415
                            $this->course['real_id'],
1416
                            $this->sessionId
1417
                        );
1418
1419
                        // Getting repeat info
1420
                        $event['repeat_info'] = $this->getRepeatedInfoByEvent(
1421
                            $id,
1422
                            $this->course['real_id']
1423
                        );
1424
1425
                        if (!empty($event['parent_event_id'])) {
1426
                            $event['parent_info'] = $this->get_event(
1427
                                $event['parent_event_id']
1428
                            );
1429
                        }
1430
1431
                        $event['attachment'] = $this->getAttachmentList(
1432
                            $id,
1433
                            $this->course
1434
                        );
1435
                    }
1436
                }
1437
                break;
1438
            case 'admin':
1439
            case 'platform':
1440
                $sql = "SELECT * FROM ".$this->tbl_global_agenda."
1441
                        WHERE id = $id";
1442
                $result = Database::query($sql);
1443
                if (Database::num_rows($result)) {
1444
                    $event = Database::fetch_array($result, 'ASSOC');
1445
                    $event['description'] = $event['content'];
1446
                }
1447
                break;
1448
        }
1449
1450
        return $event;
1451
    }
1452
1453
    /**
1454
     * Gets personal events
1455
     * @param int $start
1456
     * @param int $end
1457
     * @return array
1458
     */
1459
    public function getPersonalEvents($start, $end)
1460
    {
1461
        $start = intval($start);
1462
        $end = intval($end);
1463
        $startCondition = '';
1464
        $endCondition = '';
1465
1466
        if ($start !== 0) {
1467
            $start = api_get_utc_datetime($start);
1468
            $startCondition = "AND date >= '".$start."'";
1469
        }
1470
        if ($start !== 0) {
1471
            $end = api_get_utc_datetime($end);
1472
            $endCondition = "AND (enddate <= '".$end."' OR enddate IS NULL)";
1473
        }
1474
        $user_id = api_get_user_id();
1475
1476
        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
1477
                WHERE user = $user_id $startCondition $endCondition";
1478
1479
        $result = Database::query($sql);
1480
        $my_events = array();
1481
        if (Database::num_rows($result)) {
1482
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1483
                $event = array();
1484
                $event['id'] = 'personal_'.$row['id'];
1485
                $event['title'] = $row['title'];
1486
                $event['className'] = 'personal';
1487
                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
1488
                $event['editable'] = true;
1489
                $event['sent_to'] = get_lang('Me');
1490
                $event['type'] = 'personal';
1491
1492 View Code Duplication
                if (!empty($row['date'])) {
1493
                    $event['start'] = $this->formatEventDate($row['date']);
1494
                    $event['start_date_localtime'] = api_get_local_time(
1495
                        $row['date']
1496
                    );
1497
                }
1498
1499 View Code Duplication
                if (!empty($row['enddate'])) {
1500
                    $event['end'] = $this->formatEventDate($row['enddate']);
1501
                    $event['end_date_localtime'] = api_get_local_time(
1502
                        $row['enddate']
1503
                    );
1504
                }
1505
                $event['description'] = $row['text'];
1506
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1507
1508
                $event['parent_event_id'] = 0;
1509
                $event['has_children'] = 0;
1510
1511
                $my_events[] = $event;
1512
                $this->events[] = $event;
1513
            }
1514
        }
1515
1516
        return $my_events;
1517
    }
1518
1519
    /**
1520
     * Get user/group list per event.
1521
     *
1522
     * @param int $eventId
1523
     * @param int $courseId
1524
     * @param integer $sessionId
1525
     * @paraù int $sessionId
1526
     *
1527
     * @return array
1528
     */
1529
    public function getUsersAndGroupSubscribedToEvent(
1530
        $eventId,
1531
        $courseId,
1532
        $sessionId
1533
    ) {
1534
        $eventId = intval($eventId);
1535
        $courseId = intval($courseId);
1536
        $sessionId = intval($sessionId);
1537
1538
        $sessionCondition = "ip.session_id = $sessionId";
1539
        if (empty($sessionId)) {
1540
            $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
1541
        }
1542
1543
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1544
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1545
1546
        // Get sent_tos
1547
        $sql = "SELECT DISTINCT to_user_id, to_group_id
1548
                FROM $tbl_property ip
1549
                INNER JOIN $tlb_course_agenda agenda
1550
                ON (
1551
                  ip.ref = agenda.id AND
1552
                  ip.c_id = agenda.c_id AND
1553
                  ip.tool = '".TOOL_CALENDAR_EVENT."'
1554
                )
1555
                WHERE
1556
                    ref = $eventId AND
1557
                    ip.visibility = '1' AND
1558
                    ip.c_id = $courseId AND
1559
                    $sessionCondition
1560
                ";
1561
1562
        $result = Database::query($sql);
1563
        $users = array();
1564
        $groups = array();
1565
        $everyone = false;
1566
1567
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1568
            if (!empty($row['to_group_id'])) {
1569
                $groups[] = $row['to_group_id'];
1570
            }
1571
            if (!empty($row['to_user_id'])) {
1572
                $users[] = $row['to_user_id'];
1573
            }
1574
1575
            if (empty($groups) && empty($users)) {
1576
                if ($row['to_group_id'] == 0) {
1577
                    $everyone = true;
1578
                }
1579
            }
1580
        }
1581
1582
        return array(
1583
            'everyone' => $everyone,
1584
            'users' => $users,
1585
            'groups' => $groups
1586
        );
1587
    }
1588
1589
    /**
1590
     * @param int $start
1591
     * @param int $end
1592
     * @param int $sessionId
1593
     * @param int $userId
1594
     * @param string $color
1595
     *
1596
     * @return array
1597
     */
1598
    public function getSessionEvents(
1599
        $start,
1600
        $end,
1601
        $sessionId = 0,
1602
        $userId = 0,
1603
        $color = ''
1604
    ) {
1605
        $courses = SessionManager::get_course_list_by_session_id($sessionId);
1606
1607
        if (!empty($courses)) {
1608
            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...
1609
                $this->getCourseEvents(
1610
                    $start,
1611
                    $end,
1612
                    $course,
1613
                    0,
1614
                    $sessionId,
1615
                    0,
1616
                    $color
1617
                );
1618
            }
1619
        }
1620
    }
1621
1622
    /**
1623
     * @param int $start
1624
     * @param int $end
1625
     * @param array $courseInfo
1626
     * @param int $groupId
1627
     * @param int $session_id
1628
     * @param int $user_id
1629
     * @param string $color
1630
     *
1631
     * @return array
1632
     */
1633
    public function getCourseEvents(
1634
        $start,
1635
        $end,
1636
        $courseInfo,
1637
        $groupId = 0,
1638
        $session_id = 0,
1639
        $user_id = 0,
1640
        $color = ''
1641
    ) {
1642
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
1643
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
1644
1645
        if (empty($courseInfo)) {
1646
            return array();
1647
        }
1648
        $course_id = $courseInfo['real_id'];
1649
1650
        if (empty($course_id)) {
1651
            return array();
1652
        }
1653
1654
        $session_id = intval($session_id);
1655
        $user_id = intval($user_id);
1656
        $groupList = GroupManager::get_group_list(null, $courseInfo['code']);
1657
1658
        $group_name_list = array();
1659
        if (!empty($groupList)) {
1660
            foreach ($groupList as $group) {
1661
                $group_name_list[$group['id']] = $group['name'];
1662
            }
1663
        }
1664
1665
        if (!empty($groupId)) {
1666 View Code Duplication
            if (!api_is_allowed_to_edit()) {
1667
                $user_id = api_get_user_id();
1668
                $group_memberships = GroupManager::get_group_ids(
1669
                    $course_id,
1670
                    $user_id
1671
                );
1672
            } else {
1673
                $group_memberships = GroupManager::get_group_ids(
1674
                    $course_id,
1675
                    $user_id
1676
                );
1677
            }
1678 View Code Duplication
        } else {
1679
            // if no group was defined but I am a student reviewing his agenda,
1680
            // group events should show, so we should fetch those groups to which
1681
            // I belong
1682
            if (!api_is_allowed_to_edit()) {
1683
                $user_id = api_get_user_id();
1684
                $group_memberships = GroupManager::get_group_ids(
1685
                    $course_id,
1686
                    $user_id
1687
                );
1688
            } else {
1689
                // If no group was defined and I am a teacher/admin reviewing
1690
                // someone else's agenda, we should fetch this person's groups
1691
                $group_memberships = GroupManager::get_group_ids(
1692
                    $course_id,
1693
                    $user_id
1694
                );
1695
            }
1696
        }
1697
1698
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1699
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1700
1701
        if (!empty($groupId)) {
1702
            $group_memberships = array($groupId);
1703
        }
1704
1705
        if (is_array($group_memberships) && count($group_memberships) > 0) {
1706
            if (api_is_allowed_to_edit()) {
1707
                if (!empty($groupId)) {
1708
                    $where_condition = "( ip.to_group_id IN (".implode(
1709
                            ", ",
1710
                            $group_memberships
1711
                        ).") ) ";
1712 View Code Duplication
                } else {
1713
                    if (!empty($user_id)) {
1714
                        $where_condition = "( ip.to_user_id = $user_id OR ip.to_user_id IS NULL OR (ip.to_group_id IN (0, ".implode(
1715
                                ", ",
1716
                                $group_memberships
1717
                            ).")) ) ";
1718
                    } else {
1719
                        $where_condition = "( ip.to_group_id IN (0, ".implode(
1720
                                ", ",
1721
                                $group_memberships
1722
                            ).") ) ";
1723
                    }
1724
                }
1725
            } else {
1726
                $where_condition = "( ip.to_user_id = $user_id OR ip.to_user_id IS NULL OR (ip.to_group_id IN (0, ".implode(
1727
                        ", ",
1728
                        $group_memberships
1729
                    ).")) ) ";
1730
            }
1731
1732
            if (empty($session_id)) {
1733
                $sessionCondition = "
1734
                (
1735
                    agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
1736
                ) ";
1737
            } else {
1738
                $sessionCondition = "
1739
                (
1740
                    agenda.session_id = $session_id AND
1741
                    ip.session_id = $session_id
1742
                ) ";
1743
            }
1744
1745
            $sql = "SELECT DISTINCT
1746
                        agenda.*,
1747
                        ip.visibility,
1748
                        ip.to_group_id,
1749
                        ip.insert_user_id,
1750
                        ip.ref,
1751
                        to_user_id
1752
                    FROM $tlb_course_agenda agenda
1753
                    INNER JOIN $tbl_property ip
1754
                    ON (
1755
                        agenda.id = ip.ref AND 
1756
                        agenda.c_id = ip.c_id AND 
1757
                        ip.tool = '".TOOL_CALENDAR_EVENT."'
1758
                    )
1759
                    WHERE
1760
                        $where_condition AND
1761
                        ip.visibility = '1' AND
1762
                        agenda.c_id = $course_id AND
1763
                        ip.c_id = agenda.c_id AND
1764
                        $sessionCondition
1765
                    ";
1766
        } else {
1767
            $visibilityCondition = " ip.visibility='1' AND ";
1768
1769
            if (api_is_allowed_to_edit()) {
1770
                if ($user_id == 0) {
1771
                    $where_condition = '';
1772
                } else {
1773
                    $where_condition = " (ip.to_user_id = ".$user_id." OR ip.to_user_id IS NULL) AND ip.to_group_id IS NULL AND ";
1774
                }
1775
                $visibilityCondition = " (ip.visibility IN ('1', '0')) AND ";
1776
            } else {
1777
                $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 ";
1778
            }
1779
1780
            if (empty($session_id)) {
1781
                $sessionCondition = "
1782
                (
1783
                    agenda.session_id = 0 AND
1784
                    (ip.session_id IS NULL OR ip.session_id = 0)
1785
                ) ";
1786
            } else {
1787
                $sessionCondition = "
1788
                (
1789
                    agenda.session_id = $session_id AND
1790
                    ip.session_id = $session_id
1791
                ) ";
1792
            }
1793
1794
            $sql = "SELECT DISTINCT
1795
                        agenda.*,
1796
                        ip.visibility,
1797
                        ip.to_group_id,
1798
                        ip.insert_user_id,
1799
                        ip.ref,
1800
                        to_user_id
1801
                    FROM $tlb_course_agenda agenda
1802
                    INNER JOIN $tbl_property ip
1803
                    ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id AND ip.tool='".TOOL_CALENDAR_EVENT."' )
1804
                    WHERE
1805
                        $where_condition
1806
                        $visibilityCondition
1807
                        agenda.c_id = $course_id AND
1808
                        $sessionCondition
1809
                    ";
1810
        }
1811
1812
        $dateCondition = null;
1813
1814 View Code Duplication
        if (!empty($start) && !empty($end)) {
1815
            $dateCondition .= "AND (
1816
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1817
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1818
                 (
1819
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1820
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1821
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1822
                 )
1823
            )";
1824
        }
1825
1826
        $sql .= $dateCondition;
1827
        $result = Database::query($sql);
1828
1829
        $coachCanEdit = false;
1830
        if (!empty($session_id)) {
1831
            $coachCanEdit = api_is_coach(
1832
                    $session_id,
1833
                    $course_id
1834
                ) || api_is_platform_admin();
1835
        }
1836
1837
        if (Database::num_rows($result)) {
1838
            $eventsAdded = array_column($this->events, 'unique_id');
1839
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1840
                $event = array();
1841
                $event['id'] = 'course_'.$row['id'];
1842
                $event['unique_id'] = $row['iid'];
1843
                // To avoid doubles
1844
                if (in_array($event['unique_id'], $eventsAdded)) {
1845
                    continue;
1846
                }
1847
1848
                $eventsAdded[] = $event['unique_id'];
1849
1850
                $eventId = $row['ref'];
1851
                $items = $this->getUsersAndGroupSubscribedToEvent(
1852
                    $eventId,
1853
                    $course_id,
1854
                    $this->sessionId
1855
                );
1856
                $group_to_array = $items['groups'];
1857
                $user_to_array = $items['users'];
1858
                $attachmentList = $this->getAttachmentList(
1859
                    $row['id'],
1860
                    $courseInfo
1861
                );
1862
                $event['attachment'] = '';
1863
1864
                if (!empty($attachmentList)) {
1865
                    foreach ($attachmentList as $attachment) {
1866
                        $has_attachment = Display::return_icon(
1867
                            'attachment.gif',
1868
                            get_lang('Attachment')
1869
                        );
1870
                        $user_filename = $attachment['filename'];
1871
                        $url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$course_id.'&'.api_get_cidreq();
1872
                        $event['attachment'] .= $has_attachment.
1873
                            Display::url(
1874
                                $user_filename,
1875
                                $url
1876
                            ).'<br />';
1877
                    }
1878
                }
1879
1880
                $event['title'] = $row['title'];
1881
                $event['className'] = 'course';
1882
                $event['allDay'] = 'false';
1883
                $event['course_id'] = $course_id;
1884
                $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
1885
1886
                $sessionInfo = [];
1887 View Code Duplication
                if (isset($row['session_id']) && !empty($row['session_id'])) {
1888
                    $sessionInfo = api_get_session_info($session_id);
1889
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
1890
                }
1891
1892
                $event['session_name'] = isset($sessionInfo['name']) ? $sessionInfo['name'] : '';
1893
                $event['course_name'] = isset($courseInfo['title']) ? $courseInfo['title'] : '';
1894
1895 View Code Duplication
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1896
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
1897
                }
1898
1899
                if (!empty($color)) {
1900
                    $event['borderColor'] = $event['backgroundColor'] = $color;
1901
                }
1902
1903 View Code Duplication
                if (isset($row['color']) && !empty($row['color'])) {
1904
                    $event['borderColor'] = $event['backgroundColor'] = $row['color'];
1905
                }
1906
1907
                $event['editable'] = false;
1908
                if ($this->getIsAllowedToEdit() && $this->type == 'course') {
1909
                    $event['editable'] = true;
1910
                    if (!empty($session_id)) {
1911
                        if ($coachCanEdit == false) {
1912
                            $event['editable'] = false;
1913
                        }
1914
                    }
1915
                }
1916
1917 View Code Duplication
                if (!empty($row['start_date'])) {
1918
                    $event['start'] = $this->formatEventDate(
1919
                        $row['start_date']
1920
                    );
1921
                    $event['start_date_localtime'] = api_get_local_time(
1922
                        $row['start_date']
1923
                    );
1924
                }
1925 View Code Duplication
                if (!empty($row['end_date'])) {
1926
                    $event['end'] = $this->formatEventDate($row['end_date']);
1927
                    $event['end_date_localtime'] = api_get_local_time(
1928
                        $row['end_date']
1929
                    );
1930
                }
1931
1932
                $event['sent_to'] = '';
1933
                $event['type'] = 'course';
1934
                if ($row['session_id'] != 0) {
1935
                    $event['type'] = 'session';
1936
                }
1937
1938
                // Event Sent to a group?
1939
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1940
                    $sent_to = array();
1941
                    if (!empty($group_to_array)) {
1942
                        foreach ($group_to_array as $group_item) {
1943
                            $sent_to[] = $group_name_list[$group_item];
1944
                        }
1945
                    }
1946
                    $sent_to = implode('@@', $sent_to);
1947
                    $sent_to = str_replace(
1948
                        '@@',
1949
                        '</div><div class="label_tag notice">',
1950
                        $sent_to
1951
                    );
1952
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1953
                    $event['type'] = 'group';
1954
                }
1955
1956
                // Event sent to a user?
1957
                if (isset($row['to_user_id'])) {
1958
                    $sent_to = array();
1959
                    if (!empty($user_to_array)) {
1960
                        foreach ($user_to_array as $item) {
1961
                            $user_info = api_get_user_info($item);
1962
                            // Add username as tooltip for $event['sent_to'] - ref #4226
1963
                            $username = api_htmlentities(
1964
                                sprintf(
1965
                                    get_lang('LoginX'),
1966
                                    $user_info['username']
1967
                                ),
1968
                                ENT_QUOTES
1969
                            );
1970
                            $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
1971
                        }
1972
                    }
1973
                    $sent_to = implode('@@', $sent_to);
1974
                    $sent_to = str_replace(
1975
                        '@@',
1976
                        '</div><div class="label_tag notice">',
1977
                        $sent_to
1978
                    );
1979
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1980
                }
1981
1982
                //Event sent to everyone!
1983
                if (empty($event['sent_to'])) {
1984
                    $event['sent_to'] = '<div class="label_tag notice">'.get_lang(
1985
                            'Everyone'
1986
                        ).'</div>';
1987
                }
1988
1989
                $event['description'] = $row['content'];
1990
                $event['visibility'] = $row['visibility'];
1991
                $event['real_id'] = $row['id'];
1992
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
1993
                $event['parent_event_id'] = $row['parent_event_id'];
1994
                $event['has_children'] = $this->hasChildren(
1995
                    $row['id'],
1996
                    $course_id
1997
                ) ? 1 : 0;
1998
                $event['comment'] = $row['comment'];
1999
2000
                $this->events[] = $event;
2001
            }
2002
        }
2003
2004
        return $this->events;
2005
    }
2006
2007
    /**
2008
     * @param int $start tms
2009
     * @param int $end tms
2010
     * @return array
2011
     */
2012
    public function getPlatformEvents($start, $end)
2013
    {
2014
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(
2015
            intval($start)
2016
        ) : null;
2017
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(
2018
            intval($end)
2019
        ) : null;
2020
        $dateCondition = '';
2021
2022 View Code Duplication
        if (!empty($start) && !empty($end)) {
2023
            $dateCondition .= "AND (
2024
                 start_date BETWEEN '".$start."' AND '".$end."' OR
2025
                 end_date BETWEEN '".$start."' AND '".$end."' OR
2026
                 (
2027
                     start_date IS NOT NULL AND end_date IS NOT NULL AND
2028
                     YEAR(start_date) = YEAR(end_date) AND
2029
                     MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
2030
                 )
2031
            )";
2032
        }
2033
2034
        $access_url_id = api_get_current_access_url_id();
2035
2036
        $sql = "SELECT *
2037
                FROM ".$this->tbl_global_agenda."
2038
                WHERE access_url_id = $access_url_id
2039
                $dateCondition";
2040
        $result = Database::query($sql);
2041
        $my_events = array();
2042
        if (Database::num_rows($result)) {
2043
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2044
                $event = array();
2045
                $event['id'] = 'platform_'.$row['id'];
2046
                $event['title'] = $row['title'];
2047
                $event['className'] = 'platform';
2048
                $event['allDay'] = 'false';
2049
                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
2050
                $event['editable'] = false;
2051
                $event['type'] = 'admin';
2052
2053
                if (api_is_platform_admin() && $this->type == 'admin') {
2054
                    $event['editable'] = true;
2055
                }
2056
2057 View Code Duplication
                if (!empty($row['start_date'])) {
2058
                    $event['start'] = $this->formatEventDate(
2059
                        $row['start_date']
2060
                    );
2061
                    $event['start_date_localtime'] = api_get_local_time(
2062
                        $row['start_date']
2063
                    );
2064
                }
2065 View Code Duplication
                if (!empty($row['end_date'])) {
2066
                    $event['end'] = $this->formatEventDate($row['end_date']);
2067
                    $event['end_date_localtime'] = api_get_local_time(
2068
                        $row['end_date']
2069
                    );
2070
                }
2071
2072
                $event['description'] = $row['content'];
2073
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
2074
2075
                $event['parent_event_id'] = 0;
2076
                $event['has_children'] = 0;
2077
2078
                $my_events[] = $event;
2079
                $this->events[] = $event;
2080
            }
2081
        }
2082
2083
        return $my_events;
2084
    }
2085
2086
    /**
2087
     * Format needed for the Fullcalendar js lib
2088
     *
2089
     * @param string $utcTime
2090
     * @return bool|string
2091
     */
2092
    private function formatEventDate($utcTime)
2093
    {
2094
        $utcTimeZone = new DateTimeZone('UTC');
2095
        $platformTimeZone = new DateTimeZone(api_get_timezone());
2096
2097
        $eventDate = new DateTime($utcTime, $utcTimeZone);
2098
        $eventDate->setTimezone($platformTimeZone);
2099
2100
        return $eventDate->format(DateTime::ISO8601);
2101
    }
2102
2103
    /**
2104
     * @param FormValidator $form
2105
     * @param array $groupList
2106
     * @param array $userList
2107
     * @param array $sendTo array('users' => [1, 2], 'groups' => [3, 4])
2108
     * @param array $attributes
2109
     * @param bool $addOnlyItemsInSendTo
2110
     * @param bool $required
2111
     */
2112
    public function setSendToSelect(
2113
        $form,
2114
        $groupList = [],
2115
        $userList = [],
2116
        $sendTo = [],
2117
        $attributes = [],
2118
        $addOnlyItemsInSendTo = false,
2119
        $required = false
2120
    ) {
2121
        $params = array(
2122
            'id' => 'users_to_send_id',
2123
            'data-placeholder' => get_lang('Select'),
2124
            'multiple' => 'multiple',
2125
            'class' => 'multiple-select'
2126
        );
2127
2128
        if (!empty($attributes)) {
2129
            $params = array_merge($params, $attributes);
2130
            if (empty($params['multiple'])) {
2131
                unset($params['multiple']);
2132
            }
2133
        }
2134
2135
        $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : array();
2136
        $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : array();
2137
2138
        /** @var HTML_QuickForm_select $select */
2139
        $select = $form->addSelect(
2140
            'users_to_send',
2141
            get_lang('To'),
2142
            null,
2143
            $params
2144
        );
2145
2146
        if ($required) {
2147
            $form->setRequired($select);
2148
        }
2149
2150
        $selectedEveryoneOptions = array();
2151
        if (isset($sendTo['everyone']) && $sendTo['everyone']) {
2152
            $selectedEveryoneOptions = array('selected');
2153
            $sendToUsers = array();
2154
        }
2155
2156
        $select->addOption(
2157
            get_lang('Everyone'),
2158
            'everyone',
2159
            $selectedEveryoneOptions
2160
        );
2161
2162
        $options = array();
2163
        if (is_array($groupList)) {
2164
            foreach ($groupList as $group) {
2165
                $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
2166
                $count_users = " &ndash; $count_users ".get_lang('Users');
2167
                $option = array(
2168
                    'text' => $group['name'].$count_users,
2169
                    'value' => "GROUP:".$group['id']
2170
                );
2171
                $selected = in_array(
2172
                    $group['id'],
2173
                    $sendToGroups
2174
                ) ? true : false;
2175
                if ($selected) {
2176
                    $option['selected'] = 'selected';
2177
                }
2178
2179
                if ($addOnlyItemsInSendTo) {
2180
                    if ($selected) {
2181
                        $options[] = $option;
2182
                    }
2183
                } else {
2184
                    $options[] = $option;
2185
                }
2186
            }
2187
            $select->addOptGroup($options, get_lang('Groups'));
2188
        }
2189
2190
        // adding the individual users to the select form
2191
        if (is_array($userList)) {
2192
            $options = array();
2193
            foreach ($userList as $user) {
2194
                if ($user['status'] == ANONYMOUS) {
2195
                    continue;
2196
                }
2197
                $option = array(
2198
                    'text' => api_get_person_name(
2199
                            $user['firstname'],
2200
                            $user['lastname']
2201
                        ).' ('.$user['username'].')',
2202
                    'value' => "USER:".$user['user_id']
2203
                );
2204
2205
                $selected = in_array(
2206
                    $user['user_id'],
2207
                    $sendToUsers
2208
                ) ? true : false;
2209
2210
                if ($selected) {
2211
                    $option['selected'] = 'selected';
2212
                }
2213
2214
                if ($addOnlyItemsInSendTo) {
2215
                    if ($selected) {
2216
                        $options[] = $option;
2217
                    }
2218
                } else {
2219
                    $options[] = $option;
2220
                }
2221
            }
2222
2223
            $select->addOptGroup($options, get_lang('Users'));
2224
        }
2225
    }
2226
2227
    /**
2228
     * Separates the users and groups array
2229
     * users have a value USER:XXX (with XXX the user id
2230
     * groups have a value GROUP:YYY (with YYY the group id)
2231
     * use the 'everyone' key
2232
     * @author Julio Montoya based in separate_users_groups in agenda.inc.php
2233
     * @param array $to
2234
     * @return array
2235
     */
2236
    public function parseSendToArray($to)
2237
    {
2238
        $groupList = array();
2239
        $userList = array();
2240
        $sendTo = null;
2241
2242
        $sendTo['everyone'] = false;
2243
        if (is_array($to) && count($to) > 0) {
2244
            foreach ($to as $item) {
2245
                if ($item == 'everyone') {
2246
                    $sendTo['everyone'] = true;
2247
                } else {
2248
                    list($type, $id) = explode(':', $item);
2249
                    switch ($type) {
2250
                        case 'GROUP':
2251
                            $groupList[] = $id;
2252
                            break;
2253
                        case 'USER':
2254
                            $userList[] = $id;
2255
                            break;
2256
                    }
2257
                }
2258
            }
2259
            $sendTo['groups'] = $groupList;
2260
            $sendTo['users'] = $userList;
2261
        }
2262
2263
        return $sendTo;
2264
    }
2265
2266
    /**
2267
     * @param array $params
2268
     * @return FormValidator
2269
     */
2270
    public function getForm($params = [])
2271
    {
2272
        $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
2273
        $id = isset($params['id']) ? intval($params['id']) : null;
2274
2275
        if ($this->type == 'course') {
2276
            $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
2277
        } else {
2278
            $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
2279
        }
2280
2281
        $form = new FormValidator(
2282
            'add_event',
2283
            'post',
2284
            $url,
2285
            null,
2286
            array('enctype' => 'multipart/form-data')
2287
        );
2288
2289
        $idAttach = isset($params['id_attach']) ? intval(
2290
            $params['id_attach']
2291
        ) : null;
2292
        $groupId = api_get_group_id();
2293
2294
        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...
2295
            $form_title = get_lang('ModifyCalendarItem');
2296
        } else {
2297
            $form_title = get_lang('AddCalendarItem');
2298
        }
2299
2300
        $form->addElement('header', $form_title);
2301
        $form->addElement('hidden', 'id', $id);
2302
        $form->addElement('hidden', 'action', $action);
2303
        $form->addElement('hidden', 'id_attach', $idAttach);
2304
2305
        $isSubEventEdition = false;
2306
        $isParentFromSerie = false;
2307
        $showAttachmentForm = true;
2308
2309
        if ($this->type == 'course') {
2310
            // Edition mode.
2311
            if (!empty($id)) {
2312
                $showAttachmentForm = false;
2313
                if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
2314
                    $isSubEventEdition = true;
2315
                }
2316
                if (!empty($params['repeat_info'])) {
2317
                    $isParentFromSerie = true;
2318
                }
2319
            }
2320
        }
2321
2322
        if ($isSubEventEdition) {
2323
            $form->addElement(
2324
                'label',
2325
                null,
2326
                Display::return_message(
2327
                    get_lang('EditingThisEventWillRemoveItFromTheSerie'),
2328
                    'warning'
2329
                )
2330
            );
2331
        }
2332
2333
        $form->addElement('text', 'title', get_lang('ItemTitle'));
2334
2335
        if (isset($groupId) && !empty($groupId)) {
2336
            $form->addElement(
2337
                'hidden',
2338
                'selected_form[0]',
2339
                "GROUP:'.$groupId.'"
2340
            );
2341
            $form->addElement('hidden', 'to', 'true');
2342
        } else {
2343
            $sendTo = isset($params['send_to']) ? $params['send_to'] : ['everyone' => true];
2344
            if ($this->type == 'course') {
2345
                $this->showToForm($form, $sendTo, array(), false, true);
2346
            }
2347
        }
2348
2349
        $form->addDateRangePicker(
2350
            'date_range',
2351
            get_lang('DateRange'),
2352
            false,
2353
            array('id' => 'date_range')
2354
        );
2355
        $form->addElement('checkbox', 'all_day', null, get_lang('AllDay'));
2356
2357
        if ($this->type == 'course') {
2358
            $repeat = $form->addElement(
2359
                'checkbox',
2360
                'repeat',
2361
                null,
2362
                get_lang('RepeatEvent'),
2363
                array('onclick' => 'return plus_repeated_event();')
2364
            );
2365
            $form->addElement(
2366
                'html',
2367
                '<div id="options2" style="display:none">'
2368
            );
2369
            $form->addElement(
2370
                'select',
2371
                'repeat_type',
2372
                get_lang('RepeatType'),
2373
                self::getRepeatTypes()
2374
            );
2375
            $form->addElement(
2376
                'date_picker',
2377
                'repeat_end_day',
2378
                get_lang('RepeatEnd'),
2379
                array('id' => 'repeat_end_date_form')
2380
            );
2381
2382
            if ($isSubEventEdition || $isParentFromSerie) {
2383
                if ($isSubEventEdition) {
2384
                    $parentEvent = $params['parent_info'];
2385
                    $repeatInfo = $parentEvent['repeat_info'];
2386
                } else {
2387
                    $repeatInfo = $params['repeat_info'];
2388
                }
2389
                $params['repeat'] = 1;
2390
                $params['repeat_type'] = $repeatInfo['cal_type'];
2391
                $params['repeat_end_day'] = substr(
2392
                    api_get_local_time($repeatInfo['cal_end']),
2393
                    0,
2394
                    10
2395
                );
2396
2397
                $form->freeze(array('repeat_type', 'repeat_end_day'));
2398
                $repeat->_attributes['disabled'] = 'disabled';
2399
            }
2400
            $form->addElement('html', '</div>');
2401
        }
2402
2403
        if (!empty($id)) {
2404
            if (empty($params['end_date'])) {
2405
                $params['date_range'] = $params['end_date'];
2406
            }
2407
2408
            $params['date_range'] =
2409
                substr(api_get_local_time($params['start_date']), 0, 16).' / '.
2410
                substr(api_get_local_time($params['end_date']), 0, 16);
2411
        }
2412
2413
        if (!api_is_allowed_to_edit(null, true)) {
2414
            $toolbar = 'AgendaStudent';
2415
        } else {
2416
            $toolbar = 'Agenda';
2417
        }
2418
2419
        $form->addElement(
2420
            'html_editor',
2421
            'content',
2422
            get_lang('Description'),
2423
            null,
2424
            array(
2425
                'ToolbarSet' => $toolbar,
2426
                'Width' => '100%',
2427
                'Height' => '200'
2428
            )
2429
        );
2430
2431
        if ($this->type == 'course') {
2432
            $form->addElement('textarea', 'comment', get_lang('Comment'));
2433
            $form->addLabel(
2434
                get_lang('FilesAttachment'),
2435
                '<span id="filepaths">
2436
                        <div id="filepath_1">
2437
                            <input type="file" name="attach_1"/><br />
2438
                            '.get_lang('Description').'&nbsp;&nbsp;<input type="text" name="legend[]" /><br /><br />
2439
                        </div>
2440
                    </span>'
2441
            );
2442
2443
            $form->addLabel(
2444
                '',
2445
                '<span id="link-more-attach">
2446
                    <a href="javascript://" onclick="return add_image_form()">'.
2447
                get_lang('AddOneMoreFile').'</a>
2448
                 </span>&nbsp;('.sprintf(
2449
                    get_lang('MaximunFileSizeX'),
2450
                    format_file_size(
2451
                        api_get_setting('message_max_upload_filesize')
2452
                    )
2453
                ).')'
2454
            );
2455
2456
            if (isset($params['attachment']) && !empty($params['attachment'])) {
2457
                $attachmentList = $params['attachment'];
2458
                foreach ($attachmentList as $attachment) {
2459
                    $params['file_comment'] = $attachment['comment'];
2460
                    if (!empty($attachment['path'])) {
2461
                        $form->addElement(
2462
                            'checkbox',
2463
                            'delete_attachment['.$attachment['id'].']',
2464
                            null,
2465
                            get_lang(
2466
                                'DeleteAttachment'
2467
                            ).': '.$attachment['filename']
2468
                        );
2469
                    }
2470
                }
2471
            }
2472
2473
            $form->addElement(
2474
                'textarea',
2475
                'file_comment',
2476
                get_lang('FileComment')
2477
            );
2478
        }
2479
2480
        if (empty($id)) {
2481
            $form->addElement(
2482
                'checkbox',
2483
                'add_announcement',
2484
                null,
2485
                get_lang('AddAnnouncement').'&nbsp('.get_lang('SendMail').')'
2486
            );
2487
        }
2488
2489
        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...
2490
            $form->addButtonUpdate(get_lang('ModifyEvent'));
2491
        } else {
2492
            $form->addButtonSave(get_lang('AgendaAdd'));
2493
        }
2494
2495
        $form->setDefaults($params);
2496
2497
        $form->addRule(
2498
            'date_range',
2499
            get_lang('ThisFieldIsRequired'),
2500
            'required'
2501
        );
2502
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
2503
2504
        return $form;
2505
    }
2506
2507
    /**
2508
     * @param FormValidator $form
2509
     * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
2510
     * @param array $attributes
2511
     * @param bool $addOnlyItemsInSendTo
2512
     * @param bool $required
2513
     * @return bool
2514
     */
2515
    public function showToForm(
2516
        $form,
2517
        $sendTo = array(),
2518
        $attributes = array(),
2519
        $addOnlyItemsInSendTo = false,
2520
        $required = false
2521
    ) {
2522
        if ($this->type != 'course') {
2523
            return false;
2524
        }
2525
2526
        $order = 'lastname';
2527
        if (api_is_western_name_order()) {
2528
            $order = 'firstname';
2529
        }
2530
2531
        $userList = CourseManager::get_user_list_from_course_code(
2532
            api_get_course_id(),
2533
            $this->sessionId,
2534
            null,
2535
            $order
2536
        );
2537
2538
        $groupList = CourseManager::get_group_list_of_course(
2539
            api_get_course_id(),
2540
            $this->sessionId
2541
        );
2542
2543
        $this->setSendToSelect(
2544
            $form,
2545
            $groupList,
2546
            $userList,
0 ignored issues
show
Bug introduced by
It seems like $userList defined by \CourseManager::get_user...essionId, null, $order) on line 2531 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...
2547
            $sendTo,
2548
            $attributes,
2549
            $addOnlyItemsInSendTo,
2550
            $required
2551
        );
2552
2553
        return true;
2554
    }
2555
2556
    /**
2557
     * @param int $id
2558
     * @param int $visibility 0= invisible, 1 visible
2559
     * @param array $courseInfo
2560
     * @param int $userId
2561
     */
2562
    public static function changeVisibility(
2563
        $id,
2564
        $visibility,
2565
        $courseInfo,
2566
        $userId = null
2567
    ) {
2568
        $id = intval($id);
2569
        if (empty($userId)) {
2570
            $userId = api_get_user_id();
2571
        } else {
2572
            $userId = intval($userId);
2573
        }
2574
2575
        if ($visibility == 0) {
2576
            api_item_property_update(
2577
                $courseInfo,
2578
                TOOL_CALENDAR_EVENT,
2579
                $id,
2580
                'invisible',
2581
                $userId
2582
            );
2583
        } else {
2584
            api_item_property_update(
2585
                $courseInfo,
2586
                TOOL_CALENDAR_EVENT,
2587
                $id,
2588
                'visible',
2589
                $userId
2590
            );
2591
        }
2592
    }
2593
2594
    /**
2595
     * Get repeat types
2596
     * @return array
2597
     */
2598
    public static function getRepeatTypes()
2599
    {
2600
        return array(
2601
            'daily' => get_lang('RepeatDaily'),
2602
            'weekly' => get_lang('RepeatWeekly'),
2603
            'monthlyByDate' => get_lang('RepeatMonthlyByDate'),
2604
            //monthlyByDay"> get_lang('RepeatMonthlyByDay');
2605
            //monthlyByDayR' => get_lang('RepeatMonthlyByDayR'),
2606
            'yearly' => get_lang('RepeatYearly')
2607
        );
2608
    }
2609
2610
    /**
2611
     * Show a list with all the attachments according to the post's id
2612
     * @param int $eventId
2613
     * @param array $courseInfo
2614
     * @return array with the post info
2615
     */
2616 View Code Duplication
    public function getAttachmentList($eventId, $courseInfo)
2617
    {
2618
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2619
        $courseId = intval($courseInfo['real_id']);
2620
        $eventId = intval($eventId);
2621
2622
        $sql = "SELECT id, path, filename, comment
2623
                FROM $tableAttachment
2624
                WHERE
2625
                    c_id = $courseId AND
2626
                    agenda_id = $eventId";
2627
        $result = Database::query($sql);
2628
        $list = array();
2629
        if (Database::num_rows($result) != 0) {
2630
            $list = Database::store_result($result, 'ASSOC');
2631
        }
2632
2633
        return $list;
2634
    }
2635
2636
    /**
2637
     * Show a list with all the attachments according to the post's id
2638
     * @param int $attachmentId
2639
     * @param int $eventId
2640
     * @param array $courseInfo
2641
     * @return array with the post info
2642
     */
2643 View Code Duplication
    public function getAttachment($attachmentId, $eventId, $courseInfo)
2644
    {
2645
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2646
        $courseId = intval($courseInfo['real_id']);
2647
        $eventId = intval($eventId);
2648
        $attachmentId = intval($attachmentId);
2649
2650
        $row = array();
2651
        $sql = "SELECT id, path, filename, comment
2652
                FROM $tableAttachment
2653
                WHERE
2654
                    c_id = $courseId AND
2655
                    agenda_id = $eventId AND
2656
                    id = $attachmentId
2657
                ";
2658
        $result = Database::query($sql);
2659
        if (Database::num_rows($result) != 0) {
2660
            $row = Database::fetch_array($result, 'ASSOC');
2661
        }
2662
2663
        return $row;
2664
    }
2665
2666
    /**
2667
     * Add an attachment file into agenda
2668
     * @param int $eventId
2669
     * @param array $fileUserUpload ($_FILES['user_upload'])
2670
     * @param string $comment about file
2671
     * @param array $courseInfo
2672
     * @return string
2673
     */
2674
    public function addAttachment(
2675
        $eventId,
2676
        $fileUserUpload,
2677
        $comment,
2678
        $courseInfo
2679
    ) {
2680
        $agenda_table_attachment = Database::get_course_table(
2681
            TABLE_AGENDA_ATTACHMENT
2682
        );
2683
        $eventId = intval($eventId);
2684
2685
        // Storing the attachments
2686
        $upload_ok = false;
2687
        if (!empty($fileUserUpload['name'])) {
2688
            $upload_ok = process_uploaded_file($fileUserUpload);
2689
        }
2690
2691
        if (!empty($upload_ok)) {
2692
            $courseDir = $courseInfo['directory'].'/upload/calendar';
2693
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2694
            $uploadDir = $sys_course_path.$courseDir;
2695
2696
            // Try to add an extension to the file if it hasn't one
2697
            $new_file_name = add_ext_on_mime(
2698
                stripslashes($fileUserUpload['name']),
2699
                $fileUserUpload['type']
2700
            );
2701
2702
            // user's file name
2703
            $file_name = $fileUserUpload['name'];
2704
2705
            if (!filter_extension($new_file_name)) {
2706
                return Display::return_message(
2707
                    get_lang('UplUnableToSaveFileFilteredExtension'),
2708
                    'error'
2709
                );
2710
            } else {
2711
                $new_file_name = uniqid('');
2712
                $new_path = $uploadDir.'/'.$new_file_name;
2713
                $result = @move_uploaded_file(
2714
                    $fileUserUpload['tmp_name'],
2715
                    $new_path
2716
                );
2717
                $course_id = api_get_course_int_id();
2718
                $size = intval($fileUserUpload['size']);
2719
                // Storing the attachments if any
2720
                if ($result) {
2721
                    $params = [
2722
                        'c_id' => $course_id,
2723
                        'filename' => $file_name,
2724
                        'comment' => $comment,
2725
                        'path' => $new_file_name,
2726
                        'agenda_id' => $eventId,
2727
                        'size' => $size
2728
                    ];
2729
                    $id = Database::insert($agenda_table_attachment, $params);
2730
                    if ($id) {
2731
                        $sql = "UPDATE $agenda_table_attachment
2732
                                SET id = iid WHERE iid = $id";
2733
                        Database::query($sql);
2734
2735
                        api_item_property_update(
2736
                            $courseInfo,
2737
                            'calendar_event_attachment',
2738
                            $id,
2739
                            'AgendaAttachmentAdded',
2740
                            api_get_user_id()
2741
                        );
2742
                    }
2743
                }
2744
            }
2745
        }
2746
    }
2747
2748
    /**
2749
     * @param int $attachmentId
2750
     * @param int $eventId
2751
     * @param array $fileUserUpload
2752
     * @param string $comment
2753
     * @param array $courseInfo
2754
     */
2755
    public function updateAttachment(
2756
        $attachmentId,
2757
        $eventId,
2758
        $fileUserUpload,
2759
        $comment,
2760
        $courseInfo
2761
    ) {
2762
        $attachment = $this->getAttachment(
2763
            $attachmentId,
2764
            $eventId,
2765
            $courseInfo
2766
        );
2767
        if (!empty($attachment)) {
2768
            $this->deleteAttachmentFile($attachmentId, $courseInfo);
2769
        }
2770
        $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
2771
    }
2772
2773
    /**
2774
     * This function delete a attachment file by id
2775
     * @param int $attachmentId
2776
     * @param array $courseInfo
2777
     * @return string
2778
     */
2779
    public function deleteAttachmentFile($attachmentId, $courseInfo)
2780
    {
2781
        $agenda_table_attachment = Database::get_course_table(
2782
            TABLE_AGENDA_ATTACHMENT
2783
        );
2784
        $attachmentId = intval($attachmentId);
2785
        $courseId = $courseInfo['real_id'];
2786
2787
        if (empty($courseId) || empty($attachmentId)) {
2788
            return false;
2789
        }
2790
2791
        $sql = "DELETE FROM $agenda_table_attachment
2792
                WHERE c_id = $courseId AND id = ".$attachmentId;
2793
        $result = Database::query($sql);
2794
2795
        // update item_property
2796
        api_item_property_update(
2797
            $courseInfo,
2798
            'calendar_event_attachment',
2799
            $attachmentId,
2800
            'AgendaAttachmentDeleted',
2801
            api_get_user_id()
2802
        );
2803
2804
        if (!empty($result)) {
2805
            return Display::return_message(
2806
                get_lang("AttachmentFileDeleteSuccess"),
2807
                'confirmation'
2808
            );
2809
        }
2810
    }
2811
2812
    /**
2813
     * Adds x weeks to a UNIX timestamp
2814
     * @param   int     The timestamp
2815
     * @param   int     The number of weeks to add
2816
     * @param integer $timestamp
2817
     * @return  int     The new timestamp
2818
     */
2819
    public function addWeek($timestamp, $num = 1)
2820
    {
2821
        return $timestamp + $num * 604800;
2822
    }
2823
2824
    /**
2825
     * Adds x months to a UNIX timestamp
2826
     * @param   int     The timestamp
2827
     * @param   int     The number of years to add
2828
     * @param integer $timestamp
2829
     * @return  int     The new timestamp
2830
     */
2831
    public function addMonth($timestamp, $num = 1)
2832
    {
2833
        list($y, $m, $d, $h, $n, $s) = split(
2834
            '/',
2835
            date('Y/m/d/h/i/s', $timestamp)
2836
        );
2837 View Code Duplication
        if ($m + $num > 12) {
2838
            $y += floor($num / 12);
2839
            $m += $num % 12;
2840
        } else {
2841
            $m += $num;
2842
        }
2843
2844
        return mktime($h, $n, $s, $m, $d, $y);
2845
    }
2846
2847
    /**
2848
     * Adds x years to a UNIX timestamp
2849
     * @param   int     The timestamp
2850
     * @param   int     The number of years to add
2851
     * @param integer $timestamp
2852
     * @return  int     The new timestamp
2853
     */
2854
    public function addYear($timestamp, $num = 1)
2855
    {
2856
        list($y, $m, $d, $h, $n, $s) = split(
2857
            '/',
2858
            date('Y/m/d/h/i/s', $timestamp)
2859
        );
2860
2861
        return mktime($h, $n, $s, $m, $d, $y + $num);
2862
    }
2863
2864
    /**
2865
     * @param int $eventId
2866
     * @return array
2867
     */
2868
    public function getAllRepeatEvents($eventId)
2869
    {
2870
        $events = array();
2871
        switch ($this->type) {
2872
            case 'personal':
2873
                break;
2874
            case 'course':
2875
                if (!empty($this->course['real_id'])) {
2876
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
2877
                            WHERE
2878
                                c_id = ".$this->course['real_id']." AND
2879
                                parent_event_id = ".$eventId;
2880
                    $result = Database::query($sql);
2881
                    if (Database::num_rows($result)) {
2882
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
2883
                            $events[] = $row;
2884
                        }
2885
                    }
2886
                }
2887
                break;
2888
        }
2889
2890
        return $events;
2891
    }
2892
2893
    /**
2894
     * @param int $eventId
2895
     * @param int $courseId
2896
     *
2897
     * @return bool
2898
     */
2899 View Code Duplication
    public function hasChildren($eventId, $courseId)
2900
    {
2901
        $eventId = intval($eventId);
2902
        $courseId = intval($courseId);
2903
2904
        $sql = "SELECT count(DISTINCT(id)) as count
2905
                FROM ".$this->tbl_course_agenda."
2906
                WHERE
2907
                    c_id = $courseId AND
2908
                    parent_event_id = $eventId";
2909
        $result = Database::query($sql);
2910
        if (Database::num_rows($result)) {
2911
            $row = Database::fetch_array($result, 'ASSOC');
2912
2913
            return $row['count'] > 0;
2914
        }
2915
2916
        return false;
2917
    }
2918
2919
    /**
2920
     * @param int $filter
2921
     * @param string $view
2922
     * @return string
2923
     */
2924
    public function displayActions($view, $filter = 0)
2925
    {
2926
        $courseInfo = api_get_course_info();
2927
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
2928
        $groupIid = isset($groupInfo['iid']) ? $groupInfo['iid'] : 0;
2929
2930
        $courseCondition = '';
2931
        if (!empty($courseInfo)) {
2932
            $courseCondition = api_get_cidreq();
2933
        }
2934
2935
        $actionsLeft = '';
2936
        $actionsLeft .= "<a href='".api_get_path(
2937
                WEB_CODE_PATH
2938
            )."calendar/agenda_js.php?type={$this->type}&".$courseCondition."'>".
2939
            Display::return_icon(
2940
                'calendar.png',
2941
                get_lang('Calendar'),
2942
                '',
2943
                ICON_SIZE_MEDIUM
2944
            )."</a>";
2945
2946
        $actionsLeft .= "<a href='".api_get_path(
2947
                WEB_CODE_PATH
2948
            )."calendar/agenda_list.php?type={$this->type}&".$courseCondition."'>".
2949
            Display::return_icon(
2950
                'week.png',
2951
                get_lang('AgendaList'),
2952
                '',
2953
                ICON_SIZE_MEDIUM
2954
            )."</a>";
2955
2956
        $form = '';
2957
        if (api_is_allowed_to_edit(false, true) ||
2958
            (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) &&
2959
            api_is_allowed_to_session_edit(false, true) ||
2960
            (GroupManager::user_has_access(
2961
                    api_get_user_id(),
2962
                    $groupIid,
2963
                    GroupManager::GROUP_TOOL_CALENDAR
2964
                ) &&
2965
                GroupManager::is_tutor_of_group(api_get_user_id(), $groupInfo))
2966
        ) {
2967
            $actionsLeft .= Display::url(
2968
                Display::return_icon(
2969
                    'new_event.png',
2970
                    get_lang('AgendaAdd'),
2971
                    '',
2972
                    ICON_SIZE_MEDIUM
2973
                ),
2974
                api_get_path(
2975
                    WEB_CODE_PATH
2976
                )."calendar/agenda.php?".api_get_cidreq(
2977
                )."&action=add&type=".$this->type
2978
            );
2979
2980
            $actionsLeft .= Display::url(
2981
                Display::return_icon(
2982
                    'import_calendar.png',
2983
                    get_lang('ICalFileImport'),
2984
                    '',
2985
                    ICON_SIZE_MEDIUM
2986
                ),
2987
                api_get_path(
2988
                    WEB_CODE_PATH
2989
                )."calendar/agenda.php?".api_get_cidreq(
2990
                )."&action=importical&type=".$this->type
2991
            );
2992
2993
            if ($this->type === 'course') {
2994
                if (!isset($_GET['action'])) {
2995
                    $form = new FormValidator(
2996
                        'form-search',
2997
                        'post',
2998
                        '',
2999
                        '',
3000
                        array(),
3001
                        FormValidator::LAYOUT_INLINE
3002
                    );
3003
                    $attributes = array(
3004
                        'multiple' => false,
3005
                        'id' => 'select_form_id_search'
3006
                    );
3007
                    $selectedValues = $this->parseAgendaFilter($filter);
3008
                    $this->showToForm($form, $selectedValues, $attributes);
3009
                    $form = $form->returnForm();
3010
                }
3011
            }
3012
        }
3013
3014
        if (api_is_platform_admin() ||
3015
            api_is_teacher() ||
3016
            api_is_student_boss() ||
3017
            api_is_drh() ||
3018
            api_is_session_admin() ||
3019
            api_is_coach()
3020
        ) {
3021
            if ($this->type == 'personal') {
3022
                $form = null;
3023
                if (!isset($_GET['action'])) {
3024
                    $form = new FormValidator(
3025
                        'form-search',
3026
                        'get',
3027
                        api_get_self().'?type=personal&',
3028
                        '',
3029
                        array(),
3030
                        FormValidator::LAYOUT_INLINE
3031
                    );
3032
3033
                    $sessions = SessionManager::get_sessions_by_user(
3034
                        api_get_user_id()
3035
                    );
3036
                    $form->addHidden('type', 'personal');
3037
                    $sessions = array_column(
3038
                        $sessions,
3039
                        'session_name',
3040
                        'session_id'
3041
                    );
3042
                    $sessions = ['0' => get_lang('SelectAnOption')] + $sessions;
3043
3044
                    $form->addSelect(
3045
                        'session_id',
3046
                        get_lang('Session'),
3047
                        $sessions,
3048
                        ['id' => 'session_id', 'onchange' => 'submit();']
3049
                    );
3050
3051
                    $form->addButtonReset(get_lang('Reset'));
3052
                    $form = $form->returnForm();
3053
                }
3054
            }
3055
        }
3056
3057
        $actionsRight = '';
3058
        if ($view == 'calendar') {
3059
            $actionsRight .= $form;
3060
        }
3061
3062
        $toolbar = Display::toolbarAction(
3063
            'toolbar-agenda',
3064
            array($actionsLeft, $actionsRight)
3065
        );
3066
3067
        return $toolbar;
3068
    }
3069
3070
    /**
3071
     * @return FormValidator
3072
     */
3073
    public function getImportCalendarForm()
3074
    {
3075
        $form = new FormValidator(
3076
            'frm_import_ical',
3077
            'post',
3078
            api_get_self().'?action=importical&type='.$this->type,
3079
            array('enctype' => 'multipart/form-data')
3080
        );
3081
        $form->addElement('header', get_lang('ICalFileImport'));
3082
        $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
3083
        $form->addRule(
3084
            'ical_import',
3085
            get_lang('ThisFieldIsRequired'),
3086
            'required'
3087
        );
3088
        $form->addButtonImport(get_lang('Import'), 'ical_submit');
3089
3090
        return $form;
3091
    }
3092
3093
    /**
3094
     * @param array $courseInfo
3095
     * @param $file
3096
     * @return false|string
3097
     */
3098
    public function importEventFile($courseInfo, $file)
3099
    {
3100
        $charset = api_get_system_encoding();
3101
        $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
3102
        $messages = array();
3103
3104
        if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
3105
            error_log(
3106
                'Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__
3107
            );
3108
3109
            return false;
3110
        }
3111
3112
        $data = file_get_contents($filepath);
3113
3114
        $trans = array(
3115
            'DAILY' => 'daily',
3116
            'WEEKLY' => 'weekly',
3117
            'MONTHLY' => 'monthlyByDate',
3118
            'YEARLY' => 'yearly'
3119
        );
3120
        $sentTo = array('everyone' => true);
3121
        $calendar = Sabre\VObject\Reader::read($data);
3122
        $currentTimeZone = api_get_timezone();
3123
        if (!empty($calendar->VEVENT)) {
3124
            foreach ($calendar->VEVENT as $event) {
3125
                $start = $event->DTSTART->getDateTime();
3126
                $end = $event->DTEND->getDateTime();
3127
                //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
3128
3129
                $startDateTime = api_get_local_time(
3130
                    $start->format('Y-m-d H:i:s'),
3131
                    $currentTimeZone,
3132
                    $start->format('e')
3133
                );
3134
                $endDateTime = api_get_local_time(
3135
                    $end->format('Y-m-d H:i'),
3136
                    $currentTimeZone,
3137
                    $end->format('e')
3138
                );
3139
                $title = api_convert_encoding(
3140
                    (string)$event->summary,
3141
                    $charset,
3142
                    'UTF-8'
3143
                );
3144
                $description = api_convert_encoding(
3145
                    (string)$event->description,
3146
                    $charset,
3147
                    'UTF-8'
3148
                );
3149
3150
                $id = $this->addEvent(
3151
                    $startDateTime,
3152
                    $endDateTime,
3153
                    'false',
3154
                    $title,
3155
                    $description,
3156
                    $sentTo
3157
                );
3158
3159
                $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
3160
3161
                //$attendee = (string)$event->attendee;
3162
                /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
3163
                $repeat = $event->RRULE;
3164
                if ($id && !empty($repeat)) {
3165
                    $repeat = $repeat->getParts();
3166
                    $freq = $trans[$repeat['FREQ']];
3167
3168
                    if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
3169
                        // Check if datetime or just date (strlen == 8)
3170
                        if (strlen($repeat['UNTIL']) == 8) {
3171
                            // Fix the datetime format to avoid exception in the next step
3172
                            $repeat['UNTIL'] .= 'T000000';
3173
                        }
3174
                        $until = Sabre\VObject\DateTimeParser::parseDateTime(
3175
                            $repeat['UNTIL'],
3176
                            new DateTimeZone($currentTimeZone)
3177
                        );
3178
                        $until = $until->format('Y-m-d H:i');
3179
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $until, $attendee);
3180
                        $this->addRepeatedItem(
3181
                            $id,
3182
                            $freq,
3183
                            $until,
3184
                            $sentTo
3185
                        );
3186
                    }
3187
3188
                    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...
3189
                        /*$count = $repeat['COUNT'];
3190
                        $interval = $repeat['INTERVAL'];
3191
                        $endDate = null;
3192
                        switch($freq) {
3193
                            case 'daily':
3194
                                $start = api_strtotime($startDateTime);
3195
                                $date = new DateTime($startDateTime);
3196
                                $days = $count * $interval;
3197
                                var_dump($days);
3198
                                $date->add(new DateInterval("P".$days."D"));
3199
                                $endDate = $date->format('Y-m-d H:i');
3200
                                //$endDate = $count *
3201
                                for ($i = 0; $i < $count; $i++) {
3202
                                    $days = 86400 * 7
3203
                                }
3204
                            }
3205
                        }*/
3206
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
3207
                        /*$this->addRepeatedItem(
3208
                            $id,
3209
                            $freq,
3210
                            $endDate,
3211
                            $sentTo
3212
                        );*/
3213
                    }
3214
                }
3215
            }
3216
        }
3217
3218
        if (!empty($messages)) {
3219
            $messages = implode('<br /> ', $messages);
3220
        } else {
3221
            $messages = get_lang('NoAgendaItems');
3222
3223
        }
3224
3225
        return $messages;
3226
    }
3227
3228
    /**
3229
     * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]]
3230
     * @param integer $filter
3231
     * @return array
3232
     */
3233
    public function parseAgendaFilter($filter)
3234
    {
3235
        $everyone = false;
3236
        $groupId = null;
3237
        $userId = null;
3238
3239
        if ($filter == 'everyone') {
3240
            $everyone = true;
3241
        } else {
3242
            if (substr($filter, 0, 1) == 'G') {
3243
                $groupId = str_replace('GROUP:', '', $filter);
3244
            } else {
3245
                $userId = str_replace('USER:', '', $filter);
3246
            }
3247
        }
3248
        if (empty($userId) && empty($groupId)) {
3249
            $everyone = true;
3250
        }
3251
3252
        return array(
3253
            'everyone' => $everyone,
3254
            'users' => array($userId),
3255
            'groups' => array($groupId)
3256
        );
3257
    }
3258
3259
    /**
3260
     *    This function retrieves all the agenda items of all the courses the user is subscribed to
3261
     */
3262
    public static function get_myagendaitems(
3263
        $user_id,
3264
        $courses_dbs,
3265
        $month,
3266
        $year
3267
    ) {
3268
        $user_id = intval($user_id);
3269
3270
        $items = array();
3271
        $my_list = array();
3272
3273
        // get agenda-items for every course
3274
        foreach ($courses_dbs as $key => $array_course_info) {
3275
            //databases of the courses
3276
            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
3277
            $TABLE_ITEMPROPERTY = Database::get_course_table(
3278
                TABLE_ITEM_PROPERTY
3279
            );
3280
3281
            $group_memberships = GroupManager::get_group_ids(
3282
                $array_course_info['real_id'],
3283
                $user_id
3284
            );
3285
            $course_user_status = CourseManager::getUserInCourseStatus(
3286
                $user_id,
3287
                $array_course_info['real_id']
3288
            );
3289
            // if the user is administrator of that course we show all the agenda items
3290
            if ($course_user_status == '1') {
3291
                //echo "course admin";
3292
                $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3293
							FROM ".$TABLEAGENDA." agenda,
3294
								 ".$TABLE_ITEMPROPERTY." ip
3295
							WHERE agenda.id = ip.ref
3296
							AND MONTH(agenda.start_date)='".$month."'
3297
							AND YEAR(agenda.start_date)='".$year."'
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
3304
                if (is_array($group_memberships) && count(
3305
                        $group_memberships
3306
                    ) > 0
3307
                ) {
3308
                    $sqlquery = "SELECT	agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3309
								FROM ".$TABLEAGENDA." agenda,
3310
									".$TABLE_ITEMPROPERTY." ip
3311
								WHERE agenda.id = ip.ref
3312
								AND MONTH(agenda.start_date)='".$month."'
3313
								AND YEAR(agenda.start_date)='".$year."'
3314
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3315
								AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
3316
                            ", ",
3317
                            $group_memberships
3318
                        ).")) )
3319
								AND ip.visibility='1'
3320
								ORDER BY start_date ";
3321
                } else {
3322
                    $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3323
								FROM ".$TABLEAGENDA." agenda,
3324
									".$TABLE_ITEMPROPERTY." ip
3325
								WHERE agenda.id = ip.ref
3326
								AND MONTH(agenda.start_date)='".$month."'
3327
								AND YEAR(agenda.start_date)='".$year."'
3328
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3329
								AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
3330
								AND ip.visibility='1'
3331
								ORDER BY start_date ";
3332
                }
3333
            }
3334
            $result = Database::query($sqlquery);
3335
3336
            while ($item = Database::fetch_array($result, 'ASSOC')) {
3337
                $agendaday = -1;
3338
                if (!empty($item['start_date'])) {
3339
                    $item['start_date'] = api_get_local_time(
3340
                        $item['start_date']
3341
                    );
3342
                    $item['start_date_tms'] = api_strtotime(
3343
                        $item['start_date']
3344
                    );
3345
                    $agendaday = date("j", $item['start_date_tms']);
3346
                }
3347
                if (!empty($item['end_date'])) {
3348
                    $item['end_date'] = api_get_local_time($item['end_date']);
3349
                }
3350
3351
                $url = api_get_path(
3352
                        WEB_CODE_PATH
3353
                    )."calendar/agenda.php?cidReq=".urlencode(
3354
                        $array_course_info["code"]
3355
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
3356
3357
                $item['url'] = $url;
3358
                $item['course_name'] = $array_course_info['title'];
3359
                $item['calendar_type'] = 'course';
3360
                $item['course_id'] = $array_course_info['course_id'];
3361
3362
                $my_list[$agendaday][] = $item;
3363
            }
3364
        }
3365
3366
        // sorting by hour for every day
3367
        $agendaitems = array();
3368
        while (list ($agendaday, $tmpitems) = each($items)) {
3369
            if (!isset($agendaitems[$agendaday])) {
3370
                $agendaitems[$agendaday] = '';
3371
            }
3372
            sort($tmpitems);
3373
            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...
3374
                $agendaitems[$agendaday] .= $val;
3375
            }
3376
        }
3377
3378
        return $my_list;
3379
    }
3380
3381
    /**
3382
     * This function retrieves one personal agenda item returns it.
3383
     * @param    array    The array containing existing events. We add to this array.
3384
     * @param    int        Day
3385
     * @param    int        Month
3386
     * @param    int        Year (4 digits)
3387
     * @param    int        Week number
3388
     * @param    string    Type of view (month_view, week_view, day_view)
3389
     * @return    array    The results of the database query, or null if not found
3390
     */
3391
    public static function get_global_agenda_items(
3392
        $agendaitems,
3393
        $day = "",
3394
        $month = "",
3395
        $year = "",
3396
        $week = "",
3397
        $type
3398
    ) {
3399
        $tbl_global_agenda = Database::get_main_table(
3400
            TABLE_MAIN_SYSTEM_CALENDAR
3401
        );
3402
        $month = intval($month);
3403
        $year = intval($year);
3404
        $week = intval($week);
3405
        $day = intval($day);
3406
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3407
3408
        $current_access_url_id = api_get_current_access_url_id();
3409
3410
        if ($type == "month_view" or $type == "") {
3411
            // We are in month view
3412
            $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";
3413
        }
3414
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3415 View Code Duplication
        if ($type == "week_view") { // we are in week view
3416
            $start_end_day_of_week = self::calculate_start_end_of_week(
3417
                $week,
3418
                $year
3419
            );
3420
            $start_day = $start_end_day_of_week['start']['day'];
3421
            $start_month = $start_end_day_of_week['start']['month'];
3422
            $start_year = $start_end_day_of_week['start']['year'];
3423
            $end_day = $start_end_day_of_week['end']['day'];
3424
            $end_month = $start_end_day_of_week['end']['month'];
3425
            $end_year = $start_end_day_of_week['end']['year'];
3426
            // in sql statements you have to use year-month-day for date calculations
3427
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3428
            $start_filter = api_get_utc_datetime($start_filter);
3429
3430
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3431
            $end_filter = api_get_utc_datetime($end_filter);
3432
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND  access_url_id = $current_access_url_id ";
3433
        }
3434
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3435 View Code Duplication
        if ($type == "day_view") { // we are in day view
3436
            // we could use mysql date() function but this is only available from 4.1 and higher
3437
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3438
            $start_filter = api_get_utc_datetime($start_filter);
3439
3440
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3441
            $end_filter = api_get_utc_datetime($end_filter);
3442
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'  AND  access_url_id = $current_access_url_id";
3443
        }
3444
3445
        $result = Database::query($sql);
3446
3447
        while ($item = Database::fetch_array($result)) {
3448
3449
            if (!empty($item['start_date'])) {
3450
                $item['start_date'] = api_get_local_time($item['start_date']);
3451
                $item['start_date_tms'] = api_strtotime($item['start_date']);
3452
            }
3453
            if (!empty($item['end_date'])) {
3454
                $item['end_date'] = api_get_local_time($item['end_date']);
3455
            }
3456
3457
            // we break the date field in the database into a date and a time part
3458
            $agenda_db_date = explode(" ", $item['start_date']);
3459
            $date = $agenda_db_date[0];
3460
            $time = $agenda_db_date[1];
3461
            // we divide the date part into a day, a month and a year
3462
            $agendadate = explode("-", $date);
3463
            $year = intval($agendadate[0]);
3464
            $month = intval($agendadate[1]);
3465
            $day = intval($agendadate[2]);
3466
            // we divide the time part into hour, minutes, seconds
3467
            $agendatime = explode(":", $time);
3468
            $hour = $agendatime[0];
3469
            $minute = $agendatime[1];
3470
            $second = $agendatime[2];
3471
3472
            if ($type == 'month_view') {
3473
                $item['calendar_type'] = 'global';
3474
                $agendaitems[$day][] = $item;
3475
                continue;
3476
            }
3477
3478
            $start_time = api_format_date(
3479
                $item['start_date'],
3480
                TIME_NO_SEC_FORMAT
3481
            );
3482
            $end_time = '';
3483 View Code Duplication
            if (!empty($item['end_date'])) {
3484
                $end_time = ' - '.api_format_date(
3485
                        $item['end_date'],
3486
                        DATE_TIME_FORMAT_LONG
3487
                    );
3488
            }
3489
3490
            // if the student has specified a course we a add a link to that course
3491 View Code Duplication
            if ($item['course'] <> "") {
3492
                $url = api_get_path(
3493
                        WEB_CODE_PATH
3494
                    )."admin/agenda.php?cidReq=".urlencode(
3495
                        $item['course']
3496
                    )."&day=$day&month=$month&year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
3497
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
3498
            } else {
3499
                $course_link = "";
3500
            }
3501
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3502
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3503
            if ($type !== "day_view") {
3504
                // This is the array construction for the WEEK or MONTH view
3505
                //Display the Agenda global in the tab agenda (administrator)
3506
                $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
3507
                $agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
3508
                $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
3509
            } else {
3510
                // this is the array construction for the DAY view
3511
                $halfhour = 2 * $agendatime['0'];
3512
                if ($agendatime['1'] >= '30') {
3513
                    $halfhour = $halfhour + 1;
3514
                }
3515
                if (!is_array($agendaitems[$halfhour])) {
3516
                    $content = $agendaitems[$halfhour];
3517
                }
3518
                $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
3519
                        'GlobalEvent'
3520
                    ).":  </b>".$item['title']."</div>";
3521
            }
3522
        }
3523
3524
        return $agendaitems;
3525
    }
3526
3527
    /**
3528
     * This function retrieves all the personal agenda items and add them to the agenda items found by the other functions.
3529
     */
3530
    public static function get_personal_agenda_items(
3531
        $user_id,
3532
        $agendaitems,
3533
        $day = "",
3534
        $month = "",
3535
        $year = "",
3536
        $week = "",
3537
        $type
3538
    ) {
3539
        $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
3540
        $user_id = intval($user_id);
3541
3542
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3543
        if ($type == "month_view" or $type == "") {
3544
            // we are in month view
3545
            $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."'  ORDER BY date ASC";
3546
        }
3547
3548
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3549
        // we are in week view
3550 View Code Duplication
        if ($type == "week_view") {
3551
            $start_end_day_of_week = self::calculate_start_end_of_week(
3552
                $week,
3553
                $year
3554
            );
3555
            $start_day = $start_end_day_of_week['start']['day'];
3556
            $start_month = $start_end_day_of_week['start']['month'];
3557
            $start_year = $start_end_day_of_week['start']['year'];
3558
            $end_day = $start_end_day_of_week['end']['day'];
3559
            $end_month = $start_end_day_of_week['end']['month'];
3560
            $end_year = $start_end_day_of_week['end']['year'];
3561
            // in sql statements you have to use year-month-day for date calculations
3562
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3563
            $start_filter = api_get_utc_datetime($start_filter);
3564
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3565
            $end_filter = api_get_utc_datetime($end_filter);
3566
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3567
        }
3568
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3569 View Code Duplication
        if ($type == "day_view") {
3570
            // we are in day view
3571
            // we could use mysql date() function but this is only available from 4.1 and higher
3572
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3573
            $start_filter = api_get_utc_datetime($start_filter);
3574
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3575
            $end_filter = api_get_utc_datetime($end_filter);
3576
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3577
        }
3578
3579
        $result = Database::query($sql);
3580
        while ($item = Database::fetch_array($result, 'ASSOC')) {
3581
3582
            $time_minute = api_convert_and_format_date(
3583
                $item['date'],
3584
                TIME_NO_SEC_FORMAT
3585
            );
3586
            $item['date'] = api_get_local_time($item['date']);
3587
            $item['start_date_tms'] = api_strtotime($item['date']);
3588
            $item['content'] = $item['text'];
3589
3590
            // we break the date field in the database into a date and a time part
3591
            $agenda_db_date = explode(" ", $item['date']);
3592
            $date = $agenda_db_date[0];
3593
            $time = $agenda_db_date[1];
3594
            // we divide the date part into a day, a month and a year
3595
            $agendadate = explode("-", $item['date']);
3596
            $year = intval($agendadate[0]);
3597
            $month = intval($agendadate[1]);
3598
            $day = intval($agendadate[2]);
3599
            // we divide the time part into hour, minutes, seconds
3600
            $agendatime = explode(":", $time);
3601
3602
            $hour = $agendatime[0];
3603
            $minute = $agendatime[1];
3604
            $second = $agendatime[2];
3605
3606
            if ($type == 'month_view') {
3607
                $item['calendar_type'] = 'personal';
3608
                $item['start_date'] = $item['date'];
3609
                $agendaitems[$day][] = $item;
3610
                continue;
3611
            }
3612
3613
            // if the student has specified a course we a add a link to that course
3614 View Code Duplication
            if ($item['course'] <> "") {
3615
                $url = api_get_path(
3616
                        WEB_CODE_PATH
3617
                    )."calendar/agenda.php?cidReq=".urlencode(
3618
                        $item['course']
3619
                    )."&day=$day&month=$month&year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
3620
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
3621
            } else {
3622
                $course_link = "";
3623
            }
3624
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3625
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3626
            if ($type !== "day_view") {
3627
                // This is the array construction for the WEEK or MONTH view
3628
3629
                //Display events in agenda
3630
                $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 />";
3631
3632
            } else {
3633
                // this is the array construction for the DAY view
3634
                $halfhour = 2 * $agendatime['0'];
3635
                if ($agendatime['1'] >= '30') {
3636
                    $halfhour = $halfhour + 1;
3637
                }
3638
3639
                //Display events by list
3640
                $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>";
3641
            }
3642
        }
3643
3644
        return $agendaitems;
3645
    }
3646
3647
3648
    /**
3649
     * Show the monthcalender of the given month
3650
     * @param    array    Agendaitems
3651
     * @param    int    Month number
3652
     * @param    int    Year number
3653
     * @param    array    Array of strings containing long week day names (deprecated, you can send an empty array instead)
3654
     * @param    string    The month name
3655
     * @return    void    Direct output
3656
     */
3657
    public static function display_mymonthcalendar(
3658
        $user_id,
3659
        $agendaitems,
3660
        $month,
3661
        $year,
3662
        $weekdaynames = array(),
3663
        $monthName,
3664
        $show_content = true
3665
    ) {
3666
        global $DaysShort, $course_path;
3667
        //Handle leap year
3668
        $numberofdays = array(
3669
            0,
3670
            31,
3671
            28,
3672
            31,
3673
            30,
3674
            31,
3675
            30,
3676
            31,
3677
            31,
3678
            30,
3679
            31,
3680
            30,
3681
            31
3682
        );
3683 View Code Duplication
        if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0)) {
3684
            $numberofdays[2] = 29;
3685
        }
3686
        //Get the first day of the month
3687
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
3688
        //Start the week on monday
3689
        $startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
3690
        $g_cc = (isset($_GET['courseCode']) ? $_GET['courseCode'] : '');
3691
3692
        $next_month = ($month == 1 ? 12 : $month - 1);
3693
        $prev_month = ($month == 12 ? 1 : $month + 1);
3694
3695
        $next_year = ($month == 1 ? $year - 1 : $year);
3696
        $prev_year = ($month == 12 ? $year + 1 : $year);
3697
3698
        if ($show_content) {
3699
            $back_url = Display::url(
3700
                get_lang('Previous'),
3701
                api_get_self()."?coursePath=".urlencode(
3702
                    $course_path
3703
                )."&courseCode=".Security::remove_XSS(
3704
                    $g_cc
3705
                )."&action=view&view=month&month=".$next_month."&year=".$next_year
3706
            );
3707
            $next_url = Display::url(
3708
                get_lang('Next'),
3709
                api_get_self()."?coursePath=".urlencode(
3710
                    $course_path
3711
                )."&courseCode=".Security::remove_XSS(
3712
                    $g_cc
3713
                )."&action=view&view=month&month=".$prev_month."&year=".$prev_year
3714
            );
3715
        } else {
3716
            $back_url = Display::url(
3717
                get_lang('Previous'),
3718
                '',
3719
                array(
3720
                    'onclick' => "load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ",
3721
                    'class' => 'btn ui-button ui-widget ui-state-default'
3722
                )
3723
            );
3724
            $next_url = Display::url(
3725
                get_lang('Next'),
3726
                '',
3727
                array(
3728
                    'onclick' => "load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ",
3729
                    'class' => 'pull-right btn ui-button ui-widget ui-state-default'
3730
                )
3731
            );
3732
        }
3733
        $html = '';
3734
        $html .= '<div class="actions">';
3735
        $html .= '<div class="row">';
3736
        $html .= '<div class="col-md-4">'.$back_url.'</div>';
3737
        $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
3738
        $html .= '<div class="col-md-4">'.$next_url.'</div>';
3739
        $html .= '</div>';
3740
        $html .= '</div>';
3741
        $html .= '<table id="agenda_list2" class="table table-bordered">';
3742
        $html .= '<tr>';
3743 View Code Duplication
        for ($ii = 1; $ii < 8; $ii++) {
3744
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
3745
        }
3746
        $html .= '</tr>';
3747
3748
        $curday = -1;
3749
        $today = getdate();
3750
        while ($curday <= $numberofdays[$month]) {
3751
            $html .= "<tr>";
3752
            for ($ii = 0; $ii < 7; $ii++) {
3753
                if (($curday == -1) && ($ii == $startdayofweek)) {
3754
                    $curday = 1;
3755
                }
3756
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
3757
                    $bgcolor = $class = 'class="days_week"';
3758
                    $dayheader = Display::div(
3759
                        $curday,
3760
                        array('class' => 'agenda_day')
3761
                    );
3762 View Code Duplication
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
3763
                        $class = "class=\"days_today\" style=\"width:10%;\"";
3764
                    }
3765
3766
                    $html .= "<td ".$class.">".$dayheader;
3767
3768
                    if (!empty($agendaitems[$curday])) {
3769
                        $items = $agendaitems[$curday];
3770
                        $items = msort($items, 'start_date_tms');
3771
3772
                        foreach ($items as $value) {
3773
                            $value['title'] = Security::remove_XSS(
3774
                                $value['title']
3775
                            );
3776
                            $start_time = api_format_date(
3777
                                $value['start_date'],
3778
                                TIME_NO_SEC_FORMAT
3779
                            );
3780
                            $end_time = '';
3781
3782 View Code Duplication
                            if (!empty($value['end_date'])) {
3783
                                $end_time = '-&nbsp;<i>'.api_format_date(
3784
                                        $value['end_date'],
3785
                                        DATE_TIME_FORMAT_LONG
3786
                                    ).'</i>';
3787
                            }
3788
                            $complete_time = '<i>'.api_format_date(
3789
                                    $value['start_date'],
3790
                                    DATE_TIME_FORMAT_LONG
3791
                                ).'</i>&nbsp;'.$end_time;
3792
                            $time = '<i>'.$start_time.'</i>';
3793
3794
                            switch ($value['calendar_type']) {
3795
                                case 'personal':
3796
                                    $bg_color = '#D0E7F4';
3797
                                    $icon = Display::return_icon(
3798
                                        'user.png',
3799
                                        get_lang('MyAgenda'),
3800
                                        array(),
3801
                                        ICON_SIZE_SMALL
3802
                                    );
3803
                                    break;
3804
                                case 'global':
3805
                                    $bg_color = '#FFBC89';
3806
                                    $icon = Display::return_icon(
3807
                                        'view_remove.png',
3808
                                        get_lang('GlobalEvent'),
3809
                                        array(),
3810
                                        ICON_SIZE_SMALL
3811
                                    );
3812
                                    break;
3813
                                case 'course':
3814
                                    $bg_color = '#CAFFAA';
3815
                                    $icon_name = 'course.png';
3816
                                    if (!empty($value['session_id'])) {
3817
                                        $icon_name = 'session.png';
3818
                                    }
3819
                                    if ($show_content) {
3820
                                        $icon = Display::url(
3821
                                            Display::return_icon(
3822
                                                $icon_name,
3823
                                                $value['course_name'].' '.get_lang(
3824
                                                    'Course'
3825
                                                ),
3826
                                                array(),
3827
                                                ICON_SIZE_SMALL
3828
                                            ),
3829
                                            $value['url']
3830
                                        );
3831 View Code Duplication
                                    } else {
3832
                                        $icon = Display::return_icon(
3833
                                            $icon_name,
3834
                                            $value['course_name'].' '.get_lang(
3835
                                                'Course'
3836
                                            ),
3837
                                            array(),
3838
                                            ICON_SIZE_SMALL
3839
                                        );
3840
                                    }
3841
                                    break;
3842
                                default:
3843
                                    break;
3844
                            }
3845
3846
                            $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
3847
3848
                            if ($show_content) {
3849
3850
                                //Setting a personal event to green
3851
                                $icon = Display::div(
3852
                                    $icon,
3853
                                    array('style' => 'float:right')
3854
                                );
3855
3856
                                $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
3857
3858
                                //Link to bubble
3859
                                $url = Display::url(
3860
                                    cut($value['title'], 40),
3861
                                    '#',
3862
                                    array('id' => $link, 'class' => 'opener')
3863
                                );
3864
                                $result .= $time.' '.$icon.' '.Display::div(
3865
                                        $url
3866
                                    );
3867
3868
                                //Hidden content
3869
                                $content = Display::div(
3870
                                    $icon.Display::tag(
3871
                                        'h2',
3872
                                        $value['course_name']
3873
                                    ).'<hr />'.Display::tag(
3874
                                        'h3',
3875
                                        $value['title']
3876
                                    ).$complete_time.'<hr />'.Security::remove_XSS(
3877
                                        $value['content']
3878
                                    )
3879
                                );
3880
3881
                                //Main div
3882
                                $result .= Display::div(
3883
                                    $content,
3884
                                    array(
3885
                                        'id' => 'main_'.$link,
3886
                                        'class' => 'dialog',
3887
                                        'style' => 'display:none'
3888
                                    )
3889
                                );
3890
                                $result .= '</div>';
3891
                                $html .= $result;
3892
                                //echo Display::div($content, array('id'=>'main_'.$value['calendar_type'].'_'.$value['id'], 'class' => 'dialog'));
3893
                            } else {
3894
                                $html .= $result .= $icon.'</div>';
3895
                            }
3896
                        }
3897
                    }
3898
                    $html .= "</td>";
3899
                    $curday++;
3900
                } else {
3901
                    $html .= "<td></td>";
3902
                }
3903
            }
3904
            $html .= "</tr>";
3905
        }
3906
        $html .= "</table>";
3907
        echo $html;
3908
    }
3909
3910
    /**
3911
     * Get personal agenda items between two dates (=all events from all registered courses)
3912
     * @param    int        user ID of the user
3913
     * @param    string    Optional start date in datetime format (if no start date is given, uses today)
3914
     * @param    string    Optional end date in datetime format (if no date is given, uses one year from now)
3915
     * @param integer $user_id
3916
     * @return    array    Array of events ordered by start date, in
3917
     * [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
3918
     * where datestart and dateend are in yyyyMMddhhmmss format.
3919
     * @deprecated use agenda events
3920
     */
3921
    public static function get_personal_agenda_items_between_dates(
3922
        $user_id,
3923
        $date_start = '',
3924
        $date_end = ''
3925
    ) {
3926
        $items = array();
3927
        if ($user_id != strval(intval($user_id))) {
3928
            return $items;
3929
        }
3930
        if (empty($date_start)) {
3931
            $date_start = date('Y-m-d H:i:s');
3932
        }
3933
        if (empty($date_end)) {
3934
            $date_end = date(
3935
                'Y-m-d H:i:s',
3936
                mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1)
3937
            );
3938
        }
3939
        $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
3940
        if (!preg_match($expr, $date_start)) {
3941
            return $items;
3942
        }
3943
        if (!preg_match($expr, $date_end)) {
3944
            return $items;
3945
        }
3946
3947
        // get agenda-items for every course
3948
        $courses = api_get_user_courses($user_id, false);
3949
        foreach ($courses as $id => $course) {
3950
            $c = api_get_course_info_by_id($course['real_id']);
3951
            //databases of the courses
3952
            $t_a = Database::get_course_table(TABLE_AGENDA, $course['db']);
3953
            $t_ip = Database::get_course_table(
3954
                TABLE_ITEM_PROPERTY,
3955
                $course['db']
3956
            );
3957
            // get the groups to which the user belong
3958
            $group_memberships = GroupManager:: get_group_ids(
3959
                $course['db'],
3960
                $user_id
3961
            );
3962
            // if the user is administrator of that course we show all the agenda items
3963
            if ($course['status'] == '1') {
3964
                //echo "course admin";
3965
                $sqlquery = "SELECT ".
3966
                    " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3967
                    " FROM ".$t_a." agenda, ".
3968
                    $t_ip." ip ".
3969
                    " WHERE agenda.id = ip.ref ".
3970
                    " AND agenda.start_date>='$date_start' ".
3971
                    " AND agenda.end_date<='$date_end' ".
3972
                    " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3973
                    " AND ip.visibility='1' ".
3974
                    " GROUP BY agenda.id ".
3975
                    " ORDER BY start_date ";
3976
            } else {
3977
                // if the user is not an administrator of that course, then...
3978
                if (is_array($group_memberships) && count(
3979
                        $group_memberships
3980
                    ) > 0
3981
                ) {
3982
                    $sqlquery = "SELECT ".
3983
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3984
                        " FROM ".$t_a." agenda, ".
3985
                        $t_ip." ip ".
3986
                        " WHERE agenda.id = ip.ref ".
3987
                        " AND agenda.start_date>='$date_start' ".
3988
                        " AND agenda.end_date<='$date_end' ".
3989
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3990
                        " AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
3991
                            ", ",
3992
                            $group_memberships
3993
                        ).")) ) ".
3994
                        " AND ip.visibility='1' ".
3995
                        " ORDER BY start_date ";
3996
                } else {
3997
                    $sqlquery = "SELECT ".
3998
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3999
                        " FROM ".$t_a." agenda, ".
4000
                        $t_ip." ip ".
4001
                        " WHERE agenda.id = ip.ref ".
4002
                        " AND agenda.start_date>='$date_start' ".
4003
                        " AND agenda.end_date<='$date_end' ".
4004
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4005
                        " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
4006
                        " AND ip.visibility='1' ".
4007
                        " ORDER BY start_date ";
4008
                }
4009
            }
4010
4011
            $result = Database::query($sqlquery);
4012
            while ($item = Database::fetch_array($result)) {
4013
                $agendaday = date("j", strtotime($item['start_date']));
4014
                $month = date("n", strtotime($item['start_date']));
4015
                $year = date("Y", strtotime($item['start_date']));
4016
                $URL = api_get_path(
4017
                        WEB_PATH
4018
                    )."main/calendar/agenda.php?cidReq=".urlencode(
4019
                        $course["code"]
4020
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
4021
                list($year, $month, $day, $hour, $min, $sec) = split(
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...
4022
                    '[-: ]',
4023
                    $item['start_date']
4024
                );
4025
                $start_date = $year.$month.$day.$hour.$min;
4026
                list($year, $month, $day, $hour, $min, $sec) = split(
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...
4027
                    '[-: ]',
4028
                    $item['end_date']
4029
                );
4030
                $end_date = $year.$month.$day.$hour.$min;
4031
4032
                $items[] = array(
4033
                    'datestart' => $start_date,
4034
                    'dateend' => $end_date,
4035
                    'title' => $item['title'],
4036
                    'link' => $URL,
4037
                    'coursetitle' => $c['name'],
4038
                );
4039
            }
4040
        }
4041
4042
        return $items;
4043
    }
4044
4045
    /**
4046
     * This function retrieves one personal agenda item returns it.
4047
     * @param    int $id The agenda item ID
4048
     * @return    array    The results of the database query, or null if not found
4049
     */
4050 View Code Duplication
    public static function get_personal_agenda_item($id)
4051
    {
4052
        $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
4053
        $id = intval($id);
4054
        // make sure events of the personal agenda can only be seen by the user himself
4055
        $user = api_get_user_id();
4056
        $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE id=".$id." AND user = ".$user;
4057
        $result = Database::query($sql);
4058
        if (Database::num_rows($result) == 1) {
4059
            $item = Database::fetch_array($result);
4060
        } else {
4061
            $item = null;
4062
        }
4063
4064
        return $item;
4065
    }
4066
4067
    /**
4068
     * This function calculates the startdate of the week (monday)
4069
     * and the enddate of the week (sunday)
4070
     * and returns it as an array
4071
     */
4072
    public static function calculate_start_end_of_week($week_number, $year)
4073
    {
4074
        // determine the start and end date
4075
        // step 1: we calculate a timestamp for a day in this week
4076
        $random_day_in_week = mktime(
4077
                0,
4078
                0,
4079
                0,
4080
                1,
4081
                1,
4082
                $year
4083
            ) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
4084
        // step 2: we which day this is (0=sunday, 1=monday, ...)
4085
        $number_day_in_week = date('w', $random_day_in_week);
4086
        // step 3: we calculate the timestamp of the monday of the week we are in
4087
        $start_timestamp = $random_day_in_week - (($number_day_in_week - 1) * 24 * 60 * 60);
4088
        // step 4: we calculate the timestamp of the sunday of the week we are in
4089
        $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week + 1) * 24 * 60 * 60) - 3600;
4090
        // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
4091
        $start_day = date('j', $start_timestamp);
4092
        $start_month = date('n', $start_timestamp);
4093
        $start_year = date('Y', $start_timestamp);
4094
        $end_day = date('j', $end_timestamp);
4095
        $end_month = date('n', $end_timestamp);
4096
        $end_year = date('Y', $end_timestamp);
4097
        $start_end_array['start']['day'] = $start_day;
4098
        $start_end_array['start']['month'] = $start_month;
4099
        $start_end_array['start']['year'] = $start_year;
4100
        $start_end_array['end']['day'] = $end_day;
4101
        $start_end_array['end']['month'] = $end_month;
4102
        $start_end_array['end']['year'] = $end_year;
4103
4104
        return $start_end_array;
4105
    }
4106
4107
    /**
4108
     * @return bool
4109
     */
4110
    public function getIsAllowedToEdit()
4111
    {
4112
        return $this->isAllowedToEdit;
4113
    }
4114
4115
    /**
4116
     * @param bool $isAllowedToEdit
4117
     */
4118
    public function setIsAllowedToEdit($isAllowedToEdit)
4119
    {
4120
        $this->isAllowedToEdit = $isAllowedToEdit;
4121
    }
4122
4123
    /**
4124
     * @param int $userId
4125
     * @param array $event
4126
     *
4127
     * @return bool
4128
     */
4129
    public function sendEmail($userId, $event)
4130
    {
4131
        $userInfo = api_get_user_info($userId);
4132
4133
        if (!empty($this->sessionInfo)) {
4134
            $courseTitle = $this->course['name'].' ('.$this->sessionInfo['title'].')';
4135
        } else {
4136
            $courseTitle = $this->course['name'];
4137
        }
4138
4139
4140
4141
        api_mail_html(
4142
            $userInfo['complete_name'],
4143
            $userInfo['mail'],
4144
            $subject,
0 ignored issues
show
Bug introduced by
The variable $subject does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
4145
            $emailBody
0 ignored issues
show
Bug introduced by
The variable $emailBody does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
4146
        );
4147
4148
        return true;
4149
    }
4150
}
4151