Passed
Push — 1.11.x ( 610176...32c26a )
by Julito
15:00 queued 01:55
created

announcement_for_groups()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 19
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 35
rs 8.8333
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class SystemAnnouncementManager.
7
 */
8
class SystemAnnouncementManager
9
{
10
    public const VISIBLE_GUEST = 'visible_guest';
11
    public const VISIBLE_STUDENT = 'visible_student';
12
    public const VISIBLE_TEACHER = 'visible_teacher';
13
    // Requires DB change
14
    public const VISIBLE_DRH = 'visible_drh';
15
    public const VISIBLE_SESSION_ADMIN = 'visible_session_admin';
16
    public const VISIBLE_STUDENT_BOSS = 'visible_boss';
17
18
    /**
19
     * @return array
20
     */
21
    public static function getVisibilityList()
22
    {
23
        $extraRoles = self::newRolesActivated();
24
25
        $visibleToUsers = [
26
            self::VISIBLE_TEACHER => get_lang('Teacher'),
27
            self::VISIBLE_STUDENT => get_lang('Student'),
28
            self::VISIBLE_GUEST => get_lang('Guest'),
29
        ];
30
31
        if ($extraRoles) {
32
            $visibleToUsers[self::VISIBLE_DRH] = get_lang('DRH');
33
            $visibleToUsers[self::VISIBLE_SESSION_ADMIN] = get_lang('SessionAdministrator');
34
            $visibleToUsers[self::VISIBLE_STUDENT_BOSS] = get_lang('StudentBoss');
35
        }
36
37
        return $visibleToUsers;
38
    }
39
40
    /**
41
     * @param string $visibility
42
     *
43
     * @return string
44
     */
45
    public static function getVisibilityCondition($visibility)
46
    {
47
        $list = self::getVisibilityList();
48
        $visibilityCondition = " AND ".self::VISIBLE_GUEST." = 1 ";
49
        if (in_array($visibility, array_keys($list))) {
50
            $visibilityCondition = " AND $visibility = 1 ";
51
        }
52
53
        return $visibilityCondition;
54
    }
55
56
    /**
57
     * @param string $visibility
58
     * @param int    $id
59
     * @param int    $start
60
     * @param string $user_id
61
     *
62
     * @return string
63
     */
64
    public static function displayAllAnnouncements(
65
        $visibility,
66
        $id = -1,
67
        $start = 0,
68
        $user_id = ''
69
    ) {
70
        $user_selected_language = api_get_interface_language();
71
        $start = (int) $start;
72
        $userGroup = new UserGroup();
73
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
74
        $temp_user_groups = $userGroup->get_groups_by_user(api_get_user_id(), 0);
75
        $groups = [];
76
        foreach ($temp_user_groups as $user_group) {
77
            $groups = array_merge($groups, [$user_group['id']]);
78
            $groups = array_merge($groups, $userGroup->get_parent_groups($user_group['id']));
79
        }
80
81
        // Checks if tables exists to not break platform not updated
82
        $groups_string = '('.implode($groups, ',').')';
83
84
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
85
        $now = api_get_utc_datetime();
86
87
        $sql = "SELECT * FROM $table
88
                WHERE
89
                    (lang = '$user_selected_language' OR lang IS NULL) AND
90
                    ( '$now' >= date_start AND '$now' <= date_end) ";
91
92
        $sql .= self::getVisibilityCondition($visibility);
93
94
        if (count($groups) > 0) {
95
            $sql .= " OR id IN (
96
                    SELECT announcement_id FROM $tbl_announcement_group
97
                    WHERE group_id in $groups_string
98
                    ) ";
99
        }
100
101
        if (api_is_multiple_url_enabled()) {
102
            $current_access_url_id = api_get_current_access_url_id();
103
            $sql .= " AND access_url_id IN ('1', '$current_access_url_id')";
104
        }
105
106
        if (!isset($_GET['start']) || $_GET['start'] == 0) {
107
            $sql .= " ORDER BY date_start DESC LIMIT ".$start.",20";
108
        } else {
109
            $sql .= " ORDER BY date_start DESC LIMIT ".($start + 1).",20";
110
        }
111
        $announcements = Database::query($sql);
112
        $content = '';
113
        if (Database::num_rows($announcements) > 0) {
114
            $content .= '<div class="system_announcements">';
115
            $content .= '<h3>'.get_lang('SystemAnnouncements').'</h3>';
116
            $content .= '<table align="center">';
117
            $content .= '<tr>';
118
            $content .= '<td>';
119
            $content .= self::display_arrow($user_id);
120
            $content .= '</td>';
121
            $content .= '</tr>';
122
            $content .= '</table>';
123
            $content .= '<table align="center" border="0" width="900px">';
124
            while ($announcement = Database::fetch_object($announcements)) {
125
                $display_date = api_convert_and_format_date($announcement->display_date, DATE_FORMAT_LONG);
126
                $content .= '<tr><td>';
127
                $content .= '<a name="'.$announcement->id.'"></a>
128
                        <div class="system_announcement">
129
                        <h2>'.$announcement->title.'</h2>
130
                        <div class="system_announcement_date">'.$display_date.'</div>
131
                        <br />
132
                        <div class="system_announcement_content">'
133
                            .$announcement->content.'
134
                        </div>
135
                      </div><br />';
136
                $content .= '</tr></td>';
137
            }
138
            $content .= '</table>';
139
140
            $content .= '<table align="center">';
141
            $content .= '<tr>';
142
            $content .= '<td>';
143
            $content .= self::display_arrow($user_id);
144
            $content .= '</td>';
145
            $content .= '</tr>';
146
            $content .= '</table>';
147
            $content .= '</div>';
148
        }
149
150
        return $content;
151
    }
