Passed
Push — master ( 1a7924...8ee120 )
by Julito
11:25
created

getVisibilityCondition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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