Completed
Push — master ( 395485...bbad3a )
by Julito
43:12
created

Agenda::getSessionEvents()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 17
nc 3
nop 5
dl 0
loc 24
rs 8.9713
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
26
    /**
27
     * Constructor
28
     * @param string $type
29
     * @param int $senderId Optional The user sender ID
30
     * @param int $courseId Opitonal. The course ID
31
     * @param int $sessionId Optional The session ID
32
     */
33
    public function __construct(
34
        $type,
35
        $senderId = 0,
36
        $courseId = 0,
37
        $sessionId = 0
38
    ) {
39
        // Table definitions
40
        $this->tbl_global_agenda = Database::get_main_table(
41
            TABLE_MAIN_SYSTEM_CALENDAR
42
        );
43
        $this->tbl_personal_agenda = Database::get_main_table(
44
            TABLE_PERSONAL_AGENDA
45
        );
46
        $this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
47
        $this->table_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
48
49
        $this->setType($type);
50
        $this->setSenderId($senderId ?: api_get_user_id());
51
        $isAllowToEdit = false;
52
53
        switch ($type) {
54
            case 'course':
55
                $sessionId = $sessionId ?: api_get_session_id();
56
                $sessionInfo = api_get_session_info($sessionId);
57
                $this->setSessionId($sessionId);
58
                $this->setSessionInfo($sessionInfo);
59
60
                // Setting the course object if we are in a course
61
                $courseInfo = api_get_course_info_by_id($courseId);
62
                if (!empty($courseInfo)) {
63
                    $this->set_course($courseInfo);
64
                }
65
66
                // Check if teacher
67
                if (empty($sessionId)) {
68
                    $isAllowToEdit = api_is_allowed_to_edit(false, true);
69
                } else {
70
                    $isAllowToEdit = api_is_allowed_to_session_edit(
71
                        false,
72
                        true
73
                    );
74
                }
75
76
                // Check
77
                if (api_get_course_setting('allow_user_edit_agenda') && api_is_allowed_in_course()) {
78
                    $isAllowToEdit = true;
79
                }
80
81
                $groupId = api_get_group_id();
82
                if (!empty($groupId)) {
83
                    $groupInfo = GroupManager::get_group_properties($groupId);
84
                    $isGroupAccess = GroupManager::user_has_access(
85
                            api_get_user_id(),
86
                            $groupInfo['iid'],
87
                            GroupManager::GROUP_TOOL_CALENDAR
88
                        ) &&
89
                        GroupManager::is_tutor_of_group(
90
                            api_get_user_id(),
91
                            $groupInfo['iid']
92
                        );
93
                    if ($isGroupAccess) {
94
                        $isAllowToEdit = true;
95
                    } else {
96
                        $isAllowToEdit = false;
97
                    }
98
                }
99
100
                break;
101
            case 'admin':
102
                $isAllowToEdit = api_is_platform_admin();
103
                break;
104
            case 'personal':
105
                $isAllowToEdit = !api_is_anonymous();
106
                break;
107
        }
108
109
        $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 70 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...
110
        $this->events = [];
111
112
        // Event colors
113
        $this->event_platform_color = 'red'; //red
114
        $this->event_course_color = '#458B00'; //green
115
        $this->event_group_color = '#A0522D'; //siena
116
        $this->event_session_color = '#00496D'; // kind of green
117
        $this->eventOtherSessionColor = '#999';
118
        $this->event_personal_color = 'steel blue'; //steel blue
119
    }
120
121
    /**
122
     * @param int $senderId
123
     */
124
    public function setSenderId($senderId)
125
    {
126
        $this->senderId = intval($senderId);
127
    }
128
129
    /**
130
     * @return int
131
     */
132
    public function getSenderId()
133
    {
134
        return $this->senderId;
135
    }
136
137
    /**
138
     * @param string $type can be 'personal', 'admin'  or  'course'
139
     */
140
    public function setType($type)
141
    {
142
        $typeList = $this->getTypes();
143
144
        if (in_array($type, $typeList)) {
145
            $this->type = $type;
146
        }
147
    }
148
149
    /**
150
     * @param int $id
151
     */
152
    public function setSessionId($id)
153
    {
154
        $this->sessionId = intval($id);
155
    }
156
157
    /**
158
     * @param array $sessionInfo
159
     */
160
    public function setSessionInfo($sessionInfo)
161
    {
162
        $this->sessionInfo = $sessionInfo;
163
    }
164
165
    /**
166
     * @return int $id
167
     */
168
    public function getSessionId()
169
    {
170
        return $this->sessionId;
171
    }
172
173
    /**
174
     * @param array $courseInfo
175
     */
176
    public function set_course($courseInfo)
177
    {
178
        $this->course = $courseInfo;
179
    }
180
181
    /**
182
     * @return array
183
     */
184
    public function getTypes()
185
    {
186
        return $this->types;
187
    }
188
189
    /**
190
     * Adds an event to the calendar
191
     * @param string $start datetime format: 2012-06-14 09:00:00
192
     * @param string $end datetime format: 2012-06-14 09:00:00
193
     * @param string $allDay (true, false)
194
     * @param string $title
195
     * @param string $content
196
     * @param array $usersToSend array('everyone') or a list of user/group ids
197
     * @param bool $addAsAnnouncement event as a *course* announcement
198
     * @param int $parentEventId
199
     * @param array $attachmentArray array of $_FILES['']
200
     * @param array $attachmentCommentList
201
     * @param string $eventComment
202
     * @param string $color
203
     *
204
     * @return int
205
     */
206
    public function addEvent(
207
        $start,
208
        $end,
209
        $allDay,
210
        $title,
211
        $content,
212
        $usersToSend = array(),
213
        $addAsAnnouncement = false,
214
        $parentEventId = null,
215
        $attachmentArray = array(),
216
        $attachmentCommentList = array(),
217
        $eventComment = null,
218
        $color = ''
219
    ) {
220
        $start = api_get_utc_datetime($start);
221
        $end = api_get_utc_datetime($end);
222
        $allDay = isset($allDay) && $allDay === 'true' ? 1 : 0;
223
        $id = null;
224
225
        switch ($this->type) {
226
            case 'personal':
227
                $attributes = array(
228
                    'user' => api_get_user_id(),
229
                    'title' => $title,
230
                    'text' => $content,
231
                    'date' => $start,
232
                    'enddate' => $end,
233
                    'all_day' => $allDay,
234
                    'color' => $color
235
                );
236
237
                $id = Database::insert(
238
                    $this->tbl_personal_agenda,
239
                    $attributes
240
                );
241
                break;
242
            case 'course':
243
                $attributes = array(
244
                    'title' => $title,
245
                    'content' => $content,
246
                    'start_date' => $start,
247
                    'end_date' => $end,
248
                    'all_day' => $allDay,
249
                    'session_id' => $this->getSessionId(),
250
                    'c_id' => $this->course['real_id'],
251
                    'comment' => $eventComment,
252
                    'color' => $color
253
                );
254
255
                if (!empty($parentEventId)) {
256
                    $attributes['parent_event_id'] = $parentEventId;
257
                }
258
259
                $senderId = $this->getSenderId();
260
                $sessionId = $this->getSessionId();
261
262
                // Simple course event.
263
                $id = Database::insert($this->tbl_course_agenda, $attributes);
264
265
                if ($id) {
266
                    $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
267
                    Database::query($sql);
268
269
                    $groupId = api_get_group_id();
270
                    $groupIid = 0;
271
                    if ($groupId) {
272
                        $groupInfo = GroupManager::get_group_properties(
273
                            $groupId
274
                        );
275
                        if ($groupInfo) {
276
                            $groupIid = $groupInfo['iid'];
277
                        }
278
                    }
279
280
                    if (!empty($usersToSend)) {
281
                        $sendTo = $this->parseSendToArray($usersToSend);
282
283
                        if ($sendTo['everyone']) {
284
                            api_item_property_update(
285
                                $this->course,
286
                                TOOL_CALENDAR_EVENT,
287
                                $id,
288
                                'AgendaAdded',
289
                                $senderId,
290
                                $groupIid,
291
                                '',
292
                                $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 220 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...
293
                                $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 221 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...
294
                                $sessionId
295
                            );
296
                            api_item_property_update(
297
                                $this->course,
298
                                TOOL_CALENDAR_EVENT,
299
                                $id,
300
                                'visible',
301
                                $senderId,
302
                                $groupIid,
303
                                '',
304
                                $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 220 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...
305
                                $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 221 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...
306
                                $sessionId
307
                            );
308
                        } else {
309
                            // Storing the selected groups
310
                            if (!empty($sendTo['groups'])) {
311
                                foreach ($sendTo['groups'] as $group) {
312
                                    $groupIidItem = 0;
313
                                    if ($group) {
314
                                        $groupInfo = GroupManager::get_group_properties(
315
                                            $group
316
                                        );
317
                                        if ($groupInfo) {
318
                                            $groupIidItem = $groupInfo['iid'];
319
                                        }
320
                                    }
321
322
                                    api_item_property_update(
323
                                        $this->course,
324
                                        TOOL_CALENDAR_EVENT,
325
                                        $id,
326
                                        'AgendaAdded',
327
                                        $senderId,
328
                                        $groupIidItem,
329
                                        0,
330
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 220 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...
331
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 221 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...
332
                                        $sessionId
333
                                    );
334
335
                                    api_item_property_update(
336
                                        $this->course,
337
                                        TOOL_CALENDAR_EVENT,
338
                                        $id,
339
                                        'visible',
340
                                        $senderId,
341
                                        $groupIidItem,
342
                                        0,
343
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 220 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...
344
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 221 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...
345
                                        $sessionId
346
                                    );
347
                                }
348
                            }
349
350
                            // storing the selected users
351
                            if (!empty($sendTo['users'])) {
352
                                foreach ($sendTo['users'] as $userId) {
353
                                    api_item_property_update(
354
                                        $this->course,
355
                                        TOOL_CALENDAR_EVENT,
356
                                        $id,
357
                                        'AgendaAdded',
358
                                        $senderId,
359
                                        $groupIid,
360
                                        $userId,
361
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 220 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...
362
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 221 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...
363
                                        $sessionId
364
                                    );
365
366
                                    api_item_property_update(
367
                                        $this->course,
368
                                        TOOL_CALENDAR_EVENT,
369
                                        $id,
370
                                        'visible',
371
                                        $senderId,
372
                                        $groupIid,
373
                                        $userId,
374
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) on line 220 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...
375
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 221 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...
376
                                        $sessionId
377
                                    );
378
                                }
379
                            }
380
                        }
381
                    }
382
383
                    // Add announcement.
384
                    if ($addAsAnnouncement) {
385
                        $this->storeAgendaEventAsAnnouncement(
386
                            $id,
387
                            $usersToSend
388
                        );
389
                    }
390
391
                    // Add attachment.
392 View Code Duplication
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
393
                        $counter = 0;
394
                        foreach ($attachmentArray as $attachmentItem) {
395
                            $this->addAttachment(
396
                                $id,
397
                                $attachmentItem,
398
                                $attachmentCommentList[$counter],
399
                                $this->course
400
                            );
401
                            $counter++;
402
                        }
403
                    }
404
                }
405
                break;
406
            case 'admin':
407
                if (api_is_platform_admin()) {
408
                    $attributes = array(
409
                        'title' => $title,
410
                        'content' => $content,
411
                        'start_date' => $start,
412
                        'end_date' => $end,
413
                        'all_day' => $allDay,
414
                        'access_url_id' => api_get_current_access_url_id()
415
                    );
416
417
                    $id = Database::insert(
418
                        $this->tbl_global_agenda,
419
                        $attributes
420
                    );
421
                }
422
                break;
423
        }
424
425
        return $id;
426
    }
427
428
    /**
429
     * @param int $eventId
430
     * @param int $courseId
431
     *
432
     * @return array
433
     */
434
    public function getRepeatedInfoByEvent($eventId, $courseId)
435
    {
436
        $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
437
        $eventId = intval($eventId);
438
        $courseId = intval($courseId);
439
        $sql = "SELECT * FROM $repeatTable
440
                WHERE c_id = $courseId AND cal_id = $eventId";
441
        $res = Database::query($sql);
442
        $repeatInfo = array();
443
        if (Database::num_rows($res) > 0) {
444
            $repeatInfo = Database::fetch_array($res, 'ASSOC');
445
        }
446
447
        return $repeatInfo;
448
    }
449
450
    /**
451
     * @param int $eventId
452
     * @param string $type
453
     * @param string $end in local time
454
     * @param array $sentTo
455
     *
456
     * @return bool
457
     */
458
    public function addRepeatedItem($eventId, $type, $end, $sentTo = array())
459
    {
460
        $t_agenda = Database::get_course_table(TABLE_AGENDA);
461
        $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
462
463
        if (empty($this->course)) {
464
            return false;
465
        }
466
467
        $course_id = $this->course['real_id'];
468
        $eventId = intval($eventId);
469
470
        $sql = "SELECT title, content, start_date, end_date, all_day
471
                FROM $t_agenda
472
                WHERE c_id = $course_id AND id = $eventId";
473
        $res = Database::query($sql);
474
475
        if (Database::num_rows($res) !== 1) {
476
            return false;
477
        }
478
479
        $row = Database::fetch_array($res);
480
        $origStartDate = api_strtotime($row['start_date'], 'UTC');
481
        $origEndDate = api_strtotime($row['end_date'], 'UTC');
482
        $diff = $origEndDate - $origStartDate;
483
484
        $title = $row['title'];
485
        $content = $row['content'];
486
        $allDay = $row['all_day'];
487
488
        $now = time();
489
        $type = Database::escape_string($type);
490
        $end = api_strtotime($end);
491
492
        if (1 <= $end && $end <= 500) {
493
            // We assume that, with this type of value, the user actually gives a count of repetitions
494
            //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
495
            switch ($type) {
496
                case 'daily':
497
                    $end = $origStartDate + (86400 * $end);
498
                    break;
499
                case 'weekly':
500
                    $end = $this->addWeek($origStartDate, $end);
501
                    break;
502
                case 'monthlyByDate':
503
                    $end = $this->addMonth($origStartDate, $end);
504
                    break;
505
                case 'monthlyByDay':
506
                    //TODO
507
                    break;
508
                case 'monthlyByDayR':
509
                    //TODO
510
                    break;
511
                case 'yearly':
512
                    $end = $this->addYear($origStartDate, $end);
513
                    break;
514
            }
515
        }
516
517
        $typeList = array(
518
            'daily',
519
            'weekly',
520
            'monthlyByDate',
521
            'monthlyByDay',
522
            'monthlyByDayR',
523
            'yearly'
524
        );
525
526
        // The event has to repeat *in the future*. We don't allow repeated
527
        // events in the past
528
        if ($end > $now && in_array($type, $typeList)) {
529
            $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
530
                    VALUES ($course_id, '$eventId', '$type', '$end')";
531
            Database::query($sql);
532
533
            switch ($type) {
534
                // @todo improve loop.
535 View Code Duplication
                case 'daily':
536
                    for ($i = $origStartDate + 86400; $i <= $end; $i += 86400) {
537
                        $start = date('Y-m-d H:i:s', $i);
538
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
539
                        $this->addEvent(
540
                            $start,
541
                            $repeatEnd,
542
                            $allDay,
543
                            $title,
544
                            $content,
545
                            $sentTo,
546
                            false,
547
                            $eventId
548
                        );
549
                    }
550
                    break;
551 View Code Duplication
                case 'weekly':
552
                    for ($i = $origStartDate + 604800; $i <= $end; $i += 604800) {
553
                        $start = date('Y-m-d H:i:s', $i);
554
                        $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
555
                        $this->addEvent(
556
                            $start,
557
                            $repeatEnd,
558
                            $allDay,
559
                            $title,
560
                            $content,
561
                            $sentTo,
562
                            false,
563
                            $eventId
564
                        );
565
                    }
566
                    break;
567 View Code Duplication
                case 'monthlyByDate':
568
                    $next_start = $this->addMonth($origStartDate);
569
                    while ($next_start <= $end) {
570
                        $start = date('Y-m-d H:i:s', $next_start);
571
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
572
                        $this->addEvent(
573
                            $start,
574
                            $repeatEnd,
575
                            $allDay,
576
                            $title,
577
                            $content,
578
                            $sentTo,
579
                            false,
580
                            $eventId
581
                        );
582
                        $next_start = $this->addMonth($next_start);
583
                    }
584
                    break;
585
                case 'monthlyByDay':
586
                    //not yet implemented
587
                    break;
588
                case 'monthlyByDayR':
589
                    //not yet implemented
590
                    break;
591 View Code Duplication
                case 'yearly':
592
                    $next_start = $this->addYear($origStartDate);
593
                    while ($next_start <= $end) {
594
                        $start = date('Y-m-d H:i:s', $next_start);
595
                        $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
596
                        $this->addEvent(
597
                            $start,
598
                            $repeatEnd,
599
                            $allDay,
600
                            $title,
601
                            $content,
602
                            $sentTo,
603
                            false,
604
                            $eventId
605
                        );
606
                        $next_start = $this->addYear($next_start);
607
                    }
608
                    break;
609
            }
610
        }
611
612
        return true;
613
    }
