AnnouncementManager   F
last analyzed

Complexity

Total Complexity 268

Size/Duplication

Total Lines 2262
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 268
eloc 1162
dl 0
loc 2262
rs 0.952
c 0
b 0
f 0

30 Methods

Rating   Name   Duplication   Size   Complexity  
B edit_announcement_attachment_file() 0 58 5
A add_announcement_attachment_file() 0 53 5
A get_course_groups() 0 18 2
A get_by_id() 0 30 3
B sent_to() 0 38 6
C loadEditUsers() 0 53 16
A get_attachment() 0 15 2
F sent_to_form() 0 80 21
A delete_announcement_attachment_file() 0 13 3
A __construct() 0 2 1
C addGroupAnnouncement() 0 98 11
A getLastAnnouncementOrder() 0 24 4
B getAnnouncementInfoById() 0 85 8
A delete_all_announcements() 0 14 3
A addAnnouncementToAllUsersInSessions() 0 27 5
A createEvent() 0 34 2
A update_mail_sent() 0 12 2
A getAnnoucementCourseTotalByUser() 0 39 5
D getNumberAnnouncements() 0 171 17
A delete_announcement() 0 8 1
A get_all_annoucement_by_course() 0 33 3
A sendEmail() 0 14 1
C displayAnnouncement() 0 118 14
A getAnnouncementsByTitle() 0 29 1
A change_visibility_announcement() 0 28 2
F getAnnouncements() 0 488 70
C edit_announcement() 0 120 14
D add_announcement() 0 129 19
F parseContent() 0 87 17
A getTags() 0 35 5

How to fix   Complexity   

Complex Class

Complex classes like AnnouncementManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AnnouncementManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
5
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
6
use Chamilo\CourseBundle\Entity\CAnnouncement;
7
use Chamilo\CourseBundle\Entity\CCalendarEvent;
8
use Chamilo\CourseBundle\Entity\CItemProperty;
9
10
/**
11
 * Include file with functions for the announcements module.
12
 *
13
 * @author jmontoya
14
 *
15
 * @package chamilo.announcements
16
 *
17
 * @todo use OOP
18
 */
19
class AnnouncementManager
20
{
21
    /**
22
     * Constructor.
23
     */
24
    public function __construct()
25
    {
26
    }
27
28
    /**
29
     * @return array
30
     */
31
    public static function getTags(array $excluded = [])
32
    {
33
        $tags = [
34
            '((user_name))',
35
            '((user_email))',
36
            '((user_firstname))',
37
            '((user_lastname))',
38
            '((user_picture))',
39
            '((user_complete_name))',
40
            '((user_official_code))',
41
            '((course_title))',
42
            '((course_link))',
43
        ];
44
45
        $tags[] = '((teachers))';
46
47
        $extraField = new ExtraField('user');
48
        $extraFields = $extraField->get_all(['filter = ?' => 1]);
49
        if (!empty($extraFields)) {
50
            foreach ($extraFields as $extra) {
51
                $tags[] = "((extra_".$extra['variable']."))";
52
            }
53
        }
54
        $sessionId = api_get_session_id();
55
        if (!empty($sessionId)) {
56
            $tags[] = '((coaches))';
57
            $tags[] = '((general_coach))';
58
            $tags[] = '((general_coach_email))';
59
        }
60
61
        if ($excluded) {
62
            return array_diff($tags, $excluded);
63
        }
64
65
        return $tags;
66
    }
67
68
    /**
69
     * @param int    $userId
70
     * @param string $content
71
     * @param string $courseCode
72
     * @param int    $sessionId
73
     *
74
     * @return string
75
     */
76
    public static function parseContent(
77
        $userId,
78
        $content,
79
        $courseCode = '',
80
        $sessionId = 0
81
    ) {
82
        $readerInfo = api_get_user_info($userId, false, false, true, true, false, true);
83
        $courseInfo = $courseCode ? api_get_course_info($courseCode) : [];
84
        $teacherList = '';
85
        if ($courseInfo) {
86
            $teacherList = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code']);
87
        }
88
        $generalCoachName = '';
89
        $generalCoachEmail = '';
90
        $coaches = '';
91
        if (!empty($sessionId)) {
92
            $sessionInfo = api_get_session_info($sessionId);
93
            $coaches = $courseInfo
94
                ? CourseManager::get_coachs_from_course_to_string($sessionId, $courseInfo['real_id'])
95
                : '';
96
97
            $generalCoach = api_get_user_info($sessionInfo['id_coach']);
98
            $generalCoachName = $generalCoach['complete_name'];
99
            $generalCoachEmail = $generalCoach['email'];
100
        }
101
102
        $data = [];
103
        $data['user_name'] = '';
104
        $data['user_firstname'] = '';
105
        $data['user_lastname'] = '';
106
        $data['user_complete_name'] = '';
107
        $data['user_official_code'] = '';
108
        $data['user_email'] = '';
109
        if (!empty($readerInfo)) {
110
            $data['user_name'] = $readerInfo['username'];
111
            $data['user_email'] = $readerInfo['email'];
112
            $data['user_firstname'] = $readerInfo['firstname'];
113
            $data['user_lastname'] = $readerInfo['lastname'];
114
            $data['user_official_code'] = $readerInfo['official_code'];
115
            $data['user_complete_name'] = $readerInfo['complete_name'];
116
        }
117
118
        $data['user_picture'] = UserManager::getUserPicture($userId, USER_IMAGE_SIZE_ORIGINAL);
119
        $data['course_title'] = $courseInfo['name'] ?? '';
120
        $courseLink = $courseCode ? api_get_course_url($courseCode, $sessionId) : '';
121
        $data['course_link'] = Display::url($courseLink, $courseLink);
122
        $data['teachers'] = $teacherList;
123
124
        if (!empty($readerInfo)) {
125
            $extraField = new ExtraField('user');
126
            $extraFields = $extraField->get_all(['filter = ?' => 1]);
127
            if (!empty($extraFields)) {
128
                foreach ($extraFields as $extra) {
129
                    $data['extra_'.$extra['variable']] = '';
130
                }
131
            }
132
133
            if (!empty($readerInfo['extra'])) {
134
                foreach ($readerInfo['extra'] as $extra) {
135
                    if (isset($extra['value'])) {
136
                        /** @var \Chamilo\CoreBundle\Entity\ExtraFieldValues $value */
137
                        $value = $extra['value'];
138
                        if ($value instanceof ExtraFieldValues) {
139
                            $field = $value->getField();
140
                            if ($field instanceof ExtraFieldEntity) {
141
                                $data['extra_'.$field->getVariable()] = $value->getValue();
142
                            }
143
                        }
144
                    }
145
                }
146
            }
147
        }
148
149
        if (!empty($sessionId)) {
150
            $data['coaches'] = $coaches;
151
            $data['general_coach'] = $generalCoachName;
152
            $data['general_coach_email'] = $generalCoachEmail;
153
        }
154
155
        $tags = self::getTags();
156
        foreach ($tags as $tag) {
157
            $simpleTag = str_replace(['((', '))'], '', $tag);
158
            $value = $data[$simpleTag] ?? '';
159
            $content = str_replace($tag, $value, $content);
160
        }
161
162
        return $content;
163
    }
164
165
    /**
166
     * Gets all announcements from a course.
167
     *
168
     * @param array $course_info
169
     * @param int   $session_id
170
     *
171
     * @return array html with the content and count of announcements or false otherwise
172
     */
173
    public static function get_all_annoucement_by_course($course_info, $session_id = 0)
174
    {
175
        $session_id = (int) $session_id;
176
        $courseId = $course_info['real_id'];
177
178
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
179
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
180
181
        $sql = "SELECT DISTINCT
182
                    announcement.id,
183
                    announcement.title,
184
                    announcement.content
185
				FROM $tbl_announcement announcement
186
				INNER JOIN $tbl_item_property i
187
				ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
188
				WHERE
189
                    i.tool='announcement' AND
190
                    announcement.session_id  = '$session_id' AND
191
                    announcement.c_id = $courseId AND
192
                    i.c_id = $courseId
193
				ORDER BY display_order DESC";
194
        $rs = Database::query($sql);
195
        $num_rows = Database::num_rows($rs);
196
        if ($num_rows > 0) {
197
            $list = [];
198
            while ($row = Database::fetch_array($rs)) {
199
                $list[] = $row;
200
            }
201
202
            return $list;
203
        }
204
205
        return false;
206
    }
207
208
    /**
209
     * This functions switches the visibility a course resource
210
     * using the visibility field in 'item_property'.
211
     *
212
     * @param array $courseInfo
213
     * @param int   $id         ID of the element of the corresponding type
214
     *
215
     * @return bool False on failure, True on success
216
     */
217
    public static function change_visibility_announcement($courseInfo, $id)
218
    {
219
        $session_id = api_get_session_id();
220
        $item_visibility = api_get_item_visibility(
221
            $courseInfo,
222
            TOOL_ANNOUNCEMENT,
223
            $id,
224
            $session_id
225
        );
226
        if ($item_visibility == '1') {
227
            api_item_property_update(
228
                $courseInfo,
229
                TOOL_ANNOUNCEMENT,
230
                $id,
231
                'invisible',
232
                api_get_user_id()
233
            );
234
        } else {
235
            api_item_property_update(
236
                $courseInfo,
237
                TOOL_ANNOUNCEMENT,
238
                $id,
239
                'visible',
240
                api_get_user_id()
241
            );
242
        }
243
244
        return true;
245
    }
246
247
    /**
248
     * Deletes an announcement.
249
     *
250
     * @param array $courseInfo the course array
251
     * @param int   $id         the announcement id
252
     */
253
    public static function delete_announcement($courseInfo, $id)
254
    {
255
        api_item_property_update(
256
            $courseInfo,
257
            TOOL_ANNOUNCEMENT,
258
            $id,
259
            'delete',
260
            api_get_user_id()
261
        );
262
    }
263
264
    /**
265
     * Deletes all announcements by course.
266
     *
267
     * @param array $courseInfo the course array
268
     */
269
    public static function delete_all_announcements($courseInfo)
270
    {
271
        $announcements = self::get_all_annoucement_by_course(
272
            $courseInfo,
273
            api_get_session_id()
274
        );
275
        if (!empty($announcements)) {
276
            foreach ($announcements as $annon) {
277
                api_item_property_update(
278
                    $courseInfo,
279
                    TOOL_ANNOUNCEMENT,
280
                    $annon['id'],
281
                    'delete',
282
                    api_get_user_id()
283
                );
284
            }
285
        }
286
    }
287
288
    /**
289
     * @param string $title
290
     * @param int    $courseId
291
     * @param int    $sessionId
292
     * @param int    $visibility 1 or 0
293
     *
294
     * @return mixed
295
     */
296
    public static function getAnnouncementsByTitle(
297
        $title,
298
        $courseId,
299
        $sessionId = 0,
300
        $visibility = 1
301
    ) {
302
        $dql = "SELECT a
303
                FROM ChamiloCourseBundle:CAnnouncement a
304
                JOIN ChamiloCourseBundle:CItemProperty ip
305
                WITH a.id = ip.ref AND a.cId = ip.course
306
                WHERE
307
                    ip.tool = 'announcement' AND
308
                    a.cId = :course AND
309
                    a.sessionId = :session AND
310
                    a.title like :title AND
311
                    ip.visibility = :visibility
312
                ORDER BY a.displayOrder DESC";
313
314
        $qb = Database::getManager()->createQuery($dql);
315
        $result = $qb->execute(
316
            [
317
                'course' => $courseId,
318
                'session' => $sessionId,
319
                'visibility' => $visibility,
320
                'title' => "%$title%",
321
            ]
322
        );
323
324
        return $result;
325
    }
326
327
    /**
328
     * @param int $announcementId
329
     * @param int $courseId
330
     * @param int $userId
331
     * @param int $groupId
332
     *
333
     * @return array
334
     */
335
    public static function getAnnouncementInfoById(
336
        $announcementId,
337
        $courseId,
338
        $userId,
339
        $groupId = 0
340
    ) {
341
        $announcementId = (int) $announcementId;
342
        $courseId = (int) $courseId;
343
        $userId = (int) $userId;
344
        $groupId = (int) $groupId;
345
346
        if (api_is_allowed_to_edit(false, true) ||
347
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
348
        ) {
349
            $dql = "SELECT a, ip
350
                    FROM ChamiloCourseBundle:CAnnouncement a
351
                    JOIN ChamiloCourseBundle:CItemProperty ip
352
                    WITH a.id = ip.ref AND a.cId = ip.course
353
                    WHERE
354
                        a.id = :announcement AND
355
                        ip.tool = 'announcement' AND
356
                        a.cId = :course
357
                    ORDER BY a.displayOrder DESC";
358
        } else {
359
            $groupList[] = $groupId;
360
361
            if (api_get_user_id() != 0) {
362
                $extraGroupCondition = '';
363
                if (!empty($groupId)) {
364
                    $groupProperties = GroupManager::get_group_properties($groupId);
365
                    if ($groupProperties['announcements_state'] == GroupManager::TOOL_PRIVATE_BETWEEN_USERS) {
366
                        $extraGroupCondition = " AND (
367
                            ip.toUser = $userId AND ip.group = $groupId OR
368
                            (ip.group IN ('0') OR ip.group IS NULL) OR
369
                            (ip.group = $groupId AND (ip.toUser IS NULL OR ip.toUser = 0))
370
                        )";
371
                    }
372
                }
373
374
                $dql = "SELECT a, ip
375
                        FROM ChamiloCourseBundle:CAnnouncement a
376
                        JOIN ChamiloCourseBundle:CItemProperty ip
377
                        WITH a.id = ip.ref AND a.cId = ip.course
378
                        WHERE
379
                            a.id = :announcement AND
380
                            ip.tool='announcement' AND
381
                            (
382
                                ip.toUser = $userId OR
383
                                ip.group IN ('0', '".$groupId."') OR
384
                                ip.group IS NULL
385
                            ) AND
386
                            ip.visibility = '1' AND
387
                            ip.course = :course
388
                            $extraGroupCondition
389
                        ORDER BY a.displayOrder DESC";
390
            } else {
391
                $dql = "SELECT a, ip
392
                        FROM ChamiloCourseBundle:CAnnouncement a
393
                        JOIN ChamiloCourseBundle:CItemProperty ip
394
                        WITH a.id = ip.ref AND a.cId = ip.course
395
                        WHERE
396
                            a.id = :announcement AND
397
                            ip.tool = 'announcement' AND
398
                            (ip.group = '0' OR ip.group IS NULL) AND
399
                            ip.visibility = '1' AND
400
                            ip.course = :course";
401
            }
402
        }
403
404
        $qb = Database::getManager()->createQuery($dql);
405
        $result = $qb->execute(
406
            [
407
                'announcement' => $announcementId,
408
                'course' => $courseId,
409
            ]
410
        );
411
412
        if (!empty($result)) {
413
            return [
414
                'announcement' => $result[0],
415
                'item_property' => $result[1],
416
            ];
417
        }
418
419
        return [];
420
    }
