Passed
Push — master ( c62d0d...73098b )
by Julito
10:41
created

AnnouncementManager::get_course_groups()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 0
dl 0
loc 18
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
6
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
7
use Chamilo\CoreBundle\Entity\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
        $announcement = $repo->find($id);
268
        if ($announcement) {
0 ignored issues
show
introduced by
$announcement is of type Chamilo\CoreBundle\Entity\ResourceInterface, thus it always evaluated to true.
Loading history...
269
            $repo->getEntityManager()->remove($announcement);
270
            $repo->getEntityManager()->flush();
271
        }
272
273
        /*
274
        api_item_property_update(
275
            $courseInfo,
276
            TOOL_ANNOUNCEMENT,
277
            $id,
278
            'delete',
279
            api_get_user_id()
280
        );*/
281
    }
282
283
    /**
284
     * Deletes all announcements by course.
285
     *
286
     * @param array $courseInfo the course array
287
     */
288
    public static function delete_all_announcements($courseInfo)
289
    {
290
        $repo = Container::getAnnouncementRepository();
291
        $announcements = self::get_all_annoucement_by_course(
292
            $courseInfo,
293
            api_get_session_id()
294
        );
295
296
        if (!empty($announcements)) {
297
            foreach ($announcements as $announcement) {
298
                $repo->getEntityManager()->remove($announcement);
299
                /*api_item_property_update(
300
                    $courseInfo,
301
                    TOOL_ANNOUNCEMENT,
302
                    $annon['id'],
303
                    'delete',
304
                    api_get_user_id()
305
                );*/
306
            }
307
        }
308
        $repo->getEntityManager()->flush();
309
    }
310
311
    /**
312
     * @param string $title
313
     * @param int    $courseId
314
     * @param int    $sessionId
315
     * @param int    $visibility 1 or 0
316
     *
317
     * @return mixed
318
     */
319
    public static function getAnnouncementsByTitle(
320
        $title,
321
        $courseId,
322
        $sessionId = 0,
323
        $visibility = 1
324
    ) {
325
        $dql = "SELECT a
326
                FROM ChamiloCourseBundle:CAnnouncement a
327
                JOIN ChamiloCourseBundle:CItemProperty ip
328
                WITH a.id = ip.ref AND a.cId = ip.course
329
                WHERE
330
                    ip.tool = 'announcement' AND
331
                    a.cId = :course AND
332
                    a.sessionId = :session AND
333
                    a.title like :title AND
334
                    ip.visibility = :visibility
335
                ORDER BY a.displayOrder DESC";
336
337
        $qb = Database::getManager()->createQuery($dql);
338
        $result = $qb->execute(
339
            [
340
                'course' => $courseId,
341
                'session' => $sessionId,
342
                'visibility' => $visibility,
343
                'title' => "%$title%",
344
            ]
345
        );
346
347
        return $result;
348
    }
349
350
    /**
351
     * @param int $announcementId
352
     * @param int $courseId
353
     * @param int $userId
354
     * @param int $groupId
355
     *
356
     * @return CAnnouncement
357
     */
358
    public static function getAnnouncementInfoById(
359
        $announcementId,
360
        $courseId,
361
        $userId,
362
        $groupId = 0
363
    ) {
364
        $announcementId = (int) $announcementId;
365
366
        $repo = Container::getAnnouncementRepository();
367
368
        return $repo->find($announcementId);
369
370
        $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...
371
        $userId = (int) $userId;
372
        $groupId = (int) $groupId;
373
374
        if (api_is_allowed_to_edit(false, true) ||
375
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
376
        ) {
377
            $dql = "SELECT a, ip
378
                    FROM ChamiloCourseBundle:CAnnouncement a
379
                    JOIN ChamiloCourseBundle:CItemProperty ip
380
                    WITH a.id = ip.ref AND a.cId = ip.course
381
                    WHERE
382
                        a.id = :announcement AND
383
                        ip.tool = 'announcement' AND
384
                        a.cId = :course
385
                    ORDER BY a.displayOrder DESC";
386
        } else {
387
            $groupList[] = $groupId;
388
389
            if (0 != api_get_user_id()) {
390
                $extraGroupCondition = '';
391
                if (!empty($groupId)) {
392
                    $groupProperties = GroupManager::get_group_properties($groupId);
393
                    if (GroupManager::TOOL_PRIVATE_BETWEEN_USERS == $groupProperties['announcements_state']) {
394
                        $extraGroupCondition = " AND (
395
                            ip.toUser = $userId AND ip.group = $groupId OR
396
                            (ip.group IN ('0') OR ip.group IS NULL) OR
397
                            (ip.group = $groupId AND (ip.toUser IS NULL OR ip.toUser = 0))
398
                        )";
399
                    }
400
                }
401
402
                $dql = "SELECT a, ip
403
                        FROM ChamiloCourseBundle:CAnnouncement a
404
                        JOIN ChamiloCourseBundle:CItemProperty ip
405
                        WITH a.id = ip.ref AND a.cId = ip.course
406
                        WHERE
407
                            a.id = :announcement AND
408
                            ip.tool='announcement' AND
409
                            (
410
                                ip.toUser = $userId OR
411
                                ip.group IN ('0', '".$groupId."') OR
412
                                ip.group IS NULL
413
                            ) AND
414
                            ip.visibility = '1' AND
415
                            ip.course = :course
416
                            $extraGroupCondition
417
                        ORDER BY a.displayOrder DESC";
418
            } else {
419
                $dql = "SELECT a, ip
420
                        FROM ChamiloCourseBundle:CAnnouncement a
421
                        JOIN ChamiloCourseBundle:CItemProperty ip
422
                        WITH a.id = ip.ref AND a.cId = ip.course
423
                        WHERE
424
                            a.id = :announcement AND
425
                            ip.tool = 'announcement' AND
426
                            (ip.group = '0' OR ip.group IS NULL) AND
427
                            ip.visibility = '1' AND
428
                            ip.course = :course";
429
            }
430
        }
431
432
        $qb = Database::getManager()->createQuery($dql);
433
        $result = $qb->execute(
434
            [
435
                'announcement' => $announcementId,
436
                'course' => $courseId,
437
            ]
438
        );
439
440
        if (!empty($result)) {
441
            return [
442
                'announcement' => $result[0],
443
                'item_property' => $result[1],
444
            ];
445
        }
446
447
        return [];
448
    }
449
450
    /**
451
     * Displays one specific announcement.
452
     *
453
     * @param int $id, the id of the announcement you want to display
454
     *
455
     * @return string
456
     */
457
    public static function displayAnnouncement($id)
