Passed
Push — 1.11.x ( 84c2d4...e4781a )
by Julito
11:01
created

AnnouncementManager::addGroupAnnouncement()   C

Complexity

Conditions 11
Paths 41

Size

Total Lines 98
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 59
c 0
b 0
f 0
nc 41
nop 7
dl 0
loc 98
rs 6.7478

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\CItemProperty;
8
9
/**
10
 * Include file with functions for the announcements module.
11
 *
12
 * @author jmontoya
13
 *
14
 * @package chamilo.announcements
15
 *
16
 * @todo use OOP
17
 */
18
class AnnouncementManager
19
{
20
    /**
21
     * Constructor.
22
     */
23
    public function __construct()
24
    {
25
    }
26
27
    /**
28
     * @return array
29
     */
30
    public static function getTags()
31
    {
32
        $tags = [
33
            '((user_name))',
34
            '((user_email))',
35
            '((user_firstname))',
36
            '((user_lastname))',
37
            '((user_official_code))',
38
            '((course_title))',
39
            '((course_link))',
40
        ];
41
42
        $tags[] = '((teachers))';
43
44
        $extraField = new ExtraField('user');
45
        $extraFields = $extraField->get_all(['filter = ?' => 1]);
46
        if (!empty($extraFields)) {
47
            foreach ($extraFields as $extra) {
48
                $tags[] = "((extra_".$extra['variable']."))";
49
            }
50
        }
51
        $sessionId = api_get_session_id();
52
        if (!empty($sessionId)) {
53
            $tags[] = '((coaches))';
54
            $tags[] = '((general_coach))';
55
            $tags[] = '((general_coach_email))';
56
        }
57
58
        return $tags;
59
    }
60
61
    /**
62
     * @param int    $userId
63
     * @param string $content
64
     * @param string $courseCode
65
     * @param int    $sessionId
66
     *
67
     * @return string
68
     */
69
    public static function parseContent(
70
        $userId,
71
        $content,
72
        $courseCode,
73
        $sessionId = 0
74
    ) {
75
        $readerInfo = api_get_user_info($userId, false, false, true, true, false, true);
76
        $courseInfo = api_get_course_info($courseCode);
77
        $teacherList = '';
78
        if ($courseInfo) {
79
            $teacherList = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code']);
80
        }
81
        $generalCoachName = '';
82
        $generalCoachEmail = '';
83
        $coaches = '';
84
        if (!empty($sessionId)) {
85
            $sessionInfo = api_get_session_info($sessionId);
86
            $coaches = CourseManager::get_coachs_from_course_to_string(
87
                $sessionId,
88
                $courseInfo['real_id']
89
            );
90
91
            $generalCoach = api_get_user_info($sessionInfo['id_coach']);
92
            $generalCoachName = $generalCoach['complete_name'];
93
            $generalCoachEmail = $generalCoach['email'];
94
        }
95
96
        $data = [];
97
        $data['user_name'] = '';
98
        $data['user_firstname'] = '';
99
        $data['user_lastname'] = '';
100
        $data['user_official_code'] = '';
101
        $data['user_email'] = '';
102
        if (!empty($readerInfo)) {
103
            $data['user_name'] = $readerInfo['username'];
104
            $data['user_email'] = $readerInfo['email'];
105
            $data['user_firstname'] = $readerInfo['firstname'];
106
            $data['user_lastname'] = $readerInfo['lastname'];
107
            $data['user_official_code'] = $readerInfo['official_code'];
108
        }
109
110
        $data['course_title'] = $courseInfo['name'] ?? '';
111
        $courseLink = api_get_course_url($courseCode, $sessionId);
112
        $data['course_link'] = Display::url($courseLink, $courseLink);
113
        $data['teachers'] = $teacherList;
114
115
        if (!empty($readerInfo)) {
116
            $extraField = new ExtraField('user');
117
            $extraFields = $extraField->get_all(['filter = ?' => 1]);
118
            if (!empty($extraFields)) {
119
                foreach ($extraFields as $extra) {
120
                    $data['extra_'.$extra['variable']] = '';
121
                }
122
            }
123
124
            if (!empty($readerInfo['extra'])) {
125
                foreach ($readerInfo['extra'] as $extra) {
126
                    if (isset($extra['value'])) {
127
                        /** @var \Chamilo\CoreBundle\Entity\ExtraFieldValues $value */
128
                        $value = $extra['value'];
129
                        if ($value instanceof ExtraFieldValues) {
130
                            $field = $value->getField();
131
                            if ($field instanceof ExtraFieldEntity) {
132
                                $data['extra_'.$field->getVariable()] = $value->getValue();
133
                            }
134
                        }
135
                    }
136
                }
137
            }
138
        }
139
140
        if (!empty($sessionId)) {
141
            $data['coaches'] = $coaches;
142
            $data['general_coach'] = $generalCoachName;
143
            $data['general_coach_email'] = $generalCoachEmail;
144
        }
145
146
        $tags = self::getTags();
147
        foreach ($tags as $tag) {
148
            $simpleTag = str_replace(['((', '))'], '', $tag);
149
            $value = isset($data[$simpleTag]) ? $data[$simpleTag] : '';
150
            $content = str_replace($tag, $value, $content);
151
        }
152
153
        return $content;
154
    }
155
156
    /**
157
     * Gets all announcements from a course.
158
     *
159
     * @param array $course_info
160
     * @param int   $session_id
161
     *
162
     * @return array html with the content and count of announcements or false otherwise
163
     */
164
    public static function get_all_annoucement_by_course($course_info, $session_id = 0)
165
    {
166
        $session_id = (int) $session_id;
167
        $courseId = $course_info['real_id'];
168
169
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
170
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
171
172
        $sql = "SELECT DISTINCT
173
                    announcement.id,
174
                    announcement.title,
175
                    announcement.content
176
				FROM $tbl_announcement announcement
177
				INNER JOIN $tbl_item_property i
178
				ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
179
				WHERE
180
                    i.tool='announcement' AND
181
                    announcement.session_id  = '$session_id' AND
182
                    announcement.c_id = $courseId AND
183
                    i.c_id = $courseId
184
				ORDER BY display_order DESC";
185
        $rs = Database::query($sql);
186
        $num_rows = Database::num_rows($rs);
187
        if ($num_rows > 0) {
188
            $list = [];
189
            while ($row = Database::fetch_array($rs)) {
190
                $list[] = $row;
191
            }
192
193
            return $list;
194
        }
195
196
        return false;
197
    }
198
199
    /**
200
     * This functions switches the visibility a course resource
201
     * using the visibility field in 'item_property'.
202
     *
203
     * @param array $courseInfo
204
     * @param int   $id         ID of the element of the corresponding type
205
     *
206
     * @return bool False on failure, True on success
207
     */
208
    public static function change_visibility_announcement($courseInfo, $id)
209
    {
210
        $session_id = api_get_session_id();
211
        $item_visibility = api_get_item_visibility(
212
            $courseInfo,
213
            TOOL_ANNOUNCEMENT,
214
            $id,
215
            $session_id
216
        );
217
        if ($item_visibility == '1') {
218
            api_item_property_update(
219
                $courseInfo,
220
                TOOL_ANNOUNCEMENT,
221
                $id,
222
                'invisible',
223
                api_get_user_id()
224
            );
225
        } else {
226
            api_item_property_update(
227
                $courseInfo,
228
                TOOL_ANNOUNCEMENT,
229
                $id,
230
                'visible',
231
                api_get_user_id()
232
            );
233
        }
234
235
        return true;
236
    }
237
238
    /**
239
     * Deletes an announcement.
240
     *
241
     * @param array $courseInfo the course array
242
     * @param int   $id         the announcement id
243
     */
244
    public static function delete_announcement($courseInfo, $id)
245
    {
246
        api_item_property_update(
247
            $courseInfo,
248
            TOOL_ANNOUNCEMENT,
249
            $id,
250
            'delete',
251
            api_get_user_id()
252
        );
253
    }
254
255
    /**
256
     * Deletes all announcements by course.
257
     *
258
     * @param array $courseInfo the course array
259
     */
260
    public static function delete_all_announcements($courseInfo)
261
    {
262
        $announcements = self::get_all_annoucement_by_course(
263
            $courseInfo,
264
            api_get_session_id()
265
        );
266
        if (!empty($announcements)) {
267
            foreach ($announcements as $annon) {
268
                api_item_property_update(
269
                    $courseInfo,
270
                    TOOL_ANNOUNCEMENT,
271
                    $annon['id'],
272
                    'delete',
273
                    api_get_user_id()
274
                );
275
            }
276
        }
277
    }
278
279
    /**
280
     * @param string $title
281
     * @param int    $courseId
282
     * @param int    $sessionId
283
     * @param int    $visibility 1 or 0
284
     *
285
     * @return mixed
286
     */
287
    public static function getAnnouncementsByTitle(
288
        $title,
289
        $courseId,
290
        $sessionId = 0,
291
        $visibility = 1
292
    ) {
293
        $dql = "SELECT a
294
                FROM ChamiloCourseBundle:CAnnouncement a
295
                JOIN ChamiloCourseBundle:CItemProperty ip
296
                WITH a.id = ip.ref AND a.cId = ip.course
297
                WHERE
298
                    ip.tool = 'announcement' AND
299
                    a.cId = :course AND
300
                    a.sessionId = :session AND
301
                    a.title like :title AND
302
                    ip.visibility = :visibility
303
                ORDER BY a.displayOrder DESC";
304
305
        $qb = Database::getManager()->createQuery($dql);
306
        $result = $qb->execute(
307
            [
308
                'course' => $courseId,
309
                'session' => $sessionId,
310
                'visibility' => $visibility,
311
                'title' => "%$title%",
312
            ]
313
        );
314
315
        return $result;
316
    }
317
318
    /**
319
     * @param int $announcementId
320
     * @param int $courseId
321
     * @param int $userId
322
     * @param int $groupId
323
     *
324
     * @return array
325
     */
326
    public static function getAnnouncementInfoById(
327
        $announcementId,
328
        $courseId,
329
        $userId,
330
        $groupId = 0
331
    ) {
332
        $announcementId = (int) $announcementId;
333
        $courseId = (int) $courseId;
334
        $userId = (int) $userId;
335
        $groupId = (int) $groupId;
336
337
        if (api_is_allowed_to_edit(false, true) ||
338
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
339
        ) {
340
            $dql = "SELECT a, ip
341
                    FROM ChamiloCourseBundle:CAnnouncement a
342
                    JOIN ChamiloCourseBundle:CItemProperty ip
343
                    WITH a.id = ip.ref AND a.cId = ip.course
344
                    WHERE
345
                        a.id = :announcement AND
346
                        ip.tool = 'announcement' AND
347
                        a.cId = :course
348
                    ORDER BY a.displayOrder DESC";
349
        } else {
350
            $groupList[] = $groupId;
351
352
            if (api_get_user_id() != 0) {
353
                $extraGroupCondition = '';
354
                if (!empty($groupId)) {
355
                    $groupProperties = GroupManager::get_group_properties($groupId);
356
                    if ($groupProperties['announcements_state'] == GroupManager::TOOL_PRIVATE_BETWEEN_USERS) {
357
                        $extraGroupCondition = " AND (
358
                            ip.toUser = $userId AND ip.group = $groupId OR
359
                            (ip.group IN ('0') OR ip.group IS NULL) OR
360
                            (ip.group = $groupId AND (ip.toUser IS NULL OR ip.toUser = 0))
361
                        )";
362
                    }
363
                }
364
365
                $dql = "SELECT a, ip
366
                        FROM ChamiloCourseBundle:CAnnouncement a
367
                        JOIN ChamiloCourseBundle:CItemProperty ip
368
                        WITH a.id = ip.ref AND a.cId = ip.course
369
                        WHERE
370
                            a.id = :announcement AND
371
                            ip.tool='announcement' AND
372
                            (
373
                                ip.toUser = $userId OR
374
                                ip.group IN ('0', '".$groupId."') OR
375
                                ip.group IS NULL
376
                            ) AND
377
                            ip.visibility = '1' AND
378
                            ip.course = :course
379
                            $extraGroupCondition
380
                        ORDER BY a.displayOrder DESC";
381
            } else {
382
                $dql = "SELECT a, ip
383
                        FROM ChamiloCourseBundle:CAnnouncement a
384
                        JOIN ChamiloCourseBundle:CItemProperty ip
385
                        WITH a.id = ip.ref AND a.cId = ip.course
386
                        WHERE
387
                            a.id = :announcement AND
388
                            ip.tool = 'announcement' AND
389
                            (ip.group = '0' OR ip.group IS NULL) AND
390
                            ip.visibility = '1' AND
391
                            ip.course = :course";
392
            }
393
        }
394
395
        $qb = Database::getManager()->createQuery($dql);
396
        $result = $qb->execute(
397
            [
398
                'announcement' => $announcementId,
399
                'course' => $courseId,
400
            ]
401
        );
402
403
        if (!empty($result)) {
404
            return [
405
                'announcement' => $result[0],
406
                'item_property' => $result[1],
407
            ];
408
        }
409
410
        return [];
411
    }
