Passed
Push — master ( db53d7...84ebef )
by Julito
09:47
created

AnnouncementManager::edit_announcement()   B

Complexity

Conditions 11
Paths 37

Size

Total Lines 79
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 34
nc 37
nop 7
dl 0
loc 79
rs 7.3166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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

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

    return false;
}

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

Loading history...
371
        $userId = (int) $userId;
372
        $groupId = (int) $groupId;
373
374
        if (api_is_allowed_to_edit(false, true) ||
375
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
376
        ) {
377
            $dql = "SELECT a, ip
378
                    FROM ChamiloCourseBundle:CAnnouncement a
379
                    JOIN ChamiloCourseBundle:CItemProperty ip
380
                    WITH a.id = ip.ref AND a.cId = ip.course
381
                    WHERE
382
                        a.id = :announcement AND
383
                        ip.tool = 'announcement' AND
384
                        a.cId = :course
385
                    ORDER BY a.displayOrder DESC";
386
        } else {
387
            $groupList[] = $groupId;
388
389
            if (0 != api_get_user_id()) {
390
                $extraGroupCondition = '';
391
                if (!empty($groupId)) {
392
                    $groupProperties = GroupManager::get_group_properties($groupId);
393
                    if (GroupManager::TOOL_PRIVATE_BETWEEN_USERS == $groupProperties['announcements_state']) {
394
                        $extraGroupCondition = " AND (
395
                            ip.toUser = $userId AND ip.group = $groupId OR
396
                            (ip.group IN ('0') OR ip.group IS NULL) OR
397
                            (ip.group = $groupId AND (ip.toUser IS NULL OR ip.toUser = 0))
398
                        )";
399
                    }
400
                }
401
402
                $dql = "SELECT a, ip
403
                        FROM ChamiloCourseBundle:CAnnouncement a
404
                        JOIN ChamiloCourseBundle:CItemProperty ip
405
                        WITH a.id = ip.ref AND a.cId = ip.course
406
                        WHERE
407
                            a.id = :announcement AND
408
                            ip.tool='announcement' AND
409
                            (
410
                                ip.toUser = $userId OR
411
                                ip.group IN ('0', '".$groupId."') OR
412
                                ip.group IS NULL
413
                            ) AND
414
                            ip.visibility = '1' AND
415
                            ip.course = :course
416
                            $extraGroupCondition
417
                        ORDER BY a.displayOrder DESC";
418
            } else {
419
                $dql = "SELECT a, ip
420
                        FROM ChamiloCourseBundle:CAnnouncement a
421
                        JOIN ChamiloCourseBundle:CItemProperty ip
422
                        WITH a.id = ip.ref AND a.cId = ip.course
423
                        WHERE
424
                            a.id = :announcement AND
425
                            ip.tool = 'announcement' AND
426
                            (ip.group = '0' OR ip.group IS NULL) AND
427
                            ip.visibility = '1' AND
428
                            ip.course = :course";
429
            }
430
        }
431
432
        $qb = Database::getManager()->createQuery($dql);
433
        $result = $qb->execute(
434
            [
435
                'announcement' => $announcementId,
436
                'course' => $courseId,
437
            ]
438
        );
439
440
        if (!empty($result)) {
441
            return [
442
                'announcement' => $result[0],
443
                'item_property' => $result[1],
444
            ];
445
        }
446
447
        return [];
448
    }
449
450
    /**
451
     * Displays one specific announcement.
452
     *
453
     * @return string
454
     */
455
    public static function displayAnnouncement($id)
456
    {
457
        $id = (int) $id;
458
459
        if (empty($id)) {
460
            return '';
461
        }
462
463
        $stok = null;
464
        $html = '';
465
        $course = api_get_course_entity(api_get_course_int_id());
466
        $session = api_get_session_entity(api_get_session_id());
467
468
        $announcement = self::getAnnouncementInfoById(
469
            $id,
470
            api_get_course_int_id(),
471
            api_get_user_id(),
472
            api_get_group_id()
473
        );
474
475
        if (empty($announcement)) {
476
            return '';
477
        }
478
479
        $title = $announcement->getTitle();
480
        $content = $announcement->getContent();
481
482
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
483
        $html .= "<tr><td><h2>".$title."</h2></td></tr>";
484
485
        $isVisible = $announcement->isVisible($course, $session);
486
487
        if (api_is_allowed_to_edit(false, true) ||
488
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
489
        ) {
490
            $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
491
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
492
493
            $image_visibility = 'invisible';
494
            $alt_visibility = get_lang('Visible');
495
            $setNewStatus = 'visible';
496
            if ($isVisible) {
497
                $image_visibility = 'visible';
498
                $alt_visibility = get_lang('Hide');
499
                $setNewStatus = 'invisible';
500
            }
501
            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=set_visibility&status=".$setNewStatus."&id=".$id."&sec_token=".$stok."\">".
502
                Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
503
504
            if (api_is_allowed_to_edit(false, true)) {
505
                $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;\">".
506
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
507
                    "</a>";
508
            }
509
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
510
        } else {
511
            if (false === $isVisible) {
512
                api_not_allowed(true);
513
            }
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 = $announcement->getUsersAndGroupSubscribedToResource();
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
        return false;
591
592
        $courseId = $courseInfo['real_id'];
0 ignored issues
show
Unused Code introduced by
$courseId = $courseInfo['real_id'] is not reachable.

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

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

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

    return false;
}

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

Loading history...
593
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
594
        $sql = "SELECT MAX(display_order)
595
                FROM $table
596
                WHERE c_id = $courseId ";
597
        $result = Database::query($sql);
598
599
        $order = 0;
600
        if (Database::num_rows($result)) {
601
            $row = Database::fetch_array($result);
602
            $order = (int) $row[0] + 1;
603
        }
604
605
        return $order;
606
    }
607
608
    /**
609
     * Store an announcement in the database (including its attached file if any).
610
     *
611
     * @param array  $courseInfo
612
     * @param int    $sessionId
613
     * @param string $title        Announcement title (pure text)
614
     * @param string $content      Content of the announcement (can be HTML)
615
     * @param array  $sentTo       Array of users and groups to send the announcement to
616
     * @param array  $file         uploaded file $_FILES
617
     * @param string $file_comment Comment describing the attachment
618
     * @param string $end_date
619
     * @param bool   $sendToUsersInSession
620
     * @param int    $authorId
621
     *
622
     * @return int false on failure, ID of the announcement on success
623
     */