458
    {
459
        $id = (int) $id;
460
461
        if (empty($id)) {
462
            return '';
463
        }
464
465
        $stok = null;
466
        $html = '';
467
        $course = api_get_course_entity(api_get_course_int_id());
468
        $session = api_get_session_entity(api_get_session_id());
469
470
        $announcement = self::getAnnouncementInfoById(
471
            $id,
472
            api_get_course_int_id(),
473
            api_get_user_id(),
474
            api_get_group_id()
475
        );
476
477
        if (empty($announcement)) {
478
            return '';
479
        }
480
481
        $title = $announcement->getTitle();
482
        $content = $announcement->getContent();
483
484
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
485
        $html .= "<tr><td><h2>".$title."</h2></td></tr>";
486
487
        $isVisible = $announcement->isVisible($course, $session);
488
489
        if (api_is_allowed_to_edit(false, true) ||
490
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
491
        ) {
492
            $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
493
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
494
495
            $image_visibility = 'invisible';
496
            $alt_visibility = get_lang('Visible');
497
            $setNewStatus = 'visible';
498
            if ($isVisible) {
499
                $image_visibility = 'visible';
500
                $alt_visibility = get_lang('Hide');
501
                $setNewStatus = 'invisible';
502
            }
503
            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=set_visibility&status=".$setNewStatus."&id=".$id."&sec_token=".$stok."\">".
504
                Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
505
506
            if (api_is_allowed_to_edit(false, true)) {
507
                $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;\">".
508
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
509
                    "</a>";
510
            }
511
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
512
        } else {
513
            if (false === $isVisible) {
514
                api_not_allowed(true);
515
            }
516
        }
517
518
        // The user id is always the current one.
519
        $toUserId = api_get_user_id();
520
        $content = self::parseContent(
521
            $toUserId,
522
            $content,
523
            api_get_course_id(),
524
            api_get_session_id()
525
        );
526
527
        $html .= "<tr><td>$content</td></tr>";
528
        $html .= "<tr>";
529
        $html .= "<td class=\"announcements_datum\">".get_lang('Latest update')." : ";
530
        $lastEdit = $announcement->getResourceNode()->getUpdatedAt();
531
        $html .= Display::dateToStringAgoAndLongDate($lastEdit);
532
        $html .= "</td></tr>";
533
534
        $allow = !api_get_configuration_value('hide_announcement_sent_to_users_info');
535
        if ($allow && api_is_allowed_to_edit(false, true)) {
536
            $sent_to = self::sent_to('announcement', $id);
537
            $sentToForm = self::sent_to_form($sent_to);
538
            $html .= Display::tag(
539
                'td',
540
                get_lang('Visible to').': '.$sentToForm,
541
                ['class' => 'announcements_datum']
542
            );
543
        }
544
545
        $attachments = $announcement->getAttachments();
546
        if (count($attachments) > 0) {
547
            $repo = Container::getAnnouncementAttachmentRepository();
548
            foreach ($attachments as $attachment) {
549
                $attachmentId = $attachment->getIid();
550
                $url = $repo->getResourceFileDownloadUrl($attachment);
551
                $html .= "<tr><td>";
552
                $html .= '<br/>';
553
                $html .= Display::returnFontAwesomeIcon('paperclip');
554
                $html .= '<a href="'.$url.' "> '.$attachment->getFilename().' </a>';
555
                $html .= ' - <span class="forum_attach_comment" >'.$attachment->getComment().'</span>';
556
                if (api_is_allowed_to_edit(false, true)) {
557
                    $url = api_get_self()."?".api_get_cidreq().
558
                        "&action=delete_attachment&id_attach=".$attachmentId."&sec_token=".$stok;
559
                    $html .= Display::url(
560
                        Display::return_icon(
561
                            'delete.png',
562
                            get_lang('Delete'),
563
                            '',
564
                            16
565
                        ),
566
                        $url
567
                    );
568
                }
569
                $html .= '</td></tr>';
570
            }
571
        }
572
        $html .= '</table>';
573
574
        return $html;
575
    }
576
577
    /**
578
     * @param array $courseInfo
579
     *
580
     * @return int
581
     */
582
    public static function getLastAnnouncementOrder($courseInfo)
583
    {
584
        if (empty($courseInfo)) {
585
            return 0;
586
        }
587
588
        if (!isset($courseInfo['real_id'])) {
589
            return false;
590
        }
591
592
        return false;
593
594
        $courseId = $courseInfo['real_id'];
0 ignored issues
show
Unused Code introduced by
$courseId = $courseInfo['real_id'] 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...
595
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
596
        $sql = "SELECT MAX(display_order)
597
                FROM $table
598
                WHERE c_id = $courseId ";
599
        $result = Database::query($sql);
600
601
        $order = 0;
602
        if (Database::num_rows($result)) {
603
            $row = Database::fetch_array($result);
604
            $order = (int) $row[0] + 1;
605
        }
606
607
        return $order;
608
    }
609
610
    /**
611
     * Store an announcement in the database (including its attached file if any).
612
     *
613
     * @param array  $courseInfo
614
     * @param int    $sessionId
615
     * @param string $title                Announcement title (pure text)
616
     * @param string $newContent           Content of the announcement (can be HTML)
617
     * @param array  $sentTo               Array of users and groups to send the announcement to
618
     * @param array  $file                 uploaded file $_FILES
619
     * @param string $file_comment         Comment describing the attachment
620
     * @param string $end_date
621
     * @param bool   $sendToUsersInSession
622
     * @param int    $authorId
623
     *
624
     * @return int false on failure, ID of the announcement on success
625
     */
626
    public static function add_announcement(
627
        $courseInfo,
628
        $sessionId,
629
        $title,
630
        $newContent,
631
        $sentTo,
632
        $file = [],
633
        $file_comment = null,
634
        $end_date = null,
635
        $sendToUsersInSession = false,
636
        $authorId = 0
637
    ) {
638
        if (empty($courseInfo)) {
639
            return false;
640
        }
641
642
        if (!isset($courseInfo['real_id'])) {
643
            return false;
644
        }
645
646
        $courseId = $courseInfo['real_id'];
647
        if (empty($end_date)) {
648
            $end_date = api_get_utc_datetime();
649
        }
650
651
        $order = self::getLastAnnouncementOrder($courseInfo);
652
653
        $course = api_get_course_entity($courseId);
654
        $session = api_get_session_entity($sessionId);
655
        $group = api_get_group_entity();
656
657
        $em = Database::getManager();
658
659
        $announcement = new CAnnouncement();
660
        $announcement
661
            ->setContent($newContent)
662
            ->setTitle($title)
663
            ->setEndDate(new DateTime($end_date))
664
            ->setDisplayOrder($order)
665
            ->setParent($course)
666
            ->addCourseLink(
667
                $course,
668
                $session,
669
                $group
670
            )
671
        ;
672
673
        $em->persist($announcement);
674
        $em->flush();
675
        $last_id = $announcement->getIid();
676
677
        if (empty($last_id)) {
678
            return false;
679
        }
680
681
        if (!empty($file)) {
682
            self::add_announcement_attachment_file(
683
                $announcement,
684
                $file_comment,
685
                $_FILES['user_upload']
686
            );
687
        }
688
689
        $resourceNode = $announcement->getResourceNode();
690
691
        // store in item_property (first the groups, then the users
692
        if (empty($sentTo) ||
693
            (!empty($sentTo) && isset($sentTo[0]) && 'everyone' === $sentTo[0])
694
        ) {
695
            // The message is sent to EVERYONE, so we set the group to 0
696
            /*api_item_property_update(
697
                $courseInfo,
698
                TOOL_ANNOUNCEMENT,
699
                $last_id,
700
                'AnnouncementAdded',
701
                $authorId,
702
                '0',
703
                null,
704
                null,
705
                null,
706
                $sessionId
707
            );*/
708
        } else {
709
            $send_to = CourseManager::separateUsersGroups($sentTo);
710
            // Storing the selected groups
711
            if (is_array($send_to['groups']) &&
712
                !empty($send_to['groups'])
713
            ) {
714
                foreach ($send_to['groups'] as $group) {
715
                    $group = api_get_group_entity($group);
716
                    if ($group) {
717
                        $announcement->addGroupLink($course, $session, $group);
718
                    }
719
720
                    /*api_item_property_update(
721
                        $courseInfo,
722
                        TOOL_ANNOUNCEMENT,
723
                        $last_id,
724
                        'AnnouncementAdded',
725
                        $authorId,
726
                        $groupInfo
727
                    );*/
728
                }
729
            }
730
731
            // Storing the selected users
732
            if (is_array($send_to['users'])) {
733
                foreach ($send_to['users'] as $user) {
734
                    $user = api_get_user_entity($user);
735
                    $announcement->addUserLink($user, $course, $session, $group);
736
                    /*api_item_property_update(
737
                        $courseInfo,
738
                        TOOL_ANNOUNCEMENT,
739
                        $last_id,
740
                        'AnnouncementAdded',
741
                        $authorId,
742
                        '',
743
                        $user
744
                    );*/
745
                }
746
            }
747
        }
748
749
        if ($sendToUsersInSession) {
750
            self::addAnnouncementToAllUsersInSessions($announcement);
751
        }
752
753
        $em->persist($resourceNode);
754
        $em->persist($announcement);
755
        $em->flush();
756
757
        return $announcement;
758
    }
