Passed
Push — master ( 023819...5e8c06 )
by Julito
10:32 queued 25s
created

AnnouncementManager::delete_all_announcements()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 1
dl 0
loc 14
rs 9.9
c 0
b 0
f 0
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\CoreBundle\Entity\Resource\ResourceLink;
7
use Chamilo\CoreBundle\Framework\Container;
8
use Chamilo\CourseBundle\Entity\CAnnouncement;
9
use Chamilo\CourseBundle\Entity\CItemProperty;
10
11
/**
12
 * Include file with functions for the announcements module.
13
 *
14
 * @author jmontoya
15
 *
16
 * @package chamilo.announcements
17
 *
18
 * @todo use OOP
19
 */
20
class AnnouncementManager
21
{
22
    /**
23
     * Constructor.
24
     */
25
    public function __construct()
26
    {
27
    }
28
29
    /**
30
     * @return array
31
     */
32
    public static function getTags()
33
    {
34
        $tags = [
35
            '((user_name))',
36
            '((user_email))',
37
            '((user_firstname))',
38
            '((user_lastname))',
39
            '((user_official_code))',
40
            '((course_title))',
41
            '((course_link))',
42
        ];
43
44
        $tags[] = '((teachers))';
45
46
        $extraField = new ExtraField('user');
47
        $extraFields = $extraField->get_all(['filter = ?' => 1]);
48
        if (!empty($extraFields)) {
49
            foreach ($extraFields as $extra) {
50
                $tags[] = "((extra_".$extra['variable']."))";
51
            }
52
        }
53
        $sessionId = api_get_session_id();
54
        if (!empty($sessionId)) {
55
            $tags[] = '((coaches))';
56
            $tags[] = '((general_coach))';
57
            $tags[] = '((general_coach_email))';
58
        }
59
60
        return $tags;
61
    }
62
63
    /**
64
     * @param int    $userId
65
     * @param string $content
66
     * @param string $courseCode
67
     * @param int    $sessionId
68
     *
69
     * @return string
70
     */
71
    public static function parseContent(
72
        $userId,
73
        $content,
74
        $courseCode,
75
        $sessionId = 0
76
    ) {
77
        $readerInfo = api_get_user_info($userId, false, false, true, true);
78
        $courseInfo = api_get_course_info($courseCode);
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=\"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('Please confirm your choice'), 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('Latest update')." : ";
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('Visible to').': '.$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
        $announcement = new CAnnouncement();
628
        $announcement
629
            ->setCId($courseId)
630
            ->setContent($newContent)
631
            ->setTitle($title)
632
            ->setEndDate(new DateTime($end_date))
633
            ->setDisplayOrder($order)
634
            ->setSessionId($sessionId)
635
        ;
636
637
        $repo = Container::getAnnouncementRepository();
638
        $repo->addResourceToCourse(
639
            $announcement,
640
            ResourceLink::VISIBILITY_PUBLISHED,
641
            api_get_user_entity($authorId),
642
            api_get_course_entity($courseId),
643
            api_get_session_entity($sessionId),
644
            api_get_group_entity()
645
        );
646
        $repo->getEntityManager()->flush();
647
        $last_id = $announcement->getIid();
648
649
        if (empty($last_id)) {
650
            return false;
651
        }
652
653
        $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
654
        Database::query($sql);
655
656
        if (!empty($file)) {
657
            self::add_announcement_attachment_file(
658
                $last_id,
659
                $file_comment,
660
                $_FILES['user_upload']
661
            );
662
        }
663
664
        // store in item_property (first the groups, then the users
665
        if (empty($sentTo) ||
666
            (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')
667
        ) {
668
            // The message is sent to EVERYONE, so we set the group to 0
669
            /*api_item_property_update(
670
                $courseInfo,
671
                TOOL_ANNOUNCEMENT,
672
                $last_id,
673
                'AnnouncementAdded',
674
                $authorId,
675
                '0',
676
                null,
677
                null,
678
                null,
679
                $sessionId
680
            );*/
681
        } else {
682
            $send_to = CourseManager::separateUsersGroups($sentTo);
683
            $batchSize = 20;
684
            $em = Database::getManager();
685
            // Storing the selected groups
686
            if (is_array($send_to['groups']) &&
687
                !empty($send_to['groups'])
688
            ) {
689
                $counter = 1;
690
                foreach ($send_to['groups'] as $group) {
691
                    $groupInfo = GroupManager::get_group_properties($group);
692
                    /*api_item_property_update(
693
                        $courseInfo,
694
                        TOOL_ANNOUNCEMENT,
695
                        $last_id,
696
                        'AnnouncementAdded',
697
                        $authorId,
698
                        $groupInfo
699
                    );*/
700
                }
701
            }
702
703
            // Storing the selected users
704
            if (is_array($send_to['users'])) {
705
                $counter = 1;
706
                foreach ($send_to['users'] as $user) {
707
                    /*api_item_property_update(
708
                        $courseInfo,
709
                        TOOL_ANNOUNCEMENT,
710
                        $last_id,
711
                        'AnnouncementAdded',
712
                        $authorId,
713
                        '',
714
                        $user
715
                    );*/
716
                }
717
            }
718
        }
719
720
        if ($sendToUsersInSession) {
721
            self::addAnnouncementToAllUsersInSessions($last_id);
722
        }
723
724
        return $last_id;
725
    }
726
727
    /**
728
     * @param string $title
729
     * @param string $newContent
730
     * @param int    $groupId
731
     * @param array  $to_users
732
     * @param array  $file
733
     * @param string $file_comment
734
     * @param bool   $sendToUsersInSession
735
     *
736
     * @return bool|int
737
     */
738
    public static function addGroupAnnouncement(
739
        $title,
740
        $newContent,
741
        $groupId,
742
        $to_users,
743
        $file = [],
744
        $file_comment = '',
745
        $sendToUsersInSession = false
746
    ) {
747
        $courseInfo = api_get_course_info();
748
749
        // Database definitions
750
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
751
        $order = self::getLastAnnouncementOrder($courseInfo);
752
753
        $now = api_get_utc_datetime();
754
        $courseId = api_get_course_int_id();
755
756
        // store in the table announcement
757
        $params = [
758
            'c_id' => $courseId,
759
            'content' => $newContent,
760
            'title' => $title,
761
            'end_date' => $now,
762
            'display_order' => $order,
763
            'session_id' => api_get_session_id(),
764
        ];
765
766
        $last_id = Database::insert($table, $params);
767
768
        // Store the attach file
769
        if ($last_id) {
770
            $sql = "UPDATE $table SET id = iid
771
                    WHERE iid = $last_id";
772
            Database::query($sql);
773
774
            if (!empty($file)) {
775
                self::add_announcement_attachment_file(
776
                    $last_id,
777
                    $file_comment,
778
                    $file
779
                );
780
            }
781
782
            $send_to_users = CourseManager::separateUsersGroups($to_users);
783
784
            // if nothing was selected in the menu then send to all the group
785
            $sentToAllGroup = false;
786
            if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
787
                $groupInfo = GroupManager::get_group_properties($groupId);
788
                api_item_property_update(
789
                    $courseInfo,
790
                    TOOL_ANNOUNCEMENT,
791
                    $last_id,
792
                    'AnnouncementAdded',
793
                    api_get_user_id(),
794
                    $groupInfo
795
                );
796
                $sentToAllGroup = true;
797
            }
798
799
            if ($sentToAllGroup === false) {
800
                if (!empty($send_to_users['groups'])) {
801
                    foreach ($send_to_users['groups'] as $group) {
802
                        $groupInfo = GroupManager::get_group_properties($group);
803
                        api_item_property_update(
804
                            $courseInfo,
805
                            TOOL_ANNOUNCEMENT,
806
                            $last_id,
807
                            'AnnouncementAdded',
808
                            api_get_user_id(),
809
                            $groupInfo
810
                        );
811
                    }
812
                }
813
814
                $groupInfo = GroupManager::get_group_properties($groupId);
815
                if (!empty($send_to_users['users'])) {
816
                    foreach ($send_to_users['users'] as $user) {
817
                        api_item_property_update(
818
                            $courseInfo,
819
                            TOOL_ANNOUNCEMENT,
820
                            $last_id,
821
                            'AnnouncementAdded',
822
                            api_get_user_id(),
823
                            $groupInfo,
824
                            $user
825
                        );
826
                    }
827
                }
828
            }
829
830
            if ($sendToUsersInSession) {
831
                self::addAnnouncementToAllUsersInSessions($last_id);
832
            }
833
        }
834
835
        return $last_id;
836
    }
837
838
    /**
839
     * This function stores the announcement item in the announcement table
840
     * and updates the item_property table.
841
     *
842
     * @param int    $id                   id of the announcement
843
     * @param string $title
844
     * @param string $newContent
845
     * @param array  $to                   users that will receive the announcement
846
     * @param mixed  $file                 attachment
847
     * @param string $file_comment         file comment
848
     * @param bool   $sendToUsersInSession
849
     */
850
    public static function edit_announcement(
851
        $id,
852
        $title,
853
        $newContent,
854
        $to,
855
        $file = [],
856
        $file_comment = '',
857
        $sendToUsersInSession = false
858
    ) {
859
        $courseInfo = api_get_course_info();
860
        $courseId = api_get_course_int_id();
861
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
862
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
863
        $id = (int) $id;
864
865
        $params = [
866
            'title' => $title,
867
            'content' => $newContent,
868
        ];
869
870
        Database::update(
871
            $table,
872
            $params,
873
            ['c_id = ? AND id = ?' => [$courseId, $id]]
874
        );
875
876
        // save attachment file
877
        $row_attach = self::get_attachment($id);
878
879
        $id_attach = 0;
880
        if ($row_attach) {
881
            $id_attach = (int) $row_attach['id'];
882
        }
883
884
        if (!empty($file)) {
885
            if (empty($id_attach)) {
886
                self::add_announcement_attachment_file(
887
                    $id,
888
                    $file_comment,
889
                    $file
890
                );
891
            } else {
892
                self::edit_announcement_attachment_file(
893
                    $id_attach,
894
                    $file,
895
                    $file_comment
896
                );
897
            }
898
        }
899
900
        // We remove everything from item_property for this
901
        $sql = "DELETE FROM $tbl_item_property
902
                WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
903
        Database::query($sql);
904
905
        if ($sendToUsersInSession) {
906
            self::addAnnouncementToAllUsersInSessions($id);
907
        }
908
909
        // store in item_property (first the groups, then the users
910
        if (!empty($to)) {
911
            // !is_null($to): when no user is selected we send it to everyone
912
            $send_to = CourseManager::separateUsersGroups($to);
913
914
            // storing the selected groups
915
            if (is_array($send_to['groups'])) {
916
                foreach ($send_to['groups'] as $group) {
917
                    $groupInfo = GroupManager::get_group_properties($group);
918
                    if (empty($groupInfo)) {
919
                        // Probably the group id and iid are different try checking the iid
920
                        $groupInfo = GroupManager::get_group_properties($group, true);
921
                    }
922
                    if ($groupInfo) {
923
                        api_item_property_update(
924
                            $courseInfo,
925
                            TOOL_ANNOUNCEMENT,
926
                            $id,
927
                            'AnnouncementUpdated',
928
                            api_get_user_id(),
929
                            $groupInfo
930
                        );
931
                    }
932
                }
933
            }
934
935
            // storing the selected users
936
            if (is_array($send_to['users'])) {
937
                foreach ($send_to['users'] as $user) {
938
                    api_item_property_update(
939
                        $courseInfo,
940
                        TOOL_ANNOUNCEMENT,
941
                        $id,
942
                        'AnnouncementUpdated',
943
                        api_get_user_id(),
944
                        0,
945
                        $user
946
                    );
947
                }
948
            }
949
950
            // Send to everyone
951
            if (isset($to[0]) && $to[0] === 'everyone') {
952
                api_item_property_update(
953
                    $courseInfo,
954
                    TOOL_ANNOUNCEMENT,
955
                    $id,
956
                    'AnnouncementUpdated',
957
                    api_get_user_id(),
958
                    0
959
                );
960
            }
961
        } else {
962
            // the message is sent to everyone, so we set the group to 0
963
            api_item_property_update(
964
                $courseInfo,
965
                TOOL_ANNOUNCEMENT,
966
                $id,
967
                'AnnouncementUpdated',
968
                api_get_user_id(),
969
                0
970
            );
971
        }
972
    }
973
974
    /**
975
     * @param int $announcementId
976
     */
977
    public static function addAnnouncementToAllUsersInSessions($announcementId)
978
    {
979
        $courseCode = api_get_course_id();
980
        $courseInfo = api_get_course_info();
981
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
982
983
        if (!empty($sessionList)) {
984
            foreach ($sessionList as $sessionInfo) {
985
                $sessionId = $sessionInfo['id'];
986
                $userList = CourseManager::get_user_list_from_course_code(
987
                    $courseCode,
988
                    $sessionId
989
                );
990
991
                if (!empty($userList)) {
992
                    foreach ($userList as $user) {
993
                        api_item_property_update(
994
                            $courseInfo,
995
                            TOOL_ANNOUNCEMENT,
996
                            $announcementId,
997
                            'AnnouncementUpdated',
998
                            api_get_user_id(),
999
                            0,
1000
                            $user['user_id'],
1001
                            0,
1002
                            0,
1003
                            $sessionId
1004
                        );
1005
                    }
1006
                }
1007
            }
1008
        }
1009
    }
1010
1011
    /**
1012
     * @param int $insert_id
1013
     *
1014
     * @return bool
1015
     */
1016
    public static function update_mail_sent($insert_id)
1017
    {
1018
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1019
        if ($insert_id != strval(intval($insert_id))) {
1020
            return false;
1021
        }
1022
        $insert_id = intval($insert_id);
1023
        $courseId = api_get_course_int_id();
1024
        // store the modifications in the table tbl_annoucement
1025
        $sql = "UPDATE $table SET email_sent='1'
1026
                WHERE c_id = $courseId AND id = $insert_id";
1027
        Database::query($sql);
1028
    }
1029
1030
    /**
1031
     * @param int $user_id
1032
     *
1033
     * @return array|bool
1034
     */
1035
    public static function getAnnoucementCourseTotalByUser($user_id)
1036
    {
1037
        $user_id = (int) $user_id;
1038
1039
        if (empty($user_id)) {
1040
            return false;
1041
        }
1042
1043
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1044
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1045
1046
        $sql = "SELECT DISTINCT
1047
                    announcement.c_id,
1048
                    count(announcement.id) count
1049
                FROM $tbl_announcement announcement
1050
                INNER JOIN $tbl_item_property ip
1051
                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1052
                WHERE
1053
                    ip.tool='announcement' AND
1054
                    (
1055
                      ip.to_user_id = '$user_id' AND
1056
                      (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1057
                    )
1058
                    AND ip.visibility='1'
1059
                    AND announcement.session_id  = 0
1060
                GROUP BY announcement.c_id";
1061
        $rs = Database::query($sql);
1062
        $num_rows = Database::num_rows($rs);
1063
        $result = [];
1064
        if ($num_rows > 0) {
1065
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1066
                if (empty($row['c_id'])) {
1067
                    continue;
1068
                }
1069
                $result[] = ['course' => api_get_course_info_by_id($row['c_id']), 'count' => $row['count']];
1070
            }
1071
        }
1072
1073
        return $result;
1074
    }
1075
1076
    /**
1077
     * Returns announcement info from its id.
1078
     *
1079
     * @param int $courseId
1080
     * @param int $id
1081
     *
1082
     * @return array
1083
     */
1084
    public static function get_by_id($courseId, $id)
1085
    {
1086
        $id = (int) $id;
1087
        $courseId = $courseId ? (int) $courseId : api_get_course_int_id();
1088
1089
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1090
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1091
1092
        $sql = "SELECT DISTINCT
1093
                    announcement.id,
1094
                    announcement.title,
1095
                    announcement.content,
1096
                    ip.to_group_id
1097
               FROM $tbl_announcement announcement
1098
               INNER JOIN $tbl_item_property ip
1099
               ON
1100
                    announcement.id = ip.ref AND
1101
                    announcement.c_id = ip.c_id
1102
               WHERE
1103
                    announcement.c_id = $courseId AND
1104
                    ip.tool='announcement' AND
1105
                    announcement.id = $id
1106
                ";
1107
1108
        $result = Database::query($sql);
1109
        if (Database::num_rows($result)) {
1110
            return Database::fetch_array($result);
1111
        }
1112
1113
        return [];
1114
    }
1115
1116
    /**
1117
     * this function gets all the groups of the course,
1118
     * not including linked courses.
1119
     */
1120
    public static function get_course_groups()
1121
    {
1122
        $session_id = api_get_session_id();
1123
        if ($session_id != 0) {
1124
            $new_group_list = CourseManager::get_group_list_of_course(
1125
                api_get_course_id(),
1126
                $session_id,
1127
                1
1128
            );
1129
        } else {
1130
            $new_group_list = CourseManager::get_group_list_of_course(
1131
                api_get_course_id(),
1132
                0,
1133
                1
1134
            );
1135
        }
1136
1137
        return $new_group_list;
1138
    }
1139
1140
    /**
1141
     * This tools loads all the users and all the groups who have received
1142
     * a specific item (in this case an announcement item).
1143
     *
1144
     * @param string $tool
1145
     * @param int    $id
1146
     * @param bool   $includeGroupWhenLoadingUser
1147
     *
1148
     * @return array
1149
     */
1150
    public static function loadEditUsers($tool, $id, $includeGroupWhenLoadingUser = false)
1151
    {
1152
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1153
        $tool = Database::escape_string($tool);
1154
        $id = (int) $id;
1155
        $courseId = api_get_course_int_id();
1156
        $groupId = api_get_group_id();
1157
1158
        $sql = "SELECT to_user_id, to_group_id FROM $table
1159
                WHERE c_id = $courseId AND tool='$tool' AND ref = $id";
1160
1161
        $result = Database::query($sql);
1162
        $to = [];
1163
        while ($row = Database::fetch_array($result)) {
1164
            // This is the iid of c_group_info
1165
            $toGroup = $row['to_group_id'];
1166
            if (empty($row['to_user_id']) && !empty($groupId) && $groupId != $toGroup) {
1167
                //continue;
1168
            }
1169
            switch ($toGroup) {
1170
                // it was send to one specific user
1171
                case null:
1172
                    if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
1173
                        if (!in_array('USER:'.$row['to_user_id'], $to)) {
1174
                            $to[] = 'USER:'.$row['to_user_id'];
1175
                        }
1176
                    }
1177
                    break;
1178
                // it was sent to everyone
1179
                case 0:
1180
                    return 'everyone';
1181
                    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...
1182
                default:
1183
                    if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
1184
                        if (!in_array('USER:'.$row['to_user_id'], $to)) {
1185
                            $to[] = 'USER:'.$row['to_user_id'];
1186
                        }
1187
                    } else {
1188
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1189
                            $to[] = 'GROUP:'.$toGroup;
1190
                        }
1191
                    }
1192
1193
                    if ($includeGroupWhenLoadingUser) {
1194
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1195
                            $to[] = 'GROUP:'.$toGroup;
1196
                        }
1197
                    }
