Passed
Push — master ( 8ee120...ab271d )
by Julito
09:45
created

SystemAnnouncementManager   F

Complexity

Total Complexity 113

Size/Duplication

Total Lines 1047
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 481
dl 0
loc 1047
rs 2
c 0
b 0
f 0
wmc 113

20 Methods

Rating   Name   Duplication   Size   Complexity  
B display_announcements() 0 71 7
A getVisibilityList() 0 9 1
A update_announcements_picture() 0 7 2
B displayAllAnnouncements() 0 87 8
A display_arrow() 0 19 5
A getVisibilityCondition() 0 9 2
A count_nb_announcement() 0 24 3
A deleteAnnouncementPicture() 0 2 1
A getPictureAnnouncement() 0 2 1
A delete_announcement() 0 12 2
C update_announcement() 0 115 13
A set_visibility() 0 21 3
A announcement_for_groups() 0 28 5
A get_announcement_groups() 0 16 1
A getAnnouncement() 0 31 2
D getAnnouncements() 0 103 22
C add_announcement() 0 126 14
A get_announcement() 0 8 1
C send_system_announcement_by_email() 0 94 14
A getCurrentUserVisibility() 0 22 6

How to fix   Complexity   

Complex Class

Complex classes like SystemAnnouncementManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

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

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

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
344
     *                                langages
345
     * @param int    $send_mail       Whether to send an e-mail to all users (1) or not (0)
346
     * @param bool   $add_to_calendar
347
     * @param bool   $sendEmailTest
348
     * @param int    $careerId
349
     * @param int    $promotionId
350
     *
351
     * @return mixed insert_id on success, false on failure
352
     */
353
    public static function add_announcement(
354
        $title,
355
        $content,
356
        $date_start,
357
        $date_end,
358
        $visibility,
359
        $lang = '',
360
        $send_mail = 0,
361
        $add_to_calendar = false,
362
        $sendEmailTest = false,
363
        $careerId = 0,
364
        $promotionId = 0
365
    ) {
366
        $original_content = $content;
367
        $a_dateS = explode(' ', $date_start);
368
        $a_arraySD = explode('-', $a_dateS[0]);
369
        $a_arraySH = explode(':', $a_dateS[1]);
370
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
371
372
        $a_dateE = explode(' ', $date_end);
373
        $a_arrayED = explode('-', $a_dateE[0]);
374
        $a_arrayEH = explode(':', $a_dateE[1]);
375
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
376
377
        $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
378
379
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
380
            Display::addFlash(
381
                Display::return_message(get_lang('Invalid start date was given.'), 'warning')
382
            );
383
384
            return false;
385
        }
386
387
        if (($date_end_to_compare[1] ||
388
                $date_end_to_compare[2] ||
389
                $date_end_to_compare[0]) &&
390
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
391
        ) {
392
            Display::addFlash(
393
                Display::return_message(get_lang('Invalid end date was given.'), 'warning')
394
            );
395
396
            return false;
397
        }
398
399
        if (0 == strlen(trim($title))) {
400
            Display::addFlash(
401
                Display::return_message(get_lang('Please enter a title'), 'warning')
402
            );
403
404
            return false;
405
        }
406
407
        $start = api_get_utc_datetime($date_start, null, true);
408
        $end = api_get_utc_datetime($date_end, null, true);
409
410
        //Fixing urls that are sent by email
411
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
412
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
413
        $content = str_replace(
414
            'src=\"'.api_get_path(REL_HOME_PATH),
415
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
416
            $content
417
        );
418
        $content = str_replace(
419
            'file='.api_get_path(REL_HOME_PATH),
420
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
421
            $content
422
        );
423
        $lang = is_null($lang) ? '' : $lang;
424
425
        $sysRepo = Container::getSysAnnouncementRepository();
426
427
        $sysAnnouncement = (new SysAnnouncement())
428
            ->setTitle($title)
429
            ->setContent($content)
430
            ->setDateStart($start)
431
            ->setDateEnd($end)
432
            ->setLang($lang)
433
            ->setUrl(api_get_url_entity())
434
            ->setRoles($visibility)
435
        ;