421
422
    /**
423
     * Displays one specific announcement.
424
     *
425
     * @param int $id the id of the announcement you want to display
426
     *
427
     * @return string
428
     */
429
    public static function displayAnnouncement($id)
430
    {
431
        $id = (int) $id;
432
433
        if (empty($id)) {
434
            return '';
435
        }
436
437
        global $charset;
438
439
        $html = '';
440
        $result = self::getAnnouncementInfoById(
441
            $id,
442
            api_get_course_int_id(),
443
            api_get_user_id(),
444
            api_get_group_id()
445
        );
446
447
        if (empty($result)) {
448
            return '';
449
        }
450
451
        /** @var CAnnouncement $announcement */
452
        $announcement = $result['announcement'];
453
        /** @var CItemProperty $itemProperty */
454
        $itemProperty = $result['item_property'];
455
456
        if (empty($announcement) || empty($itemProperty)) {
457
            return '';
458
        }
459
460
        $title = Security::remove_XSS($announcement->getTitle());
461
        $content = $announcement->getContent();
462
463
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"table table-hover table-striped data_table\">";
464
        $html .= "<tr><td><h2>".$title."</h2></td></tr>";
465
466
        if (api_is_allowed_to_edit(false, true) ||
467
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
468
        ) {
469
            $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
470
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
471
472
            $image_visibility = 'invisible';
473
            $alt_visibility = get_lang('Visible');
474
            if ($itemProperty->getVisibility() === 1) {
475
                $image_visibility = 'visible';
476
                $alt_visibility = get_lang('Hide');
477
            }
478
            global $stok;
479
            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=showhide&id=".$id."&sec_token=".$stok."\">".
480
                Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
481
482
            if (api_is_allowed_to_edit(false, true)) {
483
                $modify_icons .= "<a
484
                    href=\"".api_get_self()."?".api_get_cidreq()."&action=delete&id=".$id."&sec_token=".$stok."\"
485
                    onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."')) return false;\">".
486
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
487
                    "</a>";
488
            }
489
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
490
        }
491
492
        // The user id is always the current one.
493
        $toUserId = api_get_user_id();
494
        $content = Security::remove_XSS(self::parseContent(
495
            $toUserId,
496
            $content,
497
            api_get_course_id(),
498
            api_get_session_id()
499
        ));
500
501
        $html .= "<tr><td>$content</td></tr>";
502
        $html .= "<tr>";
503
        $html .= "<td class=\"announcements_datum\">".get_lang('LastUpdateDate')." : ";
504
        $lastEdit = $itemProperty->getLasteditDate();
505
        $html .= Display::dateToStringAgoAndLongDate($lastEdit);
506
        $html .= "</td></tr>";
507
508
        $allow = !api_get_configuration_value('hide_announcement_sent_to_users_info');
509
        if ($allow && api_is_allowed_to_edit(false, true)) {
510
            $sent_to = self::sent_to('announcement', $id);
511
            $sentToForm = self::sent_to_form($sent_to);
512
            $html .= Display::tag(
513
                'td',
514
                get_lang('SentTo').': '.$sentToForm,
515
                ['class' => 'announcements_datum']
516
            );
517
        }
518
        $attachment_list = self::get_attachment($id);
519
520
        if (count($attachment_list) > 0) {
521
            $html .= "<tr><td>";
522
            $realname = $attachment_list['path'];
523
            $user_filename = $attachment_list['filename'];
524
            $full_file_name = 'download.php?'.api_get_cidreq().'&file='.$realname;
525
            $html .= '<br/>';
526
            $html .= Display::return_icon('attachment.gif', get_lang('Attachment'));
527
            $html .= '<a href="'.$full_file_name.' "> '.$user_filename.' </a>';
528
            $html .= ' - <span class="forum_attach_comment" >'.Security::remove_XSS($attachment_list['comment']).'</span>';
529
            if (api_is_allowed_to_edit(false, true)) {
530
                $url = api_get_self()."?".api_get_cidreq().
531
                    "&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok;
532
                $html .= Display::url(
533
                    Display::return_icon(
534
                        'delete.png',
535
                        get_lang('Delete'),
536
                        '',
537
                        16
538
                    ),
539
                    $url
540
                );
541
            }
542
            $html .= '</td></tr>';
543
        }
544
        $html .= '</table>';
545
546
        return $html;
547
    }