412
413
    /**
414
     * Displays one specific announcement.
415
     *
416
     * @param int $id the id of the announcement you want to display
417
     *
418
     * @return string
419
     */
420
    public static function displayAnnouncement($id)
421
    {
422
        $id = (int) $id;
423
424
        if (empty($id)) {
425
            return '';
426
        }
427
428
        global $charset;
429
430
        $html = '';
431
        $result = self::getAnnouncementInfoById(
432
            $id,
433
            api_get_course_int_id(),
434
            api_get_user_id(),
435
            api_get_group_id()
436
        );
437
438
        if (empty($result)) {
439
            return '';
440
        }
441
442
        /** @var CAnnouncement $announcement */
443
        $announcement = $result['announcement'];
444
        /** @var CItemProperty $itemProperty */
445
        $itemProperty = $result['item_property'];
446
447
        if (empty($announcement) || empty($itemProperty)) {
448
            return '';
449
        }
450
451
        $title = $announcement->getTitle();
452
        $content = $announcement->getContent();
453
454
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"table table-hover table-striped data_table\">";
455
        $html .= "<tr><td><h2>".$title."</h2></td></tr>";
456
457
        if (api_is_allowed_to_edit(false, true) ||
458
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
459
        ) {
460
            $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
461
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
462
463
            $image_visibility = 'invisible';
464
            $alt_visibility = get_lang('Visible');
465
            if ($itemProperty->getVisibility() === 1) {
466
                $image_visibility = 'visible';
467
                $alt_visibility = get_lang('Hide');
468
            }
469
            global $stok;
470
            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=showhide&id=".$id."&sec_token=".$stok."\">".
471
                Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
472
473
            if (api_is_allowed_to_edit(false, true)) {
474
                $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=delete&id=".$id."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."')) return false;\">".
475
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
476
                    "</a>";
477
            }
478
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
479
        }
480
481
        // The user id is always the current one.
482
        $toUserId = api_get_user_id();
483
        $content = self::parseContent(
484
            $toUserId,
485
            $content,
486
            api_get_course_id(),
487
            api_get_session_id()
488
        );
489
490
        $html .= "<tr><td>$content</td></tr>";
491
        $html .= "<tr>";
492
        $html .= "<td class=\"announcements_datum\">".get_lang('LastUpdateDate')." : ";
493
        $lastEdit = $itemProperty->getLasteditDate();
494
        $html .= Display::dateToStringAgoAndLongDate($lastEdit);
495
        $html .= "</td></tr>";
496
497
        $allow = !api_get_configuration_value('hide_announcement_sent_to_users_info');
498
        if ($allow && api_is_allowed_to_edit(false, true)) {
499
            $sent_to = self::sent_to('announcement', $id);
500
            $sentToForm = self::sent_to_form($sent_to);
501
            $html .= Display::tag(
502
                'td',
503
                get_lang('SentTo').': '.$sentToForm,
504
                ['class' => 'announcements_datum']
505
            );
506
        }
507
        $attachment_list = self::get_attachment($id);
508
509
        if (count($attachment_list) > 0) {
510
            $html .= "<tr><td>";
511
            $realname = $attachment_list['path'];
512
            $user_filename = $attachment_list['filename'];
513
            $full_file_name = 'download.php?'.api_get_cidreq().'&file='.$realname;
514
            $html .= '<br/>';
515
            $html .= Display::return_icon('attachment.gif', get_lang('Attachment'));
516
            $html .= '<a href="'.$full_file_name.' "> '.$user_filename.' </a>';
517
            $html .= ' - <span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
518
            if (api_is_allowed_to_edit(false, true)) {
519
                $url = api_get_self()."?".api_get_cidreq().
520
                    "&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok;
521
                $html .= Display::url(
522
                    Display::return_icon(
523
                        'delete.png',
524
                        get_lang('Delete'),
525
                        '',
526
                        16
527
                    ),
528
                    $url
529
                );
530
            }
531
            $html .= '</td></tr>';
532
        }
533
        $html .= '</table>';
534
535
        return $html;
536
    }
537
538
    /**
539
     * @param array $courseInfo
540
     *
541
     * @return int
542
     */
543
    public static function getLastAnnouncementOrder($courseInfo)
544
    {
545
        if (empty($courseInfo)) {
546
            return 0;
547
        }
548
549
        if (!isset($courseInfo['real_id'])) {
550
            return false;
551
        }
552
553
        $courseId = $courseInfo['real_id'];
554
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
555
        $sql = "SELECT MAX(display_order)
556
                FROM $table
557
                WHERE c_id = $courseId ";
558
        $result = Database::query($sql);
559
560
        $order = 0;
561
        if (Database::num_rows($result)) {
562
            $row = Database::fetch_array($result);
563
            $order = (int) $row[0] + 1;
564
        }
565
566
        return $order;
567
    }
