Passed
Push — preprodparkur ( 1e15da...a600ab )
by Angel Fernando Quiroz
20:37 queued 06:00
created

AnnouncementManager::sendEmail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 8
dl 0
loc 13
rs 10
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

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

There are several approaches to avoid long parameter lists:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
5
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
6
use Chamilo\CourseBundle\Entity\CAnnouncement;
7
use Chamilo\CourseBundle\Entity\CCalendarEvent;
8
use Chamilo\CourseBundle\Entity\CItemProperty;
9
10
/**
11
 * Include file with functions for the announcements module.
12
 *
13
 * @author jmontoya
14
 *
15
 * @package chamilo.announcements
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
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
169
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
170
171
        $sql = "SELECT DISTINCT 
172
                    announcement.id, 
173
                    announcement.title, 
174
                    announcement.content
175
				FROM $tbl_announcement announcement 
176
				INNER JOIN $tbl_item_property i
177
				ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
178
				WHERE
179
                    i.tool='announcement' AND
180
                    announcement.session_id  = '$session_id' AND
181
                    announcement.c_id = $courseId AND
182
                    i.c_id = $courseId
183
				ORDER BY display_order DESC";
184
        $rs = Database::query($sql);
185
        $num_rows = Database::num_rows($rs);
186
        if ($num_rows > 0) {
187
            $list = [];
188
            while ($row = Database::fetch_array($rs)) {
189
                $list[] = $row;
190
            }
191
192
            return $list;
193
        }
194
195
        return false;
196
    }
197
198
    /**
199
     * This functions switches the visibility a course resource
200
     * using the visibility field in 'item_property'.
201
     *
202
     * @param array $courseInfo
203
     * @param int   $id         ID of the element of the corresponding type
204
     *
205
     * @return bool False on failure, True on success
206
     */
207
    public static function change_visibility_announcement($courseInfo, $id)
208
    {
209
        $session_id = api_get_session_id();
210
        $item_visibility = api_get_item_visibility(
211
            $courseInfo,
212
            TOOL_ANNOUNCEMENT,
213
            $id,
214
            $session_id
215
        );
216
        if ($item_visibility == '1') {
217
            api_item_property_update(
218
                $courseInfo,
219
                TOOL_ANNOUNCEMENT,
220
                $id,
221
                'invisible',
222
                api_get_user_id()
223
            );
224
        } else {
225
            api_item_property_update(
226
                $courseInfo,
227
                TOOL_ANNOUNCEMENT,
228
                $id,
229
                'visible',
230
                api_get_user_id()
231
            );
232
        }
233
234
        return true;
235
    }
236
237
    /**
238
     * Deletes an announcement.
239
     *
240
     * @param array $courseInfo the course array
241
     * @param int   $id         the announcement id
242
     */
243
    public static function delete_announcement($courseInfo, $id)
244
    {
245
        api_item_property_update(
246
            $courseInfo,
247
            TOOL_ANNOUNCEMENT,
248
            $id,
249
            'delete',
250
            api_get_user_id()
251
        );
252
    }
253
254
    /**
255
     * Deletes all announcements by course.
256
     *
257
     * @param array $courseInfo the course array
258
     */
259
    public static function delete_all_announcements($courseInfo)
260
    {
261
        $announcements = self::get_all_annoucement_by_course(
262
            $courseInfo,
263
            api_get_session_id()
264
        );
265
        if (!empty($announcements)) {
266
            foreach ($announcements as $annon) {
267
                api_item_property_update(
268
                    $courseInfo,
269
                    TOOL_ANNOUNCEMENT,
270
                    $annon['id'],
271
                    'delete',
272
                    api_get_user_id()
273
                );
274
            }
275
        }
276
    }
277
278
    /**
279
     * @param string $title
280
     * @param int    $courseId
281
     * @param int    $sessionId
282
     * @param int    $visibility 1 or 0
283
     *
284
     * @return mixed
285
     */
286
    public static function getAnnouncementsByTitle(
287
        $title,
288
        $courseId,
289
        $sessionId = 0,
290
        $visibility = 1
291
    ) {
292
        $dql = "SELECT a
293
                FROM ChamiloCourseBundle:CAnnouncement a 
294
                JOIN ChamiloCourseBundle:CItemProperty ip
295
                WITH a.id = ip.ref AND a.cId = ip.course
296
                WHERE
297
                    ip.tool = 'announcement' AND                        
298
                    a.cId = :course AND
299
                    a.sessionId = :session AND
300
                    a.title like :title AND
301
                    ip.visibility = :visibility
302
                ORDER BY a.displayOrder DESC";
303
304
        $qb = Database::getManager()->createQuery($dql);
305
        $result = $qb->execute(
306
            [
307
                'course' => $courseId,
308
                'session' => $sessionId,
309
                'visibility' => $visibility,
310
                'title' => "%$title%",
311
            ]
312
        );
313
314
        return $result;
315
    }
316
317
    /**
318
     * @param int $announcementId
319
     * @param int $courseId
320
     * @param int $userId
321
     * @param int $groupId
322
     *
323
     * @return array
324
     */
325
    public static function getAnnouncementInfoById(
326
        $announcementId,
327
        $courseId,
328
        $userId,
329
        $groupId = 0
330
    ) {
331
        $announcementId = (int) $announcementId;
332
        $courseId = (int) $courseId;
333
        $userId = (int) $userId;
334
        $groupId = (int) $groupId;
335
336
        if (api_is_allowed_to_edit(false, true) ||
337
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
338
        ) {
339
            $dql = "SELECT a, ip
340
                    FROM ChamiloCourseBundle:CAnnouncement a 
341
                    JOIN ChamiloCourseBundle:CItemProperty ip
342
                    WITH a.id = ip.ref AND a.cId = ip.course
343
                    WHERE                        
344
                        a.id = :announcement AND
345
                        ip.tool = 'announcement' AND                        
346
                        a.cId = :course
347
                    ORDER BY a.displayOrder DESC";
348
        } else {
349
            $groupList[] = $groupId;
350
351
            if (api_get_user_id() != 0) {
352
                $extraGroupCondition = '';
353
                if (!empty($groupId)) {
354
                    $groupProperties = GroupManager::get_group_properties($groupId);
355
                    if ($groupProperties['announcements_state'] == GroupManager::TOOL_PRIVATE_BETWEEN_USERS) {
356
                        $extraGroupCondition = " AND (
357
                            ip.toUser = $userId AND ip.group = $groupId OR
358
                            (ip.group IN ('0') OR ip.group IS NULL) OR
359
                            (ip.group = $groupId AND (ip.toUser IS NULL OR ip.toUser = 0))
360
                        )";
361
                    }
362
                }
363
364
                $dql = "SELECT a, ip
365
                        FROM ChamiloCourseBundle:CAnnouncement a 
366
                        JOIN ChamiloCourseBundle:CItemProperty ip
367
                        WITH a.id = ip.ref AND a.cId = ip.course
368
                        WHERE                      
369
                            a.id = :announcement AND
370
                            ip.tool='announcement' AND
371
                            (
372
                                ip.toUser = $userId OR
373
                                ip.group IN ('0', '".$groupId."') OR
374
                                ip.group IS NULL
375
                            ) AND
376
                            ip.visibility = '1' AND                       
377
                            ip.course = :course
378
                            $extraGroupCondition
379
                        ORDER BY a.displayOrder DESC";
380
            } else {
381
                $dql = "SELECT a, ip
382
                        FROM ChamiloCourseBundle:CAnnouncement a 
383
                        JOIN ChamiloCourseBundle:CItemProperty ip
384
                        WITH a.id = ip.ref AND a.cId = ip.course 
385
                        WHERE                            
386
                            a.id = :announcement AND
387
                            ip.tool = 'announcement' AND
388
                            (ip.group = '0' OR ip.group IS NULL) AND
389
                            ip.visibility = '1' AND                            
390
                            ip.course = :course";
391
            }
392
        }
393
394
        $qb = Database::getManager()->createQuery($dql);
395
        $result = $qb->execute(
396
            [
397
                'announcement' => $announcementId,
398
                'course' => $courseId,
399
            ]
400
        );
401
402
        if (!empty($result)) {
403
            return [
404
                'announcement' => $result[0],
405
                'item_property' => $result[1],
406
            ];
407
        }
408
409
        return [];
410
    }
411
412
    /**
413
     * Displays one specific announcement.
414
     *
415
     * @param int $id, the id of the announcement you want to display
416
     *
417
     * @return string
418
     */
419
    public static function displayAnnouncement($id)