548
549
    /**
550
     * @param array $courseInfo
551
     *
552
     * @return int
553
     */
554
    public static function getLastAnnouncementOrder($courseInfo)
555
    {
556
        if (empty($courseInfo)) {
557
            return 0;
558
        }
559
560
        if (!isset($courseInfo['real_id'])) {
561
            return false;
562
        }
563
564
        $courseId = $courseInfo['real_id'];
565
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
566
        $sql = "SELECT MAX(display_order)
567
                FROM $table
568
                WHERE c_id = $courseId ";
569
        $result = Database::query($sql);
570
571
        $order = 0;
572
        if (Database::num_rows($result)) {
573
            $row = Database::fetch_array($result);
574
            $order = (int) $row[0] + 1;
575
        }
576
577
        return $order;
578
    }
579
580
    /**
581
     * Store an announcement in the database (including its attached file if any).
582
     *
583
     * @param array  $courseInfo
584
     * @param int    $sessionId
585
     * @param string $title                Announcement title (pure text)
586
     * @param string $newContent           Content of the announcement (can be HTML)
587
     * @param array  $sentTo               Array of users and groups to send the announcement to
588
     * @param array  $file                 uploaded file $_FILES
589
     * @param string $file_comment         Comment describing the attachment
590
     * @param string $end_date
591
     * @param bool   $sendToUsersInSession
592
     * @param int    $authorId
593
     *
594
     * @return int false on failure, ID of the announcement on success
595
     */
596
    public static function add_announcement(
597
        $courseInfo,
598
        $sessionId,
599
        $title,
600
        $newContent,
601
        $sentTo,
602
        $file = [],
603
        $file_comment = null,
604
        $end_date = null,
605
        $sendToUsersInSession = false,
606
        $authorId = 0
607
    ) {
608
        if (empty($courseInfo)) {
609
            return false;
610
        }
611
612
        if (!isset($courseInfo['real_id'])) {
613
            return false;
614
        }
615
616
        $courseId = $courseInfo['real_id'];
617
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
618
        $authorId = empty($authorId) ? api_get_user_id() : $authorId;
619
620
        if (empty($end_date)) {
621
            $end_date = api_get_utc_datetime();
622
        }
623
624
        $order = self::getLastAnnouncementOrder($courseInfo);
625
626
        // store in the table announcement
627
        $params = [
628
            'c_id' => $courseId,
629
            'content' => $newContent,
630
            'title' => $title,
631
            'end_date' => $end_date,
632
            'display_order' => $order,
633
            'session_id' => (int) $sessionId,
634
        ];
635
636
        $last_id = Database::insert($tbl_announcement, $params);
637
638
        if (empty($last_id)) {
639
            return false;
640
        } else {
641
            $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
642
            Database::query($sql);
643
644
            if (!empty($file)) {
645
                self::add_announcement_attachment_file(
646
                    $last_id,
647
                    $file_comment,
648
                    $_FILES['user_upload']
649
                );
650
            }
651
652
            // store in item_property (first the groups, then the users
653
            if (empty($sentTo) ||
654
                (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')
655
            ) {
656
                // The message is sent to EVERYONE, so we set the group to 0
657
                api_item_property_update(
658
                    $courseInfo,
659
                    TOOL_ANNOUNCEMENT,
660
                    $last_id,
661
                    'AnnouncementAdded',
662
                    $authorId,
663
                    '0',
664
                    null,
665
                    null,
666
                    null,
667
                    $sessionId
668
                );
669
            } else {
670
                $send_to = CourseManager::separateUsersGroups($sentTo);
671
                $batchSize = 20;
672
                $em = Database::getManager();
673
                // Storing the selected groups
674
                if (is_array($send_to['groups']) &&
675
                    !empty($send_to['groups'])
676
                ) {
677
                    $counter = 1;
678
                    foreach ($send_to['groups'] as $group) {
679
                        $groupInfo = GroupManager::get_group_properties($group);
680
                        api_item_property_update(
681
                            $courseInfo,
682
                            TOOL_ANNOUNCEMENT,
683
                            $last_id,
684
                            'AnnouncementAdded',
685
                            $authorId,
686
                            $groupInfo
687
                        );
688
689
                        if (($counter % $batchSize) === 0) {
690
                            $em->flush();
691
                            $em->clear();
692
                        }
693
                        $counter++;
694
                    }
695
                }
696
697
                // Storing the selected users
698
                if (is_array($send_to['users'])) {
699
                    $counter = 1;
700
                    foreach ($send_to['users'] as $user) {
701
                        api_item_property_update(
702
                            $courseInfo,
703
                            TOOL_ANNOUNCEMENT,
704
                            $last_id,
705
                            'AnnouncementAdded',
706
                            $authorId,
707
                            '',
708
                            $user
709
                        );
710
711
                        if (($counter % $batchSize) === 0) {
712
                            $em->flush();
713
                            $em->clear();
714
                        }
715
                        $counter++;
716
                    }
717
                }
718
            }
719
720
            if ($sendToUsersInSession) {
721
                self::addAnnouncementToAllUsersInSessions($last_id);
722
            }
723
724
            return $last_id;
725
        }
726
    }
727
728
    /**
729
     * @param string $title
730
     * @param string $newContent
731
     * @param int    $groupId
732
     * @param array  $to_users
733
     * @param array  $file
734
     * @param string $file_comment
735
     * @param bool   $sendToUsersInSession
736
     *
737
     * @return bool|int
738
     */
739
    public static function addGroupAnnouncement(
740
        $title,
741
        $newContent,
742
        $groupId,
743
        $to_users,
744
        $file = [],
745
        $file_comment = '',
746
        $sendToUsersInSession = false
747
    ) {
748
        $courseInfo = api_get_course_info();
749
750
        // Database definitions
751
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
752
        $order = self::getLastAnnouncementOrder($courseInfo);
753
754
        $now = api_get_utc_datetime();
755
        $courseId = api_get_course_int_id();
756
757
        // store in the table announcement
758
        $params = [
759
            'c_id' => $courseId,
760
            'content' => $newContent,
761
            'title' => $title,
762
            'end_date' => $now,
763
            'display_order' => $order,
764
            'session_id' => api_get_session_id(),
765
        ];
766
767
        $last_id = Database::insert($table, $params);
768
769
        // Store the attach file
770
        if ($last_id) {
771
            $sql = "UPDATE $table SET id = iid
772
                    WHERE iid = $last_id";
773
            Database::query($sql);
774
775
            if (!empty($file)) {
776
                self::add_announcement_attachment_file(
777
                    $last_id,
778
                    $file_comment,
779
                    $file
780
                );
781
            }
782
783
            $send_to_users = CourseManager::separateUsersGroups($to_users);
784
785
            // if nothing was selected in the menu then send to all the group
786
            $sentToAllGroup = false;
787
            if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
788
                $groupInfo = GroupManager::get_group_properties($groupId);
789
                api_item_property_update(
790
                    $courseInfo,
791
                    TOOL_ANNOUNCEMENT,
792
                    $last_id,
793
                    'AnnouncementAdded',
794
                    api_get_user_id(),
795
                    $groupInfo
796
                );
797
                $sentToAllGroup = true;
798
            }
799
800
            if ($sentToAllGroup === false) {
801
                if (!empty($send_to_users['groups'])) {
802
                    foreach ($send_to_users['groups'] as $group) {
803
                        $groupInfo = GroupManager::get_group_properties($group);
804
                        api_item_property_update(
805
                            $courseInfo,
806
                            TOOL_ANNOUNCEMENT,
807
                            $last_id,
808
                            'AnnouncementAdded',
809
                            api_get_user_id(),
810
                            $groupInfo
811
                        );
812
                    }
813
                }
814
815
                $groupInfo = GroupManager::get_group_properties($groupId);
816
                if (!empty($send_to_users['users'])) {
817
                    foreach ($send_to_users['users'] as $user) {
818
                        api_item_property_update(
819
                            $courseInfo,
820
                            TOOL_ANNOUNCEMENT,
821
                            $last_id,
822
                            'AnnouncementAdded',
823
                            api_get_user_id(),
824
                            $groupInfo,
825
                            $user
826
                        );
827
                    }
828
                }
829
            }
830
831
            if ($sendToUsersInSession) {
832
                self::addAnnouncementToAllUsersInSessions($last_id);
833
            }
834
        }
835
836
        return $last_id;
837
    }
838
839
    /**
840
     * This function stores the announcement item in the announcement table
841
     * and updates the item_property table.
842
     *
843
     * @param int    $id                   id of the announcement
844
     * @param string $title
845
     * @param string $newContent
846
     * @param array  $to                   users that will receive the announcement
847
     * @param mixed  $file                 attachment
848
     * @param string $file_comment         file comment
849
     * @param bool   $sendToUsersInSession
850
     */
