Completed
Push — master ( 395485...bbad3a )
by Julito
43:12
created

AnnouncementManager   F

Complexity

Total Complexity 205

Size/Duplication

Total Lines 1828
Duplicated Lines 15.86 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
dl 290
loc 1828
rs 3.9999
c 0
b 0
f 0
wmc 205
lcom 1
cbo 11

30 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get_tags() 13 13 1
B parse_content() 0 31 4
B get_all_annoucement_by_course() 30 34 3
B change_visibility_announcement() 0 29 2
A delete_announcement() 0 10 1
A delete_all_announcements() 0 15 3
B getAnnouncementsByTitle() 0 26 1
B getAnnouncementInfoById() 0 64 6
A get_last_announcement_order() 21 21 3
D add_announcement() 39 123 18
C add_group_announcement() 0 89 11
D edit_announcement() 0 97 10
B addAnnouncementToAllUsersInSessions() 0 33 5
A update_mail_sent() 0 13 2
B get_all_annoucement_by_user_course() 0 52 6
B get_by_id() 28 28 3
A get_course_users() 22 22 2
A get_course_groups() 18 18 2
B load_edit_users() 0 28 4
C sent_to_form() 0 63 19
B sent_to() 0 40 6
A get_attachment() 14 15 2
B add_announcement_attachment_file() 0 50 5
B edit_announcement_attachment_file() 0 46 5
A delete_announcement_attachment_file() 0 13 3
A sendEmail() 0 10 1
F getAnnouncements() 29 337 44
D getNumberAnnouncements() 64 167 17
D display_announcement() 12 108 15

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AnnouncementManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AnnouncementManager, and based on these observations, apply Extract Interface, too.

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
 * @author jmontoya
10
 * @package chamilo.announcements
11
 * @todo use OOP
12
 */
13
class AnnouncementManager
14
{
15
    /**
16
     * Constructor
17
     */
18
    public function __construct()
19
    {
20
    }
21
22
    /**
23
     * @return array
24
     */
25 View Code Duplication
    public static function get_tags()
26
    {
27
        return array(
28
            '((user_name))',
29
            '((user_firstname))',
30
            '((user_lastname))',
31
            '((teacher_name))',
32
            '((teacher_email))',
33
            '((course_title))',
34
            '((course_link))',
35
            '((official_code))'
36
        );
37
    }
38
39
    /**
40
     * @param int       $userId
41
     * @param string    $content
42
     * @param string    $course_code
43
     * @param int       $session_id
44
     *
45
     * @return mixed
46
     */
47
    public static function parse_content($userId, $content, $course_code, $session_id = 0)
48
    {
49
        $readerInfo = api_get_user_info($userId);
50
        $courseInfo = api_get_course_info($course_code);
51
        $teacherList = CourseManager::get_teacher_list_from_course_code($courseInfo['code']);
52
53
        $teacher_email = '';
54
        $teacher_name = '';
55
        if (!empty($teacherList)) {
56
            foreach ($teacherList as $teacher_data) {
57
                $teacher_name = api_get_person_name($teacher_data['firstname'], $teacher_data['lastname']);
58
                $teacher_email = $teacher_data['email'];
59
                break;
60
            }
61
        }
62
63
        $courseLink = api_get_course_url($course_code, $session_id);
64
        if (!empty($readerInfo)) {
65
            $data['user_name'] = $readerInfo['username'];
66
            $data['user_firstname'] = $readerInfo['firstname'];
67
            $data['user_lastname'] = $readerInfo['lastname'];
68
            $data['official_code'] = $readerInfo['official_code'];
69
        }
70
        $data['teacher_name'] = $teacher_name;
71
        $data['teacher_email'] = $teacher_email;
72
        $data['course_title'] = $courseInfo['name'];
73
        $data['course_link'] = Display::url($courseLink, $courseLink);
74
        $content = str_replace(self::get_tags(), $data, $content);
75
76
        return $content;
77
    }
78
79
    /**
80
     * Gets all announcements from a course
81
     * @param	array $course_info
82
     * @param	int $session_id
83
     * @return	array html with the content and count of announcements or false otherwise
84
     */
85 View Code Duplication
    public static function get_all_annoucement_by_course($course_info, $session_id = 0)
86
    {
87
        $session_id = intval($session_id);
88
        $course_id = $course_info['real_id'];
89
90
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
91
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
92
93
        $sql = "SELECT DISTINCT 
94
                    announcement.id, 
95
                    announcement.title, 
96
                    announcement.content
97
				FROM $tbl_announcement announcement 
98
				INNER JOIN $tbl_item_property i
99
				ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
100
				WHERE
101
                    i.tool='announcement' AND
102
                    announcement.session_id  = '$session_id' AND
103
                    announcement.c_id = $course_id AND
104
                    i.c_id = $course_id
105
				ORDER BY display_order DESC";
106
        $rs = Database::query($sql);
107
        $num_rows = Database::num_rows($rs);
108
        if ($num_rows > 0) {
109
            $list = array();
110
            while ($row = Database::fetch_array($rs)) {
111
                $list[] = $row;
112
            }
113
114
            return $list;
115
        }
116
117
        return false;
118
    }
119
120
    /**
121
     * This functions switches the visibility a course resource
122
     * using the visibility field in 'item_property'
123
     * @param    array	$_course
124
     * @param    int     $id ID of the element of the corresponding type
125
     * @return   bool    False on failure, True on success
126
     */
127
    public static function change_visibility_announcement($_course, $id)
128
    {
129
        $session_id = api_get_session_id();
130
        $item_visibility = api_get_item_visibility(
131
            $_course,
132
            TOOL_ANNOUNCEMENT,
133
            $id,
134
            $session_id
135
        );
136
        if ($item_visibility == '1') {
137
            api_item_property_update(
138
                $_course,
139
                TOOL_ANNOUNCEMENT,
140
                $id,
141
                'invisible',
142
                api_get_user_id()
143
            );
144
        } else {
145
            api_item_property_update(
146
                $_course,
147
                TOOL_ANNOUNCEMENT,
148
                $id,
149
                'visible',
150
                api_get_user_id()
151
            );
152
        }
153
154
        return true;
155
    }
156
157
    /**
158
     * Deletes an announcement
159
     * @param array $_course the course array
160
     * @param int $id the announcement id
161
     */
162
    public static function delete_announcement($_course, $id)
163
    {
164
        api_item_property_update(
165
            $_course,
166
            TOOL_ANNOUNCEMENT,
167
            $id,
168
            'delete',
169
            api_get_user_id()
170
        );
171
    }
172
173
    /**
174
     * Deletes all announcements by course
175
     * @param array $_course the course array
176
     */
177
    public static function delete_all_announcements($_course)
178
    {
179
        $announcements = self::get_all_annoucement_by_course($_course, api_get_session_id());
180
        if (!empty($announcements)) {
181
            foreach ($announcements as $annon) {
182
                api_item_property_update(
183
                    $_course,
184
                    TOOL_ANNOUNCEMENT,
185
                    $annon['id'],
186
                    'delete',
187
                    api_get_user_id()
188
                );
189
            }
190
        }
191
    }
192
193
    /**
194
     * @param string $title
195
     * @param int $courseId
196
     * @param int $sessionId
197
     * @param int $visibility 1 or 0
198
     *
199
     * @return mixed
200
     */
201
    public static function getAnnouncementsByTitle($title, $courseId, $sessionId = 0, $visibility = 1)
202
    {
203
        $dql = "SELECT a
204
                FROM ChamiloCourseBundle:CAnnouncement a 
205
                JOIN ChamiloCourseBundle:CItemProperty ip
206
                WITH a.id = ip.ref AND a.cId = ip.course
207
                WHERE
208
                    ip.tool = 'announcement' AND                        
209
                    a.cId = :course AND
210
                    a.sessionId = :session AND
211
                    a.title like :title AND
212
                    ip.visibility = :visibility
213
                ORDER BY a.displayOrder DESC";
214
215
        $qb = Database::getManager()->createQuery($dql);
216
        $result = $qb->execute(
217
            [
218
                'course' => $courseId,
219
                'session' => $sessionId,
220
                'visibility' => $visibility,
221
                'title' => "%$title%",
222
            ]
223
        );
224
225
        return $result;
226
    }
227
228
    /**
229
     * @param int $announcementId
230
     * @param int $courseId
231
     * @param int $userId
232
     *
233
     * @return array
234
     */
235
    public static function getAnnouncementInfoById($announcementId, $courseId, $userId)
236
    {
237
        if (api_is_allowed_to_edit(false, true) ||
238
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
239
        ) {
240
            $dql = "SELECT a, ip
241
                    FROM ChamiloCourseBundle:CAnnouncement a 
242
                    JOIN ChamiloCourseBundle:CItemProperty ip
243
                    WITH a.id = ip.ref AND a.cId = ip.course
244
                    WHERE                        
245
                        a.id = :announcement AND
246
                        ip.tool = 'announcement' AND                        
247
                        a.cId = :course
248
                    ORDER BY a.displayOrder DESC";
249
        } else {
250
            $group_list = GroupManager::get_group_ids($courseId, api_get_user_id());
251
252
            if (empty($group_list)) {
253
                $group_list[] = 0;
254
            }
255
256
            if (api_get_user_id() != 0) {
257
                $dql = "SELECT a, ip
258
                        FROM ChamiloCourseBundle:CAnnouncement a 
259
                        JOIN ChamiloCourseBundle:CItemProperty ip
260
                        WITH a.id = ip.ref AND a.cId = ip.course
261
                        WHERE                      
262
                            a.id = :announcement AND
263
                            ip.tool='announcement' AND
264
                            (
265
                                ip.toUser = $userId OR
266
                                ip.group IN ('0', '" . implode("', '", $group_list) . "') OR
267
                                ip.group IS NULL
268
                            ) AND
269
                            ip.visibility = '1' AND                       
270
                            ip.course = :course
271
                        ORDER BY a.displayOrder DESC";
272
            } else {
273
                $dql = "SELECT a, ip
274
                        FROM ChamiloCourseBundle:CAnnouncement a 
275
                        JOIN ChamiloCourseBundle:CItemProperty ip
276
                        WITH a.id = ip.ref AND a.cId = ip.course 
277
                        WHERE                            
278
                            a.id = :announcement AND
279
                            ip.tool = 'announcement' AND
280
                            (ip.group = '0' OR ip.group IS NULL) AND
281
                            ip.visibility = '1' AND                            
282
                            ip.course = :course";
283
            }
284
        }
285
286
        $qb = Database::getManager()->createQuery($dql);
287
        $result = $qb->execute(
288
            [
289
                'announcement' => $announcementId,
290
                'course' => $courseId,
291
            ]
292
        );
293
294
        return [
295
            'announcement' => $result[0],
296
            'item_property' => $result[1]
297
        ];
298
    }
299
300
    /**
301
     * Displays one specific announcement
302
     * @param int $announcement_id, the id of the announcement you want to display
0 ignored issues
show
Documentation introduced by
There is no parameter named $announcement_id,. Did you maybe mean $announcement_id?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
303
     */
304
    public static function display_announcement($announcement_id)
305
    {
306
        if ($announcement_id != strval(intval($announcement_id))) {
307
            return null;
308
        }
309
310
        global $charset;
311
312
        $html = '';
313
        $result = self::getAnnouncementInfoById(
314
            $announcement_id,
315
            api_get_course_int_id(),
316
            api_get_user_id()
317
        );
318
        /** @var CAnnouncement $announcement */
319
        $announcement = $result['announcement'];
320
        /** @var CItemProperty $itemProperty */
321
        $itemProperty = $result['item_property'];
322
323
        if (empty($announcement) || empty($itemProperty)) {
324
            return '';
325
        }
326
327
        $title = $announcement->getTitle();
328
        $content = $announcement->getContent();
329
330
        $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
331
        $html .= "<tr><td><h2>" . $title . "</h2></td></tr>";
332
333
        if (api_is_allowed_to_edit(false, true) ||
334
            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
335
        ) {
336
            $modify_icons = "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=modify&id=" . $announcement_id . "\">" .
337
                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . "</a>";
338 View Code Duplication
            if ($itemProperty->getVisibility() === 1) {
339
                $image_visibility = "visible";
340
                $alt_visibility = get_lang('Hide');
341
            } else {
342
                $image_visibility = "invisible";
343
                $alt_visibility = get_lang('Visible');
344
            }
345
            global $stok;
346
347
            $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=showhide&id=" . $announcement_id . "&sec_token=" . $stok . "\">" .
348
                Display::return_icon($image_visibility . '.png', $alt_visibility, '', ICON_SIZE_SMALL) . "</a>";
349
350 View Code Duplication
            if (api_is_allowed_to_edit(false, true)) {
351
                $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=delete&id=" . $announcement_id . "&sec_token=" . $stok . "\" onclick=\"javascript:if(!confirm('" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)) . "')) return false;\">" .
352
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) .
353
                    "</a>";
354
            }