1198
                    break;
1199
            }
1200
        }
1201
1202
        return $to;
1203
    }
1204
1205
    /**
1206
     * constructs the form to display all the groups and users the message has been sent to.
1207
     *
1208
     * @param array $sent_to_array
1209
     *                             input:
1210
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1211
     *                             the first level is a distinction between groups and users:
1212
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1213
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1214
     *                             containing all the id's of the groups (resp. users) who have received this message.
1215
     *
1216
     * @return string
1217
     *
1218
     * @author Patrick Cool <patrick.cool@>
1219
     */
1220
    public static function sent_to_form($sent_to_array)
1221
    {
1222
        // we find all the names of the groups
1223
        $group_names = self::get_course_groups();
1224
1225
        // we count the number of users and the number of groups
1226
        $number_users = 0;
1227
        if (isset($sent_to_array['users'])) {
1228
            $number_users = count($sent_to_array['users']);
1229
        }
1230
        $number_groups = 0;
1231
        if (isset($sent_to_array['groups'])) {
1232
            $number_groups = count($sent_to_array['groups']);
1233
        }
1234
1235
        $total_numbers = $number_users + $number_groups;
1236
1237
        // starting the form if there is more than one user/group
1238
        $output = [];
1239
        if ($total_numbers > 1) {
1240
            // outputting the name of the groups
1241
            if (is_array($sent_to_array['groups'])) {
1242
                foreach ($sent_to_array['groups'] as $group_id) {
1243
                    $users = GroupManager::getStudents($group_id, true);
1244
                    $userToArray = [];
1245
                    foreach ($users as $student) {
1246
                        $userToArray[] = $student['complete_name_with_username'];
1247
                    }
1248
                    $output[] =
1249
                        '<br />'.
1250
                        Display::label($group_names[$group_id]['name'], 'info').
1251
                        '&nbsp;'.implode(', ', $userToArray);
1252
                }
1253
            }
1254
1255
            if (isset($sent_to_array['users'])) {
1256
                if (is_array($sent_to_array['users'])) {
1257
                    $usersToArray = [];
1258
                    foreach ($sent_to_array['users'] as $user_id) {
1259
                        $user_info = api_get_user_info($user_id);
1260
                        $usersToArray[] = $user_info['complete_name_with_username'];
1261
                    }
1262
                    $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
1263
                }
1264
            }
1265
        } else {
1266
            // there is only one user/group
1267
            if (isset($sent_to_array['users']) && is_array($sent_to_array['users'])) {
1268
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1269
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1270
            }
1271
            if (isset($sent_to_array['groups']) &&
1272
                is_array($sent_to_array['groups']) &&
1273
                isset($sent_to_array['groups'][0]) &&
1274
                $sent_to_array['groups'][0] !== 0
1275
            ) {
1276
                $group_id = $sent_to_array['groups'][0];
1277
1278
                $users = GroupManager::getStudents($group_id, true);
1279
                $userToArray = [];
1280
                foreach ($users as $student) {
1281
                    $userToArray[] = $student['complete_name_with_username'];
1282
                }
1283
                $output[] =
1284
                    '<br />'.
1285
                    Display::label($group_names[$group_id]['name'], 'info').
1286
                    '&nbsp;'.implode(', ', $userToArray);
1287
            }
1288
            if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
1289
                $output[] = "&nbsp;".get_lang('All');
1290
            }
1291
        }