436
437
        if (api_get_configuration_value('allow_careers_in_global_announcements') && !empty($careerId)) {
438
            $careerRepo = Container::getCareerRepository();
439
            $sysAnnouncement->setCareer($careerRepo->find($careerId));
440
441
            $promotionRepo = Container::getPromotionRepository();
442
            $sysAnnouncement->setPromotion($promotionRepo->find($promotionId));
443
        }
444
445
        $sysRepo->update($sysAnnouncement);
446
        $resultId = $sysAnnouncement->getId();
447
448
        if ($resultId) {
449
            if ($sendEmailTest) {
450
                self::send_system_announcement_by_email(
451
                    $sysAnnouncement,
452
                    $visibility,
453
                    true
454
                );
455
            } else {
456
                if (1 == $send_mail) {
457
                    self::send_system_announcement_by_email(
458
                        $sysAnnouncement,
459
                        $visibility
460
                    );
461
                }
462
            }
463
464
            if ($add_to_calendar) {
465
                $agenda = new Agenda('admin');
466
                $agenda->addEvent(
467
                    $date_start,
468
                    $date_end,
469
                    false,
470
                    $title,
471
                    $original_content
472
                );
473
            }
474
475
            return $resultId;
476
        }
477
478
        return false;
479
    }
480
481
    /**
482
     * Makes the announcement id visible only for groups in groups_array.
483
     *
484
     * @param int   $announcement_id
485
     * @param array $group_array     array of group id
486
     *
487
     * @return bool
488
     */
489
    public static function announcement_for_groups($announcement_id, $group_array)
490
    {
491
        $tbl_announcement_group = Database::get_main_table(
492
            TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS
493
        );
494
        //first delete all group associations for this announcement
495
        $res = Database::query(
496
            "DELETE FROM $tbl_announcement_group
497
             WHERE announcement_id=".intval($announcement_id)
498
        );
499
500
        if (false === $res) {
501
            return false;
502
        }
503
504
        foreach ($group_array as $group_id) {
505
            if (0 != intval($group_id)) {
506
                $sql = "INSERT INTO $tbl_announcement_group SET
507
                        announcement_id=".intval($announcement_id).",
508
                        group_id=".intval($group_id);
509
                $res = Database::query($sql);
510
                if (false === $res) {
511
                    return false;
512
                }
513
            }
514
        }
515
516
        return true;
517
    }
518
519
    /**
520
     * Gets the groups of this announce.
521
     *
522
     * @param int announcement id
523
     *
524
     * @return array array of group id
525
     */
526
    public static function get_announcement_groups($announcement_id)
527
    {
528
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
529
        $tbl_group = Database::get_main_table(TABLE_USERGROUP);
530
        //first delete all group associations for this announcement
531
        $sql = "SELECT
532
                    g.id as group_id,
533
                    g.name as group_name
534
                FROM $tbl_group g , $tbl_announcement_group ag
535
                WHERE
536
                    announcement_id =".intval($announcement_id)." AND
537
                    ag.group_id = g.id";
538
        $res = Database::query($sql);
539
        $groups = Database::fetch_array($res);
540
541
        return $groups;
542
    }
543
544
    /**
545
     * Updates an announcement to the database.
546
     *
547
     * @param int    $id            of the announcement
548
     * @param string $title         title of the announcement
549
     * @param string $content       content of the announcement
550
     * @param array  $date_start    start date (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
551
     * @param array  $date_end      end date of (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
552
     * @param array  $visibility
553
     * @param array  $lang
554
     * @param int    $send_mail
555
     * @param bool   $sendEmailTest
556
     * @param int    $careerId
557
     * @param int    $promotionId
558
     *
559
     * @return bool True on success, false on failure
560
     */