759
760
    /**
761
     * @param string $title
762
     * @param string $newContent
763
     * @param int    $groupId
764
     * @param array  $to_users
765
     * @param array  $file
766
     * @param string $file_comment
767
     * @param bool   $sendToUsersInSession
768
     *
769
     * @return bool|int
770
     */
771
    public static function addGroupAnnouncement(
772
        $title,
773
        $newContent,
774
        $groupId,
775
        $to_users,
776
        $file = [],
777
        $file_comment = '',
778
        $sendToUsersInSession = false
779
    ) {
780
        $courseInfo = api_get_course_info();
781
782
        $order = self::getLastAnnouncementOrder($courseInfo);
783
784
        $now = api_get_utc_datetime();
785
        $courseId = api_get_course_int_id();
786
        $sessionId = api_get_session_id();
787
        $course = api_get_course_entity($courseId);
788
        $announcement = new CAnnouncement();
789
        $announcement
790
            ->setContent($newContent)
791
            ->setTitle($title)
792
            ->setEndDate(new DateTime($now))
793
            ->setDisplayOrder($order)
794
            ->setParent($course)
795
            ->addCourseLink(
796
                $course,
797
                api_get_session_entity($sessionId),
798
                api_get_group_entity()
799
            );
800
801
        $repo = Container::getAnnouncementRepository();
802
        $repo->getEntityManager()->flush();
803
        $last_id = $announcement->getIid();
804
805
        // Store the attach file
806
        if ($last_id) {
807
            if (!empty($file)) {
808
                self::add_announcement_attachment_file(
809
                    $announcement,
810
                    $file_comment,
811
                    $file
812
                );
813
            }
814
815
            $send_to_users = CourseManager::separateUsersGroups($to_users);
816
817
            // if nothing was selected in the menu then send to all the group
818
            $sentToAllGroup = false;
819
            if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
820
                $groupInfo = GroupManager::get_group_properties($groupId);
821
                /*api_item_property_update(
822
                    $courseInfo,
823
                    TOOL_ANNOUNCEMENT,
824
                    $last_id,
825
                    'AnnouncementAdded',
826
                    api_get_user_id(),
827
                    $groupInfo
828
                );*/
829
                $sentToAllGroup = true;
830
            }
831
832
            if (false === $sentToAllGroup) {
833
                if (!empty($send_to_users['groups'])) {
834
                    foreach ($send_to_users['groups'] as $group) {
835
                        $groupInfo = GroupManager::get_group_properties($group);
836
                        /*api_item_property_update(
837
                            $courseInfo,
838
                            TOOL_ANNOUNCEMENT,
839
                            $last_id,
840
                            'AnnouncementAdded',
841
                            api_get_user_id(),
842
                            $groupInfo
843
                        );*/
844
                    }
845
                }
846
847
                $groupInfo = GroupManager::get_group_properties($groupId);
848
                if (!empty($send_to_users['users'])) {
849
                    foreach ($send_to_users['users'] as $user) {
850
                        /*api_item_property_update(
851
                            $courseInfo,
852
                            TOOL_ANNOUNCEMENT,
853
                            $last_id,
854
                            'AnnouncementAdded',
855
                            api_get_user_id(),
856
                            $groupInfo,
857
                            $user
858
                        );*/
859
                    }
860
                }
861
            }
862
863
            if ($sendToUsersInSession) {
864
                self::addAnnouncementToAllUsersInSessions($announcement);
865
            }
866
        }
867
868
        return $last_id;
869
    }
870
871
    /**
872
     * This function stores the announcement item in the announcement table
873
     * and updates the item_property table.
874
     *
875
     * @param int    $id                   id of the announcement
876
     * @param string $title
877
     * @param string $newContent
878
     * @param array  $to                   users that will receive the announcement
879
     * @param mixed  $file                 attachment
880
     * @param string $file_comment         file comment
881
     * @param bool   $sendToUsersInSession
882
     */