1292
1293
        if (!empty($output)) {
1294
            $output = array_filter($output);
1295
            if (count($output) > 0) {
1296
                $output = implode('<br />', $output);
1297
            }
1298
1299
            return $output;
1300
        }
1301
    }
1302
1303
    /**
1304
     * Returns all the users and all the groups a specific announcement item
1305
     * has been sent to.
1306
     *
1307
     * @param    string  The tool (announcement, agenda, ...)
1308
     * @param    int     ID of the element of the corresponding type
1309
     *
1310
     * @return array Array of users and groups to whom the element has been sent
1311
     */
1312
    public static function sent_to($tool, $id)
1313
    {
1314
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1315
        $tool = Database::escape_string($tool);
1316
        $id = (int) $id;
1317
1318
        $sent_to_group = [];
1319
        $sent_to = [];
1320
        $courseId = api_get_course_int_id();
1321
1322
        $sql = "SELECT to_group_id, to_user_id
1323
                FROM $table
1324
                WHERE c_id = $courseId AND tool = '$tool' AND ref=".$id;
1325
        $result = Database::query($sql);
1326
1327
        while ($row = Database::fetch_array($result)) {
1328
            // if to_user_id <> 0 then it is sent to a specific user
1329
            if ($row['to_user_id'] != 0) {
1330
                $sent_to_user[] = $row['to_user_id'];
1331
                continue;
1332
            }
1333
1334
            // if to_group_id is null then it is sent to a specific user
1335
            // if to_group_id = 0 then it is sent to everybody
1336
            if ($row['to_group_id'] != 0) {
1337
                $sent_to_group[] = $row['to_group_id'];
1338
            }
1339
        }
1340
1341
        if (isset($sent_to_group)) {
1342
            $sent_to['groups'] = $sent_to_group;
1343
        }
1344
1345
        if (isset($sent_to_user)) {
1346
            $sent_to['users'] = $sent_to_user;
1347
        }
1348
1349
        return $sent_to;
1350
    }