614
615
    /**
616
     * @param int $item_id
617
     * @param array $sentTo
618
     * @return int
619
     */
620
    public function storeAgendaEventAsAnnouncement($item_id, $sentTo = array())
621
    {
622
        $table_agenda = Database::get_course_table(TABLE_AGENDA);
623
        $course_id = api_get_course_int_id();
624
625
        // Check params
626
        if (empty($item_id) || $item_id != strval(intval($item_id))) {
627
            return -1;
628
        }
629
630
        // Get the agenda item.
631
        $item_id = intval($item_id);
632
        $sql = "SELECT * FROM $table_agenda
633
                WHERE c_id = $course_id AND id = ".$item_id;
634
        $res = Database::query($sql);
635
636
        if (Database::num_rows($res) > 0) {
637
            $row = Database::fetch_array($res, 'ASSOC');
638
639
            // Sending announcement
640
            if (!empty($sentTo)) {
641
                $id = AnnouncementManager::add_announcement(
642
                    api_get_course_info(),
643
                    api_get_session_id(),
644
                    $row['title'],
645
                    $row['content'],
646
                    $sentTo,
647
                    null,
648
                    null,
649
                    $row['end_date']
650
                );
651
652
                AnnouncementManager::sendEmail(
653
                    api_get_course_info(),
654
                    api_get_session_id(),
655
                    $id
656
                );
657
658
                return $id;
659
            }
660
        }
661
662
        return -1;
663
    }
664
665
    /**
666
     * Edits an event
667
     *
668
     * @param int $id
669
     * @param string $start datetime format: 2012-06-14 09:00:00
670
     * @param string $end datetime format: 2012-06-14 09:00:00
671
     * @param int $allDay is all day 'true' or 'false'
672
     * @param string $title
673
     * @param string $content
674
     * @param array $usersToSend
675
     * @param array $attachmentArray
676
     * @param array $attachmentCommentList
677
     * @param string $comment
678
     * @param string $color
679
     * @param bool $addAnnouncement
680
     * @param bool $updateContent
681
     *
682
     * @return null|false
683
     */
684
    public function editEvent(
685
        $id,
686
        $start,
687
        $end,
688
        $allDay,
689
        $title,
690
        $content,
691
        $usersToSend = array(),
692
        $attachmentArray = array(),
693
        $attachmentCommentList = array(),
694
        $comment = null,
695
        $color = '',
696
        $addAnnouncement = false,
697
        $updateContent = true
698
    ) {
699
        $start = api_get_utc_datetime($start);
700
        $end = api_get_utc_datetime($end);
701
        $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
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
740
                $groupIid = 0;
741
                if ($groupId) {
742
                    $groupInfo = GroupManager::get_group_properties($groupId);
743
                    if ($groupInfo) {
744
                        $groupIid = $groupInfo['iid'];
745
                    }
746
                }
747
748
                $course_id = $this->course['real_id'];
749
750
                if (empty($course_id)) {
751
                    return false;
752
                }
753
754
                if ($this->getIsAllowedToEdit()) {
755
                    $attributes = array(
756
                        'title' => $title,
757
                        'start_date' => $start,
758
                        'end_date' => $end,
759
                        'all_day' => $allDay,
760
                        'comment' => $comment
761
                    );
762
763
                    if ($updateContent) {
764
                        $attributes['content'] = $content;
765
                    }
766
767
                    if (!empty($color)) {
768
                        $attributes['color'] = $color;
769
                    }
770
771
                    Database::update(
772
                        $this->tbl_course_agenda,
773
                        $attributes,
774
                        array(
775
                            'id = ? AND c_id = ? AND session_id = ? ' => array(
776
                                $id,
777
                                $course_id,
778
                                $this->sessionId
779
                            )
780
                        )
781
                    );
782
783
                    if (!empty($usersToSend)) {
784
                        $sendTo = $this->parseSendToArray($usersToSend);
785
786
                        $usersToDelete = array_diff(
787
                            $eventInfo['send_to']['users'],
788
                            $sendTo['users']
789
                        );
790
                        $usersToAdd = array_diff(
791
                            $sendTo['users'],
792
                            $eventInfo['send_to']['users']
793
                        );
794
795
                        $groupsToDelete = array_diff(
796
                            $eventInfo['send_to']['groups'],
797
                            $sendTo['groups']
798
                        );
799
                        $groupToAdd = array_diff(
800
                            $sendTo['groups'],
801
                            $eventInfo['send_to']['groups']
802
                        );
803
804
                        if ($sendTo['everyone']) {
805
                            // Delete all from group
806
                            if (isset($eventInfo['send_to']['groups']) &&
807
                                !empty($eventInfo['send_to']['groups'])
808
                            ) {
809
                                foreach ($eventInfo['send_to']['groups'] as $group) {
810
                                    $groupIidItem = 0;
811
                                    if ($group) {
812
                                        $groupInfo = GroupManager::get_group_properties(
813
                                            $group
814
                                        );
815
                                        if ($groupInfo) {
816
                                            $groupIidItem = $groupInfo['iid'];
817
                                        }
818
                                    }
819
820
                                    api_item_property_delete(
821
                                        $this->course,
822
                                        TOOL_CALENDAR_EVENT,
823
                                        $id,
824
                                        0,
825
                                        $groupIidItem,
826
                                        $this->sessionId
827
                                    );
828
                                }
829
                            }
830
831
                            // Storing the selected users.
832
                            if (isset($eventInfo['send_to']['users']) &&
833
                                !empty($eventInfo['send_to']['users'])
834
                            ) {
835
                                foreach ($eventInfo['send_to']['users'] as $userId) {
836
                                    api_item_property_delete(
837
                                        $this->course,
838
                                        TOOL_CALENDAR_EVENT,
839
                                        $id,
840
                                        $userId,
841
                                        $groupIid,
842
                                        $this->sessionId
843
                                    );
844
                                }
845
                            }
846
847
                            // Add to everyone only.
848
                            api_item_property_update(
849
                                $this->course,
850
                                TOOL_CALENDAR_EVENT,
851
                                $id,
852
                                'visible',
853
                                api_get_user_id(),
854
                                $groupIid,
855
                                null,
856
                                $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) 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
                                $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 700 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...
858
                                $this->sessionId
859
                            );
860
                        } else {
861
                            // Delete "everyone".
862
                            api_item_property_delete(
863
                                $this->course,
864
                                TOOL_CALENDAR_EVENT,
865
                                $id,
866
                                0,
867
                                0,
868
                                $this->sessionId
869
                            );
870
871
                            // Add groups
872 View Code Duplication
                            if (!empty($groupToAdd)) {
873
                                foreach ($groupToAdd as $group) {
874
                                    $groupIidItem = 0;
875
                                    if ($group) {
876
                                        $groupInfo = GroupManager::get_group_properties(
877
                                            $group
878
                                        );
879
                                        if ($groupInfo) {
880
                                            $groupIidItem = $groupInfo['iid'];
881
                                        }
882
                                    }
883
884
                                    api_item_property_update(
885
                                        $this->course,
886
                                        TOOL_CALENDAR_EVENT,
887
                                        $id,
888
                                        'visible',
889
                                        api_get_user_id(),
890
                                        $groupIidItem,
891
                                        0,
892
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) 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
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 700 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...
894
                                        $this->sessionId
895
                                    );
896
                                }
897
                            }
898
899
                            // Delete groups.
900 View Code Duplication
                            if (!empty($groupsToDelete)) {
901
                                foreach ($groupsToDelete as $group) {
902
                                    $groupIidItem = 0;
903
                                    if ($group) {
904
                                        $groupInfo = GroupManager::get_group_properties(
905
                                            $group
906
                                        );
907
                                        if ($groupInfo) {
908
                                            $groupIidItem = $groupInfo['iid'];
909
                                        }
910
                                    }
911
912
                                    api_item_property_delete(
913
                                        $this->course,
914
                                        TOOL_CALENDAR_EVENT,
915
                                        $id,
916
                                        0,
917
                                        $groupIidItem,
918
                                        $this->sessionId
919
                                    );
920
                                }
921
                            }
922
923
                            // Add users.
924
                            if (!empty($usersToAdd)) {
925
                                foreach ($usersToAdd as $userId) {
926
                                    api_item_property_update(
927
                                        $this->course,
928
                                        TOOL_CALENDAR_EVENT,
929
                                        $id,
930
                                        'visible',
931
                                        api_get_user_id(),
932
                                        $groupIid,
933
                                        $userId,
934
                                        $start,
0 ignored issues
show
Bug introduced by
It seems like $start defined by api_get_utc_datetime($start) 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
                                        $end,
0 ignored issues
show
Bug introduced by
It seems like $end defined by api_get_utc_datetime($end) on line 700 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...
936
                                        $this->sessionId
937
                                    );
938
                                }
939
                            }
940
941
                            // Delete users.
942
                            if (!empty($usersToDelete)) {
943
                                foreach ($usersToDelete as $userId) {
944
                                    api_item_property_delete(
945
                                        $this->course,
946
                                        TOOL_CALENDAR_EVENT,
947
                                        $id,
948
                                        $userId,
949
                                        $groupIid,
950
                                        $this->sessionId
951
                                    );
952
                                }
953
                            }
954
                        }
955
                    }
956
957
                    // Add announcement.
958
                    if (isset($addAnnouncement) && !empty($addAnnouncement)) {
959
                        $this->storeAgendaEventAsAnnouncement(
960
                            $id,
961
                            $usersToSend
962
                        );
963
                    }
964
965
                    // Add attachment.
966 View Code Duplication
                    if (isset($attachmentArray) && !empty($attachmentArray)) {
967
                        $counter = 0;
968
                        foreach ($attachmentArray as $attachmentItem) {
969
                            $this->updateAttachment(
970
                                $attachmentItem['id'],
971
                                $id,
972
                                $attachmentItem,
973
                                $attachmentCommentList[$counter],
974
                                $this->course
975
                            );
976
                            $counter++;
977
                        }
978
                    }
979
980
                    return true;
981
                } else {
982
                    return false;
983
                }
984
                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...
985
            case 'admin':
986
            case 'platform':
987
                if (api_is_platform_admin()) {
988
                    $attributes = array(
989
                        'title' => $title,
990
                        'start_date' => $start,
991
                        'end_date' => $end,
992
                        'all_day' => $allDay
993
                    );
994
995
                    if ($updateContent) {
996
                        $attributes['content'] = $content;
997
                    }
998
                    Database::update(
999
                        $this->tbl_global_agenda,
1000
                        $attributes,
1001
                        array('id = ?' => $id)
1002
                    );
1003
                }
1004
                break;
1005
        }
1006
    }
1007
1008
    /**
1009
     * @param int $id
1010
     * @param bool $deleteAllItemsFromSerie
1011
     */
1012
    public function deleteEvent($id, $deleteAllItemsFromSerie = false)
1013
    {
1014
        switch ($this->type) {
1015
            case 'personal':
1016
                $eventInfo = $this->get_event($id);
1017
                if ($eventInfo['user'] == api_get_user_id()) {
1018
                    Database::delete(
1019
                        $this->tbl_personal_agenda,
1020
                        array('id = ?' => $id)
1021
                    );
1022
                }
1023
                break;
1024
            case 'course':
1025
                $course_id = api_get_course_int_id();
1026
1027
                if (!empty($course_id) && api_is_allowed_to_edit(null, true)) {
1028
                    // Delete
1029
                    $eventInfo = $this->get_event($id);
1030
                    if ($deleteAllItemsFromSerie) {
1031
                        /* This is one of the children.
1032
                           Getting siblings and delete 'Em all + the father! */
1033
                        if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
1034
                            // Removing items.
1035
                            $events = $this->getAllRepeatEvents(
1036
                                $eventInfo['parent_event_id']
1037
                            );
1038
                            if (!empty($events)) {
1039
                                foreach ($events as $event) {
1040
                                    $this->deleteEvent($event['id']);
1041
                                }
1042
                            }
1043
                            // Removing parent.
1044
                            $this->deleteEvent($eventInfo['parent_event_id']);
1045
                        } else {
1046
                            // This is the father looking for the children.
1047
                            $events = $this->getAllRepeatEvents($id);
1048
                            if (!empty($events)) {
1049
                                foreach ($events as $event) {
1050
                                    $this->deleteEvent($event['id']);
1051
                                }
1052
                            }
1053
                        }
1054
                    }
1055
1056
                    // Removing from events.
1057
                    Database::delete(
1058
                        $this->tbl_course_agenda,
1059
                        array('id = ? AND c_id = ?' => array($id, $course_id))
1060
                    );
1061
1062
                    api_item_property_update(
1063
                        $this->course,
1064
                        TOOL_CALENDAR_EVENT,
1065
                        $id,
1066
                        'delete',
1067
                        api_get_user_id()
1068
                    );
1069
1070
                    // Removing from series.
1071
                    Database::delete(
1072
                        $this->table_repeat,
1073
                        array(
1074
                            'cal_id = ? AND c_id = ?' => array(
1075
                                $id,
1076
                                $course_id
1077
                            )
1078
                        )
1079
                    );
1080
1081
                    if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
1082
                        foreach ($eventInfo['attachment'] as $attachment) {
1083
                            self::deleteAttachmentFile(
1084
                                $attachment['id'],
1085
                                $this->course
1086
                            );
1087
                        }
1088
                    }
1089
                }
1090
                break;
1091
            case 'admin':
1092
                if (api_is_platform_admin()) {
1093
                    Database::delete(
1094
                        $this->tbl_global_agenda,
1095
                        array('id = ?' => $id)
1096
                    );
1097
                }
1098
                break;
1099
        }
1100
    }
1101
1102
    /**
1103
     * Get agenda events
1104
     * @param int $start
1105
     * @param int $end
1106
     * @param int $course_id
1107
     * @param int $groupId
1108
     * @param int $user_id
1109
     * @param string $format
1110
     *
1111
     * @return array|string
1112
     */
