Passed
Push — master ( f5688d...87bc65 )
by Julito
09:49
created

SystemAnnouncementManager::displayAnnouncement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 21
nc 2
nop 2
dl 0
loc 34
rs 9.584
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class SystemAnnouncementManager.
6
 */
7
class SystemAnnouncementManager
8
{
9
    public const VISIBLE_GUEST = 'visible_guest';
10
    public const VISIBLE_STUDENT = 'visible_student';
11
    public const VISIBLE_TEACHER = 'visible_teacher';
12
    public const VISIBLE_DRH = 'visible_drh';
13
    public const VISIBLE_SESSION_ADMIN = 'visible_session_admin';
14
    public const VISIBLE_STUDENT_BOSS = 'visible_boss';
15
16
    /**
17
     * @return array
18
     */
19
    public static function getVisibilityList(): array
20
    {
21
        $visibleToUsers = [
22
            self::VISIBLE_TEACHER => get_lang('Teacher'),
23
            self::VISIBLE_STUDENT => get_lang('Student'),
24
            self::VISIBLE_GUEST => get_lang('Guest'),
25
        ];
26
        $visibleToUsers[self::VISIBLE_DRH] = get_lang('DRH');
27
        $visibleToUsers[self::VISIBLE_SESSION_ADMIN] = get_lang('SessionAdministrator');
28
        $visibleToUsers[self::VISIBLE_STUDENT_BOSS] = get_lang('StudentBoss');
29
30
        return $visibleToUsers;
31
    }
32
33
    /**
34
     * @param string $visibility
35
     *
36
     * @return string
37
     */
38
    public static function getVisibilityCondition($visibility)
39
    {
40
        $list = self::getVisibilityList();
41
        $visibilityCondition = " AND ".self::VISIBLE_GUEST." = 1 ";
42
        if (in_array($visibility, array_keys($list))) {
43
            $visibilityCondition = " AND $visibility = 1 ";
44
        }
45
46
        return $visibilityCondition;
47
    }
48
49
    /**
50
     * Displays all announcements.
51
     *
52
     * @param string $visibility VISIBLE_GUEST, VISIBLE_STUDENT or VISIBLE_TEACHER
53
     * @param int    $id         The identifier of the announcement to display
54
     */
55
    public static function display_announcements($visibility, $id = -1)
56
    {
57
        $user_selected_language = api_get_interface_language();
58
        $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
59
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
60
        $userGroup = new UserGroup();
61
62
        $temp_user_groups = $userGroup->get_groups_by_user(api_get_user_id(), 0);
63
        $groups = [];
64
        foreach ($temp_user_groups as $user_group) {
65
            $groups = array_merge($groups, [$user_group['id']]);
66
            $groups = array_merge(
67
                $groups,
68
                $userGroup->get_parent_groups($user_group['id'])
69
            );
70
        }
71
72
        $groups_string = '('.implode($groups, ',').')';
73
        $now = api_get_utc_datetime();
74
        $sql = "SELECT *, DATE_FORMAT(date_start,'%d-%m-%Y %h:%i:%s') AS display_date
75
                FROM  $db_table
76
                WHERE
77
                    (lang='$user_selected_language' OR lang IS NULL) AND
78
                    (('$now' BETWEEN date_start AND date_end) OR date_end='0000-00-00') ";
79
80
        $sql .= self::getVisibilityCondition($visibility);
81
82
        if (count($groups) > 0) {
83
            $sql .= " OR id IN (
84
                        SELECT announcement_id FROM $tbl_announcement_group
85
                        WHERE group_id in $groups_string
86
                    ) ";
87
        }
88
        $current_access_url_id = 1;
89
        if (api_is_multiple_url_enabled()) {
90
            $current_access_url_id = api_get_current_access_url_id();
91
        }
92
        $sql .= " AND access_url_id = '$current_access_url_id' ";
93
        $sql .= " ORDER BY date_start DESC LIMIT 0,7";
94
95
        $announcements = Database::query($sql);
96
        if (Database::num_rows($announcements) > 0) {
97
            $query_string = ereg_replace('announcement=[1-9]+', '', $_SERVER['QUERY_STRING']);
0 ignored issues
show
Deprecated Code introduced by
The function ereg_replace() has been deprecated: 5.3.0 Use preg_replace() instead ( Ignorable by Annotation )

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

97
            $query_string = /** @scrutinizer ignore-deprecated */ ereg_replace('announcement=[1-9]+', '', $_SERVER['QUERY_STRING']);

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

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

Loading history...
98
            $query_string = ereg_replace('&$', '', $query_string);
0 ignored issues
show
Deprecated Code introduced by
The function ereg_replace() has been deprecated: 5.3.0 Use preg_replace() instead ( Ignorable by Annotation )

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

98
            $query_string = /** @scrutinizer ignore-deprecated */ ereg_replace('&$', '', $query_string);

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

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

Loading history...
99
            $url = api_get_self();
100
            echo '<div class="system_announcements">';
101
            echo '<h3>'.get_lang('SystemAnnouncements').'</h3>';
102
            echo '<div style="margin:10px;text-align:right;"><a href="news_list.php">'.get_lang('More').'</a></div>';
103
104
            while ($announcement = Database::fetch_object($announcements)) {
105
                if ($id != $announcement->id) {
106
                    if (strlen($query_string) > 0) {
107
                        $show_url = 'news_list.php#'.$announcement->id;
108
                    } else {
109
                        $show_url = 'news_list.php#'.$announcement->id;
110
                    }
111
                    $display_date = api_convert_and_format_date($announcement->display_date, DATE_FORMAT_LONG);
112
                    echo '<a name="'.$announcement->id.'"></a>
113
                        <div class="system_announcement">
114
                            <div class="system_announcement_title">
115
                                <a name="ann'.$announcement->id.'" href="'.$show_url.'">'.
116
                                $announcement->title.'</a>
117
                            </div>
118
                            <div class="system_announcement_date">'.$display_date.'</div>
119
                        </div>';
120
                } else {
121
                    echo '<div class="system_announcement">
122
                            <div class="system_announcement_title">'
123
                                .$announcement->display_date.'
124
                                <a name="ann'.$announcement->id.'" href="'.$url.'?'.$query_string.'#ann'.$announcement->id.'">'.
125
                                    $announcement->title.'
126
                                </a>
127
                            </div>';
128
                }
129
                echo '<br />';
130
            }
131
            echo '</div>';
132
        }
133
    }
