Passed
Push — master ( 2c125c...530df2 )
by Yannick
11:22 queued 04:18
created

get_announcement_groups()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
nc 3
nop 1
dl 0
loc 23
rs 9.8666
c 1
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\Entity\User;
7
use Chamilo\CoreBundle\Framework\Container;
8
9
class SystemAnnouncementManager
10
{
11
    /**
12
     * Adds an announcement to the database.
13
     *
14
     * @param string $title           Title of the announcement
15
     * @param string $content         Content of the announcement
16
     * @param string $date_start      Start date (YYYY-MM-DD HH:II: SS)
17
     * @param string $date_end        End date (YYYY-MM-DD HH:II: SS)
18
     * @param array  $visibility
19
     * @param string $lang            The language for which the announvement should be shown. Leave null for all
20
     *                                langages
21
     * @param int    $send_mail       Whether to send an e-mail to all users (1) or not (0)
22
     * @param bool   $add_to_calendar
23
     * @param bool   $sendEmailTest
24
     * @param int    $careerId
25
     * @param int    $promotionId
26
     *
27
     * @return mixed insert_id on success, false on failure
28
     */
29
    public static function add_announcement(
30
        $title,
31
        $content,
32
        $date_start,
33
        $date_end,
34
        $visibility,
35
        $lang = '',
36
        $send_mail = 0,
37
        $add_to_calendar = false,
38
        $sendEmailTest = false,
39
        $careerId = 0,
40
        $promotionId = 0
41
    ) {
42
        $original_content = $content;
43
        $a_dateS = explode(' ', $date_start);
44
        $a_arraySD = explode('-', $a_dateS[0]);
45
        $a_arraySH = explode(':', $a_dateS[1]);
46
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
47
48
        $a_dateE = explode(' ', $date_end);
49
        $a_arrayED = explode('-', $a_dateE[0]);
50
        $a_arrayEH = explode(':', $a_dateE[1]);
51
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
52
53
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
54
            Display::addFlash(
55
                Display::return_message(get_lang('Invalid start date was given.'), 'warning')
56
            );
57
58
            return false;
59
        }
60
61
        if (($date_end_to_compare[1] ||
62
                $date_end_to_compare[2] ||
63
                $date_end_to_compare[0]) &&
64
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
65
        ) {
66
            Display::addFlash(
67
                Display::return_message(get_lang('Invalid end date was given.'), 'warning')
68
            );
69
70
            return false;
71
        }
72
73
        if (0 == strlen(trim($title))) {
74
            Display::addFlash(
75
                Display::return_message(get_lang('Please enter a title'), 'warning')
76
            );
77
78
            return false;
79
        }
80
81
        $start = api_get_utc_datetime($date_start, null, true);
82
        $end = api_get_utc_datetime($date_end, null, true);
83
84
        //Fixing urls that are sent by email
85
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
86
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
87
        $content = str_replace(
88
            'src=\"'.api_get_path(REL_HOME_PATH),
89
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
90
            $content
91
        );
92
        $content = str_replace(
93
            'file='.api_get_path(REL_HOME_PATH),
94
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
95
            $content
96
        );
97
        $lang = is_null($lang) ? '' : $lang;
98
99
        $sysRepo = Container::getSysAnnouncementRepository();
100
101
        $sysAnnouncement = (new SysAnnouncement())
102
            ->setTitle($title)
103
            ->setContent($content)
104
            ->setDateStart($start)
105
            ->setDateEnd($end)
106
            ->setLang($lang)
107
            ->setUrl(api_get_url_entity())
108
            ->setRoles($visibility);
109
110
        if (('true' === api_get_setting('announcement.allow_careers_in_global_announcements')) && !empty($careerId)) {
111
            $careerRepo = Container::getCareerRepository();
112
            $sysAnnouncement->setCareer($careerRepo->find($careerId));
113
114
            $promotionRepo = Container::getPromotionRepository();
115
            $sysAnnouncement->setPromotion($promotionRepo->find($promotionId));
116
        }
117
118
        $sysRepo->update($sysAnnouncement);
119
        $resultId = $sysAnnouncement->getId();
120
121
        if ($resultId) {
122
            if ($sendEmailTest) {
123
                self::send_system_announcement_by_email($sysAnnouncement, true);
124
            }
125
126
            if (1 == (int) $send_mail) {
127
                self::send_system_announcement_by_email($sysAnnouncement);
128
            }
129
130
            if ($add_to_calendar) {
131
                $agenda = new Agenda('admin');
132
                $agenda->addEvent(
133
                    $date_start,
134
                    $date_end,
135
                    false,
136
                    $title,
137
                    $original_content
138
                );
139
            }
140
141
            return $resultId;
142
        }
143
144
        return false;
145
    }
146
147
    /**
148
     * Send a system announcement by e-mail to all teachers/students depending on parameters.
149
     *
150
     * @return bool True if the message was sent or there was no destination matching.
151
     *              False on database or e-mail sending error.
152
     */