561
    public static function update_announcement(
562
        $id,
563
        $title,
564
        $content,
565
        $date_start,
566
        $date_end,
567
        $visibility,
568
        $lang = null,
569
        $send_mail = 0,
570
        $sendEmailTest = false,
571
        $careerId = 0,
572
        $promotionId = 0
573
    ) {
574
        $sysRepo = Container::getSysAnnouncementRepository();
575
        /** @var SysAnnouncement $announcement */
576
        $announcement = $sysRepo->find($id);
577
        if (null === $announcement) {
578
            return false;
579
        }
580
581
        $a_dateS = explode(' ', $date_start);
582
        $a_arraySD = explode('-', $a_dateS[0]);
583
        $a_arraySH = explode(':', $a_dateS[1]);
584
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
585
586
        $a_dateE = explode(' ', $date_end);
587
        $a_arrayED = explode('-', $a_dateE[0]);
588
        $a_arrayEH = explode(':', $a_dateE[1]);
589
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
590
591
        $lang = is_null($lang) ? '' : $lang;
592
593
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
594
            echo Display::return_message(get_lang('Invalid start date was given.'));
595
596
            return false;
597
        }
598
599
        if (($date_end_to_compare[1] ||
600
                $date_end_to_compare[2] ||
601
                $date_end_to_compare[0]) &&
602
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
603
        ) {
604
            echo Display::return_message(get_lang('Invalid end date was given.'));
605
606
            return false;
607
        }
608
609
        if (0 == strlen(trim($title))) {
610
            echo Display::return_message(get_lang('Please enter a title'));
611
612
            return false;
613
        }
614
615
        $start = api_get_utc_datetime($date_start);
616
        $end = api_get_utc_datetime($date_end);
617
618
        //Fixing urls that are sent by email
619
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
620
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
621
        $content = str_replace(
622
            'src=\"'.api_get_path(REL_HOME_PATH),
623
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
624
            $content
625
        );
626
        $content = str_replace(
627
            'file='.api_get_path(REL_HOME_PATH),
628
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
629
            $content
630
        );
631
632
        $dateStart = new DateTime($start, new DateTimeZone('UTC'));
633
        $dateEnd = new DateTime($end, new DateTimeZone('UTC'));
634
635
        $announcement
636
            ->setLang($lang)
637
            ->setTitle($title)
638
            ->setContent($content)
639
            ->setDateStart($dateStart)
640
            ->setDateEnd($dateEnd)
641
            ->setRoles($visibility)
642
        ;
643
644
       $sysRepo->update($announcement);
645
646
        // Update visibility
647
        //$list = self::getVisibilityList();
648
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
649
650
        if (api_get_configuration_value('allow_careers_in_global_announcements') && !empty($careerId)) {
651
            $params = [];
652
            $params['career_id'] = (int) $careerId;
653
            $params['promotion_id'] = (int) $promotionId;
654
            Database::update(
655
                $table,
656
                $params,
657
                ['id = ? ' => $id]
658
            );
659
        }
660
661
        /*foreach ($list as $key => $title) {
662
            $value = isset($visibility[$key]) && $visibility[$key] ? 1 : 0;
663
            $sql = "UPDATE $table SET $key = '$value' WHERE id = $id";
664
            Database::query($sql);
665
        }*/
666
667
        if ($sendEmailTest) {
668
            self::send_system_announcement_by_email($announcement, true);
669
        } else {
670
            if (1 == $send_mail) {
671
                self::send_system_announcement_by_email($announcement);
672
            }
673
        }
674
675
        return true;
676
    }
677
678
    /**
679
     * Deletes an announcement.
680
     *
681
     * @param int $id The identifier of the announcement that should be
682
     *
683
     * @return bool True on success, false on failure
684
     */
685
    public static function delete_announcement($id)
686
    {
687
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
688
        $id = (int) $id;
689
        $sql = "DELETE FROM $table WHERE id =".$id;
690
        $res = Database::query($sql);
691
        if (false === $res) {
692
            return false;
693
        }
694
        self::deleteAnnouncementPicture($id);
695
696
        return true;
697
    }
698
699
    /**
700
     * Gets an announcement.
701
     *
702
     * @param int $id The identifier of the announcement that should be
703
     *
704
     * @return object Object of class StdClass or the required class, containing the query result row
705
     */
706
    public static function get_announcement($id)
707
    {
708
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
709
        $id = (int) $id;
710
        $sql = "SELECT * FROM ".$table." WHERE id = ".$id;
711
        $announcement = Database::fetch_object(Database::query($sql));
712
713
        return $announcement;
714
    }