134
135
    /**
136
     * @param string $visibility
137
     * @param int    $id
138
     * @param int    $start
139
     * @param string $user_id
140
     *
141
     * @return string
142
     */
143
    public static function displayAllAnnouncements(
144
        $visibility,
145
        $id = -1,
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

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

145
        /** @scrutinizer ignore-unused */ $id = -1,

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

Loading history...
146
        $start = 0,
147
        $user_id = ''
148
    ) {
149
        $user_selected_language = api_get_interface_language();
150
        $start = intval($start);
151
        $userGroup = new UserGroup();
152
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
153
        $temp_user_groups = $userGroup->get_groups_by_user(api_get_user_id(), 0);
154
        $groups = [];
155
        foreach ($temp_user_groups as $user_group) {
156
            $groups = array_merge($groups, [$user_group['id']]);
157
            $groups = array_merge($groups, $userGroup->get_parent_groups($user_group['id']));
158
        }
159
160
        // Checks if tables exists to not break platform not updated
161
        $groups_string = '('.implode($groups, ',').')';
162
163
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
164
        $now = api_get_utc_datetime();
165
166
        $sql = "SELECT * FROM $table
167
                WHERE
168
                    (lang = '$user_selected_language' OR lang IS NULL) AND
169
                    ( '$now' >= date_start AND '$now' <= date_end) ";
170
171
        $sql .= self::getVisibilityCondition($visibility);
172
173
        if (count($groups) > 0) {
174
            $sql .= " OR id IN (
175
                    SELECT announcement_id FROM $tbl_announcement_group
176
                    WHERE group_id in $groups_string
177
                    ) ";
178
        }
