Completed
Push — master ( d29160...d3d657 )
by Julito
20:56
created

AnnouncementManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CAnnouncement;
5
use Chamilo\CourseBundle\Entity\CItemProperty;
6
7
/**
8
 * Include file with functions for the announcements module.
9
 *
10
 * @author jmontoya
11
 *
12
 * @package chamilo.announcements
13
 *
14
 * @todo use OOP
15
 */
16
class AnnouncementManager
17
{
18
    /**
19
     * Constructor.
20
     */
21
    public function __construct()
22
    {
23
    }
24
25
    /**
26
     * @return array
27
     */
28
    public static function getTags()
29
    {
30
        $tags = [
31
            '((user_name))',
32
            '((user_firstname))',
33
            '((user_lastname))',
34
            '((user_official_code))',
35
            '((course_title))',
36
            '((course_link))',
37
        ];
38
39
        $tags[] = '((teachers))';
40
41
        $extraField = new ExtraField('user');
42
        $extraFields = $extraField->get_all(['filter = ?' => 1]);
43
        if (!empty($extraFields)) {
44
            foreach ($extraFields as $extra) {
45
                $tags[] = "((extra_".$extra['variable']."))";
46
            }
47
        }
48
49
        if (!empty(api_get_session_id())) {
50
            $tags[] = '((coaches))';
51
            $tags[] = '((general_coach))';
52
            $tags[] = '((general_coach_email))';
53
        }
54
55
        return $tags;
56
    }
57
58
    /**
59
     * @param int    $userId
60
     * @param string $content
61
     * @param string $courseCode
62
     * @param int    $sessionId
63
     *
64
     * @return string
65
     */
66
    public static function parseContent(
67
        $userId,
68
        $content,
69
        $courseCode,
70
        $sessionId = 0
71
    ) {
72
        $readerInfo = api_get_user_info($userId, false, false, true, true);
73
        $courseInfo = api_get_course_info($courseCode);
74
        $teacherList = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code']);
75
76
        $generalCoachName = '';
77
        $generalCoachEmail = '';
78
        $coaches = '';
79
        if (!empty($sessionId)) {
80
            $sessionInfo = api_get_session_info($sessionId);
81
            $coaches = CourseManager::get_coachs_from_course_to_string(
82
                $sessionId,
83
                $courseInfo['real_id']
84
            );
85
86
            $generalCoach = api_get_user_info($sessionInfo['id_coach']);
87
            $generalCoachName = $generalCoach['complete_name'];
88
            $generalCoachEmail = $generalCoach['email'];
89
        }
90
91
        $data = [];
92
        $data['user_name'] = '';
93
        $data['user_firstname'] = '';
94
        $data['user_lastname'] = '';
95
        $data['user_official_code'] = '';
96
        if (!empty($readerInfo)) {
97
            $data['user_name'] = $readerInfo['username'];
98
            $data['user_firstname'] = $readerInfo['firstname'];
99
            $data['user_lastname'] = $readerInfo['lastname'];
100
            $data['user_official_code'] = $readerInfo['official_code'];
101
        }
102
103
        $data['course_title'] = $courseInfo['name'];
104
        $courseLink = api_get_course_url($courseCode, $sessionId);
105
        $data['course_link'] = Display::url($courseLink, $courseLink);
106
        $data['teachers'] = $teacherList;
107
108
        if (!empty($readerInfo)) {
109
            $extraField = new ExtraField('user');
110
            $extraFields = $extraField->get_all(['filter = ?' => 1]);
111
            if (!empty($extraFields)) {
112
                foreach ($extraFields as $extra) {
113
                    $data["extra_".$extra['variable']] = '';
114
                }
115
            }
116
117
            if (!empty($readerInfo['extra'])) {
118
                foreach ($readerInfo['extra'] as $extra) {
119
                    if (isset($extra['value'])) {
120
                        /** @var \Chamilo\CoreBundle\Entity\ExtraFieldValues $value */
121
                        $value = $extra['value'];
122
                        $data['extra_'.$value->getField()->getVariable()] = $value->getValue();
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on Chamilo\CoreBundle\Entity\ExtraFieldValues. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

122
                        /** @scrutinizer ignore-call */ 
123
                        $data['extra_'.$value->getField()->getVariable()] = $value->getValue();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
123
                    }
124
                }
125
            }
126
        }
127
128
        if (!empty(api_get_session_id())) {
129
            $data['coaches'] = $coaches;
130
            $data['general_coach'] = $generalCoachName;
131
            $data['general_coach_email'] = $generalCoachEmail;
132
        }
133
134
        $tags = self::getTags();
135
        foreach ($tags as $tag) {
136
            $simpleTag = str_replace(['((', '))'], '', $tag);
137
            $value = isset($data[$simpleTag]) ? $data[$simpleTag] : '';
138
            $content = str_replace($tag, $value, $content);
139
        }
140
141
        return $content;
142
    }
143
144
    /**
145
     * Gets all announcements from a course.
146
     *
147
     * @param array $course_info
148
     * @param int   $session_id
149
     *
150
     * @return array html with the content and count of announcements or false otherwise
151
     */
152
    public static function get_all_annoucement_by_course($course_info, $session_id = 0)
153
    {
154
        $session_id = intval($session_id);
155
        $courseId = $course_info['real_id'];
156
157
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
158
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
159
160
        $sql = "SELECT DISTINCT 
161
                    announcement.id, 
162
                    announcement.title, 
163
                    announcement.content
164
				FROM $tbl_announcement announcement 
165
				INNER JOIN $tbl_item_property i
166
				ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
167
				WHERE
168
                    i.tool='announcement' AND
169
                    announcement.session_id  = '$session_id' AND
170
                    announcement.c_id = $courseId AND
171
                    i.c_id = $courseId
172
				ORDER BY display_order DESC";
173
        $rs = Database::query($sql);
174
        $num_rows = Database::num_rows($rs);
175
        if ($num_rows > 0) {
176
            $list = [];
177
            while ($row = Database::fetch_array($rs)) {
178
                $list[] = $row;
179
            }
180
181
            return $list;
182
        }
183
184
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
185
    }
186
187
    /**
188
     * This functions switches the visibility a course resource
189
     * using the visibility field in 'item_property'.
190
     *
191
     * @param array $courseInfo
192
     * @param int   $id         ID of the element of the corresponding type
193
     *
194
     * @return bool False on failure, True on success
195
     */
196
    public static function change_visibility_announcement($courseInfo, $id)
197
    {
198
        $session_id = api_get_session_id();
199
        $item_visibility = api_get_item_visibility(
200
            $courseInfo,
201
            TOOL_ANNOUNCEMENT,
202
            $id,
203
            $session_id
204
        );
205
        if ($item_visibility == '1') {
206
            api_item_property_update(
207
                $courseInfo,
208
                TOOL_ANNOUNCEMENT,
209
                $id,
210
                'invisible',
211
                api_get_user_id()
212
            );
213
        } else {
214
            api_item_property_update(
215
                $courseInfo,
216
                TOOL_ANNOUNCEMENT,
217
                $id,
218
                'visible',
219
                api_get_user_id()
220
            );
221
        }
222
223
        return true;
224
    }
225
226
    /**
227
     * Deletes an announcement.
228
     *
229
     * @param array $courseInfo the course array
230
     * @param int   $id         the announcement id
231
     */
232
    public static function delete_announcement($courseInfo, $id)
233
    {
234
        api_item_property_update(
235
            $courseInfo,
236
            TOOL_ANNOUNCEMENT,
237
            $id,
238
            'delete',
239
            api_get_user_id()
240
        );
241
    }
242
243
    /**
244
     * Deletes all announcements by course.
245
     *
246
     * @param array $courseInfo the course array
247
     */
248
    public static function delete_all_announcements($courseInfo)
249
    {
250
        $announcements = self::get_all_annoucement_by_course(
251
            $courseInfo,
252
            api_get_session_id()
253
        );
254
        if (!empty($announcements)) {
255
            foreach ($announcements as $annon) {
256
                api_item_property_update(
257
                    $courseInfo,
258
                    TOOL_ANNOUNCEMENT,
259
                    $annon['id'],
260
                    'delete',
261
                    api_get_user_id()
262
                );
263
            }
264
        }
265
    }
266
267
    /**
268
     * @param string $title
269
     * @param int    $courseId
270
     * @param int    $sessionId
271
     * @param int    $visibility 1 or 0
272
     *
273
     * @return mixed
274
     */
275
    public static function getAnnouncementsByTitle(
276
        $title,
277
        $courseId,
278
        $sessionId = 0,
279
        $visibility = 1
280
    ) {
281
        $dql = "SELECT a
282
                FROM ChamiloCourseBundle:CAnnouncement a 
283
                JOIN ChamiloCourseBundle:CItemProperty ip
284
                WITH a.id = ip.ref AND a.cId = ip.course
285
                WHERE
286
                    ip.tool = 'announcement' AND                        
287
                    a.cId = :course AND
288
                    a.sessionId = :session AND
289
                    a.title like :title AND
290
                    ip.visibility = :visibility
291
                ORDER BY a.displayOrder DESC";
292
293
        $qb = Database::getManager()->createQuery($dql);
294
        $result = $qb->execute(
295
            [
296
                'course' => $courseId,
297
                'session' => $sessionId,
298
                'visibility' => $visibility,
299
                'title' => "%$title%",
300
            ]
301
        );
302
303
        return $result;
304
    }
305
306
    /**
307
     * @param int $announcementId
308
     * @param int $courseId
309
     * @param int $userId
310
     *
311
     * @return array
312
     */
313
    public static function getAnnouncementInfoById(
314
        $announcementId,
315
        $courseId,
316
        $userId
317
    ) {
318
        if (api_is_allowed_to_edit(false, true) ||
319
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
320
        ) {
321
            $dql = "SELECT a, ip
322
                    FROM ChamiloCourseBundle:CAnnouncement a 
323
                    JOIN ChamiloCourseBundle:CItemProperty ip
324
                    WITH a.id = ip.ref AND a.cId = ip.course
325
                    WHERE                        
326
                        a.id = :announcement AND
327
                        ip.tool = 'announcement' AND                        
328
                        a.cId = :course
329
                    ORDER BY a.displayOrder DESC";
330
        } else {
331
            $group_list = GroupManager::get_group_ids($courseId, api_get_user_id());
332
333
            if (empty($group_list)) {
334
                $group_list[] = 0;
335
            }
336
337
            if (api_get_user_id() != 0) {
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
                            (
346
                                ip.toUser = $userId OR
347
                                ip.group IN ('0', '".implode("', '", $group_list)."') OR
348
                                ip.group IS NULL
349
                            ) AND
350
                            ip.visibility = '1' AND                       
351
                            ip.course = :course
352
                        ORDER BY a.displayOrder DESC";
353
            } else {
354
                $dql = "SELECT a, ip
355
                        FROM ChamiloCourseBundle:CAnnouncement a 
356
                        JOIN ChamiloCourseBundle:CItemProperty ip
357
                        WITH a.id = ip.ref AND a.cId = ip.course 
358
                        WHERE                            
359
                            a.id = :announcement AND
360
                            ip.tool = 'announcement' AND
361
                            (ip.group = '0' OR ip.group IS NULL) AND
362
                            ip.visibility = '1' AND                            
363
                            ip.course = :course";
364
            }
365
        }
366
367
        $qb = Database::getManager()->createQuery($dql);
368
        $result = $qb->execute(
369
            [
370
                'announcement' => $announcementId,
371
                'course' => $courseId,
372
            ]
373
        );
374
375
        return [
376
            'announcement' => $result[0],
377
            'item_property' => $result[1],
378
        ];
379
    }
380
381
    /**
382
     * Displays one specific announcement.
383
     *
384
     * @param int $id, the id of the announcement you want to display
385
     *
386
     * @return string
387
     */
388
    public static function displayAnnouncement($id)
389
    {
390
        if ($id != strval(intval($id))) {
391
            return null;
392
        }
393
394
        global $charset;
395
396
        $html = '';
397
        $result = self::getAnnouncementInfoById(
398
            $id,
399
            api_get_course_int_id(),
400
            api_get_user_id()
401
        );
402
        /** @var CAnnouncement $announcement */
403
        $announcement = $result['announcement'];
404
        /** @var CItemProperty $itemProperty */
405
        $itemProperty = $result['item_property'];
406
407
        if (empty($announcement) || empty($itemProperty)) {
408
            return '';
409
        }
410
411
        $title = $announcement->getTitle();
412
        $content = $announcement->getContent();
413
414
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
415
        $html .= "<tr><td><h2>".$title."</h2></td></tr>";
416
417
        if (api_is_allowed_to_edit(false, true) ||
418
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
419
        ) {
420
            $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
421
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
422
423
            $image_visibility = 'invisible';
424
            $alt_visibility = get_lang('Visible');
425
            if ($itemProperty->getVisibility() === 1) {
426
                $image_visibility = 'visible';
427
                $alt_visibility = get_lang('Hide');
428
            }
429
            global $stok;
430
            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=showhide&id=".$id."&sec_token=".$stok."\">".
431
                Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
432
433
            if (api_is_allowed_to_edit(false, true)) {
434
                $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;\">".
435
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
436
                    "</a>";
437
            }
438
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
439
        }
440
441
        //$toUser = $itemProperty->getToUser();
442
        //$toUserId = !empty($toUser) ? $toUser->getId() : 0;
443
        // The user id is always the current one.
444
        $toUserId = api_get_user_id();
445
        $content = self::parseContent(
446
            $toUserId,
447
            $content,
448
            api_get_course_id(),
449
            api_get_session_id()
450
        );
451
452
        $html .= "<tr><td>$content</td></tr>";
453
        $html .= "<tr>";
454
        $html .= "<td class=\"announcements_datum\">".get_lang('LastUpdateDate')." : ";
455
        $lastEdit = $itemProperty->getLasteditDate();
456
        $html .= Display::dateToStringAgoAndLongDate($lastEdit);
457
        $html .= "</td></tr>";
458
459
        if (api_is_allowed_to_edit(false, true)) {
460
            $sent_to = self::sent_to('announcement', $id);
461
            $sent_to_form = self::sent_to_form($sent_to);
462
            $html .= Display::tag(
463
                'td',
464
                get_lang('SentTo').': '.$sent_to_form,
465
                ['class' => 'announcements_datum']
466
            );
467
        }
468
        $attachment_list = self::get_attachment($id);
469
470
        if (count($attachment_list) > 0) {
471
            $html .= "<tr><td>";
472
            $realname = $attachment_list['path'];
473
            $user_filename = $attachment_list['filename'];
474
            $full_file_name = 'download.php?'.api_get_cidreq().'&file='.$realname;
475
            $html .= '<br/>';
476
            $html .= Display::return_icon('attachment.gif', get_lang('Attachment'));
477
            $html .= '<a href="'.$full_file_name.' "> '.$user_filename.' </a>';
478
            $html .= ' - <span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
479
            if (api_is_allowed_to_edit(false, true)) {
480
                $url = api_get_self()."?".api_get_cidreq().
481
                    "&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $stok does not seem to be defined for all execution paths leading up to this point.
Loading history...
482
                $html .= Display::url(
483
                    Display::return_icon(
484
                        'delete.png',
485
                        get_lang('Delete'),
486
                        '',
487
                        16
488
                    ),
489
                    $url
490
                );
491
            }
492
            $html .= '</td></tr>';
493
        }
494
        $html .= "</table>";
495
496
        return $html;
497
    }
498
499
    /**
500
     * @param array $courseInfo
501
     *
502
     * @return int
503
     */
504
    public static function getLastAnnouncementOrder($courseInfo)
505
    {
506
        if (empty($courseInfo)) {
507
            return 0;
508
        }
509
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
510
511
        $courseId = $courseInfo['real_id'];
512
        $sql = "SELECT MAX(display_order)
513
                FROM $tbl_announcement
514
                WHERE c_id = $courseId ";
515
        $res_max = Database::query($sql);
516
517
        $order = 0;
518
        if (Database::num_rows($res_max)) {
519
            $row_max = Database::fetch_array($res_max);
520
            $order = intval($row_max[0]) + 1;
521
        }
522
523
        return $order;
524
    }
525
526
    /**
527
     * Store an announcement in the database (including its attached file if any).
528
     *
529
     * @param array  $courseInfo
530
     * @param int    $sessionId
531
     * @param string $title                Announcement title (pure text)
532
     * @param string $newContent           Content of the announcement (can be HTML)
533
     * @param array  $sentTo               Array of users and groups to send the announcement to
534
     * @param array  $file                 uploaded file $_FILES
535
     * @param string $file_comment         Comment describing the attachment
536
     * @param string $end_date
537
     * @param bool   $sendToUsersInSession
538
     * @param int    $authorId
539
     *
540
     * @return int false on failure, ID of the announcement on success
541
     */
542
    public static function add_announcement(
543
        $courseInfo,
544
        $sessionId,
545
        $title,
546
        $newContent,
547
        $sentTo,
548
        $file = [],
549
        $file_comment = null,
550
        $end_date = null,
551
        $sendToUsersInSession = false,
552
        $authorId = 0
553
    ) {
554
        if (empty($courseInfo)) {
555
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
556
        }
557
558
        $courseId = $courseInfo['real_id'];
559
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
560
561
        $authorId = empty($authorId) ? api_get_user_id() : $authorId;
562
563
        if (empty($end_date)) {
564
            $end_date = api_get_utc_datetime();
565
        }
566
567
        $order = self::getLastAnnouncementOrder($courseInfo);
568
569
        // store in the table announcement
570
        $params = [
571
            'c_id' => $courseId,
572
            'content' => $newContent,
573
            'title' => $title,
574
            'end_date' => $end_date,
575
            'display_order' => $order,
576
            'session_id' => (int) $sessionId,
577
        ];
578
579
        $last_id = Database::insert($tbl_announcement, $params);
580
581
        if (empty($last_id)) {
582
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
583
        } else {
584
            $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
585
            Database::query($sql);
586
587
            if (!empty($file)) {
588
                self::add_announcement_attachment_file(
589
                    $last_id,
590
                    $file_comment,
591
                    $_FILES['user_upload']
592
                );
593
            }
594
595
            // store in item_property (first the groups, then the users
596
            if (empty($sentTo) ||
597
                (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')
598
            ) {
599
                // The message is sent to EVERYONE, so we set the group to 0
600
                api_item_property_update(
601
                    $courseInfo,
602
                    TOOL_ANNOUNCEMENT,
603
                    $last_id,
604
                    'AnnouncementAdded',
605
                    $authorId,
606
                    '0',
607
                    null,
608
                    null,
609
                    null,
610
                    $sessionId
611
                );
612
            } else {
613
                $send_to = CourseManager::separateUsersGroups($sentTo);
614
                $batchSize = 20;
615
                $em = Database::getManager();
616
                // Storing the selected groups
617
                if (is_array($send_to['groups']) &&
618
                    !empty($send_to['groups'])
619
                ) {
620
                    $counter = 1;
621
                    foreach ($send_to['groups'] as $group) {
622
                        $groupInfo = GroupManager::get_group_properties($group);
623
                        api_item_property_update(
624
                            $courseInfo,
625
                            TOOL_ANNOUNCEMENT,
626
                            $last_id,
627
                            'AnnouncementAdded',
628
                            $authorId,
629
                            $groupInfo
630
                        );
631
632
                        if (($counter % $batchSize) === 0) {
633
                            $em->flush();
634
                            $em->clear();
635
                        }
636
                        $counter++;
637
                    }
638
                }
639
640
                // Storing the selected users
641
                if (is_array($send_to['users'])) {
642
                    $counter = 1;
643
                    foreach ($send_to['users'] as $user) {
644
                        api_item_property_update(
645
                            $courseInfo,
646
                            TOOL_ANNOUNCEMENT,
647
                            $last_id,
648
                            'AnnouncementAdded',
649
                            $authorId,
650
                            '',
651
                            $user
652
                        );
653
654
                        if (($counter % $batchSize) === 0) {
655
                            $em->flush();
656
                            $em->clear();
657
                        }
658
                        $counter++;
659
                    }
660
                }
661
            }
662
663
            if ($sendToUsersInSession) {
664
                self::addAnnouncementToAllUsersInSessions($last_id);
665
            }
666
667
            return $last_id;
668
        }
669
    }
670
671
    /**
672
     * @param $title
673
     * @param $newContent
674
     * @param $to
675
     * @param $to_users
676
     * @param array  $file
677
     * @param string $file_comment
678
     * @param bool   $sendToUsersInSession
679
     *
680
     * @return bool|int
681
     */
682
    public static function add_group_announcement(
683
        $title,
684
        $newContent,
685
        $to,
686
        $to_users,
687
        $file = [],
688
        $file_comment = '',
689
        $sendToUsersInSession = false
690
    ) {
691
        $courseInfo = api_get_course_info();
692
693
        // Database definitions
694
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
695
        $order = self::getLastAnnouncementOrder($courseInfo);
696
697
        $now = api_get_utc_datetime();
698
        $courseId = api_get_course_int_id();
699
700
        // store in the table announcement
701
        $params = [
702
            'c_id' => $courseId,
703
            'content' => $newContent,
704
            'title' => $title,
705
            'end_date' => $now,
706
            'display_order' => $order,
707
            'session_id' => api_get_session_id(),
708
        ];
709
710
        $last_id = Database::insert($table, $params);
711
712
        // Store the attach file
713
        if ($last_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $last_id of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
714
            $sql = "UPDATE $table SET id = iid 
715
                    WHERE iid = $last_id";
716
            Database::query($sql);
717
718
            if (!empty($file)) {
719
                self::add_announcement_attachment_file(
720
                    $last_id,
721
                    $file_comment,
722
                    $file
723
                );
724
            }
725
726
            // Store in item_property (first the groups, then the users)
727
            //if (!isset($to_users)) {
728
            if (isset($to_users[0]) && $to_users[0] === 'everyone') {
729
                // when no user is selected we send it to everyone
730
                $send_to = CourseManager::separateUsersGroups($to);
731
                // storing the selected groups
732
                if (is_array($send_to['groups'])) {
733
                    foreach ($send_to['groups'] as $group) {
734
                        $groupInfo = GroupManager::get_group_properties($group);
735
                        api_item_property_update(
736
                            $courseInfo,
737
                            TOOL_ANNOUNCEMENT,
738
                            $last_id,
739
                            'AnnouncementAdded',
740
                            api_get_user_id(),
741
                            $groupInfo
742
                        );
743
                    }
744
                }
745
            } else {
746
                $send_to_groups = CourseManager::separateUsersGroups($to);
747
                $send_to_users = CourseManager::separateUsersGroups($to_users);
748
                $to_groups = $send_to_groups['groups'];
749
                $to_users = $send_to_users['users'];
750
                // storing the selected users
751
                if (is_array($to_users) && is_array($to_groups)) {
752
                    foreach ($to_groups as $group) {
753
                        $groupInfo = GroupManager::get_group_properties($group);
754
                        foreach ($to_users as $user) {
755
                            api_item_property_update(
756
                                $courseInfo,
757
                                TOOL_ANNOUNCEMENT,
758
                                $last_id,
759
                                'AnnouncementAdded',
760
                                api_get_user_id(),
761
                                $groupInfo,
762
                                $user
763
                            );
764
                        }
765
                    }
766
                }
767
            }
768
769
            if ($sendToUsersInSession) {
770
                self::addAnnouncementToAllUsersInSessions($last_id);
771
            }
772
        }
773
774
        return $last_id;
775
    }
776
777
    /**
778
     * This function stores the announcement item in the announcement table
779
     * and updates the item_property table.
780
     *
781
     * @param int    $id                   id of the announcement
782
     * @param string $title
783
     * @param string $newContent
784
     * @param array  $to                   users that will receive the announcement
785
     * @param mixed  $file                 attachment
786
     * @param string $file_comment         file comment
787
     * @param bool   $sendToUsersInSession
788
     */
789
    public static function edit_announcement(
790
        $id,
791
        $title,
792
        $newContent,
793
        $to,
794
        $file = [],
795
        $file_comment = '',
796
        $sendToUsersInSession = false
797
    ) {
798
        $courseInfo = api_get_course_info();
799
        $courseId = api_get_course_int_id();
800
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
801
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
802
        $id = intval($id);
803
804
        $params = [
805
            'title' => $title,
806
            'content' => $newContent,
807
        ];
808
809
        Database::update(
810
            $tbl_announcement,
811
            $params,
812
            ['c_id = ? AND id = ?' => [$courseId, $id]]
813
        );
814
815
        // save attachment file
816
        $row_attach = self::get_attachment($id);
817
818
        $id_attach = 0;
819
        if ($row_attach) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $row_attach of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
820
            $id_attach = intval($row_attach['id']);
821
        }
822
823
        if (!empty($file)) {
824
            if (empty($id_attach)) {
825
                self::add_announcement_attachment_file(
826
                    $id,
827
                    $file_comment,
828
                    $file
829
                );
830
            } else {
831
                self::edit_announcement_attachment_file(
832
                    $id_attach,
833
                    $file,
834
                    $file_comment
835
                );
836
            }
837
        }
838
839
        // We remove everything from item_property for this
840
        $sql = "DELETE FROM $tbl_item_property
841
                WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
842
        Database::query($sql);
843
844
        if ($sendToUsersInSession) {
845
            self::addAnnouncementToAllUsersInSessions($id);
846
        }
847
848
        // store in item_property (first the groups, then the users
849
        if (!is_null($to)) {
850
            // !is_null($to): when no user is selected we send it to everyone
851
            $send_to = CourseManager::separateUsersGroups($to);
852
853
            // storing the selected groups
854
            if (is_array($send_to['groups'])) {
855
                foreach ($send_to['groups'] as $group) {
856
                    $groupInfo = GroupManager::get_group_properties($group);
857
                    if (empty($groupInfo)) {
858
                        // Probably the group id and iid are different try checking the iid
859
                        $groupInfo = GroupManager::get_group_properties($group, true);
860
                    }
861
                    if ($groupInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $groupInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
862
                        api_item_property_update(
863
                            $courseInfo,
864
                            TOOL_ANNOUNCEMENT,
865
                            $id,
866
                            'AnnouncementUpdated',
867
                            api_get_user_id(),
868
                            $groupInfo
869
                        );
870
                    }
871
                }
872
            }
873
874
            // storing the selected users
875
            if (is_array($send_to['users'])) {
876
                foreach ($send_to['users'] as $user) {
877
                    api_item_property_update(
878
                        $courseInfo,
879
                        TOOL_ANNOUNCEMENT,
880
                        $id,
881
                        'AnnouncementUpdated',
882
                        api_get_user_id(),
883
                        0,
884
                        $user
885
                    );
886
                }
887
            }
888
889
            // Send to everyone
890
            if (isset($to[0]) && $to[0] === 'everyone') {
891
                api_item_property_update(
892
                    $courseInfo,
893
                    TOOL_ANNOUNCEMENT,
894
                    $id,
895
                    'AnnouncementUpdated',
896
                    api_get_user_id(),
897
                    0
898
                );
899
            }
900
        } else {
901
            // the message is sent to everyone, so we set the group to 0
902
            api_item_property_update(
903
                $courseInfo,
904
                TOOL_ANNOUNCEMENT,
905
                $id,
906
                'AnnouncementUpdated',
907
                api_get_user_id(),
908
                0
909
            );
910
        }
911
    }
912
913
    /**
914
     * @param int $announcementId
915
     */
916
    public static function addAnnouncementToAllUsersInSessions($announcementId)
917
    {
918
        $courseCode = api_get_course_id();
919
        $courseInfo = api_get_course_info();
920
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
921
922
        if (!empty($sessionList)) {
923
            foreach ($sessionList as $sessionInfo) {
924
                $sessionId = $sessionInfo['id'];
925
                $userList = CourseManager::get_user_list_from_course_code(
926
                    $courseCode,
927
                    $sessionId
928
                );
929
930
                if (!empty($userList)) {
931
                    foreach ($userList as $user) {
932
                        api_item_property_update(
933
                            $courseInfo,
934
                            TOOL_ANNOUNCEMENT,
935
                            $announcementId,
936
                            "AnnouncementUpdated",
937
                            api_get_user_id(),
938
                            0,
939
                            $user['user_id'],
940
                            0,
941
                            0,
942
                            $sessionId
943
                        );
944
                    }
945
                }
946
            }
947
        }
948
    }
949
950
    /**
951
     * @param int $insert_id
952
     *
953
     * @return bool
954
     */
955
    public static function update_mail_sent($insert_id)
956
    {
957
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
958
        if ($insert_id != strval(intval($insert_id))) {
959
            return false;
960
        }
961
        $insert_id = intval($insert_id);
962
        $courseId = api_get_course_int_id();
963
        // store the modifications in the table tbl_annoucement
964
        $sql = "UPDATE $tbl_announcement SET email_sent='1'
965
                WHERE c_id = $courseId AND id = $insert_id";
966
        Database::query($sql);
967
    }
968
969
    /**
970
     * Gets all announcements from a user by course.
971
     *
972
     * @param string course db
973
     * @param int user id
974
     *
975
     * @return array html with the content and count of announcements or false otherwise
976
     */
977
    public static function get_all_annoucement_by_user_course($course_code, $user_id)
978
    {
979
        $course_info = api_get_course_info($course_code);
980
        $courseId = $course_info['real_id'];
981
982
        if (empty($user_id)) {
983
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
984
        }
985
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
986
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
987
        if (!empty($user_id) && is_numeric($user_id)) {
988
            $user_id = (int) $user_id;
989
            $sql = "SELECT DISTINCT 
990
                        announcement.title, 
991
                        announcement.content, 
992
                        display_order
993
					FROM $tbl_announcement announcement 
994
					INNER JOIN $tbl_item_property ip
995
					ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
996
					WHERE
997
						announcement.c_id = $courseId AND
998
						ip.c_id = $courseId AND						
999
						ip.tool='announcement' AND
1000
						(
1001
						  ip.insert_user_id='$user_id' AND
1002
						  (ip.to_group_id='0' OR ip.to_group_id IS NULL)
1003
						)
1004
						AND ip.visibility='1'
1005
						AND announcement.session_id  = 0
1006
					ORDER BY display_order DESC";
1007
            $rs = Database::query($sql);
1008
            $num_rows = Database::num_rows($rs);
1009
            $content = '';
1010
            $i = 0;
1011
            $result = [];
1012
            if ($num_rows > 0) {
1013
                while ($myrow = Database::fetch_array($rs)) {
1014
                    $content .= '<strong>'.$myrow['title'].'</strong><br /><br />';
1015
                    $content .= $myrow['content'];
1016
                    $i++;
1017
                }
1018
                $result['content'] = $content;
1019
                $result['count'] = $i;
1020
1021
                return $result;
1022
            }
1023
1024
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
1025
        }
1026
1027
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
1028
    }
1029
1030
    /**
1031
     * Returns announcement info from its id.
1032
     *
1033
     * @param int $courseId
1034
     * @param int $id
1035
     *
1036
     * @return array
1037
     */
1038
    public static function get_by_id($courseId, $id)
1039
    {
1040
        $id = intval($id);
1041
        $courseId = $courseId ? intval($courseId) : api_get_course_int_id();
1042
1043
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1044
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1045
1046
        $sql = "SELECT DISTINCT 
1047
                    announcement.id, 
1048
                    announcement.title, 
1049
                    announcement.content,
1050
                    ip.to_group_id
1051
               FROM $tbl_announcement announcement
1052
               INNER JOIN $tbl_item_property ip
1053
               ON
1054
                    announcement.id = ip.ref AND
1055
                    announcement.c_id = ip.c_id
1056
               WHERE
1057
                    announcement.c_id = $courseId AND
1058
                    ip.tool='announcement' AND
1059
                    announcement.id = $id
1060
                ";
1061
        $result = Database::query($sql);
1062
        if (Database::num_rows($result)) {
1063
            return Database::fetch_array($result);
1064
        }
1065
1066
        return [];
1067
    }
1068
1069
    /**
1070
     * this function gets all the groups of the course,
1071
     * not including linked courses.
1072
     */
1073
    public static function get_course_groups()
1074
    {
1075
        $session_id = api_get_session_id();
1076
        if ($session_id != 0) {
1077
            $new_group_list = CourseManager::get_group_list_of_course(
1078
                api_get_course_id(),
1079
                $session_id,
1080
                1
1081
            );
1082
        } else {
1083
            $new_group_list = CourseManager::get_group_list_of_course(
1084
                api_get_course_id(),
1085
                0,
1086
                1
1087
            );
1088
        }
1089
1090
        return $new_group_list;
1091
    }
1092
1093
    /**
1094
     * This tools loads all the users and all the groups who have received
1095
     * a specific item (in this case an announcement item).
1096
     *
1097
     * @param string $tool
1098
     * @param int    $id
1099
     *
1100
     * @return array
1101
     */
1102
    public static function load_edit_users($tool, $id)
1103
    {
1104
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1105
        $tool = Database::escape_string($tool);
1106
        $id = (int) $id;
1107
        $courseId = api_get_course_int_id();
1108
1109
        $sql = "SELECT to_user_id, to_group_id FROM $table
1110
                WHERE c_id = $courseId AND tool='$tool' AND ref = $id";
1111
        $result = Database::query($sql);
1112
        $to = [];
1113
        while ($row = Database::fetch_array($result)) {
1114
            // This is the iid of c_group_info
1115
            $toGroup = $row['to_group_id'];
1116
            switch ($toGroup) {
1117
                // it was send to one specific user
1118
                case null:
1119
                    $to[] = "USER:".$row['to_user_id'];
1120
                    break;
1121
                // it was sent to everyone
1122
                case 0:
1123
                    return 'everyone';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'everyone' returns the type string which is incompatible with the documented return type array.
Loading history...
1124
                    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...
1125
                default:
1126
                    $to[] = "GROUP:".$toGroup;
1127
            }
1128
        }
1129
1130
        return $to;
1131
    }
1132
1133
    /**
1134
     * constructs the form to display all the groups and users the message has been sent to.
1135
     *
1136
     * @param array $sent_to_array
1137
     *                             input:
1138
     *                             $sent_to_array is a 2 dimensional array containing the groups and the users
1139
     *                             the first level is a distinction between groups and users:
1140
     *                             $sent_to_array['groups'] * and $sent_to_array['users']
1141
     *                             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1142
     *                             containing all the id's of the groups (resp. users) who have received this message.
1143
     *
1144
     * @return string
1145
     *
1146
     * @author Patrick Cool <patrick.cool@>
1147
     */
1148
    public static function sent_to_form($sent_to_array)
1149
    {
1150
        // we find all the names of the groups
1151
        $group_names = self::get_course_groups();
1152
1153
        // we count the number of users and the number of groups
1154
        if (isset($sent_to_array['users'])) {
1155
            $number_users = count($sent_to_array['users']);
1156
        } else {
1157
            $number_users = 0;
1158
        }
1159
        if (isset($sent_to_array['groups'])) {
1160
            $number_groups = count($sent_to_array['groups']);
1161
        } else {
1162
            $number_groups = 0;
1163
        }
1164
        $total_numbers = $number_users + $number_groups;
1165
1166
        // starting the form if there is more than one user/group
1167
        $output = [];
1168
        if ($total_numbers > 1) {
1169
            // outputting the name of the groups
1170
            if (is_array($sent_to_array['groups'])) {
1171
                foreach ($sent_to_array['groups'] as $group_id) {
1172
                    $output[] = $group_names[$group_id]['name'];
1173
                }
1174
            }
1175
1176
            if (isset($sent_to_array['users'])) {
1177
                if (is_array($sent_to_array['users'])) {
1178
                    foreach ($sent_to_array['users'] as $user_id) {
1179
                        $user_info = api_get_user_info($user_id);
1180
                        $output[] = $user_info['complete_name_with_username'];
1181
                    }
1182
                }
1183
            }
1184
        } else {
1185
            // there is only one user/group
1186
            if (isset($sent_to_array['users']) and is_array($sent_to_array['users'])) {
1187
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1188
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1189
            }
1190
            if (isset($sent_to_array['groups']) and
1191
                is_array($sent_to_array['groups']) and
1192
                isset($sent_to_array['groups'][0]) and
1193
                $sent_to_array['groups'][0] !== 0
1194
            ) {
1195
                $group_id = $sent_to_array['groups'][0];
1196
                $output[] = "&nbsp;".$group_names[$group_id]['name'];
1197
            }
1198
            if (empty($sent_to_array['groups']) and empty($sent_to_array['users'])) {
1199
                $output[] = "&nbsp;".get_lang('Everybody');
1200
            }
1201
        }
1202
1203
        if (!empty($output)) {
1204
            $output = array_filter($output);
1205
            if (count($output) > 0) {
1206
                $output = implode(', ', $output);
1207
            }
1208
1209
            return $output;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $output also could return the type array which is incompatible with the documented return type string.
Loading history...
1210
        }
1211
    }
1212
1213
    /**
1214
     * Returns all the users and all the groups a specific announcement item
1215
     * has been sent to.
1216
     *
1217
     * @param    string  The tool (announcement, agenda, ...)
1218
     * @param    int     ID of the element of the corresponding type
1219
     *
1220
     * @return array Array of users and groups to whom the element has been sent
1221
     */
1222
    public static function sent_to($tool, $id)
1223
    {
1224
        $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1225
        $tool = Database::escape_string($tool);
1226
        $id = (int) $id;
1227
1228
        $sent_to_group = [];
1229
        $sent_to = [];
1230
        $courseId = api_get_course_int_id();
1231
1232
        $sql = "SELECT to_group_id, to_user_id
1233
                FROM $table
1234
                WHERE c_id = $courseId AND tool = '$tool' AND ref=".$id;
1235
        $result = Database::query($sql);
1236
1237
        while ($row = Database::fetch_array($result)) {
1238
            // if to_user_id <> 0 then it is sent to a specific user
1239
            if ($row['to_user_id'] != 0) {
1240
                $sent_to_user[] = $row['to_user_id'];
1241
                continue;
1242
            }
1243
1244
            // if to_group_id is null then it is sent to a specific user
1245
            // if to_group_id = 0 then it is sent to everybody
1246
            if ($row['to_group_id'] != 0) {
1247
                $sent_to_group[] = $row['to_group_id'];
1248
            }
1249
        }
1250
1251
        if (isset($sent_to_group)) {
1252
            $sent_to['groups'] = $sent_to_group;
1253
        }
1254
1255
        if (isset($sent_to_user)) {
1256
            $sent_to['users'] = $sent_to_user;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sent_to_user does not seem to be defined for all execution paths leading up to this point.
Loading history...
1257
        }
1258
1259
        return $sent_to;
1260
    }
1261
1262
    /**
1263
     * Show a list with all the attachments according to the post's id.
1264
     *
1265
     * @param int $announcementId
1266
     *
1267
     * @return array with the post info
1268
     *
1269
     * @author Arthur Portugal
1270
     *
1271
     * @version November 2009, dokeos 1.8.6.2
1272
     */
1273
    public static function get_attachment($announcementId)
1274
    {
1275
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1276
        $announcementId = intval($announcementId);
1277
        $courseId = api_get_course_int_id();
1278
        $row = [];
1279
        $sql = 'SELECT id, path, filename, comment 
1280
                FROM '.$table.'
1281
				WHERE c_id = '.$courseId.' AND announcement_id = '.$announcementId;
1282
        $result = Database::query($sql);
1283
        if (Database::num_rows($result) != 0) {
1284
            $row = Database::fetch_array($result, 'ASSOC');
1285
        }
1286
1287
        return $row;
1288
    }
1289
1290
    /**
1291
     * This function add a attachment file into announcement.
1292
     *
1293
     * @param int  announcement id
1294
     * @param string file comment
1295
     * @param array  uploaded file $_FILES
1296
     *
1297
     * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
1298
     */
1299
    public static function add_announcement_attachment_file(
1300
        $announcement_id,
1301
        $file_comment,
1302
        $file
1303
    ) {
1304
        $courseInfo = api_get_course_info();
1305
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1306
        $return = 0;
1307
        $announcement_id = intval($announcement_id);
1308
        $courseId = api_get_course_int_id();
1309
1310
        if (is_array($file) && $file['error'] == 0) {
1311
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1312
            $courseDir = $courseInfo['path'].'/upload/announcements';
1313
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1314
            $updir = $sys_course_path.$courseDir;
1315
1316
            // Try to add an extension to the file if it hasn't one
1317
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1318
            // user's file name
1319
            $file_name = $file['name'];
1320
1321
            if (!filter_extension($new_file_name)) {
1322
                $return = -1;
1323
                echo Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error');
1324
            } else {
1325
                $new_file_name = uniqid('');
1326
                $new_path = $updir.'/'.$new_file_name;
1327
1328
                // This file is copy here but its cleaned in api_mail_html in api.lib.php
1329
                copy($file['tmp_name'], $new_path);
1330
1331
                $params = [
1332
                    'c_id' => $courseId,
1333
                    'filename' => $file_name,
1334
                    'comment' => $file_comment,
1335
                    'path' => $new_file_name,
1336
                    'announcement_id' => $announcement_id,
1337
                    'size' => intval($file['size']),
1338
                ];
1339
1340
                $insertId = Database::insert($table, $params);
1341
                if ($insertId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $insertId of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1342
                    $sql = "UPDATE $table SET id = iid 
1343
                            WHERE iid = $insertId";
1344
                    Database::query($sql);
1345
                }
1346
1347
                $return = 1;
1348
            }
1349
        }
1350
1351
        return $return;
1352
    }
1353
1354
    /**
1355
     * This function edit a attachment file into announcement.
1356
     *
1357
     * @param int attach id
1358
     * @param array uploaded file $_FILES
1359
     * @param string file comment
1360
     *
1361
     * @return int
1362
     */
1363
    public static function edit_announcement_attachment_file(
1364
        $id_attach,
1365
        $file,
1366
        $file_comment
1367
    ) {
1368
        $courseInfo = api_get_course_info();
1369
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1370
        $return = 0;
1371
        $courseId = api_get_course_int_id();
1372
1373
        if (is_array($file) && $file['error'] == 0) {
1374
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1375
            $courseDir = $courseInfo['path'].'/upload/announcements';
1376
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1377
            $updir = $sys_course_path.$courseDir;
1378
1379
            // Try to add an extension to the file if it hasn't one
1380
            $new_file_name = add_ext_on_mime(
1381
                stripslashes($file['name']),
1382
                $file['type']
1383
            );
1384
            // user's file name
1385
            $file_name = $file['name'];
1386
1387
            if (!filter_extension($new_file_name)) {
1388
                $return = -1;
1389
                echo Display::return_message(
1390
                    get_lang('UplUnableToSaveFileFilteredExtension'),
1391
                    'error'
1392
                );
1393
            } else {
1394
                $new_file_name = uniqid('');
1395
                $new_path = $updir.'/'.$new_file_name;
1396
                copy($file['tmp_name'], $new_path);
1397
                $safe_file_comment = Database::escape_string($file_comment);
1398
                $safe_file_name = Database::escape_string($file_name);
1399
                $safe_new_file_name = Database::escape_string($new_file_name);
1400
                $id_attach = intval($id_attach);
1401
                $sql = "UPDATE $table SET 
1402
                            filename = '$safe_file_name', 
1403
                            comment = '$safe_file_comment', 
1404
                            path = '$safe_new_file_name', 
1405
                            size ='".intval($file['size'])."'
1406
					 	WHERE c_id = $courseId AND id = '$id_attach'";
1407
                $result = Database::query($sql);
1408
                if ($result === false) {
1409
                    $return = -1;
1410
                    echo Display::return_message(
1411
                        get_lang('UplUnableToSaveFile'),
1412
                        'error'
1413
                    );
1414
                } else {
1415
                    $return = 1;
1416
                }
1417
            }
1418
        }
1419
1420
        return $return;
1421
    }
1422
1423
    /**
1424
     * This function delete a attachment file by id.
1425
     *
1426
     * @param int $id attachment file Id
1427
     *
1428
     * @return bool
1429
     */
1430
    public static function delete_announcement_attachment_file($id)
1431
    {
1432
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1433
        $id = intval($id);
1434
        $courseId = api_get_course_int_id();
1435
        if (empty($courseId) || empty($id)) {
1436
            return false;
1437
        }
1438
        $sql = "DELETE FROM $table
1439
                WHERE c_id = $courseId AND id = $id";
1440
        Database::query($sql);
1441
1442
        return true;
1443
    }
1444
1445
    /**
1446
     * @param array $courseInfo
1447
     * @param int   $sessionId
1448
     * @param int   $id
1449
     * @param bool  $sendToUsersInSession
1450
     * @param bool  $sendToDrhUsers
1451
     * @param Monolog\Handler\HandlerInterface logger
1452
     * @param int $senderId
1453
     */
1454
    public static function sendEmail(
1455
        $courseInfo,
1456
        $sessionId,
1457
        $id,
1458
        $sendToUsersInSession = false,
1459
        $sendToDrhUsers = false,
1460
        $logger = null,
1461
        $senderId = 0
1462
    ) {
1463
        $email = new AnnouncementEmail($courseInfo, $sessionId, $id, $logger);
1464
        $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId);
1465
    }