715
716
    /**
717
     * Change the visibility of an announcement.
718
     *
719
     * @param int  $id
720
     * @param int  $user    For who should the visibility be changed
721
     * @param bool $visible
722
     *
723
     * @return bool True on success, false on failure
724
     */
725
    public static function set_visibility($id, $user, $visible)
726
    {
727
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
728
        $id = (int) $id;
729
        $list = array_keys(self::getVisibilityList());
730
        $user = trim($user);
731
        $visible = (int) $visible;
732
        if (!in_array($user, $list)) {
733
            return false;
734
        }
735
736
        $field = $user;
737
        $sql = "UPDATE $table SET ".$field." = '".$visible."'
738
                WHERE id='".$id."'";
739
        $res = Database::query($sql);
740
741
        if (false === $res) {
742
            return false;
743
        }
744
745
        return true;
746
    }
747
748
    /**
749
     * Send a system announcement by e-mail to all teachers/students depending on parameters.
750
     *
751
     * @return bool True if the message was sent or there was no destination matching.
752
     *              False on database or e-mail sending error.
753
     */
754
    public static function send_system_announcement_by_email(SysAnnouncement $announcement, bool $sendEmailTest = false)
755
    {
756
        $title = $announcement->getTitle();
757
        $content = $announcement->getContent();
758
        $language = $announcement->getLang();
759
760
        $content = str_replace(['\r\n', '\n', '\r'], '', $content);
761
        $now = api_get_utc_datetime();
762
763
        if ($sendEmailTest) {
764
            MessageManager::send_message_simple(api_get_user_id(), $title, $content);
765
766
            return true;
767
        }
768
769
        $repo = Container::getUserRepository();
770
        $qb = $repo->addRoleListQueryBuilder($announcement->getRoles());
771
        $repo->addAccessUrlQueryBuilder(api_get_current_access_url_id(), $qb);
772
773
        if (!empty($language)) {
774
            $qb
775
                ->andWhere('u.locale = :lang')
776
                ->setParameter('lang', $language)
777
            ;
778
        }
779
780
        $repo->addActiveAndNotAnonUserQueryBuilder($qb);
781
        $repo->addExpirationDateQueryBuilder($qb);
782
783
        // Sent to active users.
784
        //$sql .= " AND email <>'' AND active = 1 ";
785
786
        // Expiration date
787
        //$sql .= " AND (expiration_date = '' OR expiration_date IS NULL OR expiration_date > '$now') ";
788
789
        $userListToFilter = [];
790
        // @todo check if other filters will apply for the career/promotion option.
791
        if (null !== $announcement->getCareer()) {
792
            $promotion = new Promotion();
793
            $promotionList = $promotion->get_all_promotions_by_career_id($announcement->getCareer()->getId());
794
            if (null !== $announcement->getPromotion()) {
795
                $promotionList = [];
796
                $promotionList[] = $promotion->get($announcement->getPromotion()->getId());
797
            }
798
799
            if (!empty($promotionList)) {
800
                foreach ($promotionList as $promotion) {
801
                    $sessionList = SessionManager::get_all_sessions_by_promotion($promotion['id']);
802
                    foreach ($sessionList as $session) {
803
                        if (in_array('ROLE_TEACHER', $announcement->getRoles(), true)) {
804
                            $users = SessionManager::get_users_by_session($session['id'], 2);
805
                            if (!empty($users)) {
806
                                $userListToFilter = array_merge($users, $userListToFilter);
807
                            }
808
                        }
809
810
                        if (in_array('ROLE_STUDENT', $announcement->getRoles(), true)) {
811
                            $users = SessionManager::get_users_by_session($session['id'], 0);
812
                            if (!empty($users)) {
813
                                $userListToFilter = array_merge($users, $userListToFilter);
814
                            }
815
                        }
816
                    }
817
                }
818
            }
819
        }
820
821
        if (!empty($userListToFilter)) {
822
            $userListToFilter = array_column($userListToFilter, 'user_id');
823
            //$userListToFilterToString = implode("', '", $userListToFilter);
824
            $qb
825
                ->andWhere('u.id IN (:users)')
826
                ->setParameter('users', $userListToFilter)
827
            ;
828
            //$sql .= " AND (u.user_id IN ('$userListToFilterToString') ) ";
829
        }
830
        $users = $qb->getQuery()->getResult();
831
832
        $message_sent = false;
833
        /** @var \Chamilo\CoreBundle\Entity\User $user */
834
        foreach ($users as $user) {
835
            MessageManager::send_message_simple($user->getId(), $title, $content);
836
            $message_sent = true;
837
        }
838
839
        // Minor validation to clean up the attachment files in the announcement
840
        /*if (!empty($_FILES)) {
841
            $attachments = $_FILES;
842
            foreach ($attachments as $attachment) {
843
                unlink($attachment['tmp_name']);
844
            }
845
        }*/
846
847
        return $message_sent; //true if at least one e-mail was sent
848
    }