179
180
        if (api_is_multiple_url_enabled()) {
181
            $current_access_url_id = api_get_current_access_url_id();
182
            $sql .= " AND access_url_id IN ('1', '$current_access_url_id')";
183
        }
184
185
        if (!isset($_GET['start']) || $_GET['start'] == 0) {
186
            $sql .= " ORDER BY date_start DESC LIMIT ".$start.",20";
187
        } else {
188
            $sql .= " ORDER BY date_start DESC LIMIT ".($start + 1).",20";
189
        }
190
        $announcements = Database::query($sql);
191
        $content = '';
192
        if (Database::num_rows($announcements) > 0) {
193
            $content .= '<div class="system_announcements">';
194
            $content .= '<h3>'.get_lang('SystemAnnouncements').'</h3>';
195
            $content .= '<table align="center">';
196
            $content .= '<tr>';
197
            $content .= '<td>';
198
            $content .= self::display_arrow($user_id);
199
            $content .= '</td>';
200
            $content .= '</tr>';
201
            $content .= '</table>';
202
            $content .= '<table align="center" border="0" width="900px">';
203
            while ($announcement = Database::fetch_object($announcements)) {
204
                $display_date = api_convert_and_format_date($announcement->display_date, DATE_FORMAT_LONG);
205
                $content .= '<tr><td>';
206
                $content .= '<a name="'.$announcement->id.'"></a>
207
                        <div class="system_announcement">
208
                        <h2>'.$announcement->title.'</h2>
209
                        <div class="system_announcement_date">'.$display_date.'</div>
210
                        <br />
211
                        <div class="system_announcement_content">'
212
                            .$announcement->content.'
213
                        </div>
214
                      </div><br />';
215
                $content .= '</tr></td>';
216
            }
217
            $content .= '</table>';
218
219
            $content .= '<table align="center">';
220
            $content .= '<tr>';
221
            $content .= '<td>';
222
            $content .= self::display_arrow($user_id);
223
            $content .= '</td>';
224
            $content .= '</tr>';
225
            $content .= '</table>';
226
            $content .= '</div>';
227
        }
228
229
        return $content;
230
    }
231
232
    /**
233
     * @param int $user_id
234
     *
235
     * @return string
236
     */
237
    public static function display_arrow($user_id)
238
    {
239
        $start = (int) $_GET['start'];
240
        $nb_announcement = self::count_nb_announcement($start, $user_id);
241
        $next = ((int) $_GET['start'] + 19);
242
        $prev = ((int) $_GET['start'] - 19);
243
        $content = '';
244
        if (!isset($_GET['start']) || $_GET['start'] == 0) {
245
            if ($nb_announcement > 20) {
246
                $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
247
            }
248
        } else {
249
            echo '<a href="news_list.php?start='.$prev.'"> << '.get_lang('Prev').'</a>';
250
            if ($nb_announcement > 20) {
251
                $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
252
            }
253
        }
254
255
        return $content;
256
    }
257
258
    /**
259
     * @param int    $start
260
     * @param string $user_id
261
     *
262
     * @return int
263
     */
264
    public static function count_nb_announcement($start = 0, $user_id = '')
0 ignored issues
show
Unused Code introduced by
The parameter $user_id is not used and could be removed. ( Ignorable by Annotation )

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

264
    public static function count_nb_announcement($start = 0, /** @scrutinizer ignore-unused */ $user_id = '')

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

Loading history...
265
    {
266
        $start = intval($start);
267
        $user_selected_language = api_get_interface_language();
268
        $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
269
        $sql = 'SELECT id FROM '.$db_table.'
270
                WHERE (lang="'.$user_selected_language.'" OR lang IS NULL) ';
271
272
        $visibility = self::getCurrentUserVisibility();
273
        $sql .= self::getVisibilityCondition($visibility);
274
275
        $current_access_url_id = 1;
276
        if (api_is_multiple_url_enabled()) {
277
            $current_access_url_id = api_get_current_access_url_id();
278
        }
279
        $sql .= " AND access_url_id = '$current_access_url_id' ";
280
        $sql .= 'LIMIT '.$start.', 21';
281
        $announcements = Database::query($sql);
282
        $i = 0;
283
        while ($rows = Database::fetch_array($announcements)) {
284
            $i++;
285
        }
286
287
        return $i;
288
    }
