Completed
Push — 1.11.x ( 204566...250b76 )
by José
72:06 queued 36:38
created

SystemAnnouncementManager::add_announcement()   D

Complexity

Conditions 13
Paths 31

Size

Total Lines 115
Code Lines 81

Duplication

Lines 36
Ratio 31.3 %

Importance

Changes 0
Metric Value
cc 13
eloc 81
c 0
b 0
f 0
nc 31
nop 11
dl 36
loc 115
rs 4.9922

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class SystemAnnouncementManager
6
 */
7
class SystemAnnouncementManager
8
{
9
    const VISIBLE_GUEST = 1;
10
    const VISIBLE_STUDENT = 2;
11
    const VISIBLE_TEACHER = 3;
12
13
	/**
14
	 * Displays all announcements
15
	 * @param int $visible VISIBLE_GUEST, VISIBLE_STUDENT or VISIBLE_TEACHER
16
	 * @param int $id The identifier of the announcement to display
17
	 */
18
	public static function display_announcements($visible, $id = -1)
19
    {
20
        $user_selected_language = api_get_interface_language();
21
        $db_table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
22
        $tbl_announcement_group = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
23
        $userGroup = new UserGroup();
24
25
        $temp_user_groups = $userGroup->get_groups_by_user(api_get_user_id(),0);
26
        $groups = array();
27 View Code Duplication
        foreach ($temp_user_groups as $user_group) {
28
            $groups = array_merge($groups, array($user_group['id']));
29
            $groups = array_merge($groups, $userGroup->get_parent_groups($user_group['id']));
30
        }
31
32
        $groups_string = '('.implode($groups,',').')';
33
        $now = api_get_utc_datetime();
34
        $sql = "SELECT *, DATE_FORMAT(date_start,'%d-%m-%Y %h:%i:%s') AS display_date
35
                FROM  $db_table
36
                WHERE
37
                    (lang='$user_selected_language' OR lang IS NULL) AND
38
                    (('$now' BETWEEN date_start AND date_end) OR date_end='0000-00-00') ";
39
40 View Code Duplication
        switch ($visible) {
41
            case self::VISIBLE_GUEST:
42
                $sql .= " AND visible_guest = 1 ";
43
                break;
44
            case self::VISIBLE_STUDENT:
45
                $sql .= " AND visible_student = 1 ";
46
                break;
47
            case self::VISIBLE_TEACHER:
48
                $sql .= " AND visible_teacher = 1 ";
49
                break;
50
        }
51
52
        if (count($groups) > 0) {
53
            $sql .= " OR id IN (
54
                        SELECT announcement_id FROM $tbl_announcement_group
55
                        WHERE group_id in $groups_string
56
                    ) ";
57
        }
58
        $current_access_url_id = 1;
59
        if (api_is_multiple_url_enabled()) {
60
            $current_access_url_id = api_get_current_access_url_id();
61
        }
62
        $sql .= " AND access_url_id = '$current_access_url_id' ";
63
        $sql .= " ORDER BY date_start DESC LIMIT 0,7";
64
65
        $announcements = Database::query($sql);
66
        if (Database::num_rows($announcements) > 0) {
67
            $query_string = ereg_replace('announcement=[1-9]+', '', $_SERVER['QUERY_STRING']);
68
            $query_string = ereg_replace('&$', '', $query_string);
69
            $url = api_get_self();
70
            echo '<div class="system_announcements">';
71
            echo '<h3>'.get_lang('SystemAnnouncements').'</h3>';
72
            echo '<div style="margin:10px;text-align:right;"><a href="news_list.php">'.get_lang('More').'</a></div>';
73
74
            while ($announcement = Database::fetch_object($announcements)) {
75
                if ($id != $announcement->id) {
76
                    if (strlen($query_string) > 0) {
77
                        $show_url = 'news_list.php#'.$announcement->id;
78
                    } else {
79
                        $show_url = 'news_list.php#'.$announcement->id;
80
                    }
81
                    $display_date = api_convert_and_format_date($announcement->display_date, DATE_FORMAT_LONG);
82
                    echo '<a name="'.$announcement->id.'"></a>
83
                        <div class="system_announcement">
84
                            <div class="system_announcement_title"><a name="ann'.$announcement->id.'" href="'.$show_url.'">'.$announcement->title.'</a></div><div class="system_announcement_date">'.$display_date.'</div>
85
                        </div>';
86
                } else {
87
                    echo '<div class="system_announcement">
88
                            <div class="system_announcement_title">'
89
                                .$announcement->display_date.'
90
                                <a name="ann'.$announcement->id.'" href="'.$url.'?'.$query_string.'#ann'.$announcement->id.'">'.$announcement->title.'</a>
91
                            </div>';
92
                }
93
                echo '<br />';
94
            }
95
            echo '</div>';
96
        }
97
        return;
98
    }