1113
    public function getEvents(
1114
        $start,
1115
        $end,
1116
        $course_id = null,
1117
        $groupId = null,
1118
        $user_id = 0,
1119
        $format = 'json',
1120
        $startLimit = 0,
1121
        $endLimit = 0
1122
    ) {
1123
        switch ($this->type) {
1124
            case 'admin':
1125
                $this->getPlatformEvents($start, $end);
1126
                break;
1127
            case 'course':
1128
                $courseInfo = api_get_course_info_by_id($course_id);
1129
1130
                // Session coach can see all events inside a session.
1131
                if (api_is_coach()) {
1132
                    // Own course
1133
                    $this->getCourseEvents(
1134
                        $start,
1135
                        $end,
1136
                        $courseInfo,
1137
                        $groupId,
1138
                        $this->sessionId,
1139
                        $user_id
1140
                    );
1141
1142
                    // Others
1143
                    $this->getSessionEvents(
1144
                        $start,
1145
                        $end,
1146
                        $this->sessionId,
1147
                        $user_id,
1148
                        $this->eventOtherSessionColor
1149
                    );
1150
                } else {
1151
                    $this->getCourseEvents(
1152
                        $start,
1153
                        $end,
1154
                        $courseInfo,
1155
                        $groupId,
1156
                        $this->sessionId,
1157
                        $user_id
1158
                    );
1159
                }
1160
                break;
1161
            case 'personal':
1162
            default:
1163
                $sessionFilterActive = false;
1164
                if (!empty($this->sessionId)) {
1165
                    $sessionFilterActive = true;
1166
                }
1167
1168
                if ($sessionFilterActive == false) {
1169
                    // Getting personal events
1170
                    $this->getPersonalEvents($start, $end);
1171
1172
                    // Getting platform/admin events
1173
                    $this->getPlatformEvents($start, $end);
1174
                }
1175
1176
                $ignoreVisibility = api_get_configuration_value('personal_agenda_show_all_session_events');
1177
1178
                // Getting course events
1179
                $my_course_list = array();
1180
                if (!api_is_anonymous()) {
1181
                    $session_list = SessionManager::get_sessions_by_user(
1182
                        api_get_user_id(),
1183
                        $ignoreVisibility
1184
1185
                    );
1186
                    $my_course_list = CourseManager::get_courses_list_by_user_id(
1187
                        api_get_user_id(),
1188
                        false
1189
                    );
1190
                }
1191
1192
                if (api_is_drh()) {
1193
                    if (api_drh_can_access_all_session_content()) {
1194
                        $session_list = array();
1195
                        $sessionList = SessionManager::get_sessions_followed_by_drh(
1196
                            api_get_user_id(),
1197
                            null,
1198
                            null,
1199
                            null,
1200
                            true,
1201
                            false
1202
                        );
1203
1204
                        if (!empty($sessionList)) {
1205
                            foreach ($sessionList as $sessionItem) {
1206
                                $sessionId = $sessionItem['id'];
1207
                                $courses = SessionManager::get_course_list_by_session_id(
1208
                                    $sessionId
1209
                                );
1210
                                $sessionInfo = array(
1211
                                    'session_id' => $sessionId,
1212
                                    'courses' => $courses
1213
                                );
1214
                                $session_list[] = $sessionInfo;
1215
                            }
1216
                        }
1217
                    }
1218
                }
1219
1220
                if (!empty($session_list)) {
1221
                    foreach ($session_list as $session_item) {
1222
                        if ($sessionFilterActive) {
1223
                            if ($this->sessionId != $session_item['session_id']) {
1224
                                continue;
1225
                            }
1226
                        }
1227
1228
                        $my_courses = $session_item['courses'];
1229
                        $my_session_id = $session_item['session_id'];
1230
1231
                        if (!empty($my_courses)) {
1232
                            foreach ($my_courses as $course_item) {
1233
                                $courseInfo = api_get_course_info_by_id(
1234
                                    $course_item['real_id']
1235
                                );
1236
                                $this->getCourseEvents(
1237
                                    $start,
1238
                                    $end,
1239
                                    $courseInfo,
1240
                                    0,
1241
                                    $my_session_id
1242
                                );
1243
                            }
1244
                        }
1245
                    }
1246
                }
1247
1248
                if (!empty($my_course_list) && $sessionFilterActive == false) {
1249
                    foreach ($my_course_list as $courseInfoItem) {
1250
                        $courseInfo = api_get_course_info_by_id(
1251
                            $courseInfoItem['real_id']
1252
                        );
1253
                        if (isset($course_id) && !empty($course_id)) {
1254
                            if ($courseInfo['real_id'] == $course_id) {
1255
                                $this->getCourseEvents(
1256
                                    $start,
1257
                                    $end,
1258
                                    $courseInfo
1259
                                );
1260
                            }
1261
                        } else {
1262
                            $this->getCourseEvents(
1263
                                $start,
1264
                                $end,
1265
                                $courseInfo
1266
                            );
1267
                        }
1268
                    }
1269
                }
1270
1271
                break;
1272
        }
1273
1274
        switch ($format) {
1275
            case 'json':
1276
                if (empty($this->events)) {
1277
                    return '';
1278
                }
1279
1280
                return json_encode($this->events);
1281
                break;
1282
            case 'array':
1283
                if (empty($this->events)) {
1284
                    return [];
1285
                }
1286
1287
                return $this->events;
1288
                break;
1289
        }
1290
    }
1291
1292
    /**
1293
     * @param int $id
1294
     * @param int $minute_delta
1295
     * @return int
1296
     */
1297
    public function resizeEvent($id, $minute_delta)
1298
    {
1299
        $delta = intval($minute_delta);
1300
        $event = $this->get_event($id);
1301
        if (!empty($event)) {
1302
            switch ($this->type) {
1303 View Code Duplication
                case 'personal':
1304
                    $sql = "UPDATE $this->tbl_personal_agenda SET
1305
                            enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
1306
							WHERE id=".intval($id);
1307
                    Database::query($sql);
1308
                    break;
1309 View Code Duplication
                case 'course':
1310
                    $sql = "UPDATE $this->tbl_course_agenda SET
1311
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1312
							WHERE c_id = ".$this->course['real_id']." AND id=".intval(
1313
                            $id
1314
                        );
1315
                    Database::query($sql);
1316
                    break;
1317 View Code Duplication
                case 'admin':
1318
                    $sql = "UPDATE $this->tbl_global_agenda SET
1319
                            end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
1320
							WHERE id=".intval($id);
1321
                    Database::query($sql);
1322
                    break;
1323
            }
1324
        }
1325
1326
        return 1;
1327
    }
1328
1329
    /**
1330
     * @param int $id
1331
     * @param int $minute_delta minutes
1332
     * @param int $allDay
1333
     * @return int
1334
     */
1335
    public function move_event($id, $minute_delta, $allDay)
1336
    {
1337
        $event = $this->get_event($id);
1338
1339
        if (empty($event)) {
1340
            return false;
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 View Code Duplication
                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=".intval($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 c_id = ".$this->course['real_id']." AND id=".intval(
1361
                            $id
1362
                        );
1363
                    Database::query($sql);
1364
                    break;
1365 View Code Duplication
                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=".intval($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 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
    /**
1624
     * @param int $start
1625
     * @param int $end
1626
     * @param array $courseInfo
1627
     * @param int $groupId
1628
     * @param int $session_id
1629
     * @param int $user_id
1630
     * @param string $color
1631
     *
1632
     * @return array
1633
     */
1634
    public function getCourseEvents(
1635
        $start,
1636
        $end,
1637
        $courseInfo,
1638
        $groupId = 0,
1639
        $session_id = 0,
1640
        $user_id = 0,
1641
        $color = ''
1642
    ) {
1643
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(
1644
            intval($start)
1645
        ) : null;
1646
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(
1647
            intval($end)
1648
        ) : null;
1649
1650
        if (empty($courseInfo)) {
1651
            return array();
1652
        }
1653
        $course_id = $courseInfo['real_id'];
1654
1655
        if (empty($course_id)) {
1656
            return array();
1657
        }
1658
1659
        $session_id = intval($session_id);
1660
        $user_id = intval($user_id);
1661
        $groupList = GroupManager::get_group_list(null, $courseInfo['code']);
1662
1663
        $group_name_list = array();
1664
        if (!empty($groupList)) {
1665
            foreach ($groupList as $group) {
1666
                $group_name_list[$group['id']] = $group['name'];
1667
            }
1668
        }
1669
1670
        if (!empty($groupId)) {
1671 View Code Duplication
            if (!api_is_allowed_to_edit()) {
1672
                $user_id = api_get_user_id();
1673
                $group_memberships = GroupManager::get_group_ids(
1674
                    $course_id,
1675
                    $user_id
1676
                );
1677
            } else {
1678
                $group_memberships = GroupManager::get_group_ids(
1679
                    $course_id,
1680
                    $user_id
1681
                );
1682
            }
1683 View Code Duplication
        } else {
1684
            // if no group was defined but I am a student reviewing his agenda,
1685
            // group events should show, so we should fetch those groups to which
1686
            // I belong
1687
            if (!api_is_allowed_to_edit()) {
1688
                $user_id = api_get_user_id();
1689
                $group_memberships = GroupManager::get_group_ids(
1690
                    $course_id,
1691
                    $user_id
1692
                );
1693
            } else {
1694
                // If no group was defined and I am a teacher/admin reviewing
1695
                // someone else's agenda, we should fetch this person's groups
1696
                $group_memberships = GroupManager::get_group_ids(
1697
                    $course_id,
1698
                    $user_id
1699
                );
1700
            }
1701
        }
1702
1703
        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
1704
        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1705
1706
        if (!empty($groupId)) {
1707
            $group_memberships = array($groupId);
1708
        }
1709
1710
        if (is_array($group_memberships) && count($group_memberships) > 0) {
1711
            if (api_is_allowed_to_edit()) {
1712
                if (!empty($groupId)) {
1713
                    $where_condition = "( ip.to_group_id IN (".implode(
1714
                            ", ",
1715
                            $group_memberships
1716
                        ).") ) ";
1717 View Code Duplication
                } else {
1718
                    if (!empty($user_id)) {
1719
                        $where_condition = "( ip.to_user_id = $user_id OR ip.to_user_id IS NULL OR (ip.to_group_id IN (0, ".implode(
1720
                                ", ",
1721
                                $group_memberships
1722
                            ).")) ) ";
1723
                    } else {
1724
                        $where_condition = "( ip.to_group_id IN (0, ".implode(
1725
                                ", ",
1726
                                $group_memberships
1727
                            ).") ) ";
1728
                    }
1729
                }
1730
            } else {
1731
                $where_condition = "( ip.to_user_id = $user_id OR ip.to_user_id IS NULL OR (ip.to_group_id IN (0, ".implode(
1732
                        ", ",
1733
                        $group_memberships
1734
                    ).")) ) ";
1735
            }
1736
1737
            if (empty($session_id)) {
1738
                $sessionCondition = "
1739
                (
1740
                    agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
1741
                ) ";
1742
            } else {
1743
                $sessionCondition = "
1744
                (
1745
                    agenda.session_id = $session_id AND
1746
                    ip.session_id = $session_id
1747
                ) ";
1748
            }
1749
1750
            $sql = "SELECT DISTINCT
1751
                        agenda.*,
1752
                        ip.visibility,
1753
                        ip.to_group_id,
1754
                        ip.insert_user_id,
1755
                        ip.ref,
1756
                        to_user_id
1757
                    FROM $tlb_course_agenda agenda
1758
                    INNER JOIN $tbl_property ip
1759
                    ON (
1760
                        agenda.id = ip.ref AND 
1761
                        agenda.c_id = ip.c_id AND 
1762
                        ip.tool = '".TOOL_CALENDAR_EVENT."'
1763
                    )
1764
                    WHERE
1765
                        $where_condition AND
1766
                        ip.visibility = '1' AND
1767
                        agenda.c_id = $course_id AND
1768
                        ip.c_id = agenda.c_id AND
1769
                        $sessionCondition
1770
                    ";
1771
        } else {
1772
            $visibilityCondition = " ip.visibility='1' AND ";
1773
1774
            if (api_is_allowed_to_edit()) {
1775
                if ($user_id == 0) {
1776
                    $where_condition = '';
1777
                } else {
1778
                    $where_condition = " (ip.to_user_id = ".$user_id." OR ip.to_user_id IS NULL) AND ip.to_group_id IS NULL AND ";
1779
                }
1780
                $visibilityCondition = " (ip.visibility IN ('1', '0')) AND ";
1781
            } else {
1782
                $where_condition = " ( (ip.to_user_id = ".api_get_user_id(
1783
                    )." OR ip.to_user_id IS NULL) AND ip.to_group_id IS NULL) AND ";
1784
            }
1785
1786
            if (empty($session_id)) {
1787
                $sessionCondition = "
1788
                (
1789
                    agenda.session_id = 0 AND
1790
                    (ip.session_id IS NULL OR ip.session_id = 0)
1791
                ) ";
1792
            } else {
1793
                $sessionCondition = "
1794
                (
1795
                    agenda.session_id = $session_id AND
1796
                    ip.session_id = $session_id
1797
                ) ";
1798
            }
1799
1800
            $sql = "SELECT DISTINCT
1801
                        agenda.*,
1802
                        ip.visibility,
1803
                        ip.to_group_id,
1804
                        ip.insert_user_id,
1805
                        ip.ref,
1806
                        to_user_id
1807
                    FROM $tlb_course_agenda agenda
1808
                    INNER JOIN $tbl_property ip
1809
                    ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id AND ip.tool='".TOOL_CALENDAR_EVENT."' )
1810
                    WHERE
1811
                        $where_condition
1812
                        $visibilityCondition
1813
                        agenda.c_id = $course_id AND
1814
                        $sessionCondition
1815
                    ";
1816
        }
1817
1818
        $dateCondition = null;
1819
1820 View Code Duplication
        if (!empty($start) && !empty($end)) {
1821
            $dateCondition .= "AND (
1822
                 agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
1823
                 agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
1824
                 (
1825
                     agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
1826
                     YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
1827
                     MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
1828
                 )
1829
            )";
1830
        }
1831
1832
        $sql .= $dateCondition;
1833
        $result = Database::query($sql);
1834
1835
        $coachCanEdit = false;
1836
        if (!empty($session_id)) {
1837
            $coachCanEdit = api_is_coach(
1838
                    $session_id,
1839
                    $course_id
1840
                ) || api_is_platform_admin();
1841
        }
1842
1843
        if (Database::num_rows($result)) {
1844
            $eventsAdded = array_column($this->events, 'unique_id');
1845
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1846
                $event = array();
1847
                $event['id'] = 'course_'.$row['id'];
1848
                $event['unique_id'] = $row['iid'];
1849
                // To avoid doubles
1850
                if (in_array($event['unique_id'], $eventsAdded)) {
1851
                    continue;
1852
                }
1853
1854
                $eventsAdded[] = $event['unique_id'];
1855
1856
                $eventId = $row['ref'];
1857
                $items = $this->getUsersAndGroupSubscribedToEvent(
1858
                    $eventId,
1859
                    $course_id,
1860
                    $this->sessionId
1861
                );
1862
                $group_to_array = $items['groups'];
1863
                $user_to_array = $items['users'];
1864
                $attachmentList = $this->getAttachmentList(
1865
                    $row['id'],
1866
                    $courseInfo
1867
                );
1868
                $event['attachment'] = '';
1869
1870
                if (!empty($attachmentList)) {
1871
                    foreach ($attachmentList as $attachment) {
1872
                        $has_attachment = Display::return_icon(
1873
                            'attachment.gif',
1874
                            get_lang('Attachment')
1875
                        );
1876
                        $user_filename = $attachment['filename'];
1877
                        $url = api_get_path(
1878
                                WEB_CODE_PATH
1879
                            ).'calendar/download.php?file='.$attachment['path'].'&course_id='.$course_id.'&'.api_get_cidreq(
1880
                            );
1881
                        $event['attachment'] .= $has_attachment.Display::url(
1882
                                $user_filename,
1883
                                $url
1884
                            ).'<br />';
1885
                    }
1886
                }
1887
1888
                $event['title'] = $row['title'];
1889
                $event['className'] = 'course';
1890
                $event['allDay'] = 'false';
1891
                $event['course_id'] = $course_id;
1892
                $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
1893
1894
                $sessionInfo = [];
1895 View Code Duplication
                if (isset($row['session_id']) && !empty($row['session_id'])) {
1896
                    $sessionInfo = api_get_session_info($session_id);
1897
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
1898
                }
1899
1900
                $event['session_name'] = isset($sessionInfo['name']) ? $sessionInfo['name'] : '';
1901
                $event['course_name'] = isset($courseInfo['title']) ? $courseInfo['title'] : '';
1902
1903 View Code Duplication
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1904
                    $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
1905
                }
1906
1907
                if (!empty($color)) {
1908
                    $event['borderColor'] = $event['backgroundColor'] = $color;
1909
                }
1910
1911 View Code Duplication
                if (isset($row['color']) && !empty($row['color'])) {
1912
                    $event['borderColor'] = $event['backgroundColor'] = $row['color'];
1913
                }
1914
1915
                $event['editable'] = false;
1916
                if ($this->getIsAllowedToEdit() && $this->type == 'course') {
1917
                    $event['editable'] = true;
1918
                    if (!empty($session_id)) {
1919
                        if ($coachCanEdit == false) {
1920
                            $event['editable'] = false;
1921
                        }
1922
                    }
1923
                }
1924
1925 View Code Duplication
                if (!empty($row['start_date'])) {
1926
                    $event['start'] = $this->formatEventDate(
1927
                        $row['start_date']
1928
                    );
1929
                    $event['start_date_localtime'] = api_get_local_time(
1930
                        $row['start_date']
1931
                    );
1932
                }
1933 View Code Duplication
                if (!empty($row['end_date'])) {
1934
                    $event['end'] = $this->formatEventDate($row['end_date']);
1935
                    $event['end_date_localtime'] = api_get_local_time(
1936
                        $row['end_date']
1937
                    );
1938
                }
1939
1940
                $event['sent_to'] = '';
1941
                $event['type'] = 'course';
1942
                if ($row['session_id'] != 0) {
1943
                    $event['type'] = 'session';
1944
                }
1945
1946
                // Event Sent to a group?
1947
                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
1948
                    $sent_to = array();
1949
                    if (!empty($group_to_array)) {
1950
                        foreach ($group_to_array as $group_item) {
1951
                            $sent_to[] = $group_name_list[$group_item];
1952
                        }
1953
                    }
1954
                    $sent_to = implode('@@', $sent_to);
1955
                    $sent_to = str_replace(
1956
                        '@@',
1957
                        '</div><div class="label_tag notice">',
1958
                        $sent_to
1959
                    );
1960
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1961
                    $event['type'] = 'group';
1962
                }