1351
1352
    /**
1353
     * Show a list with all the attachments according to the post's id.
1354
     *
1355
     * @param int $announcementId
1356
     *
1357
     * @return array with the post info
1358
     *
1359
     * @author Arthur Portugal
1360
     *
1361
     * @version November 2009, dokeos 1.8.6.2
1362
     */
1363
    public static function get_attachment($announcementId)
1364
    {
1365
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1366
        $announcementId = (int) $announcementId;
1367
        $courseId = api_get_course_int_id();
1368
        $row = [];
1369
        $sql = 'SELECT id, path, filename, comment
1370
                FROM '.$table.'
1371
				WHERE c_id = '.$courseId.' AND announcement_id = '.$announcementId;
1372
        $result = Database::query($sql);
1373
        if (Database::num_rows($result) != 0) {
1374
            $row = Database::fetch_array($result, 'ASSOC');
1375
        }
1376
1377
        return $row;
1378
    }
1379
1380
    /**
1381
     * This function add a attachment file into announcement.
1382
     *
1383
     * @param int  announcement id
1384
     * @param string file comment
1385
     * @param array  uploaded file $_FILES
1386
     *
1387
     * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
1388
     */
1389
    public static function add_announcement_attachment_file(
1390
        $announcement_id,
1391
        $file_comment,
1392
        $file
1393
    ) {
1394
        $courseInfo = api_get_course_info();
1395
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1396
        $return = 0;
1397
        $announcement_id = intval($announcement_id);
1398
        $courseId = api_get_course_int_id();
1399
1400
        if (is_array($file) && $file['error'] == 0) {
1401
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1402
            $courseDir = $courseInfo['path'].'/upload/announcements';
1403
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1404
            $updir = $sys_course_path.$courseDir;
1405
1406
            // Try to add an extension to the file if it hasn't one
1407
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1408
            // user's file name
1409
            $file_name = $file['name'];
1410
1411
            if (!filter_extension($new_file_name)) {
1412
                $return = -1;
1413
                echo Display::return_message(get_lang('File upload failed: this file extension or file type is prohibited'), 'error');
1414
            } else {
1415
                $new_file_name = uniqid('');
1416
                $new_path = $updir.'/'.$new_file_name;
1417
1418
                // This file is copy here but its cleaned in api_mail_html in api.lib.php
1419
                copy($file['tmp_name'], $new_path);
1420
1421
                $params = [
1422
                    'c_id' => $courseId,
1423
                    'filename' => $file_name,
1424
                    'comment' => $file_comment,
1425
                    'path' => $new_file_name,
1426
                    'announcement_id' => $announcement_id,
1427
                    'size' => intval($file['size']),
1428
                ];
1429
1430
                $insertId = Database::insert($table, $params);
1431
                if ($insertId) {
1432
                    $sql = "UPDATE $table SET id = iid
1433
                            WHERE iid = $insertId";
1434
                    Database::query($sql);
1435
                }
1436
1437
                $return = 1;
1438
            }
1439
        }
1440
1441
        return $return;
1442
    }
