Passed
Push — master ( fba8cd...2c308e )
by Julito
09:56 queued 11s
created

get_all_annoucement_by_course()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 41
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 22
nc 1
nop 2
dl 0
loc 41
rs 9.568
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
6
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
7
use Chamilo\CoreBundle\Entity\Resource\ResourceLink;
8
use Chamilo\CoreBundle\Framework\Container;
9
use Chamilo\CourseBundle\Entity\CAnnouncement;
10
11
/**
12
 * Include file with functions for the announcements module.
13
 *
14
 * @author jmontoya
15
 *
16
 * @todo use OOP
17
 */
18
class AnnouncementManager
19
{
20
    /**
21
     * Constructor.
22
     */
23
    public function __construct()
24
    {
25
    }
26
27
    /**
28
     * @return array
29
     */
30
    public static function getTags()
31
    {
32
        $tags = [
33
            '((user_name))',
34
            '((user_email))',
35
            '((user_firstname))',
36
            '((user_lastname))',
37
            '((user_official_code))',
38
            '((course_title))',
39
            '((course_link))',
40
        ];
41
42
        $tags[] = '((teachers))';
43
44
        $extraField = new ExtraField('user');
45
        $extraFields = $extraField->get_all(['filter = ?' => 1]);
46
        if (!empty($extraFields)) {
47
            foreach ($extraFields as $extra) {
48
                $tags[] = "((extra_".$extra['variable']."))";
49
            }
50
        }
51
        $sessionId = api_get_session_id();
52
        if (!empty($sessionId)) {
53
            $tags[] = '((coaches))';
54
            $tags[] = '((general_coach))';
55
            $tags[] = '((general_coach_email))';
56
        }
57
58
        return $tags;
59
    }
60
61
    /**
62
     * @param int    $userId
63
     * @param string $content
64
     * @param string $courseCode
65
     * @param int    $sessionId
66
     *
67
     * @return string
68
     */
69
    public static function parseContent(
70
        $userId,
71
        $content,
72
        $courseCode,
73
        $sessionId = 0
74
    ) {
75
        $readerInfo = api_get_user_info($userId, false, false, true, true);
76
        $courseInfo = api_get_course_info($courseCode);
77
        $teacherList = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code']);
78
79
        $generalCoachName = '';
80
        $generalCoachEmail = '';
81
        $coaches = '';
82
        if (!empty($sessionId)) {
83
            $sessionInfo = api_get_session_info($sessionId);
84
            $coaches = CourseManager::get_coachs_from_course_to_string(
85
                $sessionId,
86
                $courseInfo['real_id']
87
            );
88
89
            $generalCoach = api_get_user_info($sessionInfo['id_coach']);
90
            $generalCoachName = $generalCoach['complete_name'];
91
            $generalCoachEmail = $generalCoach['email'];
92
        }
93
94
        $data = [];
95
        $data['user_name'] = '';
96
        $data['user_firstname'] = '';
97
        $data['user_lastname'] = '';
98
        $data['user_official_code'] = '';
99
        $data['user_email'] = '';
100
        if (!empty($readerInfo)) {
101
            $data['user_name'] = $readerInfo['username'];
102
            $data['user_email'] = $readerInfo['email'];
103
            $data['user_firstname'] = $readerInfo['firstname'];
104
            $data['user_lastname'] = $readerInfo['lastname'];
105
            $data['user_official_code'] = $readerInfo['official_code'];
106
        }
107
108
        $data['course_title'] = $courseInfo['name'];
109
        $courseLink = api_get_course_url($courseCode, $sessionId);
110
        $data['course_link'] = Display::url($courseLink, $courseLink);
111
        $data['teachers'] = $teacherList;
112
113
        if (!empty($readerInfo)) {
114
            $extraField = new ExtraField('user');
115
            $extraFields = $extraField->get_all(['filter = ?' => 1]);
116
            if (!empty($extraFields)) {
117
                foreach ($extraFields as $extra) {
118
                    $data['extra_'.$extra['variable']] = '';
119
                }
120
            }
121
122
            if (!empty($readerInfo['extra'])) {
123
                foreach ($readerInfo['extra'] as $extra) {
124
                    if (isset($extra['value'])) {
125
                        /** @var \Chamilo\CoreBundle\Entity\ExtraFieldValues $value */
126
                        $value = $extra['value'];
127
                        if ($value instanceof ExtraFieldValues) {
128
                            $field = $value->getField();
129
                            if ($field instanceof ExtraFieldEntity) {
130
                                $data['extra_'.$field->getVariable()] = $value->getValue();
131
                            }
132
                        }
133
                    }
134
                }
135
            }
136
        }
137
138
        if (!empty($sessionId)) {
139
            $data['coaches'] = $coaches;
140
            $data['general_coach'] = $generalCoachName;
141
            $data['general_coach_email'] = $generalCoachEmail;
142
        }
143
144
        $tags = self::getTags();
145
        foreach ($tags as $tag) {
146
            $simpleTag = str_replace(['((', '))'], '', $tag);
147
            $value = isset($data[$simpleTag]) ? $data[$simpleTag] : '';
148
            $content = str_replace($tag, $value, $content);
149
        }
150
151
        return $content;
152
    }
153
154
    /**
155
     * Gets all announcements from a course.
156
     *
157
     * @param array $course_info
158
     * @param int   $session_id
159
     *
160
     * @return array html with the content and count of announcements or false otherwise
161
     */
162
    public static function get_all_annoucement_by_course($course_info, $session_id = 0)
163
    {
164
        $session_id = (int) $session_id;
165
        $courseId = $course_info['real_id'];
166
167
        $repo = Container::getAnnouncementRepository();
168
        $criteria = [
169
            'cId' => $courseId,
170
        ];
171
172
        return $repo->findBy($criteria);
173
174
175
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
0 ignored issues
show
Unused Code introduced by
$tbl_announcement = Data...ble(TABLE_ANNOUNCEMENT) is not reachable.

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

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

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

    return false;
}

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

Loading history...
176
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
177
178
        $sql = "SELECT DISTINCT
179
                    announcement.id,
180
                    announcement.title,
181
                    announcement.content
182
				FROM $tbl_announcement announcement
183
				INNER JOIN $tbl_item_property i
184
				ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
185
				WHERE
186
                    i.tool='announcement' AND
187
                    announcement.session_id  = '$session_id' AND
188
                    announcement.c_id = $courseId AND
189
                    i.c_id = $courseId
190
				ORDER BY display_order DESC";
191
        $rs = Database::query($sql);
192
        $num_rows = Database::num_rows($rs);
193
        if ($num_rows > 0) {
194
            $list = [];
195
            while ($row = Database::fetch_array($rs)) {
196
                $list[] = $row;
197
            }
198
199
            return $list;
200
        }
201
202
        return false;
203
    }