883
    public static function edit_announcement(
884
        $id,
885
        $title,
886
        $newContent,
887
        $to,
888
        $file = [],
889
        $file_comment = '',
890
        $sendToUsersInSession = false
891
    ) {
892
        $id = (int) $id;
893
894
        $repo = Container::getAnnouncementRepository();
895
        /** @var CAnnouncement $announcement */
896
        $announcement = $repo->find($id);
897
898
        if (null === $announcement) {
899
            return false;
900
        }
901
902
        $course = api_get_course_entity();
903
        $group = api_get_group_entity();
904
        $session = api_get_session_entity();
905
906
        $announcement
907
            ->setTitle($title)
908
            ->setContent($newContent)
909
        ;
910
        $repo->getEntityManager()->persist($announcement);
911
        $repo->getEntityManager()->flush();
912
913
        // save attachment file
914
        $row_attach = self::get_attachment($id);
915
916
        $id_attach = 0;
917
        if ($row_attach) {
918
            $id_attach = (int) $row_attach['id'];
919
        }
920
921
        if (!empty($file)) {
922
            if (empty($id_attach)) {
923
                self::add_announcement_attachment_file(
924
                    $announcement,
925
                    $file_comment,
926
                    $file
927
                );
928
            } else {
929
                self::edit_announcement_attachment_file(
930
                    $id_attach,
931
                    $file,
932
                    $file_comment
933
                );
934
            }
935
        }
936
937
        // We remove everything from item_property for this
938
        /*$sql = "DELETE FROM $tbl_item_property
939
                WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
940
        Database::query($sql);*/
941
942
        if ($sendToUsersInSession) {
943
            self::addAnnouncementToAllUsersInSessions($announcement);
944
        }
945
946
        // store in item_property (first the groups, then the users
947
        if (!empty($to)) {
948
            // !is_null($to): when no user is selected we send it to everyone
949
            $send_to = CourseManager::separateUsersGroups($to);
950
            $resourceNode = $announcement->getResourceNode();
951
952
            // storing the selected groups
953
            if (is_array($send_to['groups'])) {
954
                foreach ($send_to['groups'] as $group) {
955
                    $groupInfo = api_get_group_entity($group);
956
                    $announcement->addGroupLink($course, $session, $groupInfo);
957
                    /*
958
                    if ($groupInfo) {
959
                        api_item_property_update(
960
                            $courseInfo,
961
                            TOOL_ANNOUNCEMENT,
962
                            $id,
963
                            'AnnouncementUpdated',
964
                            api_get_user_id(),
965
                            $groupInfo
966
                        );
967
                    }*/
968
                }
969
            }
970
971
            // storing the selected users
972
            if (is_array($send_to['users'])) {
973
                foreach ($send_to['users'] as $user) {
974
                    $user = api_get_user_entity($user);
975
                    $announcement->addUserLink($user, $course, $session, $group);
976
                    /*api_item_property_update(
977
                        $courseInfo,
978
                        TOOL_ANNOUNCEMENT,
979
                        $id,
980
                        'AnnouncementUpdated',
981
                        api_get_user_id(),
982
                        0,
983
                        $user
984
                    );*/
985
                }
986
            }
987
988
            // Send to everyone
989
            if (isset($to[0]) && 'everyone' === $to[0]) {
990
                /*api_item_property_update(
991
                    $courseInfo,
992
                    TOOL_ANNOUNCEMENT,
993
                    $id,
994
                    'AnnouncementUpdated',
995
                    api_get_user_id(),
996
                    0
997
                );*/
998
            }
999
        } else {
1000
            // the message is sent to everyone, so we set the group 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
1011
        $repo->getEntityManager()->persist($announcement);
1012
        $repo->getEntityManager()->flush();
1013
1014
        return $announcement;
1015
    }
1016
1017
    /**
1018
     * @param CAnnouncement $announcement
1019
     */
1020
    public static function addAnnouncementToAllUsersInSessions($announcement)
1021
    {
1022
        $courseCode = api_get_course_id();
1023
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
1024
1025
        $courseEntity = api_get_course_entity();
1026
        $sessionEntity = api_get_session_entity();
1027
        $groupEntity = api_get_group_entity();
1028
1029
        $repo = Container::getAnnouncementRepository();
1030
1031
        if (!empty($sessionList)) {
1032
            foreach ($sessionList as $sessionInfo) {
1033
                $sessionId = $sessionInfo['id'];
1034
                $userList = CourseManager::get_user_list_from_course_code(
1035
                    $courseCode,
1036
                    $sessionId
1037
                );
1038
1039
                if (!empty($userList)) {
1040
                    foreach ($userList as $user) {
1041
                        $user = api_get_user_entity($user);
1042
                        $announcement->addUserLink($user, $courseEntity, $sessionEntity, $groupEntity);
1043
                        /*api_item_property_update(
1044
                            $courseInfo,
1045
                            TOOL_ANNOUNCEMENT,
1046
                            $announcementId,
1047
                            'AnnouncementUpdated',
1048
                            api_get_user_id(),
1049
                            0,
1050
                            $user['user_id'],
1051
                            0,
1052
                            0,
1053
                            $sessionId
1054
                        );*/
1055
                    }
1056
                }
1057
            }
1058
        }
1059
1060
        $repo->getEntityManager()->persist($announcement);
1061
        $repo->getEntityManager()->flush();
1062
    }
1063
1064
    /**
1065
     * @param int $insert_id
1066
     *
1067
     * @return bool
1068
     */
1069
    public static function update_mail_sent($insert_id)
1070
    {
1071
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1072
        $insert_id = intval($insert_id);
1073
        // store the modifications in the table tbl_annoucement
1074
        $sql = "UPDATE $table SET email_sent='1'
1075
                WHERE iid = $insert_id";
1076
        Database::query($sql);
1077
    }
1078
1079
    /**
1080
     * @param int $user_id
1081
     *
1082
     * @return CAnnouncement[]
1083
     */
1084
    public static function getAnnouncementCourseTotalByUser($user_id)
1085
    {
1086
        $user_id = (int) $user_id;
1087
1088
        if (empty($user_id)) {
1089
            return false;
1090
        }
1091
1092
        $user = api_get_user_entity($user_id);
1093
        $repo = Container::getAnnouncementRepository();
1094
1095
        $qb = $repo->getResourcesByLinkedUser($user);
1096
1097
        return $qb->getQuery()->getResult();
1098
1099
        /*
1100
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1101
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1102
1103
        $sql = "SELECT DISTINCT
1104
                    announcement.c_id,
1105
                    count(announcement.id) count
1106
                FROM $tbl_announcement announcement
1107
                INNER JOIN $tbl_item_property ip
1108
                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1109
                WHERE
1110
                    ip.tool='announcement' AND
1111
                    (
1112
                      ip.to_user_id = '$user_id' AND
1113
                      (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1114
                    )
1115
                    AND ip.visibility='1'
1116
                    AND announcement.session_id  = 0
1117
                GROUP BY announcement.c_id";
1118
        $rs = Database::query($sql);
1119
        $num_rows = Database::num_rows($rs);
1120
        $result = [];
1121
        if ($num_rows > 0) {
1122
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1123
                if (empty($row['c_id'])) {
1124
                    continue;
1125
                }
1126
                $result[] = ['course' => api_get_course_info_by_id($row['c_id']), 'count' => $row['count']];
1127
            }
1128
        }
1129
1130
        return $result;*/
1131
    }
1132
1133
    public static function getSenders(CAnnouncement $announcement)
1134
    {
1135
        $result = [];
1136
        $result['groups'] = [];
1137
        $result['users'] = [];
1138
1139
        $links = $announcement->getResourceNode()->getResourceLinks();
1140
1141
        if (empty($links)) {
1142
            return $result;
1143
        }
1144
1145
        /** @var ResourceLink $link */
1146
        foreach ($links as $link) {
1147
            if ($link->getUser()) {
1148
                $result['users'][] = $link->getUser()->getId();
1149
            }
1150
            if ($link->getGroup()) {
1151
                $result['groups'][] = $link->getGroup()->getIid();
1152
            }
1153
        }
1154
1155
        return $result;
1156
    }
1157
1158
    /**
1159
     * This tools loads all the users and all the groups who have received
1160
     * a specific item (in this case an announcement item).
1161
     *
1162
     * @param CAnnouncement $announcement
1163
     * @param bool          $includeGroupWhenLoadingUser
1164
     *
1165
     * @return array
1166
     */
1167
    public static function loadEditUsers($announcement, $includeGroupWhenLoadingUser = false)
1168
    {
1169
        $result = self::getSenders($announcement);
1170
        $to = [];
1171
1172
        foreach ($result['users'] as $itemId) {
1173
            $to[] = 'USER:'.$itemId;
1174
        }
1175
1176
        foreach ($result['groups'] as $itemId) {
1177
            $to[] = 'GROUP:'.$itemId;
1178
        }
1179
1180
        return $to;
1181
    }
1182
1183
    /**
1184
     * constructs the form to display all the groups and users the message has been sent to.
1185
     *
1186
     * @param array $sent_to_array
1187
     *                             input:
1188
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1189
     *                             the first level is a distinction between groups and users:
1190
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1191
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1192
     *                             containing all the id's of the groups (resp. users) who have received this message.
1193
     *
1194
     * @return string
1195
     *
1196
     * @author Patrick Cool <patrick.cool@>
1197
     */
1198
    public static function sent_to_form($sent_to_array)
1199
    {
1200
        // we find all the names of the groups
1201
        $groupList = CourseManager::getCourseGroups();
1202
1203
        // we count the number of users and the number of groups
1204
        $number_users = 0;
1205
        if (isset($sent_to_array['users'])) {
1206
            $number_users = count($sent_to_array['users']);
1207
        }
1208
        $number_groups = 0;
1209
        if (isset($sent_to_array['groups'])) {
1210
            $number_groups = count($sent_to_array['groups']);
1211
        }
1212
1213
        $total_numbers = $number_users + $number_groups;
1214
1215
        // starting the form if there is more than one user/group
1216
        $output = [];
1217
        if ($total_numbers > 1) {
1218
            // outputting the name of the groups
1219
            if (is_array($sent_to_array['groups'])) {
1220
                foreach ($sent_to_array['groups'] as $group_id) {
1221
                    $users = GroupManager::getStudents($group_id, true);
1222
                    $userToArray = [];
1223
                    foreach ($users as $student) {
1224
                        $userToArray[] = $student['complete_name_with_username'];
1225
                    }
1226
                    $output[] =
1227
                        '<br />'.
1228
                        Display::label($groupList[$group_id]->getName(), 'info').
1229
                        '&nbsp;'.implode(', ', $userToArray);
1230
                }
1231
            }
1232
1233
            if (isset($sent_to_array['users'])) {
1234
                if (is_array($sent_to_array['users'])) {
1235
                    $usersToArray = [];
1236
                    foreach ($sent_to_array['users'] as $user_id) {
1237
                        $user_info = api_get_user_info($user_id);
1238
                        $usersToArray[] = $user_info['complete_name_with_username'];
1239
                    }
1240
                    $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
1241
                }
1242
            }
1243
        } else {
1244
            // there is only one user/group
1245
            if (isset($sent_to_array['users']) && is_array($sent_to_array['users'])) {
1246
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1247
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1248
            }
1249
            if (isset($sent_to_array['groups']) &&
1250
                is_array($sent_to_array['groups']) &&
1251
                isset($sent_to_array['groups'][0]) &&
1252
                0 !== $sent_to_array['groups'][0]
1253
            ) {
1254
                $group_id = $sent_to_array['groups'][0];
1255
1256
                $users = GroupManager::getStudents($group_id, true);
1257
                $userToArray = [];
1258
                foreach ($users as $student) {
1259
                    $userToArray[] = $student['complete_name_with_username'];
1260
                }
1261
                $output[] =
1262
                    '<br />'.
1263
                    Display::label($groupList[$group_id]->getName(), 'info').
1264
                    '&nbsp;'.implode(', ', $userToArray);
1265
            }
1266
            if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
1267
                $output[] = "&nbsp;".get_lang('All');
1268
            }
1269
        }
1270
1271
        if (!empty($output)) {
1272
            $output = array_filter($output);
1273
            if (count($output) > 0) {
1274
                $output = implode('<br />', $output);
1275
            }
1276
1277
            return $output;
1278
        }
1279
    }