1443
1444
    /**
1445
     * This function edit a attachment file into announcement.
1446
     *
1447
     * @param int attach id
1448
     * @param array uploaded file $_FILES
1449
     * @param string file comment
1450
     *
1451
     * @return int
1452
     */
1453
    public static function edit_announcement_attachment_file(
1454
        $id_attach,
1455
        $file,
1456
        $file_comment
1457
    ) {
1458
        $courseInfo = api_get_course_info();
1459
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1460
        $return = 0;
1461
        $courseId = api_get_course_int_id();
1462
1463
        if (is_array($file) && $file['error'] == 0) {
1464
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1465
            $courseDir = $courseInfo['path'].'/upload/announcements';
1466
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1467
            $updir = $sys_course_path.$courseDir;
1468
1469
            // Try to add an extension to the file if it hasn't one
1470
            $new_file_name = add_ext_on_mime(
1471
                stripslashes($file['name']),
1472
                $file['type']
1473
            );
1474
            // user's file name
1475
            $file_name = $file['name'];
1476
1477
            if (!filter_extension($new_file_name)) {
1478
                $return = -1;
1479
                echo Display::return_message(
1480
                    get_lang('File upload failed: this file extension or file type is prohibited'),
1481
                    'error'
1482
                );
1483
            } else {
1484
                $new_file_name = uniqid('');
1485
                $new_path = $updir.'/'.$new_file_name;
1486
                copy($file['tmp_name'], $new_path);
1487
                $safe_file_comment = Database::escape_string($file_comment);
1488
                $safe_file_name = Database::escape_string($file_name);
1489
                $safe_new_file_name = Database::escape_string($new_file_name);
1490
                $id_attach = intval($id_attach);
1491
                $sql = "UPDATE $table SET
1492
                            filename = '$safe_file_name',
1493
                            comment = '$safe_file_comment',
1494
                            path = '$safe_new_file_name',
1495
                            size ='".intval($file['size'])."'
1496
					 	WHERE c_id = $courseId AND id = '$id_attach'";
1497
                $result = Database::query($sql);
1498
                if ($result === false) {
1499
                    $return = -1;
1500
                    echo Display::return_message(
1501
                        get_lang('The uploaded file could not be saved (perhaps a permission problem?)'),
1502
                        'error'
1503
                    );
1504
                } else {
1505
                    $return = 1;
1506
                }
1507
            }
1508
        }
1509
1510
        return $return;
1511
    }
1512
1513
    /**
1514
     * This function delete a attachment file by id.
1515
     *
1516
     * @param int $id attachment file Id
1517
     *
1518
     * @return bool
1519
     */
1520
    public static function delete_announcement_attachment_file($id)
1521
    {
1522
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1523
        $id = intval($id);
1524
        $courseId = api_get_course_int_id();
1525
        if (empty($courseId) || empty($id)) {
1526
            return false;
1527
        }
1528
        $sql = "DELETE FROM $table
1529
                WHERE c_id = $courseId AND id = $id";
1530
        Database::query($sql);
1531
1532
        return true;
1533
    }
1534
1535
    /**
1536
     * @param array $courseInfo
1537
     * @param int   $sessionId
1538
     * @param int   $announcementId
1539
     * @param bool  $sendToUsersInSession
1540
     * @param bool  $sendToDrhUsers
1541
     * @param Monolog\Handler\HandlerInterface logger
1542
     * @param int  $senderId
1543
     * @param bool $directMessage
1544
     *
1545
     * @return array
1546
     */
1547
    public static function sendEmail(
1548
        $courseInfo,
1549
        $sessionId,
1550
        $announcementId,
1551
        $sendToUsersInSession = false,
1552
        $sendToDrhUsers = false,
1553
        $logger = null,
1554
        $senderId = 0,
1555
        $directMessage = false
1556
    ) {
1557
        $email = new AnnouncementEmail($courseInfo, $sessionId, $announcementId, $logger);
1558
1559
        return $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId, $directMessage);
1560
    }
1561
1562
    /**
1563
     * @param $stok
1564
     * @param $announcement_number
1565
     * @param bool   $getCount
1566
     * @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...
1567
     * @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...
1568
     * @param string $sidx
1569
     * @param string $sord
1570
     * @param string $titleToSearch
1571
     * @param int    $userIdToSearch
1572
     * @param int    $userId
1573
     * @param int    $courseId
1574
     * @param int    $sessionId
1575
     *
1576
     * @return array
1577
     */