152
153
    /**
154
     * @param int $user_id
155
     *
156
     * @return string
157
     */
158
    public static function display_arrow($user_id)
159
    {
160
        $start = (int) $_GET['start'];
161
        $nb_announcement = self::count_nb_announcement($start, $user_id);
162
        $next = ((int) $_GET['start'] + 19);
163
        $prev = ((int) $_GET['start'] - 19);
164
        $content = '';
165
        if (!isset($_GET['start']) || $_GET['start'] == 0) {
166
            if ($nb_announcement > 20) {
167
                $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
168
            }
169
        } else {
170
            echo '<a href="news_list.php?start='.$prev.'"> << '.get_lang('Prev').'</a>';
171
            if ($nb_announcement > 20) {
172
                $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
173
            }
174
        }
175
176
        return $content;
177
    }
178
179
    /**
180
     * @param int    $start
181
     * @param string $user_id
182
     *
183
     * @return int
184
     */
185
    public static function count_nb_announcement($start = 0, $user_id = '')
186
    {
187
        $start = (int) $start;
188
        $user_selected_language = api_get_interface_language();
189
        $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
190
        $sql = 'SELECT id FROM '.$db_table.'
191
                WHERE (lang="'.$user_selected_language.'" OR lang IS NULL) ';
192
193
        $visibility = self::getCurrentUserVisibility();
194
        $sql .= self::getVisibilityCondition($visibility);
195
196
        $current_access_url_id = 1;
197
        if (api_is_multiple_url_enabled()) {
198
            $current_access_url_id = api_get_current_access_url_id();
199
        }
200
        $sql .= " AND access_url_id = '$current_access_url_id' ";
201
        $sql .= 'LIMIT '.$start.', 21';
202
        $announcements = Database::query($sql);
203
        $i = 0;
204
        while ($rows = Database::fetch_array($announcements)) {
205
            $i++;
206
        }
207
208
        return $i;
209
    }
210
211
    /**
212
     * Get all announcements.
213
     *
214
     * @return array An array with all available system announcements (as php
215
     *               objects)
216
     */
217
    public static function get_all_announcements()
218
    {
219
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
220
        $now = api_get_utc_datetime();
221
        $sql = "SELECT *, IF ( '$now'  >= date_start AND '$now' <= date_end, '1', '0') AS visible
222
                FROM $table";
223
224
        $current_access_url_id = 1;
225
        if (api_is_multiple_url_enabled()) {
226
            $current_access_url_id = api_get_current_access_url_id();
227
        }
228
        $sql .= " WHERE access_url_id = '$current_access_url_id' ";
229
        $sql .= " ORDER BY date_start ASC";
230
231
        $result = Database::query($sql);
232
        $announcements = [];
233
        while ($announcement = Database::fetch_object($result)) {
234
            $announcements[] = $announcement;
235
        }
236
237
        return $announcements;
238
    }
239
240
    /**
241
     * Adds an announcement to the database.
242
     *
243
     * @param string $title           Title of the announcement
244
     * @param string $content         Content of the announcement
245
     * @param string $date_start      Start date (YYYY-MM-DD HH:II: SS)
246
     * @param string $date_end        End date (YYYY-MM-DD HH:II: SS)
247
     * @param array  $visibility
248
     * @param string $lang            The language for which the announvement should be shown. Leave null for all langages
249
     * @param int    $send_mail       Whether to send an e-mail to all users (1) or not (0)
250
     * @param bool   $add_to_calendar
251
     * @param bool   $sendEmailTest
252
     * @param int    $careerId
253
     * @param int    $promotionId
254
     * @param int    $groupId
255
     *
256
     * @return mixed insert_id on success, false on failure
257
     */