568
569
    /**
570
     * Store an announcement in the database (including its attached file if any).
571
     *
572
     * @param array  $courseInfo
573
     * @param int    $sessionId
574
     * @param string $title                Announcement title (pure text)
575
     * @param string $newContent           Content of the announcement (can be HTML)
576
     * @param array  $sentTo               Array of users and groups to send the announcement to
577
     * @param array  $file                 uploaded file $_FILES
578
     * @param string $file_comment         Comment describing the attachment
579
     * @param string $end_date
580
     * @param bool   $sendToUsersInSession
581
     * @param int    $authorId
582
     *
583
     * @return int false on failure, ID of the announcement on success
584
     */
585
    public static function add_announcement(
586
        $courseInfo,
587
        $sessionId,
588
        $title,
589
        $newContent,
590
        $sentTo,
591
        $file = [],
592
        $file_comment = null,
593
        $end_date = null,
594
        $sendToUsersInSession = false,
595
        $authorId = 0
596
    ) {
597
        if (empty($courseInfo)) {
598
            return false;
599
        }
600
601
        if (!isset($courseInfo['real_id'])) {
602
            return false;
603
        }
604
605
        $courseId = $courseInfo['real_id'];
606
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
607
        $authorId = empty($authorId) ? api_get_user_id() : $authorId;
608
609
        if (empty($end_date)) {
610
            $end_date = api_get_utc_datetime();
611
        }
612
613
        $order = self::getLastAnnouncementOrder($courseInfo);
614
615
        // store in the table announcement
616
        $params = [
617
            'c_id' => $courseId,
618
            'content' => $newContent,
619
            'title' => $title,
620
            'end_date' => $end_date,
621
            'display_order' => $order,
622
            'session_id' => (int) $sessionId,
623
        ];
624
625
        $last_id = Database::insert($tbl_announcement, $params);
626
627
        if (empty($last_id)) {
628
            return false;
629
        } else {
630
            $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
631
            Database::query($sql);
632
633
            if (!empty($file)) {
634
                self::add_announcement_attachment_file(
635
                    $last_id,
636
                    $file_comment,
637
                    $_FILES['user_upload']
638
                );
639
            }
640
641
            // store in item_property (first the groups, then the users
642
            if (empty($sentTo) ||
643
                (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')
644
            ) {
645
                // The message is sent to EVERYONE, so we set the group to 0
646
                api_item_property_update(
647
                    $courseInfo,
648
                    TOOL_ANNOUNCEMENT,
649
                    $last_id,
650
                    'AnnouncementAdded',
651
                    $authorId,
652
                    '0',
653
                    null,
654
                    null,
655
                    null,
656
                    $sessionId
657
                );
658
            } else {
659
                $send_to = CourseManager::separateUsersGroups($sentTo);
660
                $batchSize = 20;
661
                $em = Database::getManager();
662
                // Storing the selected groups
663
                if (is_array($send_to['groups']) &&
664
                    !empty($send_to['groups'])
665
                ) {
666
                    $counter = 1;
667
                    foreach ($send_to['groups'] as $group) {
668
                        $groupInfo = GroupManager::get_group_properties($group);
669
                        api_item_property_update(
670
                            $courseInfo,
671
                            TOOL_ANNOUNCEMENT,
672
                            $last_id,
673
                            'AnnouncementAdded',
674
                            $authorId,
675
                            $groupInfo
676
                        );
677
678
                        if (($counter % $batchSize) === 0) {
679
                            $em->flush();
680
                            $em->clear();
681
                        }
682
                        $counter++;
683
                    }
684
                }
685
686
                // Storing the selected users
687
                if (is_array($send_to['users'])) {
688
                    $counter = 1;
689
                    foreach ($send_to['users'] as $user) {
690
                        api_item_property_update(
691
                            $courseInfo,
692
                            TOOL_ANNOUNCEMENT,
693
                            $last_id,
694
                            'AnnouncementAdded',
695
                            $authorId,
696
                            '',
697
                            $user
698
                        );
699
700
                        if (($counter % $batchSize) === 0) {
701
                            $em->flush();
702
                            $em->clear();
703
                        }
704
                        $counter++;
705
                    }
706
                }
707
            }
708
709
            if ($sendToUsersInSession) {
710
                self::addAnnouncementToAllUsersInSessions($last_id);
711
            }
712
713
            return $last_id;
714
        }
715
    }
716
717
    /**
718
     * @param string $title
719
     * @param string $newContent
720
     * @param int    $groupId
721
     * @param array  $to_users
722
     * @param array  $file
723
     * @param string $file_comment
724
     * @param bool   $sendToUsersInSession
725
     *
726
     * @return bool|int
727
     */
728
    public static function addGroupAnnouncement(
729
        $title,
730
        $newContent,
731
        $groupId,
732
        $to_users,
733
        $file = [],
734
        $file_comment = '',
735
        $sendToUsersInSession = false
736
    ) {
737
        $courseInfo = api_get_course_info();
738
739
        // Database definitions
740
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
741
        $order = self::getLastAnnouncementOrder($courseInfo);
742
743
        $now = api_get_utc_datetime();
744
        $courseId = api_get_course_int_id();
745
746
        // store in the table announcement
747
        $params = [
748
            'c_id' => $courseId,
749
            'content' => $newContent,
750
            'title' => $title,
751
            'end_date' => $now,
752
            'display_order' => $order,
753
            'session_id' => api_get_session_id(),
754
        ];
755
756
        $last_id = Database::insert($table, $params);
757
758
        // Store the attach file
759
        if ($last_id) {
760
            $sql = "UPDATE $table SET id = iid
761
                    WHERE iid = $last_id";
762
            Database::query($sql);
763
764
            if (!empty($file)) {
765
                self::add_announcement_attachment_file(
766
                    $last_id,
767
                    $file_comment,
768
                    $file
769
                );
770
            }
771
772
            $send_to_users = CourseManager::separateUsersGroups($to_users);
773
774
            // if nothing was selected in the menu then send to all the group
775
            $sentToAllGroup = false;
776
            if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
777
                $groupInfo = GroupManager::get_group_properties($groupId);
778
                api_item_property_update(
779
                    $courseInfo,
780
                    TOOL_ANNOUNCEMENT,
781
                    $last_id,
782
                    'AnnouncementAdded',
783
                    api_get_user_id(),
784
                    $groupInfo
785
                );
786
                $sentToAllGroup = true;
787
            }
788
789
            if ($sentToAllGroup === false) {
790
                if (!empty($send_to_users['groups'])) {
791
                    foreach ($send_to_users['groups'] as $group) {
792
                        $groupInfo = GroupManager::get_group_properties($group);
793
                        api_item_property_update(
794
                            $courseInfo,
795
                            TOOL_ANNOUNCEMENT,
796
                            $last_id,
797
                            'AnnouncementAdded',
798
                            api_get_user_id(),
799
                            $groupInfo
800
                        );
801
                    }
802
                }
803
804
                $groupInfo = GroupManager::get_group_properties($groupId);
805
                if (!empty($send_to_users['users'])) {
806
                    foreach ($send_to_users['users'] as $user) {
807
                        api_item_property_update(
808
                            $courseInfo,
809
                            TOOL_ANNOUNCEMENT,
810
                            $last_id,
811
                            'AnnouncementAdded',
812
                            api_get_user_id(),
813
                            $groupInfo,
814
                            $user
815
                        );
816
                    }
817
                }
818
            }
819
820
            if ($sendToUsersInSession) {
821
                self::addAnnouncementToAllUsersInSessions($last_id);
822
            }
823
        }
824
825
        return $last_id;
826
    }
827
828
    /**
829
     * This function stores the announcement item in the announcement table
830
     * and updates the item_property table.
831
     *
832
     * @param int    $id                   id of the announcement
833
     * @param string $title
834
     * @param string $newContent
835
     * @param array  $to                   users that will receive the announcement
836
     * @param mixed  $file                 attachment
837
     * @param string $file_comment         file comment
838
     * @param bool   $sendToUsersInSession
839
     */