289
290
    /**
291
     * Get all announcements.
292
     *
293
     * @return array An array with all available system announcements (as php
294
     *               objects)
295
     */
296
    public static function get_all_announcements()
297
    {
298
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
299
        $now = api_get_utc_datetime();
300
        $sql = "SELECT *, IF ( '$now'  >= date_start AND '$now' <= date_end, '1', '0') AS visible
301
                FROM $table";
302
303
        $current_access_url_id = 1;
304
        if (api_is_multiple_url_enabled()) {
305
            $current_access_url_id = api_get_current_access_url_id();
306
        }
307
        $sql .= " WHERE access_url_id = '$current_access_url_id' ";
308
        $sql .= " ORDER BY date_start ASC";
309
310
        $result = Database::query($sql);
311
        $announcements = [];
312
        while ($announcement = Database::fetch_object($result)) {
313
            $announcements[] = $announcement;
314
        }
315
316
        return $announcements;
317
    }
318
319
    /**
320
     * Adds an announcement to the database.
321
     *
322
     * @param string $title           Title of the announcement
323
     * @param string $content         Content of the announcement
324
     * @param string $date_start      Start date (YYYY-MM-DD HH:II: SS)
325
     * @param string $date_end        End date (YYYY-MM-DD HH:II: SS)
326
     * @param array  $visibility
327
     * @param string $lang            The language for which the announvement should be shown. Leave null for all langages
328
     * @param int    $send_mail       Whether to send an e-mail to all users (1) or not (0)
329
     * @param bool   $add_to_calendar
330
     * @param bool   $sendEmailTest
331
     *
332
     * @return mixed insert_id on success, false on failure
333
     */
334
    public static function add_announcement(
335
        $title,
336
        $content,
337
        $date_start,
338
        $date_end,
339
        $visibility,
340
        $lang = '',
341
        $send_mail = 0,
342
        $add_to_calendar = false,
343
        $sendEmailTest = false
344
    ) {
345
        $original_content = $content;
346
        $a_dateS = explode(' ', $date_start);
347
        $a_arraySD = explode('-', $a_dateS[0]);
348
        $a_arraySH = explode(':', $a_dateS[1]);
349
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
350
351
        $a_dateE = explode(' ', $date_end);
352
        $a_arrayED = explode('-', $a_dateE[0]);
353
        $a_arrayEH = explode(':', $a_dateE[1]);
354
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
355
356
        $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
357
358
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
359
            Display::addFlash(
360
                Display::return_message(get_lang('InvalidStartDate'), 'warning')
361
            );
362
363
            return false;
364
        }
365
366
        if (($date_end_to_compare[1] ||
367
            $date_end_to_compare[2] ||
368
            $date_end_to_compare[0]) &&
369
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
370
        ) {
371
            Display::addFlash(
372
                Display::return_message(get_lang('InvalidEndDate'), 'warning')
373
            );
374
375
            return false;
376
        }
377
378
        if (strlen(trim($title)) == 0) {
379
            Display::addFlash(
380
                Display::return_message(get_lang('InvalidTitle'), 'warning')
381
            );
382
383
            return false;
384
        }
385
386
        $start = api_get_utc_datetime($date_start);
387
        $end = api_get_utc_datetime($date_end);
388
389
        //Fixing urls that are sent by email
390
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
391
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
392
        $content = str_replace(
393
            'src=\"'.api_get_path(REL_HOME_PATH),
394
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
395
            $content
396
        );
397
        $content = str_replace(
398
            'file='.api_get_path(REL_HOME_PATH),
399
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
400
            $content
401
        );
402
        $lang = is_null($lang) ? '' : $lang;
403
404
        $current_access_url_id = 1;
405
        if (api_is_multiple_url_enabled()) {
406
            $current_access_url_id = api_get_current_access_url_id();
407
        }
408
409
        $params = [
410
            'title' => $title,
411
            'content' => $content,
412
            'date_start' => $start,
413
            'date_end' => $end,
414
            'lang' => $lang,
415
            'access_url_id' => $current_access_url_id,
416
        ];