204
205
    /**
206
     * This functions switches the visibility a course resource
207
     * using the visibility field in 'item_property'.
208
     *
209
     * @param array $courseInfo
210
     * @param int   $id         ID of the element of the corresponding type
211
     *
212
     * @return bool False on failure, True on success
213
     */
214
    public static function change_visibility_announcement($courseInfo, $id)
215
    {
216
        $session_id = api_get_session_id();
217
        $item_visibility = api_get_item_visibility(
218
            $courseInfo,
219
            TOOL_ANNOUNCEMENT,
220
            $id,
221
            $session_id
222
        );
223
        if ($item_visibility == '1') {
224
            api_item_property_update(
225
                $courseInfo,
226
                TOOL_ANNOUNCEMENT,
227
                $id,
228
                'invisible',
229
                api_get_user_id()
230
            );
231
        } else {
232
            api_item_property_update(
233
                $courseInfo,
234
                TOOL_ANNOUNCEMENT,
235
                $id,
236
                'visible',
237
                api_get_user_id()
238
            );
239
        }
240
241
        return true;
242
    }
243
244
    /**
245
     * Deletes an announcement.
246
     *
247
     * @param array $courseInfo the course array
248
     * @param int   $id         the announcement id
249
     */
250
    public static function delete_announcement($courseInfo, $id)
251
    {
252
        $repo = Container::getAnnouncementRepository();
253
        $criteria = [
254
            'cId' => $courseInfo['real_id'],
255
            'id' =>$id
256
        ];
257
        $announcement = $repo->findOneBy($criteria);
258
        $repo->getEntityManager()->remove($announcement);
259
        $repo->getEntityManager()->flush();
260
261
        /*
262
        api_item_property_update(
263
            $courseInfo,
264
            TOOL_ANNOUNCEMENT,
265
            $id,
266
            'delete',
267
            api_get_user_id()
268
        );*/
269
    }
270
271
    /**
272
     * Deletes all announcements by course.
273
     *
274
     * @param array $courseInfo the course array
275
     */
276
    public static function delete_all_announcements($courseInfo)
277
    {
278
        $repo = Container::getAnnouncementRepository();
279
        $announcements = self::get_all_annoucement_by_course(
280
            $courseInfo,
281
            api_get_session_id()
282
        );
283
284
        if (!empty($announcements)) {
285
            foreach ($announcements as $announcement) {
286
                $repo->getEntityManager()->remove($announcement);
287
                /*api_item_property_update(
288
                    $courseInfo,
289
                    TOOL_ANNOUNCEMENT,
290
                    $annon['id'],
291
                    'delete',
292
                    api_get_user_id()
293
                );*/
294
            }
295
        }
296
        $repo->getEntityManager()->flush();
297
    }
298
299
    /**
300
     * @param string $title
301
     * @param int    $courseId
302
     * @param int    $sessionId
303
     * @param int    $visibility 1 or 0
304
     *
305
     * @return mixed
306
     */