849
850
    /**
851
     * Displays announcements as an slideshow.
852
     *
853
     * @param string $visible see self::VISIBLE_* constants
854
     * @param int    $id      The identifier of the announcement to display
855
     */
856
    public static function getAnnouncements($visible, $id = null): array
857
    {
858
        $user_selected_language = Database::escape_string(api_get_language_isocode());
859
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
860
861
        $cut_size = 500;
862
        $now = api_get_utc_datetime();
863
        $sql = "SELECT * FROM $table
864
                WHERE
865
                    (lang = '$user_selected_language' OR lang = '') AND
866
                    ('$now' >= date_start AND '$now' <= date_end) ";
867
868
        $sql .= self::getVisibilityCondition($visible);
869
870
        if (isset($id) && !empty($id)) {
871
            $id = (int) $id;
872
            $sql .= " AND id = $id ";
873
        }
874
875
        if (api_is_multiple_url_enabled()) {
876
            $current_url_id = api_get_current_access_url_id();
877
            $sql .= " AND access_url_id IN ('1', '$current_url_id') ";
878
        }
879
880
        $checkCareers = true === api_get_configuration_value('allow_careers_in_global_announcements');
881
882
        $userId = api_get_user_id();
883
884
        $promotion = new Promotion();
885
        $sql .= ' ORDER BY date_start DESC';
886
        $result = Database::query($sql);
887
        $announcements = [];
888
        if (Database::num_rows($result) > 0) {
889
            while ($announcement = Database::fetch_object($result)) {
890
                if ($checkCareers && !empty($announcement->career_id)) {
891
                    $promotionList = [];
892
                    if (!empty($announcement->promotion_id)) {
893
                        $promotionList[] = $announcement->promotion_id;
894
                    } else {
895
                        $promotionList = $promotion->get_all_promotions_by_career_id($announcement->career_id);
896
                        if (!empty($promotionList)) {
897
                            $promotionList = array_column($promotionList, 'id');
898
                        }
899
                    }
900
901
                    $show = false;
902
                    foreach ($promotionList as $promotionId) {
903
                        $sessionList = SessionManager::get_all_sessions_by_promotion($promotionId);
904
                        foreach ($sessionList as $session) {
905
                            $sessionId = $session['id'];
906
                            // Check student
907
                            if (self::VISIBLE_STUDENT === $visible &&
908
                                SessionManager::isUserSubscribedAsStudent($sessionId, $userId)
909
                            ) {
910
                                $show = true;
911
                                break 2;
912
                            }
913
914
                            if (self::VISIBLE_TEACHER === $visible &&
915
                                SessionManager::user_is_general_coach($userId, $sessionId)
916
                            ) {
917
                                $show = true;
918
                                break 2;
919
                            }
920
921
                            // Check course coach
922
                            $coaches = SessionManager::getCoachesBySession($sessionId);
923
924
                            if (self::VISIBLE_TEACHER === $visible && in_array($userId, $coaches)) {
925
                                $show = true;
926
                                break 2;
927
                            }
928
                        }
929
                    }
930
931
                    if (false === $show) {
932
                        continue;
933
                    }
934
                }
935
936
                $announcementData = [
937
                    'id' => $announcement->id,
938
                    'title' => $announcement->title,
939
                    'content' => $announcement->content,
940
                    'readMore' => null,
941
                ];
942
943
                if (empty($id)) {
944
                    if (api_strlen(strip_tags($announcement->content)) > $cut_size) {
945
                        $announcementData['content'] = cut($announcement->content, $cut_size);
946
                        $announcementData['readMore'] = true;
947
                    }
948
                }
949
950
                $announcements[] = $announcementData;
951
            }
952
        }
953
954
        if (0 === count($announcements)) {
955
            return [];
956
        }
957
958
        return $announcements;
959
    }
