Passed
Push — master ( 689c60...4980bd )
by Julito
09:36
created

send_system_announcement_by_email()   C

Complexity

Conditions 14
Paths 41

Size

Total Lines 93
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 46
c 0
b 0
f 0
nc 41
nop 2
dl 0
loc 93
rs 6.2666

How to fix   Long Method    Complexity   

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:

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