624
    public static function add_announcement(
625
        $courseInfo,
626
        $sessionId,
627
        $title,
628
        $content,
629
        $sentTo,
630
        $file = [],
631
        $file_comment = null,
632
        $end_date = null,
633
        $sendToUsersInSession = false,
634
        $authorId = 0
635
    ) {
636
        if (empty($courseInfo)) {
637
            return false;
638
        }
639
640
        if (!isset($courseInfo['real_id'])) {
641
            return false;
642
        }
643
644
        $courseId = $courseInfo['real_id'];
645
        if (empty($end_date)) {
646
            $end_date = api_get_utc_datetime();
647
        }
648
649
        $order = self::getLastAnnouncementOrder($courseInfo);
650
651
        $course = api_get_course_entity($courseId);
652
        $session = api_get_session_entity($sessionId);
653
        $group = api_get_group_entity();
654
655
        $em = Database::getManager();
656
657
        $announcement = new CAnnouncement();
658
        $announcement
659
            ->setContent($content)
660
            ->setTitle($title)
661
            ->setEndDate(new DateTime($end_date))
662
            ->setDisplayOrder($order)
663
            ->setParent($course)
664
        ;
665
666
        if (empty($sentTo) || (isset($sentTo[0]) && 'everyone' === $sentTo[0])) {
667
            $announcement->addCourseLink(
668
                $course,
669
                $session,
670
                $group
671
            );
672
        } else {
673
            $send_to = CourseManager::separateUsersGroups($sentTo);
674
            // Storing the selected groups
675
            if (is_array($send_to['groups']) && !empty($send_to['groups'])) {
676
                foreach ($send_to['groups'] as $group) {
677
                    $group = api_get_group_entity($group);
678
                    if ($group) {
679
                        $announcement->addGroupLink($course, $session, $group);
680
                    }
681
                }
682
            }
683
684
            // Storing the selected users
685
            if (is_array($send_to['users'])) {
686
                foreach ($send_to['users'] as $user) {
687
                    $user = api_get_user_entity($user);
688
                    $announcement->addUserLink($user, $course, $session, $group);
689
                }
690
            }
691
        }
692
693
        if ($sendToUsersInSession) {
694
            self::addAnnouncementToAllUsersInSessions($announcement);
695
        }
696
697
        $em->persist($announcement);
698
        $em->flush();
699
700
        if (!empty($file)) {
701
            self::add_announcement_attachment_file(
702
                $announcement,
703
                $file_comment,
704
                $_FILES['user_upload']
705
            );
706
        }
707
708
        return $announcement;
709
    }
710
711
    /**
712
     * @param string $title
713
     * @param string $newContent
714
     * @param int    $groupId
715
     * @param array  $to_users
716
     * @param array  $file
717
     * @param string $file_comment
718
     * @param bool   $sendToUsersInSession
719
     *
720
     * @return bool|int
721
     */
722
    public static function addGroupAnnouncement(
723
        $title,
724
        $newContent,
725
        $groupId,
726
        $to_users,
727
        $file = [],
728
        $file_comment = '',
729
        $sendToUsersInSession = false
730
    ) {
731
        $courseInfo = api_get_course_info();
732
733
        $order = self::getLastAnnouncementOrder($courseInfo);
734
735
        $now = api_get_utc_datetime();
736
        $courseId = api_get_course_int_id();
737
        $sessionId = api_get_session_id();
738
        $course = api_get_course_entity($courseId);
739
        $announcement = new CAnnouncement();
740
        $announcement
741
            ->setContent($newContent)
742
            ->setTitle($title)
743
            ->setEndDate(new DateTime($now))
744
            ->setDisplayOrder($order)
745
            ->setParent($course)
746
            ->addCourseLink(
747
                $course,
748
                api_get_session_entity($sessionId),
749
                api_get_group_entity()
750
            );
751
752
        $repo = Container::getAnnouncementRepository();
753
        $repo->getEntityManager()->flush();
754
        $last_id = $announcement->getIid();
755
756
        // Store the attach file
757
        if ($last_id) {
758
            if (!empty($file)) {
759
                self::add_announcement_attachment_file(
760
                    $announcement,
761
                    $file_comment,
762
                    $file
763
                );
764
            }
765
766
            $send_to_users = CourseManager::separateUsersGroups($to_users);
767
768
            // if nothing was selected in the menu then send to all the group
769
            $sentToAllGroup = false;
770
            if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
771
                $groupInfo = GroupManager::get_group_properties($groupId);
772
                /*api_item_property_update(
773
                    $courseInfo,
774
                    TOOL_ANNOUNCEMENT,
775
                    $last_id,
776
                    'AnnouncementAdded',
777
                    api_get_user_id(),
778
                    $groupInfo
779
                );*/
780
                $sentToAllGroup = true;
781
            }
782
783
            if (false === $sentToAllGroup) {
784
                if (!empty($send_to_users['groups'])) {
785
                    foreach ($send_to_users['groups'] as $group) {
786
                        $groupInfo = GroupManager::get_group_properties($group);
787
                        /*api_item_property_update(
788
                            $courseInfo,
789
                            TOOL_ANNOUNCEMENT,
790
                            $last_id,
791
                            'AnnouncementAdded',
792
                            api_get_user_id(),
793
                            $groupInfo
794
                        );*/
795
                    }
796
                }
797
798
                $groupInfo = GroupManager::get_group_properties($groupId);
799
                if (!empty($send_to_users['users'])) {
800
                    foreach ($send_to_users['users'] as $user) {
801
                        /*api_item_property_update(
802
                            $courseInfo,
803
                            TOOL_ANNOUNCEMENT,
804
                            $last_id,
805
                            'AnnouncementAdded',
806
                            api_get_user_id(),
807
                            $groupInfo,
808
                            $user
809
                        );*/
810
                    }
811
                }
812
            }
813
814
            if ($sendToUsersInSession) {
815
                self::addAnnouncementToAllUsersInSessions($announcement);
816
            }
817
        }