420
    {
421
        $id = (int) $id;
422
423
        if (empty($id)) {
424
            return '';
425
        }
426
427
        global $charset;
428
429
        $html = '';
430
        $result = self::getAnnouncementInfoById(
431
            $id,
432
            api_get_course_int_id(),
433
            api_get_user_id(),
434
            api_get_group_id()
435
        );
436
437
        if (empty($result)) {
438
            return '';
439
        }
440
441
        /** @var CAnnouncement $announcement */
442
        $announcement = $result['announcement'];
443
        /** @var CItemProperty $itemProperty */
444
        $itemProperty = $result['item_property'];
445
446
        if (empty($announcement) || empty($itemProperty)) {
447
            return '';
448
        }
449
450
        $title = $announcement->getTitle();
451
        $content = $announcement->getContent();
452
453
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
454
        $html .= "<tr><td><h2>".$title."</h2></td></tr>";
455
456
        if (api_is_allowed_to_edit(false, true) ||
457
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
458
        ) {
459
            $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
460
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
461
462
            $image_visibility = 'invisible';
463
            $alt_visibility = get_lang('Visible');
464
            if ($itemProperty->getVisibility() === 1) {
465
                $image_visibility = 'visible';
466
                $alt_visibility = get_lang('Hide');
467
            }
468
            global $stok;
469
            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=showhide&id=".$id."&sec_token=".$stok."\">".
470
                Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
471
472
            if (api_is_allowed_to_edit(false, true)) {
473
                $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('ConfirmYourChoice'), ENT_QUOTES, $charset))."')) return false;\">".
474
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
475
                    "</a>";
476
            }
477
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
478
        }
479
480
        // The user id is always the current one.
481
        $toUserId = api_get_user_id();
482
        $content = self::parseContent(
483
            $toUserId,
484
            $content,
485
            api_get_course_id(),
486
            api_get_session_id()
487
        );
488
489
        $html .= "<tr><td>$content</td></tr>";
490
        $html .= "<tr>";
491
        $html .= "<td class=\"announcements_datum\">".get_lang('LastUpdateDate')." : ";
492
        $lastEdit = $itemProperty->getLasteditDate();
493
        $html .= Display::dateToStringAgoAndLongDate($lastEdit);
494
        $html .= "</td></tr>";
495
496
        $allow = !api_get_configuration_value('hide_announcement_sent_to_users_info');
497
        if ($allow && api_is_allowed_to_edit(false, true)) {
498
            $sent_to = self::sent_to('announcement', $id);
499
            $sentToForm = self::sent_to_form($sent_to);
500
            $html .= Display::tag(
501
                'td',
502
                get_lang('SentTo').': '.$sentToForm,
503
                ['class' => 'announcements_datum']
504
            );
505
        }
506
        $attachment_list = self::get_attachment($id);
507
508
        if (count($attachment_list) > 0) {
509
            $html .= "<tr><td>";
510
            $realname = $attachment_list['path'];
511
            $user_filename = $attachment_list['filename'];
512
            $full_file_name = 'download.php?'.api_get_cidreq().'&file='.$realname;
513
            $html .= '<br/>';
514
            $html .= Display::return_icon('attachment.gif', get_lang('Attachment'));
515
            $html .= '<a href="'.$full_file_name.' "> '.$user_filename.' </a>';
516
            $html .= ' - <span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
517
            if (api_is_allowed_to_edit(false, true)) {
518
                $url = api_get_self()."?".api_get_cidreq().
519
                    "&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok;
520
                $html .= Display::url(
521
                    Display::return_icon(
522
                        'delete.png',
523
                        get_lang('Delete'),
524
                        '',
525
                        16
526
                    ),
527
                    $url
528
                );
529
            }
530
            $html .= '</td></tr>';
531
        }
532
        $html .= '</table>';
533
534
        return $html;
535
    }
536
537
    /**
538
     * @param array $courseInfo
539
     *
540
     * @return int
541
     */
542
    public static function getLastAnnouncementOrder($courseInfo)
543
    {
544
        if (empty($courseInfo)) {
545
            return 0;
546
        }
547
548
        if (!isset($courseInfo['real_id'])) {
549
            return false;
550
        }
551
552
        $courseId = $courseInfo['real_id'];
553
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
554
        $sql = "SELECT MAX(display_order)
555
                FROM $table
556
                WHERE c_id = $courseId ";
557
        $result = Database::query($sql);
558
559
        $order = 0;
560
        if (Database::num_rows($result)) {
561
            $row = Database::fetch_array($result);
562
            $order = (int) $row[0] + 1;
563
        }
564
565
        return $order;
566
    }
567
568
    /**
569
     * Store an announcement in the database (including its attached file if any).
570
     *
571
     * @param array  $courseInfo
572
     * @param int    $sessionId
573
     * @param string $title                Announcement title (pure text)
574
     * @param string $newContent           Content of the announcement (can be HTML)
575
     * @param array  $sentTo               Array of users and groups to send the announcement to
576
     * @param array  $file                 uploaded file $_FILES
577
     * @param string $file_comment         Comment describing the attachment
578
     * @param string $end_date
579
     * @param bool   $sendToUsersInSession
580
     * @param int    $authorId
581
     *
582
     * @return int false on failure, ID of the announcement on success
583
     */