1280
1281
    /**
1282
     * Returns all the users and all the groups a specific announcement item
1283
     * has been sent to.
1284
     *
1285
     * @param    string  The tool (announcement, agenda, ...)
1286
     * @param    int     ID of the element of the corresponding type
1287
     *
1288
     * @return array Array of users and groups to whom the element has been sent
1289
     */
1290
    public static function sent_to($tool, $id)
1291
    {
1292
        return [];
1293
1294
        $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...
1295
        $tool = Database::escape_string($tool);
1296
        $id = (int) $id;
1297
1298
        $sent_to_group = [];
1299
        $sent_to = [];
1300
        $courseId = api_get_course_int_id();
1301
1302
        $sql = "SELECT to_group_id, to_user_id
1303
                FROM $table
1304
                WHERE c_id = $courseId AND tool = '$tool' AND ref=".$id;
1305
        $result = Database::query($sql);
1306
1307
        while ($row = Database::fetch_array($result)) {
1308
            // if to_user_id <> 0 then it is sent to a specific user
1309
            if (0 != $row['to_user_id']) {
1310
                $sent_to_user[] = $row['to_user_id'];
1311
                continue;
1312
            }
1313
1314
            // if to_group_id is null then it is sent to a specific user
1315
            // if to_group_id = 0 then it is sent to everybody
1316
            if (0 != $row['to_group_id']) {
1317
                $sent_to_group[] = $row['to_group_id'];
1318
            }
1319
        }
1320
1321
        if (isset($sent_to_group)) {
1322
            $sent_to['groups'] = $sent_to_group;
1323
        }
1324
1325
        if (isset($sent_to_user)) {
1326
            $sent_to['users'] = $sent_to_user;
1327
        }
1328
1329
        return $sent_to;
1330
    }
1331
1332
    /**
1333
     * Show a list with all the attachments according to the post's id.
1334
     *
1335
     * @param int $announcementId
1336
     *
1337
     * @return array with the post info
1338
     *
1339
     * @author Arthur Portugal
1340
     *
1341
     * @version November 2009, dokeos 1.8.6.2
1342
     */
1343
    public static function get_attachment($announcementId)
1344
    {
1345
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1346
        $announcementId = (int) $announcementId;
1347
        $row = [];
1348
        $sql = 'SELECT iid, path, filename, comment
1349
                FROM '.$table.'
1350
				WHERE announcement_id = '.$announcementId;
1351
        $result = Database::query($sql);
1352
        $repo = Container::getAnnouncementAttachmentRepository();
1353
        if (0 != Database::num_rows($result)) {
1354
            $row = Database::fetch_array($result, 'ASSOC');
1355
        }
1356
1357
        return $row;
1358
    }
1359
1360
    /**
1361
     * This function add a attachment file into announcement.
1362
     *
1363
     * @param string file comment
1364
     * @param array  uploaded file $_FILES
1365
     *
1366
     * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
1367
     */
1368
    public static function add_announcement_attachment_file(
1369
        CAnnouncement $announcement,
1370
        $file_comment,
1371
        $file
1372
    ) {
1373
        $return = 0;
1374
        $courseId = api_get_course_int_id();
1375
1376
        if (is_array($file) && 0 == $file['error']) {
1377
            // Try to add an extension to the file if it hasn't one
1378
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1379
            // user's file name
1380
            $file_name = $file['name'];
1381
1382
            if (!filter_extension($new_file_name)) {
1383
                $return = -1;
1384
                Display::addFlash(
1385
                    Display::return_message(
1386
                        get_lang('File upload failed: this file extension or file type is prohibited'),
1387
                        'error'
1388
                    )
1389
                );
1390
            } else {
1391
                $repo = Container::getAnnouncementAttachmentRepository();
1392
                $new_file_name = uniqid('');
1393
                $attachment = new CAnnouncementAttachment();
1394
                $attachment
1395
                    ->setFilename($file_name)
1396
                    ->setPath($new_file_name)
1397
                    ->setComment($file_comment)
1398
                    ->setAnnouncement($announcement)
1399
                    ->setSize((int) $file['size'])
1400
                    ->setParent($announcement)
1401
                    ->addCourseLink(
1402
                        api_get_course_entity($courseId),
1403
                        api_get_session_entity(api_get_session_id()),
1404
                        api_get_group_entity()
1405
                    )
1406
                ;
1407
                $repo->getEntityManager()->persist($attachment);
1408
                $repo->getEntityManager()->flush();
1409
1410
                $request = Container::getRequest();
1411
                $file = $request->files->get('user_upload');
1412
1413
                if (!empty($file)) {
1414
                    $repo->addFile($attachment, $file);
1415
                    $repo->getEntityManager()->persist($attachment);
1416
                    $repo->getEntityManager()->flush();
1417
1418
                    return 1;
1419
                }
1420
1421
                $return = 1;
1422
            }
1423
        }
1424
1425
        return $return;
1426
    }
1427
1428
    /**
1429
     * This function edit a attachment file into announcement.
1430
     *
1431
     * @param int attach id
1432
     * @param array uploaded file $_FILES
1433
     * @param string file comment
1434
     *
1435
     * @return int
1436
     */