417
418
        foreach ($visibility as $key => $value) {
419
            $params[$key] = $value;
420
        }
421
422
        $resultId = Database::insert($db_table, $params);
423
424
        if ($resultId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $resultId of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
425
            if ($sendEmailTest) {
426
                self::send_system_announcement_by_email(
427
                    $title,
428
                    $content,
429
                    $visibility,
430
                    $lang,
431
                    true
432
                );
433
            } else {
434
                if ($send_mail == 1) {
435
                    self::send_system_announcement_by_email(
436
                        $title,
437
                        $content,
438
                        $visibility,
439
                        $lang
440
                    );
441
                }
442
            }
443
444
            if ($add_to_calendar) {
445
                $agenda = new Agenda('admin');
446
                $agenda->addEvent(
447
                    $date_start,
448
                    $date_end,
449
                    false,
450
                    $title,
451
                    $original_content
452
                );
453
            }
454
455
            return $resultId;
456
        }
457
458
        return false;
459
    }
460
461
    /**
462
     * Makes the announcement id visible only for groups in groups_array.
463
     *
464
     * @param int   $announcement_id
465
     * @param array $group_array     array of group id
466
     *
467
     * @return bool
468
     */
469
    public static function announcement_for_groups($announcement_id, $group_array)
470
    {
471
        $tbl_announcement_group = Database::get_main_table(
472
            TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS
473
        );
474
        //first delete all group associations for this announcement
475
        $res = Database::query(
476
            "DELETE FROM $tbl_announcement_group 
477
             WHERE announcement_id=".intval($announcement_id)
478
        );
479
480
        if ($res === false) {
481
            return false;
482
        }
483
484
        foreach ($group_array as $group_id) {
485
            if (intval($group_id) != 0) {
486
                $sql = "INSERT INTO $tbl_announcement_group SET
487
                        announcement_id=".intval($announcement_id).",
488
                        group_id=".intval($group_id);
489
                $res = Database::query($sql);
490
                if ($res === false) {
491
                    return false;
492
                }
493
            }
494
        }
495
496
        return true;
497
    }
498
499
    /**
500
     * Gets the groups of this announce.
501
     *
502
     * @param int announcement id
503
     *
504
     * @return array array of group id
505
     */
506
    public static function get_announcement_groups($announcement_id)
507
    {
508
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
509
        $tbl_group = Database::get_main_table(TABLE_USERGROUP);
510
        //first delete all group associations for this announcement
511
        $sql = "SELECT
512
                    g.id as group_id,
513
                    g.name as group_name
514
                FROM $tbl_group g , $tbl_announcement_group ag
515
                WHERE
516
                    announcement_id =".intval($announcement_id)." AND
517
                    ag.group_id = g.id";
518
        $res = Database::query($sql);
519
        $groups = Database::fetch_array($res);
520
521
        return $groups;
522
    }
523
524
    /**
525
     * Updates an announcement to the database.
526
     *
527
     * @param int    $id            of the announcement
528
     * @param string $title         title of the announcement
529
     * @param string $content       content of the announcement
530
     * @param array  $date_start    start date (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
531
     * @param array  $date_end      end date of (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
532
     * @param array  $visibility
533
     * @param array  $lang
534
     * @param int    $send_mail
535
     * @param bool   $sendEmailTest
536
     *
537
     * @return bool True on success, false on failure
538
     */
539
    public static function update_announcement(
540
        $id,
541
        $title,
542
        $content,
543
        $date_start,
544
        $date_end,
545
        $visibility,
546
        $lang = null,
547
        $send_mail = 0,
548
        $sendEmailTest = false
549
    ) {
550
        $em = Database::getManager();
551
        $announcement = $em->find('ChamiloCoreBundle:SysAnnouncement', $id);
552
        if (!$announcement) {
553
            return false;
554
        }
555
556
        $a_dateS = explode(' ', $date_start);
557
        $a_arraySD = explode('-', $a_dateS[0]);
558
        $a_arraySH = explode(':', $a_dateS[1]);
559
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
560
561
        $a_dateE = explode(' ', $date_end);
562
        $a_arrayED = explode('-', $a_dateE[0]);
563
        $a_arrayEH = explode(':', $a_dateE[1]);
564
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
565
566
        $lang = is_null($lang) ? '' : $lang;
567
568
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
569
            echo Display::return_message(get_lang('InvalidStartDate'));
570
571
            return false;
572
        }