258
    public static function add_announcement(
259
        $title,
260
        $content,
261
        $date_start,
262
        $date_end,
263
        $visibility,
264
        $lang = '',
265
        $send_mail = 0,
266
        $add_to_calendar = false,
267
        $sendEmailTest = false,
268
        $careerId = 0,
269
        $promotionId = 0,
270
        $groupId = 0
271
    ) {
272
        $original_content = $content;
273
        $a_dateS = explode(' ', $date_start);
274
        $a_arraySD = explode('-', $a_dateS[0]);
275
        $a_arraySH = explode(':', $a_dateS[1]);
276
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
277
278
        $a_dateE = explode(' ', $date_end);
279
        $a_arrayED = explode('-', $a_dateE[0]);
280
        $a_arrayEH = explode(':', $a_dateE[1]);
281
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
282
283
        $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
284
285
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
286
            Display::addFlash(
287
                Display::return_message(get_lang('InvalidStartDate'), 'warning')
288
            );
289
290
            return false;
291
        }
292
293
        if (($date_end_to_compare[1] ||
294
            $date_end_to_compare[2] ||
295
            $date_end_to_compare[0]) &&
296
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
297
        ) {
298
            Display::addFlash(
299
                Display::return_message(get_lang('InvalidEndDate'), 'warning')
300
            );
301
302
            return false;
303
        }
304
305
        if (strlen(trim($title)) == 0) {
306
            Display::addFlash(
307
                Display::return_message(get_lang('InvalidTitle'), 'warning')
308
            );
309
310
            return false;
311
        }
312
313
        $start = api_get_utc_datetime($date_start);
314
        $end = api_get_utc_datetime($date_end);
315
316
        //Fixing urls that are sent by email
317
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
318
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
319
        $content = str_replace(
320
            'src=\"'.api_get_path(REL_HOME_PATH),
321
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
322
            $content
323
        );
324
        $content = str_replace(
325
            'file='.api_get_path(REL_HOME_PATH),
326
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
327
            $content
328
        );
329
        $lang = is_null($lang) ? '' : $lang;
330
331
        $current_access_url_id = 1;
332
        if (api_is_multiple_url_enabled()) {
333
            $current_access_url_id = api_get_current_access_url_id();
334
        }
335
336
        $params = [
337
            'title' => $title,
338
            'content' => $content,
339
            'date_start' => $start,
340
            'date_end' => $end,
341
            'lang' => $lang,
342
            'access_url_id' => $current_access_url_id,
343
        ];
344
345
        if (api_get_configuration_value('allow_careers_in_global_announcements') && !empty($careerId)) {
346
            $params['career_id'] = (int) $careerId;
347
            $params['promotion_id'] = (int) $promotionId;
348
        }
349
350
        foreach ($visibility as $key => $value) {
351
            $params[$key] = $value;
352
        }
353
354
        $resultId = Database::insert($db_table, $params);
355
356
        if ($resultId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $resultId of type false|integer 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...
357
            if ($sendEmailTest) {
358
                self::send_system_announcement_by_email(
359
                    $resultId,
360
                    $visibility,
361
                    true
362
                );
363
            } else {
364
                if ($send_mail == 1) {
365
                    self::send_system_announcement_by_email(
366
                        $resultId,
367
                        $visibility,
368
                        false,
369
                        $groupId
370
                    );
371
                }
372
            }
373
374
            if ($add_to_calendar) {
375
                $agenda = new Agenda('admin');
376
                $agenda->addEvent(
377
                    $date_start,
378
                    $date_end,
379
                    false,
380
                    $title,
381
                    $original_content
382
                );
383
            }
384
385
            return $resultId;
386
        }
387
388
        return false;
389
    }
390
391
    /**
392
     * Makes the announcement id visible only for groups in groups_array.
393
     *
394
     * @param int   $announcement_id
395
     * @param array $group_array     array of group id
396
     *
397
     * @return bool
398
     */
399
    public static function announcement_for_groups($announcement_id, $group_array)
400
    {
401
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
402
403
        $announcement_id = (int) $announcement_id;
404
405
        if (empty($announcement_id)) {
406
            return false;
407
        }
408
409
        //first delete all group associations for this announcement
410
        $res = Database::query(
411
            "DELETE FROM $tbl_announcement_group
412
             WHERE announcement_id=".$announcement_id
413
        );
414
415
        if ($res === false) {
416
            return false;
417
        }
418
419
        if (!empty($group_array)) {
420
            foreach ($group_array as $group_id) {
421
                if (intval($group_id) != 0) {
422
                    $sql = "INSERT INTO $tbl_announcement_group SET
423
                            announcement_id=".$announcement_id.",
424
                            group_id=".intval($group_id);
425
                    $res = Database::query($sql);
426
                    if ($res === false) {
427
                        return false;
428
                    }
429
                }
430
            }
431
        }
432
433
        return true;
434
    }