1963
1964
                // Event sent to a user?
1965
                if (isset($row['to_user_id'])) {
1966
                    $sent_to = array();
1967
                    if (!empty($user_to_array)) {
1968
                        foreach ($user_to_array as $item) {
1969
                            $user_info = api_get_user_info($item);
1970
                            // Add username as tooltip for $event['sent_to'] - ref #4226
1971
                            $username = api_htmlentities(
1972
                                sprintf(
1973
                                    get_lang('LoginX'),
1974
                                    $user_info['username']
1975
                                ),
1976
                                ENT_QUOTES
1977
                            );
1978
                            $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
1979
                        }
1980
                    }
1981
                    $sent_to = implode('@@', $sent_to);
1982
                    $sent_to = str_replace(
1983
                        '@@',
1984
                        '</div><div class="label_tag notice">',
1985
                        $sent_to
1986
                    );
1987
                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
1988
                }
1989
1990
                //Event sent to everyone!
1991
                if (empty($event['sent_to'])) {
1992
                    $event['sent_to'] = '<div class="label_tag notice">'.get_lang(
1993
                            'Everyone'
1994
                        ).'</div>';
1995
                }
1996
1997
                $event['description'] = $row['content'];
1998
                $event['visibility'] = $row['visibility'];
1999
                $event['real_id'] = $row['id'];
2000
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
2001
                $event['parent_event_id'] = $row['parent_event_id'];
2002
                $event['has_children'] = $this->hasChildren(
2003
                    $row['id'],
2004
                    $course_id
2005
                ) ? 1 : 0;
2006
                $event['comment'] = $row['comment'];
2007
2008
                $this->events[] = $event;
2009
            }
2010
        }
2011
2012
        return $this->events;
2013
    }
2014
2015
    /**
2016
     * @param int $start tms
2017
     * @param int $end tms
2018
     * @return array
2019
     */
2020
    public function getPlatformEvents($start, $end)
2021
    {
2022
        $start = isset($start) && !empty($start) ? api_get_utc_datetime(
2023
            intval($start)
2024
        ) : null;
2025
        $end = isset($end) && !empty($end) ? api_get_utc_datetime(
2026
            intval($end)
2027
        ) : null;
2028
        $dateCondition = '';
2029
2030 View Code Duplication
        if (!empty($start) && !empty($end)) {
2031
            $dateCondition .= "AND (
2032
                 start_date BETWEEN '".$start."' AND '".$end."' OR
2033
                 end_date BETWEEN '".$start."' AND '".$end."' OR
2034
                 (
2035
                     start_date IS NOT NULL AND end_date IS NOT NULL AND
2036
                     YEAR(start_date) = YEAR(end_date) AND
2037
                     MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
2038
                 )
2039
            )";
2040
        }
2041
2042
        $access_url_id = api_get_current_access_url_id();
2043
2044
        $sql = "SELECT *
2045
                FROM ".$this->tbl_global_agenda."
2046
                WHERE access_url_id = $access_url_id
2047
                $dateCondition";
2048
        $result = Database::query($sql);
2049
        $my_events = array();
2050
        if (Database::num_rows($result)) {
2051
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2052
                $event = array();
2053
                $event['id'] = 'platform_'.$row['id'];
2054
                $event['title'] = $row['title'];
2055
                $event['className'] = 'platform';
2056
                $event['allDay'] = 'false';
2057
                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
2058
                $event['editable'] = false;
2059
                $event['type'] = 'admin';
2060
2061
                if (api_is_platform_admin() && $this->type == 'admin') {
2062
                    $event['editable'] = true;
2063
                }
2064
2065 View Code Duplication
                if (!empty($row['start_date'])) {
2066
                    $event['start'] = $this->formatEventDate(
2067
                        $row['start_date']
2068
                    );
2069
                    $event['start_date_localtime'] = api_get_local_time(
2070
                        $row['start_date']
2071
                    );
2072
                }
2073 View Code Duplication
                if (!empty($row['end_date'])) {
2074
                    $event['end'] = $this->formatEventDate($row['end_date']);
2075
                    $event['end_date_localtime'] = api_get_local_time(
2076
                        $row['end_date']
2077
                    );
2078
                }
2079
2080
                $event['description'] = $row['content'];
2081
                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
2082
2083
                $event['parent_event_id'] = 0;
2084
                $event['has_children'] = 0;
2085
2086
                $my_events[] = $event;
2087
                $this->events[] = $event;
2088
            }
2089
        }
2090
2091
        return $my_events;
2092
    }
2093
2094
    /**
2095
     * Format needed for the Fullcalendar js lib
2096
     *
2097
     * @param string $utcTime
2098
     * @return bool|string
2099
     */
2100
    private function formatEventDate($utcTime)
2101
    {
2102
        $utcTimeZone = new DateTimeZone('UTC');
2103
        $platformTimeZone = new DateTimeZone(api_get_timezone());
2104
2105
        $eventDate = new DateTime($utcTime, $utcTimeZone);
2106
        $eventDate->setTimezone($platformTimeZone);
2107
2108
        return $eventDate->format(DateTime::ISO8601);
2109
    }
2110
2111
    /**
2112
     * @param FormValidator $form
2113
     * @param array $groupList
2114
     * @param array $userList
2115
     * @param array $sendTo array('users' => [1, 2], 'groups' => [3, 4])
2116
     * @param array $attributes
2117
     * @param bool $addOnlyItemsInSendTo
2118
     * @param bool $required
2119
     */
2120
    public function setSendToSelect(
2121
        $form,
2122
        $groupList = [],
2123
        $userList = [],
2124
        $sendTo = [],
2125
        $attributes = [],
2126
        $addOnlyItemsInSendTo = false,
2127
        $required = false
2128
    ) {
2129
        $params = array(
2130
            'id' => 'users_to_send_id',
2131
            'data-placeholder' => get_lang('Select'),
2132
            'multiple' => 'multiple',
2133
            'class' => 'multiple-select'
2134
        );
2135
2136
        if (!empty($attributes)) {
2137
            $params = array_merge($params, $attributes);
2138
            if (empty($params['multiple'])) {
2139
                unset($params['multiple']);
2140
            }
2141
        }
2142
2143
        $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : array();
2144
        $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : array();
2145
2146
        /** @var HTML_QuickForm_select $select */
2147
        $select = $form->addSelect(
2148
            'users_to_send',
2149
            get_lang('To'),
2150
            null,
2151
            $params
2152
        );
2153
2154
        if ($required) {
2155
            $form->setRequired($select);
2156
        }
2157
2158
        $selectedEveryoneOptions = array();
2159
        if (isset($sendTo['everyone']) && $sendTo['everyone']) {
2160
            $selectedEveryoneOptions = array('selected');
2161
            $sendToUsers = array();
2162
        }
2163
2164
        $select->addOption(
2165
            get_lang('Everyone'),
2166
            'everyone',
2167
            $selectedEveryoneOptions
2168
        );
2169
2170
        $options = array();
2171
        if (is_array($groupList)) {
2172
            foreach ($groupList as $group) {
2173
                $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
2174
                $count_users = " &ndash; $count_users ".get_lang('Users');
2175
                $option = array(
2176
                    'text' => $group['name'].$count_users,
2177
                    'value' => "GROUP:".$group['id']
2178
                );
2179
                $selected = in_array(
2180
                    $group['id'],
2181
                    $sendToGroups
2182
                ) ? true : false;
2183
                if ($selected) {
2184
                    $option['selected'] = 'selected';
2185
                }
2186
2187
                if ($addOnlyItemsInSendTo) {
2188
                    if ($selected) {
2189
                        $options[] = $option;
2190
                    }
2191
                } else {
2192
                    $options[] = $option;
2193
                }
2194
            }
2195
            $select->addOptGroup($options, get_lang('Groups'));
2196
        }
2197
2198
        // adding the individual users to the select form
2199
        if (is_array($userList)) {
2200
            $options = array();
2201
            foreach ($userList as $user) {
2202
                if ($user['status'] == ANONYMOUS) {
2203
                    continue;
2204
                }
2205
                $option = array(
2206
                    'text' => api_get_person_name(
2207
                            $user['firstname'],
2208
                            $user['lastname']
2209
                        ).' ('.$user['username'].')',
2210
                    'value' => "USER:".$user['user_id']
2211
                );
2212
2213
                $selected = in_array(
2214
                    $user['user_id'],
2215
                    $sendToUsers
2216
                ) ? true : false;
2217
2218
                if ($selected) {
2219
                    $option['selected'] = 'selected';
2220
                }
2221
2222
                if ($addOnlyItemsInSendTo) {
2223
                    if ($selected) {
2224
                        $options[] = $option;
2225
                    }
2226
                } else {
2227
                    $options[] = $option;
2228
                }
2229
            }
2230
2231
            $select->addOptGroup($options, get_lang('Users'));
2232
        }
2233
    }
2234
2235
    /**
2236
     * Separates the users and groups array
2237
     * users have a value USER:XXX (with XXX the user id
2238
     * groups have a value GROUP:YYY (with YYY the group id)
2239
     * use the 'everyone' key
2240
     * @author Julio Montoya based in separate_users_groups in agenda.inc.php
2241
     * @param array $to
2242
     * @return array
2243
     */
2244
    public function parseSendToArray($to)
2245
    {
2246
        $groupList = array();
2247
        $userList = array();
2248
        $sendTo = null;
2249
2250
        $sendTo['everyone'] = false;
2251
        if (is_array($to) && count($to) > 0) {
2252
            foreach ($to as $item) {
2253
                if ($item == 'everyone') {
2254
                    $sendTo['everyone'] = true;
2255
                } else {
2256
                    list($type, $id) = explode(':', $item);
2257
                    switch ($type) {
2258
                        case 'GROUP':
2259
                            $groupList[] = $id;
2260
                            break;
2261
                        case 'USER':
2262
                            $userList[] = $id;
2263
                            break;
2264
                    }
2265
                }
2266
            }
2267
            $sendTo['groups'] = $groupList;
2268
            $sendTo['users'] = $userList;
2269
        }
2270
2271
        return $sendTo;
2272
    }
2273
2274
    /**
2275
     * @param array $params
2276
     * @return FormValidator
2277
     */
2278
    public function getForm($params = [])
2279
    {
2280
        $action = isset($params['action']) ? Security::remove_XSS(
2281
            $params['action']
2282
        ) : null;
2283
        $id = isset($params['id']) ? intval($params['id']) : null;
2284
        if ($this->type == 'course') {
2285
            $url = api_get_self().'?'.api_get_cidreq(
2286
                ).'&action='.$action.'&id='.$id.'&type='.$this->type;
2287
        } else {
2288
            $url = api_get_self(
2289
                ).'?action='.$action.'&id='.$id.'&type='.$this->type;
2290
        }
2291
2292
        $form = new FormValidator(
2293
            'add_event',
2294
            'post',
2295
            $url,
2296
            null,
2297
            array('enctype' => 'multipart/form-data')
2298
        );
2299
2300
        $idAttach = isset($params['id_attach']) ? intval(
2301
            $params['id_attach']
2302
        ) : null;
2303
        $groupId = api_get_group_id();
2304
2305
        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...
2306
            $form_title = get_lang('ModifyCalendarItem');
2307
        } else {
2308
            $form_title = get_lang('AddCalendarItem');
2309
        }
2310
2311
        $form->addElement('header', $form_title);
2312
        $form->addElement('hidden', 'id', $id);
2313
        $form->addElement('hidden', 'action', $action);
2314
        $form->addElement('hidden', 'id_attach', $idAttach);
2315
2316
        $isSubEventEdition = false;
2317
        $isParentFromSerie = false;
2318
        $showAttachmentForm = true;
2319
2320
        if ($this->type == 'course') {
2321
            // Edition mode.
2322
            if (!empty($id)) {
2323
                $showAttachmentForm = false;
2324
                if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
2325
                    $isSubEventEdition = true;
2326
                }
2327
                if (!empty($params['repeat_info'])) {
2328
                    $isParentFromSerie = true;
2329
                }
2330
            }
2331
        }
2332
2333
        if ($isSubEventEdition) {
2334
            $form->addElement(
2335
                'label',
2336
                null,
2337
                Display::return_message(
2338
                    get_lang('EditingThisEventWillRemoveItFromTheSerie'),
2339
                    'warning'
2340
                )
2341
            );
2342
        }
2343
2344
        $form->addElement('text', 'title', get_lang('ItemTitle'));