153
    public static function send_system_announcement_by_email(SysAnnouncement $announcement, bool $sendEmailTest = false)
154
    {
155
        $title = $announcement->getTitle();
156
        $content = $announcement->getContent();
157
        $language = $announcement->getLang();
158
159
        $content = str_replace(['\r\n', '\n', '\r'], '', $content);
160
161
        if ($sendEmailTest) {
162
            MessageManager::send_message_simple(api_get_user_id(), $title, $content);
163
164
            return true;
165
        }
166
167
        $repo = Container::getUserRepository();
168
        $qb = $repo->addRoleListQueryBuilder($announcement->getRoles());
169
        $repo->addAccessUrlQueryBuilder(api_get_current_access_url_id(), $qb);
170
171
        if (!empty($language)) {
172
            $qb
173
                ->andWhere('u.locale = :lang')
174
                ->setParameter('lang', $language);
175
        }
176
177
        $repo->addActiveAndNotAnonUserQueryBuilder($qb);
178
        $repo->addExpirationDateQueryBuilder($qb);
179
180
        // Sent to active users.
181
        //$sql .= " AND email <>'' AND active = 1 ";
182
183
        // Expiration date
184
        //$sql .= " AND (expiration_date = '' OR expiration_date IS NULL OR expiration_date > '$now') ";
185
186
        $userListToFilter = [];
187
        if (in_array('ROLE_TEACHER', $announcement->getRoles(), true)) {
188
            $users =  UserManager::get_user_list(['status' => COURSEMANAGER]);
189
            if (!empty($users)) {
190
                $userListToFilter = array_merge($users, $userListToFilter);
191
            }
192
        }
193
194
        if (in_array('ROLE_STUDENT', $announcement->getRoles(), true)) {
195
            $users = UserManager::get_user_list(['status' => STUDENT]);
196
            if (!empty($users)) {
197
                $userListToFilter = array_merge($users, $userListToFilter);
198
            }
199
        }
200
        // @todo check if other filters will apply for the career/promotion option.
201
        if (null !== $announcement->getCareer()) {
202
            $promotion = new Promotion();
203
            $promotionList = $promotion->get_all_promotions_by_career_id($announcement->getCareer()->getId());
204
            if (null !== $announcement->getPromotion()) {
205
                $promotionList = [];
206
                $promotionList[] = $promotion->get($announcement->getPromotion()->getId());
207
            }
208
209
            if (!empty($promotionList)) {
210
                foreach ($promotionList as $promotion) {
211
                    $sessionList = SessionManager::get_all_sessions_by_promotion($promotion['id']);
212
                    foreach ($sessionList as $session) {
213
                        if (in_array('ROLE_TEACHER', $announcement->getRoles(), true)) {
214
                            $users = SessionManager::get_users_by_session($session['id'], 2);
215
                            if (!empty($users)) {
216
                                $userListToFilter = array_merge($users, $userListToFilter);
217
                            }
218
                        }
219
220
                        if (in_array('ROLE_STUDENT', $announcement->getRoles(), true)) {
221
                            $users = SessionManager::get_users_by_session($session['id'], 0);
222
                            if (!empty($users)) {
223
                                $userListToFilter = array_merge($users, $userListToFilter);
224
                            }
225
                        }
226
                    }
227
                }
228
            }
229
        }
230
231
        if (!empty($userListToFilter)) {
232
            $userListToFilter = array_column($userListToFilter, 'user_id');
233
            //$userListToFilterToString = implode("', '", $userListToFilter);
234
            $qb
235
                ->andWhere('u.id IN (:users)')
236
                ->setParameter('users', $userListToFilter);
237
            //$sql .= " AND (u.user_id IN ('$userListToFilterToString') ) ";
238
        }
239
        $users = $qb->getQuery()->getResult();
240
241
        $message_sent = false;
242
        /** @var User $user */
243
        foreach ($users as $user) {
244
            MessageManager::send_message_simple($user->getId(), $title, $content);
245
            $message_sent = true;
246
        }
247
248
        // Minor validation to clean up the attachment files in the announcement
249
        /*if (!empty($_FILES)) {
250
            $attachments = $_FILES;
251
            foreach ($attachments as $attachment) {
252
                unlink($attachment['tmp_name']);
253
            }
254
        }*/
255
256
        return $message_sent; //true if at least one e-mail was sent
257
    }
258
259
    /**
260
     * Makes the announcement id visible only for groups in groups_array.
261
     *
262
     * @param int   $announcement_id
263
     * @param array $group_array     array of group id
264
     *
265
     * @return bool
266
     */
267
    public static function announcement_for_groups($announcement_id, $group_array)
268
    {
269
        $tbl_announcement_group = Database::get_main_table(
270
            TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS
271
        );
272
        //first delete all group associations for this announcement
273
        $res = Database::query(
274
            "DELETE FROM $tbl_announcement_group
275
             WHERE announcement_id=".intval($announcement_id)
276
        );
277
278
        if (false === $res) {
279
            return false;
280
        }
281
282
        foreach ($group_array as $group_id) {
283
            if (0 != intval($group_id)) {
284
                $sql = "INSERT INTO $tbl_announcement_group SET
285
                        announcement_id=".intval($announcement_id).",
286
                        group_id=".intval($group_id);
287
                $res = Database::query($sql);
288
                if (false === $res) {
289
                    return false;
290
                }
291
            }
292
        }
293
294
        return true;
295
    }