851
    public static function edit_announcement(
852
        $id,
853
        $title,
854
        $newContent,
855
        $to,
856
        $file = [],
857
        $file_comment = '',
858
        $sendToUsersInSession = false
859
    ) {
860
        $courseInfo = api_get_course_info();
861
        $courseId = api_get_course_int_id();
862
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
863
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
864
        $id = (int) $id;
865
866
        $params = [
867
            'title' => $title,
868
            'content' => $newContent,
869
        ];
870
871
        Database::update(
872
            $table,
873
            $params,
874
            ['c_id = ? AND id = ?' => [$courseId, $id]]
875
        );
876
877
        // save attachment file
878
        $row_attach = self::get_attachment($id);
879
880
        $id_attach = 0;
881
        if ($row_attach) {
882
            $id_attach = (int) $row_attach['id'];
883
        }
884
885
        if (!empty($file)) {
886
            if (empty($id_attach)) {
887
                self::add_announcement_attachment_file(
888
                    $id,
889
                    $file_comment,
890
                    $file
891
                );
892
            } else {
893
                self::edit_announcement_attachment_file(
894
                    $id_attach,
895
                    $file,
896
                    $file_comment
897
                );
898
            }
899
        }
900
901
        // We remove everything from item_property for this
902
        $sql = "DELETE FROM $tbl_item_property
903
                WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
904
        Database::query($sql);
905
906
        if ($sendToUsersInSession) {
907
            self::addAnnouncementToAllUsersInSessions($id);
908
        }
909
910
        // store in item_property (first the groups, then the users
911
        if (!empty($to)) {
912
            // !is_null($to): when no user is selected we send it to everyone
913
            $send_to = CourseManager::separateUsersGroups($to);
914
915
            // storing the selected groups
916
            if (is_array($send_to['groups'])) {
917
                foreach ($send_to['groups'] as $group) {
918
                    $groupInfo = GroupManager::get_group_properties($group);
919
                    if (empty($groupInfo)) {
920
                        // Probably the group id and iid are different try checking the iid
921
                        $groupInfo = GroupManager::get_group_properties($group, true);
922
                    }
923
                    if ($groupInfo) {
924
                        api_item_property_update(
925
                            $courseInfo,
926
                            TOOL_ANNOUNCEMENT,
927
                            $id,
928
                            'AnnouncementUpdated',
929
                            api_get_user_id(),
930
                            $groupInfo
931
                        );
932
                    }
933
                }
934
            }
935
936
            // storing the selected users
937
            if (is_array($send_to['users'])) {
938
                foreach ($send_to['users'] as $user) {
939
                    api_item_property_update(
940
                        $courseInfo,
941
                        TOOL_ANNOUNCEMENT,
942
                        $id,
943
                        'AnnouncementUpdated',
944
                        api_get_user_id(),
945
                        0,
946
                        $user
947
                    );
948
                }
949
            }
950
951
            // Send to everyone
952
            if (isset($to[0]) && $to[0] === 'everyone') {
953
                api_item_property_update(
954
                    $courseInfo,
955
                    TOOL_ANNOUNCEMENT,
956
                    $id,
957
                    'AnnouncementUpdated',
958
                    api_get_user_id(),
959
                    0
960
                );
961
            }
962
        } else {
963
            // the message is sent to everyone, so we set the group to 0
964
            api_item_property_update(
965
                $courseInfo,
966
                TOOL_ANNOUNCEMENT,
967
                $id,
968
                'AnnouncementUpdated',
969
                api_get_user_id(),
970
                0
971
            );
972
        }
973
    }
974
975
    /**
976
     * @param int $announcementId
977
     */
978
    public static function addAnnouncementToAllUsersInSessions($announcementId)
979
    {
980
        $courseCode = api_get_course_id();
981
        $courseInfo = api_get_course_info();
982
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
983
984
        if (!empty($sessionList)) {
985
            foreach ($sessionList as $sessionInfo) {
986
                $sessionId = $sessionInfo['id'];
987
                $userList = CourseManager::get_user_list_from_course_code(
988
                    $courseCode,
989
                    $sessionId
990
                );
991
992
                if (!empty($userList)) {
993
                    foreach ($userList as $user) {
994
                        api_item_property_update(
995
                            $courseInfo,
996
                            TOOL_ANNOUNCEMENT,
997
                            $announcementId,
998
                            'AnnouncementUpdated',
999
                            api_get_user_id(),
1000
                            0,
1001
                            $user['user_id'],
1002
                            0,
1003
                            0,
1004
                            $sessionId
1005
                        );
1006
                    }
1007
                }
1008
            }
1009
        }
1010
    }
1011
1012
    /**
1013
     * @param int $insert_id
1014
     *
1015
     * @return bool
1016
     */
1017
    public static function update_mail_sent($insert_id)
1018
    {
1019
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1020
        if ($insert_id != strval(intval($insert_id))) {
1021
            return false;
1022
        }
1023
        $insert_id = intval($insert_id);
1024
        $courseId = api_get_course_int_id();
1025
        // store the modifications in the table tbl_annoucement
1026
        $sql = "UPDATE $table SET email_sent='1'
1027
                WHERE c_id = $courseId AND id = $insert_id";
1028
        Database::query($sql);
1029
    }
1030
1031
    /**
1032
     * @param int $user_id
1033
     *
1034
     * @return array|bool
1035
     */
1036
    public static function getAnnoucementCourseTotalByUser($user_id)
1037
    {
1038
        $user_id = (int) $user_id;
1039
1040
        if (empty($user_id)) {
1041
            return false;
1042
        }
1043
1044
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1045
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1046
1047
        $sql = "SELECT DISTINCT
1048
                    announcement.c_id,
1049
                    count(announcement.id) count
1050
                FROM $tbl_announcement announcement
1051
                INNER JOIN $tbl_item_property ip
1052
                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1053
                WHERE
1054
                    ip.tool='announcement' AND
1055
                    (
1056
                      ip.to_user_id = '$user_id' AND
1057
                      (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1058
                    )
1059
                    AND ip.visibility='1'
1060
                    AND announcement.session_id  = 0
1061
                GROUP BY announcement.c_id";
1062
        $rs = Database::query($sql);
1063
        $num_rows = Database::num_rows($rs);
1064
        $result = [];
1065
        if ($num_rows > 0) {
1066
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1067
                if (empty($row['c_id'])) {
1068
                    continue;
1069
                }
1070
                $result[] = ['course' => api_get_course_info_by_id($row['c_id']), 'count' => $row['count']];
1071
            }
1072
        }
1073
1074
        return $result;
1075
    }
1076
1077
    /**
1078
     * Returns announcement info from its id.
1079
     *
1080
     * @param int $courseId
1081
     * @param int $id
1082
     *
1083
     * @return array
1084
     */
1085
    public static function get_by_id($courseId, $id)
1086
    {
1087
        $id = (int) $id;
1088
        $courseId = $courseId ? (int) $courseId : api_get_course_int_id();
1089
1090
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1091
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1092
1093
        $sql = "SELECT DISTINCT
1094
                    announcement.id,
1095
                    announcement.title,
1096
                    announcement.content,
1097
                    ip.to_group_id
1098
               FROM $tbl_announcement announcement
1099
               INNER JOIN $tbl_item_property ip
1100
               ON
1101
                    announcement.id = ip.ref AND
1102
                    announcement.c_id = ip.c_id
1103
               WHERE
1104
                    announcement.c_id = $courseId AND
1105
                    ip.tool='announcement' AND
1106
                    announcement.id = $id
1107
                ";
1108
1109
        $result = Database::query($sql);
1110
        if (Database::num_rows($result)) {
1111
            return Database::fetch_array($result);
1112
        }
1113
1114
        return [];
1115
    }
1116
1117
    /**
1118
     * this function gets all the groups of the course,
1119
     * not including linked courses.
1120
     */
1121
    public static function get_course_groups()
1122
    {
1123
        $session_id = api_get_session_id();
1124
        if ($session_id != 0) {
1125
            $new_group_list = CourseManager::get_group_list_of_course(
1126
                api_get_course_id(),
1127
                $session_id,
1128
                1
1129
            );
1130
        } else {
1131
            $new_group_list = CourseManager::get_group_list_of_course(
1132
                api_get_course_id(),
1133
                0,
1134
                1
1135
            );
1136
        }
1137
1138
        return $new_group_list;
1139
    }
1140
1141
    /**
1142
     * This tools loads all the users and all the groups who have received
1143
     * a specific item (in this case an announcement item).
1144
     *
1145
     * @param string $tool
1146
     * @param int    $id
1147
     * @param bool   $includeGroupWhenLoadingUser
1148
     *
1149
     * @return array
1150
     */
1151
    public static function loadEditUsers($tool, $id, $includeGroupWhenLoadingUser = false)
1152
    {
1153
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1154
        $tool = Database::escape_string($tool);
1155
        $id = (int) $id;
1156
        $courseId = api_get_course_int_id();
1157
        $groupId = api_get_group_id();
1158
1159
        $sql = "SELECT to_user_id, to_group_id FROM $table
1160
                WHERE c_id = $courseId AND tool='$tool' AND ref = $id";
1161
1162
        $result = Database::query($sql);
1163
        $to = [];
1164
        while ($row = Database::fetch_array($result)) {
1165
            // This is the iid of c_group_info
1166
            $toGroup = $row['to_group_id'];
1167
            if (empty($row['to_user_id']) && !empty($groupId) && $groupId != $toGroup) {
1168
                //continue;
1169
            }
1170
            switch ($toGroup) {
1171
                // it was send to one specific user
1172
                case null:
1173
                    if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
1174
                        if (!in_array('USER:'.$row['to_user_id'], $to)) {
1175
                            $to[] = 'USER:'.$row['to_user_id'];
1176
                        }
1177
                    }
1178
                    break;
1179
                // it was sent to everyone
1180
                case 0:
1181
                    return 'everyone';
1182
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1183
                default:
1184
                    if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
1185
                        if (!in_array('USER:'.$row['to_user_id'], $to)) {
1186
                            $to[] = 'USER:'.$row['to_user_id'];
1187
                        }
1188
                    } else {
1189
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1190
                            $to[] = 'GROUP:'.$toGroup;
1191
                        }
1192
                    }
