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