2345
2346
        if (isset($groupId) && !empty($groupId)) {
2347
            $form->addElement(
2348
                'hidden',
2349
                'selected_form[0]',
2350
                "GROUP:'.$groupId.'"
2351
            );
2352
            $form->addElement('hidden', 'to', 'true');
2353
        } else {
2354
            $sendTo = isset($params['send_to']) ? $params['send_to'] : ['everyone' => true];
2355
            if ($this->type == 'course') {
2356
                $this->showToForm($form, $sendTo, array(), false, true);
2357
            }
2358
        }
2359
2360
        $form->addDateRangePicker(
2361
            'date_range',
2362
            get_lang('DateRange'),
2363
            false,
2364
            array('id' => 'date_range')
2365
        );
2366
        $form->addElement('checkbox', 'all_day', null, get_lang('AllDay'));
2367
2368
        if ($this->type == 'course') {
2369
            $repeat = $form->addElement(
2370
                'checkbox',
2371
                'repeat',
2372
                null,
2373
                get_lang('RepeatEvent'),
2374
                array('onclick' => 'return plus_repeated_event();')
2375
            );
2376
            $form->addElement(
2377
                'html',
2378
                '<div id="options2" style="display:none">'
2379
            );
2380
            $form->addElement(
2381
                'select',
2382
                'repeat_type',
2383
                get_lang('RepeatType'),
2384
                self::getRepeatTypes()
2385
            );
2386
            $form->addElement(
2387
                'date_picker',
2388
                'repeat_end_day',
2389
                get_lang('RepeatEnd'),
2390
                array('id' => 'repeat_end_date_form')
2391
            );
2392
2393
            if ($isSubEventEdition || $isParentFromSerie) {
2394
                if ($isSubEventEdition) {
2395
                    $parentEvent = $params['parent_info'];
2396
                    $repeatInfo = $parentEvent['repeat_info'];
2397
                } else {
2398
                    $repeatInfo = $params['repeat_info'];
2399
                }
2400
                $params['repeat'] = 1;
2401
                $params['repeat_type'] = $repeatInfo['cal_type'];
2402
                $params['repeat_end_day'] = substr(
2403
                    api_get_local_time($repeatInfo['cal_end']),
2404
                    0,
2405
                    10
2406
                );
2407
2408
                $form->freeze(array('repeat_type', 'repeat_end_day'));
2409
                $repeat->_attributes['disabled'] = 'disabled';
2410
            }
2411
            $form->addElement('html', '</div>');
2412
        }
2413
2414
        if (!empty($id)) {
2415
            if (empty($params['end_date'])) {
2416
                $params['date_range'] = $params['end_date'];
2417
            }
2418
2419
            $params['date_range'] =
2420
                substr(api_get_local_time($params['start_date']), 0, 16).' / '.
2421
                substr(api_get_local_time($params['end_date']), 0, 16);
2422
        }
2423
2424
        if (!api_is_allowed_to_edit(null, true)) {
2425
            $toolbar = 'AgendaStudent';
2426
        } else {
2427
            $toolbar = 'Agenda';
2428
        }
2429
2430
        $form->addElement(
2431
            'html_editor',
2432
            'content',
2433
            get_lang('Description'),
2434
            null,
2435
            array(
2436
                'ToolbarSet' => $toolbar,
2437
                'Width' => '100%',
2438
                'Height' => '200'
2439
            )
2440
        );
2441
2442
        if ($this->type == 'course') {
2443
            $form->addElement('textarea', 'comment', get_lang('Comment'));
2444
            $form->addLabel(
2445
                get_lang('FilesAttachment'),
2446
                '<span id="filepaths">
2447
                        <div id="filepath_1">
2448
                            <input type="file" name="attach_1"/><br />
2449
                            '.get_lang('Description').'&nbsp;&nbsp;<input type="text" name="legend[]" /><br /><br />
2450
                        </div>
2451
                    </span>'
2452
            );
2453
2454
            $form->addLabel(
2455
                '',
2456
                '<span id="link-more-attach">
2457
                    <a href="javascript://" onclick="return add_image_form()">'.
2458
                get_lang('AddOneMoreFile').'</a>
2459
                 </span>&nbsp;('.sprintf(
2460
                    get_lang('MaximunFileSizeX'),
2461
                    format_file_size(
2462
                        api_get_setting('message_max_upload_filesize')
2463
                    )
2464
                ).')'
2465
            );
2466
2467
            if (isset($params['attachment']) && !empty($params['attachment'])) {
2468
                $attachmentList = $params['attachment'];
2469
                foreach ($attachmentList as $attachment) {
2470
                    $params['file_comment'] = $attachment['comment'];
2471
                    if (!empty($attachment['path'])) {
2472
                        $form->addElement(
2473
                            'checkbox',
2474
                            'delete_attachment['.$attachment['id'].']',
2475
                            null,
2476
                            get_lang(
2477
                                'DeleteAttachment'
2478
                            ).': '.$attachment['filename']
2479
                        );
2480
                    }
2481
                }
2482
            }
2483
2484
            $form->addElement(
2485
                'textarea',
2486
                'file_comment',
2487
                get_lang('FileComment')
2488
            );
2489
        }
2490
2491
        if (empty($id)) {
2492
            $form->addElement(
2493
                'checkbox',
2494
                'add_announcement',
2495
                null,
2496
                get_lang('AddAnnouncement').'&nbsp('.get_lang('SendMail').')'
2497
            );
2498
        }
2499
2500
        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...
2501
            $form->addButtonUpdate(get_lang('ModifyEvent'));
2502
        } else {
2503
            $form->addButtonSave(get_lang('AgendaAdd'));
2504
        }
2505
2506
        $form->setDefaults($params);
2507
2508
        $form->addRule(
2509
            'date_range',
2510
            get_lang('ThisFieldIsRequired'),
2511
            'required'
2512
        );
2513
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
2514
2515
        return $form;
2516
    }
2517
2518
    /**
2519
     * @param FormValidator $form
2520
     * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
2521
     * @param array $attributes
2522
     * @param bool $addOnlyItemsInSendTo
2523
     * @param bool $required
2524
     * @return bool
2525
     */
2526
    public function showToForm(
2527
        $form,
2528
        $sendTo = array(),
2529
        $attributes = array(),
2530
        $addOnlyItemsInSendTo = false,
2531
        $required = false
2532
    ) {
2533
        if ($this->type != 'course') {
2534
            return false;
2535
        }
2536
2537
        $order = 'lastname';
2538
        if (api_is_western_name_order()) {
2539
            $order = 'firstname';
2540
        }
2541
2542
        $userList = CourseManager::get_user_list_from_course_code(
2543
            api_get_course_id(),
2544
            $this->sessionId,
2545
            null,
2546
            $order
2547
        );
2548
2549
        $groupList = CourseManager::get_group_list_of_course(
2550
            api_get_course_id(),
2551
            $this->sessionId
2552
        );
2553
2554
        $this->setSendToSelect(
2555
            $form,
2556
            $groupList,
2557
            $userList,
0 ignored issues
show
Bug introduced by
It seems like $userList defined by \CourseManager::get_user...essionId, null, $order) on line 2542 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...
2558
            $sendTo,
2559
            $attributes,
2560
            $addOnlyItemsInSendTo,
2561
            $required
2562
        );
2563
2564
        return true;
2565
    }
2566
2567
    /**
2568
     * @param int $id
2569
     * @param int $visibility 0= invisible, 1 visible
2570
     * @param array $courseInfo
2571
     * @param int $userId
2572
     */
2573
    public static function changeVisibility(
2574
        $id,
2575
        $visibility,
2576
        $courseInfo,
2577
        $userId = null
2578
    ) {
2579
        $id = intval($id);
2580
        if (empty($userId)) {
2581
            $userId = api_get_user_id();
2582
        } else {
2583
            $userId = intval($userId);
2584
        }
2585
2586
        if ($visibility == 0) {
2587
            api_item_property_update(
2588
                $courseInfo,
2589
                TOOL_CALENDAR_EVENT,
2590
                $id,
2591
                'invisible',
2592
                $userId
2593
            );
2594
        } else {
2595
            api_item_property_update(
2596
                $courseInfo,
2597
                TOOL_CALENDAR_EVENT,
2598
                $id,
2599
                'visible',
2600
                $userId
2601
            );
2602
        }
2603
    }
2604
2605
    /**
2606
     * Get repeat types
2607
     * @return array
2608
     */
2609
    public static function getRepeatTypes()
2610
    {
2611
        return array(
2612
            'daily' => get_lang('RepeatDaily'),
2613
            'weekly' => get_lang('RepeatWeekly'),
2614
            'monthlyByDate' => get_lang('RepeatMonthlyByDate'),
2615
            //monthlyByDay"> get_lang('RepeatMonthlyByDay');
2616
            //monthlyByDayR' => get_lang('RepeatMonthlyByDayR'),
2617
            'yearly' => get_lang('RepeatYearly')
2618
        );
2619
    }
2620
2621
    /**
2622
     * Show a list with all the attachments according to the post's id
2623
     * @param int $eventId
2624
     * @param array $courseInfo
2625
     * @return array with the post info
2626
     */
2627 View Code Duplication
    public function getAttachmentList($eventId, $courseInfo)
2628
    {
2629
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2630
        $courseId = intval($courseInfo['real_id']);
2631
        $eventId = intval($eventId);
2632
2633
        $sql = "SELECT id, path, filename, comment
2634
                FROM $tableAttachment
2635
                WHERE
2636
                    c_id = $courseId AND
2637
                    agenda_id = $eventId";
2638
        $result = Database::query($sql);
2639
        $list = array();
2640
        if (Database::num_rows($result) != 0) {
2641
            $list = Database::store_result($result, 'ASSOC');
2642
        }
2643
2644
        return $list;
2645
    }
2646
2647
    /**
2648
     * Show a list with all the attachments according to the post's id
2649
     * @param int $attachmentId
2650
     * @param int $eventId
2651
     * @param array $courseInfo
2652
     * @return array with the post info
2653
     */
2654 View Code Duplication
    public function getAttachment($attachmentId, $eventId, $courseInfo)
2655
    {
2656
        $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
2657
        $courseId = intval($courseInfo['real_id']);
2658
        $eventId = intval($eventId);
2659
        $attachmentId = intval($attachmentId);
2660
2661
        $row = array();
2662
        $sql = "SELECT id, path, filename, comment
2663
                FROM $tableAttachment
2664
                WHERE
2665
                    c_id = $courseId AND
2666
                    agenda_id = $eventId AND
2667
                    id = $attachmentId
2668
                ";
2669
        $result = Database::query($sql);
2670
        if (Database::num_rows($result) != 0) {
2671
            $row = Database::fetch_array($result, 'ASSOC');
2672
        }
2673
2674
        return $row;
2675
    }
2676
2677
    /**
2678
     * Add an attachment file into agenda
2679
     * @param int $eventId
2680
     * @param array $fileUserUpload ($_FILES['user_upload'])
2681
     * @param string $comment about file
2682
     * @param array $courseInfo
2683
     * @return string
2684
     */
2685
    public function addAttachment(
2686
        $eventId,
2687
        $fileUserUpload,
2688
        $comment,
2689
        $courseInfo
2690
    ) {
2691
        $agenda_table_attachment = Database::get_course_table(
2692
            TABLE_AGENDA_ATTACHMENT
2693
        );
2694
        $eventId = intval($eventId);
2695
2696
        // Storing the attachments
2697
        $upload_ok = false;
2698
        if (!empty($fileUserUpload['name'])) {
2699
            $upload_ok = process_uploaded_file($fileUserUpload);
2700
        }
2701
2702
        if (!empty($upload_ok)) {
2703
            $courseDir = $courseInfo['directory'].'/upload/calendar';
2704
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
2705
            $uploadDir = $sys_course_path.$courseDir;
2706
2707
            // Try to add an extension to the file if it hasn't one
2708
            $new_file_name = add_ext_on_mime(
2709
                stripslashes($fileUserUpload['name']),
2710
                $fileUserUpload['type']
2711
            );
2712
2713
            // user's file name
2714
            $file_name = $fileUserUpload['name'];
2715
2716
            if (!filter_extension($new_file_name)) {
2717
                return Display::return_message(
2718
                    get_lang('UplUnableToSaveFileFilteredExtension'),
2719
                    'error'
2720
                );
2721
            } else {
2722
                $new_file_name = uniqid('');
2723
                $new_path = $uploadDir.'/'.$new_file_name;
2724
                $result = @move_uploaded_file(
2725
                    $fileUserUpload['tmp_name'],
2726
                    $new_path
2727
                );
2728
                $course_id = api_get_course_int_id();
2729
                $size = intval($fileUserUpload['size']);
2730
                // Storing the attachments if any
2731
                if ($result) {
2732
                    $params = [
2733
                        'c_id' => $course_id,
2734
                        'filename' => $file_name,
2735
                        'comment' => $comment,
2736
                        'path' => $new_file_name,
2737
                        'agenda_id' => $eventId,
2738
                        'size' => $size
2739
                    ];
2740
                    $id = Database::insert($agenda_table_attachment, $params);
2741
                    if ($id) {
2742
                        $sql = "UPDATE $agenda_table_attachment
2743
                                SET id = iid WHERE iid = $id";
2744
                        Database::query($sql);
2745
2746
                        api_item_property_update(
2747
                            $courseInfo,
2748
                            'calendar_event_attachment',
2749
                            $id,
2750
                            'AgendaAttachmentAdded',
2751
                            api_get_user_id()
2752
                        );
2753
                    }
2754
                }
2755
            }
2756
        }
2757
    }
2758
2759
    /**
2760
     * @param int $attachmentId
2761
     * @param int $eventId
2762
     * @param array $fileUserUpload
2763
     * @param string $comment
2764
     * @param array $courseInfo
2765
     */
2766
    public function updateAttachment(
2767
        $attachmentId,
2768
        $eventId,
2769
        $fileUserUpload,
2770
        $comment,
2771
        $courseInfo
2772
    ) {
2773
        $attachment = $this->getAttachment(
2774
            $attachmentId,
2775
            $eventId,
2776
            $courseInfo
2777
        );
2778
        if (!empty($attachment)) {
2779
            $this->deleteAttachmentFile($attachmentId, $courseInfo);
2780
        }
2781
        $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
2782
    }
2783
2784
    /**
2785
     * This function delete a attachment file by id
2786
     * @param int $attachmentId
2787
     * @param array $courseInfo
2788
     * @return string
2789
     */
2790
    public function deleteAttachmentFile($attachmentId, $courseInfo)
2791
    {
2792
        $agenda_table_attachment = Database::get_course_table(
2793
            TABLE_AGENDA_ATTACHMENT
2794
        );
2795
        $attachmentId = intval($attachmentId);
2796
        $courseId = $courseInfo['real_id'];
2797
2798
        if (empty($courseId) || empty($attachmentId)) {
2799
            return false;
2800
        }
2801
2802
        $sql = "DELETE FROM $agenda_table_attachment
2803
                WHERE c_id = $courseId AND id = ".$attachmentId;
2804
        $result = Database::query($sql);
2805
2806
        // update item_property
2807
        api_item_property_update(
2808
            $courseInfo,
2809
            'calendar_event_attachment',
2810
            $attachmentId,
2811
            'AgendaAttachmentDeleted',
2812
            api_get_user_id()
2813
        );
2814
2815
        if (!empty($result)) {
2816
            return Display::return_message(
2817
                get_lang("AttachmentFileDeleteSuccess"),
2818
                'confirmation'
2819
            );
2820
        }
2821
    }