1193
1194
                    if ($includeGroupWhenLoadingUser) {
1195
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1196
                            $to[] = 'GROUP:'.$toGroup;
1197
                        }
1198
                    }
1199
                    break;
1200
            }
1201
        }
1202
1203
        return $to;
1204
    }
1205
1206
    /**
1207
     * constructs the form to display all the groups and users the message has been sent to.
1208
     *
1209
     * @param array $sent_to_array
1210
     *                             input:
1211
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1212
     *                             the first level is a distinction between groups and users:
1213
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1214
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1215
     *                             containing all the id's of the groups (resp. users) who have received this message.
1216
     *
1217
     * @return string
1218
     *
1219
     * @author Patrick Cool <patrick.cool@>
1220
     */
1221
    public static function sent_to_form($sent_to_array)
1222
    {
1223
        // we find all the names of the groups
1224
        $group_names = self::get_course_groups();
1225
1226
        // we count the number of users and the number of groups
1227
        $number_users = 0;
1228
        if (isset($sent_to_array['users'])) {
1229
            $number_users = count($sent_to_array['users']);
1230
        }
1231
        $number_groups = 0;
1232
        if (isset($sent_to_array['groups'])) {
1233
            $number_groups = count($sent_to_array['groups']);
1234
        }
1235
1236
        $total_numbers = $number_users + $number_groups;
1237
1238
        // starting the form if there is more than one user/group
1239
        $output = [];
1240
        if ($total_numbers > 1) {
1241
            // outputting the name of the groups
1242
            if (is_array($sent_to_array['groups'])) {
1243
                foreach ($sent_to_array['groups'] as $group_id) {
1244
                    $users = GroupManager::getStudents($group_id, true);
1245
                    $userToArray = [];
1246
                    foreach ($users as $student) {
1247
                        $userToArray[] = $student['complete_name_with_username'];
1248
                    }
1249
                    $output[] =
1250
                        '<br />'.
1251
                        Display::label($group_names[$group_id]['name'], 'info').
1252
                        '&nbsp;'.implode(', ', $userToArray);
1253
                }
1254
            }
1255
1256
            if (isset($sent_to_array['users'])) {
1257
                if (is_array($sent_to_array['users'])) {
1258
                    $usersToArray = [];
1259
                    foreach ($sent_to_array['users'] as $user_id) {
1260
                        $user_info = api_get_user_info($user_id);
1261
                        $usersToArray[] = $user_info['complete_name_with_username'];
1262
                    }
1263
                    $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
1264
                }
1265
            }
1266
        } else {
1267
            // there is only one user/group
1268
            if (isset($sent_to_array['users']) && is_array($sent_to_array['users'])) {
1269
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1270
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1271
            }
1272
            if (isset($sent_to_array['groups']) &&
1273
                is_array($sent_to_array['groups']) &&
1274
                isset($sent_to_array['groups'][0]) &&
1275
                $sent_to_array['groups'][0] !== 0
1276
            ) {
1277
                $group_id = $sent_to_array['groups'][0];
1278
1279
                $users = GroupManager::getStudents($group_id, true);
1280
                $userToArray = [];
1281
                foreach ($users as $student) {
1282
                    $userToArray[] = $student['complete_name_with_username'];
1283
                }
1284
                $output[] =
1285
                    '<br />'.
1286
                    Display::label($group_names[$group_id]['name'], 'info').
1287
                    '&nbsp;'.implode(', ', $userToArray);
1288
            }
1289
            if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
1290
                $output[] = "&nbsp;".get_lang('Everybody');
1291
            }
1292
        }
1293
1294
        if (!empty($output)) {
1295
            $output = array_filter($output);
1296
            if (count($output) > 0) {
1297
                $output = implode('<br />', $output);
1298
            }
1299
1300
            return $output;
1301
        }
1302
    }
1303
1304
    /**
1305
     * Returns all the users and all the groups a specific announcement item
1306
     * has been sent to.
1307
     *
1308
     * @param    string  The tool (announcement, agenda, ...)
1309
     * @param    int     ID of the element of the corresponding type
1310
     *
1311
     * @return array Array of users and groups to whom the element has been sent
1312
     */
1313
    public static function sent_to($tool, $id)
1314
    {
1315
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1316
        $tool = Database::escape_string($tool);
1317
        $id = (int) $id;
1318
1319
        $sent_to_group = [];
1320
        $sent_to = [];
1321
        $courseId = api_get_course_int_id();
1322
1323
        $sql = "SELECT to_group_id, to_user_id
1324
                FROM $table
1325
                WHERE c_id = $courseId AND tool = '$tool' AND ref=".$id;
1326
        $result = Database::query($sql);
1327
1328
        while ($row = Database::fetch_array($result)) {
1329
            // if to_user_id <> 0 then it is sent to a specific user
1330
            if ($row['to_user_id'] != 0) {
1331
                $sent_to_user[] = $row['to_user_id'];
1332
                continue;
1333
            }
1334
1335
            // if to_group_id is null then it is sent to a specific user
1336
            // if to_group_id = 0 then it is sent to everybody
1337
            if ($row['to_group_id'] != 0) {
1338
                $sent_to_group[] = $row['to_group_id'];
1339
            }
1340
        }
1341
1342
        if (isset($sent_to_group)) {
1343
            $sent_to['groups'] = $sent_to_group;
1344
        }
1345
1346
        if (isset($sent_to_user)) {
1347
            $sent_to['users'] = $sent_to_user;
1348
        }
1349
1350
        return $sent_to;
1351
    }
1352
1353
    /**
1354
     * Show a list with all the attachments according to the post's id.
1355
     *
1356
     * @param int $announcementId
1357
     *
1358
     * @return array with the post info
1359
     *
1360
     * @author Arthur Portugal
1361
     *
1362
     * @version November 2009, dokeos 1.8.6.2
1363
     */
1364
    public static function get_attachment($announcementId)
1365
    {
1366
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1367
        $announcementId = (int) $announcementId;
1368
        $courseId = api_get_course_int_id();
1369
        $row = [];
1370
        $sql = 'SELECT id, path, filename, comment
1371
                FROM '.$table.'
1372
				WHERE c_id = '.$courseId.' AND announcement_id = '.$announcementId;
1373
        $result = Database::query($sql);
1374
        if (Database::num_rows($result) != 0) {
1375
            $row = Database::fetch_array($result, 'ASSOC');
1376
        }
1377
1378
        return $row;
1379
    }
1380
1381
    /**
1382
     * This function add a attachment file into announcement.
1383
     *
1384
     * @param int  announcement id
1385
     * @param string file comment
1386
     * @param array  uploaded file $_FILES
1387
     *
1388
     * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
1389
     */
1390
    public static function add_announcement_attachment_file(
1391
        $announcement_id,
1392
        $file_comment,
1393
        $file
1394
    ) {
1395
        $courseInfo = api_get_course_info();
1396
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1397
        $return = 0;
1398
        $announcement_id = intval($announcement_id);
1399
        $courseId = api_get_course_int_id();
1400
1401
        if (is_array($file) && $file['error'] == 0) {
1402
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1403
            $courseDir = $courseInfo['path'].'/upload/announcements';
1404
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1405
            $updir = $sys_course_path.$courseDir;
1406
1407
            // Try to add an extension to the file if it hasn't one
1408
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1409
            // user's file name
1410
            $file_name = $file['name'];
1411
1412
            if (!filter_extension($new_file_name)) {
1413
                $return = -1;
1414
                echo Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error');
1415
            } else {
1416
                $new_file_name = uniqid('');
1417
                $new_path = $updir.'/'.$new_file_name;
1418
1419
                // This file is copy here but its cleaned in api_mail_html in api.lib.php
1420
                copy($file['tmp_name'], $new_path);
1421
1422
                $params = [
1423
                    'c_id' => $courseId,
1424
                    'filename' => $file_name,
1425
                    'comment' => $file_comment,
1426
                    'path' => $new_file_name,
1427
                    'announcement_id' => $announcement_id,
1428
                    'size' => (int) $file['size'],
1429
                ];
1430
1431
                $insertId = Database::insert($table, $params);
1432
                if ($insertId) {
1433
                    $sql = "UPDATE $table SET id = iid
1434
                            WHERE iid = $insertId";
1435
                    Database::query($sql);
1436
                }
1437
1438
                $return = 1;
1439
            }
1440
        }
1441
1442
        return $return;
1443
    }
1444
1445
    /**
1446
     * This function edit a attachment file into announcement.
1447
     *
1448
     * @param int attach id
1449
     * @param array uploaded file $_FILES
1450
     * @param string file comment
1451
     *
1452
     * @return int
1453
     */