355
            $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
356
        }
357
358
        $toUser = $itemProperty->getToUser();
359
        $toUserId = !empty($toUser) ? $toUser->getId() : 0;
360
361
        $content = self::parse_content(
362
            $toUserId,
363
            $content,
364
            api_get_course_id(),
365
            api_get_session_id()
366
        );
367
368
        $lastEdit = $itemProperty->getLasteditDate();
369
370
        $html .= "<tr><td>$content</td></tr>";
371
        $html .= "<tr><td class=\"announcements_datum\">" . get_lang('LastUpdateDate') . " : " .
372
            Display::dateToStringAgoAndLongDate(
373
                !empty($lastEdit) ? $lastEdit->format('Y-m-d h:i:s') : ''
374
            ) . "</td></tr>";
375
376
        if ($itemProperty->getGroup() !== null) {
377
            $sent_to_icon = Display::return_icon('group.gif', get_lang('AnnounceSentToUserSelection'));
378
        }
379
380
        if (api_is_allowed_to_edit(false, true)) {
381
            $sent_to = self::sent_to('announcement', $announcement_id);
382
            $sent_to_form = self::sent_to_form($sent_to);
383
            $html .= Display::tag(
384
                'td',
385
                get_lang('SentTo').': ' . $sent_to_form,
386
                array('class' => 'announcements_datum')
387
            );
388
        }
389
        $attachment_list = self::get_attachment($announcement_id);
390
391
        if (count($attachment_list) > 0) {
392
            $html .= "<tr><td>";
393
            $realname = $attachment_list['path'];
394
            $user_filename = $attachment_list['filename'];
395
            $full_file_name = 'download.php?'.api_get_cidreq().'&file=' . $realname;
396
            $html .= '<br/>';
397
            $html .= Display::return_icon('attachment.gif', get_lang('Attachment'));
398
            $html .= '<a href="' . $full_file_name . ' "> ' . $user_filename . ' </a>';
399
            $html .= ' - <span class="forum_attach_comment" >' . $attachment_list['comment'] . '</span>';
400
            if (api_is_allowed_to_edit(false, true)) {
401
                $html .= Display::url(
402
                    Display::return_icon('delete.png', get_lang('Delete'), '', 16),
403
                    api_get_self() . "?" . api_get_cidreq() . "&action=delete_attachment&id_attach=" . $attachment_list['id'] . "&sec_token=" . $stok
404
                );
405
            }
406
            $html .= '</td></tr>';
407
        }
408
        $html .= "</table>";
409
410
        return $html;
411
    }
412
413
    /**
414
     * @param array $courseInfo
415
     *
416
     * @return int
417
     */
418 View Code Duplication
    public static function get_last_announcement_order($courseInfo)
419
    {
420
        if (empty($courseInfo)) {
421
            return 0;
422
        }
423
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
424
425
        $course_id = $courseInfo['real_id'];
426
        $sql = "SELECT MAX(display_order)
427
                FROM $tbl_announcement
428
                WHERE c_id = $course_id ";
429
        $res_max = Database::query($sql);
430
431
        $order = 0;
432
        if (Database::num_rows($res_max)) {
433
            $row_max = Database::fetch_array($res_max);
434
            $order = intval($row_max[0])+1;
435
        }
436
437
        return $order;
438
    }