296
297
    /**
298
     * Gets the groups of this announce.
299
     *
300
     * @param int $announcement_id announcement id
301
     *
302
     * @return array array of group id
303
     * @throws Exception
304
     */
305
    public static function get_announcement_groups(int $announcement_id): array
306
    {
307
        if (empty($announcement_id)) {
308
            return [];
309
        }
310
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
311
        $tbl_group = Database::get_main_table(TABLE_USERGROUP);
312
        //first delete all group associations for this announcement
313
        $sql = "SELECT
314
                    g.id as group_id,
315
                    g.title as group_name
316
                FROM $tbl_group g , $tbl_announcement_group ag
317
                WHERE
318
                    announcement_id = $announcement_id AND
319
                    ag.group_id = g.id";
320
        $res = Database::query($sql);
321
322
        $array = Database::fetch_array($res);
323
        if (!empty($array)) {
324
            return $array;
325
        }
326
327
        return [];
328
    }
329
330
    /**
331
     * Updates an announcement to the database.
332
     *
333
     * @param int    $id            of the announcement
334
     * @param string $title         title of the announcement
335
     * @param string $content       content of the announcement
336
     * @param array  $date_start    start date (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
337
     * @param array  $date_end      end date of (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
338
     * @param array  $visibility
339
     * @param array  $lang
340
     * @param int    $send_mail
341
     * @param bool   $sendEmailTest
342
     * @param int    $careerId
343
     * @param int    $promotionId
344
     *
345
     * @return bool True on success, false on failure
346
     */
347
    public static function update_announcement(
348
        $id,
349
        $title,
350
        $content,
351
        $date_start,
352
        $date_end,
353
        $visibility,
354
        $lang = null,
355
        $send_mail = 0,
356
        $sendEmailTest = false,
357
        $careerId = 0,
358
        $promotionId = 0
359
    ) {
360
        $sysRepo = Container::getSysAnnouncementRepository();
361
        /** @var SysAnnouncement|null $announcement */
362
        $announcement = $sysRepo->find($id);
363
        if (null === $announcement) {
364
            return false;
365
        }
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
        $lang = is_null($lang) ? '' : $lang;
377
378
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
379
            echo Display::return_message(get_lang('Invalid start date was given.'));
380
381
            return false;
382
        }
383
384
        if (($date_end_to_compare[1] ||
385
                $date_end_to_compare[2] ||
386
                $date_end_to_compare[0]) &&
387
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
388
        ) {
389
            echo Display::return_message(get_lang('Invalid end date was given.'));
390
391
            return false;
392
        }
393
394
        if (0 == strlen(trim($title))) {
395
            echo Display::return_message(get_lang('Please enter a title'));
396
397
            return false;
398
        }
399
400
        $start = api_get_utc_datetime($date_start);
401
        $end = api_get_utc_datetime($date_end);
402
403
        //Fixing urls that are sent by email
404
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
405
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
406
        $content = str_replace(
407
            'src=\"'.api_get_path(REL_HOME_PATH),
408
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
409
            $content
410
        );
411
        $content = str_replace(
412
            'file='.api_get_path(REL_HOME_PATH),
413
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
414
            $content
415
        );
416
417
        $dateStart = new DateTime($start, new DateTimeZone('UTC'));
418
        $dateEnd = new DateTime($end, new DateTimeZone('UTC'));
419
420
        $announcement
421
            ->setLang($lang)
422
            ->setTitle($title)
423
            ->setContent($content)
424
            ->setDateStart($dateStart)
425
            ->setDateEnd($dateEnd)
426
            ->setRoles($visibility);
427
428
        $sysRepo->update($announcement);
429
430
        // Update visibility
431
        //$list = self::getVisibilityList();
432
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
433
434
        if (('true' === api_get_setting('announcement.allow_careers_in_global_announcements')) && !empty($careerId)) {
435
            $params = [];
436
            $params['career_id'] = (int) $careerId;
437
            $params['promotion_id'] = (int) $promotionId;
438
            Database::update(
439
                $table,
440
                $params,
441
                ['id = ? ' => $id]
442
            );
443
        }
444
445
        /*foreach ($list as $key => $title) {
446
            $value = isset($visibility[$key]) && $visibility[$key] ? 1 : 0;
447
            $sql = "UPDATE $table SET $key = '$value' WHERE id = $id";
448
            Database::query($sql);
449
        }*/
450
451
        if ($sendEmailTest) {
452
            self::send_system_announcement_by_email($announcement, true);
453
        } else {
454
            if (1 == $send_mail) {
455
                self::send_system_announcement_by_email($announcement);
456
            }
457
        }
458
459
        return true;
460
    }
461
}
462