1466
1467
    /**
1468
     * @param $stok
1469
     * @param $announcement_number
1470
     * @param bool   $getCount
1471
     * @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...
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...
1472
     * @param null   $limit
1473
     * @param string $sidx
1474
     * @param string $sord
1475
     * @param string $titleToSearch
1476
     * @param int    $userIdToSearch
1477
     * @param int    $userId
1478
     * @param int    $courseId
1479
     * @param int    $sessionId
1480
     *
1481
     * @return array
1482
     */
1483
    public static function getAnnouncements(
1484
        $stok,
1485
        $announcement_number,
1486
        $getCount = false,
1487
        $start = null,
1488
        $limit = null,
1489
        $sidx = '',
0 ignored issues
show
Unused Code introduced by
The parameter $sidx is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1489
        /** @scrutinizer ignore-unused */ $sidx = '',

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1490
        $sord = '',
0 ignored issues
show
Unused Code introduced by
The parameter $sord is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1490
        /** @scrutinizer ignore-unused */ $sord = '',

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1491
        $titleToSearch = '',
1492
        $userIdToSearch = 0,
1493
        $userId = 0,
1494
        $courseId = 0,
1495
        $sessionId = 0
1496
    ) {
1497
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1498
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1499
1500
        $user_id = $userId ?: api_get_user_id();
1501
        $group_id = api_get_group_id();
1502
        $session_id = $sessionId ?: api_get_session_id();
1503
        if (empty($courseId)) {
1504
            $courseInfo = api_get_course_info();
1505
            $courseId = $courseInfo['real_id'];
1506
        } else {
1507
            $courseId = (int) $courseId;
1508
            $courseInfo = api_get_course_info($courseId);
1509
        }
1510
1511
        if (empty($courseInfo)) {
1512
            return [];
1513
        }
1514
1515
        $condition_session = api_get_session_condition(
1516
            $session_id,
1517
            true,
1518
            true,
1519
            'announcement.session_id'
1520
        );
1521
1522
        $group_memberships = GroupManager::get_group_ids(
1523
            $courseId,
1524
            api_get_user_id()
1525
        );
1526
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1527
1528
        $select = ' DISTINCT 
1529
                        announcement.*, 
1530
                        ip.visibility, 
1531
                        ip.to_group_id, 
1532
                        ip.insert_user_id, 
1533
                        ip.insert_date, 
1534
                        ip.lastedit_date';
1535
        $groupBy = ' GROUP BY announcement.iid';
1536
        if ($getCount) {
1537
            $groupBy = '';
1538
            $select = ' COUNT(DISTINCT announcement.iid) count';
1539
        }
1540
1541
        $searchCondition = '';
1542
        if (!empty($titleToSearch)) {
1543
            $titleToSearch = Database::escape_string($titleToSearch);
1544
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1545
        }
1546
1547
        if (!empty($userIdToSearch)) {
1548
            $userIdToSearch = intval($userIdToSearch);
1549
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1550
        }
1551
1552
        $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
1553
        $extraGroupCondition = '';
1554
        if ($allowOnlyGroup) {
1555
            $extraGroupCondition = " AND ip.to_group_id = $group_id ";
1556
        }
1557
1558
        if (api_is_allowed_to_edit(false, true) ||
1559
            ($allowUserEditSetting && !api_is_anonymous())
1560
        ) {
1561
            // A.1. you are a course admin with a USER filter
1562
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1563
1564
            //if (!empty($user_id)) {
1565
            if (0) {
1566
                if (is_array($group_memberships) &&
1567
                    count($group_memberships) > 0
1568
                ) {
1569
                    $sql = "SELECT $select
1570
                            FROM $tbl_announcement announcement 
1571
                            INNER JOIN $tbl_item_property ip
1572
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1573
                            WHERE
1574
                                announcement.c_id = $courseId AND
1575
                                ip.c_id = $courseId AND                                
1576
                                ip.tool = 'announcement' AND
1577
                                (
1578
                                    ip.to_user_id = $user_id OR
1579
                                    ip.to_group_id IS NULL OR
1580
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1581
                                ) AND
1582
                                ip.visibility IN ('1', '0')
1583
                                $condition_session
1584
                                $searchCondition
1585
                            ORDER BY display_order DESC";
1586
                } else {
1587
                    $sql = "SELECT $select
1588
                            FROM $tbl_announcement announcement 
1589
                            INNER JOIN $tbl_item_property ip
1590
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1591
                            WHERE
1592
                                announcement.c_id = $courseId AND
1593
                                ip.c_id = $courseId AND
1594
                                ip.tool ='announcement' AND
1595
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1596
                                ip.visibility IN ('1', '0')
1597
                            $condition_session
1598
                            $searchCondition
1599
                            ORDER BY display_order DESC";
1600
                }
1601
            } elseif ($group_id != 0) {
1602
                // A.2. you are a course admin with a GROUP filter
1603
                // => see only the messages of this specific group
1604
                $sql = "SELECT $select
1605
                        FROM $tbl_announcement announcement 
1606
                        INNER JOIN $tbl_item_property ip
1607
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1608
                        WHERE
1609
                            ip.tool='announcement' AND
1610
                            announcement.c_id = $courseId AND
1611
                            ip.c_id = $courseId AND
1612
                            ip.visibility<>'2' AND
1613
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1614
                            $condition_session
1615
                            $searchCondition
1616
                            $extraGroupCondition
1617
                        $groupBy
1618
                        ORDER BY display_order DESC";
1619
            } else {
1620
                // A.3 you are a course admin without any group or user filter
1621
                // A.3.a you are a course admin without user or group filter but WITH studentview
1622
                // => see all the messages of all the users and groups without editing possibilities
1623
                if (isset($isStudentView) && $isStudentView == 'true') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $isStudentView seems to never exist and therefore isset should always be false.
Loading history...
1624
                    $sql = "SELECT $select
1625
                            FROM $tbl_announcement announcement 
1626
                            INNER JOIN $tbl_item_property ip
1627
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1628
                            WHERE
1629
                                ip.tool='announcement' AND
1630
                                announcement.c_id = $courseId AND
1631
                                ip.c_id = $courseId AND                                
1632
                                ip.visibility='1'
1633
                                $condition_session
1634
                                $searchCondition
1635
                            $groupBy
1636
                            ORDER BY display_order DESC";
1637
                } else {
1638
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1639
                    // => see all the messages of all the users and groups with editing possibilities
1640
                    $sql = "SELECT $select
1641
                            FROM $tbl_announcement announcement 
1642
                            INNER JOIN $tbl_item_property ip
1643
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1644
                            WHERE
1645
                                ip.tool = 'announcement' AND
1646
                                announcement.c_id = $courseId AND
1647
                                ip.c_id = $courseId  AND
1648
                                (ip.visibility='0' OR ip.visibility='1')
1649
                                $condition_session
1650
                                $searchCondition
1651
                            $groupBy
1652
                            ORDER BY display_order DESC";
1653
                }
1654
            }
1655
        } else {
1656
            // STUDENT
1657
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1658
                if ($allowUserEditSetting && !api_is_anonymous()) {
1659
                    if ($group_id == 0) {
1660
                        // No group
1661
                        $cond_user_id = " AND (
1662
                            ip.lastedit_user_id = '".$user_id."' OR (
1663
                                (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
1664
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1665
                            )
1666
                        ) ";
1667
                    } else {
1668
                        $cond_user_id = " AND (
1669
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1670
                        )";
1671
                        $cond_user_id .= $extraGroupCondition;
1672
                    }
1673
                } else {
1674
                    if ($group_id == 0) {
1675
                        $cond_user_id = " AND (
1676
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1677
                        ) ";
1678
                    } else {
1679
                        $cond_user_id = " AND (
1680
                            (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1681
                        )";
1682
                        $cond_user_id .= $extraGroupCondition;
1683
                    }