439
440
    /**
441
     * Store an announcement in the database (including its attached file if any)
442
     * @param array $courseInfo
443
     * @param int $sessionId
444
     * @param string $title   Announcement title (pure text)
445
     * @param string $newContent   Content of the announcement (can be HTML)
446
     * @param array  $sentTo      Array of users and groups to send the announcement to
447
     * @param array   $file     uploaded file $_FILES
448
     * @param string  $file_comment  Comment describing the attachment
449
     * @param string $end_date
450
     * @param bool $sendToUsersInSession
451
     * @param int $authorId
452
     *
453
     * @return int      false on failure, ID of the announcement on success
454
     */
455
    public static function add_announcement(
456
        $courseInfo,
457
        $sessionId,
458
        $title,
459
        $newContent,
460
        $sentTo,
461
        $file = array(),
462
        $file_comment = null,
463
        $end_date = null,
464
        $sendToUsersInSession = false,
465
        $authorId = 0
466
    ) {
467
        if (empty($courseInfo)) {
468
            return false;
469
        }
470
471
        $course_id = $courseInfo['real_id'];
472
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
473
474
        $authorId = empty($authorId) ? api_get_user_id() : $authorId;
475
476
        if (empty($end_date)) {
477
            $end_date = api_get_utc_datetime();
478
        }
479
480
        $order = self::get_last_announcement_order($courseInfo);
481
482
        // store in the table announcement
483
        $params = array(
484
            'c_id' => $course_id,
485
            'content' => $newContent,
486
            'title' => $title,
487
            'end_date' => $end_date,
488
            'display_order' => $order,
489
            'session_id' => (int) $sessionId
490
        );
491
492
        $last_id = Database::insert($tbl_announcement, $params);
493
494
        if (empty($last_id)) {
495
            return false;
496
        } else {
497
            $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
498
            Database::query($sql);
499
500
            if (!empty($file)) {
501
                self::add_announcement_attachment_file(
502
                    $last_id,
503
                    $file_comment,
504
                    $_FILES['user_upload']
505
                );
506
            }
507
508
            // store in item_property (first the groups, then the users
509
            if (empty($sentTo) || (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')) {
510
                // The message is sent to EVERYONE, so we set the group to 0
511
                api_item_property_update(
512
                    $courseInfo,
513
                    TOOL_ANNOUNCEMENT,
514
                    $last_id,
515
                    'AnnouncementAdded',
516
                    $authorId,
517
                    '0',
518
                    null,
519
                    null,
520
                    null,
521
                    $sessionId
522
                );
523
            } else {
524
                $send_to = CourseManager::separateUsersGroups($sentTo);
525
                $batchSize = 20;
526
                $em = Database::getManager();
527
                // Storing the selected groups
528 View Code Duplication
                if (is_array($send_to['groups']) && !empty($send_to['groups'])) {
529
                    $counter = 1;
530
                    foreach ($send_to['groups'] as $group) {
531
                        api_item_property_update(
532
                            $courseInfo,
533
                            TOOL_ANNOUNCEMENT,
534
                            $last_id,
535
                            'AnnouncementAdded',
536
                            $authorId,
537
                            $group
538
                        );
539
540
                        if (($counter % $batchSize) === 0) {
541
                             $em->flush();
542
                             $em->clear();
543
                        }
544
                        $counter++;
545
                    }
546
                }
547
548
                // Storing the selected users
549 View Code Duplication
                if (is_array($send_to['users'])) {
550
                    $counter = 1;
551
                    foreach ($send_to['users'] as $user) {
552
                        api_item_property_update(
553
                            $courseInfo,
554
                            TOOL_ANNOUNCEMENT,
555
                            $last_id,
556
                            'AnnouncementAdded',
557
                            $authorId,
558
                            '',
559
                            $user
560
                        );
561
562
                        if (($counter % $batchSize) === 0) {
563
                             $em->flush();
564
                             $em->clear();
565
                        }
566
                        $counter++;
567
                    }
568
                }
569
            }
570
571
            if ($sendToUsersInSession) {
572
                self::addAnnouncementToAllUsersInSessions($last_id);
573
            }
574
575
            return $last_id;
576
        }
577
    }
578
579
    /**
580
     * @param $title
581
     * @param $newContent
582
     * @param $to
583
     * @param $to_users
584
     * @param array $file
585
     * @param string $file_comment
586
     * @param bool $sendToUsersInSession
587
     *
588
     * @return bool|int
589
     */
590
    public static function add_group_announcement(
591
        $title,
592
        $newContent,
593
        $to,
594
        $to_users,
595
        $file = array(),
596
        $file_comment = '',
597
        $sendToUsersInSession = false
598
    ) {
599
        $_course = api_get_course_info();
600
601
        // Database definitions
602
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
603
        $order = self::get_last_announcement_order($_course);
604
605
        $now = api_get_utc_datetime();
606
        $course_id = api_get_course_int_id();
607
608
        // store in the table announcement
609
        $params = [
610
            'c_id' => $course_id,
611
            'content' => $newContent,
612
            'title' => $title,
613
            'end_date' => $now,
614
            'display_order' => $order,
615
            'session_id' => api_get_session_id()
616
        ];
617
618
        $last_id = Database::insert($tbl_announcement, $params);
619
620
        // Store the attach file
621
        if ($last_id) {
622
            $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
623
            Database::query($sql);
624
625
            if (!empty($file)) {
626
                self::add_announcement_attachment_file(
627
                    $last_id,
628
                    $file_comment,
629
                    $file
630
                );
631
            }
632
633
            // Store in item_property (first the groups, then the users
634
            if (!isset($to_users)) {
635
                // when no user is selected we send it to everyone
636
                $send_to = CourseManager::separateUsersGroups($to);
637
                // storing the selected groups
638
                if (is_array($send_to['groups'])) {
639
                    foreach ($send_to['groups'] as $group) {
640
                        api_item_property_update(
641
                            $_course,
642
                            TOOL_ANNOUNCEMENT,
643
                            $last_id,
644
                            "AnnouncementAdded",
645
                            api_get_user_id(),
646
                            $group
647
                        );
648
                    }
649
                }
650
            } else {
651
                $send_to_groups = CourseManager::separateUsersGroups($to);
652
                $send_to_users = CourseManager::separateUsersGroups($to_users);
653
                $to_groups = $send_to_groups['groups'];
654
                $to_users = $send_to_users['users'];
655
                // storing the selected users
656
                if (is_array($to_users) && is_array($to_groups)) {
657
                    foreach ($to_groups as $group) {
658
                        foreach ($to_users as $user) {
659
                            api_item_property_update(
660
                                $_course,
661
                                TOOL_ANNOUNCEMENT,
662
                                $last_id,
663
                                'AnnouncementAdded',
664
                                api_get_user_id(),
665
                                $group,
666
                                $user
667
                            );
668
                        }
669
                    }
670
                }
671
            }
672
673
            if ($sendToUsersInSession) {
674
                self::addAnnouncementToAllUsersInSessions($last_id);
675
            }
676
        }
677
        return $last_id;
678
    }
679
680
    /**
681
     * This function stores the announcement item in the announcement table
682
     * and updates the item_property table
683
     *
684
     * @param int   $id id of the announcement
685
     * @param string $title
686
     * @param string $newContent
687
     * @param array $to	users that will receive the announcement
688
     * @param mixed $file	attachment
689
     * @param string $file_comment file comment
690
     * @param bool $sendToUsersInSession
691
     */
692
    public static function edit_announcement(
693
        $id,
694
        $title,
695
        $newContent,
696
        $to,
697
        $file = array(),
698
        $file_comment = '',
699
        $sendToUsersInSession = false
700
    ) {
701
        $_course = api_get_course_info();
702
        $course_id = api_get_course_int_id();
703
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
704
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
705
706
        $id = intval($id);
707
708
        $params = [
709
            'title' => $title,
710
            'content' => $newContent
711
        ];
712
713
        Database::update(
714
            $tbl_announcement,
715
            $params,
716
            ['c_id = ? AND id = ?' => [$course_id, $id]]
717
        );
718
719
        // save attachment file
720
        $row_attach = self::get_attachment($id);
721
722
        $id_attach = 0;
723
        if ($row_attach) {
724
            $id_attach = intval($row_attach['id']);
725
        }
726
727
        if (!empty($file)) {
728
            if (empty($id_attach)) {
729
                self::add_announcement_attachment_file($id, $file_comment, $file);
730
            } else {
731
                self::edit_announcement_attachment_file($id_attach, $file, $file_comment);
732
            }
733
        }
734
735
        // we remove everything from item_property for this
736
        $sql = "DELETE FROM $tbl_item_property
737
                WHERE c_id = $course_id AND ref='$id' AND tool='announcement'";
738
        Database::query($sql);
739
740
        if ($sendToUsersInSession) {
741
            self::addAnnouncementToAllUsersInSessions($id);
742
        }
743
744
        // store in item_property (first the groups, then the users
745
        if (!is_null($to)) {
746
            // !is_null($to): when no user is selected we send it to everyone
747
            $send_to = CourseManager::separateUsersGroups($to);
748
749
            // storing the selected groups
750
            if (is_array($send_to['groups'])) {
751
                foreach ($send_to['groups'] as $group) {
752
                    api_item_property_update(
753
                        $_course,
754
                        TOOL_ANNOUNCEMENT,
755
                        $id,
756
                        "AnnouncementUpdated",
757
                        api_get_user_id(),
758
                        $group
759
                    );
760
                }
761
            }
762
763
            // storing the selected users
764
            if (is_array($send_to['users'])) {
765
                foreach ($send_to['users'] as $user) {
766
                    api_item_property_update(
767
                        $_course,
768
                        TOOL_ANNOUNCEMENT,
769
                        $id,
770
                        "AnnouncementUpdated",
771
                        api_get_user_id(),
772
                        0,
773
                        $user
774
                    );
775
                }
776
            }
777
        } else {
778
            // the message is sent to everyone, so we set the group to 0
779
            api_item_property_update(
780
                $_course,
781
                TOOL_ANNOUNCEMENT,
782
                $id,
783
                "AnnouncementUpdated",
784
                api_get_user_id(),
785
                '0'
786
            );
787
        }
788
    }
789
790
    /**
791
     * @param int $announcementId
792
     */
793
    public static function addAnnouncementToAllUsersInSessions($announcementId)
794
    {
795
        $courseCode = api_get_course_id();
796
        $_course = api_get_course_info();
797
        $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
798
799
        if (!empty($sessionList)) {
800
            foreach ($sessionList as $sessionInfo) {
801
                $sessionId = $sessionInfo['id'];
802
                $userList = CourseManager::get_user_list_from_course_code(
803
                    $courseCode,
804
                    $sessionId
805
                );
806
807
                if (!empty($userList)) {
808
                    foreach ($userList as $user) {
0 ignored issues
show
Bug introduced by
The expression $userList of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
809
                        api_item_property_update(
810
                            $_course,
811
                            TOOL_ANNOUNCEMENT,
812
                            $announcementId,
813
                            "AnnouncementUpdated",
814
                            api_get_user_id(),
815
                            0,
816
                            $user['user_id'],
817
                            0,
818
                            0,
819
                            $sessionId
820
                        );
821
                    }
822
                }
823
            }
824
        }
825
    }
826
827
    /**
828
     * @param int $insert_id
829
     * @return bool
830
     */
831
    public static function update_mail_sent($insert_id)
832
    {
833
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
834
        if ($insert_id != strval(intval($insert_id))) {
835
            return false;
836
        }
837
        $insert_id = intval($insert_id);
838
        $course_id = api_get_course_int_id();
839
        // store the modifications in the table tbl_annoucement
840
        $sql = "UPDATE $tbl_announcement SET email_sent='1'
841
                WHERE c_id = $course_id AND id = $insert_id";
842
        Database::query($sql);
843
    }
844
845
    /**
846
     * Gets all announcements from a user by course
847
     * @param	string course db
848
     * @param	int user id
849
     * @return	array html with the content and count of announcements or false otherwise
850
     */
851
    public static function get_all_annoucement_by_user_course($course_code, $user_id)
852
    {
853
        $course_info = api_get_course_info($course_code);
854
        $course_id = $course_info['real_id'];
855
856
        if (empty($user_id)) {
857
            return false;
858
        }
859
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
860
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
861
        if (!empty($user_id) && is_numeric($user_id)) {
862
            $user_id = (int) $user_id;
863
            $sql = "SELECT DISTINCT 
864
                        announcement.title, 
865
                        announcement.content, 
866
                        display_order
867
					FROM $tbl_announcement announcement 
868
					INNER JOIN $tbl_item_property ip
869
					ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
870
					WHERE
871
						announcement.c_id = $course_id AND
872
						ip.c_id = $course_id AND						
873
						ip.tool='announcement' AND
874
						(
875
						  ip.insert_user_id='$user_id' AND
876
						  (ip.to_group_id='0' OR ip.to_group_id IS NULL)
877
						)
878
						AND ip.visibility='1'
879
						AND announcement.session_id  = 0
880
					ORDER BY display_order DESC";
881
            $rs = Database::query($sql);
882
            $num_rows = Database::num_rows($rs);
883
            $content = '';
884
            $i = 0;
885
            $result = array();
886
            if ($num_rows > 0) {
887
                while ($myrow = Database::fetch_array($rs)) {
888
                    $content.= '<strong>' . $myrow['title'] . '</strong><br /><br />';
889
                    $content.= $myrow['content'];
890
                    $i++;
891
                }
892
                $result['content'] = $content;
893
                $result['count'] = $i;
894
895
                return $result;
896
            }
897
898
            return false;
899
        }
900
901
        return false;
902
    }
903
904
    /**
905
     * Returns announcement info from its id
906
     *
907
     * @param int $course_id
908
     * @param int $annoucement_id
909
     * @return array
910
     */
911 View Code Duplication
    public static function get_by_id($course_id, $annoucement_id)
912
    {
913
        $annoucement_id = intval($annoucement_id);
914
        $course_id = $course_id ? intval($course_id) : api_get_course_int_id();
915
916
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
917
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
918
919
        $sql = "SELECT DISTINCT 
920
                    announcement.id, 
921
                    announcement.title, 
922
                    announcement.content
923
               FROM $tbl_announcement announcement
924
               INNER JOIN $tbl_item_property ip
925
               ON
926
                    announcement.id = ip.ref AND
927
                    announcement.c_id = ip.c_id
928
               WHERE
929
                    announcement.c_id = $course_id AND
930
                    ip.tool='announcement' AND
931
                    announcement.id = $annoucement_id
932
                ";
933
        $result = Database::query($sql);
934
        if (Database::num_rows($result)) {
935
            return Database::fetch_array($result);
936
        }
937
        return array();
938
    }
939
940
    /**
941
     * this function gets all the users of the course,
942
     * including users from linked courses
943
     * @deprecate use CourseManager class
944
     */
945 View Code Duplication
    public static function get_course_users()
946
    {
947
        //this would return only the users from real courses:
948
        $session_id = api_get_session_id();
949
        if ($session_id != 0) {
950
            $userList = CourseManager::get_real_and_linked_user_list(
951
                api_get_course_id(),
952
                true,
953
                $session_id,
954
                true
955
            );
956
        } else {
957
            $userList = CourseManager::get_real_and_linked_user_list(
958
                api_get_course_id(),
959
                false,
960
                0,
961
                true
962
            );
963
        }
964
965
        return $userList;
966
    }
967
968
    /**
969
     * this function gets all the groups of the course,
970
     * not including linked courses
971
     */
972 View Code Duplication
    public static function get_course_groups()
973
    {
974
        $session_id = api_get_session_id();
975
        if ($session_id != 0) {
976
            $new_group_list = CourseManager::get_group_list_of_course(
977
                api_get_course_id(),
978
                $session_id,
979
                1
980
            );
981
        } else {
982
            $new_group_list = CourseManager::get_group_list_of_course(
983
                api_get_course_id(),
984
                0,
985
                1
986
            );
987
        }
988
        return $new_group_list;
989
    }
990
991
    /**
992
     * This tools loads all the users and all the groups who have received
993
     * a specific item (in this case an announcement item)
994
     */
995
    public static function load_edit_users($tool, $id)
996
    {
997
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
998
        $tool = Database::escape_string($tool);
999
        $id = intval($id);
1000
        $course_id = api_get_course_int_id();
1001
1002
        $sql = "SELECT * FROM $tbl_item_property
1003
                WHERE c_id = $course_id AND tool='$tool' AND ref = $id";
1004
        $result = Database::query($sql);
1005
        $to = array();
1006
        while ($row = Database::fetch_array($result)) {
1007
            $to_group = $row['to_group_id'];
1008
            switch ($to_group) {
1009
                // it was send to one specific user
1010
                case null:
1011
                    $to[] = "USER:" . $row['to_user_id'];
1012
                    break;
1013
                // it was sent to everyone
1014
                case 0:
1015
                    return "everyone";
1016
                    break;
1017
                default:
1018
                    $to[] = "GROUP:" . $row['to_group_id'];
1019
            }
1020
        }
1021
        return $to;
1022
    }
1023
1024
    /**
1025
     * constructs the form to display all the groups and users the message has been sent to
1026
     * input: 	$sent_to_array is a 2 dimensional array containing the groups and the users
1027
     * 			the first level is a distinction between groups and users:
1028
     * 			$sent_to_array['groups'] * and $sent_to_array['users']
1029
     * 			$sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
1030
     * 			containing all the id's of the groups (resp. users) who have received this message.
1031
     * @author Patrick Cool <patrick.cool@>
1032
     */
1033
    public static function sent_to_form($sent_to_array)
1034
    {
1035
        // we find all the names of the groups
1036
        $group_names = self::get_course_groups();
1037
1038
        // we count the number of users and the number of groups
1039
        if (isset($sent_to_array['users'])) {
1040
            $number_users = count($sent_to_array['users']);
1041
        } else {
1042
            $number_users = 0;
1043
        }
1044
        if (isset($sent_to_array['groups'])) {
1045
            $number_groups = count($sent_to_array['groups']);
1046
        } else {
1047
            $number_groups = 0;
1048
        }
1049
        $total_numbers = $number_users + $number_groups;
1050
1051
        // starting the form if there is more than one user/group
1052
        $output = array();
1053
        if ($total_numbers > 1) {
1054
            // outputting the name of the groups
1055
            if (is_array($sent_to_array['groups'])) {
1056
                foreach ($sent_to_array['groups'] as $group_id) {
1057
                    $output[] = $group_names[$group_id]['name'];
1058
                }
1059
            }
1060
1061
            if (isset($sent_to_array['users'])) {
1062
                if (is_array($sent_to_array['users'])) {
1063
                    foreach ($sent_to_array['users'] as $user_id) {
1064
                        $user_info = api_get_user_info($user_id);
1065
                        $output[] = $user_info['complete_name_with_username'];
1066
                    }
1067
                }
1068
            }
1069
        } else {
1070
            // there is only one user/group
1071
            if (isset($sent_to_array['users']) and is_array($sent_to_array['users'])) {
1072
                $user_info = api_get_user_info($sent_to_array['users'][0]);
1073
                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
1074
            }
1075
            if (isset($sent_to_array['groups']) and
1076
                is_array($sent_to_array['groups']) and
1077
                isset($sent_to_array['groups'][0]) and
1078
                $sent_to_array['groups'][0] !== 0
1079
            ) {
1080
                $group_id = $sent_to_array['groups'][0];
1081
                $output[] = "&nbsp;" . $group_names[$group_id]['name'];
1082
            }
1083
            if (empty($sent_to_array['groups']) and empty($sent_to_array['users'])) {
1084
                $output[] = "&nbsp;" . get_lang('Everybody');
1085
            }
1086
        }
1087
1088
        if (!empty($output)) {
1089
            $output = array_filter($output);
1090
            if (count($output) > 0) {
1091
                $output = implode(', ', $output);
1092
            }
1093
            return $output;
1094
        }
1095
    }
1096
1097
    /**
1098
     * Returns all the users and all the groups a specific announcement item
1099
     * has been sent to
1100
     * @param    string  The tool (announcement, agenda, ...)
1101
     * @param    int     ID of the element of the corresponding type
1102
     * @return   array   Array of users and groups to whom the element has been sent
1103
     */
1104
    public static function sent_to($tool, $id)
1105
    {
1106
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1107
1108
        $tool = Database::escape_string($tool);
1109
        $id = (int) $id;
1110
1111
        $sent_to_group = array();
1112
        $sent_to = array();
1113
        $course_id = api_get_course_int_id();
1114
1115
        $sql = "SELECT to_group_id, to_user_id
1116
                FROM $tbl_item_property
1117
                WHERE c_id = $course_id AND tool = '$tool' AND ref=" . $id;
1118
        $result = Database::query($sql);
1119
1120
        while ($row = Database::fetch_array($result)) {
1121
            // if to_user_id <> 0 then it is sent to a specific user
1122
            if ($row['to_user_id'] <> 0) {
1123
                $sent_to_user[] = $row['to_user_id'];
1124
                continue;
1125
            }
1126
1127
            // if to_group_id is null then it is sent to a specific user
1128
            // if to_group_id = 0 then it is sent to everybody
1129
            if ($row['to_group_id'] != 0) {
1130
                $sent_to_group[] = $row['to_group_id'];
1131
            }
1132
        }
1133
1134
        if (isset($sent_to_group)) {
1135
            $sent_to['groups'] = $sent_to_group;
1136
        }
1137
1138
        if (isset($sent_to_user)) {
1139
            $sent_to['users'] = $sent_to_user;
1140
        }
1141
1142
        return $sent_to;
1143
    }
1144
1145
    /**
1146
     * Show a list with all the attachments according to the post's id
1147
     * @param int $announcementId
1148
     * @return array with the post info
1149
     * @author Arthur Portugal
1150
     * @version November 2009, dokeos 1.8.6.2
1151
     */
1152 View Code Duplication
    public static function get_attachment($announcementId)
1153
    {
1154
        $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1155
        $announcementId = intval($announcementId);
1156
        $course_id = api_get_course_int_id();
1157
        $row = array();
1158
        $sql = 'SELECT id, path, filename, comment 
1159
                FROM ' . $tbl_announcement_attachment . '
1160
				WHERE c_id = ' . $course_id . ' AND announcement_id = ' . $announcementId;
1161
        $result = Database::query($sql);
1162
        if (Database::num_rows($result) != 0) {
1163
            $row = Database::fetch_array($result, 'ASSOC');
1164
        }
1165
        return $row;
1166
    }
1167
1168
    /**
1169
     * This function add a attachment file into announcement
1170
     * @param int  announcement id
1171
     * @param string file comment
1172
     * @param array  uploaded file $_FILES
1173
     * @return int  -1 if failed, 0 if unknown (should not happen), 1 if success
1174
     */
1175
    public static function add_announcement_attachment_file($announcement_id, $file_comment, $file)
1176
    {
1177
        $_course = api_get_course_info();
1178
        $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1179
        $return = 0;
1180
        $announcement_id = intval($announcement_id);
1181
        $course_id = api_get_course_int_id();
1182
1183
        if (is_array($file) && $file['error'] == 0) {
1184
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1185
            $courseDir = $_course['path'] . '/upload/announcements';
1186
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1187
            $updir = $sys_course_path . $courseDir;
1188
1189
            // Try to add an extension to the file if it hasn't one
1190
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1191
            // user's file name
1192
            $file_name = $file['name'];
1193
1194
            if (!filter_extension($new_file_name)) {
1195
                $return = -1;
1196
                Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1197
            } else {
1198
                $new_file_name = uniqid('');
1199
                $new_path = $updir . '/' . $new_file_name;
1200
1201
                // This file is copy here but its cleaned in api_mail_html in api.lib.php
1202
                copy($file['tmp_name'], $new_path);
1203
1204
                $params = [
1205
                    'c_id' => $course_id,
1206
                    'filename' => $file_name,
1207
                    'comment' => $file_comment,
1208
                    'path' => $new_file_name,
1209
                    'announcement_id' => $announcement_id,
1210
                    'size' => intval($file['size']),
1211
                ];
1212
1213
                $insertId = Database::insert($tbl_announcement_attachment, $params);
1214
                if ($insertId) {
1215
                    $sql = "UPDATE $tbl_announcement_attachment SET id = iid WHERE iid = $insertId";
1216
                    Database::query($sql);
1217
                }
1218
1219
                $return = 1;
1220
            }
1221
        }
1222
1223
        return $return;
1224
    }
1225
1226
    /**
1227
     * This function edit a attachment file into announcement
1228
     * @param int attach id
1229
     * @param array uploaded file $_FILES
1230
     * @param string file comment
1231
     * @return int
1232
     */
1233
    public static function edit_announcement_attachment_file($id_attach, $file, $file_comment)
1234
    {
1235
        $_course = api_get_course_info();
1236
        $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1237
        $return = 0;
1238
        $course_id = api_get_course_int_id();
1239
1240
        if (is_array($file) && $file['error'] == 0) {
1241
            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
1242
            $courseDir = $_course['path'] . '/upload/announcements';
1243
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
1244
            $updir = $sys_course_path . $courseDir;
1245
1246
            // Try to add an extension to the file if it hasn't one
1247
            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
1248
            // user's file name
1249
            $file_name = $file ['name'];
1250
1251
            if (!filter_extension($new_file_name)) {
1252
                $return = -1;
1253
                Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1254
            } else {
1255
                $new_file_name = uniqid('');
1256
                $new_path = $updir . '/' . $new_file_name;
1257
                copy($file['tmp_name'], $new_path);
1258
                $safe_file_comment = Database::escape_string($file_comment);
1259
                $safe_file_name = Database::escape_string($file_name);
1260
                $safe_new_file_name = Database::escape_string($new_file_name);
1261
                $id_attach = intval($id_attach);
1262
                $sql = "UPDATE $tbl_announcement_attachment SET 
1263
                            filename = '$safe_file_name', 
1264
                            comment = '$safe_file_comment', 
1265
                            path = '$safe_new_file_name', 
1266
                            size ='" . intval($file['size']) . "'
1267
					 	WHERE c_id = $course_id AND id = '$id_attach'";
1268
                $result = Database::query($sql);
1269
                if ($result === false) {
1270
                    $return = -1;
1271
                    Display :: display_error_message(get_lang('UplUnableToSaveFile'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1272
                } else {
1273
                    $return = 1;
1274
                }
1275
            }
1276
        }
1277
        return $return;
1278
    }
1279
1280
    /**
1281
     * This function delete a attachment file by id
1282
     * @param integer $id attachment file Id
1283
     *
1284
     */
1285
    public static function delete_announcement_attachment_file($id)
1286
    {
1287
        $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
1288
        $id = intval($id);
1289
        $course_id = api_get_course_int_id();
1290
        if (empty($course_id) || empty($id)) {
1291
            return false;
1292
        }
1293
        $sql = "DELETE FROM $table
1294
                WHERE c_id = $course_id AND id = $id";
1295
1296
        Database::query($sql);
1297
    }
1298
1299
    /**
1300
     * @param array $courseInfo
1301
     * @param int $sessionId
1302
     * @param int $id
1303
     * @param bool $sendToUsersInSession
1304
     * @param bool $sendToDrhUsers
1305
     */
1306
    public static function sendEmail(
1307
        $courseInfo,
1308
        $sessionId,
1309
        $id,
1310
        $sendToUsersInSession = false,
1311
        $sendToDrhUsers = false
1312
    ) {
1313
        $email = AnnouncementEmail::create($courseInfo, $sessionId, $id);
1314
        $email->send($sendToUsersInSession, $sendToDrhUsers);
1315
    }
1316
1317
    /**
1318
     * @param $stok
1319
     * @param $announcement_number
1320
     * @param bool $getCount
1321
     * @param null $start
1322
     * @param null $limit
1323
     * @param string $sidx
1324
     * @param string $sord
1325
     * @param string $titleToSearch
1326
     * @param int $userIdToSearch
1327
     * @param int $userId
1328
     * @param int $courseId
1329
     * @param int $sessionId
1330
     * @return array
1331
     */
1332
    public static function getAnnouncements(
1333
        $stok,
1334
        $announcement_number,
1335
        $getCount = false,
1336
        $start = null,
1337
        $limit = null,
1338
        $sidx = '',
1339
        $sord = '',
1340
        $titleToSearch = '',
1341
        $userIdToSearch = 0,
1342
        $userId = 0,
1343
        $courseId = 0,
1344
        $sessionId = 0
1345
    ) {
1346
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1347
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1348
1349
        $user_id = $userId ?: api_get_user_id();
1350
        $group_id = api_get_group_id();
1351
        $session_id = $sessionId ?: api_get_session_id();
1352
        $condition_session = api_get_session_condition($session_id, true, true, 'announcement.session_id');
1353
        $course_id = $courseId ?: api_get_course_int_id();
1354
        $_course = api_get_course_info();
1355
1356
        $group_memberships = GroupManager::get_group_ids($course_id, api_get_user_id());
1357
        $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
1358
1359
        $select = ' DISTINCT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date';
1360
        if ($getCount) {
1361
            $select = ' COUNT(announcement.iid) count';
1362
        }
1363
1364
        $searchCondition = '';
1365
        if (!empty($titleToSearch)) {
1366
            $titleToSearch = Database::escape_string($titleToSearch);
1367
            $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
1368
        }
1369
1370
        if (!empty($userIdToSearch)) {
1371
            $userIdToSearch = intval($userIdToSearch);
1372
            $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
1373
        }
1374
1375
        if (api_is_allowed_to_edit(false, true) ||
1376
            ($allowUserEditSetting && !api_is_anonymous())
1377
        ) {
1378
            // A.1. you are a course admin with a USER filter
1379
            // => see only the messages of this specific user + the messages of the group (s)he is member of.
1380
1381
            //if (!empty($user_id)) {
1382
            if (0) {
1383
                if (is_array($group_memberships) && count($group_memberships) > 0) {
1384
                    $sql = "SELECT $select
1385
                            FROM $tbl_announcement announcement 
1386
                            INNER JOIN $tbl_item_property ip
1387
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1388
                            WHERE
1389
                                announcement.c_id = $course_id AND
1390
                                ip.c_id = $course_id AND                                
1391
                                ip.tool = 'announcement' AND
1392
                                (
1393
                                    ip.to_user_id = $user_id OR
1394
                                    ip.to_group_id IS NULL OR
1395
                                    ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
1396
                                ) AND
1397
                                ip.visibility IN ('1', '0')
1398
                                $condition_session
1399
                                $searchCondition
1400
                            ORDER BY display_order DESC";
1401
                } else {
1402
                    $sql = "SELECT $select
1403
                            FROM $tbl_announcement announcement 
1404
                            INNER JOIN $tbl_item_property ip
1405
                            ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
1406
                            WHERE
1407
                                announcement.c_id = $course_id AND
1408
                                ip.c_id = $course_id AND
1409
                                ip.tool ='announcement' AND
1410
                                (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
1411
                                ip.visibility IN ('1', '0')
1412
                            $condition_session
1413
                            $searchCondition
1414
                            ORDER BY display_order DESC";
1415
                }
1416
            } elseif ($group_id != 0) {
1417
                // A.2. you are a course admin with a GROUP filter
1418
                // => see only the messages of this specific group
1419
                $sql = "SELECT $select
1420
                        FROM $tbl_announcement announcement 
1421
                        INNER JOIN $tbl_item_property ip
1422
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1423
                        WHERE
1424
                            ip.tool='announcement' AND
1425
                            announcement.c_id = $course_id AND
1426
                            ip.c_id = $course_id AND
1427
                            ip.visibility<>'2' AND
1428
                            (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1429
                            $condition_session
1430
                            $searchCondition
1431
                        ORDER BY display_order DESC";
1432
                //GROUP BY ip.ref
1433
            } else {
1434
                // A.3 you are a course admin without any group or user filter
1435
                // A.3.a you are a course admin without user or group filter but WITH studentview
1436
                // => see all the messages of all the users and groups without editing possibilities
1437
                if (isset($isStudentView) && $isStudentView == "true") {
0 ignored issues
show
Bug introduced by
The variable $isStudentView seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
1438
                    $sql = "SELECT $select
1439
                            FROM $tbl_announcement announcement 
1440
                            INNER JOIN $tbl_item_property ip
1441
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1442
                            WHERE
1443
                                ip.tool='announcement' AND
1444
                                announcement.c_id = $course_id AND
1445
                                ip.c_id = $course_id AND                                
1446
                                ip.visibility='1'
1447
                                $condition_session
1448
                                $searchCondition
1449
                            ORDER BY display_order DESC";
1450
1451
                    //GROUP BY ip.ref
1452
                } else {
1453
                    // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
1454
                    // => see all the messages of all the users and groups with editing possibilities
1455
                    $sql = "SELECT $select
1456
                            FROM $tbl_announcement announcement 
1457
                            INNER JOIN $tbl_item_property ip
1458
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1459
                            WHERE
1460
                                ip.tool='announcement' AND
1461
                                announcement.c_id = $course_id AND
1462
                                ip.c_id = $course_id  AND
1463
                                (ip.visibility='0' OR ip.visibility='1')
1464
                                $condition_session
1465
                                $searchCondition
1466
                            ORDER BY display_order DESC";
1467
                    //GROUP BY ip.ref
1468
                }
1469
            }
1470
        } else {
1471
            // STUDENT
1472
            if (is_array($group_memberships) && count($group_memberships) > 0) {
1473
                if ($allowUserEditSetting && !api_is_anonymous()) {
1474
                    if ($group_id == 0) {
1475
                        // No group
1476
                        $cond_user_id = " AND (
1477
                            ip.lastedit_user_id = '".$user_id."' OR (
1478
                                ip.to_user_id='".$user_id."' OR
1479
                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1480
                            )
1481
                        ) ";
1482
                    } else {
1483
                        $cond_user_id = " AND (
1484
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
1485
                        )";
1486
                    }
1487 View Code Duplication
                } else {
1488
                    if ($group_id == 0) {
1489
                        $cond_user_id = " AND (
1490
                            ip.to_user_id = $user_id AND (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
1491
                        ) ";
1492
                    } else {
1493
                       $cond_user_id = " AND (
1494
                            ip.to_user_id = $user_id AND (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
1495
                        )";
1496
                    }
1497
                }
1498
1499
                $sql = "SELECT $select
1500
                        FROM $tbl_announcement announcement INNER JOIN
1501
                        $tbl_item_property ip
1502
                        ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1503
                        WHERE
1504
                            announcement.c_id = $course_id AND
1505
                            ip.c_id = $course_id AND                            
1506
                            ip.tool='announcement' 
1507
                            $cond_user_id
1508
                            $condition_session
1509
                            $searchCondition
1510
                            AND ip.visibility='1'
1511
                        ORDER BY display_order DESC";
1512
            } else {
1513
                if ($user_id) {
1514
                    if ($allowUserEditSetting && !api_is_anonymous()) {
1515
                        $cond_user_id = " AND (
1516
                            ip.lastedit_user_id = '".api_get_user_id()."' OR
1517
                            (ip.to_user_id='".$user_id."' AND (ip.to_group_id='0' OR ip.to_group_id IS NULL))
1518
                        ) ";
1519
                    } else {
1520
                        $cond_user_id = " AND (ip.to_user_id='".$user_id."' AND (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
1521
                    }
1522
1523
                    $sql = "SELECT $select
1524
						FROM $tbl_announcement announcement 
1525
						INNER JOIN $tbl_item_property ip
1526
						ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1527
						WHERE
1528
    						announcement.c_id = $course_id AND
1529
							ip.c_id = $course_id AND    						
1530
    						ip.tool='announcement'
1531
    						$cond_user_id
1532
    						$condition_session
1533
    						$searchCondition
1534
    						AND ip.visibility='1'
1535
    						AND announcement.session_id IN(0, ".$session_id.")
1536
						ORDER BY display_order DESC";
1537
                } else {
1538
                    if (($allowUserEditSetting && !api_is_anonymous())) {
1539
                        $cond_user_id = " AND (
1540
                            ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1541
                        )";
1542
                    } else {
1543
                        $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
1544
                    }
1545
1546
                    $sql = "SELECT $select
1547
                            FROM $tbl_announcement announcement 
1548
                            INNER JOIN $tbl_item_property ip
1549
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1550
                            WHERE
1551
                                announcement.c_id = $course_id AND
1552
                                ip.c_id = $course_id AND                            
1553
                                ip.tool='announcement'
1554
                                $cond_user_id
1555
                                $condition_session
1556
                                $searchCondition  AND
1557
                                ip.visibility='1' AND
1558
                                announcement.session_id IN ( 0,".api_get_session_id().")";
1559
                }
1560
            }
1561
        }
1562
1563
        if (!is_null($start) && !is_null($limit)) {
1564
            $start = intval($start);
1565
            $limit = intval($limit);
1566
            $sql .= " LIMIT $start, $limit";
1567
        }
1568
1569
        $result = Database::query($sql);
1570
        if ($getCount) {
1571
            $result = Database::fetch_array($result, 'ASSOC');
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1572
1573
            return $result['count'];
1574
        }
1575
1576
        $iterator = 1;
1577
        $bottomAnnouncement = $announcement_number;
1578
        $displayed = [];
1579
        $results = [];
1580
        $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.api_get_cidreq();
1581
        while ($myrow = Database::fetch_array($result, 'ASSOC')) {
1582
            if (!in_array($myrow['id'], $displayed)) {
1583
                $sent_to_icon = '';
1584
                // the email icon
1585
                if ($myrow['email_sent'] == '1') {
1586
                    $sent_to_icon = ' '.Display::return_icon('email.gif', get_lang('AnnounceSentByEmail'));
1587
                }
1588
                $groupReference = ($myrow['to_group_id'] > 0) ? ' <span class="label label-info">' . get_lang('Group') . '</span> ' : '' ;
1589
                $title = $myrow['title'] . $groupReference . $sent_to_icon;
1590
                $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $myrow['id'], $session_id);
1591
                $myrow['visibility'] = $item_visibility;
1592
1593
                // show attachment list
1594
                $attachment_list = AnnouncementManager::get_attachment($myrow['id']);
1595
1596
                $attachment_icon = '';
1597
                if (count($attachment_list)>0) {
1598
                    $attachment_icon = ' '.Display::return_icon('attachment.gif',get_lang('Attachment'));
1599
                }
1600
1601
                /* TITLE */
1602
                $user_info = api_get_user_info($myrow['insert_user_id']);
1603
                $username = sprintf(get_lang("LoginX"), $user_info['username']);
1604
                $username_span = Display::tag('span', api_get_person_name($user_info['firstName'], $user_info['lastName']), array('title'=>$username));
1605
                $title = Display::url($title.$attachment_icon, $actionUrl.'&action=view&id='.$myrow['id']);
1606
                //$html .= Display::tag('td', $username_span, array('class' => 'announcements-list-line-by-user'));
1607
                //$html .= Display::tag('td', api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG), array('class' => 'announcements-list-line-datetime'));
1608
1609
                $modify_icons = '';
1610
                // we can edit if : we are the teacher OR the element belongs to
1611
                // the session we are coaching OR the option to allow users to edit is on
1612
                if (api_is_allowed_to_edit(false, true) ||
1613
                    (api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']))
1614
                    || (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
1615
                ) {
1616
                    $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$myrow['id']."\">".
1617
                        Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL)."</a>";
1618 View Code Duplication
                    if ($myrow['visibility']==1) {
1619
                        $image_visibility="visible";
1620
                        $alt_visibility=get_lang('Hide');
1621
                    } else {
1622
                        $image_visibility="invisible";
1623
                        $alt_visibility=get_lang('Visible');
1624
                    }
1625
                    $modify_icons .=  "<a href=\"".$actionUrl."&action=showhide&id=".$myrow['id']."&sec_token=".$stok."\">".
1626
                        Display::return_icon($image_visibility.'.png', $alt_visibility,'',ICON_SIZE_SMALL)."</a>";
1627
1628
                    // DISPLAY MOVE UP COMMAND only if it is not the top announcement
1629 View Code Duplication
                    if ($iterator != 1) {
1630
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$myrow["id"]."&sec_token=".$stok."\">".
1631
                            Display::return_icon('up.gif', get_lang('Up'))."</a>";
1632
                    } else {
1633
                        $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
1634
                    }
1635
                    if ($iterator < $bottomAnnouncement) {
1636
                        $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$myrow["id"]."&sec_token=".$stok."\">".
1637
                            Display::return_icon('down.gif', get_lang('Down'))."</a>";
1638
                    } else {
1639
                        $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
1640
                    }
1641 View Code Duplication
                    if (api_is_allowed_to_edit(false,true)) {
1642
                        $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$myrow['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,api_get_system_encoding()))."')) return false;\">".
1643
                            Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).
1644
                            "</a>";
1645
                    }
1646
                    $iterator ++;
1647
                } else {
1648
                    $modify_icons = Display::url(
1649
                        Display::return_icon('default.png'),
1650
                        $actionUrl.'&action=view&id='.$myrow['id']
1651
                    );
1652
                }
1653
1654
                $announcement = [
1655
                    'id' => $myrow["id"],
1656
                    'title' => $title,
1657
                    'username' => $username_span,
1658
                    'insert_date' => api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG),
1659
                    'actions' => $modify_icons
1660
                ];
1661
1662
                $results[] = $announcement;
1663
            }
