Passed
Push — master ( 738da4...5790ec )
by Julito
08:48
created

SystemAnnouncementManager::delete_announcement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 12
rs 10
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 (api_get_configuration_value('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
            } else {
125
                if (1 == $send_mail) {
126
                    self::send_system_announcement_by_email($sysAnnouncement);
127
                }
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
        // @todo check if other filters will apply for the career/promotion option.
188
        if (null !== $announcement->getCareer()) {
189
            $promotion = new Promotion();
190
            $promotionList = $promotion->get_all_promotions_by_career_id($announcement->getCareer()->getId());
191
            if (null !== $announcement->getPromotion()) {
192
                $promotionList = [];
193
                $promotionList[] = $promotion->get($announcement->getPromotion()->getId());
194
            }
195
196
            if (!empty($promotionList)) {
197
                foreach ($promotionList as $promotion) {
198
                    $sessionList = SessionManager::get_all_sessions_by_promotion($promotion['id']);
199
                    foreach ($sessionList as $session) {
200
                        if (in_array('ROLE_TEACHER', $announcement->getRoles(), true)) {
201
                            $users = SessionManager::get_users_by_session($session['id'], 2);
202
                            if (!empty($users)) {
203
                                $userListToFilter = array_merge($users, $userListToFilter);
204
                            }
205
                        }
206
207
                        if (in_array('ROLE_STUDENT', $announcement->getRoles(), true)) {
208
                            $users = SessionManager::get_users_by_session($session['id'], 0);
209
                            if (!empty($users)) {
210
                                $userListToFilter = array_merge($users, $userListToFilter);
211
                            }
212
                        }
213
                    }
214
                }
215
            }
216
        }
217
218
        if (!empty($userListToFilter)) {
219
            $userListToFilter = array_column($userListToFilter, 'user_id');
220
            //$userListToFilterToString = implode("', '", $userListToFilter);
221
            $qb
222
                ->andWhere('u.id IN (:users)')
223
                ->setParameter('users', $userListToFilter);
224
            //$sql .= " AND (u.user_id IN ('$userListToFilterToString') ) ";
225
        }
226
        $users = $qb->getQuery()->getResult();
227
228
        $message_sent = false;
229
        /** @var User $user */
230
        foreach ($users as $user) {
231
            MessageManager::send_message_simple($user->getId(), $title, $content);
232
            $message_sent = true;
233
        }
234
235
        // Minor validation to clean up the attachment files in the announcement
236
        /*if (!empty($_FILES)) {
237
            $attachments = $_FILES;
238
            foreach ($attachments as $attachment) {
239
                unlink($attachment['tmp_name']);
240
            }
241
        }*/
242
243
        return $message_sent; //true if at least one e-mail was sent
244
    }
245
246
    /**
247
     * Makes the announcement id visible only for groups in groups_array.
248
     *
249
     * @param int   $announcement_id
250
     * @param array $group_array array of group id
251
     *
252
     * @return bool
253
     */
254
    public static function announcement_for_groups($announcement_id, $group_array)
255
    {
256
        $tbl_announcement_group = Database::get_main_table(
257
            TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS
258
        );
259
        //first delete all group associations for this announcement
260
        $res = Database::query(
261
            "DELETE FROM $tbl_announcement_group
262
             WHERE announcement_id=".intval($announcement_id)
263
        );
264
265
        if (false === $res) {
266
            return false;
267
        }
268
269
        foreach ($group_array as $group_id) {
270
            if (0 != intval($group_id)) {
271
                $sql = "INSERT INTO $tbl_announcement_group SET
272
                        announcement_id=".intval($announcement_id).",
273
                        group_id=".intval($group_id);
274
                $res = Database::query($sql);
275
                if (false === $res) {
276
                    return false;
277
                }
278
            }
279
        }
280
281
        return true;
282
    }
283
284
    /**
285
     * Gets the groups of this announce.
286
     *
287
     * @param int announcement id
288
     *
289
     * @return array array of group id
290
     */
291
    public static function get_announcement_groups($announcement_id)
292
    {
293
        $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
294
        $tbl_group = Database::get_main_table(TABLE_USERGROUP);
295
        //first delete all group associations for this announcement
296
        $sql = "SELECT
297
                    g.id as group_id,
298
                    g.name as group_name
299
                FROM $tbl_group g , $tbl_announcement_group ag
300
                WHERE
301
                    announcement_id =".intval($announcement_id)." AND
302
                    ag.group_id = g.id";
303
        $res = Database::query($sql);
304
305
        return Database::fetch_array($res);
306
    }
307
308
    /**
309
     * Updates an announcement to the database.
310
     *
311
     * @param int    $id         of the announcement
312
     * @param string $title      title of the announcement
313
     * @param string $content    content of the announcement
314
     * @param array  $date_start start date (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
315
     * @param array  $date_end   end date of (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
316
     * @param array  $visibility
317
     * @param array  $lang
318
     * @param int    $send_mail
319
     * @param bool   $sendEmailTest
320
     * @param int    $careerId
321
     * @param int    $promotionId
322
     *
323
     * @return bool True on success, false on failure
324
     */
325
    public static function update_announcement(
326
        $id,
327
        $title,
328
        $content,
329
        $date_start,
330
        $date_end,
331
        $visibility,
332
        $lang = null,
333
        $send_mail = 0,
334
        $sendEmailTest = false,
335
        $careerId = 0,
336
        $promotionId = 0
337
    ) {
338
        $sysRepo = Container::getSysAnnouncementRepository();
339
        /** @var SysAnnouncement $announcement */
340
        $announcement = $sysRepo->find($id);
341
        if (null === $announcement) {
342
            return false;
343
        }
344
345
        $a_dateS = explode(' ', $date_start);
346
        $a_arraySD = explode('-', $a_dateS[0]);
347
        $a_arraySH = explode(':', $a_dateS[1]);
348
        $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
349
350
        $a_dateE = explode(' ', $date_end);
351
        $a_arrayED = explode('-', $a_dateE[0]);
352
        $a_arrayEH = explode(':', $a_dateE[1]);
353
        $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
354
355
        $lang = is_null($lang) ? '' : $lang;
356
357
        if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
358
            echo Display::return_message(get_lang('Invalid start date was given.'));
359
360
            return false;
361
        }
362
363
        if (($date_end_to_compare[1] ||
364
                $date_end_to_compare[2] ||
365
                $date_end_to_compare[0]) &&
366
            !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
367
        ) {
368
            echo Display::return_message(get_lang('Invalid end date was given.'));
369
370
            return false;
371
        }
372
373
        if (0 == strlen(trim($title))) {
374
            echo Display::return_message(get_lang('Please enter a title'));
375
376
            return false;
377
        }
378
379
        $start = api_get_utc_datetime($date_start);
380
        $end = api_get_utc_datetime($date_end);
381
382
        //Fixing urls that are sent by email
383
        //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
384
        //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
385
        $content = str_replace(
386
            'src=\"'.api_get_path(REL_HOME_PATH),
387
            'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
388
            $content
389
        );
390
        $content = str_replace(
391
            'file='.api_get_path(REL_HOME_PATH),
392
            'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH),
393
            $content
394
        );
395
396
        $dateStart = new DateTime($start, new DateTimeZone('UTC'));
397
        $dateEnd = new DateTime($end, new DateTimeZone('UTC'));
398
399
        $announcement
400
            ->setLang($lang)
401
            ->setTitle($title)
402
            ->setContent($content)
403
            ->setDateStart($dateStart)
404
            ->setDateEnd($dateEnd)
405
            ->setRoles($visibility);
406
407
        $sysRepo->update($announcement);
408
409
        // Update visibility
410
        //$list = self::getVisibilityList();
411
        $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
412
413
        if (api_get_configuration_value('allow_careers_in_global_announcements') && !empty($careerId)) {
414
            $params = [];
415
            $params['career_id'] = (int) $careerId;
416
            $params['promotion_id'] = (int) $promotionId;
417
            Database::update(
418
                $table,
419
                $params,
420
                ['id = ? ' => $id]
421
            );
422
        }
423
424
        /*foreach ($list as $key => $title) {
425
            $value = isset($visibility[$key]) && $visibility[$key] ? 1 : 0;
426
            $sql = "UPDATE $table SET $key = '$value' WHERE id = $id";
427
            Database::query($sql);
428
        }*/
429
430
        if ($sendEmailTest) {
431
            self::send_system_announcement_by_email($announcement, true);
432
        } else {
433
            if (1 == $send_mail) {
434
                self::send_system_announcement_by_email($announcement);
435
            }
436
        }
437
438
        return true;
439
    }
440
}
441