1578
    public static function getAnnouncements(
1579
        $stok,
1580
        $announcement_number,
1581
        $getCount = false,
1582
        $start = null,
1583
        $limit = null,
1584
        $sidx = '',
1585
        $sord = '',
1586
        $titleToSearch = '',
1587
        $userIdToSearch = 0,
1588
        $userId = 0,
1589
        $courseId = 0,
1590
        $sessionId = 0
1591
    ) {
1592
        $user_id = $userId ?: api_get_user_id();
1593
        $group_id = api_get_group_id();
1594
        $session_id = $sessionId ?: api_get_session_id();
1595
        if (empty($courseId)) {
1596
            $courseInfo = api_get_course_info();
1597
            $courseId = $courseInfo['real_id'];
1598
        } else {
1599
            $courseId = (int) $courseId;
1600
            $courseInfo = api_get_course_info_by_id($courseId);
1601
        }
1602
1603
        if (empty($courseInfo)) {
1604
            return [];
1605
        }
1606
1607
        $repo = Container::getAnnouncementRepository();
1608
        $course = api_get_course_entity($courseId);
1609
        $session = api_get_session_entity($session_id);
1610
        $group = api_get_group_entity(api_get_group_id());
1611
1612
        $qb = $repo->getResourcesByCourse($course, $session, $group);
1613
1614
        $announcements = $qb->getQuery()->getResult();
1615
1616
        /*$condition_session = api_get_session_condition(
1617
            $session_id,
1618
            true,
1619
            true,
1620
            'announcement.session_id'
1621
        );
1622
1623
        $group_memberships = GroupManager::get_group_ids(
1624
            $courseId,
1625
            api_get_user_id()
1626
        );
1627
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1628
1629
        $select = ' DISTINCT
1630
                        announcement.*,
1631
                        ip.visibility,
1632
                        ip.to_group_id,
1633
                        ip.insert_user_id,
1634
                        ip.insert_date,
1635
                        ip.lastedit_date';
1636
        $groupBy = ' GROUP BY announcement.iid';
1637
        if ($getCount) {
1638
            $groupBy = '';
1639
            $select = ' COUNT(DISTINCT announcement.iid) count';
1640
        }
1641
1642
        $searchCondition = '';
1643
        if (!empty($titleToSearch)) {
1644
            $titleToSearch = Database::escape_string($titleToSearch);
1645
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1646
        }
1647
1648
        if (!empty($userIdToSearch)) {
1649
            $userIdToSearch = (int) $userIdToSearch;
1650
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1651
        }
1652
1653
        $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
1654
        $extraGroupCondition = '';
1655
        if ($allowOnlyGroup) {
1656
            $extraGroupCondition = " AND ip.to_group_id = $group_id ";
1657
        }
1658
1659
        $allowDrhAccess = api_get_configuration_value('allow_drh_access_announcement');
1660
1661
        if ($allowDrhAccess && api_is_drh()) {
1662
            // DRH only can see visible
1663
            $searchCondition .= ' AND (ip.visibility = 1)';
1664
        }
1665
1666
        if (api_is_allowed_to_edit(false, true) ||
1667
            ($allowUserEditSetting && !api_is_anonymous()) ||
1668
            ($allowDrhAccess && api_is_drh())
1669
        ) {
1670
            // A.1. you are a course admin with a USER filter
1671
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1672
            //if (!empty($user_id)) {
1673
            if (0) {
1674
                if (is_array($group_memberships) &&
1675
                    count($group_memberships) > 0
1676
                ) {
1677
                    $sql = "SELECT $select
1678
                            FROM $tbl_announcement announcement
1679
                            INNER JOIN $tbl_item_property ip
1680
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1681
                            WHERE
1682
                                announcement.c_id = $courseId AND
1683
                                ip.c_id = $courseId AND
1684
                                ip.tool = 'announcement' AND
1685
                                (
1686
                                    ip.to_user_id = $user_id OR
1687
                                    ip.to_group_id IS NULL OR
1688
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1689
                                ) AND
1690
                                ip.visibility IN ('1', '0')
1691
                                $condition_session
1692
                                $searchCondition
1693
                            ORDER BY display_order DESC";
1694
                } else {
1695
                    $sql = "SELECT $select
1696
                            FROM $tbl_announcement announcement
1697
                            INNER JOIN $tbl_item_property ip
1698
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1699
                            WHERE
1700
                                announcement.c_id = $courseId AND
1701
                                ip.c_id = $courseId AND
1702
                                ip.tool ='announcement' AND
1703
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1704
                                ip.visibility IN ('1', '0')
1705
                            $condition_session
1706
                            $searchCondition
1707
                            ORDER BY display_order DESC";
1708
                }
1709
            } elseif ($group_id != 0) {
1710
                // A.2. you are a course admin with a GROUP filter
1711
                // => see only the messages of this specific group
1712
                $sql = "SELECT $select
1713
                        FROM $tbl_announcement announcement
1714
                        INNER JOIN $tbl_item_property ip
1715
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1716
                        WHERE
1717
                            ip.tool='announcement' AND
1718
                            announcement.c_id = $courseId AND
1719
                            ip.c_id = $courseId AND
1720
                            ip.visibility<>'2' AND
1721
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1722
                            $condition_session
1723
                            $searchCondition
1724
                            $extraGroupCondition
1725
                        $groupBy
1726
                        ORDER BY display_order DESC";
1727
            } else {
1728
                // A.3 you are a course admin without any group or user filter
1729
                // A.3.a you are a course admin without user or group filter but WITH studentview
1730
                // => see all the messages of all the users and groups without editing possibilities
1731
                if (isset($isStudentView) && $isStudentView == 'true') {
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='1'
1741
                                $condition_session
1742
                                $searchCondition
1743
                            $groupBy
1744
                            ORDER BY display_order DESC";
1745
                } else {
1746
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1747
                    // => see all the messages of all the users and groups with editing possibilities
1748
                    $sql = "SELECT $select
1749
                            FROM $tbl_announcement announcement
1750
                            INNER JOIN $tbl_item_property ip
1751
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1752
                            WHERE
1753
                                ip.tool = 'announcement' AND
1754
                                announcement.c_id = $courseId AND
1755
                                ip.c_id = $courseId  AND
1756
                                (ip.visibility='0' OR ip.visibility='1')
1757
                                $condition_session
1758
                                $searchCondition
1759
                            $groupBy
1760
                            ORDER BY display_order DESC";
1761
                }
1762
            }
1763
        } else {
1764
            // STUDENT
1765
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1766
                if ($allowUserEditSetting && !api_is_anonymous()) {
1767
                    if ($group_id == 0) {
1768
                        // No group
1769
                        $cond_user_id = " AND (
1770
                            ip.lastedit_user_id = '".$user_id."' OR (
1771
                                (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
1772
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1773
                            )
1774
                        ) ";
1775
                    } else {
1776
                        $cond_user_id = " AND (
1777
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1778
                        )";
1779
                        $cond_user_id .= $extraGroupCondition;
1780
                    }
1781
                } else {
1782
                    if ($group_id == 0) {
1783
                        $cond_user_id = " AND (
1784
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1785
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1786
                        ) ";
1787
                    } else {
1788
                        $cond_user_id = " AND (
1789
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1790
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1791
                        )";
1792
                        $cond_user_id .= $extraGroupCondition;
1793
                    }
1794
                }
1795
1796
                $sql = "SELECT $select
1797
                        FROM $tbl_announcement announcement INNER JOIN
1798
                        $tbl_item_property ip
1799
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1800
                        WHERE
1801
                            announcement.c_id = $courseId AND
1802
                            ip.c_id = $courseId AND
1803
                            ip.tool='announcement'
1804
                            $cond_user_id
1805
                            $condition_session
1806
                            $searchCondition AND
1807
                            ip.visibility='1'
1808
                            $groupBy
1809
                        ORDER BY display_order DESC";
1810
            } else {
1811
                if ($user_id) {
1812
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1813
                        $cond_user_id = " AND (
1814
                                ip.lastedit_user_id = '".api_get_user_id()."' OR
1815
                                ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1816
                                (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1817
                            )
1818
                        ) ";
1819
                    } else {
1820
                        $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1821
                        (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1822
                    }
1823
1824
                    $sql = "SELECT $select
1825
						FROM $tbl_announcement announcement
1826
						INNER JOIN $tbl_item_property ip
1827
						ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1828
						WHERE
1829
    						announcement.c_id = $courseId AND
1830
							ip.c_id = $courseId AND
1831
    						ip.tool='announcement'
1832
    						$cond_user_id
1833
    						$condition_session
1834
    						$searchCondition
1835
    						AND ip.visibility='1'
1836
    						AND announcement.session_id IN(0, ".$session_id.")
1837
                        $groupBy
1838
						ORDER BY display_order DESC";
1839
                } else {
1840
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1841
                        $cond_user_id = " AND (
1842
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1843
                        )";
1844
                    } else {
1845
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1846
                    }
1847
1848
                    $sql = "SELECT $select
1849
                            FROM $tbl_announcement announcement
1850
                            INNER JOIN $tbl_item_property ip
1851
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1852
                            WHERE
1853
                                announcement.c_id = $courseId AND
1854
                                ip.c_id = $courseId AND
1855
                                ip.tool='announcement'
1856
                                $cond_user_id
1857
                                $condition_session
1858
                                $searchCondition  AND
1859
                                ip.visibility='1' AND
1860
                                announcement.session_id IN ( 0,".api_get_session_id().")
1861
                                $groupBy
1862
                            ";
1863
                }
1864
            }
1865
        }
1866
1867
        if (!is_null($start) && !is_null($limit)) {
1868
            $start = (int) $start;
1869
            $limit = (int) $limit;
1870
            $sql .= " LIMIT $start, $limit";
1871
        }
1872
1873
        $result = Database::query($sql);
1874
        if ($getCount) {
1875
            $result = Database::fetch_array($result, 'ASSOC');
1876
1877
            return $result['count'];
1878
        }*/
1879
1880
        $iterator = 1;
1881
        $bottomAnnouncement = $announcement_number;
1882
        $displayed = [];
1883
1884
        $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.api_get_cidreq();
1885
        $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('Announcement sent by e-mail').'"></i>';
1886
        $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
1887
1888
        $editIcon = Display::return_icon(
1889
            'edit.png',
1890
            get_lang('Edit'),
1891
            '',
1892
            ICON_SIZE_SMALL
1893
        );
1894
1895
        $editIconDisable = Display::return_icon(
1896
            'edit_na.png',
1897
            get_lang('Edit'),
1898
            '',
1899
            ICON_SIZE_SMALL
1900
        );
1901
        $deleteIcon = Display::return_icon(
1902
            'delete.png',
1903
            get_lang('Delete'),
1904
            '',
1905
            ICON_SIZE_SMALL
1906
        );
1907
1908
        $deleteIconDisable = Display::return_icon(
1909
            'delete_na.png',
1910
            get_lang('Delete'),
1911
            '',
1912
            ICON_SIZE_SMALL
1913
        );
1914
1915
        $isTutor = false;
1916
        if (!empty($group_id)) {
1917
            $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1918
            //User has access in the group?
1919
            $isTutor = GroupManager::is_tutor_of_group(
1920
                api_get_user_id(),
1921
                $groupInfo
1922
            );
1923
        }
1924
1925
        $results = [];
1926
        /** @var CAnnouncement $announcement */
1927
        foreach ($announcements as $announcement) {
1928
            $announcementId = $announcement->getIid();
1929
            if (!in_array($announcementId, $displayed)) {
1930
                $sent_to_icon = '';
1931
                // the email icon
1932
                if ($announcement->getEmailSent() == '1') {
1933
                    $sent_to_icon = ' '.$emailIcon;
1934
                }
1935
1936
                //$groupReference = $row['to_group_id'] > 0 ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
1937
                $groupReference = '';
1938
                $disableEdit = false;
1939
                //$to = self::loadEditUsers('announcement', $announcementId, true);
1940
                $to = [];
1941
                $separated = CourseManager::separateUsersGroups($to);
1942
                if (!empty($group_id)) {
1943
                    // If the announcement was sent to many groups, disable edition inside a group
1944
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1945
                        $disableEdit = true;
1946
                    }
1947
1948
                    // If the announcement was sent only to the course disable edition
1949
                    if (empty($separated['groups']) && empty($separated['users'])) {
1950
                        $disableEdit = true;
1951
                    }
1952
1953
                    // Announcement sent to only a user
1954
                    if ($separated['groups'] > 1 && !in_array($group_id, $separated['groups'])) {
1955
                        $disableEdit = true;
1956
                    }
1957
                } else {
1958
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1959
                        $groupReference = '';
1960
                    }
1961
                }
1962
1963
                $title = $announcement->getTitle().$groupReference.$sent_to_icon;
1964
                /*$item_visibility = api_get_item_visibility(
1965
                    $courseInfo,
1966
                    TOOL_ANNOUNCEMENT,
1967
                    $row['id'],
1968
                    $session_id
1969
                );*/
1970
                $visibility = $announcement->isVisible($course, $session);
1971
1972
                // show attachment list
1973
                $attachment_list = self::get_attachment($announcementId);
1974
                $attachment_icon = '';
1975
                if (count($attachment_list) > 0) {
1976
                    $attachment_icon = ' '.$attachmentIcon;
1977
                }
1978
1979
                /* TITLE */
1980
                $username = $announcement->getResourceNode()->getCreator()->getUsername();
1981
1982
                $username_span = Display::tag(
1983
                    'span',
1984
                    $username,
1985
                    ['title' => $username]
1986
                );
1987
1988
                $title = Display::url(
1989
                    $title.$attachment_icon,
1990
                    $actionUrl.'&action=view&id='.$announcementId
1991
                );
1992
1993
                // we can edit if : we are the teacher OR the element belongs to
1994
                // the session we are coaching OR the option to allow users to edit is on
1995
                if (api_is_allowed_to_edit(false, true) ||
1996
                    (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $announcementId)) ||
1997
                    (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
1998
                    ($row['to_group_id'] == $group_id && $isTutor)
1999
                ) {
2000
                    if ($disableEdit === true) {
2001
                        $modify_icons = "<a href='#'>".$editIconDisable."</a>";
2002
                    } else {
2003
                        $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$announcementId."\">".$editIcon."</a>";
2004
                    }
2005
2006
                    if ($visibility) {
2007
                        $image_visibility = "visible";
2008
                        $alt_visibility = get_lang('Hide');
2009
                    } else {
2010
                        $image_visibility = "invisible";
2011
                        $alt_visibility = get_lang('Visible');
2012
                    }
2013
2014
                    $modify_icons .= "<a href=\"".$actionUrl."&action=showhide&id=".$announcementId."&sec_token=".$stok."\">".
2015
                        Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
2016
2017
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
2018
                    if ($iterator != 1) {
2019
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$announcementId."&sec_token=".$stok."\">".
2020
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
2021
                    } else {
2022
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
2023
                    }
2024
                    if ($iterator < $bottomAnnouncement) {
2025
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$announcementId."&sec_token=".$stok."\">".
2026
                            Display::return_icon('down.gif', get_lang('down'))."</a>";
2027
                    } else {
2028
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('down'));
2029
                    }
2030
                    if (api_is_allowed_to_edit(false, true)) {
2031
                        if ($disableEdit === true) {
2032
                            $modify_icons .= Display::url($deleteIconDisable, '#');
2033
                        } else {
2034
                            $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$announcementId."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
2035
                                    api_htmlentities(
2036
                                        get_lang('Please confirm your choice'),
2037
                                        ENT_QUOTES,
2038
                                        api_get_system_encoding()
2039
                                    )
2040
                                )."')) return false;\">".
2041
                                $deleteIcon."</a>";
2042
                        }
2043
                    }
