Passed
Push — master ( 0334ca...02c608 )
by Julito
10:30
created

change_visibility_announcement()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 41
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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