2822
2823
    /**
2824
     * Adds x weeks to a UNIX timestamp
2825
     * @param   int     The timestamp
2826
     * @param   int     The number of weeks to add
2827
     * @param integer $timestamp
2828
     * @return  int     The new timestamp
2829
     */
2830
    public function addWeek($timestamp, $num = 1)
2831
    {
2832
        return $timestamp + $num * 604800;
2833
    }
2834
2835
    /**
2836
     * Adds x months to a UNIX timestamp
2837
     * @param   int     The timestamp
2838
     * @param   int     The number of years to add
2839
     * @param integer $timestamp
2840
     * @return  int     The new timestamp
2841
     */
2842
    public function addMonth($timestamp, $num = 1)
2843
    {
2844
        list($y, $m, $d, $h, $n, $s) = split(
2845
            '/',
2846
            date('Y/m/d/h/i/s', $timestamp)
2847
        );
2848 View Code Duplication
        if ($m + $num > 12) {
2849
            $y += floor($num / 12);
2850
            $m += $num % 12;
2851
        } else {
2852
            $m += $num;
2853
        }
2854
2855
        return mktime($h, $n, $s, $m, $d, $y);
2856
    }
2857
2858
    /**
2859
     * Adds x years to a UNIX timestamp
2860
     * @param   int     The timestamp
2861
     * @param   int     The number of years to add
2862
     * @param integer $timestamp
2863
     * @return  int     The new timestamp
2864
     */
2865
    public function addYear($timestamp, $num = 1)
2866
    {
2867
        list($y, $m, $d, $h, $n, $s) = split(
2868
            '/',
2869
            date('Y/m/d/h/i/s', $timestamp)
2870
        );
2871
2872
        return mktime($h, $n, $s, $m, $d, $y + $num);
2873
    }
2874
2875
    /**
2876
     * @param int $eventId
2877
     * @return array
2878
     */
2879
    public function getAllRepeatEvents($eventId)
2880
    {
2881
        $events = array();
2882
        switch ($this->type) {
2883
            case 'personal':
2884
                break;
2885
            case 'course':
2886
                if (!empty($this->course['real_id'])) {
2887
                    $sql = "SELECT * FROM ".$this->tbl_course_agenda."
2888
                            WHERE
2889
                                c_id = ".$this->course['real_id']." AND
2890
                                parent_event_id = ".$eventId;
2891
                    $result = Database::query($sql);
2892
                    if (Database::num_rows($result)) {
2893
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
2894
                            $events[] = $row;
2895
                        }
2896
                    }
2897
                }
2898
                break;
2899
        }
2900
2901
        return $events;
2902
    }
2903
2904
    /**
2905
     * @param int $eventId
2906
     * @param int $courseId
2907
     *
2908
     * @return bool
2909
     */
2910 View Code Duplication
    public function hasChildren($eventId, $courseId)
2911
    {
2912
        $eventId = intval($eventId);
2913
        $courseId = intval($courseId);
2914
2915
        $sql = "SELECT count(DISTINCT(id)) as count
2916
                FROM ".$this->tbl_course_agenda."
2917
                WHERE
2918
                    c_id = $courseId AND
2919
                    parent_event_id = $eventId";
2920
        $result = Database::query($sql);
2921
        if (Database::num_rows($result)) {
2922
            $row = Database::fetch_array($result, 'ASSOC');
2923
2924
            return $row['count'] > 0;
2925
        }
2926
2927
        return false;
2928
    }
2929
2930
    /**
2931
     * @param int $filter
2932
     * @param string $view
2933
     * @return string
2934
     */
2935
    public function displayActions($view, $filter = 0)
2936
    {
2937
        $courseInfo = api_get_course_info();
2938
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
2939
        $groupIid = isset($groupInfo['iid']) ? $groupInfo['iid'] : 0;
2940
2941
        $courseCondition = '';
2942
        if (!empty($courseInfo)) {
2943
            $courseCondition = api_get_cidreq();
2944
        }
2945
2946
        $actionsLeft = '';
2947
        $actionsLeft .= "<a href='".api_get_path(
2948
                WEB_CODE_PATH
2949
            )."calendar/agenda_js.php?type={$this->type}&".$courseCondition."'>".
2950
            Display::return_icon(
2951
                'calendar.png',
2952
                get_lang('Calendar'),
2953
                '',
2954
                ICON_SIZE_MEDIUM
2955
            )."</a>";
2956
2957
        $actionsLeft .= "<a href='".api_get_path(
2958
                WEB_CODE_PATH
2959
            )."calendar/agenda_list.php?type={$this->type}&".$courseCondition."'>".
2960
            Display::return_icon(
2961
                'week.png',
2962
                get_lang('AgendaList'),
2963
                '',
2964
                ICON_SIZE_MEDIUM
2965
            )."</a>";
2966
2967
        $form = '';
2968
        if (api_is_allowed_to_edit(false, true) ||
2969
            (api_get_course_setting(
2970
                    'allow_user_edit_agenda'
2971
                ) && !api_is_anonymous()) &&
2972
            api_is_allowed_to_session_edit(false, true) ||
2973
            (GroupManager::user_has_access(
2974
                    api_get_user_id(),
2975
                    $groupIid,
2976
                    GroupManager::GROUP_TOOL_CALENDAR
2977
                ) &&
2978
                GroupManager::is_tutor_of_group(api_get_user_id(), $groupIid))
2979
        ) {
2980
            $actionsLeft .= Display::url(
2981
                Display::return_icon(
2982
                    'new_event.png',
2983
                    get_lang('AgendaAdd'),
2984
                    '',
2985
                    ICON_SIZE_MEDIUM
2986
                ),
2987
                api_get_path(
2988
                    WEB_CODE_PATH
2989
                )."calendar/agenda.php?".api_get_cidreq(
2990
                )."&action=add&type=".$this->type
2991
            );
2992
2993
            $actionsLeft .= Display::url(
2994
                Display::return_icon(
2995
                    'import_calendar.png',
2996
                    get_lang('ICalFileImport'),
2997
                    '',
2998
                    ICON_SIZE_MEDIUM
2999
                ),
3000
                api_get_path(
3001
                    WEB_CODE_PATH
3002
                )."calendar/agenda.php?".api_get_cidreq(
3003
                )."&action=importical&type=".$this->type
3004
            );
3005
3006
            if ($this->type === 'course') {
3007
                if (!isset($_GET['action'])) {
3008
                    $form = new FormValidator(
3009
                        'form-search',
3010
                        'post',
3011
                        '',
3012
                        '',
3013
                        array(),
3014
                        FormValidator::LAYOUT_INLINE
3015
                    );
3016
                    $attributes = array(
3017
                        'multiple' => false,
3018
                        'id' => 'select_form_id_search'
3019
                    );
3020
                    $selectedValues = $this->parseAgendaFilter($filter);
3021
                    $this->showToForm($form, $selectedValues, $attributes);
3022
                    $form = $form->returnForm();
3023
                }
3024
            }
3025
        }
3026
3027
        if (api_is_platform_admin() ||
3028
            api_is_teacher() ||
3029
            api_is_student_boss() ||
3030
            api_is_drh() ||
3031
            api_is_session_admin() ||
3032
            api_is_coach()
3033
        ) {
3034
            if ($this->type == 'personal') {
3035
                $form = null;
3036
                if (!isset($_GET['action'])) {
3037
                    $form = new FormValidator(
3038
                        'form-search',
3039
                        'get',
3040
                        api_get_self().'?type=personal&',
3041
                        '',
3042
                        array(),
3043
                        FormValidator::LAYOUT_INLINE
3044
                    );
3045
3046
                    $sessions = SessionManager::get_sessions_by_user(
3047
                        api_get_user_id()
3048
                    );
3049
                    $form->addHidden('type', 'personal');
3050
                    $sessions = array_column(
3051
                        $sessions,
3052
                        'session_name',
3053
                        'session_id'
3054
                    );
3055
                    $sessions = ['0' => get_lang('SelectAnOption')] + $sessions;
3056
3057
                    $form->addSelect(
3058
                        'session_id',
3059
                        get_lang('Session'),
3060
                        $sessions,
3061
                        ['id' => 'session_id', 'onchange' => 'submit();']
3062
                    );
3063
3064
                    $form->addButtonReset(get_lang('Reset'));
3065
                    $form = $form->returnForm();
3066
                }
3067
            }
3068
        }
3069
3070
        $actionsRight = '';
3071
        if ($view == 'calendar') {
3072
            $actionsRight .= $form;
3073
        }
3074
3075
        $toolbar = Display::toolbarAction(
3076
            'toolbar-agenda',
3077
            array(0 => $actionsLeft, 1 => $actionsRight),
3078
            2,
3079
            false
3080
        );
3081
3082
        return $toolbar;
3083
    }
3084
3085
    /**
3086
     * @return FormValidator
3087
     */
3088
    public function getImportCalendarForm()
3089
    {
3090
        $form = new FormValidator(
3091
            'frm_import_ical',
3092
            'post',
3093
            api_get_self().'?action=importical&type='.$this->type,
3094
            array('enctype' => 'multipart/form-data')
3095
        );
3096
        $form->addElement('header', get_lang('ICalFileImport'));
3097
        $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
3098
        $form->addRule(
3099
            'ical_import',
3100
            get_lang('ThisFieldIsRequired'),
3101
            'required'
3102
        );
3103
        $form->addButtonImport(get_lang('Import'), 'ical_submit');
3104
3105
        return $form;
3106
    }
3107
3108
    /**
3109
     * @param array $courseInfo
3110
     * @param $file
3111
     * @return false|string
3112
     */
3113
    public function importEventFile($courseInfo, $file)
3114
    {
3115
        $charset = api_get_system_encoding();
3116
        $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
3117
        $messages = array();
3118
3119
        if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
3120
            error_log(
3121
                'Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__
3122
            );
3123
3124
            return false;
3125
        }
3126
3127
        $data = file_get_contents($filepath);
3128
3129
        $trans = array(
3130
            'DAILY' => 'daily',
3131
            'WEEKLY' => 'weekly',
3132
            'MONTHLY' => 'monthlyByDate',
3133
            'YEARLY' => 'yearly'
3134
        );
3135
        $sentTo = array('everyone' => true);
3136
        $calendar = Sabre\VObject\Reader::read($data);
3137
        $currentTimeZone = api_get_timezone();
3138
        if (!empty($calendar->VEVENT)) {
3139
            foreach ($calendar->VEVENT as $event) {
3140
                $start = $event->DTSTART->getDateTime();
3141
                $end = $event->DTEND->getDateTime();
3142
                //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
3143
3144
                $startDateTime = api_get_local_time(
3145
                    $start->format('Y-m-d H:i:s'),
3146
                    $currentTimeZone,
3147
                    $start->format('e')
3148
                );
3149
                $endDateTime = api_get_local_time(
3150
                    $end->format('Y-m-d H:i'),
3151
                    $currentTimeZone,
3152
                    $end->format('e')
3153
                );
3154
                $title = api_convert_encoding(
3155
                    (string)$event->summary,
3156
                    $charset,
3157
                    'UTF-8'
3158
                );
3159
                $description = api_convert_encoding(
3160
                    (string)$event->description,
3161
                    $charset,
3162
                    'UTF-8'
3163
                );
3164
3165
                $id = $this->addEvent(
3166
                    $startDateTime,
3167
                    $endDateTime,
3168
                    'false',
3169
                    $title,
3170
                    $description,
3171
                    $sentTo
3172
                );
3173
3174
                $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
3175
3176
                //$attendee = (string)$event->attendee;
3177
                /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
3178
                $repeat = $event->RRULE;
3179
                if ($id && !empty($repeat)) {
3180
                    $repeat = $repeat->getParts();
3181
                    $freq = $trans[$repeat['FREQ']];
3182
3183
                    if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
3184
                        // Check if datetime or just date (strlen == 8)
3185
                        if (strlen($repeat['UNTIL']) == 8) {
3186
                            // Fix the datetime format to avoid exception in the next step
3187
                            $repeat['UNTIL'] .= 'T000000';
3188
                        }
3189
                        $until = Sabre\VObject\DateTimeParser::parseDateTime(
3190
                            $repeat['UNTIL'],
3191
                            new DateTimeZone($currentTimeZone)
3192
                        );
3193
                        $until = $until->format('Y-m-d H:i');
3194
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $until, $attendee);
3195
                        $this->addRepeatedItem(
3196
                            $id,
3197
                            $freq,
3198
                            $until,
3199
                            $sentTo
3200
                        );
3201
                    }
3202
3203
                    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...
3204
                        /*$count = $repeat['COUNT'];
3205
                        $interval = $repeat['INTERVAL'];
3206
                        $endDate = null;
3207
                        switch($freq) {
3208
                            case 'daily':
3209
                                $start = api_strtotime($startDateTime);
3210
                                $date = new DateTime($startDateTime);
3211
                                $days = $count * $interval;
3212
                                var_dump($days);
3213
                                $date->add(new DateInterval("P".$days."D"));
3214
                                $endDate = $date->format('Y-m-d H:i');
3215
                                //$endDate = $count *
3216
                                for ($i = 0; $i < $count; $i++) {
3217
                                    $days = 86400 * 7
3218
                                }
3219
                            }
3220
                        }*/
3221
                        //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
3222
                        /*$this->addRepeatedItem(
3223
                            $id,
3224
                            $freq,
3225
                            $endDate,
3226
                            $sentTo
3227
                        );*/
3228
                    }
3229
                }
3230
            }
3231
        }
3232
3233
        if (!empty($messages)) {
3234
            $messages = implode('<br /> ', $messages);
3235
        } else {
3236
            $messages = get_lang('NoAgendaItems');
3237
3238
        }
3239
3240
        return $messages;
3241
    }
3242
3243
    /**
3244
     * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]]
3245
     * @param integer $filter
3246
     * @return array
3247
     */
3248
    public function parseAgendaFilter($filter)
3249
    {
3250
        $everyone = false;
3251
        $groupId = null;
3252
        $userId = null;
3253
3254
        if ($filter == 'everyone') {
3255
            $everyone = true;
3256
        } else {
3257
            if (substr($filter, 0, 1) == 'G') {
3258
                $groupId = str_replace('GROUP:', '', $filter);
3259
            } else {
3260
                $userId = str_replace('USER:', '', $filter);
3261
            }
3262
        }
3263
        if (empty($userId) && empty($groupId)) {
3264
            $everyone = true;
3265
        }
3266
3267
        return array(
3268
            'everyone' => $everyone,
3269
            'users' => array($userId),
3270
            'groups' => array($groupId)
3271
        );
3272
    }
3273
3274
    /**
3275
     *    This function retrieves all the agenda items of all the courses the user is subscribed to
3276
     */