584
    public static function add_announcement(
585
        $courseInfo,
586
        $sessionId,
587
        $title,
588
        $newContent,
589
        $sentTo,
590
        $file = [],
591
        $file_comment = null,
592
        $end_date = null,
593
        $sendToUsersInSession = false,
594
        $authorId = 0
595
    ) {
596
        if (empty($courseInfo)) {
597
            return false;
598
        }
599
600
        if (!isset($courseInfo['real_id'])) {
601
            return false;
602
        }
603
604
        $courseId = $courseInfo['real_id'];
605
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
606
        $authorId = empty($authorId) ? api_get_user_id() : $authorId;
607
608
        if (empty($end_date)) {
609
            $end_date = api_get_utc_datetime();
610
        }
611
612
        $order = self::getLastAnnouncementOrder($courseInfo);
613
614
        // store in the table announcement
615
        $params = [
616
            'c_id' => $courseId,
617
            'content' => $newContent,
618
            'title' => $title,
619
            'end_date' => $end_date,
620
            'display_order' => $order,
621
            'session_id' => (int) $sessionId,
622
        ];
623
624
        $last_id = Database::insert($tbl_announcement, $params);
625
626
        if (empty($last_id)) {
627
            return false;
628
        } else {
629
            $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
630
            Database::query($sql);
631
632
            if (!empty($file)) {
633
                self::add_announcement_attachment_file(
634
                    $last_id,
635
                    $file_comment,
636
                    $_FILES['user_upload']
637
                );
638
            }
639
640
            // store in item_property (first the groups, then the users
641
            if (empty($sentTo) ||
642
                (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')
643
            ) {
644
                // The message is sent to EVERYONE, so we set the group to 0
645
                api_item_property_update(
646
                    $courseInfo,
647
                    TOOL_ANNOUNCEMENT,
648
                    $last_id,
649
                    'AnnouncementAdded',
650
                    $authorId,
651
                    '0',
652
                    null,
653
                    null,
654
                    null,
655
                    $sessionId
656
                );
657
            } else {
658
                $send_to = CourseManager::separateUsersGroups($sentTo);
659
                $batchSize = 20;
660
                $em = Database::getManager();
661
                // Storing the selected groups
662
                if (is_array($send_to['groups']) &&
663
                    !empty($send_to['groups'])
664
                ) {
665
                    $counter = 1;
666
                    foreach ($send_to['groups'] as $group) {
667
                        $groupInfo = GroupManager::get_group_properties($group);
668
                        api_item_property_update(
669
                            $courseInfo,
670
                            TOOL_ANNOUNCEMENT,
671
                            $last_id,
672
                            'AnnouncementAdded',
673
                            $authorId,
674
                            $groupInfo
675
                        );
676
677
                        if (($counter % $batchSize) === 0) {
678
                            $em->flush();
679
                            $em->clear();
680
                        }
681
                        $counter++;
682
                    }
683
                }
684
685
                // Storing the selected users
686
                if (is_array($send_to['users'])) {
687
                    $counter = 1;
688
                    foreach ($send_to['users'] as $user) {
689
                        api_item_property_update(
690
                            $courseInfo,
691
                            TOOL_ANNOUNCEMENT,
692
                            $last_id,
693
                            'AnnouncementAdded',
694
                            $authorId,
695
                            '',
696
                            $user
697
                        );
698
699
                        if (($counter % $batchSize) === 0) {
700
                            $em->flush();
701
                            $em->clear();
702
                        }
703
                        $counter++;
704
                    }
705
                }
706
            }
707
708
            if ($sendToUsersInSession) {
709
                self::addAnnouncementToAllUsersInSessions($last_id);
710
            }
711
712
            return $last_id;
713
        }
714
    }
715
716
    /**
717
     * @param string $title
718
     * @param string $newContent
719
     * @param int    $groupId
720
     * @param array  $to_users
721
     * @param array  $file
722
     * @param string $file_comment
723
     * @param bool   $sendToUsersInSession
724
     *
725
     * @return bool|int
726
     */
727
    public static function addGroupAnnouncement(
728
        $title,
729
        $newContent,
730
        $groupId,
731
        $to_users,
732
        $file = [],
733
        $file_comment = '',
734
        $sendToUsersInSession = false
735
    ) {
736
        $courseInfo = api_get_course_info();
737
738
        // Database definitions
739
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
740
        $order = self::getLastAnnouncementOrder($courseInfo);
741
742
        $now = api_get_utc_datetime();
743
        $courseId = api_get_course_int_id();
744
745
        // store in the table announcement
746
        $params = [
747
            'c_id' => $courseId,
748
            'content' => $newContent,
749
            'title' => $title,
750
            'end_date' => $now,
751
            'display_order' => $order,
752
            'session_id' => api_get_session_id(),
753
        ];
754
755
        $last_id = Database::insert($table, $params);
756
757
        // Store the attach file
758
        if ($last_id) {
759
            $sql = "UPDATE $table SET id = iid 
760
                    WHERE iid = $last_id";
761
            Database::query($sql);
762
763
            if (!empty($file)) {
764
                self::add_announcement_attachment_file(
765
                    $last_id,
766
                    $file_comment,
767
                    $file
768
                );
769
            }
770
771
            $send_to_users = CourseManager::separateUsersGroups($to_users);
772
773
            // if nothing was selected in the menu then send to all the group
774
            $sentToAllGroup = false;
775
            if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
776
                $groupInfo = GroupManager::get_group_properties($groupId);
777
                api_item_property_update(
778
                    $courseInfo,
779
                    TOOL_ANNOUNCEMENT,
780
                    $last_id,
781
                    'AnnouncementAdded',
782
                    api_get_user_id(),
783
                    $groupInfo
784
                );
785
                $sentToAllGroup = true;
786
            }
787
788
            if ($sentToAllGroup === false) {
789
                if (!empty($send_to_users['groups'])) {
790
                    foreach ($send_to_users['groups'] as $group) {
791
                        $groupInfo = GroupManager::get_group_properties($group);
792
                        api_item_property_update(
793
                            $courseInfo,
794
                            TOOL_ANNOUNCEMENT,
795
                            $last_id,
796
                            'AnnouncementAdded',
797
                            api_get_user_id(),
798
                            $groupInfo
799
                        );
800
                    }
801
                }
802
803
                $groupInfo = GroupManager::get_group_properties($groupId);
804
                if (!empty($send_to_users['users'])) {
805
                    foreach ($send_to_users['users'] as $user) {
806
                        api_item_property_update(
807
                            $courseInfo,
808
                            TOOL_ANNOUNCEMENT,
809
                            $last_id,
810
                            'AnnouncementAdded',
811
                            api_get_user_id(),
812
                            $groupInfo,
813
                            $user
814
                        );
815
                    }
816
                }
817
            }
818
819
            if ($sendToUsersInSession) {
820
                self::addAnnouncementToAllUsersInSessions($last_id);
821
            }
822
        }
823
824
        return $last_id;
825
    }
826
827
    /**
828
     * This function stores the announcement item in the announcement table
829
     * and updates the item_property table.
830
     *
831
     * @param int    $id                   id of the announcement
832
     * @param string $title
833
     * @param string $newContent
834
     * @param array  $to                   users that will receive the announcement
835
     * @param mixed  $file                 attachment
836
     * @param string $file_comment         file comment
837
     * @param bool   $sendToUsersInSession
838
     */
839
    public static function edit_announcement(
840
        $id,
841
        $title,
842
        $newContent,
843
        $to,
844
        $file = [],
845
        $file_comment = '',
846
        $sendToUsersInSession = false
847
    ) {
848
        $courseInfo = api_get_course_info();
849
        $courseId = api_get_course_int_id();
850
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
851
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
852
        $id = (int) $id;
853
854
        $params = [
855
            'title' => $title,
856
            'content' => $newContent,
857
        ];
858
859
        Database::update(
860
            $table,
861
            $params,
862
            ['c_id = ? AND id = ?' => [$courseId, $id]]
863
        );
864
865
        // save attachment file
866
        $row_attach = self::get_attachment($id);
867
868
        $id_attach = 0;
869
        if ($row_attach) {
870
            $id_attach = (int) $row_attach['id'];
871
        }
872
873
        if (!empty($file)) {
874
            if (empty($id_attach)) {
875
                self::add_announcement_attachment_file(
876
                    $id,
877
                    $file_comment,
878
                    $file
879
                );
880
            } else {
881
                self::edit_announcement_attachment_file(
882
                    $id_attach,
883
                    $file,
884
                    $file_comment
885
                );
886
            }
887
        }
888
889
        // We remove everything from item_property for this
890
        $sql = "DELETE FROM $tbl_item_property
891
                WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
892
        Database::query($sql);
893
894
        if ($sendToUsersInSession) {
895
            self::addAnnouncementToAllUsersInSessions($id);
896
        }
897
898
        // store in item_property (first the groups, then the users
899
        if (!empty($to)) {
900
            // !is_null($to): when no user is selected we send it to everyone
901
            $send_to = CourseManager::separateUsersGroups($to);
902
903
            // storing the selected groups
904
            if (is_array($send_to['groups'])) {
905
                foreach ($send_to['groups'] as $group) {
906
                    $groupInfo = GroupManager::get_group_properties($group);
907
                    if (empty($groupInfo)) {
908
                        // Probably the group id and iid are different try checking the iid
909
                        $groupInfo = GroupManager::get_group_properties($group, true);
910
                    }
911
                    if ($groupInfo) {
912
                        api_item_property_update(
913
                            $courseInfo,
914
                            TOOL_ANNOUNCEMENT,
915
                            $id,
916
                            'AnnouncementUpdated',
917
                            api_get_user_id(),
918
                            $groupInfo
919
                        );
920
                    }
921
                }
922
            }
923
924
            // storing the selected users
925
            if (is_array($send_to['users'])) {
926
                foreach ($send_to['users'] as $user) {
927
                    api_item_property_update(
928
                        $courseInfo,
929
                        TOOL_ANNOUNCEMENT,
930
                        $id,
931
                        'AnnouncementUpdated',
932
                        api_get_user_id(),
933
                        0,
934
                        $user
935
                    );
936
                }
937
            }
938
939
            // Send to everyone
940
            if (isset($to[0]) && $to[0] === 'everyone') {
941
                api_item_property_update(
942
                    $courseInfo,
943
                    TOOL_ANNOUNCEMENT,
944
                    $id,
945
                    'AnnouncementUpdated',
946
                    api_get_user_id(),
947
                    0
948
                );
949
            }
950
        } else {
951
            // the message is sent to everyone, so we set the group to 0
952
            api_item_property_update(
953
                $courseInfo,
954
                TOOL_ANNOUNCEMENT,
955
                $id,
956
                'AnnouncementUpdated',
957
                api_get_user_id(),
958
                0
959
            );
960
        }
961
    }
962
963
    /**
964
     * @param int $announcementId
965
     */
966
    public static function addAnnouncementToAllUsersInSessions($announcementId)
967
    {
968
        $courseCode = api_get_course_id();
969
        $courseInfo = api_get_course_info();
970
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
971
972
        if (!empty($sessionList)) {
973
            foreach ($sessionList as $sessionInfo) {
974
                $sessionId = $sessionInfo['id'];
975
                $userList = CourseManager::get_user_list_from_course_code(
976
                    $courseCode,
977
                    $sessionId
978
                );
979
980
                if (!empty($userList)) {
981
                    foreach ($userList as $user) {
982
                        api_item_property_update(
983
                            $courseInfo,
984
                            TOOL_ANNOUNCEMENT,
985
                            $announcementId,
986
                            'AnnouncementUpdated',
987
                            api_get_user_id(),
988
                            0,
989
                            $user['user_id'],
990
                            0,
991
                            0,
992
                            $sessionId
993
                        );
994
                    }
995
                }
996
            }
997
        }
998
    }
999
1000
    /**
1001
     * @param int $insert_id
1002
     *
1003
     * @return bool
1004
     */