1684
                }
1685
1686
                $sql = "SELECT $select
1687
                        FROM $tbl_announcement announcement INNER JOIN
1688
                        $tbl_item_property ip
1689
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1690
                        WHERE
1691
                            announcement.c_id = $courseId AND
1692
                            ip.c_id = $courseId AND                            
1693
                            ip.tool='announcement' 
1694
                            $cond_user_id
1695
                            $condition_session
1696
                            $searchCondition
1697
                            AND ip.visibility='1'
1698
                        $groupBy
1699
                        ORDER BY display_order DESC";
1700
            } else {
1701
                if ($user_id) {
1702
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1703
                        $cond_user_id = " AND (
1704
                            ip.lastedit_user_id = '".api_get_user_id()."' OR
1705
                            ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND (ip.to_group_id='0' OR ip.to_group_id IS NULL))
1706
                        ) ";
1707
                    } else {
1708
                        $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1709
                    }
1710
1711
                    $sql = "SELECT $select
1712
						FROM $tbl_announcement announcement 
1713
						INNER JOIN $tbl_item_property ip
1714
						ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1715
						WHERE
1716
    						announcement.c_id = $courseId AND
1717
							ip.c_id = $courseId AND    						
1718
    						ip.tool='announcement'
1719
    						$cond_user_id
