Passed
Push — master ( 905664...dfb4c6 )
by Julito
09:06
created

AnnouncementManager::addGroupAnnouncement()   C

Complexity

Conditions 11
Paths 41

Size

Total Lines 110
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 71
nc 41
nop 7
dl 0
loc 110
rs 6.486
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
6
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
7
use Chamilo\CoreBundle\Entity\Resource\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);
0 ignored issues
show
Unused Code introduced by
$tbl_announcement = Data...ble(TABLE_ANNOUNCEMENT) is not reachable.

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

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

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

    return false;
}

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

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