307
    public static function getAnnouncementsByTitle(
308
        $title,
309
        $courseId,
310
        $sessionId = 0,
311
        $visibility = 1
312
    ) {
313
        $dql = "SELECT a
314
                FROM ChamiloCourseBundle:CAnnouncement a
315
                JOIN ChamiloCourseBundle:CItemProperty ip
316
                WITH a.id = ip.ref AND a.cId = ip.course
317
                WHERE
318
                    ip.tool = 'announcement' AND
319
                    a.cId = :course AND
320
                    a.sessionId = :session AND
321
                    a.title like :title AND
322
                    ip.visibility = :visibility
323
                ORDER BY a.displayOrder DESC";
324
325
        $qb = Database::getManager()->createQuery($dql);
326
        $result = $qb->execute(
327
            [
328
                'course' => $courseId,
329
                'session' => $sessionId,
330
                'visibility' => $visibility,
331
                'title' => "%$title%",
332
            ]
333
        );
334
335
        return $result;
336
    }
337
338
    /**
339
     * @param int $announcementId
340
     * @param int $courseId
341
     * @param int $userId
342
     * @param int $groupId
343
     *
344
     * @return CAnnouncement
345
     */
346
    public static function getAnnouncementInfoById(
347
        $announcementId,
348
        $courseId,
349
        $userId,
350
        $groupId = 0
351
    ) {
352
        $announcementId = (int) $announcementId;
353
354
        $repo = Container::getAnnouncementRepository();
355
356
        return $repo->find($announcementId);
357
358
        $courseId = (int) $courseId;
0 ignored issues
show
Unused Code introduced by
$courseId = (int)$courseId is not reachable.

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

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

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

    return false;
}

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

Loading history...
359
        $userId = (int) $userId;
360
        $groupId = (int) $groupId;
361
362
        if (api_is_allowed_to_edit(false, true) ||
363
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
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
                        a.cId = :course
373
                    ORDER BY a.displayOrder DESC";
374
        } else {
375
            $groupList[] = $groupId;
376
377
            if (api_get_user_id() != 0) {
378
                $extraGroupCondition = '';
379
                if (!empty($groupId)) {
380
                    $groupProperties = GroupManager::get_group_properties($groupId);
381
                    if ($groupProperties['announcements_state'] == GroupManager::TOOL_PRIVATE_BETWEEN_USERS) {
382
                        $extraGroupCondition = " AND (
383
                            ip.toUser = $userId AND ip.group = $groupId OR
384
                            (ip.group IN ('0') OR ip.group IS NULL) OR
385
                            (ip.group = $groupId AND (ip.toUser IS NULL OR ip.toUser = 0))
386
                        )";
387
                    }
388
                }
389
390
                $dql = "SELECT a, ip
391
                        FROM ChamiloCourseBundle:CAnnouncement a
392
                        JOIN ChamiloCourseBundle:CItemProperty ip
393
                        WITH a.id = ip.ref AND a.cId = ip.course
394
                        WHERE
395
                            a.id = :announcement AND
396
                            ip.tool='announcement' AND
397
                            (
398
                                ip.toUser = $userId OR
399
                                ip.group IN ('0', '".$groupId."') OR
400
                                ip.group IS NULL
401
                            ) AND
402
                            ip.visibility = '1' AND
403
                            ip.course = :course
404
                            $extraGroupCondition
405
                        ORDER BY a.displayOrder DESC";
406
            } else {
407
                $dql = "SELECT a, ip
408
                        FROM ChamiloCourseBundle:CAnnouncement a
409
                        JOIN ChamiloCourseBundle:CItemProperty ip
410
                        WITH a.id = ip.ref AND a.cId = ip.course
411
                        WHERE
412
                            a.id = :announcement AND
413
                            ip.tool = 'announcement' AND
414
                            (ip.group = '0' OR ip.group IS NULL) AND
415
                            ip.visibility = '1' AND
416
                            ip.course = :course";
417
            }
418
        }
419
420
        $qb = Database::getManager()->createQuery($dql);
421
        $result = $qb->execute(
422
            [
423
                'announcement' => $announcementId,
424
                'course' => $courseId,
425
            ]
426
        );
427
428
        if (!empty($result)) {
429
            return [
430
                'announcement' => $result[0],
431
                'item_property' => $result[1],
432
            ];
433
        }
434
435
        return [];
436
    }
437
438
    /**
439
     * Displays one specific announcement.
440
     *
441
     * @param int $id, the id of the announcement you want to display
442
     *
443
     * @return string
444
     */
445
    public static function displayAnnouncement($id)
446
    {
447
        $id = (int) $id;
448
449
        if (empty($id)) {
450
            return '';
451
        }
452
453
        $html = '';
454
        $course = api_get_course_entity(api_get_course_int_id());
455
        $session = api_get_session_entity(api_get_session_id());
456
457
        $announcement = self::getAnnouncementInfoById(
458
            $id,
459
            api_get_course_int_id(),
460
            api_get_user_id(),
461
            api_get_group_id()
462
        );
463
464
        if (empty($announcement)) {
465
            return '';
466
        }
467
468
        $title = $announcement->getTitle();
469
        $content = $announcement->getContent();
470
471
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
472
        $html .= "<tr><td><h2>".$title."</h2></td></tr>";
473
474
        if (api_is_allowed_to_edit(false, true) ||
475
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
476
        ) {
477
            $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
478
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
479
480
            $image_visibility = 'invisible';
481
            $alt_visibility = get_lang('Visible');
482
            if ($announcement->isVisible($course, $session)) {
483
                $image_visibility = 'visible';
484
                $alt_visibility = get_lang('Hide');
485
            }
486
            global $stok;
487
            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=showhide&id=".$id."&sec_token=".$stok."\">".
488
                Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
489
490
            if (api_is_allowed_to_edit(false, true)) {
491
                $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))."')) return false;\">".
492
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
493
                    "</a>";
494
            }