840
    public static function edit_announcement(
841
        $id,
842
        $title,
843
        $newContent,
844
        $to,
845
        $file = [],
846
        $file_comment = '',
847
        $sendToUsersInSession = false
848
    ) {
849
        $courseInfo = api_get_course_info();
850
        $courseId = api_get_course_int_id();
851
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
852
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
853
        $id = (int) $id;
854
855
        $params = [
856
            'title' => $title,
857
            'content' => $newContent,
858
        ];
859
860
        Database::update(
861
            $table,
862
            $params,
863
            ['c_id = ? AND id = ?' => [$courseId, $id]]
864
        );
865
866
        // save attachment file
867
        $row_attach = self::get_attachment($id);
868
869
        $id_attach = 0;
870
        if ($row_attach) {
871
            $id_attach = (int) $row_attach['id'];
872
        }
873
874
        if (!empty($file)) {
875
            if (empty($id_attach)) {
876
                self::add_announcement_attachment_file(
877
                    $id,
878
                    $file_comment,
879
                    $file
880
                );
881
            } else {
882
                self::edit_announcement_attachment_file(
883
                    $id_attach,
884
                    $file,
885
                    $file_comment
886
                );
887
            }
888
        }
889
890
        // We remove everything from item_property for this
891
        $sql = "DELETE FROM $tbl_item_property
892
                WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
893
        Database::query($sql);
894
895
        if ($sendToUsersInSession) {
896
            self::addAnnouncementToAllUsersInSessions($id);
897
        }
898
899
        // store in item_property (first the groups, then the users
900
        if (!empty($to)) {
901
            // !is_null($to): when no user is selected we send it to everyone
902
            $send_to = CourseManager::separateUsersGroups($to);
903
904
            // storing the selected groups
905
            if (is_array($send_to['groups'])) {
906
                foreach ($send_to['groups'] as $group) {
907
                    $groupInfo = GroupManager::get_group_properties($group);
908
                    if (empty($groupInfo)) {
909
                        // Probably the group id and iid are different try checking the iid
910
                        $groupInfo = GroupManager::get_group_properties($group, true);
911
                    }
912
                    if ($groupInfo) {
913
                        api_item_property_update(
914
                            $courseInfo,
915
                            TOOL_ANNOUNCEMENT,
916
                            $id,
917
                            'AnnouncementUpdated',
918
                            api_get_user_id(),
919
                            $groupInfo
920
                        );
921
                    }
922
                }
923
            }
924
925
            // storing the selected users
926
            if (is_array($send_to['users'])) {
927
                foreach ($send_to['users'] as $user) {
928
                    api_item_property_update(
929
                        $courseInfo,
930
                        TOOL_ANNOUNCEMENT,
931
                        $id,
932
                        'AnnouncementUpdated',
933
                        api_get_user_id(),
934
                        0,
935
                        $user
936
                    );
937
                }
938
            }
939
940
            // Send to everyone
941
            if (isset($to[0]) && $to[0] === 'everyone') {
942
                api_item_property_update(
943
                    $courseInfo,
944
                    TOOL_ANNOUNCEMENT,
945
                    $id,
946
                    'AnnouncementUpdated',
947
                    api_get_user_id(),
948
                    0
949
                );
950
            }
951
        } else {
952
            // the message is sent to everyone, so we set the group to 0
953
            api_item_property_update(
954
                $courseInfo,
955
                TOOL_ANNOUNCEMENT,
956
                $id,
957
                'AnnouncementUpdated',
958
                api_get_user_id(),
959
                0
960
            );
961
        }
962
    }
963
964
    /**
965
     * @param int $announcementId
966
     */
967
    public static function addAnnouncementToAllUsersInSessions($announcementId)
968
    {
969
        $courseCode = api_get_course_id();
970
        $courseInfo = api_get_course_info();
971
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
972
973
        if (!empty($sessionList)) {
974
            foreach ($sessionList as $sessionInfo) {
975
                $sessionId = $sessionInfo['id'];
976
                $userList = CourseManager::get_user_list_from_course_code(
977
                    $courseCode,
978
                    $sessionId
979
                );
980
981
                if (!empty($userList)) {
982
                    foreach ($userList as $user) {
983
                        api_item_property_update(
984
                            $courseInfo,
985
                            TOOL_ANNOUNCEMENT,
986
                            $announcementId,
987
                            'AnnouncementUpdated',
988
                            api_get_user_id(),
989
                            0,
990
                            $user['user_id'],
991
                            0,
992
                            0,
993
                            $sessionId
994
                        );
995
                    }
996
                }
997
            }
998
        }
999
    }
1000
1001
    /**
1002
     * @param int $insert_id
1003
     *
1004
     * @return bool
1005
     */
1006
    public static function update_mail_sent($insert_id)
1007
    {
1008
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1009
        if ($insert_id != strval(intval($insert_id))) {
1010
            return false;
1011
        }
1012
        $insert_id = intval($insert_id);
1013
        $courseId = api_get_course_int_id();
1014
        // store the modifications in the table tbl_annoucement
1015
        $sql = "UPDATE $table SET email_sent='1'
1016
                WHERE c_id = $courseId AND id = $insert_id";
1017
        Database::query($sql);
1018
    }
1019
1020
    /**
1021
     * @param int $user_id
1022
     *
1023
     * @return array|bool
1024
     */
1025
    public static function getAnnoucementCourseTotalByUser($user_id)
1026
    {
1027
        $user_id = (int) $user_id;
1028
1029
        if (empty($user_id)) {
1030
            return false;
1031
        }
1032
1033
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1034
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1035
1036
        $sql = "SELECT DISTINCT
1037
                    announcement.c_id,
1038
                    count(announcement.id) count
1039
                FROM $tbl_announcement announcement
1040
                INNER JOIN $tbl_item_property ip
1041
                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1042
                WHERE
1043
                    ip.tool='announcement' AND
1044
                    (
1045
                      ip.to_user_id = '$user_id' AND
1046
                      (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1047
                    )
1048
                    AND ip.visibility='1'
1049
                    AND announcement.session_id  = 0
1050
                GROUP BY announcement.c_id";
1051
        $rs = Database::query($sql);
1052
        $num_rows = Database::num_rows($rs);
1053
        $result = [];
1054
        if ($num_rows > 0) {
1055
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1056
                if (empty($row['c_id'])) {
1057
                    continue;
1058
                }
1059
                $result[] = ['course' => api_get_course_info_by_id($row['c_id']), 'count' => $row['count']];
1060
            }
1061
        }
1062
1063
        return $result;
1064
    }
1065
1066
    /**
1067
     * Returns announcement info from its id.
1068
     *
1069
     * @param int $courseId
1070
     * @param int $id
1071
     *
1072
     * @return array
1073
     */
1074
    public static function get_by_id($courseId, $id)
1075
    {
1076
        $id = (int) $id;
1077
        $courseId = $courseId ? (int) $courseId : api_get_course_int_id();
1078
1079
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1080
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1081
1082
        $sql = "SELECT DISTINCT
1083
                    announcement.id,
1084
                    announcement.title,
1085
                    announcement.content,
1086
                    ip.to_group_id
1087
               FROM $tbl_announcement announcement
1088
               INNER JOIN $tbl_item_property ip
1089
               ON
1090
                    announcement.id = ip.ref AND
1091
                    announcement.c_id = ip.c_id
1092
               WHERE
1093
                    announcement.c_id = $courseId AND
1094
                    ip.tool='announcement' AND
1095
                    announcement.id = $id
1096
                ";
1097
1098
        $result = Database::query($sql);
1099
        if (Database::num_rows($result)) {
1100
            return Database::fetch_array($result);
1101
        }
1102
1103
        return [];
1104
    }
1105
1106
    /**
1107
     * this function gets all the groups of the course,
1108
     * not including linked courses.
1109
     */
1110
    public static function get_course_groups()
1111
    {
1112
        $session_id = api_get_session_id();
1113
        if ($session_id != 0) {
1114
            $new_group_list = CourseManager::get_group_list_of_course(
1115
                api_get_course_id(),
1116
                $session_id,
1117
                1
1118
            );
1119
        } else {
1120
            $new_group_list = CourseManager::get_group_list_of_course(
1121
                api_get_course_id(),
1122
                0,
1123
                1
1124
            );
1125
        }
1126
1127
        return $new_group_list;
1128
    }
1129
1130
    /**
1131
     * This tools loads all the users and all the groups who have received
1132
     * a specific item (in this case an announcement item).
1133
     *
1134
     * @param string $tool
1135
     * @param int    $id
1136
     * @param bool   $includeGroupWhenLoadingUser
1137
     *
1138
     * @return array
1139
     */
1140
    public static function loadEditUsers($tool, $id, $includeGroupWhenLoadingUser = false)
1141
    {
1142
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1143
        $tool = Database::escape_string($tool);
1144
        $id = (int) $id;
1145
        $courseId = api_get_course_int_id();
1146
        $groupId = api_get_group_id();
1147
1148
        $sql = "SELECT to_user_id, to_group_id FROM $table
1149
                WHERE c_id = $courseId AND tool='$tool' AND ref = $id";
1150
1151
        $result = Database::query($sql);
1152
        $to = [];
1153
        while ($row = Database::fetch_array($result)) {
1154
            // This is the iid of c_group_info
1155
            $toGroup = $row['to_group_id'];
1156
            if (empty($row['to_user_id']) && !empty($groupId) && $groupId != $toGroup) {
1157
                //continue;
1158
            }
1159
            switch ($toGroup) {
1160
                // it was send to one specific user
1161
                case null:
1162
                    if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
1163
                        if (!in_array('USER:'.$row['to_user_id'], $to)) {
1164
                            $to[] = 'USER:'.$row['to_user_id'];
1165
                        }
1166
                    }
1167
                    break;
1168
                // it was sent to everyone
1169
                case 0:
1170
                    return 'everyone';
1171
                    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...
1172
                default:
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
                    } else {
1178
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1179
                            $to[] = 'GROUP:'.$toGroup;
1180
                        }
1181
                    }