99
100
    /**
101
     * @param $visible
102
     * @param $id
103
     * @param int $start
104
     * @param string $user_id
105
     * @return string
106
     */
107
    public static function display_all_announcements($visible, $id = -1, $start = 0,$user_id='')
108
    {
109
        $user_selected_language = api_get_interface_language();
110
        $start	= intval($start);
111
        $userGroup = new UserGroup();
112
        $tbl_announcement_group = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
113
        $temp_user_groups = $userGroup->get_groups_by_user(api_get_user_id(),0);
114
        $groups = array();
115 View Code Duplication
        foreach ($temp_user_groups as $user_group) {
116
            $groups = array_merge($groups, array($user_group['id']));
117
            $groups = array_merge($groups, $userGroup->get_parent_groups($user_group['id']));
118
        }
119
120
        // Checks if tables exists to not break platform not updated
121
        $groups_string = '('.implode($groups,',').')';
122
123
        $db_table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
124
        $now  = api_get_utc_datetime();
125
126
        $sql = "SELECT * FROM ".$db_table."
127
                WHERE
128
                    (lang = '$user_selected_language' OR lang IS NULL) AND
129
                    ( '$now' >= date_start AND '$now' <= date_end) ";
130
131 View Code Duplication
        switch ($visible) {
132
            case self::VISIBLE_GUEST:
133
                $sql .= " AND visible_guest = 1 ";
134
                break;
135
            case self::VISIBLE_STUDENT:
136
                $sql .= " AND visible_student = 1 ";
137
                break;
138
            case self::VISIBLE_TEACHER:
139
                $sql .= " AND visible_teacher = 1 ";
140
                break;
141
        }
142
143
        if (count($groups) > 0) {
144
            $sql .= " OR id IN (
145
                    SELECT announcement_id FROM $tbl_announcement_group
146
                    WHERE group_id in $groups_string
147
                    ) ";
148
        }
149
150
        if (api_is_multiple_url_enabled()) {
151
            $current_access_url_id = api_get_current_access_url_id();
152
            $sql .= " AND access_url_id IN ('1', '$current_access_url_id')";
153
        }
154
155
        if(!isset($_GET['start']) || $_GET['start'] == 0) {
156
            $sql .= " ORDER BY date_start DESC LIMIT ".$start.",20";
157
        } else {
158
            $sql .= " ORDER BY date_start DESC LIMIT ".($start+1).",20";
159
        }
160
        $announcements = Database::query($sql);
161
        $content = '';