1005
    public static function update_mail_sent($insert_id)
1006
    {
1007
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
1008
        if ($insert_id != strval(intval($insert_id))) {
1009
            return false;
1010
        }
1011
        $insert_id = intval($insert_id);
1012
        $courseId = api_get_course_int_id();
1013
        // store the modifications in the table tbl_annoucement
1014
        $sql = "UPDATE $table SET email_sent='1'
1015
                WHERE c_id = $courseId AND id = $insert_id";
1016
        Database::query($sql);
1017
    }
1018
1019
    /**
1020
     * Gets all announcements from a user by course.
1021
     *
1022
     * @param string course db
1023
     * @param int user id
1024
     *
1025
     * @return array html with the content and count of announcements or false otherwise
1026
     */
1027
    public static function get_all_annoucement_by_user_course($course_code, $user_id)
1028
    {
1029
        $course_info = api_get_course_info($course_code);
1030
        $courseId = $course_info['real_id'];
1031
1032
        if (empty($user_id)) {
1033
            return false;
1034
        }
1035
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1036
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1037
        if (!empty($user_id) && is_numeric($user_id)) {
1038
            $user_id = (int) $user_id;
1039
            $sql = "SELECT DISTINCT 
1040
                        announcement.title, 
1041
                        announcement.content, 
1042
                        display_order
1043
					FROM $tbl_announcement announcement 
1044
					INNER JOIN $tbl_item_property ip
1045
					ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1046
					WHERE
1047
						announcement.c_id = $courseId AND
1048
						ip.c_id = $courseId AND						
1049
						ip.tool='announcement' AND
1050
						(
1051
						  ip.insert_user_id='$user_id' AND
1052
						  (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1053
						)
1054
						AND ip.visibility='1'
1055
						AND announcement.session_id  = 0
1056
					ORDER BY display_order DESC";
1057
            $rs = Database::query($sql);
1058
            $num_rows = Database::num_rows($rs);
1059
            $content = '';
1060
            $i = 0;
1061
            $result = [];
1062
            if ($num_rows > 0) {
1063
                while ($myrow = Database::fetch_array($rs)) {
1064
                    $content .= '<strong>'.$myrow['title'].'</strong><br /><br />';
1065
                    $content .= $myrow['content'];
1066
                    $i++;
1067
                }
1068
                $result['content'] = $content;
1069
                $result['count'] = $i;
1070
1071
                return $result;
1072
            }
1073
1074
            return false;
1075
        }
1076
1077
        return false;
1078
    }
1079
1080
    /**
1081
     * Returns announcement info from its id.
1082
     *
1083
     * @param int $courseId
1084
     * @param int $id
1085
     *
1086
     * @return array
1087
     */
1088
    public static function get_by_id($courseId, $id)
1089
    {
1090
        $id = (int) $id;
1091
        $courseId = $courseId ? (int) $courseId : api_get_course_int_id();
1092
1093
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1094
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1095
1096
        $sql = "SELECT DISTINCT 
1097
                    announcement.id, 
1098
                    announcement.title, 
1099
                    announcement.content,
1100
                    ip.to_group_id
1101
               FROM $tbl_announcement announcement
1102
               INNER JOIN $tbl_item_property ip
1103
               ON
1104
                    announcement.id = ip.ref AND
1105
                    announcement.c_id = ip.c_id
1106
               WHERE
1107
                    announcement.c_id = $courseId AND
1108
                    ip.tool='announcement' AND
1109
                    announcement.id = $id
1110
                ";
1111
1112
        $result = Database::query($sql);
1113
        if (Database::num_rows($result)) {
1114
            return Database::fetch_array($result);
1115
        }
1116
1117
        return [];
1118
    }
1119
1120
    /**
1121
     * this function gets all the groups of the course,
1122
     * not including linked courses.
1123
     */
1124
    public static function get_course_groups()
1125
    {
1126
        $session_id = api_get_session_id();
1127
        if ($session_id != 0) {
1128
            $new_group_list = CourseManager::get_group_list_of_course(
1129
                api_get_course_id(),
1130
                $session_id,
1131
                1
1132
            );
1133
        } else {
1134
            $new_group_list = CourseManager::get_group_list_of_course(
1135
                api_get_course_id(),
1136
                0,
1137
                1
1138
            );
1139
        }
1140
1141
        return $new_group_list;
1142
    }
1143
1144
    /**
1145
     * This tools loads all the users and all the groups who have received
1146
     * a specific item (in this case an announcement item).
1147
     *
1148
     * @param string $tool
1149
     * @param int    $id
1150
     * @param bool   $includeGroupWhenLoadingUser
1151
     *
1152
     * @return array
1153
     */
1154
    public static function loadEditUsers($tool, $id, $includeGroupWhenLoadingUser = false)
1155
    {
1156
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1157
        $tool = Database::escape_string($tool);
1158
        $id = (int) $id;
1159
        $courseId = api_get_course_int_id();
1160
        $groupId = api_get_group_id();
1161
1162
        $sql = "SELECT to_user_id, to_group_id FROM $table
1163
                WHERE c_id = $courseId AND tool='$tool' AND ref = $id";
1164
1165
        $result = Database::query($sql);
1166
        $to = [];
1167
        while ($row = Database::fetch_array($result)) {
1168
            // This is the iid of c_group_info
1169
            $toGroup = $row['to_group_id'];
1170
            if (empty($row['to_user_id']) && !empty($groupId) && $groupId != $toGroup) {
1171
                //continue;
1172
            }
1173
            switch ($toGroup) {
1174
                // it was send to one specific user
1175
                case null:
1176
                    if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
1177
                        if (!in_array('USER:'.$row['to_user_id'], $to)) {
1178
                            $to[] = 'USER:'.$row['to_user_id'];
1179
                        }
1180
                    }
1181
                    break;
1182
                // it was sent to everyone
1183
                case 0:
1184
                    return 'everyone';
1185
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1186
                default:
1187
                    if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
1188
                        if (!in_array('USER:'.$row['to_user_id'], $to)) {
1189
                            $to[] = 'USER:'.$row['to_user_id'];
1190
                        }
1191
                    } else {
1192
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1193
                            $to[] = 'GROUP:'.$toGroup;
1194
                        }
1195
                    }
1196
1197
                    if ($includeGroupWhenLoadingUser) {
1198
                        if (!in_array('GROUP:'.$toGroup, $to)) {
1199
                            $to[] = 'GROUP:'.$toGroup;
1200
                        }
1201
                    }
1202
                    break;
1203
            }
1204
        }
1205
1206
        return $to;
1207
    }
1208
1209
    /**
1210
     * constructs the form to display all the groups and users the message has been sent to.
1211
     *
1212
     * @param array $sent_to_array
1213
     *                             input:
1214
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1215
     *                             the first level is a distinction between groups and users:
1216
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1217
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1218
     *                             containing all the id's of the groups (resp. users) who have received this message.
1219
     *
1220
     * @return string
1221
     *
1222
     * @author Patrick Cool <patrick.cool@>
1223
     */
1224
    public static function sent_to_form($sent_to_array)
1225
    {
1226
        // we find all the names of the groups
1227
        $group_names = self::get_course_groups();
1228
1229
        // we count the number of users and the number of groups
1230
        $number_users = 0;
1231
        if (isset($sent_to_array['users'])) {
1232
            $number_users = count($sent_to_array['users']);
1233
        }
1234
        $number_groups = 0;
1235
        if (isset($sent_to_array['groups'])) {
1236
            $number_groups = count($sent_to_array['groups']);
1237
        }
1238
1239
        $total_numbers = $number_users + $number_groups;
1240
1241
        // starting the form if there is more than one user/group
1242
        $output = [];
1243
        if ($total_numbers > 1) {
1244
            // outputting the name of the groups
1245
            if (is_array($sent_to_array['groups'])) {
1246
                foreach ($sent_to_array['groups'] as $group_id) {
1247
                    $users = GroupManager::getStudents($group_id, true);
1248
                    $userToArray = [];
1249
                    foreach ($users as $student) {
1250
                        $userToArray[] = $student['complete_name_with_username'];
1251
                    }
1252
                    $output[] =
1253
                        '<br />'.
1254
                        Display::label($group_names[$group_id]['name'], 'info').
1255
                        '&nbsp;'.implode(', ', $userToArray);
1256
                }
1257
            }
1258
1259
            if (isset($sent_to_array['users'])) {
1260
                if (is_array($sent_to_array['users'])) {
1261
                    $usersToArray = [];
1262
                    foreach ($sent_to_array['users'] as $user_id) {
1263
                        $user_info = api_get_user_info($user_id);
1264
                        $usersToArray[] = $user_info['complete_name_with_username'];
1265
                    }
1266
                    $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
1267
                }
1268
            }
1269
        } else {
1270
            // there is only one user/group
1271
            if (isset($sent_to_array['users']) && is_array($sent_to_array['users'])) {
1272
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1273
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1274
            }
1275
            if (isset($sent_to_array['groups']) &&
1276
                is_array($sent_to_array['groups']) &&
1277
                isset($sent_to_array['groups'][0]) &&
1278
                $sent_to_array['groups'][0] !== 0
1279
            ) {
1280
                $group_id = $sent_to_array['groups'][0];
1281
1282
                $users = GroupManager::getStudents($group_id, true);
1283
                $userToArray = [];
1284
                foreach ($users as $student) {
1285
                    $userToArray[] = $student['complete_name_with_username'];
1286
                }
1287
                $output[] =
1288
                    '<br />'.
1289
                    Display::label($group_names[$group_id]['name'], 'info').
1290
                    '&nbsp;'.implode(', ', $userToArray);
1291
            }
1292
            if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
1293
                $output[] = "&nbsp;".get_lang('Everybody');
1294
            }
1295
        }