1182
1183
                    if ($includeGroupWhenLoadingUser) {
1184
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1185
                            $to[] = 'GROUP:'.$toGroup;
1186
                        }
1187
                    }
1188
                    break;
1189
            }
1190
        }
1191
1192
        return $to;
1193
    }
1194
1195
    /**
1196
     * constructs the form to display all the groups and users the message has been sent to.
1197
     *
1198
     * @param array $sent_to_array
1199
     *                             input:
1200
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1201
     *                             the first level is a distinction between groups and users:
1202
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1203
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1204
     *                             containing all the id's of the groups (resp. users) who have received this message.
1205
     *
1206
     * @return string
1207
     *
1208
     * @author Patrick Cool <patrick.cool@>
1209
     */
1210
    public static function sent_to_form($sent_to_array)
1211
    {
1212
        // we find all the names of the groups
1213
        $group_names = self::get_course_groups();
1214
1215
        // we count the number of users and the number of groups
1216
        $number_users = 0;
1217
        if (isset($sent_to_array['users'])) {
1218
            $number_users = count($sent_to_array['users']);
1219
        }
1220
        $number_groups = 0;
1221
        if (isset($sent_to_array['groups'])) {
1222
            $number_groups = count($sent_to_array['groups']);
1223
        }
1224
1225
        $total_numbers = $number_users + $number_groups;
1226
1227
        // starting the form if there is more than one user/group
1228
        $output = [];
1229
        if ($total_numbers > 1) {
1230
            // outputting the name of the groups
1231
            if (is_array($sent_to_array['groups'])) {
1232
                foreach ($sent_to_array['groups'] as $group_id) {
1233
                    $users = GroupManager::getStudents($group_id, true);
1234
                    $userToArray = [];
1235
                    foreach ($users as $student) {
1236
                        $userToArray[] = $student['complete_name_with_username'];
1237
                    }
1238
                    $output[] =
1239
                        '<br />'.
1240
                        Display::label($group_names[$group_id]['name'], 'info').
1241
                        '&nbsp;'.implode(', ', $userToArray);
1242
                }
1243
            }
1244
1245
            if (isset($sent_to_array['users'])) {
1246
                if (is_array($sent_to_array['users'])) {
1247
                    $usersToArray = [];
1248
                    foreach ($sent_to_array['users'] as $user_id) {
1249
                        $user_info = api_get_user_info($user_id);
1250
                        $usersToArray[] = $user_info['complete_name_with_username'];
1251
                    }
1252
                    $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
1253
                }
1254
            }
1255
        } else {
1256
            // there is only one user/group
1257
            if (isset($sent_to_array['users']) && is_array($sent_to_array['users'])) {
1258
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1259
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1260
            }
1261
            if (isset($sent_to_array['groups']) &&
1262
                is_array($sent_to_array['groups']) &&
1263
                isset($sent_to_array['groups'][0]) &&
1264
                $sent_to_array['groups'][0] !== 0
1265
            ) {
1266
                $group_id = $sent_to_array['groups'][0];
1267
1268
                $users = GroupManager::getStudents($group_id, true);
1269
                $userToArray = [];
1270
                foreach ($users as $student) {
1271
                    $userToArray[] = $student['complete_name_with_username'];
1272
                }
1273
                $output[] =
1274
                    '<br />'.
1275
                    Display::label($group_names[$group_id]['name'], 'info').
1276
                    '&nbsp;'.implode(', ', $userToArray);
1277
            }
1278
            if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
1279
                $output[] = "&nbsp;".get_lang('Everybody');
1280
            }
1281
        }
1282
1283
        if (!empty($output)) {
1284
            $output = array_filter($output);
1285
            if (count($output) > 0) {
1286
                $output = implode('<br />', $output);
1287
            }
1288
1289
            return $output;
1290
        }
1291
    }
1292
1293
    /**
1294
     * Returns all the users and all the groups a specific announcement item
1295
     * has been sent to.
1296
     *
1297
     * @param    string  The tool (announcement, agenda, ...)
1298
     * @param    int     ID of the element of the corresponding type
1299
     *
1300
     * @return array Array of users and groups to whom the element has been sent
1301
     */
1302
    public static function sent_to($tool, $id)
1303
    {
1304
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1305
        $tool = Database::escape_string($tool);
1306
        $id = (int) $id;
1307
1308
        $sent_to_group = [];
1309
        $sent_to = [];
1310
        $courseId = api_get_course_int_id();
1311
1312
        $sql = "SELECT to_group_id, to_user_id
1313
                FROM $table
1314
                WHERE c_id = $courseId AND tool = '$tool' AND ref=".$id;
1315
        $result = Database::query($sql);
1316
1317
        while ($row = Database::fetch_array($result)) {
1318
            // if to_user_id <> 0 then it is sent to a specific user
1319
            if ($row['to_user_id'] != 0) {
1320
                $sent_to_user[] = $row['to_user_id'];
1321
                continue;
1322
            }
1323
1324
            // if to_group_id is null then it is sent to a specific user
1325
            // if to_group_id = 0 then it is sent to everybody
1326
            if ($row['to_group_id'] != 0) {
1327
                $sent_to_group[] = $row['to_group_id'];
1328
            }
1329
        }
1330
1331
        if (isset($sent_to_group)) {
1332
            $sent_to['groups'] = $sent_to_group;
1333
        }
1334
1335
        if (isset($sent_to_user)) {
1336
            $sent_to['users'] = $sent_to_user;
1337
        }
1338
1339
        return $sent_to;
1340
    }
1341
1342
    /**
1343
     * Show a list with all the attachments according to the post's id.
1344
     *
1345
     * @param int $announcementId
1346
     *
1347
     * @return array with the post info
1348
     *
1349
     * @author Arthur Portugal
1350
     *
1351
     * @version November 2009, dokeos 1.8.6.2
1352
     */
1353
    public static function get_attachment($announcementId)
1354
    {
1355
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1356
        $announcementId = (int) $announcementId;
1357
        $courseId = api_get_course_int_id();
1358
        $row = [];
1359
        $sql = 'SELECT id, path, filename, comment
1360
                FROM '.$table.'
1361
				WHERE c_id = '.$courseId.' AND announcement_id = '.$announcementId;
1362
        $result = Database::query($sql);
1363
        if (Database::num_rows($result) != 0) {
1364
            $row = Database::fetch_array($result, 'ASSOC');
1365
        }
1366
1367
        return $row;
1368
    }
1369
1370
    /**
1371
     * This function add a attachment file into announcement.
1372
     *
1373
     * @param int  announcement id
1374
     * @param string file comment
1375
     * @param array  uploaded file $_FILES
1376
     *
1377
     * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
1378
     */
1379
    public static function add_announcement_attachment_file(
1380
        $announcement_id,
1381
        $file_comment,
1382
        $file
1383
    ) {
1384
        $courseInfo = api_get_course_info();
1385
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1386
        $return = 0;
1387
        $announcement_id = intval($announcement_id);
1388
        $courseId = api_get_course_int_id();
1389
1390
        if (is_array($file) && $file['error'] == 0) {
1391
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1392
            $courseDir = $courseInfo['path'].'/upload/announcements';
1393
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1394
            $updir = $sys_course_path.$courseDir;
1395
1396
            // Try to add an extension to the file if it hasn't one
1397
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1398
            // user's file name
1399
            $file_name = $file['name'];
1400
1401
            if (!filter_extension($new_file_name)) {
1402
                $return = -1;
1403
                echo Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error');
1404
            } else {
1405
                $new_file_name = uniqid('');
1406
                $new_path = $updir.'/'.$new_file_name;
1407
1408
                // This file is copy here but its cleaned in api_mail_html in api.lib.php
1409
                copy($file['tmp_name'], $new_path);
1410
1411
                $params = [
1412
                    'c_id' => $courseId,
1413
                    'filename' => $file_name,
1414
                    'comment' => $file_comment,
1415
                    'path' => $new_file_name,
1416
                    'announcement_id' => $announcement_id,
1417
                    'size' => (int) $file['size'],
1418
                ];
1419
1420
                $insertId = Database::insert($table, $params);
1421
                if ($insertId) {
1422
                    $sql = "UPDATE $table SET id = iid
1423
                            WHERE iid = $insertId";
1424
                    Database::query($sql);
1425
                }
1426
1427
                $return = 1;
1428
            }
1429
        }
1430
1431
        return $return;
1432
    }
1433
1434
    /**
1435
     * This function edit a attachment file into announcement.
1436
     *
1437
     * @param int attach id
1438
     * @param array uploaded file $_FILES
1439
     * @param string file comment
1440
     *
1441
     * @return int
1442
     */