1720
    						$condition_session
1721
    						$searchCondition
1722
    						AND ip.visibility='1'
1723
    						AND announcement.session_id IN(0, ".$session_id.")
1724
                        $groupBy
1725
						ORDER BY display_order DESC";
1726
                } else {
1727
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1728
                        $cond_user_id = " AND (
1729
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1730
                        )";
1731
                    } else {
1732
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1733
                    }
1734
1735
                    $sql = "SELECT $select
1736
                            FROM $tbl_announcement announcement 
1737
                            INNER JOIN $tbl_item_property ip
1738
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1739
                            WHERE
1740
                                announcement.c_id = $courseId AND
1741
                                ip.c_id = $courseId AND                            
1742
                                ip.tool='announcement'
1743
                                $cond_user_id
1744
                                $condition_session
1745
                                $searchCondition  AND
1746
                                ip.visibility='1' AND
1747
                                announcement.session_id IN ( 0,".api_get_session_id().")
1748
                            $groupBy
1749
                            ";
1750
                }
1751
            }
1752
        }
1753
1754
        if (!is_null($start) && !is_null($limit)) {
1755
            $start = intval($start);
1756
            $limit = intval($limit);
1757
            $sql .= " LIMIT $start, $limit";
1758
        }
1759
1760
        $result = Database::query($sql);