1296
1297
        if (!empty($output)) {
1298
            $output = array_filter($output);
1299
            if (count($output) > 0) {
1300
                $output = implode('<br />', $output);
1301
            }
1302
1303
            return $output;
1304
        }
1305
    }
1306
1307
    /**
1308
     * Returns all the users and all the groups a specific announcement item
1309
     * has been sent to.
1310
     *
1311
     * @param    string  The tool (announcement, agenda, ...)
1312
     * @param    int     ID of the element of the corresponding type
1313
     *
1314
     * @return array Array of users and groups to whom the element has been sent
1315
     */
1316
    public static function sent_to($tool, $id)
1317
    {
1318
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1319
        $tool = Database::escape_string($tool);
1320
        $id = (int) $id;
1321
1322
        $sent_to_group = [];
1323
        $sent_to = [];
1324
        $courseId = api_get_course_int_id();
1325
1326
        $sql = "SELECT to_group_id, to_user_id
1327
                FROM $table
1328
                WHERE c_id = $courseId AND tool = '$tool' AND ref=".$id;
1329
        $result = Database::query($sql);
1330
1331
        while ($row = Database::fetch_array($result)) {
1332
            // if to_user_id <> 0 then it is sent to a specific user
1333
            if ($row['to_user_id'] != 0) {
1334
                $sent_to_user[] = $row['to_user_id'];
1335
                continue;
1336
            }
1337
1338
            // if to_group_id is null then it is sent to a specific user
1339
            // if to_group_id = 0 then it is sent to everybody
1340
            if ($row['to_group_id'] != 0) {
1341
                $sent_to_group[] = $row['to_group_id'];
1342
            }
1343
        }
1344
1345
        if (isset($sent_to_group)) {
1346
            $sent_to['groups'] = $sent_to_group;
1347
        }
1348
1349
        if (isset($sent_to_user)) {
1350
            $sent_to['users'] = $sent_to_user;
1351
        }
1352
1353
        return $sent_to;
1354
    }
1355
1356
    /**
1357
     * Show a list with all the attachments according to the post's id.
1358
     *
1359
     * @param int $announcementId
1360
     *
1361
     * @return array with the post info
1362
     *
1363
     * @author Arthur Portugal
1364
     *
1365
     * @version November 2009, dokeos 1.8.6.2
1366
     */
1367
    public static function get_attachment($announcementId)
1368
    {
1369
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1370
        $announcementId = (int) $announcementId;
1371
        $courseId = api_get_course_int_id();
1372
        $row = [];
1373
        $sql = 'SELECT id, path, filename, comment 
1374
                FROM '.$table.'
1375
				WHERE c_id = '.$courseId.' AND announcement_id = '.$announcementId;
1376
        $result = Database::query($sql);
1377
        if (Database::num_rows($result) != 0) {
1378
            $row = Database::fetch_array($result, 'ASSOC');
1379
        }
1380
1381
        return $row;
1382
    }
1383
1384
    /**
1385
     * This function add a attachment file into announcement.
1386
     *
1387
     * @param int  announcement id
1388
     * @param string file comment
1389
     * @param array  uploaded file $_FILES
1390
     *
1391
     * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
1392
     */
1393
    public static function add_announcement_attachment_file(
1394
        $announcement_id,
1395
        $file_comment,
1396
        $file
1397
    ) {
1398
        $courseInfo = api_get_course_info();
1399
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1400
        $return = 0;
1401
        $announcement_id = intval($announcement_id);
1402
        $courseId = api_get_course_int_id();
1403
1404
        if (is_array($file) && $file['error'] == 0) {
1405
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1406
            $courseDir = $courseInfo['path'].'/upload/announcements';
1407
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1408
            $updir = $sys_course_path.$courseDir;
1409
1410
            // Try to add an extension to the file if it hasn't one
1411
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1412
            // user's file name
1413
            $file_name = $file['name'];
1414
1415
            if (!filter_extension($new_file_name)) {
1416
                $return = -1;
1417
                echo Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error');
1418
            } else {
1419
                $new_file_name = uniqid('');
1420
                $new_path = $updir.'/'.$new_file_name;
1421
1422
                // This file is copy here but its cleaned in api_mail_html in api.lib.php
1423
                copy($file['tmp_name'], $new_path);
1424
1425
                $params = [
1426
                    'c_id' => $courseId,
1427
                    'filename' => $file_name,
1428
                    'comment' => $file_comment,
1429
                    'path' => $new_file_name,
1430
                    'announcement_id' => $announcement_id,
1431
                    'size' => intval($file['size']),
1432
                ];
1433
1434
                $insertId = Database::insert($table, $params);
1435
                if ($insertId) {
1436
                    $sql = "UPDATE $table SET id = iid 
1437
                            WHERE iid = $insertId";
1438
                    Database::query($sql);
1439
                }
1440
1441
                $return = 1;
1442
            }
1443
        }
1444
1445
        return $return;
1446
    }
1447
1448
    /**
1449
     * This function edit a attachment file into announcement.
1450
     *
1451
     * @param int attach id
1452
     * @param array uploaded file $_FILES
1453
     * @param string file comment
1454
     *
1455
     * @return int
1456
     */
1457
    public static function edit_announcement_attachment_file(
1458
        $id_attach,
1459
        $file,
1460
        $file_comment
1461
    ) {
1462
        $courseInfo = api_get_course_info();
1463
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1464
        $return = 0;
1465
        $courseId = api_get_course_int_id();
1466
1467
        if (is_array($file) && $file['error'] == 0) {
1468
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1469
            $courseDir = $courseInfo['path'].'/upload/announcements';
1470
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1471
            $updir = $sys_course_path.$courseDir;
1472
1473
            // Try to add an extension to the file if it hasn't one
1474
            $new_file_name = add_ext_on_mime(
1475
                stripslashes($file['name']),
1476
                $file['type']
1477
            );
1478
            // user's file name
1479
            $file_name = $file['name'];
1480
1481
            if (!filter_extension($new_file_name)) {
1482
                $return = -1;
1483
                echo Display::return_message(
1484
                    get_lang('UplUnableToSaveFileFilteredExtension'),
1485
                    'error'
1486
                );
1487
            } else {
1488
                $new_file_name = uniqid('');
1489
                $new_path = $updir.'/'.$new_file_name;
1490
                copy($file['tmp_name'], $new_path);
1491
                $safe_file_comment = Database::escape_string($file_comment);
1492
                $safe_file_name = Database::escape_string($file_name);
1493
                $safe_new_file_name = Database::escape_string($new_file_name);
1494
                $id_attach = intval($id_attach);
1495
                $sql = "UPDATE $table SET 
1496
                            filename = '$safe_file_name', 
1497
                            comment = '$safe_file_comment', 
1498
                            path = '$safe_new_file_name', 
1499
                            size ='".intval($file['size'])."'
1500
					 	WHERE c_id = $courseId AND id = '$id_attach'";
1501
                $result = Database::query($sql);
1502
                if ($result === false) {
1503
                    $return = -1;
1504
                    echo Display::return_message(
1505
                        get_lang('UplUnableToSaveFile'),
1506
                        'error'
1507
                    );
1508
                } else {
1509
                    $return = 1;
1510
                }
1511
            }
1512
        }
1513
1514
        return $return;
1515
    }
1516
1517
    /**
1518
     * This function delete a attachment file by id.
1519
     *
1520
     * @param int $id attachment file Id
1521
     *
1522
     * @return bool
1523
     */