1443
    public static function edit_announcement_attachment_file(
1444
        $id_attach,
1445
        $file,
1446
        $file_comment
1447
    ) {
1448
        $courseInfo = api_get_course_info();
1449
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1450
        $return = 0;
1451
        $courseId = api_get_course_int_id();
1452
1453
        if (is_array($file) && $file['error'] == 0) {
1454
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1455
            $courseDir = $courseInfo['path'].'/upload/announcements';
1456
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1457
            $updir = $sys_course_path.$courseDir;
1458
1459
            // Try to add an extension to the file if it hasn't one
1460
            $new_file_name = add_ext_on_mime(
1461
                stripslashes($file['name']),
1462
                $file['type']
1463
            );
1464
            // user's file name
1465
            $file_name = $file['name'];
1466
1467
            if (!filter_extension($new_file_name)) {
1468
                $return = -1;
1469
                echo Display::return_message(
1470
                    get_lang('UplUnableToSaveFileFilteredExtension'),
1471
                    'error'
1472
                );
1473
            } else {
1474
                $new_file_name = uniqid('');
1475
                $new_path = $updir.'/'.$new_file_name;
1476
                copy($file['tmp_name'], $new_path);
1477
                $safe_file_comment = Database::escape_string($file_comment);
1478
                $safe_file_name = Database::escape_string($file_name);
1479
                $safe_new_file_name = Database::escape_string($new_file_name);
1480
                $id_attach = intval($id_attach);
1481
                $sql = "UPDATE $table SET
1482
                            filename = '$safe_file_name',
1483
                            comment = '$safe_file_comment',
1484
                            path = '$safe_new_file_name',
1485
                            size ='".intval($file['size'])."'
1486
					 	WHERE c_id = $courseId AND id = '$id_attach'";
1487
                $result = Database::query($sql);
1488
                if ($result === false) {
1489
                    $return = -1;
1490
                    echo Display::return_message(
1491
                        get_lang('UplUnableToSaveFile'),
1492
                        'error'
1493
                    );
1494
                } else {
1495
                    $return = 1;
1496
                }
1497
            }
1498
        }
1499
1500
        return $return;
1501
    }
1502
1503
    /**
1504
     * This function delete a attachment file by id.
1505
     *
1506
     * @param int $id attachment file Id
1507
     *
1508
     * @return bool
1509
     */
1510
    public static function delete_announcement_attachment_file($id)
1511
    {
1512
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1513
        $id = intval($id);
1514
        $courseId = api_get_course_int_id();
1515
        if (empty($courseId) || empty($id)) {
1516
            return false;
1517
        }
1518
        $sql = "DELETE FROM $table
1519
                WHERE c_id = $courseId AND id = $id";
1520
        Database::query($sql);
1521
1522
        return true;
1523
    }
1524
1525
    /**
1526
     * @param array $courseInfo
1527
     * @param int   $sessionId
1528
     * @param int   $announcementId
1529
     * @param bool  $sendToUsersInSession
1530
     * @param bool  $sendToDrhUsers
1531
     * @param Monolog\Handler\HandlerInterface logger
1532
     * @param int  $senderId
1533
     * @param bool $directMessage
1534
     *
1535
     * @return array
1536
     */
1537
    public static function sendEmail(
1538
        $courseInfo,
1539
        $sessionId,
1540
        $announcementId,
1541
        $sendToUsersInSession = false,
1542
        $sendToDrhUsers = false,
1543
        $logger = null,
1544
        $senderId = 0,
1545
        $directMessage = false
1546
    ) {
1547
        $email = new AnnouncementEmail($courseInfo, $sessionId, $announcementId, $logger);
1548
1549
        return $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId, $directMessage);
1550
    }
1551
1552
    /**
1553
     * @param $stok
1554
     * @param $announcement_number
1555
     * @param bool   $getCount
1556
     * @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...
1557
     * @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...
1558
     * @param string $sidx
1559
     * @param string $sord
1560
     * @param string $titleToSearch
1561
     * @param int    $userIdToSearch
1562
     * @param int    $userId
1563
     * @param int    $courseId
1564
     * @param int    $sessionId
1565
     *
1566
     * @return array
1567
     */
1568
    public static function getAnnouncements(
1569
        $stok,
1570
        $announcement_number,
1571
        $getCount = false,
1572
        $start = null,
1573
        $limit = null,
1574
        $sidx = '',
1575
        $sord = '',
1576
        $titleToSearch = '',
1577
        $userIdToSearch = 0,
1578
        $userId = 0,
1579
        $courseId = 0,
1580
        $sessionId = 0
1581
    ) {
1582
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1583
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1584
1585
        $user_id = $userId ?: api_get_user_id();
1586
        $group_id = api_get_group_id();
1587
        $session_id = $sessionId ?: api_get_session_id();
1588
        if (empty($courseId)) {
1589
            $courseInfo = api_get_course_info();
1590
            $courseId = $courseInfo['real_id'];
1591
        } else {
1592
            $courseId = (int) $courseId;
1593
            $courseInfo = api_get_course_info_by_id($courseId);
1594
        }
1595
1596
        if (empty($courseInfo)) {
1597
            return [];
1598
        }
1599
1600
        $condition_session = api_get_session_condition(
1601
            $session_id,
1602
            true,
1603
            true,
1604
            'announcement.session_id'
1605
        );
1606
1607
        $group_memberships = GroupManager::get_group_ids(
1608
            $courseId,
1609
            api_get_user_id()
1610
        );
1611
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1612
1613
        $select = ' DISTINCT
1614
                        announcement.*,
1615
                        ip.visibility,
1616
                        ip.to_group_id,
1617
                        ip.insert_user_id,
1618
                        ip.insert_date,
1619
                        ip.lastedit_date';
1620
        $groupBy = ' GROUP BY announcement.iid';
1621
        if ($getCount) {
1622
            $groupBy = '';
1623
            $select = ' COUNT(DISTINCT announcement.iid) count';
1624
        }
1625
1626
        $searchCondition = '';
1627
        if (!empty($titleToSearch)) {
1628
            $titleToSearch = Database::escape_string($titleToSearch);
1629
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1630
        }
1631
1632
        if (!empty($userIdToSearch)) {
1633
            $userIdToSearch = (int) $userIdToSearch;
1634
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1635
        }
1636
1637
        $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
1638
        $extraGroupCondition = '';
1639
        if ($allowOnlyGroup) {
1640
            $extraGroupCondition = " AND ip.to_group_id = $group_id ";
1641
        }
1642
1643
        $allowDrhAccess = api_get_configuration_value('allow_drh_access_announcement');
1644
1645
        if ($allowDrhAccess && api_is_drh()) {
1646
            // DRH only can see visible
1647
            $searchCondition .= ' AND (ip.visibility = 1)';
1648
        }
1649
1650
        if (api_is_allowed_to_edit(false, true) ||
1651
            ($allowUserEditSetting && !api_is_anonymous()) ||
1652
            ($allowDrhAccess && api_is_drh())
1653
        ) {
1654
            // A.1. you are a course admin with a USER filter
1655
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1656
            //if (!empty($user_id)) {
1657
            if (0) {
1658
                if (is_array($group_memberships) &&
1659
                    count($group_memberships) > 0
1660
                ) {
1661
                    $sql = "SELECT $select
1662
                            FROM $tbl_announcement announcement
1663
                            INNER JOIN $tbl_item_property ip
1664
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1665
                            WHERE
1666
                                announcement.c_id = $courseId AND
1667
                                ip.c_id = $courseId AND
1668
                                ip.tool = 'announcement' AND
1669
                                (
1670
                                    ip.to_user_id = $user_id OR
1671
                                    ip.to_group_id IS NULL OR
1672
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1673
                                ) AND
1674
                                ip.visibility IN ('1', '0')
1675
                                $condition_session
1676
                                $searchCondition
1677
                            ORDER BY display_order DESC";
1678
                } else {
1679
                    $sql = "SELECT $select
1680
                            FROM $tbl_announcement announcement
1681
                            INNER JOIN $tbl_item_property ip
1682
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1683
                            WHERE
1684
                                announcement.c_id = $courseId AND
1685
                                ip.c_id = $courseId AND
1686
                                ip.tool ='announcement' AND
1687
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1688
                                ip.visibility IN ('1', '0')
1689
                            $condition_session
1690
                            $searchCondition
1691
                            ORDER BY display_order DESC";
1692
                }
1693
            } elseif ($group_id != 0) {
1694
                // A.2. you are a course admin with a GROUP filter
1695
                // => see only the messages of this specific group
1696
                $sql = "SELECT $select
1697
                        FROM $tbl_announcement announcement
1698
                        INNER JOIN $tbl_item_property ip
1699
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1700
                        WHERE
1701
                            ip.tool='announcement' AND
1702
                            announcement.c_id = $courseId AND
1703
                            ip.c_id = $courseId AND
1704
                            ip.visibility<>'2' AND
1705
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1706
                            $condition_session
1707
                            $searchCondition
1708
                            $extraGroupCondition
1709
                        $groupBy
1710
                        ORDER BY display_order DESC";
1711
            } else {
1712
                // A.3 you are a course admin without any group or user filter
1713
                // A.3.a you are a course admin without user or group filter but WITH studentview
1714
                // => see all the messages of all the users and groups without editing possibilities
1715
                if (isset($isStudentView) && $isStudentView == 'true') {
1716
                    $sql = "SELECT $select
1717
                            FROM $tbl_announcement announcement
1718
                            INNER JOIN $tbl_item_property ip
1719
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1720
                            WHERE
1721
                                ip.tool='announcement' AND
1722
                                announcement.c_id = $courseId AND
1723
                                ip.c_id = $courseId AND
1724
                                ip.visibility='1'
1725
                                $condition_session
1726
                                $searchCondition
1727
                            $groupBy
1728
                            ORDER BY display_order DESC";
1729
                } else {
1730
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1731
                    // => see all the messages of all the users and groups with editing possibilities
1732
                    $sql = "SELECT $select
1733
                            FROM $tbl_announcement announcement
1734
                            INNER JOIN $tbl_item_property ip
1735
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1736
                            WHERE
1737
                                ip.tool = 'announcement' AND
1738
                                announcement.c_id = $courseId AND
1739
                                ip.c_id = $courseId  AND
1740
                                (ip.visibility='0' OR ip.visibility='1')
1741
                                $condition_session
1742
                                $searchCondition
1743
                            $groupBy
1744
                            ORDER BY display_order DESC";
1745
                }
1746
            }
1747
        } else {
1748
            // STUDENT
1749
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1750
                if ($allowUserEditSetting && !api_is_anonymous()) {
1751
                    if ($group_id == 0) {
1752
                        // No group
1753
                        $cond_user_id = " AND (
1754
                            ip.lastedit_user_id = '".$user_id."' OR (
1755
                                (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
1756
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1757
                            )
1758
                        ) ";
1759
                    } else {
1760
                        $cond_user_id = " AND (
1761
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1762
                        )";
1763
                        $cond_user_id .= $extraGroupCondition;
1764
                    }
1765
                } else {
1766
                    if ($group_id == 0) {
1767
                        $cond_user_id = " AND (
1768
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1769
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1770
                        ) ";
1771
                    } else {
1772
                        $cond_user_id = " AND (
1773
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1774
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1775
                        )";
1776
                        $cond_user_id .= $extraGroupCondition;
1777
                    }