1437
    public static function edit_announcement_attachment_file(
1438
        $id_attach,
1439
        $file,
1440
        $file_comment
1441
    ) {
1442
        // @todo fix edition
1443
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1444
        /*
1445
        $courseInfo = api_get_course_info();
1446
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1447
        $return = 0;
1448
        $courseId = api_get_course_int_id();
1449
1450
        if (is_array($file) && 0 == $file['error']) {
1451
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1452
            $courseDir = $courseInfo['path'].'/upload/announcements';
1453
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1454
            $updir = $sys_course_path.$courseDir;
1455
1456
            // Try to add an extension to the file if it hasn't one
1457
            $new_file_name = add_ext_on_mime(
1458
                stripslashes($file['name']),
1459
                $file['type']
1460
            );
1461
            // user's file name
1462
            $file_name = $file['name'];
1463
1464
            if (!filter_extension($new_file_name)) {
1465
                $return = -1;
1466
                echo Display::return_message(
1467
                    get_lang('File upload failed: this file extension or file type is prohibited'),
1468
                    'error'
1469
                );
1470
            } else {
1471
                $new_file_name = uniqid('');
1472
                $new_path = $updir.'/'.$new_file_name;
1473
                copy($file['tmp_name'], $new_path);
1474
                $safe_file_comment = Database::escape_string($file_comment);
1475
                $safe_file_name = Database::escape_string($file_name);
1476
                $safe_new_file_name = Database::escape_string($new_file_name);
1477
                $id_attach = intval($id_attach);
1478
                $sql = "UPDATE $table SET
1479
                            filename = '$safe_file_name',
1480
                            comment = '$safe_file_comment',
1481
                            path = '$safe_new_file_name',
1482
                            size ='".intval($file['size'])."'
1483
                         WHERE iid = '$id_attach'";
1484
                $result = Database::query($sql);
1485
                if (false === $result) {
1486
                    $return = -1;
1487
                    echo Display::return_message(
1488
                        get_lang('The uploaded file could not be saved (perhaps a permission problem?)'),
1489
                        'error'
1490
                    );
1491
                } else {
1492
                    $return = 1;
1493
                }
1494
            }
1495
        }
1496
1497
        return $return;*/
1498
    }
1499
1500
    /**
1501
     * This function delete a attachment file by id.
1502
     *
1503
     * @param int $id attachment file Id
1504
     *
1505
     * @return bool
1506
     */
1507
    public static function delete_announcement_attachment_file($id)
1508
    {
1509
        $id = (int) $id;
1510
        $repo = Container::getAnnouncementAttachmentRepository();
1511
        $attachment = $repo->find($id);
1512
        $repo->getEntityManager()->remove($attachment);
1513
        $repo->getEntityManager()->flush();
1514
1515
        return true;
1516
    }
1517
1518
    /**
1519
     * @param array         $courseInfo
1520
     * @param int           $sessionId
1521
     * @param CAnnouncement $announcement
1522
     * @param bool          $sendToUsersInSession
1523
     * @param bool          $sendToDrhUsers
1524
     * @param Monolog\Handler\HandlerInterface logger
1525
     * @param int  $senderId
1526
     * @param bool $directMessage
1527
     *
1528
     * @return array
1529
     */
1530
    public static function sendEmail(
1531
        $courseInfo,
1532
        $sessionId,
1533
        $announcement,
1534
        $sendToUsersInSession = false,
1535
        $sendToDrhUsers = false,
1536
        $logger = null,
1537
        $senderId = 0,
1538
        $directMessage = false
1539
    ) {
1540
        $email = new AnnouncementEmail($courseInfo, $sessionId, $announcement, $logger);
1541
1542
        return $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId, $directMessage);
1543
    }
1544
1545
    /**
1546
     * @param $stok
1547
     * @param $announcement_number
1548
     * @param bool   $getCount
1549
     * @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...
1550
     * @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...
1551
     * @param string $sidx
1552
     * @param string $sord
1553
     * @param string $titleToSearch
1554
     * @param int    $userIdToSearch
1555
     * @param int    $userId
1556
     * @param int    $courseId
1557
     * @param int    $sessionId
1558
     *
1559
     * @return array
1560
     */