495
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
496
        }
497
498
        // The user id is always the current one.
499
        $toUserId = api_get_user_id();
500
        $content = self::parseContent(
501
            $toUserId,
502
            $content,
503
            api_get_course_id(),
504
            api_get_session_id()
505
        );
506
507
        $html .= "<tr><td>$content</td></tr>";
508
        $html .= "<tr>";
509
        $html .= "<td class=\"announcements_datum\">".get_lang('Latest update')." : ";
510
        $lastEdit = $announcement->getResourceNode()->getUpdatedAt();
511
        $html .= Display::dateToStringAgoAndLongDate($lastEdit);
512
        $html .= "</td></tr>";
513
514
        $allow = !api_get_configuration_value('hide_announcement_sent_to_users_info');
515
        if ($allow && api_is_allowed_to_edit(false, true)) {
516
            $sent_to = self::sent_to('announcement', $id);
517
            $sentToForm = self::sent_to_form($sent_to);
518
            $html .= Display::tag(
519
                'td',
520
                get_lang('Visible to').': '.$sentToForm,
521
                ['class' => 'announcements_datum']
522
            );
523
        }
524
        $attachment_list = self::get_attachment($id);
525
526
        if (count($attachment_list) > 0) {
527
            $html .= "<tr><td>";
528
            $realname = $attachment_list['path'];
529
            $user_filename = $attachment_list['filename'];
530
            $full_file_name = 'download.php?'.api_get_cidreq().'&file='.$realname;
531
            $html .= '<br/>';
532
            $html .= Display::return_icon('attachment.gif', get_lang('Attachment'));
533
            $html .= '<a href="'.$full_file_name.' "> '.$user_filename.' </a>';
534
            $html .= ' - <span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
535
            if (api_is_allowed_to_edit(false, true)) {
536
                $url = api_get_self()."?".api_get_cidreq().
537
                    "&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok;
538
                $html .= Display::url(
539
                    Display::return_icon(
540
                        'delete.png',
541
                        get_lang('Delete'),
542
                        '',
543
                        16
544
                    ),
545
                    $url
546
                );
547
            }
548
            $html .= '</td></tr>';
549
        }
550
        $html .= '</table>';
551
552
        return $html;
553
    }
554
555
    /**
556
     * @param array $courseInfo
557
     *
558
     * @return int
559
     */
560
    public static function getLastAnnouncementOrder($courseInfo)
561
    {
562
        if (empty($courseInfo)) {
563
            return 0;
564
        }
565
566
        if (!isset($courseInfo['real_id'])) {
567
            return false;
568
        }
569
570
        $courseId = $courseInfo['real_id'];
571
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
572
        $sql = "SELECT MAX(display_order)
573
                FROM $table
574
                WHERE c_id = $courseId ";
575
        $result = Database::query($sql);
576
577
        $order = 0;
578
        if (Database::num_rows($result)) {
579
            $row = Database::fetch_array($result);
580
            $order = (int) $row[0] + 1;
581
        }
582
583
        return $order;
584
    }
585
586
    /**
587
     * Store an announcement in the database (including its attached file if any).
588
     *
589
     * @param array  $courseInfo
590
     * @param int    $sessionId
591
     * @param string $title                Announcement title (pure text)
592
     * @param string $newContent           Content of the announcement (can be HTML)
593
     * @param array  $sentTo               Array of users and groups to send the announcement to
594
     * @param array  $file                 uploaded file $_FILES
595
     * @param string $file_comment         Comment describing the attachment
596
     * @param string $end_date
597
     * @param bool   $sendToUsersInSession
598
     * @param int    $authorId
599
     *
600
     * @return int false on failure, ID of the announcement on success
601
     */