573
574
        if (($date_end_to_compare[1] ||
575
            $date_end_to_compare[2] ||
576
            $date_end_to_compare[0]) &&
577
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
578
        ) {
579
            echo Display::return_message(get_lang('InvalidEndDate'));
580
581
            return false;
582
        }
583
584
        if (strlen(trim($title)) == 0) {
585
            echo Display::return_message(get_lang('InvalidTitle'));
586
587
            return false;
588
        }
589
590
        $start = api_get_utc_datetime($date_start);
591
        $end = api_get_utc_datetime($date_end);
592
593
        //Fixing urls that are sent by email
594
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
595
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
596
        $content = str_replace(
597
            'src=\"'.api_get_path(REL_HOME_PATH),
598
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
599
            $content
600
        );
601
        $content = str_replace(
602
            'file='.api_get_path(REL_HOME_PATH),
603
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
604
            $content
605
        );
606
607
        if ($sendEmailTest) {
608
            self::send_system_announcement_by_email(
609
                $title,
610
                $content,
611
                null,
612
                null,
613
                $lang,
614
                $sendEmailTest
615
            );
616
        } else {
617
            if ($send_mail == 1) {
618
                self::send_system_announcement_by_email(
619
                    $title,
620
                    $content,
621
                    $visibility,
622
                    $lang
0 ignored issues
show
Bug introduced by
It seems like $lang can also be of type array; however, parameter $language of SystemAnnouncementManage...announcement_by_email() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

622
                    /** @scrutinizer ignore-type */ $lang
Loading history...
623
                );
624
            }
625
        }
626
627
        $dateStart = new DateTime($start, new DateTimeZone('UTC'));
628
        $dateEnd = new DateTime($end, new DateTimeZone('UTC'));
629
630
        $announcement
631
            ->setLang($lang)
632
            ->setTitle($title)
633
            ->setContent($content)
634
            ->setDateStart($dateStart)
635
            ->setDateEnd($dateEnd)
636
            /*->setVisibleTeacher($visible_teacher)
637
            ->setVisibleStudent($visible_student)
638
            ->setVisibleGuest($visible_guest)*/
639
            ->setAccessUrlId(api_get_current_access_url_id());
640
641
        $em->merge($announcement);
642
        $em->flush();
643
644
        // Update visibility
645
        $list = self::getVisibilityList();
646
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
647
        foreach ($list as $key => $title) {
0 ignored issues
show
introduced by
$title is overwriting one of the parameters of this function.
Loading history...
648
            $value = isset($visibility[$key]) && $visibility[$key] ? 1 : 0;
649
            $sql = "UPDATE $table SET $key = '$value' WHERE id = $id";
650
            Database::query($sql);
651
        }
652
653
        return true;
654
    }
655
656
    /**
657
     * Deletes an announcement.
658
     *
659
     * @param int $id The identifier of the announcement that should be
660
     *
661
     * @return bool True on success, false on failure
662
     */
663
    public static function delete_announcement($id)
664
    {
665
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
666
        $id = intval($id);
667
        $sql = "DELETE FROM $table WHERE id =".$id;
668
        $res = Database::query($sql);
669
        if ($res === false) {
670
            return false;
671
        }
672
673
        return true;
674
    }
675
676
    /**
677
     * Gets an announcement.
678
     *
679
     * @param int $id The identifier of the announcement that should be
680
     *
681
     * @return object Object of class StdClass or the required class, containing the query result row
682
     */
683
    public static function get_announcement($id)
684
    {
685
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
686
        $id = intval($id);
687
        $sql = "SELECT * FROM ".$table." WHERE id = ".$id;
688
        $announcement = Database::fetch_object(Database::query($sql));
689
690
        return $announcement;
691
    }
