Completed
Push — master ( 9dadb1...edd250 )
by Julito
12:09 queued 19s
created

AnnouncementManager::parseContent()   C

Complexity

Conditions 14
Paths 120

Size

Total Lines 83
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 54
nc 120
nop 4
dl 0
loc 83
rs 6.1
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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