602
    public static function add_announcement(
603
        $courseInfo,
604
        $sessionId,
605
        $title,
606
        $newContent,
607
        $sentTo,
608
        $file = [],
609
        $file_comment = null,
610
        $end_date = null,
611
        $sendToUsersInSession = false,
612
        $authorId = 0
613
    ) {
614
        if (empty($courseInfo)) {
615
            return false;
616
        }
617
618
        if (!isset($courseInfo['real_id'])) {
619
            return false;
620
        }
621
622
        $courseId = $courseInfo['real_id'];
623
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
624
        $authorId = empty($authorId) ? api_get_user_id() : $authorId;
625
626
        if (empty($end_date)) {
627
            $end_date = api_get_utc_datetime();
628
        }
629
630
        $order = self::getLastAnnouncementOrder($courseInfo);
631
632
        $announcement = new CAnnouncement();
633
        $announcement
634
            ->setCId($courseId)
635
            ->setContent($newContent)
636
            ->setTitle($title)
637
            ->setEndDate(new DateTime($end_date))
638
            ->setDisplayOrder($order)
639
            ->setSessionId($sessionId)
640
        ;
641
642
        $repo = Container::getAnnouncementRepository();
643
        $repo->addResourceToCourse(
644
            $announcement,
645
            ResourceLink::VISIBILITY_PUBLISHED,
646
            api_get_user_entity($authorId),
647
            api_get_course_entity($courseId),
648
            api_get_session_entity($sessionId),
649
            api_get_group_entity()
650
        );
651
        $repo->getEntityManager()->flush();
652
        $last_id = $announcement->getIid();
653
654
        if (empty($last_id)) {
655
            return false;
656
        }
657
658
        $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
659
        Database::query($sql);
660
661
        if (!empty($file)) {
662
            self::add_announcement_attachment_file(
663
                $last_id,
664
                $file_comment,
665
                $_FILES['user_upload']
666
            );
667
        }
668
669
        // store in item_property (first the groups, then the users
670
        if (empty($sentTo) ||
671
            (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')
672
        ) {
673
            // The message is sent to EVERYONE, so we set the group to 0
674
            /*api_item_property_update(
675
                $courseInfo,
676
                TOOL_ANNOUNCEMENT,
677
                $last_id,
678
                'AnnouncementAdded',
679
                $authorId,
680
                '0',
681
                null,
682
                null,
683
                null,
684
                $sessionId
685
            );*/
686
        } else {
687
            $send_to = CourseManager::separateUsersGroups($sentTo);
688
            $batchSize = 20;
689
            $em = Database::getManager();
690
            // Storing the selected groups
691
            if (is_array($send_to['groups']) &&
692
                !empty($send_to['groups'])
693
            ) {
694
                $counter = 1;
695
                foreach ($send_to['groups'] as $group) {
696
                    $groupInfo = GroupManager::get_group_properties($group);
697
                    /*api_item_property_update(
698
                        $courseInfo,
699
                        TOOL_ANNOUNCEMENT,
700
                        $last_id,
701
                        'AnnouncementAdded',
702
                        $authorId,
703
                        $groupInfo
704
                    );*/
705
                }
706
            }
707
708
            // Storing the selected users
709
            if (is_array($send_to['users'])) {
710
                $counter = 1;
711
                foreach ($send_to['users'] as $user) {
712
                    /*api_item_property_update(
713
                        $courseInfo,
714
                        TOOL_ANNOUNCEMENT,
715
                        $last_id,
716
                        'AnnouncementAdded',
717
                        $authorId,
718
                        '',
719
                        $user
720
                    );*/
721
                }
722
            }
723
        }
724
725
        if ($sendToUsersInSession) {
726
            self::addAnnouncementToAllUsersInSessions($last_id);
727
        }
728
729
        return $announcement;
730
    }
731
732
    /**
733
     * @param string $title
734
     * @param string $newContent
735
     * @param int    $groupId
736
     * @param array  $to_users
737
     * @param array  $file
738
     * @param string $file_comment
739
     * @param bool   $sendToUsersInSession
740
     *
741
     * @return bool|int
742
     */
743
    public static function addGroupAnnouncement(
744
        $title,
745
        $newContent,
746
        $groupId,
747
        $to_users,
748
        $file = [],
749
        $file_comment = '',
750
        $sendToUsersInSession = false
751
    ) {
752
        $courseInfo = api_get_course_info();
753
754
        // Database definitions
755
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
756
        $order = self::getLastAnnouncementOrder($courseInfo);
757
758
        $now = api_get_utc_datetime();
759
        $courseId = api_get_course_int_id();
760
        $sessionId = api_get_session_id();
761
        $authorId = api_get_user_id();
762
763
        $announcement = new CAnnouncement();
764
        $announcement
765
            ->setCId($courseId)
766
            ->setContent($newContent)
767
            ->setTitle($title)
768
            ->setEndDate(new DateTime($now))
769
            ->setDisplayOrder($order)
770
            ->setSessionId($sessionId)
771
        ;
772
773
        $repo = Container::getAnnouncementRepository();
774
        $repo->addResourceToCourse(
775
            $announcement,
776
            ResourceLink::VISIBILITY_PUBLISHED,
777
            api_get_user_entity($authorId),
778
            api_get_course_entity($courseId),
779
            api_get_session_entity($sessionId),
780
            api_get_group_entity()
781
        );
782
        $repo->getEntityManager()->flush();
783
        $last_id = $announcement->getIid();
784
785
        // Store the attach file
786
        if ($last_id) {
787
            $sql = "UPDATE $table SET id = iid
788
                    WHERE iid = $last_id";
789
            Database::query($sql);
790
791
            if (!empty($file)) {
792
                self::add_announcement_attachment_file(
793
                    $last_id,
794
                    $file_comment,
795
                    $file
796
                );
797
            }
798
799
            $send_to_users = CourseManager::separateUsersGroups($to_users);
800
801
            // if nothing was selected in the menu then send to all the group
802
            $sentToAllGroup = false;
803
            if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
804
                $groupInfo = GroupManager::get_group_properties($groupId);
805
                api_item_property_update(
806
                    $courseInfo,
807
                    TOOL_ANNOUNCEMENT,
808
                    $last_id,
809
                    'AnnouncementAdded',
810
                    api_get_user_id(),
811
                    $groupInfo
812
                );
813
                $sentToAllGroup = true;
814
            }
815
816
            if ($sentToAllGroup === false) {
817
                if (!empty($send_to_users['groups'])) {
818
                    foreach ($send_to_users['groups'] as $group) {
819
                        $groupInfo = GroupManager::get_group_properties($group);
820
                        api_item_property_update(
821
                            $courseInfo,
822
                            TOOL_ANNOUNCEMENT,
823
                            $last_id,
824
                            'AnnouncementAdded',
825
                            api_get_user_id(),
826
                            $groupInfo
827
                        );
828
                    }
829
                }
830
831
                $groupInfo = GroupManager::get_group_properties($groupId);
832
                if (!empty($send_to_users['users'])) {
833
                    foreach ($send_to_users['users'] as $user) {
834
                        api_item_property_update(
835
                            $courseInfo,
836
                            TOOL_ANNOUNCEMENT,
837
                            $last_id,
838
                            'AnnouncementAdded',
839
                            api_get_user_id(),
840
                            $groupInfo,
841
                            $user
842
                        );
843
                    }
844
                }
845
            }
846
847
            if ($sendToUsersInSession) {
848
                self::addAnnouncementToAllUsersInSessions($last_id);
849
            }
850
        }
851
852
        return $last_id;
853
    }
