Completed
Push — master ( 1b7a17...dd6a34 )
by Julito
13:30
created

AnnouncementManager::add_announcement()   D

Complexity

Conditions 18
Paths 86

Size

Total Lines 144
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 62
c 1
b 0
f 0
nc 86
nop 10
dl 0
loc 144
rs 4.8666

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
6
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
7
use Chamilo\CoreBundle\Entity\ResourceLink;
8
use Chamilo\CoreBundle\Framework\Container;
9
use Chamilo\CourseBundle\Entity\CAnnouncement;
10
use Chamilo\CourseBundle\Entity\CAnnouncementAttachment;
11
12
/**
13
 * Include file with functions for the announcements module.
14
 *
15
 * @author jmontoya
16
 *
17
 * @todo use OOP
18
 */
19
class AnnouncementManager
20
{
21
    /**
22
     * Constructor.
23
     */
24
    public function __construct()
25
    {
26
    }
27
28
    /**
29
     * @return array
30
     */
31
    public static function getTags()
32
    {
33
        $tags = [
34
            '((user_name))',
35
            '((user_email))',
36
            '((user_firstname))',
37
            '((user_lastname))',
38
            '((user_official_code))',
39
            '((course_title))',
40
            '((course_link))',
41
        ];
42
43
        $tags[] = '((teachers))';
44
45
        $extraField = new ExtraField('user');
46
        $extraFields = $extraField->get_all(['filter = ?' => 1]);
47
        if (!empty($extraFields)) {
48
            foreach ($extraFields as $extra) {
49
                $tags[] = "((extra_".$extra['variable']."))";
50
            }
51
        }
52
        $sessionId = api_get_session_id();
53
        if (!empty($sessionId)) {
54
            $tags[] = '((coaches))';
55
            $tags[] = '((general_coach))';
56
            $tags[] = '((general_coach_email))';
57
        }
58
59
        return $tags;
60
    }
61
62
    /**
63
     * @param int    $userId
64
     * @param string $content
65
     * @param string $courseCode
66
     * @param int    $sessionId
67
     *
68
     * @return string
69
     */
70
    public static function parseContent(
71
        $userId,
72
        $content,
73
        $courseCode,
74
        $sessionId = 0
75
    ) {
76
        $readerInfo = api_get_user_info($userId, false, false, true, true);
77
        $courseInfo = api_get_course_info($courseCode);
78
        $teacherList = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code']);
79
80
        $generalCoachName = '';
81
        $generalCoachEmail = '';
82
        $coaches = '';
83
        if (!empty($sessionId)) {
84
            $sessionInfo = api_get_session_info($sessionId);
85
            $coaches = CourseManager::get_coachs_from_course_to_string(
86
                $sessionId,
87
                $courseInfo['real_id']
88
            );
89
90
            $generalCoach = api_get_user_info($sessionInfo['id_coach']);
91
            $generalCoachName = $generalCoach['complete_name'];
92
            $generalCoachEmail = $generalCoach['email'];
93
        }
94
95
        $data = [];
96
        $data['user_name'] = '';
97
        $data['user_firstname'] = '';
98
        $data['user_lastname'] = '';
99
        $data['user_official_code'] = '';
100
        $data['user_email'] = '';
101
        if (!empty($readerInfo)) {
102
            $data['user_name'] = $readerInfo['username'];
103
            $data['user_email'] = $readerInfo['email'];
104
            $data['user_firstname'] = $readerInfo['firstname'];
105
            $data['user_lastname'] = $readerInfo['lastname'];
106
            $data['user_official_code'] = $readerInfo['official_code'];
107
        }
108
109
        $data['course_title'] = $courseInfo['name'];
110
        $courseLink = api_get_course_url($courseCode, $sessionId);
111
        $data['course_link'] = Display::url($courseLink, $courseLink);
112
        $data['teachers'] = $teacherList;
113
114
        if (!empty($readerInfo)) {
115
            $extraField = new ExtraField('user');
116
            $extraFields = $extraField->get_all(['filter = ?' => 1]);
117
            if (!empty($extraFields)) {
118
                foreach ($extraFields as $extra) {
119
                    $data['extra_'.$extra['variable']] = '';
120
                }
121
            }
122
123
            if (!empty($readerInfo['extra'])) {
124
                foreach ($readerInfo['extra'] as $extra) {
125
                    if (isset($extra['value'])) {
126
                        /** @var \Chamilo\CoreBundle\Entity\ExtraFieldValues $value */
127
                        $value = $extra['value'];
128
                        if ($value instanceof ExtraFieldValues) {
129
                            $field = $value->getField();
130
                            if ($field instanceof ExtraFieldEntity) {
131
                                $data['extra_'.$field->getVariable()] = $value->getValue();
132
                            }
133
                        }
134
                    }
135
                }
136
            }
137
        }
138
139
        if (!empty($sessionId)) {
140
            $data['coaches'] = $coaches;
141
            $data['general_coach'] = $generalCoachName;
142
            $data['general_coach_email'] = $generalCoachEmail;
143
        }
144
145
        $tags = self::getTags();
146
        foreach ($tags as $tag) {
147
            $simpleTag = str_replace(['((', '))'], '', $tag);
148
            $value = isset($data[$simpleTag]) ? $data[$simpleTag] : '';
149
            $content = str_replace($tag, $value, $content);
150
        }
151
152
        return $content;
153
    }
154
155
    /**
156
     * Gets all announcements from a course.
157
     *
158
     * @param array $course_info
159
     * @param int   $session_id
160
     *
161
     * @return array html with the content and count of announcements or false otherwise
162
     */
163
    public static function get_all_annoucement_by_course($course_info, $session_id = 0)
164
    {
165
        $session_id = (int) $session_id;
166
        $courseId = $course_info['real_id'];
167
168
        $repo = Container::getAnnouncementRepository();
169
        $criteria = [
170
            'cId' => $courseId,
171
        ];
172
173
        return $repo->findBy($criteria);
174
        /*
175
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
176
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
177
178
        $sql = "SELECT DISTINCT
179
                    announcement.id,
180
                    announcement.title,
181
                    announcement.content
182
                FROM $tbl_announcement announcement
183
                INNER JOIN $tbl_item_property i
184
                ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
185
                WHERE
186
                    i.tool='announcement' AND
187
                    announcement.session_id  = '$session_id' AND
188
                    announcement.c_id = $courseId AND
189
                    i.c_id = $courseId
190
                ORDER BY display_order DESC";
191
        $rs = Database::query($sql);
192
        $num_rows = Database::num_rows($rs);
193
        if ($num_rows > 0) {
194
            $list = [];
195
            while ($row = Database::fetch_array($rs)) {
196
                $list[] = $row;
197
            }
198
199
            return $list;
200
        }
201
202
        return false;*/
203
    }
204
205
    /**
206
     * This functions switches the visibility a course resource
207
     * using the visibility field in 'item_property'.
208
     *
209
     * @param array  $courseInfo
210
     * @param int    $id
211
     * @param string $status
212
     *
213
     * @return bool False on failure, True on success
214
     */
215
    public static function change_visibility_announcement($courseInfo, $id, $status)
216
    {
217
        $repo = Container::getAnnouncementRepository();
218
        $announcement = $repo->find($id);
219
        if ($announcement) {
0 ignored issues
show
introduced by
$announcement is of type Chamilo\CoreBundle\Entity\ResourceInterface, thus it always evaluated to true.
Loading history...
220
            switch ($status) {
221
                case 'invisible':
222
                    $repo->setVisibilityDraft($announcement);
223
                    break;
224
                case 'visible':
225
                    $repo->setVisibilityPublished($announcement);
226
                    break;
227
            }
228
        }
229
230
        /*$session_id = api_get_session_id();
231
        $item_visibility = api_get_item_visibility(
232
            $courseInfo,
233
            TOOL_ANNOUNCEMENT,
234
            $id,
235
            $session_id
236
        );
237
        if ('1' == $item_visibility) {
238
            api_item_property_update(
239
                $courseInfo,
240
                TOOL_ANNOUNCEMENT,
241
                $id,
242
                'invisible',
243
                api_get_user_id()
244
            );
245
        } else {
246
            api_item_property_update(
247
                $courseInfo,
248
                TOOL_ANNOUNCEMENT,
249
                $id,
250
                'visible',
251
                api_get_user_id()
252
            );
253
        }*/
254
255
        return true;
256
    }
257
258
    /**
259
     * Deletes an announcement.
260
     *
261
     * @param array $courseInfo the course array
262
     * @param int   $id         the announcement id
263
     */
264
    public static function delete_announcement($courseInfo, $id)
265
    {
266
        $repo = Container::getAnnouncementRepository();
267
        $criteria = [
268
            'cId' => $courseInfo['real_id'],
269
            'id' => $id,
270
        ];
271
        $announcement = $repo->findOneBy($criteria);
272
        if ($announcement) {
273
            $repo->getEntityManager()->remove($announcement);
274
            $repo->getEntityManager()->flush();
275
        }
276
277
        /*
278
        api_item_property_update(
279
            $courseInfo,
280
            TOOL_ANNOUNCEMENT,
281
            $id,
282
            'delete',
283
            api_get_user_id()
284
        );*/
285
    }
286
287
    /**
288
     * Deletes all announcements by course.
289
     *
290
     * @param array $courseInfo the course array
291
     */
292
    public static function delete_all_announcements($courseInfo)
293
    {
294
        $repo = Container::getAnnouncementRepository();
295
        $announcements = self::get_all_annoucement_by_course(
296
            $courseInfo,
297
            api_get_session_id()
298
        );
299
300
        if (!empty($announcements)) {
301
            foreach ($announcements as $announcement) {
302
                $repo->getEntityManager()->remove($announcement);
303
                /*api_item_property_update(
304
                    $courseInfo,
305
                    TOOL_ANNOUNCEMENT,
306
                    $annon['id'],
307
                    'delete',
308
                    api_get_user_id()
309
                );*/
310
            }
311
        }
312
        $repo->getEntityManager()->flush();
313
    }
314
315
    /**
316
     * @param string $title
317
     * @param int    $courseId
318
     * @param int    $sessionId
319
     * @param int    $visibility 1 or 0
320
     *
321
     * @return mixed
322
     */
323
    public static function getAnnouncementsByTitle(
324
        $title,
325
        $courseId,
326
        $sessionId = 0,
327
        $visibility = 1
328
    ) {
329
        $dql = "SELECT a
330
                FROM ChamiloCourseBundle:CAnnouncement a
331
                JOIN ChamiloCourseBundle:CItemProperty ip
332
                WITH a.id = ip.ref AND a.cId = ip.course
333
                WHERE
334
                    ip.tool = 'announcement' AND
335
                    a.cId = :course AND
336
                    a.sessionId = :session AND
337
                    a.title like :title AND
338
                    ip.visibility = :visibility
339
                ORDER BY a.displayOrder DESC";
340
341
        $qb = Database::getManager()->createQuery($dql);
342
        $result = $qb->execute(
343
            [
344
                'course' => $courseId,
345
                'session' => $sessionId,
346
                'visibility' => $visibility,
347
                'title' => "%$title%",
348
            ]
349
        );
350
351
        return $result;
352
    }
353
354
    /**
355
     * @param int $announcementId
356
     * @param int $courseId
357
     * @param int $userId
358
     * @param int $groupId
359
     *
360
     * @return CAnnouncement
361
     */
362
    public static function getAnnouncementInfoById(
363
        $announcementId,
364
        $courseId,
365
        $userId,
366
        $groupId = 0
367
    ) {
368
        $announcementId = (int) $announcementId;
369
370
        $repo = Container::getAnnouncementRepository();
371
372
        return $repo->find($announcementId);
373
374
        $courseId = (int) $courseId;
0 ignored issues
show
Unused Code introduced by
$courseId = (int)$courseId is not reachable.

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

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

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

    return false;
}

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

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

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

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

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

    return false;
}

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