818
819
        return $last_id;
820
    }
821
822
    /**
823
     * @param int    $id                   id of the announcement
824
     * @param string $title
825
     * @param string $newContent
826
     * @param array  $to                   users that will receive the announcement
827
     * @param mixed  $file                 attachment
828
     * @param string $file_comment         file comment
829
     * @param bool   $sendToUsersInSession
830
     */
831
    public static function edit_announcement(
832
        $id,
833
        $title,
834
        $newContent,
835
        $to,
836
        $file = [],
837
        $file_comment = '',
838
        $sendToUsersInSession = false
839
    ) {
840
        $id = (int) $id;
841
842
        $repo = Container::getAnnouncementRepository();
843
        /** @var CAnnouncement $announcement */
844
        $announcement = $repo->find($id);
845
846
        if (null === $announcement) {
847
            return false;
848
        }
849
850
        $course = api_get_course_entity();
851
        $group = api_get_group_entity();
852
        $session = api_get_session_entity();
853
854
        $announcement
855
            ->setTitle($title)
856
            ->setContent($newContent)
857
        ;
858
859
        if (!empty($file)) {
860
            self::add_announcement_attachment_file(
861
                $announcement,
862
                $file_comment,
863
                $file
864
            );
865
            /*if (empty($id_attach)) {
866
            } else {
867
                self::edit_announcement_attachment_file(
868
                    $id_attach,
869
                    $file,
870
                    $file_comment
871
                );
872
            }*/
873
        }
874
875
        if ($sendToUsersInSession) {
876
            self::addAnnouncementToAllUsersInSessions($announcement);
877
        }
878
879
        // store, first the groups, then the users
880
        if (!empty($to)) {
881
            $send_to = CourseManager::separateUsersGroups($to);
882
883
            // storing the selected groups
884
            if (is_array($send_to['groups'])) {
885
                foreach ($send_to['groups'] as $groupId) {
886
                    $announcement->addGroupLink($course, $session, api_get_group_entity($groupId));
887
                }
888
            }
889
890
            // storing the selected users
891
            if (is_array($send_to['users'])) {
892
                foreach ($send_to['users'] as $user) {
893
                    $user = api_get_user_entity($user);
894
                    $announcement->addUserLink($user, $course, $session, $group);
895
                }
896
            }
897
898
            // Send to everyone
899
            if (isset($to[0]) && 'everyone' === $to[0]) {
900
                $announcement->addCourseLink($course, $session, $group);
901
            }
902
        } else {
903
            $announcement->addCourseLink($course, $session);
904
        }
905
906
        $repo->getEntityManager()->persist($announcement);
907
        $repo->getEntityManager()->flush();
908
909
        return $announcement;
910
    }
911
912
    /**
913
     * Requires persist + flush after the function is called.
914
     *
915
     * @param CAnnouncement $announcement
916
     */
917
    public static function addAnnouncementToAllUsersInSessions($announcement)
918
    {
919
        $courseCode = api_get_course_id();
920
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
921
922
        $courseEntity = api_get_course_entity();
923
        $sessionEntity = api_get_session_entity();
924
        $groupEntity = api_get_group_entity();
925
926
        if (!empty($sessionList)) {
927
            foreach ($sessionList as $sessionInfo) {
928
                $sessionId = $sessionInfo['id'];
929
                $userList = CourseManager::get_user_list_from_course_code(
930
                    $courseCode,
931
                    $sessionId
932
                );
933
934
                if (!empty($userList)) {
935
                    foreach ($userList as $user) {
936
                        $user = api_get_user_entity($user);
937
                        $announcement->addUserLink($user, $courseEntity, $sessionEntity, $groupEntity);
938
                    }
939
                }
940
            }
941
        }
942
    }
943
944
    /**
945
     * @param int $insert_id
946
     *
947
     * @return bool
948
     */
949
    public static function update_mail_sent($insert_id)
950
    {
951
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
952
        $insert_id = intval($insert_id);
953
        // store the modifications in the table tbl_annoucement
954
        $sql = "UPDATE $table SET email_sent='1'
955
                WHERE iid = $insert_id";
956
        Database::query($sql);
957
    }
958
959
    /**
960
     * @param int $user_id
961
     *
962
     * @return CAnnouncement[]
963
     */
964
    public static function getAnnouncementCourseTotalByUser($user_id)
965
    {
966
        $user_id = (int) $user_id;
967
968
        if (empty($user_id)) {
969
            return false;
970
        }
971
972
        $user = api_get_user_entity($user_id);
973
        $repo = Container::getAnnouncementRepository();
974
975
        $qb = $repo->getResourcesByLinkedUser($user);
976
977
        return $qb->getQuery()->getResult();
978
979
        /*
980
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
981
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
982
983
        $sql = "SELECT DISTINCT
984
                    announcement.c_id,
985
                    count(announcement.id) count
986
                FROM $tbl_announcement announcement
987
                INNER JOIN $tbl_item_property ip
988
                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
989
                WHERE
990
                    ip.tool='announcement' AND
991
                    (
992
                      ip.to_user_id = '$user_id' AND
993
                      (ip.to_group_id='0' OR ip.to_group_id IS NULL)
994
                    )
995
                    AND ip.visibility='1'
996
                    AND announcement.session_id  = 0
997
                GROUP BY announcement.c_id";
998
        $rs = Database::query($sql);
999
        $num_rows = Database::num_rows($rs);
1000
        $result = [];
1001
        if ($num_rows > 0) {
1002
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1003
                if (empty($row['c_id'])) {
1004
                    continue;
1005
                }
1006
                $result[] = ['course' => api_get_course_info_by_id($row['c_id']), 'count' => $row['count']];
1007
            }
1008
        }
1009
1010
        return $result;*/
1011
    }
1012
1013
    /**
1014
     * This tools loads all the users and all the groups who have received
1015
     * a specific item (in this case an announcement item).
1016
     *
1017
     * @param CAnnouncement $announcement
1018
     * @param bool          $includeGroupWhenLoadingUser
1019
     *
1020
     * @return array
1021
     */
1022
    public static function loadEditUsers($announcement, $includeGroupWhenLoadingUser = false)