1761
        if ($getCount) {
1762
            $result = Database::fetch_array($result, 'ASSOC');
1763
1764
            return $result['count'];
1765
        }
1766
1767
        $iterator = 1;
1768
        $bottomAnnouncement = $announcement_number;
1769
        $displayed = [];
1770
        $results = [];
1771
        $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.api_get_cidreq();
1772
        $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('AnnounceSentByEmail').'"></i>';
1773
        $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
1774
1775
        $editIcon = Display::return_icon(
1776
            'edit.png',
1777
            get_lang('Edit'),
1778
            '',
1779
            ICON_SIZE_SMALL
1780
        );
1781
1782
        $deleteIcon = Display::return_icon(
1783
            'delete.png',
1784
            get_lang('Delete'),
1785
            '',
1786
            ICON_SIZE_SMALL
1787
        );
1788
1789
        $isTutor = false;
1790
        if (!empty($group_id)) {
1791
            $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1792
            //User has access in the group?
1793
            $isTutor = GroupManager::is_tutor_of_group(
1794
                api_get_user_id(),
1795
                $groupInfo
1796
            );
1797
        }
1798
1799
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1800
            if (!in_array($row['id'], $displayed)) {
1801
                $sent_to_icon = '';
1802
                // the email icon
1803
                if ($row['email_sent'] == '1') {
1804
                    $sent_to_icon = ' '.$emailIcon;
1805
                }
1806
                $groupReference = ($row['to_group_id'] > 0) ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
1807
                $title = $row['title'].$groupReference.$sent_to_icon;
1808
                $item_visibility = api_get_item_visibility(
1809
                    $courseInfo,
1810
                    TOOL_ANNOUNCEMENT,
1811
                    $row['id'],
1812
                    $session_id
1813
                );
1814
                $row['visibility'] = $item_visibility;
1815
1816
                // show attachment list
1817
                $attachment_list = self::get_attachment($row['id']);
1818
1819
                $attachment_icon = '';
1820
                if (count($attachment_list) > 0) {
1821
                    $attachment_icon = ' '.$attachmentIcon;
1822
                }
1823
1824
                /* TITLE */
1825
                $user_info = api_get_user_info($row['insert_user_id']);
1826
                $username = sprintf(get_lang("LoginX"), $user_info['username']);
1827
1828
                $username_span = Display::tag(
1829
                    'span',
1830
                    $user_info['complete_name'],
1831
                    ['title' => $username]
1832
                );
1833
1834
                $title = Display::url(
1835
                    $title.$attachment_icon,
1836
                    $actionUrl.'&action=view&id='.$row['id']
1837
                );
1838
1839
                // we can edit if : we are the teacher OR the element belongs to
1840
                // the session we are coaching OR the option to allow users to edit is on
1841
                if (api_is_allowed_to_edit(false, true) ||
1842
                    (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $row['id'])) ||
1843
                    (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
1844
                    ($row['to_group_id'] == $group_id && $isTutor)
1845
                ) {
1846
                    $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$row['id']."\">".$editIcon."</a>";
1847
                    if ($row['visibility'] == 1) {
1848
                        $image_visibility = "visible";
1849
                        $alt_visibility = get_lang('Hide');
1850
                    } else {
1851
                        $image_visibility = "invisible";
1852
                        $alt_visibility = get_lang('Visible');
1853
                    }
1854
                    $modify_icons .= "<a href=\"".$actionUrl."&action=showhide&id=".$row['id']."&sec_token=".$stok."\">".
1855
                        Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
1856
1857
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
1858
                    if ($iterator != 1) {
1859
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$row["id"]."&sec_token=".$stok."\">".
1860
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
1861
                    } else {
1862
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
1863
                    }
1864
                    if ($iterator < $bottomAnnouncement) {
1865
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$row["id"]."&sec_token=".$stok."\">".
1866
                            Display::return_icon('down.gif', get_lang('Down'))."</a>";
1867
                    } else {
1868
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
1869
                    }
1870
                    if (api_is_allowed_to_edit(false, true)) {
1871
                        $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$row['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, api_get_system_encoding()))."')) return false;\">".
1872
                            $deleteIcon."</a>";
1873
                    }
1874
                    $iterator++;
1875
                } else {
1876
                    $modify_icons = Display::url(
1877
                        Display::return_icon('default.png'),
1878
                        $actionUrl.'&action=view&id='.$row['id']
1879
                    );
1880
                }