1524
    public static function delete_announcement_attachment_file($id)
1525
    {
1526
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1527
        $id = intval($id);
1528
        $courseId = api_get_course_int_id();
1529
        if (empty($courseId) || empty($id)) {
1530
            return false;
1531
        }
1532
        $sql = "DELETE FROM $table
1533
                WHERE c_id = $courseId AND id = $id";
1534
        Database::query($sql);
1535
1536
        return true;
1537
    }
1538
1539
    /**
1540
     * @param array $courseInfo
1541
     * @param int   $sessionId
1542
     * @param int   $announcementId
1543
     * @param bool  $sendToUsersInSession
1544
     * @param bool  $sendToDrhUsers
1545
     * @param Monolog\Handler\HandlerInterface logger
1546
     * @param int  $senderId
1547
     * @param bool $directMessage
1548
     *
1549
     * @return array
1550
     */
1551
    public static function sendEmail(
1552
        $courseInfo,
1553
        $sessionId,
1554
        $announcementId,
1555
        $sendToUsersInSession = false,
1556
        $sendToDrhUsers = false,
1557
        $logger = null,
1558
        $senderId = 0,
1559
        $directMessage = false
1560
    ) {
1561
        $email = new AnnouncementEmail($courseInfo, $sessionId, $announcementId, $logger);
1562
1563
        return $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId, $directMessage);
1564
    }
1565
1566
    /**
1567
     * @param $stok
1568
     * @param $announcement_number
1569
     * @param bool   $getCount
1570
     * @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...
1571
     * @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...
1572
     * @param string $sidx
1573
     * @param string $sord
1574
     * @param string $titleToSearch
1575
     * @param int    $userIdToSearch
1576
     * @param int    $userId
1577
     * @param int    $courseId
1578
     * @param int    $sessionId
1579
     *
1580
     * @return array
1581
     */
1582
    public static function getAnnouncements(
1583
        $stok,
1584
        $announcement_number,
1585
        $getCount = false,
1586
        $start = null,
1587
        $limit = null,
1588
        $sidx = '',
1589
        $sord = '',
1590
        $titleToSearch = '',
1591
        $userIdToSearch = 0,
1592
        $userId = 0,
1593
        $courseId = 0,
1594
        $sessionId = 0
1595
    ) {
1596
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1597
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1598
1599
        $user_id = $userId ?: api_get_user_id();
1600
        $group_id = api_get_group_id();
1601
        $session_id = $sessionId ?: api_get_session_id();
1602
        if (empty($courseId)) {
1603
            $courseInfo = api_get_course_info();
1604
            $courseId = $courseInfo['real_id'];
1605
        } else {
1606
            $courseId = (int) $courseId;
1607
            $courseInfo = api_get_course_info_by_id($courseId);
1608
        }
1609
1610
        if (empty($courseInfo)) {
1611
            return [];
1612
        }
1613
1614
        $condition_session = api_get_session_condition(
1615
            $session_id,
1616
            true,
1617
            true,
1618
            'announcement.session_id'
1619
        );
1620
1621
        $group_memberships = GroupManager::get_group_ids(
1622
            $courseId,
1623
            api_get_user_id()
1624
        );
1625
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1626
1627
        $select = ' DISTINCT 
1628
                        announcement.*, 
1629
                        ip.visibility, 
1630
                        ip.to_group_id, 
1631
                        ip.insert_user_id, 
1632
                        ip.insert_date, 
1633
                        ip.lastedit_date';
1634
        $groupBy = ' GROUP BY announcement.iid';
1635
        if ($getCount) {
1636
            $groupBy = '';
1637
            $select = ' COUNT(DISTINCT announcement.iid) count';
1638
        }
1639
1640
        $searchCondition = '';
1641
        if (!empty($titleToSearch)) {
1642
            $titleToSearch = Database::escape_string($titleToSearch);
1643
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1644
        }
1645
1646
        if (!empty($userIdToSearch)) {
1647
            $userIdToSearch = (int) $userIdToSearch;
1648
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1649
        }
1650
1651
        $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
1652
        $extraGroupCondition = '';
1653
        if ($allowOnlyGroup) {
1654
            $extraGroupCondition = " AND ip.to_group_id = $group_id ";
1655
        }
1656
1657
        $allowDrhAccess = api_get_configuration_value('allow_drh_access_announcement');
1658
1659
        if ($allowDrhAccess && api_is_drh()) {
1660
            // DRH only can see visible
1661
            $searchCondition .= ' AND (ip.visibility = 1)';
1662
        }
1663
1664
        if (api_is_allowed_to_edit(false, true) ||
1665
            ($allowUserEditSetting && !api_is_anonymous()) ||
1666
            ($allowDrhAccess && api_is_drh())
1667
        ) {
1668
            // A.1. you are a course admin with a USER filter
1669
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1670
            //if (!empty($user_id)) {
1671
            if (0) {
1672
                if (is_array($group_memberships) &&
1673
                    count($group_memberships) > 0
1674
                ) {
1675
                    $sql = "SELECT $select
1676
                            FROM $tbl_announcement announcement 
1677
                            INNER JOIN $tbl_item_property ip
1678
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1679
                            WHERE
1680
                                announcement.c_id = $courseId AND
1681
                                ip.c_id = $courseId AND                                
1682
                                ip.tool = 'announcement' AND
1683
                                (
1684
                                    ip.to_user_id = $user_id OR
1685
                                    ip.to_group_id IS NULL OR
1686
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1687
                                ) AND
1688
                                ip.visibility IN ('1', '0')
1689
                                $condition_session
1690
                                $searchCondition
1691
                            ORDER BY display_order DESC";
1692
                } else {
1693
                    $sql = "SELECT $select
1694
                            FROM $tbl_announcement announcement 
1695
                            INNER JOIN $tbl_item_property ip
1696
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1697
                            WHERE
1698
                                announcement.c_id = $courseId AND
1699
                                ip.c_id = $courseId AND
1700
                                ip.tool ='announcement' AND
1701
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1702
                                ip.visibility IN ('1', '0')
1703
                            $condition_session
1704
                            $searchCondition
1705
                            ORDER BY display_order DESC";
1706
                }
1707
            } elseif ($group_id != 0) {
1708
                // A.2. you are a course admin with a GROUP filter
1709
                // => see only the messages of this specific group
1710
                $sql = "SELECT $select
1711
                        FROM $tbl_announcement announcement 
1712
                        INNER JOIN $tbl_item_property ip
1713
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1714
                        WHERE
1715
                            ip.tool='announcement' AND
1716
                            announcement.c_id = $courseId AND
1717
                            ip.c_id = $courseId AND
1718
                            ip.visibility<>'2' AND
1719
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1720
                            $condition_session
1721
                            $searchCondition
1722
                            $extraGroupCondition
1723
                        $groupBy
1724
                        ORDER BY display_order DESC";
1725
            } else {
1726
                // A.3 you are a course admin without any group or user filter
1727
                // A.3.a you are a course admin without user or group filter but WITH studentview
1728
                // => see all the messages of all the users and groups without editing possibilities
1729
                if (isset($isStudentView) && $isStudentView == 'true') {
1730
                    $sql = "SELECT $select
1731
                            FROM $tbl_announcement announcement 
1732
                            INNER JOIN $tbl_item_property ip
1733
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1734
                            WHERE
1735
                                ip.tool='announcement' AND
1736
                                announcement.c_id = $courseId AND
1737
                                ip.c_id = $courseId AND                                
1738
                                ip.visibility='1'
1739
                                $condition_session
1740
                                $searchCondition
1741
                            $groupBy
1742
                            ORDER BY display_order DESC";
1743
                } else {
1744
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1745
                    // => see all the messages of all the users and groups with editing possibilities
1746
                    $sql = "SELECT $select
1747
                            FROM $tbl_announcement announcement 
1748
                            INNER JOIN $tbl_item_property ip
1749
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1750
                            WHERE
1751
                                ip.tool = 'announcement' AND
1752
                                announcement.c_id = $courseId AND
1753
                                ip.c_id = $courseId  AND
1754
                                (ip.visibility='0' OR ip.visibility='1')
1755
                                $condition_session
1756
                                $searchCondition
1757
                            $groupBy
1758
                            ORDER BY display_order DESC";
1759
                }
1760
            }
1761
        } else {
1762
            // STUDENT
1763
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1764
                if ($allowUserEditSetting && !api_is_anonymous()) {
1765
                    if ($group_id == 0) {
1766
                        // No group
1767
                        $cond_user_id = " AND (
1768
                            ip.lastedit_user_id = '".$user_id."' OR (
1769
                                (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
1770
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1771
                            )
1772
                        ) ";
1773
                    } else {
1774
                        $cond_user_id = " AND (
1775
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1776
                        )";
1777
                        $cond_user_id .= $extraGroupCondition;
1778
                    }
1779
                } else {
1780
                    if ($group_id == 0) {
1781
                        $cond_user_id = " AND (
1782
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND 
1783
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1784
                        ) ";
1785
                    } else {
1786
                        $cond_user_id = " AND (
1787
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND 
1788
                            (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1789
                        )";
1790
                        $cond_user_id .= $extraGroupCondition;
1791
                    }
1792
                }