1454
    public static function edit_announcement_attachment_file(
1455
        $id_attach,
1456
        $file,
1457
        $file_comment
1458
    ) {
1459
        $courseInfo = api_get_course_info();
1460
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1461
        $return = 0;
1462
        $courseId = api_get_course_int_id();
1463
1464
        if (is_array($file) && $file['error'] == 0) {
1465
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1466
            $courseDir = $courseInfo['path'].'/upload/announcements';
1467
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1468
            $updir = $sys_course_path.$courseDir;
1469
1470
            // Try to add an extension to the file if it hasn't one
1471
            $new_file_name = add_ext_on_mime(
1472
                stripslashes($file['name']),
1473
                $file['type']
1474
            );
1475
            // user's file name
1476
            $file_name = $file['name'];
1477
1478
            if (!filter_extension($new_file_name)) {
1479
                $return = -1;
1480
                echo Display::return_message(
1481
                    get_lang('UplUnableToSaveFileFilteredExtension'),
1482
                    'error'
1483
                );
1484
            } else {
1485
                $new_file_name = uniqid('');
1486
                $new_path = $updir.'/'.$new_file_name;
1487
                copy($file['tmp_name'], $new_path);
1488
                $safe_file_comment = Database::escape_string($file_comment);
1489
                $safe_file_name = Database::escape_string($file_name);
1490
                $safe_new_file_name = Database::escape_string($new_file_name);
1491
                $id_attach = intval($id_attach);
1492
                $sql = "UPDATE $table SET
1493
                            filename = '$safe_file_name',
1494
                            comment = '$safe_file_comment',
1495
                            path = '$safe_new_file_name',
1496
                            size ='".intval($file['size'])."'
1497
					 	WHERE c_id = $courseId AND id = '$id_attach'";
1498
                $result = Database::query($sql);
1499
                if ($result === false) {
1500
                    $return = -1;
1501
                    echo Display::return_message(
1502
                        get_lang('UplUnableToSaveFile'),
1503
                        'error'
1504
                    );
1505
                } else {
1506
                    $return = 1;
1507
                }
1508
            }
1509
        }
1510
1511
        return $return;
1512
    }
1513
1514
    /**
1515
     * This function delete a attachment file by id.
1516
     *
1517
     * @param int $id attachment file Id
1518
     *
1519
     * @return bool
1520
     */
1521
    public static function delete_announcement_attachment_file($id)
1522
    {
1523
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1524
        $id = intval($id);
1525
        $courseId = api_get_course_int_id();
1526
        if (empty($courseId) || empty($id)) {
1527
            return false;
1528
        }
1529
        $sql = "DELETE FROM $table
1530
                WHERE c_id = $courseId AND id = $id";
1531
        Database::query($sql);
1532
1533
        return true;
1534
    }
1535
1536
    /**
1537
     * @param array $courseInfo
1538
     * @param int   $sessionId
1539
     * @param int   $announcementId
1540
     * @param bool  $sendToUsersInSession
1541
     * @param bool  $sendToDrhUsers
1542
     * @param Monolog\Handler\HandlerInterface logger
1543
     * @param int  $senderId
1544
     * @param bool $directMessage
1545
     * @param bool $checkUrls     It checks access url of user when multiple_access_urls = true
1546
     *
1547
     * @return array
1548
     */
1549
    public static function sendEmail(
1550
        $courseInfo,
1551
        $sessionId,
1552
        $announcementId,
1553
        $sendToUsersInSession = false,
1554
        $sendToDrhUsers = false,
1555
        $logger = null,
1556
        $senderId = 0,
1557
        $directMessage = false,
1558
        $checkUrls = false
1559
    ) {
1560
        $email = new AnnouncementEmail($courseInfo, $sessionId, $announcementId, $logger);
1561
1562
        return $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId, $directMessage, $checkUrls);
1563
    }
1564
1565
    /**
1566
     * @param $stok
1567
     * @param $announcement_number
1568
     * @param bool   $getCount
1569
     * @param null   $start
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $start is correct as it would always require null to be passed?
Loading history...
1570
     * @param null   $limit
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $limit is correct as it would always require null to be passed?
Loading history...
1571
     * @param string $sidx
1572
     * @param string $sord
1573
     * @param string $titleToSearch
1574
     * @param int    $userIdToSearch
1575
     * @param int    $userId
1576
     * @param int    $courseId
1577
     * @param int    $sessionId
1578
     *
1579
     * @return array
1580
     */
1581
    public static function getAnnouncements(
1582
        $stok,
1583
        $announcement_number,
1584
        $getCount = false,
1585
        $start = null,
1586
        $limit = null,
1587
        $sidx = '',
1588
        $sord = '',
1589
        $titleToSearch = '',
1590
        $userIdToSearch = 0,
1591
        $userId = 0,
1592
        $courseId = 0,
1593
        $sessionId = 0
1594
    ) {
1595
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1596
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1597
1598
        $user_id = $userId ?: api_get_user_id();
1599
        $group_id = api_get_group_id();
1600
        $session_id = $sessionId ?: api_get_session_id();
1601
        if (empty($courseId)) {
1602
            $courseInfo = api_get_course_info();
1603
            $courseId = $courseInfo['real_id'];
1604
        } else {
1605
            $courseId = (int) $courseId;
1606
            $courseInfo = api_get_course_info_by_id($courseId);
1607
        }
1608
1609
        if (empty($courseInfo)) {
1610
            return [];
1611
        }
1612
1613
        $condition_session = api_get_session_condition(
1614
            $session_id,
1615
            true,
1616
            true,
1617
            'announcement.session_id'
1618
        );
1619
1620
        $group_memberships = GroupManager::get_group_ids(
1621
            $courseId,
1622
            api_get_user_id()
1623
        );
1624
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1625
1626
        $select = ' DISTINCT
1627
                        announcement.*,
1628
                        ip.visibility,
1629
                        ip.to_group_id,
1630
                        ip.insert_user_id,
1631
                        ip.insert_date,
1632
                        ip.lastedit_date';
1633
        $groupBy = ' GROUP BY announcement.iid';
1634
        if ($getCount) {
1635
            $groupBy = '';
1636
            $select = ' COUNT(DISTINCT announcement.iid) count';
1637
        }
1638
1639
        $searchCondition = '';
1640
        if (!empty($titleToSearch)) {
1641
            $titleToSearch = Database::escape_string($titleToSearch);
1642
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1643
        }
1644
1645
        if (!empty($userIdToSearch)) {
1646
            $userIdToSearch = (int) $userIdToSearch;
1647
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1648
        }
1649
1650
        $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
1651
        $extraGroupCondition = '';
1652
        if ($allowOnlyGroup) {
1653
            $extraGroupCondition = " AND ip.to_group_id = $group_id ";
1654
        }
1655
1656
        $allowDrhAccess = api_get_configuration_value('allow_drh_access_announcement');
1657
1658
        if ($allowDrhAccess && api_is_drh()) {
1659
            // DRH only can see visible
1660
            $searchCondition .= ' AND (ip.visibility = 1)';
1661
        }
1662
1663
        if (api_is_allowed_to_edit(false, true) ||
1664
            ($allowUserEditSetting && !api_is_anonymous()) ||
1665
            ($allowDrhAccess && api_is_drh()) ||
1666
            ($session_id && api_is_coach() && api_get_configuration_value('allow_coach_to_edit_announcements'))
1667
        ) {
1668
            // A.1. you are a course admin with a USER filter
1669
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1670
            //if (!empty($user_id)) {
1671
            if (0) {
1672
                if (is_array($group_memberships) &&
1673
                    count($group_memberships) > 0
1674
                ) {
1675
                    $sql = "SELECT $select
1676
                            FROM $tbl_announcement announcement
1677
                            INNER JOIN $tbl_item_property ip
1678
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1679
                            WHERE
1680
                                announcement.c_id = $courseId AND
1681
                                ip.c_id = $courseId AND
1682
                                ip.tool = 'announcement' AND
1683
                                (
1684
                                    ip.to_user_id = $user_id OR
1685
                                    ip.to_group_id IS NULL OR
1686
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1687
                                ) AND
1688
                                ip.visibility IN ('1', '0')
1689
                                $condition_session
1690
                                $searchCondition
1691
                            ORDER BY display_order DESC";
1692
                } else {
1693
                    $sql = "SELECT $select
1694
                            FROM $tbl_announcement announcement
1695
                            INNER JOIN $tbl_item_property ip
1696
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1697
                            WHERE
1698
                                announcement.c_id = $courseId AND
1699
                                ip.c_id = $courseId AND
1700
                                ip.tool ='announcement' AND
1701
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1702
                                ip.visibility IN ('1', '0')
1703
                            $condition_session
1704
                            $searchCondition
1705
                            ORDER BY display_order DESC";
1706
                }
1707
            } elseif ($group_id != 0) {
1708
                // A.2. you are a course admin with a GROUP filter
1709
                // => see only the messages of this specific group
1710
                $sql = "SELECT $select
1711
                        FROM $tbl_announcement announcement
1712
                        INNER JOIN $tbl_item_property ip
1713
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1714
                        WHERE
1715
                            ip.tool='announcement' AND
1716
                            announcement.c_id = $courseId AND
1717
                            ip.c_id = $courseId AND
1718
                            ip.visibility<>'2' AND
1719
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1720
                            $condition_session
1721
                            $searchCondition
1722
                            $extraGroupCondition
1723
                        $groupBy
1724
                        ORDER BY display_order DESC";
1725
            } else {
1726
                // A.3 you are a course admin without any group or user filter
1727
                // A.3.a you are a course admin without user or group filter but WITH studentview
1728
                // => see all the messages of all the users and groups without editing possibilities
1729
                if (isset($isStudentView) && $isStudentView == 'true') {
1730
                    $sql = "SELECT $select
1731
                            FROM $tbl_announcement announcement
1732
                            INNER JOIN $tbl_item_property ip
1733
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1734
                            WHERE
1735
                                ip.tool='announcement' AND
1736
                                announcement.c_id = $courseId AND
1737
                                ip.c_id = $courseId AND
1738
                                ip.visibility='1'
1739
                                $condition_session
1740
                                $searchCondition
1741
                            $groupBy
1742
                            ORDER BY display_order DESC";
1743
                } else {
1744
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1745
                    // => see all the messages of all the users and groups with editing possibilities
1746
                    $sql = "SELECT $select
1747
                            FROM $tbl_announcement announcement
1748
                            INNER JOIN $tbl_item_property ip
1749
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1750
                            WHERE
1751
                                ip.tool = 'announcement' AND
1752
                                announcement.c_id = $courseId AND
1753
                                ip.c_id = $courseId  AND
1754
                                (ip.visibility='0' OR ip.visibility='1')
1755
                                $condition_session
1756
                                $searchCondition
1757
                            $groupBy
1758
                            ORDER BY display_order DESC";
1759
                }
1760
            }
1761
        } else {
1762
            // STUDENT
1763
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1764
                if ($allowUserEditSetting && !api_is_anonymous()) {
1765
                    if ($group_id == 0) {
1766
                        // No group
1767
                        $cond_user_id = " AND (
1768
                            ip.lastedit_user_id = '".$user_id."' OR (
1769
                                (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
1770
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1771
                            )
1772
                        ) ";
1773
                    } else {
1774
                        $cond_user_id = " AND (
1775
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1776
                        )";
1777
                        $cond_user_id .= $extraGroupCondition;
1778
                    }
1779
                } else {
1780
                    if ($group_id == 0) {
1781
                        $cond_user_id = " AND (
1782
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1783
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1784
                        ) ";
1785
                    } else {
1786
                        $cond_user_id = " AND (
1787
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1788
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1789
                        )";
1790
                        $cond_user_id .= $extraGroupCondition;
1791
                    }