1023
    {
1024
        $result = $announcement->getUsersAndGroupSubscribedToResource();
1025
        $to = [];
1026
1027
        foreach ($result['users'] as $itemId) {
1028
            $to[] = 'USER:'.$itemId;
1029
        }
1030
1031
        foreach ($result['groups'] as $itemId) {
1032
            $to[] = 'GROUP:'.$itemId;
1033
        }
1034
1035
        return $to;
1036
    }
1037
1038
    /**
1039
     * constructs the form to display all the groups and users the message has been sent to.
1040
     *
1041
     * @param array $sent_to_array
1042
     *                             input:
1043
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1044
     *                             the first level is a distinction between groups and users:
1045
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1046
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1047
     *                             containing all the id's of the groups (resp. users) who have received this message.
1048
     *
1049
     * @return string
1050
     *
1051
     * @author Patrick Cool <patrick.cool@>
1052
     */
1053
    public static function sent_to_form($sent_to_array)
1054
    {
1055
        // we find all the names of the groups
1056
        $groupList = CourseManager::getCourseGroups();
1057
1058
        // we count the number of users and the number of groups
1059
        $number_users = 0;
1060
        if (isset($sent_to_array['users'])) {
1061
            $number_users = count($sent_to_array['users']);
1062
        }
1063
        $number_groups = 0;
1064
        if (isset($sent_to_array['groups'])) {
1065
            $number_groups = count($sent_to_array['groups']);
1066
        }
1067
1068
        $total_numbers = $number_users + $number_groups;
1069
1070
        // starting the form if there is more than one user/group
1071
        $output = [];
1072
        if ($total_numbers > 1) {
1073
            // outputting the name of the groups
1074
            if (is_array($sent_to_array['groups'])) {
1075
                foreach ($sent_to_array['groups'] as $group_id) {
1076
                    $users = GroupManager::getStudents($group_id, true);
1077
                    $userToArray = [];
1078
                    foreach ($users as $student) {
1079
                        $userToArray[] = $student['complete_name_with_username'];
1080
                    }
1081
                    $output[] =
1082
                        '<br />'.
1083
                        Display::label($groupList[$group_id]->getName(), 'info').
1084
                        '&nbsp;'.implode(', ', $userToArray);
1085
                }
1086
            }
1087
1088
            if (isset($sent_to_array['users'])) {
1089
                if (is_array($sent_to_array['users'])) {
1090
                    $usersToArray = [];
1091
                    foreach ($sent_to_array['users'] as $user_id) {
1092
                        $user_info = api_get_user_info($user_id);
1093
                        $usersToArray[] = $user_info['complete_name_with_username'];
1094
                    }
1095
                    $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
1096
                }
1097
            }
1098
        } else {
1099
            // there is only one user/group
1100
            if (isset($sent_to_array['users']) && !empty($sent_to_array['users'])) {
1101
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1102
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1103
            }
1104
            if (isset($sent_to_array['groups']) &&
1105
                is_array($sent_to_array['groups']) &&
1106
                isset($sent_to_array['groups'][0]) &&
1107
                0 !== $sent_to_array['groups'][0]
1108
            ) {
1109
                $group_id = $sent_to_array['groups'][0];
1110
1111
                $users = GroupManager::getStudents($group_id, true);
1112
                $userToArray = [];
1113
                foreach ($users as $student) {
1114
                    $userToArray[] = $student['complete_name_with_username'];
1115
                }
1116
                $output[] =
1117
                    '<br />'.
1118
                    Display::label($groupList[$group_id]->getName(), 'info').
1119
                    '&nbsp;'.implode(', ', $userToArray);
1120
            }
1121
            if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
1122
                $output[] = "&nbsp;".get_lang('All');
1123
            }
1124
        }
1125
1126
        if (!empty($output)) {
1127
            $output = array_filter($output);
1128
            if (count($output) > 0) {
1129
                $output = implode('<br />', $output);
1130
            }
1131
1132
            return $output;
1133
        }
1134
    }
1135
1136
    /**
1137
     * Show a list with all the attachments according to the post's id.
1138
     *
1139
     * @param int $announcementId
1140
     *
1141
     * @return array with the post info
1142
     *
1143
     * @author Arthur Portugal
1144
     *
1145
     * @version November 2009, dokeos 1.8.6.2
1146
     */
1147
    public static function get_attachment($announcementId)
1148
    {
1149
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1150
        $announcementId = (int) $announcementId;
1151
        $row = [];
1152
        $sql = 'SELECT iid, path, filename, comment
1153
                FROM '.$table.'
1154
				WHERE announcement_id = '.$announcementId;
1155
        $result = Database::query($sql);
1156
        $repo = Container::getAnnouncementAttachmentRepository();
1157
        if (0 != Database::num_rows($result)) {
1158
            $row = Database::fetch_array($result, 'ASSOC');
1159
        }
1160
1161
        return $row;
1162
    }
1163
1164
    /**
1165
     * This function add a attachment file into announcement.
1166
     *
1167
     * @param string file comment
1168
     * @param array  uploaded file $_FILES
1169
     *
1170
     * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
1171
     */
1172
    public static function add_announcement_attachment_file(CAnnouncement $announcement, $file_comment, $file)
1173
    {
1174
        $return = 0;
1175
        $courseId = api_get_course_int_id();
1176
1177
        if (is_array($file) && 0 == $file['error']) {
1178
            // Try to add an extension to the file if it hasn't one
1179
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1180
            // user's file name
1181
            $file_name = $file['name'];
1182
1183
            if (!filter_extension($new_file_name)) {
1184
                $return = -1;
1185
                Display::addFlash(
1186
                    Display::return_message(
1187
                        get_lang('File upload failed: this file extension or file type is prohibited'),
1188
                        'error'
1189
                    )
1190
                );
1191
            } else {
1192
                $repo = Container::getAnnouncementAttachmentRepository();
1193
                $new_file_name = uniqid('');
1194
                $attachment = new CAnnouncementAttachment();
1195
                $attachment
1196
                    ->setFilename($file_name)
1197
                    ->setPath($new_file_name)
1198
                    ->setComment($file_comment)
1199
                    ->setAnnouncement($announcement)
1200
                    ->setSize((int) $file['size'])
1201
                    ->setParent($announcement)
1202
                    ->addCourseLink(
1203
                        api_get_course_entity($courseId),
1204
                        api_get_session_entity(api_get_session_id()),
1205
                        api_get_group_entity()
1206
                    )
1207
                ;
1208
                $repo->getEntityManager()->persist($attachment);
1209
                $repo->getEntityManager()->flush();
1210
1211
                $request = Container::getRequest();
1212
                $file = $request->files->get('user_upload');
1213
1214
                if (!empty($file)) {
1215
                    $repo->addFile($attachment, $file);
1216
                    $repo->getEntityManager()->persist($attachment);
1217
                    $repo->getEntityManager()->flush();
1218
1219
                    return 1;
1220
                }
1221
1222
                $return = 1;
1223
            }
1224
        }
1225
1226
        return $return;
1227
    }