1561
    public static function getAnnouncements(
1562
        $stok,
1563
        $announcement_number,
1564
        $getCount = false,
1565
        $start = null,
1566
        $limit = null,
1567
        $sidx = '',
1568
        $sord = '',
1569
        $titleToSearch = '',
1570
        $userIdToSearch = 0,
1571
        $userId = 0,
1572
        $courseId = 0,
1573
        $sessionId = 0
1574
    ) {
1575
        $group_id = api_get_group_id();
1576
        $session_id = $sessionId ?: api_get_session_id();
1577
        if (empty($courseId)) {
1578
            $courseInfo = api_get_course_info();
1579
            $courseId = $courseInfo['real_id'];
1580
        } else {
1581
            $courseId = (int) $courseId;
1582
            $courseInfo = api_get_course_info_by_id($courseId);
1583
        }
1584
1585
        if (empty($courseInfo)) {
1586
            return [];
1587
        }
1588
1589
        $repo = Container::getAnnouncementRepository();
1590
        $course = api_get_course_entity($courseId);
1591
        $session = api_get_session_entity($session_id);
1592
        $group = api_get_group_entity(api_get_group_id());
1593
1594
        $qb = $repo->getResourcesByCourse($course, $session, $group);
1595
        $announcements = $qb->getQuery()->getResult();
1596
1597
        /*$condition_session = api_get_session_condition(
1598
            $session_id,
1599
            true,
1600
            true,
1601
            'announcement.session_id'
1602
        );
1603
1604
        $group_memberships = GroupManager::get_group_ids(
1605
            $courseId,
1606
            api_get_user_id()
1607
        );
1608
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1609
1610
        $select = ' DISTINCT
1611
                        announcement.*,
1612
                        ip.visibility,
1613
                        ip.to_group_id,
1614
                        ip.insert_user_id,
1615
                        ip.insert_date,
1616
                        ip.lastedit_date';
1617
        $groupBy = ' GROUP BY announcement.iid';
1618
        if ($getCount) {
1619
            $groupBy = '';
1620
            $select = ' COUNT(DISTINCT announcement.iid) count';
1621
        }
1622
1623
        $searchCondition = '';
1624
        if (!empty($titleToSearch)) {
1625
            $titleToSearch = Database::escape_string($titleToSearch);
1626
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1627
        }
1628
1629
        if (!empty($userIdToSearch)) {
1630
            $userIdToSearch = (int) $userIdToSearch;
1631
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1632
        }
1633
1634
        $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
1635
        $extraGroupCondition = '';
1636
        if ($allowOnlyGroup) {
1637
            $extraGroupCondition = " AND ip.to_group_id = $group_id ";
1638
        }
1639
1640
        $allowDrhAccess = api_get_configuration_value('allow_drh_access_announcement');
1641
1642
        if ($allowDrhAccess && api_is_drh()) {
1643
            // DRH only can see visible
1644
            $searchCondition .= ' AND (ip.visibility = 1)';
1645
        }
1646
1647
        if (api_is_allowed_to_edit(false, true) ||
1648
            ($allowUserEditSetting && !api_is_anonymous()) ||
1649
            ($allowDrhAccess && api_is_drh())
1650
        ) {
1651
            // A.1. you are a course admin with a USER filter
1652
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1653
            //if (!empty($user_id)) {
1654
            if (0) {
1655
                if (is_array($group_memberships) &&
1656
                    count($group_memberships) > 0
1657
                ) {
1658
                    $sql = "SELECT $select
1659
                            FROM $tbl_announcement announcement
1660
                            INNER JOIN $tbl_item_property ip
1661
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1662
                            WHERE
1663
                                announcement.c_id = $courseId AND
1664
                                ip.c_id = $courseId AND
1665
                                ip.tool = 'announcement' AND
1666
                                (
1667
                                    ip.to_user_id = $user_id OR
1668
                                    ip.to_group_id IS NULL OR
1669
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1670
                                ) AND
1671
                                ip.visibility IN ('1', '0')
1672
                                $condition_session
1673
                                $searchCondition
1674
                            ORDER BY display_order DESC";
1675
                } else {
1676
                    $sql = "SELECT $select
1677
                            FROM $tbl_announcement announcement
1678
                            INNER JOIN $tbl_item_property ip
1679
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1680
                            WHERE
1681
                                announcement.c_id = $courseId AND
1682
                                ip.c_id = $courseId AND
1683
                                ip.tool ='announcement' AND
1684
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1685
                                ip.visibility IN ('1', '0')
1686
                            $condition_session
1687
                            $searchCondition
1688
                            ORDER BY display_order DESC";
1689
                }
1690
            } elseif ($group_id != 0) {
1691
                // A.2. you are a course admin with a GROUP filter
1692
                // => see only the messages of this specific group
1693
                $sql = "SELECT $select
1694
                        FROM $tbl_announcement announcement
1695
                        INNER JOIN $tbl_item_property ip
1696
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1697
                        WHERE
1698
                            ip.tool='announcement' AND
1699
                            announcement.c_id = $courseId AND
1700
                            ip.c_id = $courseId AND
1701
                            ip.visibility<>'2' AND
1702
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1703
                            $condition_session
1704
                            $searchCondition
1705
                            $extraGroupCondition
1706
                        $groupBy
1707
                        ORDER BY display_order DESC";
1708
            } else {
1709
                // A.3 you are a course admin without any group or user filter
1710
                // A.3.a you are a course admin without user or group filter but WITH studentview
1711
                // => see all the messages of all the users and groups without editing possibilities
1712
                if (isset($isStudentView) && $isStudentView == 'true') {
1713
                    $sql = "SELECT $select
1714
                            FROM $tbl_announcement announcement
1715
                            INNER JOIN $tbl_item_property ip
1716
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1717
                            WHERE
1718
                                ip.tool='announcement' AND
1719
                                announcement.c_id = $courseId AND
1720
                                ip.c_id = $courseId AND
1721
                                ip.visibility='1'
1722
                                $condition_session
1723
                                $searchCondition
1724
                            $groupBy
1725
                            ORDER BY display_order DESC";
1726
                } else {
1727
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1728
                    // => see all the messages of all the users and groups with editing possibilities
1729
                    $sql = "SELECT $select
1730
                            FROM $tbl_announcement announcement
1731
                            INNER JOIN $tbl_item_property ip
1732
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1733
                            WHERE
1734
                                ip.tool = 'announcement' AND
1735
                                announcement.c_id = $courseId AND
1736
                                ip.c_id = $courseId  AND
1737
                                (ip.visibility='0' OR ip.visibility='1')
1738
                                $condition_session
1739
                                $searchCondition
1740
                            $groupBy
1741
                            ORDER BY display_order DESC";
1742
                }
1743
            }
1744
        } else {
1745
            // STUDENT
1746
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1747
                if ($allowUserEditSetting && !api_is_anonymous()) {
1748
                    if ($group_id == 0) {
1749
                        // No group
1750
                        $cond_user_id = " AND (
1751
                            ip.lastedit_user_id = '".$user_id."' OR (
1752
                                (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
1753
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1754
                            )
1755
                        ) ";
1756
                    } else {
1757
                        $cond_user_id = " AND (
1758
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1759
                        )";
1760
                        $cond_user_id .= $extraGroupCondition;
1761
                    }
1762
                } else {
1763
                    if ($group_id == 0) {
1764
                        $cond_user_id = " AND (
1765
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1766
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1767
                        ) ";
1768
                    } else {
1769
                        $cond_user_id = " AND (
1770
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1771
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1772
                        )";
1773
                        $cond_user_id .= $extraGroupCondition;
1774
                    }
1775
                }
1776
1777
                $sql = "SELECT $select
1778
                        FROM $tbl_announcement announcement INNER JOIN
1779
                        $tbl_item_property ip
1780
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1781
                        WHERE
1782
                            announcement.c_id = $courseId AND
1783
                            ip.c_id = $courseId AND
1784
                            ip.tool='announcement'
1785
                            $cond_user_id
1786
                            $condition_session
1787
                            $searchCondition AND
1788
                            ip.visibility='1'
1789
                            $groupBy
1790
                        ORDER BY display_order DESC";
1791
            } else {
1792
                if ($user_id) {
1793
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1794
                        $cond_user_id = " AND (
1795
                                ip.lastedit_user_id = '".api_get_user_id()."' OR
1796
                                ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1797
                                (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1798
                            )
1799
                        ) ";
1800
                    } else {
1801
                        $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1802
                        (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1803
                    }
1804
1805
                    $sql = "SELECT $select
1806
                        FROM $tbl_announcement announcement
1807
                        INNER JOIN $tbl_item_property ip
1808
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1809
                        WHERE
1810
                            announcement.c_id = $courseId AND
1811
                            ip.c_id = $courseId AND
1812
                            ip.tool='announcement'
1813
                            $cond_user_id
1814
                            $condition_session
1815
                            $searchCondition
1816
                            AND ip.visibility='1'
1817
                            AND announcement.session_id IN(0, ".$session_id.")
1818
                        $groupBy
1819
                        ORDER BY display_order DESC";
1820
                } else {
1821
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1822
                        $cond_user_id = " AND (
1823
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1824
                        )";
1825
                    } else {
1826
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1827
                    }
1828
1829
                    $sql = "SELECT $select
1830
                            FROM $tbl_announcement announcement
1831
                            INNER JOIN $tbl_item_property ip
1832
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1833
                            WHERE
1834
                                announcement.c_id = $courseId AND
1835
                                ip.c_id = $courseId AND
1836
                                ip.tool='announcement'
1837
                                $cond_user_id
1838
                                $condition_session
1839
                                $searchCondition  AND
1840
                                ip.visibility='1' AND
1841
                                announcement.session_id IN ( 0,".api_get_session_id().")
1842
                                $groupBy
1843
                            ";
1844
                }
1845
            }
1846
        }
1847
1848
        if (!is_null($start) && !is_null($limit)) {
1849
            $start = (int) $start;
1850
            $limit = (int) $limit;
1851
            $sql .= " LIMIT $start, $limit";
1852
        }
1853
1854
        $result = Database::query($sql);
1855
        if ($getCount) {
1856
            $result = Database::fetch_array($result, 'ASSOC');
1857
1858
            return $result['count'];
1859
        }*/
1860
1861
        $iterator = 1;
1862
        $bottomAnnouncement = $announcement_number;
1863
        $displayed = [];
1864
1865
        $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.api_get_cidreq();
1866
        $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('Announcement sent by e-mail').'"></i>';
1867
        $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
1868
1869
        $editIcon = Display::return_icon(
1870
            'edit.png',
1871
            get_lang('Edit'),
1872
            '',
1873
            ICON_SIZE_SMALL
1874
        );
1875
1876
        $editIconDisable = Display::return_icon(
1877
            'edit_na.png',
1878
            get_lang('Edit'),
1879
            '',
1880
            ICON_SIZE_SMALL
1881
        );
1882
        $deleteIcon = Display::return_icon(
1883
            'delete.png',
1884
            get_lang('Delete'),
1885
            '',
1886
            ICON_SIZE_SMALL
1887
        );
1888
1889
        $deleteIconDisable = Display::return_icon(
1890
            'delete_na.png',
1891
            get_lang('Delete'),
1892
            '',
1893
            ICON_SIZE_SMALL
1894
        );
1895
1896
        $isTutor = false;
1897
        if (!empty($group_id)) {
1898
            $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1899
            //User has access in the group?
1900
            $isTutor = GroupManager::is_tutor_of_group(
1901
                api_get_user_id(),
1902
                $groupInfo
1903
            );
1904
        }
1905
1906
        $results = [];
1907
        /** @var CAnnouncement $announcement */
1908
        foreach ($announcements as $announcement) {
1909
            $announcementId = $announcement->getIid();
1910
            if (!in_array($announcementId, $displayed)) {
1911
                $sent_to_icon = '';
1912
                // the email icon
1913
                if ('1' == $announcement->getEmailSent()) {
1914
                    $sent_to_icon = ' '.$emailIcon;
1915
                }
1916
1917
                //$groupReference = $row['to_group_id'] > 0 ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
1918
                $groupReference = '';
1919
                $disableEdit = false;
1920
                //$to = self::loadEditUsers('announcement', $announcementId, true);
1921
                $to = [];
1922
                $separated = CourseManager::separateUsersGroups($to);
1923
                if (!empty($group_id)) {
1924
                    // If the announcement was sent to many groups, disable edition inside a group
1925
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1926
                        $disableEdit = true;
1927
                    }
1928
1929
                    // If the announcement was sent only to the course disable edition
1930
                    if (empty($separated['groups']) && empty($separated['users'])) {
1931
                        $disableEdit = true;
1932
                    }
1933
1934
                    // Announcement sent to only a user
1935
                    if ($separated['groups'] > 1 && !in_array($group_id, $separated['groups'])) {
1936
                        $disableEdit = true;
1937
                    }
1938
                } else {
1939
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1940
                        $groupReference = '';
1941
                    }
1942
                }
1943
1944
                $title = $announcement->getTitle().$groupReference.$sent_to_icon;
1945
                /*$item_visibility = api_get_item_visibility(
1946
                    $courseInfo,
1947
                    TOOL_ANNOUNCEMENT,
1948
                    $row['id'],
1949
                    $session_id
1950
                );*/
1951
                $visibility = $announcement->isVisible($course, $session);
1952
1953
                // show attachment list
1954
                $attachment_list = self::get_attachment($announcementId);
1955
                $attachment_icon = '';
1956
                if (count($attachment_list) > 0) {
1957
                    $attachment_icon = ' '.$attachmentIcon;
1958
                }
1959
1960
                /* TITLE */
1961
                $username = $announcement->getResourceNode()->getCreator()->getUsername();
1962
1963
                $username_span = Display::tag(
1964
                    'span',
1965
                    $username,
1966
                    ['title' => $username]
1967
                );
1968
1969
                $title = Display::url(
1970
                    $title.$attachment_icon,
1971
                    $actionUrl.'&action=view&id='.$announcementId
1972
                );
1973
1974
                // we can edit if : we are the teacher OR the element belongs to
1975
                // the session we are coaching OR the option to allow users to edit is on
1976
                if (api_is_allowed_to_edit(false, true) ||
1977
                    (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $announcementId)) ||
1978
                    (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
1979
                    ($isTutor)
1980
                    //$row['to_group_id'] == $group_id &&
1981
                ) {
1982
                    if (true === $disableEdit) {
1983
                        $modify_icons = "<a href='#'>".$editIconDisable."</a>";
1984
                    } else {
1985
                        $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$announcementId."\">".$editIcon."</a>";
1986
                    }
1987
1988
                    $image_visibility = 'invisible';
1989
                    $setNewStatus = 'visible';
1990
                    $alt_visibility = get_lang('Visible');
1991
1992
                    if ($visibility) {
1993
                        $image_visibility = 'visible';
1994
                        $setNewStatus = 'invisible';
1995
                        $alt_visibility = get_lang('Hide');
1996
                    }
1997
1998
                    $modify_icons .= "<a href=\"".$actionUrl."&action=set_visibility&status=".$setNewStatus."&id=".$announcementId."&sec_token=".$stok."\">".
1999
                        Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
2000
2001
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
2002
                    if (1 != $iterator) {
2003
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$announcementId."&sec_token=".$stok."\">".
2004
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
2005
                    } else {
2006
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
2007
                    }
2008
                    if ($iterator < $bottomAnnouncement) {
2009
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$announcementId."&sec_token=".$stok."\">".
2010
                            Display::return_icon('down.gif', get_lang('down'))."</a>";
2011
                    } else {
2012
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('down'));
2013
                    }
2014
                    if (api_is_allowed_to_edit(false, true)) {
2015
                        if (true === $disableEdit) {
2016
                            $modify_icons .= Display::url($deleteIconDisable, '#');
2017
                        } else {
2018
                            $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$announcementId."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
2019
                                    api_htmlentities(
2020
                                        get_lang('Please confirm your choice'),
2021
                                        ENT_QUOTES,
2022
                                        api_get_system_encoding()
2023
                                    )
2024
                                )."')) return false;\">".
2025
                                $deleteIcon."</a>";
2026
                        }
2027
                    }