854
855
    /**
856
     * This function stores the announcement item in the announcement table
857
     * and updates the item_property table.
858
     *
859
     * @param int    $id                   id of the announcement
860
     * @param string $title
861
     * @param string $newContent
862
     * @param array  $to                   users that will receive the announcement
863
     * @param mixed  $file                 attachment
864
     * @param string $file_comment         file comment
865
     * @param bool   $sendToUsersInSession
866
     */
867
    public static function edit_announcement(
868
        $id,
869
        $title,
870
        $newContent,
871
        $to,
872
        $file = [],
873
        $file_comment = '',
874
        $sendToUsersInSession = false
875
    ) {
876
        $courseInfo = api_get_course_info();
877
        $id = (int) $id;
878
879
        $repo = Container::getAnnouncementRepository();
880
        /** @var CAnnouncement $announcement */
881
        $announcement = $repo->find($id);
882
883
        $announcement
884
            ->setTitle($title)
885
            ->setContent($newContent)
886
        ;
887
        $repo->getEntityManager()->persist($announcement);
888
        $repo->getEntityManager()->flush();
889
890
        // save attachment file
891
        $row_attach = self::get_attachment($id);
892
893
        $id_attach = 0;
894
        if ($row_attach) {
895
            $id_attach = (int) $row_attach['id'];
896
        }
897
898
        if (!empty($file)) {
899
            if (empty($id_attach)) {
900
                self::add_announcement_attachment_file(
901
                    $id,
902
                    $file_comment,
903
                    $file
904
                );
905
            } else {
906
                self::edit_announcement_attachment_file(
907
                    $id_attach,
908
                    $file,
909
                    $file_comment
910
                );
911
            }
912
        }
913
914
        // We remove everything from item_property for this
915
        /*$sql = "DELETE FROM $tbl_item_property
916
                WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
917
        Database::query($sql);*/
918
919
        if ($sendToUsersInSession) {
920
            self::addAnnouncementToAllUsersInSessions($id);
921
        }
922
923
        // store in item_property (first the groups, then the users
924
        if (!empty($to)) {
925
            // !is_null($to): when no user is selected we send it to everyone
926
            $send_to = CourseManager::separateUsersGroups($to);
927
            $resourceNode = $announcement->getResourceNode();
928
929
            // storing the selected groups
930
            if (is_array($send_to['groups'])) {
931
                foreach ($send_to['groups'] as $group) {
932
                    $groupInfo = api_get_group_entity($group);
933
                    $repo->addResourceToCourseGroup($resourceNode, $groupInfo);
934
                    /*
935
                    if ($groupInfo) {
936
                        api_item_property_update(
937
                            $courseInfo,
938
                            TOOL_ANNOUNCEMENT,
939
                            $id,
940
                            'AnnouncementUpdated',
941
                            api_get_user_id(),
942
                            $groupInfo
943
                        );
944
                    }*/
945
                }
946
            }
947
948
            // storing the selected users
949
            if (is_array($send_to['users'])) {
950
                foreach ($send_to['users'] as $user) {
951
                    $user = api_get_user_entity($user);
952
                    $repo->addResourceToUser($resourceNode, $user);
953
                    /*api_item_property_update(
954
                        $courseInfo,
955
                        TOOL_ANNOUNCEMENT,
956
                        $id,
957
                        'AnnouncementUpdated',
958
                        api_get_user_id(),
959
                        0,
960
                        $user
961
                    );*/
962
                }
963
            }
964
965
            // Send to everyone
966
            if (isset($to[0]) && $to[0] === 'everyone') {
967
                /*api_item_property_update(
968
                    $courseInfo,
969
                    TOOL_ANNOUNCEMENT,
970
                    $id,
971
                    'AnnouncementUpdated',
972
                    api_get_user_id(),
973
                    0
974
                );*/
975
            }
976
        } else {
977
            // the message is sent to everyone, so we set the group to 0
978
            /*api_item_property_update(
979
                $courseInfo,
980
                TOOL_ANNOUNCEMENT,
981
                $id,
982
                'AnnouncementUpdated',
983
                api_get_user_id(),
984
                0
985
            );*/
986
        }
987
988
        $repo->getEntityManager()->flush();
989
990
        return $announcement;
991
    }
