Passed
Push — master ( 8f8ee7...6565b2 )
by Julito
11:41
created

AnnouncementManager::addGroupAnnouncement()   C

Complexity

Conditions 13
Paths 50

Size

Total Lines 92
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

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