2028
                    $iterator++;
2029
                } else {
2030
                    $modify_icons = Display::url(
2031
                        Display::return_icon('default.png'),
2032
                        $actionUrl.'&action=view&id='.$announcementId
2033
                    );
2034
                }
2035
2036
                $results[] = [
2037
                    'id' => $announcementId,
2038
                    'title' => $title,
2039
                    'username' => $username_span,
2040
                    'insert_date' => api_convert_and_format_date(
2041
                        $announcement->getResourceNode()->getCreatedAt(),
2042
                        DATE_TIME_FORMAT_LONG
2043
                    ),
2044
                    'lastedit_date' => api_convert_and_format_date(
2045
                        $announcement->getResourceNode()->getUpdatedAt(),
2046
                        DATE_TIME_FORMAT_LONG
2047
                    ),
2048
                    'actions' => $modify_icons,
2049
                ];
2050
            }
2051
            $displayed[] = $announcementId;
2052
        }
2053
2054
        return $results;
2055
    }
2056
2057
    /**
2058
     * @return int
2059
     */
2060
    public static function getNumberAnnouncements()
2061
    {
2062
        // Maximum title messages to display
2063
        $maximum = '12';
2064
2065
        $session_id = api_get_session_id();
2066
        $courseInfo = api_get_course_info();
2067
        $courseId = $courseInfo['real_id'];
2068
        $userId = api_get_user_id();
2069
        $condition_session = api_get_session_condition(
2070
            $session_id,
2071
            true,
2072
            true,
2073
            'announcement.session_id'
2074
        );
2075
2076
        $repo = Container::getAnnouncementRepository();
2077
        $course = api_get_course_entity($courseId);
2078
        $session = api_get_session_entity($session_id);
2079
        $group = api_get_group_entity(api_get_group_id());
2080
2081
        if (api_is_allowed_to_edit(false, true)) {
2082
            // check teacher status
2083
            if (empty($_GET['origin']) || 'learnpath' !== $_GET['origin']) {
2084
                /*if (0 == api_get_group_id()) {
2085
                    $group_condition = '';
2086
                } else {
2087
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
2088
                }
2089
2090
                $sql = "SELECT
2091
                            announcement.*,
2092
                            ip.visibility,
2093
                            ip.to_group_id,
2094
                            ip.insert_user_id
2095
                        FROM $tbl_announcement announcement
2096
                        INNER JOIN $tbl_item_property ip
2097
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2098
                        WHERE
2099
                            announcement.c_id = $courseId AND
2100
                            ip.c_id = $courseId AND
2101
                            ip.tool = 'announcement' AND
2102
                            ip.visibility <> '2'
2103
                            $group_condition
2104
                            $condition_session
2105
                        GROUP BY ip.ref
2106
                        ORDER BY display_order DESC
2107
                        LIMIT 0, $maximum";*/
2108
2109
                $qb = $repo->getResourcesByCourse($course, $session, $group);
2110
                $qb->select('count(resource)');
2111
2112
                return $qb->getQuery()->getSingleScalarResult();
2113
            }
2114
        } else {
2115
            $user = api_get_user_entity($userId);
2116
2117
            if (null === $user) {
2118
                return 0;
2119
            }
2120
2121
            $qb = $repo->getResourcesByCourseLinkedToUser($user, $course, $session, $group);
2122
            $qb->select('count(resource)');
2123
2124
            return $qb->getQuery()->getSingleScalarResult();
2125
        }
2126
    }
2127
}
2128