Completed
Push — master ( 8f0a09...1a8186 )
by Julito
24:55
created

AnnouncementManager::getAnnouncementInfoById()   B

Complexity

Conditions 8
Paths 1

Size

Total Lines 90
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 34
nc 1
nop 4
dl 0
loc 90
rs 8.1315
c 1
b 0
f 0

How to fix   Long Method   

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

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

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

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

    return false;
}

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

Loading history...
2143
                $group_memberships = GroupManager::get_group_ids(
2144
                    $courseInfo['real_id'],
2145
                    $userId
2146
                );
2147
2148
                if ((api_get_course_setting('allow_user_edit_announcement') &&
2149
                    !api_is_anonymous())
2150
                ) {
2151
                    if (0 == api_get_group_id()) {
2152
                        $cond_user_id = " AND (
2153
                        ip.lastedit_user_id = '".$userId."' OR (
2154
                            ip.to_user_id='".$userId."' OR
2155
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2156
                            ip.to_group_id IS NULL
2157
                            )
2158
                        )
2159
                        ";
2160
                    } else {
2161
                        $cond_user_id = " AND (
2162
                            ip.lastedit_user_id = '".$userId."'OR
2163
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2164
                            ip.to_group_id IS NULL
2165
                        )";
2166
                    }
2167
                } else {
2168
                    if (0 == api_get_group_id()) {
2169
                        $cond_user_id = " AND (
2170
                            ip.to_user_id='".$userId."' OR
2171
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2172
                            ip.to_group_id IS NULL
2173
                        ) ";
2174
                    } else {
2175
                        $cond_user_id = " AND (
2176
                            ip.to_user_id='".$userId."' OR
2177
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2178
                            ip.to_group_id IS NULL
2179
                        ) ";
2180
                    }
2181
                }
2182
2183
                // the user is member of several groups => display personal announcements AND
2184
                // his group announcements AND the general announcements
2185
                if (is_array($group_memberships) && count($group_memberships) > 0) {
2186
                    $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2187
                            FROM $tbl_announcement announcement
2188
                            INNER JOIN $tbl_item_property ip
2189
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2190
                            WHERE
2191
                                announcement.c_id = $courseId AND
2192
                                ip.c_id = $courseId AND
2193
                                ip.tool='announcement' AND
2194
                                ip.visibility='1'
2195
                                $cond_user_id
2196
                                $condition_session
2197
                            GROUP BY ip.ref
2198
                            ORDER BY display_order DESC
2199
                            LIMIT 0, $maximum";
2200
                } else {
2201
                    // the user is not member of any group
2202
                    // this is an identified user => show the general announcements AND his personal announcements
2203
                    if ($userId) {
2204
                        if ((api_get_course_setting('allow_user_edit_announcement') &&
2205
                            !api_is_anonymous())
2206
                        ) {
2207
                            $cond_user_id = " AND (
2208
                                ip.lastedit_user_id = '".$userId."' OR
2209
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2210
                            ) ";
2211
                        } else {
2212
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
2213
                        }
2214
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2215
                                FROM $tbl_announcement announcement
2216
                                INNER JOIN $tbl_item_property ip
2217
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2218
                                WHERE
2219
                                    announcement.c_id = $courseId AND
2220
                                    ip.c_id = $courseId AND
2221
                                    ip.tool='announcement' AND
2222
                                    ip.visibility='1'
2223
                                    $cond_user_id
2224
                                    $condition_session
2225
                                GROUP BY ip.ref
2226
                                ORDER BY display_order DESC
2227
                                LIMIT 0, $maximum";
2228
                    } else {
2229
                        if (api_get_course_setting('allow_user_edit_announcement')) {
2230
                            $cond_user_id = " AND (
2231
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
2232
                            ) ";
2233
                        } else {
2234
                            $cond_user_id = " AND ip.to_group_id='0' ";
2235
                        }
2236
2237
                        // the user is not identiefied => show only the general announcements
2238
                        $sql = "SELECT
2239
                                    announcement.*,
2240
                                    ip.visibility,
2241
                                    ip.to_group_id,
2242
                                    ip.insert_user_id
2243
                                FROM $tbl_announcement announcement
2244
                                INNER JOIN $tbl_item_property ip
2245
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2246
                                WHERE
2247
                                    announcement.c_id = $courseId AND
2248
                                    ip.c_id = $courseId AND
2249
                                    ip.tool='announcement' AND
2250
                                    ip.visibility='1' AND
2251
                                    ip.to_group_id='0'
2252
                                    $condition_session
2253
                                GROUP BY ip.ref
2254
                                ORDER BY display_order DESC
2255
                                LIMIT 0, $maximum";
2256
                    }
2257
                }
2258
            }
2259
        }
2260
2261
        $result = Database::query($sql);
2262
2263
        return Database::num_rows($result);
2264
    }
2265
}
2266