1778
                }
1779
1780
                $sql = "SELECT $select
1781
                        FROM $tbl_announcement announcement INNER JOIN
1782
                        $tbl_item_property ip
1783
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1784
                        WHERE
1785
                            announcement.c_id = $courseId AND
1786
                            ip.c_id = $courseId AND
1787
                            ip.tool='announcement'
1788
                            $cond_user_id
1789
                            $condition_session
1790
                            $searchCondition AND
1791
                            ip.visibility='1'
1792
                            $groupBy
1793
                        ORDER BY display_order DESC";
1794
            } else {
1795
                if ($user_id) {
1796
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1797
                        $cond_user_id = " AND (
1798
                                ip.lastedit_user_id = '".api_get_user_id()."' OR
1799
                                ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1800
                                (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1801
                            )
1802
                        ) ";
1803
                    } else {
1804
                        $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1805
                        (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1806
                    }
1807
1808
                    $sql = "SELECT $select
1809
						FROM $tbl_announcement announcement
1810
						INNER JOIN $tbl_item_property ip
1811
						ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1812
						WHERE
1813
    						announcement.c_id = $courseId AND
1814
							ip.c_id = $courseId AND
1815
    						ip.tool='announcement'
1816
    						$cond_user_id
1817
    						$condition_session
1818
    						$searchCondition
1819
    						AND ip.visibility='1'
1820
    						AND announcement.session_id IN(0, ".$session_id.")
1821
                        $groupBy
1822
						ORDER BY display_order DESC";
1823
                } else {
1824
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1825
                        $cond_user_id = " AND (
1826
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1827
                        )";
1828
                    } else {
1829
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1830
                    }
1831
1832
                    $sql = "SELECT $select
1833
                            FROM $tbl_announcement announcement
1834
                            INNER JOIN $tbl_item_property ip
1835
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1836
                            WHERE
1837
                                announcement.c_id = $courseId AND
1838
                                ip.c_id = $courseId AND
1839
                                ip.tool='announcement'
1840
                                $cond_user_id
1841
                                $condition_session
1842
                                $searchCondition  AND
1843
                                ip.visibility='1' AND
1844
                                announcement.session_id IN ( 0,".api_get_session_id().")
1845
                                $groupBy
1846
                            ";
1847
                }
1848
            }
1849
        }
1850
1851
        if (!is_null($start) && !is_null($limit)) {
1852
            $start = (int) $start;
1853
            $limit = (int) $limit;
1854
            $sql .= " LIMIT $start, $limit";
1855
        }
1856
1857
        $result = Database::query($sql);
1858
        if ($getCount) {
1859
            $result = Database::fetch_array($result, 'ASSOC');
1860
1861
            return $result['count'];
1862
        }
1863
1864
        $iterator = 1;
1865
        $bottomAnnouncement = $announcement_number;
1866
        $displayed = [];
1867
        $results = [];
1868
        $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('AnnounceSentByEmail').'"></i>';
1869
        $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
1870
1871
        $editIcon = Display::return_icon(
1872
            'edit.png',
1873
            get_lang('Edit'),
1874
            '',
1875
            ICON_SIZE_SMALL
1876
        );
1877
1878
        $editIconDisable = Display::return_icon(
1879
            'edit_na.png',
1880
            get_lang('Edit'),
1881
            '',
1882
            ICON_SIZE_SMALL
1883
        );
1884
        $deleteIcon = Display::return_icon(
1885
            'delete.png',
1886
            get_lang('Delete'),
1887
            '',
1888
            ICON_SIZE_SMALL
1889
        );
1890
1891
        $deleteIconDisable = Display::return_icon(
1892
            'delete_na.png',
1893
            get_lang('Delete'),
1894
            '',
1895
            ICON_SIZE_SMALL
1896
        );
1897
1898
        $isTutor = false;
1899
        if (!empty($group_id)) {
1900
            $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1901
            //User has access in the group?
1902
            $isTutor = GroupManager::is_tutor_of_group(
1903
                api_get_user_id(),
1904
                $groupInfo
1905
            );
1906
        }
1907
1908
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1909
            if (!in_array($row['id'], $displayed)) {
1910
                $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'
1911
                    .api_get_cidreq_params($courseInfo['code'], $session_id, $row['to_group_id']);
1912
1913
                $sent_to_icon = '';
1914
                // the email icon
1915
                if ($row['email_sent'] == '1') {
1916
                    $sent_to_icon = ' '.$emailIcon;
1917
                }
1918
1919
                $groupReference = $row['to_group_id'] > 0 ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
1920
                $disableEdit = false;
1921
                $to = self::loadEditUsers('announcement', $row['id'], true);
1922
                $separated = CourseManager::separateUsersGroups($to);
1923
                if (!empty($group_id)) {
1924
                    // If the announcement was sent to many groups, disable edition inside a group
1925
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1926
                        $disableEdit = true;
1927
                    }
1928
1929
                    // If the announcement was sent only to the course disable edition
1930
                    if (empty($separated['groups']) && empty($separated['users'])) {
1931
                        $disableEdit = true;
1932
                    }
1933
1934
                    // Announcement sent to only a user
1935
                    if ($separated['groups'] > 1 && !in_array($group_id, $separated['groups'])) {
1936
                        $disableEdit = true;
1937
                    }
1938
                } else {
1939
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1940
                        $groupReference = '';
1941
                    }
1942
                }
1943
1944
                $title = $row['title'].$groupReference.$sent_to_icon;
1945
                $item_visibility = api_get_item_visibility(
1946
                    $courseInfo,
1947
                    TOOL_ANNOUNCEMENT,
1948
                    $row['id'],
1949
                    $session_id
1950
                );
1951
                $row['visibility'] = $item_visibility;
1952
1953
                // show attachment list
1954
                $attachment_list = self::get_attachment($row['id']);
1955
                $attachment_icon = '';
1956
                if (count($attachment_list) > 0) {
1957
                    $attachment_icon = ' '.$attachmentIcon;
1958
                }
1959
1960
                /* TITLE */
1961
                $user_info = api_get_user_info($row['insert_user_id']);
1962
                $username = sprintf(get_lang('LoginX'), $user_info['username']);
1963
1964
                $username_span = Display::tag(
1965
                    'span',
1966
                    $user_info['complete_name'],
1967
                    ['title' => $username]
1968
                );
1969
1970
                $title = Display::url(
1971
                    $title.$attachment_icon,
1972
                    $actionUrl.'&action=view&id='.$row['id']
1973
                );