2044
                    $iterator++;
2045
                } else {
2046
                    $modify_icons = Display::url(
2047
                        Display::return_icon('default.png'),
2048
                        $actionUrl.'&action=view&id='.$announcementId
2049
                    );
2050
                }
2051
2052
                $results[] = [
2053
                    'id' => $announcementId,
2054
                    'title' => $title,
2055
                    'username' => $username_span,
2056
                    'insert_date' => api_convert_and_format_date(
2057
                        $announcement->getResourceNode()->getCreatedAt(),
2058
                        DATE_TIME_FORMAT_LONG
2059
                    ),
2060
                    'lastedit_date' => api_convert_and_format_date(
2061
                        $announcement->getResourceNode()->getUpdatedAt(),
2062
                        DATE_TIME_FORMAT_LONG
2063
                    ),
2064
                    'actions' => $modify_icons,
2065
                ];
2066
            }
2067
            $displayed[] = $announcementId;
2068
        }
2069
2070
        return $results;
2071
    }
2072
2073
    /**
2074
     * @return int
2075
     */
2076
    public static function getNumberAnnouncements()
2077
    {
2078
        // Maximum title messages to display
2079
        $maximum = '12';
2080
        // Database Table Definitions
2081
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
2082
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
2083
2084
        $session_id = api_get_session_id();
2085
        $courseInfo = api_get_course_info();
2086
        $courseId = $courseInfo['real_id'];
2087
        $userId = api_get_user_id();
2088
        $condition_session = api_get_session_condition(
2089
            $session_id,
2090
            true,
2091
            true,
2092
            'announcement.session_id'
2093
        );
2094
2095
        $repo = Container::getAnnouncementRepository();
2096
        $course = api_get_course_entity($courseId);
2097
        $session = api_get_session_entity($session_id);
2098
        $group = api_get_group_entity(api_get_group_id());
2099
2100
        if (api_is_allowed_to_edit(false, true)) {
2101
            // check teacher status
2102
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2103
                if (api_get_group_id() == 0) {
2104
                    $group_condition = '';
2105
                } else {
2106
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
2107
                }
2108
2109
                $sql = "SELECT
2110
                            announcement.*,
2111
                            ip.visibility,
2112
                            ip.to_group_id,
2113
                            ip.insert_user_id
2114
                        FROM $tbl_announcement announcement
2115
                        INNER JOIN $tbl_item_property ip
2116
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2117
                        WHERE
2118
                            announcement.c_id = $courseId AND
2119
                            ip.c_id = $courseId AND
2120
                            ip.tool = 'announcement' AND
2121
                            ip.visibility <> '2'
2122
                            $group_condition
2123
                            $condition_session
2124
                        GROUP BY ip.ref
2125
                        ORDER BY display_order DESC
2126
                        LIMIT 0, $maximum";
2127
2128
                $qb = $repo->getResourcesByCourse($course, $session, $group);
2129
                $qb->select('count(resource)');
2130
                $count = $qb->getQuery()->getSingleScalarResult();
2131
2132
                return $count;
2133
2134
            }
2135
        } else {
2136
            // students only get to see the visible announcements
2137
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2138
                $group_memberships = GroupManager::get_group_ids(
2139
                    $courseInfo['real_id'],
2140
                    $userId
2141
                );
2142
2143
                if ((api_get_course_setting('allow_user_edit_announcement') &&
2144
                    !api_is_anonymous())
2145
                ) {
2146
                    if (api_get_group_id() == 0) {
2147
                        $cond_user_id = " AND (
2148
                        ip.lastedit_user_id = '".$userId."' OR (
2149
                            ip.to_user_id='".$userId."' OR
2150
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2151
                            ip.to_group_id IS NULL
2152
                            )
2153
                        )
2154
                        ";
2155
                    } else {
2156
                        $cond_user_id = " AND (
2157
                            ip.lastedit_user_id = '".$userId."'OR
2158
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2159
                            ip.to_group_id IS NULL
2160
                        )";
2161
                    }