992
993
    /**
994
     * @param int $announcementId
995
     */
996
    public static function addAnnouncementToAllUsersInSessions($announcementId)
997
    {
998
        $courseCode = api_get_course_id();
999
        $courseInfo = api_get_course_info();
1000
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
1001
1002
        if (!empty($sessionList)) {
1003
            foreach ($sessionList as $sessionInfo) {
1004
                $sessionId = $sessionInfo['id'];
1005
                $userList = CourseManager::get_user_list_from_course_code(
1006
                    $courseCode,
1007
                    $sessionId
1008
                );
1009
1010
                if (!empty($userList)) {
1011
                    foreach ($userList as $user) {
1012
                        api_item_property_update(
1013
                            $courseInfo,
1014
                            TOOL_ANNOUNCEMENT,
1015
                            $announcementId,
1016
                            'AnnouncementUpdated',
1017
                            api_get_user_id(),
1018
                            0,
1019
                            $user['user_id'],
1020
                            0,
1021
                            0,
1022
                            $sessionId
1023
                        );
1024
                    }
1025
                }
1026
            }
1027
        }
1028
    }
1029
1030
    /**
1031
     * @param int $insert_id
1032
     *
1033
     * @return bool
1034
     */
1035
    public static function update_mail_sent($insert_id)
1036
    {
1037
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1038
        if ($insert_id != strval(intval($insert_id))) {
1039
            return false;
1040
        }
1041
        $insert_id = intval($insert_id);
1042
        $courseId = api_get_course_int_id();
1043
        // store the modifications in the table tbl_annoucement
1044
        $sql = "UPDATE $table SET email_sent='1'
1045
                WHERE c_id = $courseId AND id = $insert_id";
1046
        Database::query($sql);
1047
    }
1048
1049
    /**
1050
     * @param int $user_id
1051
     *
1052
     * @return array|bool
1053
     */
1054
    public static function getAnnoucementCourseTotalByUser($user_id)
1055
    {
1056
        $user_id = (int) $user_id;
1057
1058
        if (empty($user_id)) {
1059
            return false;
1060
        }
1061
1062
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1063
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1064
1065
        $sql = "SELECT DISTINCT
1066
                    announcement.c_id,
1067
                    count(announcement.id) count
1068
                FROM $tbl_announcement announcement
1069
                INNER JOIN $tbl_item_property ip
1070
                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1071
                WHERE
1072
                    ip.tool='announcement' AND
1073
                    (
1074
                      ip.to_user_id = '$user_id' AND
1075
                      (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1076
                    )
1077
                    AND ip.visibility='1'
1078
                    AND announcement.session_id  = 0
1079
                GROUP BY announcement.c_id";
1080
        $rs = Database::query($sql);
1081
        $num_rows = Database::num_rows($rs);
1082
        $result = [];
1083
        if ($num_rows > 0) {
1084
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1085
                if (empty($row['c_id'])) {
1086
                    continue;
1087
                }
1088
                $result[] = ['course' => api_get_course_info_by_id($row['c_id']), 'count' => $row['count']];
1089
            }
1090
        }
1091
1092
        return $result;
1093
    }
1094
1095
    /**
1096
     * this function gets all the groups of the course,
1097
     * not including linked courses.
1098
     */
1099
    public static function get_course_groups()
1100
    {
1101
        $session_id = api_get_session_id();
1102
        if ($session_id != 0) {
1103
            $new_group_list = CourseManager::get_group_list_of_course(
1104
                api_get_course_id(),
1105
                $session_id,
1106
                1
1107
            );
1108
        } else {
1109
            $new_group_list = CourseManager::get_group_list_of_course(
1110
                api_get_course_id(),
1111
                0,
1112
                1
1113
            );
1114
        }
1115
1116
        return $new_group_list;
1117
    }
1118
1119
    public static function getSenders(CAnnouncement $announcement)