435
436
    /**
437
     * Gets the groups of this announce.
438
     *
439
     * @param int announcement id
440
     *
441
     * @return array array of group id
442
     */
443
    public static function get_announcement_groups($announcement_id)
444
    {
445
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
446
        $tbl_group = Database::get_main_table(TABLE_USERGROUP);
447
        //first delete all group associations for this announcement
448
        $sql = "SELECT
449
                    g.id as group_id,
450
                    g.name as group_name
451
                FROM $tbl_group g , $tbl_announcement_group ag
452
                WHERE
453
                    announcement_id =".intval($announcement_id)." AND
454
                    ag.group_id = g.id";
455
        $res = Database::query($sql);
456
        $groups = Database::fetch_array($res);
457
458
        return $groups;
459
    }
460
461
    /**
462
     * Updates an announcement to the database.
463
     *
464
     * @param int    $id            of the announcement
465
     * @param string $title         title of the announcement
466
     * @param string $content       content of the announcement
467
     * @param array  $date_start    start date (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
468
     * @param array  $date_end      end date of (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
469
     * @param array  $visibility
470
     * @param array  $lang
471
     * @param int    $send_mail
472
     * @param bool   $sendEmailTest
473
     * @param int    $careerId
474
     * @param int    $promotionId
475
     *
476
     * @return bool True on success, false on failure
477
     */
478
    public static function update_announcement(
479
        $id,
480
        $title,
481
        $content,
482
        $date_start,
483
        $date_end,
484
        $visibility,
485
        $lang = null,
486
        $send_mail = 0,
487
        $sendEmailTest = false,
488
        $careerId = 0,
489
        $promotionId = 0,
490
        $groupId = 0
491
    ) {
492
        $em = Database::getManager();
493
        $announcement = $em->find('ChamiloCoreBundle:SysAnnouncement', $id);
494
        if (!$announcement) {
495
            return false;
496
        }
497
498
        $a_dateS = explode(' ', $date_start);
499
        $a_arraySD = explode('-', $a_dateS[0]);
500
        $a_arraySH = explode(':', $a_dateS[1]);
501
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
502
503
        $a_dateE = explode(' ', $date_end);
504
        $a_arrayED = explode('-', $a_dateE[0]);
505
        $a_arrayEH = explode(':', $a_dateE[1]);
506
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
507
508
        $lang = is_null($lang) ? '' : $lang;
509
510
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
511
            echo Display::return_message(get_lang('InvalidStartDate'));
512
513
            return false;
514
        }
515
516
        if (($date_end_to_compare[1] ||
517
            $date_end_to_compare[2] ||
518
            $date_end_to_compare[0]) &&
519
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
520
        ) {
521
            echo Display::return_message(get_lang('InvalidEndDate'));
522
523
            return false;
524
        }
525
526
        if (strlen(trim($title)) == 0) {
527
            echo Display::return_message(get_lang('InvalidTitle'));
528
529
            return false;
530
        }
531
532
        $start = api_get_utc_datetime($date_start);
533
        $end = api_get_utc_datetime($date_end);
534
535
        //Fixing urls that are sent by email
536
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
537
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
538
        $content = str_replace(
539
            'src=\"'.api_get_path(REL_HOME_PATH),
540
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
541
            $content
542
        );
543
        $content = str_replace(
544
            'file='.api_get_path(REL_HOME_PATH),
545
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
546
            $content
547
        );
548
549
        $dateStart = new DateTime($start, new DateTimeZone('UTC'));
550
        $dateEnd = new DateTime($end, new DateTimeZone('UTC'));
551
552
        $announcement
553
            ->setLang($lang)
554
            ->setTitle($title)
555
            ->setContent($content)
556
            ->setDateStart($dateStart)
557
            ->setDateEnd($dateEnd)
558
            //->setVisibleTeacher($visible_teacher)
559
            //->setVisibleStudent($visible_student)
560
            //->setVisibleGuest($visible_guest)
561
            ->setAccessUrlId(api_get_current_access_url_id());
562
563
        $em->merge($announcement);
564
        $em->flush();
565
566
        // Update visibility
567
        $list = self::getVisibilityList();
568
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
569
570
        if (api_get_configuration_value('allow_careers_in_global_announcements') && !empty($careerId)) {
571
            $params = [];
572
            $params['career_id'] = (int) $careerId;
573
            $params['promotion_id'] = (int) $promotionId;
574
            Database::update(
575
                $table,
576
                $params,
577
                ['id = ? ' => $id]
578
            );
579
        }