692
693
    /**
694
     * Change the visibility of an announcement.
695
     *
696
     * @param int  $id
697
     * @param int  $user    For who should the visibility be changed
698
     * @param bool $visible
699
     *
700
     * @return bool True on success, false on failure
701
     */
702
    public static function set_visibility($id, $user, $visible)
703
    {
704
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
705
        $id = (int) $id;
706
        $list = array_keys(self::getVisibilityList());
707
        $user = trim($user);
708
        $visible = (int) $visible;
709
        if (!in_array($user, $list)) {
710
            return false;
711
        }
712
713
        $field = $user;
714
        $sql = "UPDATE $table SET ".$field." = '".$visible."'
715
                WHERE id='".$id."'";
716
        $res = Database::query($sql);
717
718
        if ($res === false) {
719
            return false;
720
        }
721
722
        return true;
723
    }
724
725
    /**
726
     * Send a system announcement by e-mail to all teachers/students depending on parameters.
727
     *
728
     * @param string $title
729
     * @param string $content
730
     * @param array  $visibility
731
     * @param string $language      Language (optional, considered for all languages if left empty)
732
     * @param bool   $sendEmailTest
733
     *
734
     * @return bool True if the message was sent or there was no destination matching.
735
     *              False on database or e-mail sending error.
736
     */
737
    public static function send_system_announcement_by_email(
738
        $title,
739
        $content,
740
        $visibility,
741
        $language = null,
742
        $sendEmailTest = false
743
    ) {
744
        $content = str_replace(['\r\n', '\n', '\r'], '', $content);
745
        $now = api_get_utc_datetime();
746
        $teacher = $visibility['visible_teacher'];
747
        $student = $visibility['visible_student'];
748
        if ($sendEmailTest) {
749
            MessageManager::send_message_simple(api_get_user_id(), $title, $content);
750
751
            return true;
752
        }
753
754
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
755
        if (api_is_multiple_url_enabled()) {
756
            $current_access_url_id = api_get_current_access_url_id();
757
            $url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
758
            $url_condition = " INNER JOIN $url_rel_user uu ON uu.user_id = u.user_id ";
759
        }
760
761
        if ($teacher != 0 && $student == 0) {
762
            $sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition 
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $url_condition does not seem to be defined for all execution paths leading up to this point.
Loading history...
763
                    WHERE status = '1' ";
764
        }
765
766
        if ($teacher == 0 && $student != 0) {
767
            $sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition 
768
                    WHERE status = '5' ";
769
        }
770
771
        if ($teacher != 0 && $student != 0) {
772
            $sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition 
773
                    WHERE 1 = 1 ";
774
        }
775
776
        if (!empty($language)) {
777
            //special condition because language was already treated for SQL insert before
778
            $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...
779
        }
780
781
        if (api_is_multiple_url_enabled()) {
782
            $sql .= " AND access_url_id = '".$current_access_url_id."' ";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $current_access_url_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
783
        }
784
785
        // Sent to active users.
786
        $sql .= " AND email <>'' AND active = 1 ";
787
788
        // Expiration date
789
        $sql .= " AND (expiration_date = '' OR expiration_date IS NULL OR expiration_date > '$now') ";
790
791
        if ((empty($teacher) || $teacher == '0') && (empty($student) || $student == '0')) {
792
            return true;
793
        }
794
795
        $result = Database::query($sql);
796
        if ($result === false) {
797
            return false;
798
        }
799
800
        $message_sent = false;
801
        while ($row = Database::fetch_array($result, 'ASSOC')) {
802
            MessageManager::send_message_simple($row['user_id'], $title, $content);
803
            $message_sent = true;
804
        }
805
806
        // Minor validation to clean up the attachment files in the announcement
807
        if (!empty($_FILES)) {
808
            $attachments = $_FILES;
809
            foreach ($attachments as $attachment) {
810
                unlink($attachment['tmp_name']);
811
            }
812
        }
813
814
        return $message_sent; //true if at least one e-mail was sent
815
    }