162
        if (Database::num_rows($announcements) > 0) {
163
            $content .= '<div class="system_announcements">';
164
            $content .= '<h3>'.get_lang('SystemAnnouncements').'</h3>';
165
            $content .= '<table align="center">';
166
                $content .= '<tr>';
167
                    $content .= '<td>';
168
                        $content .= SystemAnnouncementManager :: display_arrow($user_id);
169
                    $content .= '</td>';
170
                $content .= '</tr>';
171
            $content .= '</table>';
172
            $content .= '<table align="center" border="0" width="900px">';
173
            while ($announcement = Database::fetch_object($announcements)) {
174
                $display_date = api_convert_and_format_date($announcement->display_date, DATE_FORMAT_LONG);
175
                $content .= '<tr><td>';
176
                $content .= '<a name="'.$announcement->id.'"></a>
177
                        <div class="system_announcement">
178
                        <h2>'.$announcement->title.'</h2><div class="system_announcement_date">'.$display_date.'</div>
179
                        <br />
180
                        <div class="system_announcement_content">'
181
                                .$announcement->content.'
182
                        </div>
183
                      </div><br />';
184
                $content .= '</tr></td>';
185
            }
186
            $content .= '</table>';
187
188
            $content .= '<table align="center">';
189
                $content .= '<tr>';
190
                    $content .= '<td>';
191
                        $content .= SystemAnnouncementManager :: display_arrow($user_id);
192
                    $content .= '</td>';
193
                $content .= '</tr>';
194
            $content .= '</table>';
195
            $content .= '</div>';
196
        }
197
198
        return $content;
199
    }
200
201
    /**
202
     * @param int $user_id
203
     * @return string
204
     */
205
    public static function display_arrow($user_id)
206
    {
207
        $start = (int)$_GET['start'];
208
        $nb_announcement = SystemAnnouncementManager :: count_nb_announcement($start, $user_id);
209
        $next = ((int)$_GET['start']+19);
210
        $prev = ((int)$_GET['start']-19);
211
        $content = '';
212
        if (!isset($_GET['start']) || $_GET['start'] == 0) {
213 View Code Duplication
            if ($nb_announcement > 20) {
214
                $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
215
            }
216
        } else {
217
            echo '<a href="news_list.php?start='.$prev.'"> << '.get_lang('Prev').'</a>';
218 View Code Duplication
            if ($nb_announcement > 20) {
219
                $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
220
            }
221
        }
222
        return $content;
223
    }
224
225
    /**
226
     * @param int $start
227
     * @param string $user_id
228
     * @return int
229
     */
230
    public static function count_nb_announcement($start = 0, $user_id = '')
231
    {
232
        $start = intval($start);
233
        $visibility = api_is_allowed_to_create_course() ? self::VISIBLE_TEACHER : self::VISIBLE_STUDENT;
234
        $user_selected_language = api_get_interface_language();
235
        $db_table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
236
        $sql = 'SELECT id FROM '.$db_table.'
237
                WHERE (lang="'.$user_selected_language.'" OR lang IS NULL) ';
238
        if (isset($user_id)) {
239
            switch ($visibility) {
240
                case self::VISIBLE_GUEST:
241
                    $sql .= " AND visible_guest = 1 ";
242
                    break;
243
                case self::VISIBLE_STUDENT:
244
                    $sql .= " AND visible_student = 1 ";
245
                    break;
246
                case self::VISIBLE_TEACHER:
247
                    $sql .= " AND visible_teacher = 1 ";
248
                    break;
249
            }
250
        }
251
252
        $current_access_url_id = 1;
253
        if (api_is_multiple_url_enabled()) {
254
            $current_access_url_id = api_get_current_access_url_id();
255
        }
256
        $sql .= " AND access_url_id = '$current_access_url_id' ";
257
258
259
        $sql .= 'LIMIT '.$start.', 21';
260
        $announcements = Database::query($sql);
261
        $i = 0;
262
        while ($rows = Database::fetch_array($announcements)) {
263
            $i++;
264
        }
265
266
        return $i;
267
    }
268
269
    /**
270
     * Get all announcements
271
     * @return array An array with all available system announcements (as php
272
     * objects)
273
     */
274 View Code Duplication
    public static function get_all_announcements()
275
    {
276
        $table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
277
        $now = api_get_utc_datetime();
278
        $sql = "SELECT *, IF ( '$now'  >= date_start AND '$now' <= date_end, '1', '0') AS visible
279
                FROM $table";
280
281
        $current_access_url_id = 1;
282
        if (api_is_multiple_url_enabled()) {
283
            $current_access_url_id = api_get_current_access_url_id();
284
        }
285
        $sql .= " WHERE access_url_id = '$current_access_url_id' ";
286
        $sql .= " ORDER BY date_start ASC";
287
288
        $announcements = Database::query($sql);
289
        $all_announcements = array();
290
        while ($announcement = Database::fetch_object($announcements)) {
291
            $all_announcements[] = $announcement;
292
        }
293
        return $all_announcements;
294
    }