Loading history...
2176
                $group_memberships = GroupManager::get_group_ids(
2177
                    $courseInfo['real_id'],
2178
                    $userId
2179
                );
2180
2181
                if ((api_get_course_setting('allow_user_edit_announcement') &&
2182
                    !api_is_anonymous())
2183
                ) {
2184
                    if (0 == api_get_group_id()) {
2185
                        $cond_user_id = " AND (
2186
                        ip.lastedit_user_id = '".$userId."' OR (
2187
                            ip.to_user_id='".$userId."' OR
2188
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2189
                            ip.to_group_id IS NULL
2190
                            )
2191
                        )
2192
                        ";
2193
                    } else {
2194
                        $cond_user_id = " AND (
2195
                            ip.lastedit_user_id = '".$userId."'OR
2196
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2197
                            ip.to_group_id IS NULL
2198
                        )";
2199
                    }
2200
                } else {
2201
                    if (0 == api_get_group_id()) {
2202
                        $cond_user_id = " AND (
2203
                            ip.to_user_id='".$userId."' OR
2204
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2205
                            ip.to_group_id IS NULL
2206
                        ) ";
2207
                    } else {
2208
                        $cond_user_id = " AND (
2209
                            ip.to_user_id='".$userId."' OR
2210
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2211
                            ip.to_group_id IS NULL
2212
                        ) ";