580
581
        foreach ($list as $key => $title) {
0 ignored issues
show
introduced by
$title is overwriting one of the parameters of this function.
Loading history...
582
            $value = isset($visibility[$key]) && $visibility[$key] ? 1 : 0;
583
            $sql = "UPDATE $table SET $key = '$value' WHERE id = $id";
584
            Database::query($sql);
585
        }
586
587
        if ($sendEmailTest) {
588
            self::send_system_announcement_by_email(
589
                $id,
590
                $visibility,
591
                true
592
            );
593
        } else {
594
            if ($send_mail == 1) {
595
                self::send_system_announcement_by_email(
596
                    $id,
597
                    $visibility,
598
                    false,
599
                    $groupId
600
                );
601
            }
602
        }
603
604
        return true;
605
    }
606
607
    /**
608
     * Deletes an announcement.
609
     *
610
     * @param int $id The identifier of the announcement that should be
611
     *
612
     * @return bool True on success, false on failure
613
     */
614
    public static function delete_announcement($id)
615
    {
616
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
617
        $id = (int) $id;
618
        $sql = "DELETE FROM $table WHERE id =".$id;
619
        $res = Database::query($sql);
620
        if ($res === false) {
621
            return false;
622
        }
623
624
        return true;
625
    }
626
627
    /**
628
     * Gets an announcement.
629
     *
630
     * @param int $id The identifier of the announcement that should be
631
     *
632
     * @return object Object of class StdClass or the required class, containing the query result row
633
     */
634
    public static function get_announcement($id)
635
    {
636
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
637
        $id = (int) $id;
638
        $sql = "SELECT * FROM ".$table." WHERE id = ".$id;
639
        $announcement = Database::fetch_object(Database::query($sql));
640
641
        return $announcement;
642
    }
643
644
    /**
645
     * Change the visibility of an announcement.
646
     *
647
     * @param int  $id
648
     * @param int  $user    For who should the visibility be changed
649
     * @param bool $visible
650
     *
651
     * @return bool True on success, false on failure
652
     */
653
    public static function set_visibility($id, $user, $visible)
654
    {
655
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
656
        $id = (int) $id;
657
        $list = array_keys(self::getVisibilityList());
658
        $user = trim($user);
659
        $visible = (int) $visible;
660
        if (!in_array($user, $list)) {
661
            return false;
662
        }
663
664
        $field = $user;
665
        $sql = "UPDATE $table SET ".$field." = '".$visible."'
666
                WHERE id='".$id."'";
667
        $res = Database::query($sql);
668
669
        if ($res === false) {
670
            return false;
671
        }
672
673
        return true;
674
    }
675
676
    /**
677
     * Send a system announcement by e-mail to all teachers/students depending on parameters.
678
     *
679
     * @param int   $id
680
     * @param array $visibility
681
     * @param bool  $sendEmailTest
682
     * @param int   $groupId
683
     *
684
     * @return bool True if the message was sent or there was no destination matching.
685
     *              False on database or e-mail sending error.
686
     */
