Completed
Push — master ( 7bef58...5c053f )
by Julito
25:30
created

ScheduledAnnouncement::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
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;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.
Loading history...
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
            //$file = api_get_uploaded_web_url('schedule_announcement', $id, basename($file['value']));
269
            $url = api_get_path(WEB_UPLOAD_PATH).$file['value'];
270
271
            return get_lang('Attachment').': '.Display::url(basename($file['value']), $url, ['target' => '_blank']);
272
        }
273
274
        return '';
275
    }
276
277
    /**
278
     * @param int $id
279
     *
280
     * @return array
281
     */
282
    public function getAttachment($id)
283
    {
284
        $extraFieldValue = new ExtraFieldValue('scheduled_announcement');
285
        $attachment = $extraFieldValue->get_values_by_handler_and_field_variable($id, 'attachment');
286
287
        return $attachment;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $attachment could also return false which is incompatible with the documented return type array. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
288
    }
289
290
    /**
291
     * @param int $urlId
292
     *
293
     * @return int
294
     */
295
    public function sendPendingMessages($urlId = 0)
296
    {
297
        if (!$this->allowed()) {
298
            return 0;
299
        }
300
301
        $messagesSent = 0;
302
        $now = api_get_utc_datetime();
303
        $result = $this->get_all();
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
                    if (empty($users)) {
321
                        continue;
322
                    }
323
324
                    $attachments = $this->getAttachmentToString($result['id']);
325
326
                    self::update(['id' => $result['id'], 'sent' => 1]);
0 ignored issues
show
Bug Best Practice introduced by
The method Model::update() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

326
                    self::/** @scrutinizer ignore-call */ 
327
                          update(['id' => $result['id'], 'sent' => 1]);
Loading history...
327
328
                    $subject = $result['subject'];
329
330
                    if ($users) {
331
                        foreach ($users as $user) {
332
                            // Take original message
333
                            $message = $result['message'];
334
335
                            $userInfo = api_get_user_info($user['user_id']);
336
                            $courseList = SessionManager::getCoursesInSession($sessionId);
337
                            $courseInfo = [];
338
                            if (!empty($courseList)) {
339
                                $courseId = current($courseList);
340
                                $courseInfo = api_get_course_info_by_id($courseId);
341
                            }
342
343
                            $progress = '';
344
                            if (!empty($sessionInfo) && !empty($courseInfo)) {
345
                                $progress = Tracking::get_avg_student_progress(
346
                                    $user['user_id'],
347
                                    $courseInfo['code'],
348
                                    [],
349
                                    $sessionId
350
                                );
351
                            }
352
353
                            if (is_numeric($progress)) {
354
                                $progress = $progress.'%';
355
                            } else {
356
                                $progress = '0%';
357
                            }
358
359
                            $startTime = api_get_local_time(
360
                                $sessionInfo['access_start_date'],
361
                                null,
362
                                null,
363
                                true
364
                            );
365
                            $endTime = api_get_local_time(
366
                                $sessionInfo['access_end_date'],
367
                                null,
368
                                null,
369
                                true
370
                            );
371
372
                            $generalCoach = '';
373
                            $generalCoachEmail = '';
374
                            if (!empty($sessionInfo['coach_id'])) {
375
                                $coachInfo = api_get_user_info($sessionInfo['coach_id']);
376
                                if (!empty($coachInfo)) {
377
                                    $generalCoach = $coachInfo['complete_name'];
378
                                    $generalCoachEmail = $coachInfo['email'];
379
                                }
380
                            }
381
                            $tags = [
382
                                '((session_name))' => $sessionInfo['name'],
383
                                '((session_start_date))' => $startTime,
384
                                '((general_coach))' => $generalCoach,
385
                                '((general_coach_email))' => $generalCoachEmail,
386
                                '((session_end_date))' => $endTime,
387
                                '((user_complete_name))' => $userInfo['complete_name'],
388
                                '((user_first_name))' => $userInfo['firstname'],
389
                                '((user_last_name))' => $userInfo['lastname'],
390
                                '((lp_progress))' => $progress,
391
                            ];
392
393
                            $message = str_replace(array_keys($tags), $tags, $message);
394
                            $message .= $attachments;
395
396
                            MessageManager::send_message(
397
                                $userInfo['user_id'],
398
                                $subject,
399
                                $message
400
                            );
401
                        }
402
                    }
403
404
                    $messagesSent++;
405
                }
406
            }
407
        }
408
409
        return $messagesSent;
410
    }
411
412
    /**
413
     * @return array
414
     */
415
    public function getTags()
416
    {
417
        $tags = [
418
            '((session_name))',
419
            '((session_start_date))',
420
            '((session_end_date))',
421
            '((general_coach))',
422
            '((general_coach_email))',
423
            '((user_complete_name))',
424
            '((user_first_name))',
425
            '((user_last_name))',
426
            '((lp_progress))',
427
        ];
428
429
        return $tags;
430
    }
431
432
    /**
433
     * @return bool
434
     */
435
    public function allowed()
436
    {
437
        return api_get_configuration_value('allow_scheduled_announcements');
438
    }
439
440
    /**
441
     * @param FormValidator $form
442
     */
443
    private function setTagsInForm(&$form)
444
    {
445
        $form->addLabel(
446
            get_lang('Tags'),
447
            Display::return_message(
448
                implode('<br />', $this->getTags()),
449
                'normal',
450
                false
451
            )
452
        );
453
    }
454
}
455