2162
                } else {
2163
                    if (api_get_group_id() == 0) {
2164
                        $cond_user_id = " AND (
2165
                            ip.to_user_id='".$userId."' OR
2166
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2167
                            ip.to_group_id IS NULL
2168
                        ) ";
2169
                    } else {
2170
                        $cond_user_id = " AND (
2171
                            ip.to_user_id='".$userId."' OR
2172
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2173
                            ip.to_group_id IS NULL
2174
                        ) ";
2175
                    }
2176
                }
2177
2178
                // the user is member of several groups => display personal announcements AND
2179
                // his group announcements AND the general announcements
2180
                if (is_array($group_memberships) && count($group_memberships) > 0) {
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.id = ip.ref AND announcement.c_id = ip.c_id)
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
                    // the user is not member of any group
2197
                    // this is an identified user => show the general announcements AND his personal announcements
2198
                    if ($userId) {
2199
                        if ((api_get_course_setting('allow_user_edit_announcement') &&
2200
                            !api_is_anonymous())
2201
                        ) {
2202
                            $cond_user_id = " AND (
2203
                                ip.lastedit_user_id = '".$userId."' OR
2204
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2205
                            ) ";
2206
                        } else {
2207
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
2208
                        }
2209
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2210
                                FROM $tbl_announcement announcement
2211
                                INNER JOIN $tbl_item_property ip
2212
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2213
                                WHERE
2214
                                    announcement.c_id = $courseId AND
2215
                                    ip.c_id = $courseId AND
2216
                                    ip.tool='announcement' AND
2217
                                    ip.visibility='1'
2218
                                    $cond_user_id
2219
                                    $condition_session
2220
                                GROUP BY ip.ref
2221
                                ORDER BY display_order DESC
2222
                                LIMIT 0, $maximum";
2223
                    } else {
2224
                        if (api_get_course_setting('allow_user_edit_announcement')) {
2225
                            $cond_user_id = " AND (
2226
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
2227
                            ) ";
2228
                        } else {
2229
                            $cond_user_id = " AND ip.to_group_id='0' ";
2230
                        }
2231
2232
                        // the user is not identiefied => show only the general announcements
2233
                        $sql = "SELECT
2234
                                    announcement.*,
2235
                                    ip.visibility,
2236
                                    ip.to_group_id,
2237
                                    ip.insert_user_id
2238
                                FROM $tbl_announcement announcement
2239
                                INNER JOIN $tbl_item_property ip
2240
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2241
                                WHERE
2242
                                    announcement.c_id = $courseId AND
2243
                                    ip.c_id = $courseId AND
2244
                                    ip.tool='announcement' AND
2245
                                    ip.visibility='1' AND
2246
                                    ip.to_group_id='0'
2247
                                    $condition_session
2248
                                GROUP BY ip.ref
2249
                                ORDER BY display_order DESC
2250
                                LIMIT 0, $maximum";
2251
                    }
2252
                }
2253
            }
2254
        }
2255
2256
        $result = Database::query($sql);
2257
2258
        return Database::num_rows($result);
2259
    }
2260
}
2261