Passed
Push — master ( 3e71cc...8cb8bb )
by Julito
09:43
created

announcement_for_groups()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
1131
    {
1132
        /*$store_path = api_get_path(SYS_UPLOAD_PATH).'announcements';
1133
        $announcementPicture = $store_path.'/announcement_'.$announcementId.'.png';
1134
        if (file_exists($announcementPicture)) {
1135
            $web_path = api_get_path(WEB_UPLOAD_PATH).'announcements';
1136
            $urlPicture = $web_path.'/announcement_'.$announcementId.'.png';
1137
1138
            return $urlPicture;
1139
        }
1140
1141
        return null;*/
1142
    }
1143
}
1144