295
296
    /**
297
     * Adds an announcement to the database
298
     * @param string Title of the announcement
299
     * @param string Content of the announcement
300
     * @param string Start date (YYYY-MM-DD HH:II: SS)
301
     * @param string End date (YYYY-MM-DD HH:II: SS)
302
     * @param int    Whether the announcement should be visible to teachers (1) or not (0)
303
     * @param int    Whether the announcement should be visible to students (1) or not (0)
304
     * @param int    Whether the announcement should be visible to anonymous users (1) or not (0)
305
     * @param string The language for which the announvement should be shown. Leave null for all langages
306
     * @param int    Whether to send an e-mail to all users (1) or not (0)
307
     * @return mixed  insert_id on success, false on failure
308
     */
309
    public static function add_announcement(
310
        $title,
311
        $content,
312
        $date_start,
313
        $date_end,
314
        $visible_teacher = 0,
315
        $visible_student = 0,
316
        $visible_guest = 0,
317
        $lang = '',
318
        $send_mail = 0,
319
        $add_to_calendar = false,
320
        $sendEmailTest = false
321
    ) {
322
        $original_content = $content;
323
        $a_dateS = explode(' ', $date_start);
324
        $a_arraySD = explode('-', $a_dateS[0]);
325
        $a_arraySH = explode(':', $a_dateS[1]);
326
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
327
328
        $a_dateE = explode(' ', $date_end);
329
        $a_arrayED = explode('-', $a_dateE[0]);
330
        $a_arrayEH = explode(':', $a_dateE[1]);
331
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
332
333
        $db_table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
334
335 View Code Duplication
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
336
            Display :: display_normal_message(get_lang('InvalidStartDate'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

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

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

Loading history...
337
            return false;
338
        }
339
340 View Code Duplication
        if (($date_end_to_compare[1] ||
341
            $date_end_to_compare[2] ||
342
            $date_end_to_compare[0]) &&
343
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
344
        ) {
345
            Display :: display_normal_message(get_lang('InvalidEndDate'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

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

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

Loading history...
346
            return false;
347
        }
348
349 View Code Duplication
        if (strlen(trim($title)) == 0) {
350
            Display::display_normal_message(get_lang('InvalidTitle'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

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

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

Loading history...
351
352
            return false;
353
        }
354
355
        $start = api_get_utc_datetime($date_start);
356
        $end = api_get_utc_datetime($date_end);
357
358
        //Fixing urls that are sent by email
359
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
360
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
361
        $content = str_replace('src=\"'.api_get_path(REL_HOME_PATH), 'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
362
        $content = str_replace('file='.api_get_path(REL_HOME_PATH), 'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
363
        $lang = is_null($lang) ? '' : $lang;
364
365
        $current_access_url_id = 1;
366
        if (api_is_multiple_url_enabled()) {
367
            $current_access_url_id = api_get_current_access_url_id();
368
        }
369
370
        $params = [
371
            'title' => $title,
372
            'content' => $content,
373
            'date_start' => $start,
374
            'date_end' => $end,
375
            'visible_teacher' => $visible_teacher,
376
            'visible_student' => $visible_student,
377
            'visible_guest' => $visible_guest,
378
            'lang' => $lang,
379
            'access_url_id' => $current_access_url_id
380
        ];
381
382
        $resultId = Database::insert($db_table, $params);
383
384
        if ($resultId) {
385 View Code Duplication
            if ($sendEmailTest) {
386
                SystemAnnouncementManager::send_system_announcement_by_email(
387
                    $title,
388
                    $content,
389
                    $visible_teacher,
390
                    $visible_student,
391
                    $lang,
392
                    true
393
                );
394
            } else {
395
                if ($send_mail == 1) {
396
                    SystemAnnouncementManager::send_system_announcement_by_email(
397
                        $title,
398
                        $content,
399
                        $visible_teacher,
400
                        $visible_student,
401
                        $lang
402
                    );
403
                }
404
            }
405
406
            if ($add_to_calendar) {
407
                $agenda = new Agenda();
408
                $agenda->setType('admin');
409
                $agenda->addEvent(
410
                    $date_start,
411
                    $date_end,
412
                    false,
413
                    $title,
414
                    $original_content
415
                );
416
            }
417
418
            return $resultId;
419
420
        }
421
422
        return false;
423
    }
424
425
    /**
426
    * Makes the announcement id visible only for groups in groups_array
427
    * @param int $announcement_id
428
    * @param array $group_array array of group id
429
    **/
430
    public static function announcement_for_groups($announcement_id, $group_array)
431
    {
432
        $tbl_announcement_group = Database:: get_main_table(
433
            TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS
434
        );
435
        //first delete all group associations for this announcement
436
        $res = Database::query(
437
            "DELETE FROM $tbl_announcement_group 
438
             WHERE announcement_id=".intval($announcement_id)
439
        );
440
441
        if ($res === false) {
442
            return false;
443
        }
444
445
        foreach ($group_array as $group_id) {
446
            if (intval($group_id) != 0) {
447
                $sql = "INSERT INTO $tbl_announcement_group SET
448
                        announcement_id=".intval($announcement_id).",
449
                        group_id=".intval($group_id);
450
                $res = Database::query($sql);
451
                if ($res === false) {
452
453
                    return false;
454
                }
455
            }
456
        }
457
458
        return true;
459
    }
460
461
    /**
462
    * Gets the groups of this announce
463
    * @param int announcement id
464
    * @return array array of group id
465
    **/
466 View Code Duplication
    public static function get_announcement_groups($announcement_id)
467
    {
468
        $tbl_announcement_group = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
469
        $tbl_group = Database :: get_main_table(TABLE_USERGROUP);
470
        //first delete all group associations for this announcement
471
472
        $sql = "SELECT
473
                    g.id as group_id,
474
                    g.name as group_name
475
                FROM $tbl_group g , $tbl_announcement_group ag
476
                WHERE
477
                    announcement_id =".intval($announcement_id)." AND
478
                    ag.group_id = g.id";
479
        $res = Database::query($sql);
480
        $groups = Database::fetch_array($res);
481
482
        return $groups;
483
    }
484
485
	/**
486
	 * Updates an announcement to the database
487
	 * @param integer $id      : id of the announcement
488
	 * @param string  $title   : title of the announcement
489
	 * @param string  $content : content of the announcement
490
	 * @param array $date_start: start date of announcement (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
0 ignored issues
show
Documentation introduced by
There is no parameter named $date_start:. Did you maybe mean $date_start?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
491
	 * @param array $date_end : end date of announcement (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
492
	 * @return	bool	True on success, false on failure
493
	 */
494
    public static function update_announcement(
495
        $id,
496
        $title,
497
        $content,
498
        $date_start,
499
        $date_end,
500
        $visible_teacher = 0,
501
        $visible_student = 0,
502
        $visible_guest = 0,
503
        $lang = null,
504
        $send_mail = 0,
505
        $sendEmailTest = false
506
    ) {
507
        $em = Database::getManager();
508
		$announcement = $em->find('ChamiloCoreBundle:SysAnnouncement', $id);
509
510
        if (!$announcement) {
511
            return false;
512
        }
513
514
        $a_dateS = explode(' ', $date_start);
515
        $a_arraySD = explode('-', $a_dateS[0]);
516
        $a_arraySH = explode(':', $a_dateS[1]);
517
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
518
519
        $a_dateE = explode(' ', $date_end);
520
        $a_arrayED = explode('-', $a_dateE[0]);
521
        $a_arrayEH = explode(':', $a_dateE[1]);
522
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
523
524
        $lang = is_null($lang) ? '' : $lang;
525
526 View Code Duplication
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
527
            Display:: display_normal_message(get_lang('InvalidStartDate'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

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

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

Loading history...
528
529
            return false;
530
        }
531
532 View Code Duplication
		if (($date_end_to_compare[1] ||
533
            $date_end_to_compare[2] ||
534
            $date_end_to_compare[0]) &&
535
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
536
        ) {
537
			Display :: display_normal_message(get_lang('InvalidEndDate'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

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

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

Loading history...
538
539
			return false;
540
		}
541
542 View Code Duplication
		if (strlen(trim($title)) == 0) {
543
			Display::display_normal_message(get_lang('InvalidTitle'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

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

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

Loading history...
544
545
			return false;
546
		}
547
548
        $start = api_get_utc_datetime($date_start);
549
        $end = api_get_utc_datetime($date_end);
550
551
		//Fixing urls that are sent by email
552
		//$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
553
		//$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
554
        $content = str_replace('src=\"'.api_get_path(REL_HOME_PATH), 'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
555
        $content = str_replace('file='.api_get_path(REL_HOME_PATH), 'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
556
557 View Code Duplication
        if ($sendEmailTest) {
558
            SystemAnnouncementManager::send_system_announcement_by_email(
559
                $title,
560
                $content,
561
                null,
562
                null,
563
                $lang,
564
                $sendEmailTest
565
            );
566
        } else {
567
            if ($send_mail==1) {
568
                SystemAnnouncementManager::send_system_announcement_by_email(
569
                    $title,
570
                    $content,
571
                    $visible_teacher,
572
                    $visible_student,
573
                    $lang
574
                );
575
            }
576
        }
577
578
        $dateStart = new DateTime($start, new DateTimeZone('UTC'));
579
        $dateEnd = new DateTime($end, new DateTimeZone('UTC'));
580
581
        $announcement
582
            ->setLang($lang)
583
            ->setTitle($title)
584
            ->setContent($content)
585
            ->setDateStart($dateStart)
586
            ->setDateEnd($dateEnd)
587
            ->setVisibleTeacher($visible_teacher)
588
            ->setVisibleStudent($visible_student)
589
            ->setVisibleGuest($visible_guest)
590
            ->setAccessUrlId(api_get_current_access_url_id());
591
592
        $em->merge($announcement);
593
        $em->flush();
594
595
		return true;
596
	}
597
598
	/**
599
	 * Deletes an announcement
600
	 * @param 	int $id The identifier of the announcement that should be
601
	 * @return	bool	True on success, false on failure
602
	 */
603
	public static function delete_announcement($id)
604
    {
605
		$db_table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
606
		$id = intval($id);
607
		$sql = "DELETE FROM ".$db_table." WHERE id =".$id;
608
		$res = Database::query($sql);
609
        if ($res === false) {
610
			return false;
611
		}
612
		return true;
613
	}
614
615
	/**
616
	 * Gets an announcement
617
	 * @param 	int		$id The identifier of the announcement that should be
618
	 * @return	object	Object of class StdClass or the required class, containing the query result row
619
	 */
620
	public static function get_announcement($id)
621
    {
622
		$db_table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
623
		$id = intval($id);
624
		$sql = "SELECT * FROM ".$db_table." WHERE id = ".$id;
625
		$announcement = Database::fetch_object(Database::query($sql));
0 ignored issues
show
Bug introduced by
It seems like \Database::query($sql) can be null; however, fetch_object() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
626
627
		return $announcement;
628
	}
629
630
	/**
631
	 * Change the visibility of an announcement
632
	 * @param 	int $announcement_id
633
	 * @param 	int $user For who should the visibility be changed
634
     * (possible values are VISIBLE_TEACHER, VISIBLE_STUDENT, VISIBLE_GUEST)
635
	 * @return 	bool	True on success, false on failure
636
	 */
637
	public static function set_visibility($announcement_id, $user, $visible)
638
    {
639
		$db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
640
		$visible = intval($visible);
641
		$announcement_id = intval($announcement_id);
642
643
        if (!in_array($user, array(self::VISIBLE_GUEST, self::VISIBLE_STUDENT, self::VISIBLE_TEACHER))) {
644
            return false;
645
        }
646
647
		$field = ($user == self::VISIBLE_TEACHER ? 'visible_teacher' : ($user == self::VISIBLE_STUDENT ? 'visible_student' : 'visible_guest'));
648
649
		$sql = "UPDATE ".$db_table." SET ".$field." = '".$visible."'
650
		        WHERE id='".$announcement_id."'";
651
		$res = Database::query($sql);
652
653
		if ($res === false) {
654
			return false;
655
		}
656
657
		return true;
658
	}
659
660
	/**
661
	 * Send a system announcement by e-mail to all teachers/students depending on parameters
662
	 * @param	string	$title
663
	 * @param	string	$content
664
	 * @param	int		$teacher Whether to send to all teachers (1) or not (0)
665
	 * @param	int		$student Whether to send to all students (1) or not (0)
666
	 * @param	string	$language Language (optional, considered for all languages if left empty)
667
     * @param	bool	$sendEmailTest
668
     * @return  bool    True if the message was sent or there was no destination matching. False on database or e-mail sending error.
669
	 */
670
    public static function send_system_announcement_by_email(
671
        $title,
672
        $content,
673
        $teacher,
674
        $student,
675
        $language = null,
676
        $sendEmailTest = false
677
    ) {
678
        $content = str_replace(array('\r\n', '\n', '\r'),'', $content);
679
        $now = api_get_utc_datetime();
680
681
        if ($sendEmailTest) {
682
            MessageManager::send_message_simple(api_get_user_id(), $title, $content);
683
684
            return true;
685
        }
686
687
        $user_table = Database :: get_main_table(TABLE_MAIN_USER);
688
        if (api_is_multiple_url_enabled()) {
689
            $current_access_url_id = api_get_current_access_url_id();
690
            $url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
691
            $url_condition = " INNER JOIN $url_rel_user uu ON uu.user_id = u.user_id ";
692
        }
693
694
        if ($teacher <> 0 && $student == 0) {
695
			$sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition 
696
					WHERE status = '1' ";
697
		}
698
699
		if ($teacher == 0 && $student <> 0) {
700
			$sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition 
701
					WHERE status = '5' ";
702
		}
703
704
		if ($teacher<> 0 && $student <> 0) {
705
			$sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition 
706
					WHERE 1 = 1 ";
707
		}
708
709
		if (!empty($language)) {
710
			//special condition because language was already treated for SQL insert before
711
			$sql .= " AND language = '".Database::escape_string($language)."' ";
712
		}
713
714
		if (api_is_multiple_url_enabled()) {
715
            $sql .= " AND access_url_id = '".$current_access_url_id."' ";
716
        }
717
718
        // Sent to active users.
719
        $sql .= " AND email <>'' AND active = 1 ";
720
721
        // Expiration date
722
        $sql .= " AND (expiration_date = '' OR expiration_date IS NULL OR expiration_date > '$now') ";
723
724
		if ((empty($teacher) || $teacher == '0') && (empty($student) || $student == '0')) {
725
726
			return true;
727
		}
728
729
		$result = Database::query($sql);
730
		if ($result === false) {
731
732
			return false;
733
		}
734
735
        $message_sent = false;
736
737
		while ($row = Database::fetch_array($result,'ASSOC')) {
738
            MessageManager::send_message_simple($row['user_id'], $title, $content);
739
            $message_sent = true;
740
		}
741
	    
742
	    	// Minor validation to clean up the attachment files in the announcement
743
		if (!empty($_FILES)) {
744
		    $attachments = $_FILES;
745
		    foreach ($attachments as $attachment) {
746
			unlink($attachment['tmp_name']);
747
		    }
748
		}
749
750
		return $message_sent; //true if at least one e-mail was sent
751
	}
752
753
	/**
754
     * Displays announcements as an slideshow
755
     * @param int $visible VISIBLE_GUEST, VISIBLE_STUDENT or VISIBLE_TEACHER
756
     * @param int $id The identifier of the announcement to display
757
     */
758
    public static function display_announcements_slider($visible, $id = null)
759
    {
760
        $user_selected_language = Database::escape_string(api_get_interface_language());
761
        $table = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
762
763
        $cut_size = 500;
764
        $now = api_get_utc_datetime();
765
766
        $sql = "SELECT * FROM " . $table . "
767
				WHERE
768
				    (lang = '$user_selected_language' OR lang = '') AND
769
				    ('$now' >= date_start AND '$now' <= date_end) ";
770
771 View Code Duplication
        switch ($visible) {
772
            case self::VISIBLE_GUEST:
773
                $sql .= " AND visible_guest = 1 ";
774
                break;
775
            case self::VISIBLE_STUDENT:
776
                $sql .= " AND visible_student = 1 ";
777
                break;
778
            case self::VISIBLE_TEACHER:
779
                $sql .= " AND visible_teacher = 1 ";
780
                break;
781
        }
782
783
        if (isset($id) && !empty($id)) {
784
            $id = intval($id);
785
            $sql .= " AND id = $id ";
786
        }
787
788
        if (api_is_multiple_url_enabled()) {
789
            $current_url_id = api_get_current_access_url_id();
790
            $sql .= " AND access_url_id IN ('1', '$current_url_id') ";
791
        }
792
793
        $sql .= " ORDER BY date_start DESC";
794
        $result = Database::query($sql);
795
        $announcements = [];
796
797
        if (Database::num_rows($result) > 0) {
798
            while ($announcement = Database::fetch_object($result)) {
799
                $announcementData = [
800
                    'id' => $announcement->id,
801
                    'title' => $announcement->title,
802
                    'content' => $announcement->content,
803
                    'readMore' => null
804
                ];
805
806
                if (empty($id)) {
807
                    if (api_strlen(strip_tags($announcement->content)) > $cut_size) {
808
                        $announcementData['content'] = cut($announcement->content, $cut_size);
809
                        $announcementData['readMore'] = true;
810
                    }
811
                }
812
813
                $announcements[] = $announcementData;
814
            }
815
        }
816
817
        if (count($announcements) === 0) {
818
            return null;
819
        }
820
821
        $template = new Template(null, false, false);
822
        $template->assign('announcements', $announcements);
823
        $layout = $template->get_template('announcement/slider.tpl');
824
825
        return $template->fetch($layout);
826
    }
827
828
    /**
829
     * Get the HTML code for an announcement
830
     * @param int $announcementId The announcement ID
831
     * @param int $visibility The announcement visibility
832
     * @return string The HTML code
833
     */
834
    public static function displayAnnouncement($announcementId, $visibility)
835
    {
836
        $selectedUserLanguage = Database::escape_string(api_get_interface_language());
837
        $announcementTable = Database :: get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
838
839
        $now = api_get_utc_datetime();
840
841
        $whereConditions = [
842
            "(lang = ? OR lang IS NULL) " => $selectedUserLanguage,
843
            "AND (? >= date_start AND ? <= date_end) " => [$now, $now],
844
            "AND id = ? " => intval($announcementId)
845
        ];
846
847
        switch ($visibility) {
848
            case self::VISIBLE_GUEST :
849
                $whereConditions["AND visible_guest = ? "] = 1;
850
                break;
851
            case self::VISIBLE_STUDENT :
852
                $whereConditions["AND visible_student = ? "] = 1;
853
                break;
854
            case self::VISIBLE_TEACHER :
855
                $whereConditions["AND visible_teacher = ? "] = 1;
856
                break;
857
        }
858
859
        if (api_is_multiple_url_enabled()) {
860
            $whereConditions["AND access_url_id IN (1, ?) "] = api_get_current_access_url_id();
861
        }
862
863
        $announcement = Database::select(
864
            '*',
865
            $announcementTable,
866
            [
867
                'where' => $whereConditions,
868
                'order' => 'date_start'
869
            ], 'first'
870
        );
871
872
        $template = new Template(null, false, false);
873
        $template->assign('announcement', $announcement);
874
        $layout = $template->get_template('announcement/view.tpl');
875
876
        return $template->fetch($layout);
877
    }
878
}
879