816
817
    /**
818
     * Displays announcements as an slideshow.
819
     *
820
     * @param string $visible see self::VISIBLE_* constants
821
     * @param int    $id      The identifier of the announcement to display
822
     *
823
     * @return array
824
     */
825
    public static function getAnnouncements($visible, $id = null) : array
826
    {
827
        $user_selected_language = Database::escape_string(api_get_interface_language());
828
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
829
830
        $cut_size = 500;
831
        $now = api_get_utc_datetime();
832
        $sql = "SELECT * FROM $table
833
                WHERE
834
                    (lang = '$user_selected_language' OR lang = '') AND
835
                    ('$now' >= date_start AND '$now' <= date_end) ";
836
837
        $sql .= self::getVisibilityCondition($visible);
838
839
        if (isset($id) && !empty($id)) {
840
            $id = (int) $id;
841
            $sql .= " AND id = $id ";
842
        }
843
844
        if (api_is_multiple_url_enabled()) {
845
            $current_url_id = api_get_current_access_url_id();
846
            $sql .= " AND access_url_id IN ('1', '$current_url_id') ";
847
        }
848
849
        $sql .= ' ORDER BY date_start DESC';
850
        $result = Database::query($sql);
851
        $announcements = [];
852
853
        if (Database::num_rows($result) > 0) {
854
            while ($announcement = Database::fetch_object($result)) {
855
                $announcementData = [
856
                    'id' => $announcement->id,
857
                    'title' => $announcement->title,
858
                    'content' => $announcement->content,
859
                    'readMore' => null,
860
                ];
861
862
                if (empty($id)) {
863
                    if (api_strlen(strip_tags($announcement->content)) > $cut_size) {
864
                        $announcementData['content'] = cut($announcement->content, $cut_size);
865
                        $announcementData['readMore'] = true;
866
                    }
867
                }
868
869
                $announcements[] = $announcementData;
870
            }
871
        }
872
873
        if (count($announcements) === 0) {
874
            return [];
875
        }
876
877
        return $announcements;
878
    }
879
880
    /**
881
     * Get the HTML code for an announcement.
882
     *
883
     * @param int $announcementId The announcement ID
884
     * @param int $visibility     The announcement visibility
885
     *
886
     * @return array
887
     */
888
    public static function getAnnouncement($announcementId, $visibility): array
889
    {
890
        $selectedUserLanguage = Database::escape_string(api_get_interface_language());
891
        $announcementTable = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
892
        $now = api_get_utc_datetime();
893
        $announcementId = (int) $announcementId;
894
895
        $whereConditions = [
896
            "(lang = ? OR lang IS NULL OR lang = '') " => $selectedUserLanguage,
897
            "AND (? >= date_start AND ? <= date_end) " => [$now, $now],
898
            "AND id = ? " => $announcementId,
899
        ];
900
901
        $condition = self::getVisibilityCondition($visibility);
902
        $whereConditions[$condition] = 1;
903
904
        if (api_is_multiple_url_enabled()) {
905
            $whereConditions["AND access_url_id IN (1, ?) "] = api_get_current_access_url_id();
906
        }
907
908
        $announcement = Database::select(
909
            '*',
910
            $announcementTable,
911
            [
912
                'where' => $whereConditions,
913
                'order' => 'date_start',
914
            ],
915
            'first'
916
        );
917
918
        return $announcement;
919
    }
920
921
922
    /**
923
     * @return string
924
     */
925
    public static function getCurrentUserVisibility()
926
    {
927
        if (api_is_anonymous()) {
928
            return self::VISIBLE_GUEST;
929
        }
930
931
        if (api_is_student_boss()) {
932
            return self::VISIBLE_STUDENT_BOSS;
933
        }
934
935
        if (api_is_session_admin()) {
936
            return self::VISIBLE_SESSION_ADMIN;
937
        }
938
939
        if (api_is_drh()) {
940
            return self::VISIBLE_DRH;
941
        }
942
943
        if (api_is_teacher()) {
944
            return self::VISIBLE_TEACHER;
945
        } else {
946
            return self::VISIBLE_STUDENT;
947
        }
948
    }
949
}
950