960
961
    /**
962
     * Get the HTML code for an announcement.
963
     *
964
     * @param int    $announcementId The announcement ID
965
     * @param string $visibility     The announcement visibility
966
     */
967
    public static function getAnnouncement($announcementId, $visibility): array
968
    {
969
        $selectedUserLanguage = Database::escape_string(api_get_language_isocode());
970
        $announcementTable = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
971
        $now = api_get_utc_datetime();
972
        $announcementId = (int) $announcementId;
973
974
        $whereConditions = [
975
            "(lang = ? OR lang IS NULL OR lang = '') " => $selectedUserLanguage,
976
            "AND (? >= date_start AND ? <= date_end) " => [$now, $now],
977
            "AND id = ? " => $announcementId,
978
        ];
979
980
        $condition = self::getVisibilityCondition($visibility);
981
        $whereConditions[$condition] = 1;
982
983
        if (api_is_multiple_url_enabled()) {
984
            $whereConditions["AND access_url_id IN (1, ?) "] = api_get_current_access_url_id();
985
        }
986
987
        $announcement = Database::select(
988
            '*',
989
            $announcementTable,
990
            [
991
                'where' => $whereConditions,
992
                'order' => 'date_start',
993
            ],
994
            'first'
995
        );
996
997
        return $announcement;
998
    }
999
1000
    /**
1001
     * @return string
1002
     */
1003
    public static function getCurrentUserVisibility()
1004
    {
1005
        if (api_is_anonymous()) {
1006
            return self::VISIBLE_GUEST;
1007
        }
1008
1009
        if (api_is_student_boss()) {
1010
            return self::VISIBLE_STUDENT_BOSS;
1011
        }
1012
1013
        if (api_is_session_admin()) {
1014
            return self::VISIBLE_SESSION_ADMIN;
1015
        }
1016
1017
        if (api_is_drh()) {
1018
            return self::VISIBLE_DRH;
1019
        }
1020
1021
        if (api_is_teacher()) {
1022
            return self::VISIBLE_TEACHER;
1023
        } else {
1024
            return self::VISIBLE_STUDENT;
1025
        }
1026
    }
1027
1028
    /**
1029
     * Deletes the Announcement picture.
1030
     *
1031
     * @param int $announcementId
1032
     */
1033
    public static function deleteAnnouncementPicture($announcementId)
1034
    {
1035
        /*$store_path = api_get_path(SYS_UPLOAD_PATH).'announcements';
1036
1037
        // image name
1038
        $announcementPicture = $store_path.'/announcement_'.$announcementId.'.png';
1039
        $announcementPictureSmall = $store_path.'/announcement_'.$announcementId.'_100x100.png';
1040
1041
        if (file_exists($announcementPicture)) {
1042
            unlink($announcementPicture);
1043
        }
1044
        if (file_exists($announcementPictureSmall)) {
1045
            unlink($announcementPictureSmall);
1046
        }*/
1047
    }
1048
1049
    /**
1050
     * get announcement picture.
1051
     *
1052
     * @param int $announcementId
1053
     *
1054
     * @return string|null
1055
     */
1056
    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...
1057
    {
1058
        /*$store_path = api_get_path(SYS_UPLOAD_PATH).'announcements';
1059
        $announcementPicture = $store_path.'/announcement_'.$announcementId.'.png';
1060
        if (file_exists($announcementPicture)) {
1061
            $web_path = api_get_path(WEB_UPLOAD_PATH).'announcements';
1062
            $urlPicture = $web_path.'/announcement_'.$announcementId.'.png';
1063
1064
            return $urlPicture;
1065
        }
1066
1067
        return null;*/
1068
    }
1069
}
1070