1881
1882
                $announcement = [
1883
                    'id' => $row['id'],
1884
                    'title' => $title,
1885
                    'username' => $username_span,
1886
                    'insert_date' => api_convert_and_format_date(
1887
                        $row['insert_date'],
1888
                        DATE_TIME_FORMAT_LONG
1889
                    ),
1890
                    'lastedit_date' => api_convert_and_format_date(
1891
                        $row['lastedit_date'],
1892
                        DATE_TIME_FORMAT_LONG
1893
                    ),
1894
                    'actions' => $modify_icons,
1895
                ];
1896
1897
                $results[] = $announcement;
1898
            }
1899
            $displayed[] = $row['id'];
1900
        }
1901
1902
        return $results;
1903
    }
1904
1905
    /**
1906
     * @return int
1907
     */
1908
    public static function getNumberAnnouncements()
1909
    {
1910
        // Maximum title messages to display
1911
        $maximum = '12';
1912
        // Database Table Definitions
1913
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1914
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1915
1916
        $session_id = api_get_session_id();
1917
        $courseInfo = api_get_course_info();
1918
        $courseId = $courseInfo['real_id'];
1919
        $userId = api_get_user_id();
1920
        $condition_session = api_get_session_condition(
1921
            $session_id,
1922
            true,
1923
            true,
1924
            'announcement.session_id'
1925
        );
1926
1927
        if (api_is_allowed_to_edit(false, true)) {
1928
            // check teacher status
1929
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
1930
                if (api_get_group_id() == 0) {
1931
                    $group_condition = '';
1932
                } else {
1933
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
1934
                }
1935
1936
                $sql = "SELECT 
1937
                            announcement.*, 
1938
                            ip.visibility, 
1939
                            ip.to_group_id, 
1940
                            ip.insert_user_id
1941
                        FROM $tbl_announcement announcement 
1942
                        INNER JOIN $tbl_item_property ip
1943
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
1944
                        WHERE
1945
                            announcement.c_id = $courseId AND
1946
                            ip.c_id = $courseId AND                    
1947
                            ip.tool = 'announcement' AND
1948
                            ip.visibility <> '2'
1949
                            $group_condition
1950
                            $condition_session
1951
                        GROUP BY ip.ref
1952
                        ORDER BY display_order DESC
1953
                        LIMIT 0, $maximum";
1954
            }
1955
        } else {
1956
            // students only get to see the visible announcements
1957
            if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
1958
                $group_memberships = GroupManager::get_group_ids(
1959
                    $courseInfo['real_id'],
1960
                    $userId
1961
                );
1962
1963
                if ((api_get_course_setting('allow_user_edit_announcement') &&
1964
                    !api_is_anonymous())
1965
                ) {
1966
                    if (api_get_group_id() == 0) {
1967
                        $cond_user_id = " AND (
1968
                        ip.lastedit_user_id = '".$userId."' OR (
1969
                            ip.to_user_id='".$userId."' OR
1970
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
1971
                            ip.to_group_id IS NULL
1972
                            )
1973
                        )
1974
                        ";
1975
                    } else {
1976
                        $cond_user_id = " AND (
1977
                            ip.lastedit_user_id = '".$userId."'OR
1978
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
1979
                            ip.to_group_id IS NULL
1980
                        )";
1981
                    }