3277
    public static function get_myagendaitems(
3278
        $user_id,
3279
        $courses_dbs,
3280
        $month,
3281
        $year
3282
    ) {
3283
        $user_id = intval($user_id);
3284
3285
        $items = array();
3286
        $my_list = array();
3287
3288
        // get agenda-items for every course
3289
        foreach ($courses_dbs as $key => $array_course_info) {
3290
            //databases of the courses
3291
            $TABLEAGENDA = Database:: get_course_table(TABLE_AGENDA);
3292
            $TABLE_ITEMPROPERTY = Database:: get_course_table(
3293
                TABLE_ITEM_PROPERTY
3294
            );
3295
3296
            $group_memberships = GroupManager::get_group_ids(
3297
                $array_course_info['real_id'],
3298
                $user_id
3299
            );
3300
            $course_user_status = CourseManager::getUserInCourseStatus(
3301
                $user_id,
3302
                $array_course_info['real_id']
3303
            );
3304
            // if the user is administrator of that course we show all the agenda items
3305
            if ($course_user_status == '1') {
3306
                //echo "course admin";
3307
                $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3308
							FROM ".$TABLEAGENDA." agenda,
3309
								 ".$TABLE_ITEMPROPERTY." ip
3310
							WHERE agenda.id = ip.ref
3311
							AND MONTH(agenda.start_date)='".$month."'
3312
							AND YEAR(agenda.start_date)='".$year."'
3313
							AND ip.tool='".TOOL_CALENDAR_EVENT."'
3314
							AND ip.visibility='1'
3315
							GROUP BY agenda.id
3316
							ORDER BY start_date ";
3317
            } else {
3318
                // if the user is not an administrator of that course
3319
                if (is_array($group_memberships) && count(
3320
                        $group_memberships
3321
                    ) > 0
3322
                ) {
3323
                    $sqlquery = "SELECT	agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3324
								FROM ".$TABLEAGENDA." agenda,
3325
									".$TABLE_ITEMPROPERTY." ip
3326
								WHERE agenda.id = ip.ref
3327
								AND MONTH(agenda.start_date)='".$month."'
3328
								AND YEAR(agenda.start_date)='".$year."'
3329
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3330
								AND	( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
3331
                            ", ",
3332
                            $group_memberships
3333
                        ).")) )
3334
								AND ip.visibility='1'
3335
								ORDER BY start_date ";
3336
                } else {
3337
                    $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
3338
								FROM ".$TABLEAGENDA." agenda,
3339
									".$TABLE_ITEMPROPERTY." ip
3340
								WHERE agenda.id = ip.ref
3341
								AND MONTH(agenda.start_date)='".$month."'
3342
								AND YEAR(agenda.start_date)='".$year."'
3343
								AND ip.tool='".TOOL_CALENDAR_EVENT."'
3344
								AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
3345
								AND ip.visibility='1'
3346
								ORDER BY start_date ";
3347
                }
3348
            }
3349
            $result = Database::query($sqlquery);
3350
3351
            while ($item = Database::fetch_array($result, 'ASSOC')) {
3352
                $agendaday = -1;
3353
                if (!empty($item['start_date'])) {
3354
                    $item['start_date'] = api_get_local_time(
3355
                        $item['start_date']
3356
                    );
3357
                    $item['start_date_tms'] = api_strtotime(
3358
                        $item['start_date']
3359
                    );
3360
                    $agendaday = date("j", $item['start_date_tms']);
3361
                }
3362
                if (!empty($item['end_date'])) {
3363
                    $item['end_date'] = api_get_local_time($item['end_date']);
3364
                }
3365
3366
                $url = api_get_path(
3367
                        WEB_CODE_PATH
3368
                    )."calendar/agenda.php?cidReq=".urlencode(
3369
                        $array_course_info["code"]
3370
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
3371
3372
                $item['url'] = $url;
3373
                $item['course_name'] = $array_course_info['title'];
3374
                $item['calendar_type'] = 'course';
3375
                $item['course_id'] = $array_course_info['course_id'];
3376
3377
                $my_list[$agendaday][] = $item;
3378
            }
3379
        }
3380
3381
        // sorting by hour for every day
3382
        $agendaitems = array();
3383
        while (list ($agendaday, $tmpitems) = each($items)) {
3384
            if (!isset($agendaitems[$agendaday])) {
3385
                $agendaitems[$agendaday] = '';
3386
            }
3387
            sort($tmpitems);
3388
            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...
3389
                $agendaitems[$agendaday] .= $val;
3390
            }
3391
        }
3392
3393
        return $my_list;
3394
    }
3395
3396
    /**
3397
     * This function retrieves one personal agenda item returns it.
3398
     * @param    array    The array containing existing events. We add to this array.
3399
     * @param    int        Day
3400
     * @param    int        Month
3401
     * @param    int        Year (4 digits)
3402
     * @param    int        Week number
3403
     * @param    string    Type of view (month_view, week_view, day_view)
3404
     * @return    array    The results of the database query, or null if not found
3405
     */
3406
    public static function get_global_agenda_items(
3407
        $agendaitems,
3408
        $day = "",
3409
        $month = "",
3410
        $year = "",
3411
        $week = "",
3412
        $type
3413
    ) {
3414
        $tbl_global_agenda = Database::get_main_table(
3415
            TABLE_MAIN_SYSTEM_CALENDAR
3416
        );
3417
        $month = intval($month);
3418
        $year = intval($year);
3419
        $week = intval($week);
3420
        $day = intval($day);
3421
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3422
3423
        $current_access_url_id = api_get_current_access_url_id();
3424
3425
        if ($type == "month_view" or $type == "") {
3426
            // We are in month view
3427
            $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";
3428
        }
3429
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3430 View Code Duplication
        if ($type == "week_view") { // we are in week view
3431
            $start_end_day_of_week = self::calculate_start_end_of_week(
3432
                $week,
3433
                $year
3434
            );
3435
            $start_day = $start_end_day_of_week['start']['day'];
3436
            $start_month = $start_end_day_of_week['start']['month'];
3437
            $start_year = $start_end_day_of_week['start']['year'];
3438
            $end_day = $start_end_day_of_week['end']['day'];
3439
            $end_month = $start_end_day_of_week['end']['month'];
3440
            $end_year = $start_end_day_of_week['end']['year'];
3441
            // in sql statements you have to use year-month-day for date calculations
3442
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3443
            $start_filter = api_get_utc_datetime($start_filter);
3444
3445
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3446
            $end_filter = api_get_utc_datetime($end_filter);
3447
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND  access_url_id = $current_access_url_id ";
3448
        }
3449
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3450 View Code Duplication
        if ($type == "day_view") { // we are in day view
3451
            // we could use mysql date() function but this is only available from 4.1 and higher
3452
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3453
            $start_filter = api_get_utc_datetime($start_filter);
3454
3455
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3456
            $end_filter = api_get_utc_datetime($end_filter);
3457
            $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'  AND  access_url_id = $current_access_url_id";
3458
        }
3459
3460
        $result = Database::query($sql);
3461
3462
        while ($item = Database::fetch_array($result)) {
3463
3464
            if (!empty($item['start_date'])) {
3465
                $item['start_date'] = api_get_local_time($item['start_date']);
3466
                $item['start_date_tms'] = api_strtotime($item['start_date']);
3467
            }
3468
            if (!empty($item['end_date'])) {
3469
                $item['end_date'] = api_get_local_time($item['end_date']);
3470
            }
3471
3472
            // we break the date field in the database into a date and a time part
3473
            $agenda_db_date = explode(" ", $item['start_date']);
3474
            $date = $agenda_db_date[0];
3475
            $time = $agenda_db_date[1];
3476
            // we divide the date part into a day, a month and a year
3477
            $agendadate = explode("-", $date);
3478
            $year = intval($agendadate[0]);
3479
            $month = intval($agendadate[1]);
3480
            $day = intval($agendadate[2]);
3481
            // we divide the time part into hour, minutes, seconds
3482
            $agendatime = explode(":", $time);
3483
            $hour = $agendatime[0];
3484
            $minute = $agendatime[1];
3485
            $second = $agendatime[2];
3486
3487
            if ($type == 'month_view') {
3488
                $item['calendar_type'] = 'global';
3489
                $agendaitems[$day][] = $item;
3490
                continue;
3491
            }
3492
3493
            $start_time = api_format_date(
3494
                $item['start_date'],
3495
                TIME_NO_SEC_FORMAT
3496
            );
3497
            $end_time = '';
3498 View Code Duplication
            if (!empty($item['end_date'])) {
3499
                $end_time = ' - '.api_format_date(
3500
                        $item['end_date'],
3501
                        DATE_TIME_FORMAT_LONG
3502
                    );
3503
            }
3504
3505
            // if the student has specified a course we a add a link to that course
3506 View Code Duplication
            if ($item['course'] <> "") {
3507
                $url = api_get_path(
3508
                        WEB_CODE_PATH
3509
                    )."admin/agenda.php?cidReq=".urlencode(
3510
                        $item['course']
3511
                    )."&day=$day&month=$month&year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
3512
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
3513
            } else {
3514
                $course_link = "";
3515
            }
3516
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3517
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3518
            if ($type !== "day_view") {
3519
                // This is the array construction for the WEEK or MONTH view
3520
                //Display the Agenda global in the tab agenda (administrator)
3521
                $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
3522
                $agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
3523
                $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
3524
            } else {
3525
                // this is the array construction for the DAY view
3526
                $halfhour = 2 * $agendatime['0'];
3527
                if ($agendatime['1'] >= '30') {
3528
                    $halfhour = $halfhour + 1;
3529
                }
3530
                if (!is_array($agendaitems[$halfhour])) {
3531
                    $content = $agendaitems[$halfhour];
3532
                }
3533
                $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
3534
                        'GlobalEvent'
3535
                    ).":  </b>".$item['title']."</div>";
3536
            }
3537
        }
3538
3539
        return $agendaitems;
3540
    }
3541
3542
    /**
3543
     * This function retrieves all the personal agenda items and add them to the agenda items found by the other functions.
3544
     */
3545
    public static function get_personal_agenda_items(
3546
        $user_id,
3547
        $agendaitems,
3548
        $day = "",
3549
        $month = "",
3550
        $year = "",
3551
        $week = "",
3552
        $type
3553
    ) {
3554
        $tbl_personal_agenda = Database:: get_main_table(TABLE_PERSONAL_AGENDA);
3555
        $user_id = intval($user_id);
3556
3557
        // 1. creating the SQL statement for getting the personal agenda items in MONTH view
3558
        if ($type == "month_view" or $type == "") {
3559
            // we are in month view
3560
            $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."'  ORDER BY date ASC";
3561
        }
3562
3563
        // 2. creating the SQL statement for getting the personal agenda items in WEEK view
3564
        // we are in week view
3565 View Code Duplication
        if ($type == "week_view") {
3566
            $start_end_day_of_week = self::calculate_start_end_of_week(
3567
                $week,
3568
                $year
3569
            );
3570
            $start_day = $start_end_day_of_week['start']['day'];
3571
            $start_month = $start_end_day_of_week['start']['month'];
3572
            $start_year = $start_end_day_of_week['start']['year'];
3573
            $end_day = $start_end_day_of_week['end']['day'];
3574
            $end_month = $start_end_day_of_week['end']['month'];
3575
            $end_year = $start_end_day_of_week['end']['year'];
3576
            // in sql statements you have to use year-month-day for date calculations
3577
            $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
3578
            $start_filter = api_get_utc_datetime($start_filter);
3579
            $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
3580
            $end_filter = api_get_utc_datetime($end_filter);
3581
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3582
        }
3583
        // 3. creating the SQL statement for getting the personal agenda items in DAY view
3584 View Code Duplication
        if ($type == "day_view") {
3585
            // we are in day view
3586
            // we could use mysql date() function but this is only available from 4.1 and higher
3587
            $start_filter = $year."-".$month."-".$day." 00:00:00";
3588
            $start_filter = api_get_utc_datetime($start_filter);
3589
            $end_filter = $year."-".$month."-".$day." 23:59:59";
3590
            $end_filter = api_get_utc_datetime($end_filter);
3591
            $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
3592
        }
3593
3594
        $result = Database::query($sql);
3595
        while ($item = Database::fetch_array($result, 'ASSOC')) {
3596
3597
            $time_minute = api_convert_and_format_date(
3598
                $item['date'],
3599
                TIME_NO_SEC_FORMAT
3600
            );
3601
            $item['date'] = api_get_local_time($item['date']);
3602
            $item['start_date_tms'] = api_strtotime($item['date']);
3603
            $item['content'] = $item['text'];
3604
3605
            // we break the date field in the database into a date and a time part
3606
            $agenda_db_date = explode(" ", $item['date']);
3607
            $date = $agenda_db_date[0];
3608
            $time = $agenda_db_date[1];
3609
            // we divide the date part into a day, a month and a year
3610
            $agendadate = explode("-", $item['date']);
3611
            $year = intval($agendadate[0]);
3612
            $month = intval($agendadate[1]);
3613
            $day = intval($agendadate[2]);
3614
            // we divide the time part into hour, minutes, seconds
3615
            $agendatime = explode(":", $time);
3616
3617
            $hour = $agendatime[0];
3618
            $minute = $agendatime[1];
3619
            $second = $agendatime[2];
3620
3621
            if ($type == 'month_view') {
3622
                $item['calendar_type'] = 'personal';
3623
                $item['start_date'] = $item['date'];
3624
                $agendaitems[$day][] = $item;
3625
                continue;
3626
            }
3627
3628
            // if the student has specified a course we a add a link to that course
3629 View Code Duplication
            if ($item['course'] <> "") {
3630
                $url = api_get_path(
3631
                        WEB_CODE_PATH
3632
                    )."calendar/agenda.php?cidReq=".urlencode(
3633
                        $item['course']
3634
                    )."&day=$day&month=$month&year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
3635
                $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
3636
            } else {
3637
                $course_link = "";
3638
            }
3639
            // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
3640
            // if we have a day_view we use a half hour as index => key 33 = 16h30
3641
            if ($type !== "day_view") {
3642
                // This is the array construction for the WEEK or MONTH view
3643
3644
                //Display events in agenda
3645
                $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 />";
3646
3647
            } else {
3648
                // this is the array construction for the DAY view
3649
                $halfhour = 2 * $agendatime['0'];
3650
                if ($agendatime['1'] >= '30') {
3651
                    $halfhour = $halfhour + 1;
3652
                }
3653
3654
                //Display events by list
3655
                $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>";
3656
            }
3657
        }
3658
3659
        return $agendaitems;
3660
    }
3661
3662
3663
    /**
3664
     * Show the monthcalender of the given month
3665
     * @param    array    Agendaitems
3666
     * @param    int    Month number
3667
     * @param    int    Year number
3668
     * @param    array    Array of strings containing long week day names (deprecated, you can send an empty array instead)
3669
     * @param    string    The month name
3670
     * @return    void    Direct output
3671
     */
3672
    public static function display_mymonthcalendar(
3673
        $user_id,
3674
        $agendaitems,
3675
        $month,
3676
        $year,
3677
        $weekdaynames = array(),
3678
        $monthName,
3679
        $show_content = true
3680
    ) {
3681
        global $DaysShort, $course_path;
3682
        //Handle leap year
3683
        $numberofdays = array(
3684
            0,
3685
            31,
3686
            28,
3687
            31,
3688
            30,
3689
            31,
3690
            30,
3691
            31,
3692
            31,
3693
            30,
3694
            31,
3695
            30,
3696
            31
3697
        );
3698 View Code Duplication
        if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0)) {
3699
            $numberofdays[2] = 29;
3700
        }
3701
        //Get the first day of the month
3702
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
3703
        //Start the week on monday
3704
        $startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
3705
        $g_cc = (isset($_GET['courseCode']) ? $_GET['courseCode'] : '');
3706
3707
        $next_month = ($month == 1 ? 12 : $month - 1);
3708
        $prev_month = ($month == 12 ? 1 : $month + 1);
3709
3710
        $next_year = ($month == 1 ? $year - 1 : $year);
3711
        $prev_year = ($month == 12 ? $year + 1 : $year);