1792
                }
1793
1794
                $sql = "SELECT $select
1795
                        FROM $tbl_announcement announcement INNER JOIN
1796
                        $tbl_item_property ip
1797
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1798
                        WHERE
1799
                            announcement.c_id = $courseId AND
1800
                            ip.c_id = $courseId AND
1801
                            ip.tool='announcement'
1802
                            $cond_user_id
1803
                            $condition_session
1804
                            $searchCondition AND
1805
                            ip.visibility='1'
1806
                            $groupBy
1807
                        ORDER BY display_order DESC";
1808
            } else {
1809
                if ($user_id) {
1810
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1811
                        $cond_user_id = " AND (
1812
                                ip.lastedit_user_id = '".api_get_user_id()."' OR
1813
                                ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1814
                                (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1815
                            )
1816
                        ) ";
1817
                    } else {
1818
                        $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1819
                        (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1820
                    }
1821
1822
                    $sql = "SELECT $select
1823
						FROM $tbl_announcement announcement
1824
						INNER JOIN $tbl_item_property ip
1825
						ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1826
						WHERE
1827
    						announcement.c_id = $courseId AND
1828
							ip.c_id = $courseId AND
1829
    						ip.tool='announcement'
1830
    						$cond_user_id
1831
    						$condition_session
1832
    						$searchCondition
1833
    						AND ip.visibility='1'
1834
    						AND announcement.session_id IN(0, ".$session_id.")
1835
                        $groupBy
1836
						ORDER BY display_order DESC";
1837
                } else {
1838
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1839
                        $cond_user_id = " AND (
1840
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1841
                        )";
1842
                    } else {
1843
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1844
                    }
1845
1846
                    $sql = "SELECT $select
1847
                            FROM $tbl_announcement announcement
1848
                            INNER JOIN $tbl_item_property ip
1849
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1850
                            WHERE
1851
                                announcement.c_id = $courseId AND
1852
                                ip.c_id = $courseId AND
1853
                                ip.tool='announcement'
1854
                                $cond_user_id
1855
                                $condition_session
1856
                                $searchCondition  AND
1857
                                ip.visibility='1' AND
1858
                                announcement.session_id IN ( 0,".api_get_session_id().")
1859
                                $groupBy
1860
                            ";
1861
                }
1862
            }
1863
        }
1864
1865
        if (!is_null($start) && !is_null($limit)) {
1866
            $start = (int) $start;
1867
            $limit = (int) $limit;
1868
            $sql .= " LIMIT $start, $limit";
1869
        }
1870
1871
        $result = Database::query($sql);
1872
        if ($getCount) {
1873
            $result = Database::fetch_array($result, 'ASSOC');
1874
1875
            return $result['count'];
1876
        }
1877
1878
        $iterator = 1;
1879
        $bottomAnnouncement = $announcement_number;
1880
        $displayed = [];
1881
        $results = [];
1882
        $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('AnnounceSentByEmail').'"></i>';
1883
        $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
1884
        $editIcon = Display::return_icon(
1885
            'edit.png',
1886
            get_lang('Edit'),
1887
            '',
1888
            ICON_SIZE_SMALL
1889
        );
1890
1891
        $editIconDisable = Display::return_icon(
1892
            'edit_na.png',
1893
            get_lang('Edit'),
1894
            '',
1895
            ICON_SIZE_SMALL
1896
        );
1897
        $deleteIcon = Display::return_icon(
1898
            'delete.png',
1899
            get_lang('Delete'),
1900
            '',
1901
            ICON_SIZE_SMALL
1902
        );
1903
1904
        $deleteIconDisable = Display::return_icon(
1905
            'delete_na.png',
1906
            get_lang('Delete'),
1907
            '',
1908
            ICON_SIZE_SMALL
1909
        );
1910
1911
        $isTutor = false;
1912
        if (!empty($group_id)) {
1913
            $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1914
            //User has access in the group?
1915
            $isTutor = GroupManager::is_tutor_of_group(
1916
                api_get_user_id(),
1917
                $groupInfo
1918
            );
1919
        }
1920
1921
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1922
            if (!in_array($row['id'], $displayed)) {
1923
                $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'
1924
                    .api_get_cidreq_params($courseInfo['code'], $session_id, $group_id);
1925
                $sent_to_icon = '';
1926
                // the email icon
1927
                if ($row['email_sent'] == '1') {
1928
                    $sent_to_icon = ' '.$emailIcon;
1929
                }
1930
1931
                $groupReference = $row['to_group_id'] > 0 ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
1932
                $disableEdit = false;
1933
                $to = self::loadEditUsers('announcement', $row['id'], true);
1934
                $separated = CourseManager::separateUsersGroups($to);
1935
                if (!empty($group_id)) {
1936
                    // If the announcement was sent to many groups, disable edition inside a group
1937
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1938
                        $disableEdit = true;
1939
                    }
1940
1941
                    // If the announcement was sent only to the course disable edition
1942
                    if (empty($separated['groups']) && empty($separated['users'])) {
1943
                        $disableEdit = true;
1944
                    }
1945
1946
                    // Announcement sent to only a user
1947
                    if ($separated['groups'] > 1 && !in_array($group_id, $separated['groups'])) {
1948
                        $disableEdit = true;
1949
                    }
1950
                } else {
1951
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1952
                        $groupReference = '';
1953
                    }
1954
                }
1955
1956
                $title = $row['title'].$groupReference.$sent_to_icon;
1957
                $item_visibility = api_get_item_visibility(
1958
                    $courseInfo,
1959
                    TOOL_ANNOUNCEMENT,
1960
                    $row['id'],
1961
                    $session_id
1962
                );
1963
                $row['visibility'] = $item_visibility;
1964
1965
                // show attachment list
1966
                $attachment_list = self::get_attachment($row['id']);
1967
                $attachment_icon = '';
1968
                if (count($attachment_list) > 0) {
1969
                    $attachment_icon = ' '.$attachmentIcon;
1970
                }
1971
1972
                $user_info = api_get_user_info($row['insert_user_id']);
1973
                $username = sprintf(get_lang('LoginX'), $user_info['username']);
1974
                $username_span = Display::tag(
1975
                    'span',
1976
                    $user_info['complete_name'],
1977
                    ['title' => $username]
1978
                );
1979
1980
                $title = Display::url(
1981
                    $title.$attachment_icon,
1982
                    $actionUrl.'&action=view&id='.$row['id']
1983
                );
1984
1985
                // we can edit if : we are the teacher OR the element belongs to
1986
                // the session we are coaching OR the option to allow users to edit is on
1987
                if (api_is_allowed_to_edit(false, true) ||
1988
                    (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $row['id'])) ||
1989
                    (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
1990
                    ($row['to_group_id'] == $group_id && $isTutor) ||
1991
                    ($session_id && api_is_coach() && api_get_configuration_value('allow_coach_to_edit_announcements'))
1992
                ) {
1993
                    if ($disableEdit === true) {
1994
                        $modify_icons = "<a href='#'>".$editIconDisable."</a>";
1995
                    } else {
1996
                        $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$row['id']."\">".$editIcon."</a>";
1997
                    }
1998
1999
                    $image_visibility = 'invisible';
2000
                    $alt_visibility = get_lang('Visible');
2001
                    if ($row['visibility'] == 1) {
2002
                        $image_visibility = 'visible';
2003
                        $alt_visibility = get_lang('Hide');
2004
                    }
2005
2006
                    $modify_icons .= "<a
2007
                        href=\"".$actionUrl."&action=showhide&id=".$row['id']."&sec_token=".$stok."\">".
2008
                        Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL).