1982
                } else {
1983
                    if (api_get_group_id() == 0) {
1984
                        $cond_user_id = " AND (
1985
                            ip.to_user_id='".$userId."' OR
1986
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
1987
                            ip.to_group_id IS NULL
1988
                        ) ";
1989
                    } else {
1990
                        $cond_user_id = " AND (
1991
                            ip.to_user_id='".$userId."' OR
1992
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
1993
                            ip.to_group_id IS NULL
1994
                        ) ";
1995
                    }
1996
                }
1997
1998
                // the user is member of several groups => display personal announcements AND
1999
                // his group announcements AND the general announcements
2000
                if (is_array($group_memberships) && count($group_memberships) > 0) {
2001
                    $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2002
                            FROM $tbl_announcement announcement 
2003
                            INNER JOIN $tbl_item_property ip
2004
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2005
                            WHERE
2006
                                announcement.c_id = $courseId AND
2007
                                ip.c_id = $courseId AND                                
2008
                                ip.tool='announcement' AND 
2009
                                ip.visibility='1'
2010
                                $cond_user_id
2011
                                $condition_session
2012
                            GROUP BY ip.ref
2013
                            ORDER BY display_order DESC
2014
                            LIMIT 0, $maximum";
2015
                } else {
2016
                    // the user is not member of any group
2017
                    // this is an identified user => show the general announcements AND his personal announcements
2018
                    if ($userId) {
2019
                        if ((api_get_course_setting('allow_user_edit_announcement') &&
2020
                            !api_is_anonymous())
2021
                        ) {
2022
                            $cond_user_id = " AND (
2023
                                ip.lastedit_user_id = '".$userId."' OR
2024
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
2025
                            ) ";
2026
                        } else {
2027
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
2028
                        }
2029
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
2030
                                FROM $tbl_announcement announcement 
2031
                                INNER JOIN $tbl_item_property ip
2032
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
2033
                                WHERE
2034
                                    announcement.c_id = $courseId AND
2035
                                    ip.c_id = $courseId AND 
2036
                                    ip.tool='announcement' AND 
2037
                                    ip.visibility='1'
2038
                                    $cond_user_id
2039
                                    $condition_session
2040
                                GROUP BY ip.ref
2041
                                ORDER BY display_order DESC
2042
                                LIMIT 0, $maximum";
2043
                    } else {
2044
                        if (api_get_course_setting('allow_user_edit_announcement')) {
2045
                            $cond_user_id = " AND (
2046
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
2047
                            ) ";
2048
                        } else {
2049
                            $cond_user_id = " AND ip.to_group_id='0' ";
2050
                        }
2051
2052
                        // the user is not identiefied => show only the general announcements
2053
                        $sql = "SELECT 
2054
                                    announcement.*, 
2055
                                    ip.visibility, 
2056
                                    ip.to_group_id, 
2057
                                    ip.insert_user_id
2058
                                FROM $tbl_announcement announcement 
2059
                                INNER JOIN $tbl_item_property ip
2060
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
2061
                                WHERE
2062
                                    announcement.c_id = $courseId AND
2063
                                    ip.c_id = $courseId AND 
2064
                                    ip.tool='announcement' AND 
2065
                                    ip.visibility='1' AND 
2066
                                    ip.to_group_id='0'
2067
                                    $condition_session
2068
                                GROUP BY ip.ref
2069
                                ORDER BY display_order DESC
2070
                                LIMIT 0, $maximum";
2071
                    }
2072
                }
2073
            }
2074
        }
2075
2076
        $result = Database::query($sql);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sql does not seem to be defined for all execution paths leading up to this point.
Loading history...
2077
2078
        return Database::num_rows($result);
2079
    }
2080
}
2081