687
    public static function send_system_announcement_by_email(
688
        $id,
689
        $visibility,
690
        $sendEmailTest = false,
691
        $groupId = 0
692
    ) {
693
        $announcement = self::get_announcement($id);
694
695
        if (empty($announcement)) {
696
            return false;
697
        }
698
699
        $groupId = (int) $groupId;
700
        $title = $announcement->title;
701
        $content = $announcement->content;
702
        $language = $announcement->lang;
703
704
        $content = str_replace(['\r\n', '\n', '\r'], '', $content);
705
        $now = api_get_utc_datetime();
706
        $teacher = $visibility['visible_teacher'];
707
        $student = $visibility['visible_student'];
708
        if ($sendEmailTest) {
709
            MessageManager::send_message_simple(api_get_user_id(), $title, $content);
710
711
            return true;
712
        }
713
        $whereUsersInGroup = '';
714
        if (0 != $groupId) {
715
            $tblGroupRelUser = Database::get_main_table(TABLE_USERGROUP_REL_USER);
716
            $sql = "SELECT user_id FROM $tblGroupRelUser WHERE usergroup_id = $groupId";
717
            $result = Database::query($sql);
718
            $data = Database::store_result($result);
719
            $usersId = [];
720
            foreach ($data as $userArray) {
721
                $usersId[] = $userArray['user_id'];
722
            }
723
            $usersId = implode(',', $usersId);
724
            $whereUsersInGroup = " AND u.user_id in ($usersId) ";
725
        }
726
727
        $urlJoin = '';
728
        $urlCondition = '';
729
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
730
        if (api_is_multiple_url_enabled()) {
731
            $current_access_url_id = api_get_current_access_url_id();
732
            $url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
733
            $urlJoin = " INNER JOIN $url_rel_user uu ON uu.user_id = u.user_id ";
734
            $urlCondition = " AND access_url_id = '".$current_access_url_id."' ";
735
        }
736
737
        if ($teacher != 0 && $student == 0) {
738
            $sql = "SELECT DISTINCT u.user_id FROM $user_table u $urlJoin
739
                    WHERE status = '1' $urlCondition $whereUsersInGroup";
740
        }
741
742
        if ($teacher == 0 && $student != 0) {
743
            $sql = "SELECT DISTINCT u.user_id FROM $user_table u $urlJoin
744
                    WHERE status = '5' $urlCondition $whereUsersInGroup";
745
        }
746
747
        if ($teacher != 0 && $student != 0) {
748
            $sql = "SELECT DISTINCT u.user_id FROM $user_table u $urlJoin
749
                    WHERE 1 = 1 $urlCondition $whereUsersInGroup";
750
        }
751
752
        if (!isset($sql)) {
753
            return false;
754
        }
755
756
        if (!empty($language)) {
757
            //special condition because language was already treated for SQL insert before
758
            $sql .= " AND language = '".Database::escape_string($language)."' ";
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...
759
        }
760
761
        // Sent to active users.
762
        $sql .= " AND email <>'' AND active = 1 ";
763
764
        // Expiration date
765
        $sql .= " AND (expiration_date = '' OR expiration_date IS NULL OR expiration_date > '$now') ";
766
767
        if ((empty($teacher) || $teacher == '0') && (empty($student) || $student == '0')) {
768
            return true;
769
        }
770
771
        $userListToFilter = [];
772
        // @todo check if other filters will apply for the career/promotion option.
773
        if (isset($announcement->career_id) && !empty($announcement->career_id)) {
774
            $promotion = new Promotion();
775
            $promotionList = $promotion->get_all_promotions_by_career_id($announcement->career_id);
776
            if (isset($announcement->promotion_id) && !empty($announcement->promotion_id)) {
777
                $promotionList = [];
778
                $promotionList[] = $promotion->get($announcement->promotion_id);
779
            }
780
781
            if (!empty($promotionList)) {
782
                foreach ($promotionList as $promotion) {
783
                    $sessionList = SessionManager::get_all_sessions_by_promotion($promotion['id']);
784
                    foreach ($sessionList as $session) {
785
                        if ($teacher) {
786
                            $users = SessionManager::get_users_by_session($session['id'], 2);
787
                            if (!empty($users)) {
788
                                $userListToFilter = array_merge($users, $userListToFilter);
789
                            }
790
                        }
791
792
                        if ($student) {
793
                            $users = SessionManager::get_users_by_session($session['id'], 0);
794
                            if (!empty($users)) {
795
                                $userListToFilter = array_merge($users, $userListToFilter);
796
                            }
797
                        }
798
                    }
799
                }
800
            }
801
        }
802
803
        if (!empty($userListToFilter)) {
804
            $userListToFilter = array_column($userListToFilter, 'user_id');
805
            $userListToFilterToString = implode("', '", $userListToFilter);
806
            $sql .= " AND (u.user_id IN ('$userListToFilterToString') ) ";
807
        }
808
809
        $result = Database::query($sql);
810
        if ($result === false) {
811
            return false;
812
        }
813
814
        $message_sent = false;
815
        while ($row = Database::fetch_array($result, 'ASSOC')) {
816
            MessageManager::send_message_simple($row['user_id'], $title, $content);
817
            $message_sent = true;
818
        }
819
820
        // Minor validation to clean up the attachment files in the announcement
821
        if (!empty($_FILES)) {
822
            $attachments = $_FILES;
823
            foreach ($attachments as $attachment) {
824
                unlink($attachment['tmp_name']);
825
            }
826
        }
827
828
        return $message_sent; //true if at least one e-mail was sent
829
    }
830
831
    /**
832
     * Returns the group announcements where the user is subscribed.
833
     *
834
     * @param $userId
835
     * @param $visible
836
     *
837
     * @throws \Exception
838
     *
839
     * @return array
840
     */
841
    public static function getAnnouncementsForGroups($userId, $visible)