1664
            $displayed[] = $myrow['id'];
1665
        }
1666
1667
        return $results;
1668
    }
1669
1670
    /**
1671
     * @return int
1672
     */
1673
    public static function getNumberAnnouncements()
1674
    {
1675
        // Maximum title messages to display
1676
        $maximum = '12';
1677
        // Database Table Definitions
1678
        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
1679
        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
1680
1681
        $session_id = api_get_session_id();
1682
        $_course = api_get_course_info();
1683
        $course_id = $_course['real_id'];
1684
        $userId = api_get_user_id();
1685
        $condition_session = api_get_session_condition(
1686
            $session_id,
1687
            true,
1688
            true,
1689
            'announcement.session_id'
1690
        );
1691
1692
        if (api_is_allowed_to_edit(false,true))  {
1693
            // check teacher status
1694
            if (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') {
1695
1696
                if (api_get_group_id() == 0) {
1697
                    $group_condition = '';
1698
                } else {
1699
                    $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
1700
                }
1701
1702
                $sql = "SELECT 
1703
                            announcement.*, 
1704
                            ip.visibility, 
1705
                            ip.to_group_id, 
1706
                            ip.insert_user_id
1707
                        FROM $tbl_announcement announcement 
1708
                        INNER JOIN $tbl_item_property ip
1709
                        ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
1710
                        WHERE
1711
                            announcement.c_id = $course_id AND
1712
                            ip.c_id = $course_id AND                    
1713
                            ip.tool = 'announcement' AND
1714
                            ip.visibility <> '2'
1715
                            $group_condition
1716
                            $condition_session
1717
                        GROUP BY ip.ref
1718
                        ORDER BY display_order DESC
1719
                        LIMIT 0, $maximum";
1720
            }
1721
        } else {
1722
            // students only get to see the visible announcements
1723
            if (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') {
1724
                $group_memberships = GroupManager::get_group_ids($_course['real_id'], $userId);
1725
1726
                if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
1727 View Code Duplication
                    if (api_get_group_id() == 0) {
1728
                        $cond_user_id = " AND (
1729
                        ip.lastedit_user_id = '".$userId."' OR (
1730
                            ip.to_user_id='".$userId."' OR
1731
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
1732
                            ip.to_group_id IS NULL
1733
                            )
1734
                        )
1735
                        ";
1736
                    } else {
1737
                        $cond_user_id = " AND (
1738
                            ip.lastedit_user_id = '".$userId."'OR
1739
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
1740
                            ip.to_group_id IS NULL
1741
                        )";
1742
                    }
1743 View Code Duplication
                } else {
1744
                    if (api_get_group_id() == 0) {
1745
                        $cond_user_id = " AND (
1746
                            ip.to_user_id='".$userId."' OR
1747
                            ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
1748
                            ip.to_group_id IS NULL
1749
                        ) ";
1750
                    } else {
1751
                        $cond_user_id = " AND (
1752
                            ip.to_user_id='".$userId."' OR
1753
                            ip.to_group_id IN (0, ".api_get_group_id().") OR
1754
                            ip.to_group_id IS NULL
1755
                        ) ";