3712
3713
        if ($show_content) {
3714
            $back_url = Display::url(
3715
                get_lang('Previous'),
3716
                api_get_self()."?coursePath=".urlencode(
3717
                    $course_path
3718
                )."&courseCode=".Security::remove_XSS(
3719
                    $g_cc
3720
                )."&action=view&view=month&month=".$next_month."&year=".$next_year
3721
            );
3722
            $next_url = Display::url(
3723
                get_lang('Next'),
3724
                api_get_self()."?coursePath=".urlencode(
3725
                    $course_path
3726
                )."&courseCode=".Security::remove_XSS(
3727
                    $g_cc
3728
                )."&action=view&view=month&month=".$prev_month."&year=".$prev_year
3729
            );
3730
        } else {
3731
            $back_url = Display::url(
3732
                get_lang('Previous'),
3733
                '',
3734
                array(
3735
                    'onclick' => "load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ",
3736
                    'class' => 'btn ui-button ui-widget ui-state-default'
3737
                )
3738
            );
3739
            $next_url = Display::url(
3740
                get_lang('Next'),
3741
                '',
3742
                array(
3743
                    'onclick' => "load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ",
3744
                    'class' => 'pull-right btn ui-button ui-widget ui-state-default'
3745
                )
3746
            );
3747
        }
3748
        $html = '';
3749
        $html .= '<div class="actions">';
3750
        $html .= '<div class="row">';
3751
        $html .= '<div class="col-md-4">'.$back_url.'</div>';
3752
        $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
3753
        $html .= '<div class="col-md-4">'.$next_url.'</div>';
3754
        $html .= '</div>';
3755
        $html .= '</div>';
3756
        $html .= '<table id="agenda_list2" class="table table-bordered">';
3757
        $html .= '<tr>';
3758 View Code Duplication
        for ($ii = 1; $ii < 8; $ii++) {
3759
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
3760
        }
3761
        $html .= '</tr>';
3762
3763
        $curday = -1;
3764
        $today = getdate();
3765
        while ($curday <= $numberofdays[$month]) {
3766
            $html .= "<tr>";
3767
            for ($ii = 0; $ii < 7; $ii++) {
3768
                if (($curday == -1) && ($ii == $startdayofweek)) {
3769
                    $curday = 1;
3770
                }
3771
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
3772
                    $bgcolor = $class = 'class="days_week"';
3773
                    $dayheader = Display::div(
3774
                        $curday,
3775
                        array('class' => 'agenda_day')
3776
                    );
3777 View Code Duplication
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
3778
                        $class = "class=\"days_today\" style=\"width:10%;\"";
3779
                    }
3780
3781
                    $html .= "<td ".$class.">".$dayheader;
3782
3783
                    if (!empty($agendaitems[$curday])) {
3784
                        $items = $agendaitems[$curday];
3785
                        $items = msort($items, 'start_date_tms');
3786
3787
                        foreach ($items as $value) {
3788
                            $value['title'] = Security::remove_XSS(
3789
                                $value['title']
3790
                            );
3791
                            $start_time = api_format_date(
3792
                                $value['start_date'],
3793
                                TIME_NO_SEC_FORMAT
3794
                            );
3795
                            $end_time = '';
3796
3797 View Code Duplication
                            if (!empty($value['end_date'])) {
3798
                                $end_time = '-&nbsp;<i>'.api_format_date(
3799
                                        $value['end_date'],
3800
                                        DATE_TIME_FORMAT_LONG
3801
                                    ).'</i>';
3802
                            }
3803
                            $complete_time = '<i>'.api_format_date(
3804
                                    $value['start_date'],
3805
                                    DATE_TIME_FORMAT_LONG
3806
                                ).'</i>&nbsp;'.$end_time;
3807
                            $time = '<i>'.$start_time.'</i>';
3808
3809
                            switch ($value['calendar_type']) {
3810
                                case 'personal':
3811
                                    $bg_color = '#D0E7F4';
3812
                                    $icon = Display::return_icon(
3813
                                        'user.png',
3814
                                        get_lang('MyAgenda'),
3815
                                        array(),
3816
                                        ICON_SIZE_SMALL
3817
                                    );
3818
                                    break;
3819
                                case 'global':
3820
                                    $bg_color = '#FFBC89';
3821
                                    $icon = Display::return_icon(
3822
                                        'view_remove.png',
3823
                                        get_lang('GlobalEvent'),
3824
                                        array(),
3825
                                        ICON_SIZE_SMALL
3826
                                    );
3827
                                    break;
3828
                                case 'course':
3829
                                    $bg_color = '#CAFFAA';
3830
                                    $icon_name = 'course.png';
3831
                                    if (!empty($value['session_id'])) {
3832
                                        $icon_name = 'session.png';
3833
                                    }
3834
                                    if ($show_content) {
3835
                                        $icon = Display::url(
3836
                                            Display::return_icon(
3837
                                                $icon_name,
3838
                                                $value['course_name'].' '.get_lang(
3839
                                                    'Course'
3840
                                                ),
3841
                                                array(),
3842
                                                ICON_SIZE_SMALL
3843
                                            ),
3844
                                            $value['url']
3845
                                        );
3846 View Code Duplication
                                    } else {
3847
                                        $icon = Display::return_icon(
3848
                                            $icon_name,
3849
                                            $value['course_name'].' '.get_lang(
3850
                                                'Course'
3851
                                            ),
3852
                                            array(),
3853
                                            ICON_SIZE_SMALL
3854
                                        );
3855
                                    }
3856
                                    break;
3857
                                default:
3858
                                    break;
3859
                            }
3860
3861
                            $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
3862
3863
                            if ($show_content) {
3864
3865
                                //Setting a personal event to green
3866
                                $icon = Display::div(
3867
                                    $icon,
3868
                                    array('style' => 'float:right')
3869
                                );
3870
3871
                                $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
3872
3873
                                //Link to bubble
3874
                                $url = Display::url(
3875
                                    cut($value['title'], 40),
3876
                                    '#',
3877
                                    array('id' => $link, 'class' => 'opener')
3878
                                );
3879
                                $result .= $time.' '.$icon.' '.Display::div(
3880
                                        $url
3881
                                    );
3882
3883
                                //Hidden content
3884
                                $content = Display::div(
3885
                                    $icon.Display::tag(
3886
                                        'h2',
3887
                                        $value['course_name']
3888
                                    ).'<hr />'.Display::tag(
3889
                                        'h3',
3890
                                        $value['title']
3891
                                    ).$complete_time.'<hr />'.Security::remove_XSS(
3892
                                        $value['content']
3893
                                    )
3894
                                );
3895
3896
                                //Main div
3897
                                $result .= Display::div(
3898
                                    $content,
3899
                                    array(
3900
                                        'id' => 'main_'.$link,
3901
                                        'class' => 'dialog',
3902
                                        'style' => 'display:none'
3903
                                    )
3904
                                );
3905
                                $result .= '</div>';
3906
                                $html .= $result;
3907
                                //echo Display::div($content, array('id'=>'main_'.$value['calendar_type'].'_'.$value['id'], 'class' => 'dialog'));
3908
                            } else {
3909
                                $html .= $result .= $icon.'</div>';
3910
                            }
3911
                        }
3912
                    }
3913
                    $html .= "</td>";
3914
                    $curday++;
3915
                } else {
3916
                    $html .= "<td></td>";
3917
                }
3918
            }
3919
            $html .= "</tr>";
3920
        }
3921
        $html .= "</table>";
3922
        echo $html;
3923
    }
3924
3925
    /**
3926
     * Get personal agenda items between two dates (=all events from all registered courses)
3927
     * @param    int        user ID of the user
3928
     * @param    string    Optional start date in datetime format (if no start date is given, uses today)
3929
     * @param    string    Optional end date in datetime format (if no date is given, uses one year from now)
3930
     * @param integer $user_id
3931
     * @return    array    Array of events ordered by start date, in
3932
     * [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
3933
     * where datestart and dateend are in yyyyMMddhhmmss format.
3934
     * @TODO Implement really personal events (from user DB) and global events (from main DB)
3935
     */
3936
    public static function get_personal_agenda_items_between_dates(
3937
        $user_id,
3938
        $date_start = '',
3939
        $date_end = ''
3940
    ) {
3941
        $items = array();
3942
        if ($user_id != strval(intval($user_id))) {
3943
            return $items;
3944
        }
3945
        if (empty($date_start)) {
3946
            $date_start = date('Y-m-d H:i:s');
3947
        }
3948
        if (empty($date_end)) {
3949
            $date_end = date(
3950
                'Y-m-d H:i:s',
3951
                mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1)
3952
            );
3953
        }
3954
        $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
3955
        if (!preg_match($expr, $date_start)) {
3956
            return $items;
3957
        }
3958
        if (!preg_match($expr, $date_end)) {
3959
            return $items;
3960
        }
3961
3962
        // get agenda-items for every course
3963
        $courses = api_get_user_courses($user_id, false);
3964
        foreach ($courses as $id => $course) {
3965
            $c = api_get_course_info_by_id($course['real_id']);
3966
            //databases of the courses
3967
            $t_a = Database:: get_course_table(TABLE_AGENDA, $course['db']);
3968
            $t_ip = Database:: get_course_table(
3969
                TABLE_ITEM_PROPERTY,
3970
                $course['db']
3971
            );
3972
            // get the groups to which the user belong
3973
            $group_memberships = GroupManager:: get_group_ids(
3974
                $course['db'],
3975
                $user_id
3976
            );
3977
            // if the user is administrator of that course we show all the agenda items
3978
            if ($course['status'] == '1') {
3979
                //echo "course admin";
3980
                $sqlquery = "SELECT ".
3981
                    " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
3982
                    " FROM ".$t_a." agenda, ".
3983
                    $t_ip." ip ".
3984
                    " WHERE agenda.id = ip.ref ".
3985
                    " AND agenda.start_date>='$date_start' ".
3986
                    " AND agenda.end_date<='$date_end' ".
3987
                    " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
3988
                    " AND ip.visibility='1' ".
3989
                    " GROUP BY agenda.id ".
3990
                    " ORDER BY start_date ";
3991
            } else {
3992
                // if the user is not an administrator of that course, then...
3993
                if (is_array($group_memberships) && count(
3994
                        $group_memberships
3995
                    ) > 0
3996
                ) {
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 IS NULL OR ip.to_group_id IN (0, ".implode(
4006
                            ", ",
4007
                            $group_memberships
4008
                        ).")) ) ".
4009
                        " AND ip.visibility='1' ".
4010
                        " ORDER BY start_date ";
4011
                } else {
4012
                    $sqlquery = "SELECT ".
4013
                        "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
4014
                        " FROM ".$t_a." agenda, ".
4015
                        $t_ip." ip ".
4016
                        " WHERE agenda.id = ip.ref ".
4017
                        " AND agenda.start_date>='$date_start' ".
4018
                        " AND agenda.end_date<='$date_end' ".
4019
                        " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
4020
                        " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
4021
                        " AND ip.visibility='1' ".
4022
                        " ORDER BY start_date ";
4023
                }
4024
            }
4025
4026
            $result = Database::query($sqlquery);
4027
            while ($item = Database::fetch_array($result)) {
4028
                $agendaday = date("j", strtotime($item['start_date']));
4029
                $month = date("n", strtotime($item['start_date']));
4030
                $year = date("Y", strtotime($item['start_date']));
4031
                $URL = api_get_path(
4032
                        WEB_PATH
4033
                    )."main/calendar/agenda.php?cidReq=".urlencode(
4034
                        $course["code"]
4035
                    )."&day=$agendaday&month=$month&year=$year#$agendaday";
4036
                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...
4037
                    '[-: ]',
4038
                    $item['start_date']
4039
                );
4040
                $start_date = $year.$month.$day.$hour.$min;
4041
                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...
4042
                    '[-: ]',
4043
                    $item['end_date']
4044
                );
4045
                $end_date = $year.$month.$day.$hour.$min;
4046
4047
                $items[] = array(
4048
                    'datestart' => $start_date,
4049
                    'dateend' => $end_date,
4050
                    'title' => $item['title'],
4051
                    'link' => $URL,
4052
                    'coursetitle' => $c['name'],
4053
                );
4054
            }
4055
        }
4056
4057
        return $items;
4058
    }
4059
4060
    /**
4061
     * This function retrieves one personal agenda item returns it.
4062
     * @param    int $id The agenda item ID
4063
     * @return    array    The results of the database query, or null if not found
4064
     */
4065 View Code Duplication
    public static function get_personal_agenda_item($id)
4066
    {
4067
        $tbl_personal_agenda = Database:: get_main_table(TABLE_PERSONAL_AGENDA);
4068
        $id = intval($id);
4069
        // make sure events of the personal agenda can only be seen by the user himself
4070
        $user = api_get_user_id();
4071
        $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE id=".$id." AND user = ".$user;
4072
        $result = Database::query($sql);
4073
        if (Database::num_rows($result) == 1) {
4074
            $item = Database::fetch_array($result);
4075
        } else {
4076
            $item = null;
4077
        }
4078
4079
        return $item;
4080
    }
4081
4082
    /**
4083
     * This function calculates the startdate of the week (monday)
4084
     * and the enddate of the week (sunday)
4085
     * and returns it as an array
4086
     */
4087
    public static function calculate_start_end_of_week($week_number, $year)
4088
    {
4089
        // determine the start and end date
4090
        // step 1: we calculate a timestamp for a day in this week
4091
        $random_day_in_week = mktime(
4092
                0,
4093
                0,
4094
                0,
4095
                1,
4096
                1,
4097
                $year
4098
            ) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
4099
        // step 2: we which day this is (0=sunday, 1=monday, ...)
4100
        $number_day_in_week = date('w', $random_day_in_week);
4101
        // step 3: we calculate the timestamp of the monday of the week we are in
4102
        $start_timestamp = $random_day_in_week - (($number_day_in_week - 1) * 24 * 60 * 60);
4103
        // step 4: we calculate the timestamp of the sunday of the week we are in
4104
        $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week + 1) * 24 * 60 * 60) - 3600;
4105
        // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
4106
        $start_day = date('j', $start_timestamp);
4107
        $start_month = date('n', $start_timestamp);
4108
        $start_year = date('Y', $start_timestamp);
4109
        $end_day = date('j', $end_timestamp);
4110
        $end_month = date('n', $end_timestamp);
4111
        $end_year = date('Y', $end_timestamp);
4112
        $start_end_array['start']['day'] = $start_day;
4113
        $start_end_array['start']['month'] = $start_month;
4114
        $start_end_array['start']['year'] = $start_year;
4115
        $start_end_array['end']['day'] = $end_day;
4116
        $start_end_array['end']['month'] = $end_month;
4117
        $start_end_array['end']['year'] = $end_year;
4118
4119
        return $start_end_array;
4120
    }
4121
4122
    /**
4123
     * @return bool
4124
     */
4125
    public function getIsAllowedToEdit()
4126
    {
4127
        return $this->isAllowedToEdit;
4128
    }
4129
4130
    /**
4131
     * @param bool $isAllowedToEdit
4132
     */
4133
    public function setIsAllowedToEdit($isAllowedToEdit)
4134
    {
4135
        $this->isAllowedToEdit = $isAllowedToEdit;
4136
    }
4137
4138
    /**
4139
     * @param int $userId
4140
     * @param array $event
4141
     *
4142
     * @return bool
4143
     */
4144
    public function sendEmail($userId, $event)
4145
    {
4146
        $userInfo = api_get_user_info($userId);
4147
4148
        if (!empty($this->sessionInfo)) {
4149
            $courseTitle = $this->course['name'].' ('.$this->sessionInfo['title'].')';
4150
        } else {
4151
            $courseTitle = $this->course['name'];
4152
        }
4153
4154
4155
4156
        api_mail_html(
4157
            $userInfo['complete_name'],
4158
            $userInfo['mail'],
4159
            $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...
4160
            $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...
4161
        );
4162
4163
        return true;
4164
    }
4165
}
4166