842
    {
843
        $userSelectedLanguage = Database::escape_string(api_get_interface_language());
844
        $tblSysAnnouncements = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
845
        $tblGrpAnnouncements = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
846
        $tblUsrGrp = Database::get_main_table(TABLE_USERGROUP_REL_USER);
847
        $now = api_get_utc_datetime();
848
849
        $sql = "SELECT sys_announcement.*
850
        FROM $tblSysAnnouncements AS sys_announcement
851
        INNER JOIN $tblGrpAnnouncements AS announcement_rel_group
852
            ON sys_announcement.id = announcement_rel_group.announcement_id
853
        INNER JOIN $tblUsrGrp AS usergroup_rel_user
854
            ON usergroup_rel_user.usergroup_id = announcement_rel_group.group_id
855
        WHERE
856
            usergroup_rel_user.user_id = $userId AND
857
            (sys_announcement.lang = '$userSelectedLanguage' OR sys_announcement.lang = '') AND
858
            ('$now' >= sys_announcement.date_start AND '$now' <= sys_announcement.date_end)";
859
        $sql .= self::getVisibilityCondition($visible);
860
        $result = Database::query($sql);
861
        $data = Database::store_result($result, 'ASSOC');
862
        Database::free_result($result);
863
864
        return $data;
865
    }
866
867
    /**
868
     * Displays announcements as an slideshow.
869
     *
870
     * @param string $visible see self::VISIBLE_* constants
871
     * @param int    $id      The identifier of the announcement to display
872
     *
873
     * @return string
874
     */
875
    public static function displayAnnouncementsSlider($visible, $id = null)
876
    {
877
        $user_selected_language = Database::escape_string(api_get_interface_language());
878
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
879
        $tblGrpAnnouncements = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
880
881
        $cut_size = 500;
882
        $now = api_get_utc_datetime();
883
        //Exclude announcement to groups
884
        $sql = "SELECT sys_announcement.*
885
            FROM $table as sys_announcement
886
            LEFT JOIN $tblGrpAnnouncements AS announcement_rel_group
887
                ON sys_announcement.id = announcement_rel_group.announcement_id
888
            WHERE
889
                (sys_announcement.lang = '$user_selected_language' OR sys_announcement.lang = '') AND
890
                ('$now' >= sys_announcement.date_start AND '$now' <= sys_announcement.date_end) AND
891
                announcement_rel_group.group_id is null";
892
893
        $sql .= self::getVisibilityCondition($visible);
894
895
        if (isset($id) && !empty($id)) {
896
            $id = (int) $id;
897
            $sql .= " AND id = $id ";
898
        }
899
900
        if (api_is_multiple_url_enabled()) {
901
            $current_url_id = api_get_current_access_url_id();
902
            $sql .= " AND access_url_id IN ('1', '$current_url_id') ";
903
        }
904
905
        $checkCareers = api_get_configuration_value('allow_careers_in_global_announcements') === true;
906
907
        $userId = api_get_user_id();
908
909
        $promotion = new Promotion();
910
        $sql .= ' ORDER BY date_start DESC';
911
        $result = Database::query($sql);
912
        $announcements = [];
913
        if (Database::num_rows($result) > 0) {
914
            while ($announcement = Database::fetch_object($result)) {
915
                if ($checkCareers && !empty($announcement->career_id)) {
916
                    $promotionList = [];
917
                    if (!empty($announcement->promotion_id)) {
918
                        $promotionList[] = $announcement->promotion_id;
919
                    } else {
920
                        $promotionList = $promotion->get_all_promotions_by_career_id($announcement->career_id);
921
                        if (!empty($promotionList)) {
922
                            $promotionList = array_column($promotionList, 'id');
923
                        }
924
                    }
925
926
                    $show = false;
927
                    foreach ($promotionList as $promotionId) {
928
                        $sessionList = SessionManager::get_all_sessions_by_promotion($promotionId);
929
                        foreach ($sessionList as $session) {
930
                            $sessionId = $session['id'];
931
                            // Check student
932
                            if ($visible === self::VISIBLE_STUDENT &&
933
                                SessionManager::isUserSubscribedAsStudent($sessionId, $userId)
934
                            ) {
935
                                $show = true;
936
                                break 2;
937
                            }
938
939
                            if ($visible === self::VISIBLE_TEACHER &&
940
                                SessionManager::user_is_general_coach($userId, $sessionId)
941
                            ) {
942
                                $show = true;
943
                                break 2;
944
                            }
945
946
                            // Check course coach
947
                            $coaches = SessionManager::getCoachesBySession($sessionId);
948
949
                            if ($visible === self::VISIBLE_TEACHER && in_array($userId, $coaches)) {
950
                                $show = true;
951
                                break 2;
952
                            }
953
                        }
954
                    }
955
956
                    if (false === $show) {
957
                        continue;
958
                    }
959
                }
960
961
                $announcementData = [
962
                    'id' => $announcement->id,
963
                    'title' => $announcement->title,
964
                    'content' => $announcement->content,
965
                    'readMore' => null,
966
                ];
967
968
                if (empty($id)) {
969
                    if (api_strlen(strip_tags($announcement->content)) > $cut_size) {
970
                        $announcementData['content'] = cut($announcement->content, $cut_size);
971
                        $announcementData['readMore'] = true;
972
                    }
973
                }
974
975
                $announcements[] = $announcementData;
976
            }
977
        }
978
979
        /** Show announcement of group */
980
        $announcementToGroup = self::getAnnouncementsForGroups($userId, $visible);
981
        $totalAnnouncementToGroup = count($announcementToGroup);
982
        for ($i = 0; $i < $totalAnnouncementToGroup; $i++) {
983
            $announcement = $announcementToGroup[$i];
984
            $announcementData = [
985
                'id' => $announcement['id'],
986
                'title' => $announcement['title'],
987
                'content' => $announcement['content'],
988
                'readMore' => null,
989
            ];
990
            $content = $announcement['content'];
991
            if (api_strlen(strip_tags($content)) > $cut_size) {
992
                $announcementData['content'] = cut($content, $cut_size);
993
                $announcementData['readMore'] = true;
994
            }
995
            $announcements[] = $announcementData;
996
        }
997
998
        if (count($announcements) === 0) {
999
            return null;
1000
        }
1001
        $template = new Template(null, false, false);
1002
        $template->assign('announcements', $announcements);
1003
        $layout = $template->get_template('announcement/slider.tpl');
1004
1005
        return $template->fetch($layout);
1006
    }