1120
    {
1121
        $result = [];
1122
        $result['groups'] = [];
1123
        $result['users'] = [];
1124
1125
        $links = $announcement->getResourceNode()->getResourceLinks();
1126
1127
        /** @var ResourceLink $link */
1128
        foreach ($links as $link) {
1129
            if ($link->getUser()) {
1130
                $result['users'][] = $link->getUser()->getId();
1131
            }
1132
            if ($link->getGroup()) {
1133
                $result['groups'][] = $link->getGroup()->getId();
1134
            }
1135
        }
1136
1137
        return $result;
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 CAnnouncement $announcement
1145
     * @param bool          $includeGroupWhenLoadingUser
1146
     *
1147
     * @return array
1148
     */
1149
    public static function loadEditUsers($announcement, $includeGroupWhenLoadingUser = false)
1150
    {
1151
        $result = self::getSenders($announcement);
1152
        $to = [];
1153
1154
        foreach ($result['users'] as $itemId) {
1155
            $to[] = 'USER:'.$itemId;
1156
        }
1157
1158
        foreach ($result['groups'] as $itemId) {
1159
            $to[] = 'GROUP:'.$itemId;
1160
        }
1161
1162
        return $to;
1163
    }
1164
1165
    /**
1166
     * constructs the form to display all the groups and users the message has been sent to.
1167
     *
1168
     * @param array $sent_to_array
1169
     *                             input:
1170
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1171
     *                             the first level is a distinction between groups and users:
1172
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1173
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1174
     *                             containing all the id's of the groups (resp. users) who have received this message.
1175
     *
1176
     * @return string
1177
     *
1178
     * @author Patrick Cool <patrick.cool@>
1179
     */
1180
    public static function sent_to_form($sent_to_array)
1181
    {
1182
        // we find all the names of the groups
1183
        $group_names = self::get_course_groups();
1184
1185
        // we count the number of users and the number of groups
1186
        $number_users = 0;
1187
        if (isset($sent_to_array['users'])) {
1188
            $number_users = count($sent_to_array['users']);
1189
        }
1190
        $number_groups = 0;
1191
        if (isset($sent_to_array['groups'])) {
1192
            $number_groups = count($sent_to_array['groups']);
1193
        }
1194
1195
        $total_numbers = $number_users + $number_groups;
1196
1197
        // starting the form if there is more than one user/group
1198
        $output = [];
1199
        if ($total_numbers > 1) {
1200
            // outputting the name of the groups
1201
            if (is_array($sent_to_array['groups'])) {
1202
                foreach ($sent_to_array['groups'] as $group_id) {
1203
                    $users = GroupManager::getStudents($group_id, true);
1204
                    $userToArray = [];
1205
                    foreach ($users as $student) {
1206
                        $userToArray[] = $student['complete_name_with_username'];
1207
                    }
1208
                    $output[] =
1209
                        '<br />'.
1210
                        Display::label($group_names[$group_id]['name'], 'info').
1211
                        '&nbsp;'.implode(', ', $userToArray);
1212
                }
1213
            }
1214
1215
            if (isset($sent_to_array['users'])) {
1216
                if (is_array($sent_to_array['users'])) {
1217
                    $usersToArray = [];
1218
                    foreach ($sent_to_array['users'] as $user_id) {
1219
                        $user_info = api_get_user_info($user_id);
1220
                        $usersToArray[] = $user_info['complete_name_with_username'];
1221
                    }
1222
                    $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
1223
                }
1224
            }
1225
        } else {
1226
            // there is only one user/group
1227
            if (isset($sent_to_array['users']) && is_array($sent_to_array['users'])) {
1228
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1229
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1230
            }
1231
            if (isset($sent_to_array['groups']) &&
1232
                is_array($sent_to_array['groups']) &&
1233
                isset($sent_to_array['groups'][0]) &&
1234
                $sent_to_array['groups'][0] !== 0
1235
            ) {
1236
                $group_id = $sent_to_array['groups'][0];
1237
1238
                $users = GroupManager::getStudents($group_id, true);
1239
                $userToArray = [];
1240
                foreach ($users as $student) {
1241
                    $userToArray[] = $student['complete_name_with_username'];
1242
                }
1243
                $output[] =
1244
                    '<br />'.
1245
                    Display::label($group_names[$group_id]['name'], 'info').
1246
                    '&nbsp;'.implode(', ', $userToArray);
1247
            }
1248
            if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
1249
                $output[] = "&nbsp;".get_lang('All');
1250
            }
1251
        }
1252
1253
        if (!empty($output)) {
1254
            $output = array_filter($output);
1255
            if (count($output) > 0) {
1256
                $output = implode('<br />', $output);
1257
            }
1258
1259
            return $output;
1260
        }
1261
    }
1262
1263
    /**
1264
     * Returns all the users and all the groups a specific announcement item
1265
     * has been sent to.
1266
     *
1267
     * @param    string  The tool (announcement, agenda, ...)
1268
     * @param    int     ID of the element of the corresponding type
1269
     *
1270
     * @return array Array of users and groups to whom the element has been sent
1271
     */
1272
    public static function sent_to($tool, $id)
1273
    {
1274
        return [];
1275
1276
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
0 ignored issues
show
Unused Code introduced by
$table = Database::get_c...le(TABLE_ITEM_PROPERTY) is not reachable.

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

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

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

    return false;
}

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

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