1756
                    }
1757
                }
1758
1759
                // the user is member of several groups => display personal announcements AND
1760
                // his group announcements AND the general announcements
1761
                if (is_array($group_memberships) && count($group_memberships)>0) {
1762
                    $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
1763
                            FROM $tbl_announcement announcement 
1764
                            INNER JOIN $tbl_item_property ip
1765
                            ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1766
                            WHERE
1767
                                announcement.c_id = $course_id AND
1768
                                ip.c_id = $course_id AND                                
1769
                                ip.tool='announcement' AND 
1770
                                ip.visibility='1'
1771
                                $cond_user_id
1772
                                $condition_session
1773
                            GROUP BY ip.ref
1774
                            ORDER BY display_order DESC
1775
                            LIMIT 0, $maximum";
1776
                } else {
1777
                    // the user is not member of any group
1778
                    // this is an identified user => show the general announcements AND his personal announcements
1779
                    if ($userId) {
1780 View Code Duplication
                        if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
1781
                            $cond_user_id = " AND (
1782
                                ip.lastedit_user_id = '".$userId."' OR
1783
                                ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
1784
                            ) ";
1785
                        } else {
1786
                            $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
1787
                        }
1788
                        $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
1789
                                FROM $tbl_announcement announcement 
1790
                                INNER JOIN $tbl_item_property ip