2213
                    }
2214
                }
2215
2216
                // the user is member of several groups => display personal announcements AND
2217
                // his group announcements AND the general announcements
2218
                if (is_array($group_memberships) && count($group_memberships) > 0) {
2219
                    $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2220
                            FROM $tbl_announcement announcement
2221
                            INNER JOIN $tbl_item_property ip
2222
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2223
                            WHERE
2224
                                announcement.c_id = $courseId AND
2225
                                ip.c_id = $courseId AND
2226
                                ip.tool='announcement' AND
2227
                                ip.visibility='1'
2228
                                $cond_user_id
2229
                                $condition_session
2230
                            GROUP BY ip.ref
2231
                            ORDER BY display_order DESC
2232
                            LIMIT 0, $maximum";
2233
                } else {
2234
                    // the user is not member of any group
2235
                    // this is an identified user => show the general announcements AND his personal announcements
2236
                    if ($userId) {
2237
                        if ((api_get_course_setting('allow_user_edit_announcement') &&
2238
                            !api_is_anonymous())
2239
                        ) {
2240
                            $cond_user_id = " AND (
2241
                                ip.lastedit_user_id = '".$userId."' OR
2242
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2243
                            ) ";
2244
                        } else {
2245
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
2246
                        }
2247
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2248
                                FROM $tbl_announcement announcement
2249
                                INNER JOIN $tbl_item_property ip
2250
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2251
                                WHERE
2252
                                    announcement.c_id = $courseId AND
2253
                                    ip.c_id = $courseId AND
2254
                                    ip.tool='announcement' AND
2255
                                    ip.visibility='1'
2256
                                    $cond_user_id
2257
                                    $condition_session
2258
                                GROUP BY ip.ref
2259
                                ORDER BY display_order DESC
2260
                                LIMIT 0, $maximum";
2261
                    } else {
2262
                        if (api_get_course_setting('allow_user_edit_announcement')) {
2263
                            $cond_user_id = " AND (
2264
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
2265
                            ) ";
2266
                        } else {
2267
                            $cond_user_id = " AND ip.to_group_id='0' ";
2268
                        }
2269
2270
                        // the user is not identiefied => show only the general announcements
2271
                        $sql = "SELECT
2272
                                    announcement.*,
2273
                                    ip.visibility,
2274
                                    ip.to_group_id,
2275
                                    ip.insert_user_id
2276
                                FROM $tbl_announcement announcement
2277
                                INNER JOIN $tbl_item_property ip
2278
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2279
                                WHERE
2280
                                    announcement.c_id = $courseId AND
2281
                                    ip.c_id = $courseId AND
2282
                                    ip.tool='announcement' AND
2283
                                    ip.visibility='1' AND
2284
                                    ip.to_group_id='0'
2285
                                    $condition_session
2286
                                GROUP BY ip.ref
2287
                                ORDER BY display_order DESC
2288
                                LIMIT 0, $maximum";
2289
                    }
2290
                }
2291
            }
2292
        }
2293
2294
        $result = Database::query($sql);
2295
2296
        return Database::num_rows($result);
2297
    }
2298
}
2299