Passed
Push — master ( 447a4c...2f567c )
by Julito
09:40
created

ScheduledAnnouncement::returnSimpleForm()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 17
nc 2
nop 4
dl 0
loc 27
rs 9.7
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class ScheduledAnnouncement
6
 * Requires DB change:.
7
 *
8
 * CREATE TABLE scheduled_announcements (id INT AUTO_INCREMENT NOT NULL, subject VARCHAR(255) NOT NULL, message LONGTEXT NOT NULL, date DATETIME DEFAULT NULL, sent TINYINT(1) NOT NULL, session_id INT NOT NULL, c_id INT DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
9
 *
10
 * Config setting:
11
 * $_configuration['allow_scheduled_announcements'] = true;
12
 *
13
 * Setup linux cron file:
14
 * main/cron/scheduled_announcement.php
15
 *
16
 * Requires:
17
 * composer update
18
 *
19
 * @package chamilo.library
20
 */
21
class ScheduledAnnouncement extends Model
22
{
23
    public $table;
24
    public $columns = ['id', 'subject', 'message', 'date', 'sent', 'session_id'];
25
26
    /**
27
     * Constructor.
28
     */
29
    public function __construct()
30
    {
31
        parent::__construct();
32
        $this->table = 'scheduled_announcements';
33
    }
34
35
    /**
36
     * @param array $where_conditions
37
     *
38
     * @return array
39
     */
40
    public function get_all($where_conditions = [])
41
    {
42
        return Database::select(
43
            '*',
44
            $this->table,
45
            ['where' => $where_conditions, 'order' => 'subject ASC']
46
        );
47
    }
48
49
    /**
50
     * @return mixed
51
     */
52
    public function get_count()
53
    {
54
        $row = Database::select(
55
            'count(*) as count',
56
            $this->table,
57
            [],
58
            'first'
59
        );
60
61
        return $row['count'];
62
    }
63
64
    /**
65
     * Displays the title + grid.
66
     *
67
     * @param int $sessionId
68
     *
69
     * @return string
70
     */
71
    public function getGrid($sessionId)
72
    {
73
        // action links
74
        $action = '<div class="actions" style="margin-bottom:20px">';
75
        $action .= Display::url(
76
            Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM),
77
            api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$sessionId
78
        );
79
80
        $action .= '<a href="'.api_get_self().'?action=add&session_id='.$sessionId.'">'.
81
            Display::return_icon('add.png', get_lang('Add'), '', ICON_SIZE_MEDIUM).'</a>';
82
        $action .= '<a href="scheduled_announcement.php?action=run&session_id='.$sessionId.'">'.
83
            Display::return_icon('tuning.png', get_lang('SendManuallyPendingAnnouncements'), '', ICON_SIZE_MEDIUM).
84
            '</a>';
85
86
        $action .= '</div>';
87
88
        $html = $action;
89
        $html .= '<div id="session-table" class="table-responsive">';
90
        $html .= Display::grid_html('programmed');
91
        $html .= '</div>';
92
93
        return $html;
94
    }
95
96
    /**
97
     * Returns a Form validator Obj.
98
     *
99
     * @param int    $id
100
     * @param string $url
101
     * @param string $action      add, edit
102
     * @param array  $sessionInfo
103
     *
104
     * @return FormValidator form validator obj
105
     */
106
    public function returnSimpleForm($id, $url, $action, $sessionInfo = [])
107
    {
108
        $form = new FormValidator(
109
            'announcement',
110
            'post',
111
            $url
112
        );
113
114
        $form->addHidden('session_id', $sessionInfo['id']);
115
        $form->addDateTimePicker('date', get_lang('Date'));
116
        $form->addText('subject', get_lang('Subject'));
117
        $form->addHtmlEditor('message', get_lang('Message'));
118
119
        $extraField = new ExtraField('scheduled_announcement');
120
        $extra = $extraField->addElements($form, $id);
121
        $js = $extra['jquery_ready_content'];
122
        $form->addHtml("<script> $(function() { $js }); </script> ");
123
124
        $this->setTagsInForm($form);
125
126
        $form->addCheckBox('sent', null, get_lang('MessageSent'));
127
128
        if ($action == 'edit') {
129
            $form->addButtonUpdate(get_lang('Modify'));
130
        }
131
132
        return $form;
133
    }
134
135
    /**
136
     * Returns a Form validator Obj.
137
     *
138
     * @todo the form should be auto generated
139
     *
140
     * @param string $url
141
     * @param string $action add, edit
142
     * @param array
143
     *
144
     * @return FormValidator form validator obj
145
     */
146
    public function returnForm($url, $action, $sessionInfo = [])
147
    {
148
        // Setting the form elements
149
        $header = get_lang('Add');
150
151
        if ($action == 'edit') {
152
            $header = get_lang('Modify');
153
        }
154
155
        $form = new FormValidator(
156
            'announcement',
157
            'post',
158
            $url
159
        );
160
161
        $form->addHeader($header);
162
        if ($action == 'add') {
163
            $form->addHtml(
164
                Display::return_message(
165
                    nl2br(get_lang('ScheduleAnnouncementDescription')),
166
                    'normal',
167
                    false
168
                )
169
            );
170
        }
171
        $form->addHidden('session_id', $sessionInfo['id']);
172
173
        $useBaseDate = false;
174
        $startDate = $sessionInfo['access_start_date'];
175
        $endDate = $sessionInfo['access_end_date'];
176
177
        if (!empty($startDate) || !empty($endDate)) {
178
            $useBaseDate = true;
179
        }
180
181
        $typeOptions = [
182
            'specific_date' => get_lang('SpecificDate'),
183
        ];
184
185
        if ($useBaseDate) {
186
            $typeOptions['base_date'] = get_lang('BaseDate');
187
        }
188
189
        $form->addSelect(
190
            'type',
191
            get_lang('Type'),
192
            $typeOptions,
193
            [
194
                'onchange' => "javascript: 
195
                    if (this.options[this.selectedIndex].value == 'base_date') {
196
                        document.getElementById('options').style.display = 'block';
197
                        document.getElementById('specific_date').style.display = 'none';
198
                    } else {
199
                        document.getElementById('options').style.display = 'none';
200
                        document.getElementById('specific_date').style.display = 'block';
201
                    }
202
            ", ]
203
        );
204
205
        $form->addHtml('<div id="specific_date">');
206
        $form->addDateTimePicker('date', get_lang('Date'));
207
        $form->addHtml('</div>');
208
        $form->addHtml('<div id="options" style="display:none">');
209
210
        $startDate = $sessionInfo['access_start_date'];
211
        $endDate = $sessionInfo['access_end_date'];
212
213
        $form->addText(
214
            'days',
215
            get_lang('Days'),
216
            false
217
        );
218
219
        $form->addSelect(
220
            'moment_type',
221
            get_lang('AfterOrBefore'),
222
            [
223
                'after' => get_lang('After'),
224
                'before' => get_lang('Before'),
225
            ]
226
        );
227
228
        if (!empty($startDate)) {
229
            $options['start_date'] = get_lang('StartDate').' - '.$startDate;
230
        }
231
232
        if (!empty($endDate)) {
233
            $options['end_date'] = get_lang('EndDate').' - '.$endDate;
234
        }
235
        if (!empty($options)) {
236
            $form->addSelect('base_date', get_lang('BaseDate'), $options);
237
        }
238
239
        $form->addHtml('</div>');
240
        $form->addText('subject', get_lang('Subject'));
241
        $form->addHtmlEditor('message', get_lang('Message'));
242
243
        $extraField = new ExtraField('scheduled_announcement');
244
        $extra = $extraField->addElements($form);
245
        $js = $extra['jquery_ready_content'];
246
        $form->addHtml("<script> $(function() { $js }); </script> ");
247
248
        $this->setTagsInForm($form);
249
250
        if ($action == 'edit') {
251
            $form->addButtonUpdate(get_lang('Modify'));
252
        } else {
253
            $form->addButtonCreate(get_lang('Add'));
254
        }
255
256
        return $form;
257
    }
258
259
    /**
260
     * @param int $id
261
     *
262
     * @return string
263
     */
264
    public function getAttachmentToString($id)
265
    {
266
        $file = $this->getAttachment($id);
267
        if (!empty($file) && !empty($file['value'])) {
268
            $url = api_get_path(WEB_UPLOAD_PATH).$file['value'];
269
270
            return get_lang('Attachment').': '.Display::url(basename($file['value']), $url, ['target' => '_blank']);
271
        }
272
273
        return '';
274
    }
275
276
    /**
277
     * @param int $id
278
     *
279
     * @return array
280
     */
281
    public function getAttachment($id)
282
    {
283
        $extraFieldValue = new ExtraFieldValue('scheduled_announcement');
284
        $attachment = $extraFieldValue->get_values_by_handler_and_field_variable($id, 'attachment');
285
286
        return $attachment;
287
    }
288
289
    /**
290
     * @param int $urlId
291
     *
292
     * @return int
293
     */
294
    public function sendPendingMessages($urlId = 0)
295
    {
296
        if (!$this->allowed()) {
297
            return 0;
298
        }
299
300
        $messagesSent = 0;
301
        $now = api_get_utc_datetime();
302
        $result = $this->get_all();
303
        $extraFieldValue = new ExtraFieldValue('scheduled_announcement');
304
305
        foreach ($result as $result) {
306
            if (empty($result['sent'])) {
307
                if (!empty($result['date']) && $result['date'] < $now) {
308
                    $sessionId = $result['session_id'];
309
                    $sessionInfo = api_get_session_info($sessionId);
310
                    if (empty($sessionInfo)) {
311
                        continue;
312
                    }
313
                    $users = SessionManager::get_users_by_session(
314
                        $sessionId,
315
                        0,
316
                        false,
317
                        $urlId
318
                    );
319
320
                    $coachId = $sessionInfo['id_coach'];
321
322
                    if (empty($users) || empty($coachId)) {
323
                        continue;
324
                    }
325
326
                    if ($users) {
327
                        $sendToCoaches = $extraFieldValue->get_values_by_handler_and_field_variable($result['id'], 'send_to_coaches');
328
                        $courseList = SessionManager::getCoursesInSession($sessionId);
329
                        $coachList = [];
330
                        if (!empty($sendToCoaches) && !empty($sendToCoaches['value']) && $sendToCoaches['value'] == 1) {
331
                            foreach ($courseList as $courseItemId) {
332
                                $coaches = SessionManager::getCoachesByCourseSession(
333
                                    $sessionId,
334
                                    $courseItemId
335
                                );
336
                                $coachList = array_merge($coachList, $coaches);
337
                            }
338
                            $coachList = array_unique($coachList);
339
                        }
340
341
                        $this->update(['id' => $result['id'], 'sent' => 1]);
342
                        $attachments = $this->getAttachmentToString($result['id']);
343
                        $subject = $result['subject'];
344
345
                        $courseInfo = [];
346
                        if (!empty($courseList)) {
347
                            $courseId = current($courseList);
348
                            $courseInfo = api_get_course_info_by_id($courseId);
349
                        }
350
351
                        foreach ($users as $user) {
352
                            // Take original message
353
                            $message = $result['message'];
354
                            $userInfo = api_get_user_info($user['user_id']);
355
356
                            $progress = '';
357
                            if (!empty($sessionInfo) && !empty($courseInfo)) {
358
                                $progress = Tracking::get_avg_student_progress(
359
                                    $user['user_id'],
360
                                    $courseInfo['code'],
361
                                    [],
362
                                    $sessionId
363
                                );
364
                            }
365
366
                            if (is_numeric($progress)) {
367
                                $progress = $progress.'%';
368
                            } else {
369
                                $progress = '0%';
370
                            }
371
372
                            $startTime = api_get_local_time(
373
                                $sessionInfo['access_start_date'],
374
                                null,
375
                                null,
376
                                true
377
                            );
378
                            $endTime = api_get_local_time(
379
                                $sessionInfo['access_end_date'],
380
                                null,
381
                                null,
382
                                true
383
                            );
384
385
                            $generalCoach = '';
386
                            $generalCoachEmail = '';
387
                            if (!empty($sessionInfo['id_coach'])) {
388
                                $coachInfo = api_get_user_info($sessionInfo['id_coach']);
389
                                if (!empty($coachInfo)) {
390
                                    $generalCoach = $coachInfo['complete_name'];
391
                                    $generalCoachEmail = $coachInfo['email'];
392
                                }
393
                            }
394
395
                            $tags = [
396
                                '((session_name))' => $sessionInfo['name'],
397
                                '((session_start_date))' => $startTime,
398
                                '((general_coach))' => $generalCoach,
399
                                '((general_coach_email))' => $generalCoachEmail,
400
                                '((session_end_date))' => $endTime,
401
                                '((user_complete_name))' => $userInfo['complete_name'],
402
                                '((user_first_name))' => $userInfo['firstname'],
403
                                '((user_last_name))' => $userInfo['lastname'],
404
                                '((lp_progress))' => $progress,
405
                            ];
406
407
                            $message = str_replace(array_keys($tags), $tags, $message);
408
                            $message .= $attachments;
409
410
                            MessageManager::send_message_simple(
411
                                $userInfo['user_id'],
412
                                $subject,
413
                                $message,
414
                                $coachId
415
                            );
416
                        }
417
418
                        $message = get_lang('YouAreReceivingACopyBecauseYouAreACourseCoach').'<br /><br />'.$message;
419
420
                        foreach ($coachList as $courseCoachId) {
421
                            MessageManager::send_message_simple(
422
                                $courseCoachId,
423
                                get_lang('YouAreReceivingACopyBecauseYouAreACourseCoach').'&nbsp;'.$subject,
424
                                $message,
425
                                $coachId
426
                            );
427
                        }
428
                    }
429
430
                    $messagesSent++;
431
                }
432
            }
433
        }
434
435
        return $messagesSent;
436
    }
437
438
    /**
439
     * @return array
440
     */
441
    public function getTags()
442
    {
443
        $tags = [
444
            '((session_name))',
445
            '((session_start_date))',
446
            '((session_end_date))',
447
            '((general_coach))',
448
            '((general_coach_email))',
449
            '((user_complete_name))',
450
            '((user_first_name))',
451
            '((user_last_name))',
452
            '((lp_progress))',
453
        ];
454
455
        return $tags;
456
    }
457
458
    /**
459
     * @return bool
460
     */
461
    public function allowed()
462
    {
463
        return api_get_configuration_value('allow_scheduled_announcements');
464
    }
465
466
    /**
467
     * @param FormValidator $form
468
     */
469
    private function setTagsInForm(&$form)
470
    {
471
        $form->addLabel(
472
            get_lang('Tags'),
473
            Display::return_message(
474
                implode('<br />', $this->getTags()),
475
                'normal',
476
                false
477
            )
478
        );
479
    }
480
}
481