1791
                                ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
1792
                                WHERE
1793
                                    announcement.c_id = $course_id AND
1794
                                    ip.c_id = $course_id AND 
1795
                                    ip.tool='announcement' AND 
1796
                                    ip.visibility='1'
1797
                                    $cond_user_id
1798
                                    $condition_session
1799
                                GROUP BY ip.ref
1800
                                ORDER BY display_order DESC
1801
                                LIMIT 0, $maximum";
1802 View Code Duplication
                    } else {
1803
1804
                        if (api_get_course_setting('allow_user_edit_announcement')) {
1805
                            $cond_user_id = " AND (
1806
                                ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
1807
                            ) ";
1808
                        } else {
1809
                            $cond_user_id = " AND ip.to_group_id='0' ";
1810
                        }
1811
1812
                        // the user is not identiefied => show only the general announcements
1813
                        $sql = "SELECT 
1814
                                    announcement.*, 
1815
                                    ip.visibility, 
1816
                                    ip.to_group_id, 
1817
                                    ip.insert_user_id
1818
                                FROM $tbl_announcement announcement 
1819
                                INNER JOIN $tbl_item_property ip
1820
                                ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
1821
                                WHERE
1822
                                    announcement.c_id = $course_id AND
1823
                                    ip.c_id = $course_id AND 
1824
                                    ip.tool='announcement' AND 
1825
                                    ip.visibility='1' AND 
1826
                                    ip.to_group_id='0'
1827
                                    $condition_session
1828
                                GROUP BY ip.ref
1829
                                ORDER BY display_order DESC
1830
                                LIMIT 0, $maximum";
1831
                    }
1832
                }
1833
            }
1834
        }
1835
1836
        $result = Database::query($sql);
1837
1838
        return Database::num_rows($result);
1839
    }
1840
}
1841