1974
1975
                // we can edit if : we are the teacher OR the element belongs to
1976
                // the session we are coaching OR the option to allow users to edit is on
1977
                if (api_is_allowed_to_edit(false, true) ||
1978
                    (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $row['id'])) ||
1979
                    (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
1980
                    ($row['to_group_id'] == $group_id && $isTutor)
1981
                ) {
1982
                    if ($disableEdit === true) {
1983
                        $modify_icons = "<a href='#'>".$editIconDisable."</a>";
1984
                    } else {
1985
                        $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$row['id']."\">".$editIcon."</a>";
1986
                    }
1987
1988
                    if ($row['visibility'] == 1) {
1989
                        $image_visibility = "visible";
1990
                        $alt_visibility = get_lang('Hide');
1991
                    } else {
1992
                        $image_visibility = "invisible";
1993
                        $alt_visibility = get_lang('Visible');
1994
                    }
1995
1996
                    $modify_icons .= "<a href=\"".$actionUrl."&action=showhide&id=".$row['id']."&sec_token=".$stok."\">".
1997
                        Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
1998
1999
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
2000
                    if ($iterator != 1) {
2001
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$row["id"]."&sec_token=".$stok."\">".
2002
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
2003
                    } else {
2004
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
2005
                    }
2006
                    if ($iterator < $bottomAnnouncement) {
2007
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$row["id"]."&sec_token=".$stok."\">".
2008
                            Display::return_icon('down.gif', get_lang('Down'))."</a>";
2009
                    } else {
2010
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
2011
                    }
2012
                    if (api_is_allowed_to_edit(false, true)) {
2013
                        if ($disableEdit === true) {
2014
                            $modify_icons .= Display::url($deleteIconDisable, '#');
2015
                        } else {
2016
                            $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$row['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
2017
                                    api_htmlentities(
2018
                                        get_lang('ConfirmYourChoice'),
2019
                                        ENT_QUOTES,
2020
                                        api_get_system_encoding()
2021
                                    )
2022
                                )."')) return false;\">".
2023
                                $deleteIcon."</a>";
2024
                        }
2025
                    }
2026
                    $iterator++;
2027
                } else {
2028
                    $modify_icons = Display::url(
2029
                        Display::return_icon('default.png'),
2030
                        $actionUrl.'&action=view&id='.$row['id']
2031
                    );
2032
                }
2033
2034
                $announcement = [
2035
                    'id' => $row['id'],
2036
                    'title' => $title,
2037
                    'username' => $username_span,
2038
                    'insert_date' => api_convert_and_format_date(
2039
                        $row['insert_date'],
2040
                        DATE_TIME_FORMAT_LONG
2041
                    ),
2042
                    'lastedit_date' => api_convert_and_format_date(
2043
                        $row['lastedit_date'],
2044
                        DATE_TIME_FORMAT_LONG
2045
                    ),
2046
                    'actions' => $modify_icons,
2047
                ];
2048
2049
                $results[] = $announcement;
2050
            }
2051
            $displayed[] = $row['id'];
2052
        }
2053
2054
        return $results;
2055
    }
2056
2057
    /**
2058
     * @return int
2059
     */
2060
    public static function getNumberAnnouncements()
2061
    {
2062
        // Maximum title messages to display
2063
        $maximum = '12';
2064
        // Database Table Definitions
2065
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
2066
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
2067
2068
        $session_id = api_get_session_id();
2069
        $courseInfo = api_get_course_info();
2070
        $courseId = $courseInfo['real_id'];
2071
        $userId = api_get_user_id();
2072
        $condition_session = api_get_session_condition(
2073
            $session_id,
2074
            true,
2075
            true,
2076
            'announcement.session_id'
2077
        );
2078
2079
        if (api_is_allowed_to_edit(false, true)) {
2080
            // check teacher status
2081
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2082
                if (api_get_group_id() == 0) {
2083
                    $group_condition = '';
2084
                } else {
2085
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
2086
                }
2087
2088
                $sql = "SELECT
2089
                            announcement.*,
2090
                            ip.visibility,
2091
                            ip.to_group_id,
2092
                            ip.insert_user_id
2093
                        FROM $tbl_announcement announcement
2094
                        INNER JOIN $tbl_item_property ip
2095
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2096
                        WHERE
2097
                            announcement.c_id = $courseId AND
2098
                            ip.c_id = $courseId AND
2099
                            ip.tool = 'announcement' AND
2100
                            ip.visibility <> '2'
2101
                            $group_condition
2102
                            $condition_session
2103
                        GROUP BY ip.ref
2104
                        ORDER BY display_order DESC
2105
                        LIMIT 0, $maximum";
2106
            }
2107
        } else {
2108
            // students only get to see the visible announcements
2109
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2110
                $group_memberships = GroupManager::get_group_ids(
2111
                    $courseInfo['real_id'],
2112
                    $userId
2113
                );
2114
2115
                if ((api_get_course_setting('allow_user_edit_announcement') &&
2116
                    !api_is_anonymous())
2117
                ) {
2118
                    if (api_get_group_id() == 0) {
2119
                        $cond_user_id = " AND (
2120
                        ip.lastedit_user_id = '".$userId."' OR (
2121
                            ip.to_user_id='".$userId."' OR
2122
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2123
                            ip.to_group_id IS NULL
2124
                            )
2125
                        )
2126
                        ";
2127
                    } else {
2128
                        $cond_user_id = " AND (
2129
                            ip.lastedit_user_id = '".$userId."'OR
2130
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2131
                            ip.to_group_id IS NULL
2132
                        )";
2133
                    }
2134
                } else {
2135
                    if (api_get_group_id() == 0) {
2136
                        $cond_user_id = " AND (
2137
                            ip.to_user_id='".$userId."' OR
2138
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2139
                            ip.to_group_id IS NULL
2140
                        ) ";
2141
                    } else {
2142
                        $cond_user_id = " AND (
2143
                            ip.to_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
                }
2149
2150
                // the user is member of several groups => display personal announcements AND
2151
                // his group announcements AND the general announcements
2152
                if (is_array($group_memberships) && count($group_memberships) > 0) {
2153
                    $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2154
                            FROM $tbl_announcement announcement
2155
                            INNER JOIN $tbl_item_property ip
2156
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2157
                            WHERE
2158
                                announcement.c_id = $courseId AND
2159
                                ip.c_id = $courseId AND
2160
                                ip.tool='announcement' AND
2161
                                ip.visibility='1'
2162
                                $cond_user_id
2163
                                $condition_session
2164
                            GROUP BY ip.ref
2165
                            ORDER BY display_order DESC
2166
                            LIMIT 0, $maximum";
2167
                } else {
2168
                    // the user is not member of any group
2169
                    // this is an identified user => show the general announcements AND his personal announcements
2170
                    if ($userId) {
2171
                        if ((api_get_course_setting('allow_user_edit_announcement') &&
2172
                            !api_is_anonymous())
2173
                        ) {
2174
                            $cond_user_id = " AND (
2175
                                ip.lastedit_user_id = '".$userId."' OR
2176
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2177
                            ) ";
2178
                        } else {
2179
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
2180
                        }
2181
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2182
                                FROM $tbl_announcement announcement
2183
                                INNER JOIN $tbl_item_property ip
2184
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2185
                                WHERE
2186
                                    announcement.c_id = $courseId AND
2187
                                    ip.c_id = $courseId AND
2188
                                    ip.tool='announcement' AND
2189
                                    ip.visibility='1'
2190
                                    $cond_user_id
2191
                                    $condition_session
2192
                                GROUP BY ip.ref
2193
                                ORDER BY display_order DESC
2194
                                LIMIT 0, $maximum";
2195
                    } else {
2196
                        if (api_get_course_setting('allow_user_edit_announcement')) {
2197
                            $cond_user_id = " AND (
2198
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
2199
                            ) ";
2200
                        } else {
2201
                            $cond_user_id = " AND ip.to_group_id='0' ";
2202
                        }
2203
2204
                        // the user is not identiefied => show only the general announcements
2205
                        $sql = "SELECT
2206
                                    announcement.*,
2207
                                    ip.visibility,
2208
                                    ip.to_group_id,
2209
                                    ip.insert_user_id
2210
                                FROM $tbl_announcement announcement
2211
                                INNER JOIN $tbl_item_property ip
2212
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2213
                                WHERE
2214
                                    announcement.c_id = $courseId AND
2215
                                    ip.c_id = $courseId AND
2216
                                    ip.tool='announcement' AND
2217
                                    ip.visibility='1' AND
2218
                                    ip.to_group_id='0'
2219
                                    $condition_session
2220
                                GROUP BY ip.ref
2221
                                ORDER BY display_order DESC
2222
                                LIMIT 0, $maximum";
2223
                    }
2224
                }
2225
            }
2226
        }
2227
2228
        $result = Database::query($sql);
2229
2230
        return Database::num_rows($result);
2231
    }
2232
}
2233