2009
                        "</a>";
2010
2011
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
2012
                    if ($iterator != 1) {
2013
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$row["id"]."&sec_token=".$stok."\">".
2014
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
2015
                    } else {
2016
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
2017
                    }
2018
2019
                    if ($iterator < $bottomAnnouncement) {
2020
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$row["id"]."&sec_token=".$stok."\">".
2021
                            Display::return_icon('down.gif', get_lang('Down'))."</a>";
2022
                    } else {
2023
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
2024
                    }
2025
2026
                    if (api_is_allowed_to_edit(false, true)) {
2027
                        if ($disableEdit === true) {
2028
                            $modify_icons .= Display::url($deleteIconDisable, '#');
2029
                        } else {
2030
                            $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$row['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
2031
                                    api_htmlentities(
2032
                                        get_lang('ConfirmYourChoice'),
2033
                                        ENT_QUOTES,
2034
                                        api_get_system_encoding()
2035
                                    )
2036
                                )."')) return false;\">".
2037
                                $deleteIcon."</a>";
2038
                        }
2039
                    }
2040
                    $iterator++;
2041
                } else {
2042
                    $modify_icons = Display::url(
2043
                        Display::return_icon('default.png'),
2044
                        $actionUrl.'&action=view&id='.$row['id']
2045
                    );
2046
                }
2047
2048
                $announcement = [
2049
                    'id' => $row['id'],
2050
                    'title' => $title,
2051
                    'username' => $username_span,
2052
                    'insert_date' => api_convert_and_format_date(
2053
                        $row['insert_date'],
2054
                        DATE_TIME_FORMAT_LONG
2055
                    ),
2056
                    'lastedit_date' => api_convert_and_format_date(
2057
                        $row['lastedit_date'],
2058
                        DATE_TIME_FORMAT_LONG
2059
                    ),
2060
                    'actions' => $modify_icons,
2061
                ];
2062
2063
                $results[] = $announcement;
2064
            }
2065
            $displayed[] = $row['id'];
2066
        }
2067
2068
        return $results;
2069
    }
2070
2071
    /**
2072
     * @return int
2073
     */
2074
    public static function getNumberAnnouncements()
2075
    {
2076
        // Maximum title messages to display
2077
        $maximum = '12';
2078
        // Database Table Definitions
2079
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
2080
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
2081
2082
        $session_id = api_get_session_id();
2083
        $courseInfo = api_get_course_info();
2084
        $courseId = $courseInfo['real_id'];
2085
        $userId = api_get_user_id();
2086
        $condition_session = api_get_session_condition(
2087
            $session_id,
2088
            true,
2089
            true,
2090
            'announcement.session_id'
2091
        );
2092
2093
        if (api_is_allowed_to_edit(false, true)) {
2094
            // check teacher status
2095
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2096
                if (api_get_group_id() == 0) {
2097
                    $group_condition = '';
2098
                } else {
2099
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
2100
                }
2101
2102
                $sql = "SELECT
2103
                            announcement.*,
2104
                            ip.visibility,
2105
                            ip.to_group_id,
2106
                            ip.insert_user_id
2107
                        FROM $tbl_announcement announcement
2108
                        INNER JOIN $tbl_item_property ip
2109
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2110
                        WHERE
2111
                            announcement.c_id = $courseId AND
2112
                            ip.c_id = $courseId AND
2113
                            ip.tool = 'announcement' AND
2114
                            ip.visibility <> '2'
2115
                            $group_condition
2116
                            $condition_session
2117
                        GROUP BY ip.ref
2118
                        ORDER BY display_order DESC
2119
                        LIMIT 0, $maximum";
2120
            }
2121
        } else {
2122
            // students only get to see the visible announcements
2123
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2124
                $group_memberships = GroupManager::get_group_ids(
2125
                    $courseInfo['real_id'],
2126
                    $userId
2127
                );
2128
2129
                if ((api_get_course_setting('allow_user_edit_announcement') &&
2130
                    !api_is_anonymous())
2131
                ) {
2132
                    if (api_get_group_id() == 0) {
2133
                        $cond_user_id = " AND (
2134
                        ip.lastedit_user_id = '".$userId."' OR (
2135
                            ip.to_user_id='".$userId."' OR
2136
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2137
                            ip.to_group_id IS NULL
2138
                            )
2139
                        )
2140
                        ";
2141
                    } else {
2142
                        $cond_user_id = " AND (
2143
                            ip.lastedit_user_id = '".$userId."'OR
2144
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2145
                            ip.to_group_id IS NULL
2146
                        )";
2147
                    }
2148
                } else {
2149
                    if (api_get_group_id() == 0) {
2150
                        $cond_user_id = " AND (
2151
                            ip.to_user_id='".$userId."' OR
2152
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2153
                            ip.to_group_id IS NULL
2154
                        ) ";
2155
                    } else {
2156
                        $cond_user_id = " AND (
2157
                            ip.to_user_id='".$userId."' OR
2158
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2159
                            ip.to_group_id IS NULL
2160
                        ) ";
2161
                    }
2162
                }
2163
2164
                // the user is member of several groups => display personal announcements AND
2165
                // his group announcements AND the general announcements
2166
                if (is_array($group_memberships) && count($group_memberships) > 0) {
2167
                    $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2168
                            FROM $tbl_announcement announcement
2169
                            INNER JOIN $tbl_item_property ip
2170
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2171
                            WHERE
2172
                                announcement.c_id = $courseId AND
2173
                                ip.c_id = $courseId AND
2174
                                ip.tool='announcement' AND
2175
                                ip.visibility='1'
2176
                                $cond_user_id
2177
                                $condition_session
2178
                            GROUP BY ip.ref
2179
                            ORDER BY display_order DESC
2180
                            LIMIT 0, $maximum";
2181
                } else {
2182
                    // the user is not member of any group
2183
                    // this is an identified user => show the general announcements AND his personal announcements
2184
                    if ($userId) {
2185
                        if ((api_get_course_setting('allow_user_edit_announcement') &&
2186
                            !api_is_anonymous())
2187
                        ) {
2188
                            $cond_user_id = " AND (
2189
                                ip.lastedit_user_id = '".$userId."' OR
2190
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2191
                            ) ";
2192
                        } else {
2193
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
2194
                        }
2195
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2196
                                FROM $tbl_announcement announcement
2197
                                INNER JOIN $tbl_item_property ip
2198
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2199
                                WHERE
2200
                                    announcement.c_id = $courseId AND
2201
                                    ip.c_id = $courseId AND
2202
                                    ip.tool='announcement' AND
2203
                                    ip.visibility='1'
2204
                                    $cond_user_id
2205
                                    $condition_session
2206
                                GROUP BY ip.ref
2207
                                ORDER BY display_order DESC
2208
                                LIMIT 0, $maximum";
2209
                    } else {
2210
                        if (api_get_course_setting('allow_user_edit_announcement')) {
2211
                            $cond_user_id = " AND (
2212
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
2213
                            ) ";
2214
                        } else {
2215
                            $cond_user_id = " AND ip.to_group_id='0' ";
2216
                        }
2217
2218
                        // the user is not identiefied => show only the general announcements
2219
                        $sql = "SELECT
2220
                                    announcement.*,
2221
                                    ip.visibility,
2222
                                    ip.to_group_id,
2223
                                    ip.insert_user_id
2224
                                FROM $tbl_announcement announcement
2225
                                INNER JOIN $tbl_item_property ip
2226
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2227
                                WHERE
2228
                                    announcement.c_id = $courseId AND
2229
                                    ip.c_id = $courseId AND
2230
                                    ip.tool='announcement' AND
2231
                                    ip.visibility='1' AND
2232
                                    ip.to_group_id='0'
2233
                                    $condition_session
2234
                                GROUP BY ip.ref
2235
                                ORDER BY display_order DESC
2236
                                LIMIT 0, $maximum";
2237
                    }
2238
                }
2239
            }
2240
        }
2241
2242
        $result = Database::query($sql);
2243
2244
        return Database::num_rows($result);
2245
    }
2246
2247
    public static function createEvent(
2248
        int $announcementId,
2249
        string $startDate,
2250
        string $endDate,
2251
        array $choosenUsers = [],
2252
        array $reminders = []
2253
    ): ?CCalendarEvent {
2254
        $em = Database::getManager();
2255
        $announcement = $em->find('ChamiloCourseBundle:CAnnouncement', $announcementId);
2256
        $agenda = new Agenda('course');
2257
2258
        $eventId = $agenda->addEvent(
2259
            $startDate,
2260
            $endDate,
2261
            '',
2262
            $announcement->getTitle(),
2263
            $announcement->getContent(),
2264
            $choosenUsers,
2265
            false,
2266
            null,
2267
            [],
2268
            [],
2269
            null,
2270
            '',
2271
            [],
2272
            false,
2273
            $reminders
2274
        );
2275
2276
        if ($eventId) {
2277
            return $em->find('ChamiloCourseBundle:CCalendarEvent', $eventId);
2278
        }
2279
2280
        return null;
2281
    }
2282
}
2283