1228
1229
    /**
1230
     * This function edit a attachment file into announcement.
1231
     *
1232
     * @param int attach id
1233
     * @param array uploaded file $_FILES
1234
     * @param string file comment
1235
     *
1236
     * @return int
1237
     */
1238
    public static function edit_announcement_attachment_file(
1239
        $id_attach,
1240
        $file,
1241
        $file_comment
1242
    ) {
1243
        // @todo fix edition
1244
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
1245
        /*
1246
        $courseInfo = api_get_course_info();
1247
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1248
        $return = 0;
1249
        $courseId = api_get_course_int_id();
1250
1251
        if (is_array($file) && 0 == $file['error']) {
1252
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1253
            $courseDir = $courseInfo['path'].'/upload/announcements';
1254
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1255
            $updir = $sys_course_path.$courseDir;
1256
1257
            // Try to add an extension to the file if it hasn't one
1258
            $new_file_name = add_ext_on_mime(
1259
                stripslashes($file['name']),
1260
                $file['type']
1261
            );
1262
            // user's file name
1263
            $file_name = $file['name'];
1264
1265
            if (!filter_extension($new_file_name)) {
1266
                $return = -1;
1267
                echo Display::return_message(
1268
                    get_lang('File upload failed: this file extension or file type is prohibited'),
1269
                    'error'
1270
                );
1271
            } else {
1272
                $new_file_name = uniqid('');
1273
                $new_path = $updir.'/'.$new_file_name;
1274
                copy($file['tmp_name'], $new_path);
1275
                $safe_file_comment = Database::escape_string($file_comment);
1276
                $safe_file_name = Database::escape_string($file_name);
1277
                $safe_new_file_name = Database::escape_string($new_file_name);
1278
                $id_attach = intval($id_attach);
1279
                $sql = "UPDATE $table SET
1280
                            filename = '$safe_file_name',
1281
                            comment = '$safe_file_comment',
1282
                            path = '$safe_new_file_name',
1283
                            size ='".intval($file['size'])."'
1284
                         WHERE iid = '$id_attach'";
1285
                $result = Database::query($sql);
1286
                if (false === $result) {
1287
                    $return = -1;
1288
                    echo Display::return_message(
1289
                        get_lang('The uploaded file could not be saved (perhaps a permission problem?)'),
1290
                        'error'
1291
                    );
1292
                } else {
1293
                    $return = 1;
1294
                }
1295
            }
1296
        }
1297
1298
        return $return;*/
1299
    }
1300
1301
    /**
1302
     * This function delete a attachment file by id.
1303
     *
1304
     * @param int $id attachment file Id
1305
     *
1306
     * @return bool
1307
     */
1308
    public static function delete_announcement_attachment_file($id)
1309
    {
1310
        $id = (int) $id;
1311
        $repo = Container::getAnnouncementAttachmentRepository();
1312
        $attachment = $repo->find($id);
1313
        $repo->getEntityManager()->remove($attachment);
1314
        $repo->getEntityManager()->flush();
1315
1316
        return true;
1317
    }
1318
1319
    /**
1320
     * @param array         $courseInfo
1321
     * @param int           $sessionId
1322
     * @param CAnnouncement $announcement
1323
     * @param bool          $sendToUsersInSession
1324
     * @param bool          $sendToDrhUsers
1325
     * @param Monolog\Handler\HandlerInterface logger
1326
     * @param int  $senderId
1327
     * @param bool $directMessage
1328
     *
1329
     * @return array
1330
     */
1331
    public static function sendEmail(
1332
        $courseInfo,
1333
        $sessionId,
1334
        $announcement,
1335
        $sendToUsersInSession = false,
1336
        $sendToDrhUsers = false,
1337
        $logger = null,
1338
        $senderId = 0,
1339
        $directMessage = false
1340
    ) {
1341
        $email = new AnnouncementEmail($courseInfo, $sessionId, $announcement, $logger);
1342
1343
        return $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId, $directMessage);
1344
    }
1345
1346
    /**
1347
     * @param $stok
1348
     * @param $announcement_number
1349
     * @param bool   $getCount
1350
     * @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...
1351
     * @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...
1352
     * @param string $sidx
1353
     * @param string $sord
1354
     * @param string $titleToSearch
1355
     * @param int    $userIdToSearch
1356
     * @param int    $userId
1357
     * @param int    $courseId
1358
     * @param int    $sessionId
1359
     *
1360
     * @return array
1361
     */