1793
1794
                $sql = "SELECT $select
1795
                        FROM $tbl_announcement announcement INNER JOIN
1796
                        $tbl_item_property ip
1797
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1798
                        WHERE
1799
                            announcement.c_id = $courseId AND
1800
                            ip.c_id = $courseId AND                            
1801
                            ip.tool='announcement' 
1802
                            $cond_user_id
1803
                            $condition_session
1804
                            $searchCondition AND 
1805
                            ip.visibility='1'
1806
                            $groupBy
1807
                        ORDER BY display_order DESC";
1808
            } else {
1809
                if ($user_id) {
1810
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1811
                        $cond_user_id = " AND (
1812
                                ip.lastedit_user_id = '".api_get_user_id()."' OR
1813
                                ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND 
1814
                                (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1815
                            )
1816
                        ) ";
1817
                    } else {
1818
                        $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND 
1819
                        (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1820
                    }
1821
1822
                    $sql = "SELECT $select
1823
						FROM $tbl_announcement announcement 
1824
						INNER JOIN $tbl_item_property ip
1825
						ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1826
						WHERE
1827
    						announcement.c_id = $courseId AND
1828
							ip.c_id = $courseId AND    						
1829
    						ip.tool='announcement'
1830
    						$cond_user_id
1831
    						$condition_session
1832
    						$searchCondition
1833
    						AND ip.visibility='1'
1834
    						AND announcement.session_id IN(0, ".$session_id.")
1835
                        $groupBy
1836
						ORDER BY display_order DESC";
1837
                } else {
1838
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1839
                        $cond_user_id = " AND (
1840
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1841
                        )";
1842
                    } else {
1843
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1844
                    }
1845
1846
                    $sql = "SELECT $select
1847
                            FROM $tbl_announcement announcement 
1848
                            INNER JOIN $tbl_item_property ip
1849
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1850
                            WHERE
1851
                                announcement.c_id = $courseId AND
1852
                                ip.c_id = $courseId AND                            
1853
                                ip.tool='announcement'
1854
                                $cond_user_id
1855
                                $condition_session
1856
                                $searchCondition  AND
1857
                                ip.visibility='1' AND
1858
                                announcement.session_id IN ( 0,".api_get_session_id().")
1859
                                $groupBy
1860
                            ";
1861
                }
1862
            }
1863
        }
1864
1865
        if (!is_null($start) && !is_null($limit)) {
1866
            $start = (int) $start;
1867
            $limit = (int) $limit;
1868
            $sql .= " LIMIT $start, $limit";
1869
        }
1870
1871
        $result = Database::query($sql);
1872
        if ($getCount) {
1873
            $result = Database::fetch_array($result, 'ASSOC');
1874
1875
            return $result['count'];
1876
        }
1877
1878
        $iterator = 1;
1879
        $bottomAnnouncement = $announcement_number;
1880
        $displayed = [];
1881
        $results = [];
1882
        $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.api_get_cidreq();
1883
        $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('AnnounceSentByEmail').'"></i>';
1884
        $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
1885
1886
        $editIcon = Display::return_icon(
1887
            'edit.png',
1888
            get_lang('Edit'),
1889
            '',
1890
            ICON_SIZE_SMALL
1891
        );
1892
1893
        $editIconDisable = Display::return_icon(
1894
            'edit_na.png',
1895
            get_lang('Edit'),
1896
            '',
1897
            ICON_SIZE_SMALL
1898
        );
1899
        $deleteIcon = Display::return_icon(
1900
            'delete.png',
1901
            get_lang('Delete'),
1902
            '',
1903
            ICON_SIZE_SMALL
1904
        );
1905
1906
        $deleteIconDisable = Display::return_icon(
1907
            'delete_na.png',
1908
            get_lang('Delete'),
1909
            '',
1910
            ICON_SIZE_SMALL
1911
        );
1912
1913
        $isTutor = false;
1914
        if (!empty($group_id)) {
1915
            $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1916
            //User has access in the group?
1917
            $isTutor = GroupManager::is_tutor_of_group(
1918
                api_get_user_id(),
1919
                $groupInfo
1920
            );
1921
        }
1922
1923
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1924
            if (!in_array($row['id'], $displayed)) {
1925
                $sent_to_icon = '';
1926
                // the email icon
1927
                if ($row['email_sent'] == '1') {
1928
                    $sent_to_icon = ' '.$emailIcon;
1929
                }
1930
1931
                $groupReference = $row['to_group_id'] > 0 ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
1932
                $disableEdit = false;
1933
                $to = self::loadEditUsers('announcement', $row['id'], true);
1934
                $separated = CourseManager::separateUsersGroups($to);
1935
                if (!empty($group_id)) {
1936
                    // If the announcement was sent to many groups, disable edition inside a group
1937
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1938
                        $disableEdit = true;
1939
                    }
1940
1941
                    // If the announcement was sent only to the course disable edition
1942
                    if (empty($separated['groups']) && empty($separated['users'])) {
1943
                        $disableEdit = true;
1944
                    }
1945
1946
                    // Announcement sent to only a user
1947
                    if ($separated['groups'] > 1 && !in_array($group_id, $separated['groups'])) {
1948
                        $disableEdit = true;
1949
                    }
1950
                } else {
1951
                    if (isset($separated['groups']) && count($separated['groups']) > 1) {
1952
                        $groupReference = '';
1953
                    }
1954
                }
1955
1956
                $title = $row['title'].$groupReference.$sent_to_icon;
1957
                $item_visibility = api_get_item_visibility(
1958
                    $courseInfo,
1959
                    TOOL_ANNOUNCEMENT,
1960
                    $row['id'],
1961
                    $session_id
1962
                );
1963
                $row['visibility'] = $item_visibility;
1964
1965
                // show attachment list
1966
                $attachment_list = self::get_attachment($row['id']);
1967
                $attachment_icon = '';
1968
                if (count($attachment_list) > 0) {
1969
                    $attachment_icon = ' '.$attachmentIcon;
1970
                }
1971
1972
                /* TITLE */
1973
                $user_info = api_get_user_info($row['insert_user_id']);
1974
                $username = sprintf(get_lang('LoginX'), $user_info['username']);
1975
1976
                $username_span = Display::tag(
1977
                    'span',
1978
                    $user_info['complete_name'],
1979
                    ['title' => $username]
1980
                );
1981
1982
                $title = Display::url(
1983
                    $title.$attachment_icon,
1984
                    $actionUrl.'&action=view&id='.$row['id']
1985
                );
1986
1987
                // we can edit if : we are the teacher OR the element belongs to
1988
                // the session we are coaching OR the option to allow users to edit is on
1989
                if (api_is_allowed_to_edit(false, true) ||
1990
                    (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $row['id'])) ||
1991
                    (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
1992
                    ($row['to_group_id'] == $group_id && $isTutor)
1993
                ) {
1994
                    if ($disableEdit === true) {
1995
                        $modify_icons = "<a href='#'>".$editIconDisable."</a>";
1996
                    } else {
1997
                        $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$row['id']."\">".$editIcon."</a>";
1998
                    }
1999
2000
                    if ($row['visibility'] == 1) {
2001
                        $image_visibility = "visible";
2002
                        $alt_visibility = get_lang('Hide');
2003
                    } else {
2004
                        $image_visibility = "invisible";
2005
                        $alt_visibility = get_lang('Visible');
2006
                    }
2007
2008
                    $modify_icons .= "<a href=\"".$actionUrl."&action=showhide&id=".$row['id']."&sec_token=".$stok."\">".
2009
                        Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
2010
2011
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
2012
                    if ($iterator != 1) {
2013
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$row["id"]."&sec_token=".$stok."\">".
2014
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
2015
                    } else {
2016
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
2017
                    }
2018
                    if ($iterator < $bottomAnnouncement) {
2019
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$row["id"]."&sec_token=".$stok."\">".
2020
                            Display::return_icon('down.gif', get_lang('Down'))."</a>";
2021
                    } else {
2022
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
2023
                    }
2024
                    if (api_is_allowed_to_edit(false, true)) {
2025
                        if ($disableEdit === true) {
2026
                            $modify_icons .= Display::url($deleteIconDisable, '#');
2027
                        } else {
2028
                            $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$row['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
2029
                                    api_htmlentities(
2030
                                        get_lang('ConfirmYourChoice'),
2031
                                        ENT_QUOTES,
2032
                                        api_get_system_encoding()
2033
                                    )
2034
                                )."')) return false;\">".
2035
                                $deleteIcon."</a>";
2036
                        }
2037
                    }
2038
                    $iterator++;
2039
                } else {
2040
                    $modify_icons = Display::url(
2041
                        Display::return_icon('default.png'),
2042
                        $actionUrl.'&action=view&id='.$row['id']
2043
                    );
2044
                }