1007
1008
    /**
1009
     * Get the HTML code for an announcement.
1010
     *
1011
     * @param int $announcementId The announcement ID
1012
     * @param int $visibility     The announcement visibility
1013
     *
1014
     * @return string The HTML code
1015
     */
1016
    public static function displayAnnouncement($announcementId, $visibility)
1017
    {
1018
        $selectedUserLanguage = Database::escape_string(api_get_interface_language());
1019
        $announcementTable = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
1020
        $now = api_get_utc_datetime();
1021
        $announcementId = (int) $announcementId;
1022
1023
        $whereConditions = [
1024
            "(lang = ? OR lang IS NULL OR lang = '') " => $selectedUserLanguage,
1025
            "AND (? >= date_start AND ? <= date_end) " => [$now, $now],
1026
            "AND id = ? " => $announcementId,
1027
        ];
1028
1029
        $condition = self::getVisibilityCondition($visibility);
1030
        $whereConditions[$condition] = 1;
1031
1032
        if (api_is_multiple_url_enabled()) {
1033
            $whereConditions["AND access_url_id IN (1, ?) "] = api_get_current_access_url_id();
1034
        }
1035
1036
        $announcement = Database::select(
1037
            '*',
1038
            $announcementTable,
1039
            [
1040
                'where' => $whereConditions,
1041
                'order' => 'date_start',
1042
            ],
1043
            'first'
1044
        );
1045
1046
        $template = new Template(null, false, false);
1047
        $template->assign('announcement', $announcement);
1048
        $layout = $template->get_template('announcement/view.tpl');
1049
1050
        return $template->fetch($layout);
1051
    }
1052
1053
    /**
1054
     * @return bool
1055
     */
1056
    public static function newRolesActivated()
1057
    {
1058
        /* In order to use this option you need to run this SQL changes :
1059
         ALTER TABLE sys_announcement ADD COLUMN visible_drh INT DEFAULT 0;
1060
         ALTER TABLE sys_announcement ADD COLUMN visible_session_admin INT DEFAULT 0;
1061
         ALTER TABLE sys_announcement ADD COLUMN visible_boss INT DEFAULT 0;
1062
        */
1063
        return api_get_configuration_value('system_announce_extra_roles');
1064
    }
1065
1066
    /**
1067
     * @return string
1068
     */
1069
    public static function getCurrentUserVisibility()
1070
    {
1071
        if (api_is_anonymous()) {
1072
            return SystemAnnouncementManager::VISIBLE_GUEST;
1073
        }
1074
1075
        if (self::newRolesActivated()) {
1076
            if (api_is_student_boss()) {
1077
                return SystemAnnouncementManager::VISIBLE_STUDENT_BOSS;
1078
            }
1079
1080
            if (api_is_session_admin()) {
1081
                return SystemAnnouncementManager::VISIBLE_SESSION_ADMIN;
1082
            }
1083
1084
            if (api_is_drh()) {
1085
                return SystemAnnouncementManager::VISIBLE_DRH;
1086
            }
1087
1088
            if (api_is_teacher()) {
1089
                return SystemAnnouncementManager::VISIBLE_TEACHER;
1090
            } else {
1091
                return SystemAnnouncementManager::VISIBLE_STUDENT;
1092
            }
1093
        } else {
1094
            // Default behaviour
1095
            return api_is_teacher() ? SystemAnnouncementManager::VISIBLE_TEACHER : SystemAnnouncementManager::VISIBLE_STUDENT;
1096
        }
1097
    }
1098
}
1099