1362
    public static function getAnnouncements(
1363
        $stok,
1364
        $announcement_number,
1365
        $getCount = false,
1366
        $start = null,
1367
        $limit = null,
1368
        $sidx = '',
1369
        $sord = '',
1370
        $titleToSearch = '',
1371
        $userIdToSearch = 0,
1372
        $userId = 0,
1373
        $courseId = 0,
1374
        $sessionId = 0
1375
    ) {
1376
        $group_id = api_get_group_id();
1377
        $session_id = $sessionId ?: api_get_session_id();
1378
        if (empty($courseId)) {
1379
            $courseInfo = api_get_course_info();
1380
            $courseId = $courseInfo['real_id'];
1381
        } else {
1382
            $courseId = (int) $courseId;
1383
            $courseInfo = api_get_course_info_by_id($courseId);
1384
        }
1385
1386
        if (empty($courseInfo)) {
1387
            return [];
1388
        }
1389
1390
        $repo = Container::getAnnouncementRepository();
1391
        $course = api_get_course_entity($courseId);
1392
        $session = api_get_session_entity($session_id);
1393
        $group = api_get_group_entity(api_get_group_id());
1394
1395
        $qb = $repo->getResourcesByCourse($course, $session, $group);
1396
        $announcements = $qb->getQuery()->getResult();
1397
1398
        /*$condition_session = api_get_session_condition(
1399
            $session_id,
1400
            true,
1401
            true,
1402
            'announcement.session_id'
1403
        );
1404
1405
        $group_memberships = GroupManager::get_group_ids(
1406
            $courseId,
1407
            api_get_user_id()
1408
        );
1409
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1410
1411
        $select = ' DISTINCT
1412
                        announcement.*,
1413
                        ip.visibility,
1414
                        ip.to_group_id,
1415
                        ip.insert_user_id,
1416
                        ip.insert_date,
1417
                        ip.lastedit_date';
1418
        $groupBy = ' GROUP BY announcement.iid';
1419
        if ($getCount) {
1420
            $groupBy = '';
1421
            $select = ' COUNT(DISTINCT announcement.iid) count';
1422
        }
1423
1424
        $searchCondition = '';
1425
        if (!empty($titleToSearch)) {
1426
            $titleToSearch = Database::escape_string($titleToSearch);
1427
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1428
        }
1429
1430
        if (!empty($userIdToSearch)) {
1431
            $userIdToSearch = (int) $userIdToSearch;
1432
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1433
        }
1434
1435
        $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
1436
        $extraGroupCondition = '';
1437
        if ($allowOnlyGroup) {
1438
            $extraGroupCondition = " AND ip.to_group_id = $group_id ";
1439
        }
1440
1441
        $allowDrhAccess = api_get_configuration_value('allow_drh_access_announcement');
1442
1443
        if ($allowDrhAccess && api_is_drh()) {
1444
            // DRH only can see visible
1445
            $searchCondition .= ' AND (ip.visibility = 1)';
1446
        }
1447
1448
        if (api_is_allowed_to_edit(false, true) ||
1449
            ($allowUserEditSetting && !api_is_anonymous()) ||
1450
            ($allowDrhAccess && api_is_drh())
1451
        ) {
1452
            // A.1. you are a course admin with a USER filter
1453
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1454
            //if (!empty($user_id)) {
1455
            if (0) {
1456
                if (is_array($group_memberships) &&
1457
                    count($group_memberships) > 0
1458
                ) {
1459
                    $sql = "SELECT $select
1460
                            FROM $tbl_announcement announcement
1461
                            INNER JOIN $tbl_item_property ip
1462
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1463
                            WHERE
1464
                                announcement.c_id = $courseId AND
1465
                                ip.c_id = $courseId AND
1466
                                ip.tool = 'announcement' AND
1467
                                (
1468
                                    ip.to_user_id = $user_id OR
1469
                                    ip.to_group_id IS NULL OR
1470
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1471
                                ) AND
1472
                                ip.visibility IN ('1', '0')
1473
                                $condition_session
1474
                                $searchCondition
1475
                            ORDER BY display_order DESC";
1476
                } else {
1477
                    $sql = "SELECT $select
1478
                            FROM $tbl_announcement announcement
1479
                            INNER JOIN $tbl_item_property ip
1480
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1481
                            WHERE
1482
                                announcement.c_id = $courseId AND
1483
                                ip.c_id = $courseId AND
1484
                                ip.tool ='announcement' AND
1485
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1486
                                ip.visibility IN ('1', '0')
1487
                            $condition_session
1488
                            $searchCondition
1489
                            ORDER BY display_order DESC";
1490
                }
1491
            } elseif ($group_id != 0) {
1492
                // A.2. you are a course admin with a GROUP filter
1493
                // => see only the messages of this specific group
1494
                $sql = "SELECT $select
1495
                        FROM $tbl_announcement announcement
1496
                        INNER JOIN $tbl_item_property ip
1497
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1498
                        WHERE
1499
                            ip.tool='announcement' AND
1500
                            announcement.c_id = $courseId AND
1501
                            ip.c_id = $courseId AND
1502
                            ip.visibility<>'2' AND
1503
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1504
                            $condition_session
1505
                            $searchCondition
1506
                            $extraGroupCondition
1507
                        $groupBy
1508
                        ORDER BY display_order DESC";
1509
            } else {
1510
                // A.3 you are a course admin without any group or user filter
1511
                // A.3.a you are a course admin without user or group filter but WITH studentview
1512
                // => see all the messages of all the users and groups without editing possibilities
1513
                if (isset($isStudentView) && $isStudentView == 'true') {
1514
                    $sql = "SELECT $select
1515
                            FROM $tbl_announcement announcement
1516
                            INNER JOIN $tbl_item_property ip
1517
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1518
                            WHERE
1519
                                ip.tool='announcement' AND
1520
                                announcement.c_id = $courseId AND
1521
                                ip.c_id = $courseId AND
1522
                                ip.visibility='1'
1523
                                $condition_session
1524
                                $searchCondition
1525
                            $groupBy
1526
                            ORDER BY display_order DESC";
1527
                } else {
1528
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1529
                    // => see all the messages of all the users and groups with editing possibilities
1530
                    $sql = "SELECT $select
1531
                            FROM $tbl_announcement announcement
1532
                            INNER JOIN $tbl_item_property ip
1533
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1534
                            WHERE
1535
                                ip.tool = 'announcement' AND
1536
                                announcement.c_id = $courseId AND
1537
                                ip.c_id = $courseId  AND
1538
                                (ip.visibility='0' OR ip.visibility='1')
1539
                                $condition_session
1540
                                $searchCondition
1541
                            $groupBy
1542
                            ORDER BY display_order DESC";
1543
                }
1544
            }
1545
        } else {
1546
            // STUDENT
1547
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1548
                if ($allowUserEditSetting && !api_is_anonymous()) {
1549
                    if ($group_id == 0) {
1550
                        // No group
1551
                        $cond_user_id = " AND (
1552
                            ip.lastedit_user_id = '".$user_id."' OR (
1553
                                (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
1554
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1555
                            )
1556
                        ) ";
1557
                    } else {
1558
                        $cond_user_id = " AND (
1559
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1560
                        )";
1561
                        $cond_user_id .= $extraGroupCondition;
1562
                    }
1563
                } else {
1564
                    if ($group_id == 0) {
1565
                        $cond_user_id = " AND (
1566
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1567
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1568
                        ) ";
1569
                    } else {
1570
                        $cond_user_id = " AND (
1571
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1572
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1573
                        )";
1574
                        $cond_user_id .= $extraGroupCondition;
1575
                    }
1576
                }
1577
1578
                $sql = "SELECT $select
1579
                        FROM $tbl_announcement announcement INNER JOIN
1580
                        $tbl_item_property ip
1581
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1582
                        WHERE
1583
                            announcement.c_id = $courseId AND
1584
                            ip.c_id = $courseId AND
1585
                            ip.tool='announcement'
1586
                            $cond_user_id
1587
                            $condition_session
1588
                            $searchCondition AND
1589
                            ip.visibility='1'
1590
                            $groupBy
1591
                        ORDER BY display_order DESC";
1592
            } else {
1593
                if ($user_id) {
1594
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1595
                        $cond_user_id = " AND (
1596
                                ip.lastedit_user_id = '".api_get_user_id()."' OR
1597
                                ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1598
                                (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1599
                            )
1600
                        ) ";
1601
                    } else {
1602
                        $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
1603
                        (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1604
                    }
1605
1606
                    $sql = "SELECT $select
1607
                        FROM $tbl_announcement announcement
1608
                        INNER JOIN $tbl_item_property ip
1609
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1610
                        WHERE
1611
                            announcement.c_id = $courseId AND
1612
                            ip.c_id = $courseId AND
1613
                            ip.tool='announcement'
1614
                            $cond_user_id
1615
                            $condition_session
1616
                            $searchCondition
1617
                            AND ip.visibility='1'
1618
                            AND announcement.session_id IN(0, ".$session_id.")
1619
                        $groupBy
1620
                        ORDER BY display_order DESC";
1621
                } else {
1622
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1623
                        $cond_user_id = " AND (
1624
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1625
                        )";
1626
                    } else {
1627
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1628
                    }
1629
1630
                    $sql = "SELECT $select
1631
                            FROM $tbl_announcement announcement
1632
                            INNER JOIN $tbl_item_property ip
1633
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1634
                            WHERE
1635
                                announcement.c_id = $courseId AND
1636
                                ip.c_id = $courseId AND
1637
                                ip.tool='announcement'
1638
                                $cond_user_id
1639
                                $condition_session
1640
                                $searchCondition  AND
1641
                                ip.visibility='1' AND
1642
                                announcement.session_id IN ( 0,".api_get_session_id().")
1643
                                $groupBy
1644
                            ";
1645
                }
1646
            }
1647
        }
1648
1649
        if (!is_null($start) && !is_null($limit)) {
1650
            $start = (int) $start;
1651
            $limit = (int) $limit;
1652
            $sql .= " LIMIT $start, $limit";
1653
        }
1654
1655
        $result = Database::query($sql);
1656
        if ($getCount) {
1657
            $result = Database::fetch_array($result, 'ASSOC');
1658
1659
            return $result['count'];
1660
        }*/
1661
1662
        $iterator = 1;
1663
        $bottomAnnouncement = $announcement_number;
1664
        $displayed = [];
1665
1666
        $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.api_get_cidreq();
1667
        $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('Announcement sent by e-mail').'"></i>';
1668
        $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
1669
1670
        $editIcon = Display::return_icon(
1671
            'edit.png',
1672
            get_lang('Edit'),
1673
            '',
1674
            ICON_SIZE_SMALL
1675
        );
1676
1677
        $editIconDisable = Display::return_icon(
1678
            'edit_na.png',
1679
            get_lang('Edit'),
1680
            '',
1681
            ICON_SIZE_SMALL
1682
        );
1683
        $deleteIcon = Display::return_icon(
1684
            'delete.png',
1685
            get_lang('Delete'),
1686
            '',
1687
            ICON_SIZE_SMALL
1688
        );
1689
1690
        $deleteIconDisable = Display::return_icon(
1691
            'delete_na.png',
1692
            get_lang('Delete'),
1693
            '',
1694
            ICON_SIZE_SMALL
1695
        );
1696
1697
        $isTutor = false;
1698
        if (!empty($group_id)) {
1699
            $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1700
            //User has access in the group?
1701
            $isTutor = GroupManager::is_tutor_of_group(
1702
                api_get_user_id(),
1703
                $groupInfo
1704
            );
1705
        }
1706
1707
        $results = [];
1708
        /** @var CAnnouncement $announcement */
1709
        foreach ($announcements as $announcement) {
1710
            $announcementId = $announcement->getIid();
1711
            if (!in_array($announcementId, $displayed)) {
1712
                $sent_to_icon = '';
1713
                // the email icon
1714
                if ('1' == $announcement->getEmailSent()) {
1715
                    $sent_to_icon = ' '.$emailIcon;
1716
                }
1717
1718
                //$groupReference = $row['to_group_id'] > 0 ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
1719
                $groupReference = '';
1720
                $disableEdit = false;
1721
                //$to = self::loadEditUsers('announcement', $announcementId, true);
1722
                $to = [];
1723
                $separated = CourseManager::separateUsersGroups($to);
1724
                if (!empty($group_id)) {
1725
                    // If the announcement was sent to many groups, disable edition inside a group
1726
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1727
                        $disableEdit = true;
1728
                    }
1729
1730
                    // If the announcement was sent only to the course disable edition
1731
                    if (empty($separated['groups']) && empty($separated['users'])) {
1732
                        $disableEdit = true;
1733
                    }
1734
1735
                    // Announcement sent to only a user
1736
                    if ($separated['groups'] > 1 && !in_array($group_id, $separated['groups'])) {
1737
                        $disableEdit = true;
1738
                    }
1739
                } else {
1740
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1741
                        $groupReference = '';
1742
                    }
1743
                }
1744
1745
                $title = $announcement->getTitle().$groupReference.$sent_to_icon;
1746
                /*$item_visibility = api_get_item_visibility(
1747
                    $courseInfo,
1748
                    TOOL_ANNOUNCEMENT,
1749
                    $row['id'],
1750
                    $session_id
1751
                );*/
1752
                $visibility = $announcement->isVisible($course, $session);
1753
1754
                // show attachment list
1755
                $attachment_list = self::get_attachment($announcementId);
1756
                $attachment_icon = '';
1757
                if (count($attachment_list) > 0) {
1758
                    $attachment_icon = ' '.$attachmentIcon;
1759
                }
1760
1761
                /* TITLE */
1762
                $username = $announcement->getResourceNode()->getCreator()->getUsername();
1763
1764
                $username_span = Display::tag(
1765
                    'span',
1766
                    $username,
1767
                    ['title' => $username]
1768
                );
1769
1770
                $title = Display::url(
1771
                    $title.$attachment_icon,
1772
                    $actionUrl.'&action=view&id='.$announcementId
1773
                );
1774
1775
                // we can edit if : we are the teacher OR the element belongs to
1776
                // the session we are coaching OR the option to allow users to edit is on
1777
                if (api_is_allowed_to_edit(false, true) ||
1778
                    (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $announcementId)) ||
1779
                    (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
1780
                    ($isTutor)
1781
                    //$row['to_group_id'] == $group_id &&
1782
                ) {
1783
                    if (true === $disableEdit) {
1784
                        $modify_icons = "<a href='#'>".$editIconDisable."</a>";
1785
                    } else {
1786
                        $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$announcementId."\">".$editIcon."</a>";
1787
                    }
1788
1789
                    $image_visibility = 'invisible';
1790
                    $setNewStatus = 'visible';
1791
                    $alt_visibility = get_lang('Visible');
1792
1793
                    if ($visibility) {
1794
                        $image_visibility = 'visible';
1795
                        $setNewStatus = 'invisible';
1796
                        $alt_visibility = get_lang('Hide');
1797
                    }
1798
1799
                    $modify_icons .= "<a href=\"".$actionUrl."&action=set_visibility&status=".$setNewStatus."&id=".$announcementId."&sec_token=".$stok."\">".
1800
                        Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
1801
1802
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
1803
                    if (1 != $iterator) {
1804
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$announcementId."&sec_token=".$stok."\">".
1805
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
1806
                    } else {
1807
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
1808
                    }
1809
                    if ($iterator < $bottomAnnouncement) {
1810
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$announcementId."&sec_token=".$stok."\">".
1811
                            Display::return_icon('down.gif', get_lang('down'))."</a>";
1812
                    } else {
1813
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('down'));
1814
                    }
1815
                    if (api_is_allowed_to_edit(false, true)) {
1816
                        if (true === $disableEdit) {
1817
                            $modify_icons .= Display::url($deleteIconDisable, '#');
1818
                        } else {
1819
                            $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$announcementId."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
1820
                                    api_htmlentities(
1821
                                        get_lang('Please confirm your choice'),
1822
                                        ENT_QUOTES,
1823
                                        api_get_system_encoding()
1824
                                    )
1825
                                )."')) return false;\">".
1826
                                $deleteIcon."</a>";
1827
                        }
1828
                    }