2045
2046
                $announcement = [
2047
                    'id' => $row['id'],
2048
                    'title' => $title,
2049
                    'username' => $username_span,
2050
                    'insert_date' => api_convert_and_format_date(
2051
                        $row['insert_date'],
2052
                        DATE_TIME_FORMAT_LONG
2053
                    ),
2054
                    'lastedit_date' => api_convert_and_format_date(
2055
                        $row['lastedit_date'],
2056
                        DATE_TIME_FORMAT_LONG
2057
                    ),
2058
                    'actions' => $modify_icons,
2059
                ];
2060
2061
                $results[] = $announcement;
2062
            }
2063
            $displayed[] = $row['id'];
2064
        }
2065
2066
        return $results;
2067
    }
2068
2069
    /**
2070
     * @return int
2071
     */
2072
    public static function getNumberAnnouncements()
2073
    {
2074
        // Maximum title messages to display
2075
        $maximum = '12';
2076
        // Database Table Definitions
2077
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
2078
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
2079
2080
        $session_id = api_get_session_id();
2081
        $courseInfo = api_get_course_info();
2082
        $courseId = $courseInfo['real_id'];
2083
        $userId = api_get_user_id();
2084
        $condition_session = api_get_session_condition(
2085
            $session_id,
2086
            true,
2087
            true,
2088
            'announcement.session_id'
2089
        );
2090
2091
        if (api_is_allowed_to_edit(false, true)) {
2092
            // check teacher status
2093
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2094
                if (api_get_group_id() == 0) {
2095
                    $group_condition = '';
2096
                } else {
2097
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
2098
                }
2099
2100
                $sql = "SELECT 
2101
                            announcement.*, 
2102
                            ip.visibility, 
2103
                            ip.to_group_id, 
2104
                            ip.insert_user_id
2105
                        FROM $tbl_announcement announcement 
2106
                        INNER JOIN $tbl_item_property ip
2107
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2108
                        WHERE
2109
                            announcement.c_id = $courseId AND
2110
                            ip.c_id = $courseId AND                    
2111
                            ip.tool = 'announcement' AND
2112
                            ip.visibility <> '2'
2113
                            $group_condition
2114
                            $condition_session
2115
                        GROUP BY ip.ref
2116
                        ORDER BY display_order DESC
2117
                        LIMIT 0, $maximum";
2118
            }
2119
        } else {
2120
            // students only get to see the visible announcements
2121
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
2122
                $group_memberships = GroupManager::get_group_ids(
2123
                    $courseInfo['real_id'],
2124
                    $userId
2125
                );
2126
2127
                if ((api_get_course_setting('allow_user_edit_announcement') &&
2128
                    !api_is_anonymous())
2129
                ) {
2130
                    if (api_get_group_id() == 0) {
2131
                        $cond_user_id = " AND (
2132
                        ip.lastedit_user_id = '".$userId."' OR (
2133
                            ip.to_user_id='".$userId."' OR
2134
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2135
                            ip.to_group_id IS NULL
2136
                            )
2137
                        )
2138
                        ";
2139
                    } else {
2140
                        $cond_user_id = " AND (
2141
                            ip.lastedit_user_id = '".$userId."'OR
2142
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2143
                            ip.to_group_id IS NULL
2144
                        )";
2145
                    }
2146
                } else {
2147
                    if (api_get_group_id() == 0) {
2148
                        $cond_user_id = " AND (
2149
                            ip.to_user_id='".$userId."' OR
2150
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
2151
                            ip.to_group_id IS NULL
2152
                        ) ";
2153
                    } else {
2154
                        $cond_user_id = " AND (
2155
                            ip.to_user_id='".$userId."' OR
2156
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
2157
                            ip.to_group_id IS NULL
2158
                        ) ";
2159
                    }
2160
                }
2161
2162
                // the user is member of several groups => display personal announcements AND
2163
                // his group announcements AND the general announcements
2164
                if (is_array($group_memberships) && count($group_memberships) > 0) {
2165
                    $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2166
                            FROM $tbl_announcement announcement 
2167
                            INNER JOIN $tbl_item_property ip
2168
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2169
                            WHERE
2170
                                announcement.c_id = $courseId AND
2171
                                ip.c_id = $courseId AND                                
2172
                                ip.tool='announcement' AND 
2173
                                ip.visibility='1'
2174
                                $cond_user_id
2175
                                $condition_session
2176
                            GROUP BY ip.ref
2177
                            ORDER BY display_order DESC
2178
                            LIMIT 0, $maximum";
2179
                } else {
2180
                    // the user is not member of any group
2181
                    // this is an identified user => show the general announcements AND his personal announcements
2182
                    if ($userId) {
2183
                        if ((api_get_course_setting('allow_user_edit_announcement') &&
2184
                            !api_is_anonymous())
2185
                        ) {
2186
                            $cond_user_id = " AND (
2187
                                ip.lastedit_user_id = '".$userId."' OR
2188
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2189
                            ) ";
2190
                        } else {
2191
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
2192
                        }
2193
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2194
                                FROM $tbl_announcement announcement 
2195
                                INNER JOIN $tbl_item_property ip
2196
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2197
                                WHERE
2198
                                    announcement.c_id = $courseId AND
2199
                                    ip.c_id = $courseId AND 
2200
                                    ip.tool='announcement' AND 
2201
                                    ip.visibility='1'
2202
                                    $cond_user_id
2203
                                    $condition_session
2204
                                GROUP BY ip.ref
2205
                                ORDER BY display_order DESC
2206
                                LIMIT 0, $maximum";
2207
                    } else {
2208
                        if (api_get_course_setting('allow_user_edit_announcement')) {
2209
                            $cond_user_id = " AND (
2210
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
2211
                            ) ";
2212
                        } else {
2213
                            $cond_user_id = " AND ip.to_group_id='0' ";
2214
                        }
2215
2216
                        // the user is not identiefied => show only the general announcements
2217
                        $sql = "SELECT 
2218
                                    announcement.*, 
2219
                                    ip.visibility, 
2220
                                    ip.to_group_id, 
2221
                                    ip.insert_user_id
2222
                                FROM $tbl_announcement announcement 
2223
                                INNER JOIN $tbl_item_property ip
2224
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2225
                                WHERE
2226
                                    announcement.c_id = $courseId AND
2227
                                    ip.c_id = $courseId AND 
2228
                                    ip.tool='announcement' AND 
2229
                                    ip.visibility='1' AND 
2230
                                    ip.to_group_id='0'
2231
                                    $condition_session
2232
                                GROUP BY ip.ref
2233
                                ORDER BY display_order DESC
2234
                                LIMIT 0, $maximum";
2235
                    }
2236
                }
2237
            }
2238
        }
2239
2240
        $result = Database::query($sql);
2241
2242
        return Database::num_rows($result);
2243
    }
2244
2245
    public static function createEvent(
2246
        int $announcementId,
2247
        string $startDate,
2248
        string $endDate,
2249
        array $choosenUsers = []
2250
    ): ?CCalendarEvent {
2251
        $em = Database::getManager();
2252
        $announcement = $em->find('ChamiloCourseBundle:CAnnouncement', $announcementId);
2253
        $agenda = new Agenda('course');
2254
2255
        $eventId = $agenda->addEvent(
2256
            $startDate,
2257
            $endDate,
2258
            '',
2259
            $announcement->getTitle(),
2260
            $announcement->getContent(),
2261
            $choosenUsers,
2262
            false,
2263
            null,
2264
            [],
2265
            [],
2266
            null,
2267
            ''
2268
        );
2269
2270
        if ($eventId) {
2271
            return $em->find('ChamiloCourseBundle:CCalendarEvent', $eventId);
2272
        }
2273
2274
        return null;
2275
    }
2276
}
2277