1829
                    $iterator++;
1830
                } else {
1831
                    $modify_icons = Display::url(
1832
                        Display::return_icon('default.png'),
1833
                        $actionUrl.'&action=view&id='.$announcementId
1834
                    );
1835
                }
1836
1837
                $results[] = [
1838
                    'id' => $announcementId,
1839
                    'title' => $title,
1840
                    'username' => $username_span,
1841
                    'insert_date' => api_convert_and_format_date(
1842
                        $announcement->getResourceNode()->getCreatedAt(),
1843
                        DATE_TIME_FORMAT_LONG
1844
                    ),
1845
                    'lastedit_date' => api_convert_and_format_date(
1846
                        $announcement->getResourceNode()->getUpdatedAt(),
1847
                        DATE_TIME_FORMAT_LONG
1848
                    ),
1849
                    'actions' => $modify_icons,
1850
                ];
1851
            }
1852
            $displayed[] = $announcementId;
1853
        }
1854
1855
        return $results;
1856
    }
1857
1858
    /**
1859
     * @return int
1860
     */
1861
    public static function getNumberAnnouncements()
1862
    {
1863
        $session_id = api_get_session_id();
1864
        $courseInfo = api_get_course_info();
1865
        $courseId = $courseInfo['real_id'];
1866
        $userId = api_get_user_id();
1867
1868
        $repo = Container::getAnnouncementRepository();
1869
        $course = api_get_course_entity($courseId);
1870
        $session = api_get_session_entity($session_id);
1871
        $group = api_get_group_entity(api_get_group_id());
1872
        if (api_is_allowed_to_edit(false, true)) {
1873
            // check teacher status
1874
            if (empty($_GET['origin']) || 'learnpath' !== $_GET['origin']) {
1875
                /*if (0 == api_get_group_id()) {
1876
                    $group_condition = '';
1877
                } else {
1878
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
1879
                }
1880
1881
                $sql = "SELECT
1882
                            announcement.*,
1883
                            ip.visibility,
1884
                            ip.to_group_id,
1885
                            ip.insert_user_id
1886
                        FROM $tbl_announcement announcement
1887
                        INNER JOIN $tbl_item_property ip
1888
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
1889
                        WHERE
1890
                            announcement.c_id = $courseId AND
1891
                            ip.c_id = $courseId AND
1892
                            ip.tool = 'announcement' AND
1893
                            ip.visibility <> '2'
1894
                            $group_condition
1895
                            $condition_session
1896
                        GROUP BY ip.ref
1897
                        ORDER BY display_order DESC
1898
                        LIMIT 0, $maximum";*/
1899
1900
                $qb = $repo->getResourcesByCourse($course, $session, $group);
1901
                $qb->select('count(resource)');
1902
1903
                return $qb->getQuery()->getSingleScalarResult();
1904
            }
1905
        } else {
1906
            $user = api_get_user_entity($userId);
1907
1908
            if (null === $user) {
1909
                return 0;
1910
            }
1911
1912
            $qb = $repo->getResourcesByCourseLinkedToUser($user, $course, $session, $group);
1913
            $qb->select('count(resource)');
1914
1915
            return $qb->getQuery()->getSingleScalarResult();
1916
        }
1917
    }
1918
}
1919