Passed
Push — master ( aa4c59...a5a2a4 )
by Julito
09:58
created

NotificationEvent::getUserExtraData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 5
rs 10
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
class NotificationEvent extends Model
5
{
6
    public $table;
7
    public $columns = [
8
        'id',
9
        'title',
10
        'content',
11
        'link',
12
        'persistent',
13
        'day_diff',
14
        'event_type',
15
        'event_id',
16
    ];
17
18
    const ACCOUNT_EXPIRATION = 1;
19
    const JUSTIFICATION_EXPIRATION = 2;
20
    public $extraFieldName;
21
22
    /**
23
     * Constructor.
24
     */
25
    public function __construct()
26
    {
27
        parent::__construct();
28
        $this->table = 'notification_event';
29
        $this->extraFieldName = 'notification_event';
30
    }
31
32
    public function eventTypeToString($eventTypeId)
33
    {
34
        $list = $this->getEventsForSelect();
35
36
        return $list[$eventTypeId];
37
    }
38
39
    public function getEventsForSelect()
40
    {
41
        return [
42
            self::ACCOUNT_EXPIRATION => get_lang('AccountExpiration'),
43
            self::JUSTIFICATION_EXPIRATION => get_lang('JustificationExpiration'),
44
        ];
45
    }
46
47
    public function getForm(FormValidator $form, $data = [])
48
    {
49
        $options = $this->getEventsForSelect();
50
        $form->addSelect('event_type', get_lang('EventType'), $options);
51
        $form->freeze('event_type');
52
53
        $eventType = $data['event_type'];
54
        switch ($eventType) {
55
            case self::JUSTIFICATION_EXPIRATION:
56
                $plugin = Justification::create();
57
                $list = $plugin->getList();
58
                $list = array_column($list, 'name', 'id');
59
                $form->addSelect('event_id', get_lang('JustificationType'), $list);
60
                break;
61
            default:
62
                break;
63
        }
64
        $form->freeze('event_id');
65
66
67
        $form->addText('title', get_lang('Title'));
68
        $form->addTextarea('content', get_lang('Content'));
69
        $form->addText('link', get_lang('Link'), false);
70
        $form->addCheckBox('persistent', get_lang('Persistent'));
71
        $form->addNumeric('day_diff', get_lang('DayDiff'), false);
72
73
        return $form;
74
    }
75
76
    public function getAddForm(FormValidator $form)
77
    {
78
        $options = $this->getEventsForSelect();
79
        $eventType = $form->getSubmitValue('event_type');
80
81
        $form->addSelect(
82
            'event_type',
83
            get_lang('EventType'),
84
            $options,
85
            ['placeholder' => get_lang('SelectAnOption'), 'onchange' => 'document.add.submit()']
86
        );
87
88
        if (!empty($eventType)) {
89
            $form->freeze('event_type');
90
            $form->addText('title', get_lang('Title'));
91
            $form->addTextarea('content', get_lang('Content'));
92
            $form->addText('link', get_lang('Link'), false);
93
            $form->addCheckBox('persistent', get_lang('Persistent'));
94
            $form->addNumeric('day_diff', get_lang('DayDiff'), false);
95
96
            switch ($eventType) {
97
                case self::JUSTIFICATION_EXPIRATION:
98
                    $plugin = Justification::create();
99
                    $list = $plugin->getList();
100
                    $list = array_column($list, 'name', 'id');
101
                    $form->addSelect('event_id', get_lang('JustificationType'), $list);
102
                    break;
103
                default:
104
                    break;
105
            }
106
            $form->addButtonSave(get_lang('Save'));
107
        }
108
109
        return $form;
110
    }
111
112
    public function getUserExtraData($userId)
113
    {
114
        $data = UserManager::get_extra_user_data_by_field($userId, $this->extraFieldName);
115
116
        return isset($data['notification_event']) ? $data['notification_event'] : '';
117
    }
118
119
    public function getNotificationsByUser($userId)
120
    {
121
        $userInfo = api_get_user_info($userId);
122
        $events = $this->get_all();
123
        $extraFieldData = $this->getUserExtraData(api_get_user_id());
124
        $allowJustification = api_get_plugin_setting('justification', 'tool_enable') === 'true';
125
126
        $userJustificationList = [];
127
        if ($allowJustification) {
128
            $plugin = Justification::create();
129
            $userJustificationList = $plugin->getUserJustificationList($userId);
130
        }
131
132
        $notifications = [];
133
        foreach ($events as $event) {
134
            $days = (int) $event['day_diff'];
135
            $checkIsRead = $event['persistent'] == 0 ? true : false;
136
            $eventItemId = $event['event_id'];
137
138
            switch ($event['event_type']) {
139
                case self::ACCOUNT_EXPIRATION:
140
                    if (empty($userInfo['expiration_date'])) {
141
                        break;
142
                    }
143
144
                    $id = 'id_'.self::ACCOUNT_EXPIRATION.'_event_'.$event['id'].'_'.$userInfo['id'];
145
146
                    $read = false;
147
                    if ($checkIsRead) {
148
                        $read = $this->isRead($id, $extraFieldData);
149
                    }
150
151
                    $showNotification = $this->showNotification($userInfo['expiration_date'], $days);
152
                    if ($showNotification && $read === false) {
153
                        $notifications[] = [
154
                            'id' => $id,
155
                            'title' => $event['title'],
156
                            'content' => $event['content'],
157
                            'event_text' => get_lang('ExpirationDate').': '.api_get_local_time($userInfo['expiration_date']),
158
                            'link' => $event['link'],
159
                            'persistent' => $event['persistent']
160
                        ];
161
                    }
162
                    break;
163
                case self::JUSTIFICATION_EXPIRATION:
164
                    if (!empty($userJustificationList)) {
165
                        foreach ($userJustificationList as $userJustification) {
166
                            if (empty($userJustification['date_validity'])) {
167
                                continue;
168
                            }
169
170
                            if ($eventItemId != $userJustification['justification_document_id']) {
171
                                continue;
172
                            }
173
174
                            $showNotification = $this->showNotification($userJustification['date_validity'], $days);
175
176
                            $id = 'id_'.self::JUSTIFICATION_EXPIRATION.'_event_'.$event['id'].'_'.$userJustification['id'];
177
178
                            $fieldData = $plugin->getJustification($userJustification['justification_document_id']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $plugin does not seem to be defined for all execution paths leading up to this point.
Loading history...
179
180
                            $read = false;
181
                            if ($checkIsRead) {
182
                                $read = $this->isRead($id, $extraFieldData);
183
                            }
184
185
                            $eventText = $plugin->get_lang('Justification').': '.$fieldData['name'].' <br />';
186
                            $eventText .= $plugin->get_lang('JustificationDate').': '.$userJustification['date_validity'];
187
188
                            $url = $event['link'];
189
                            if (empty($url)) {
190
                                $url = api_get_path(WEB_CODE_PATH).'auth/justification.php#'.$fieldData['code'];
191
                            }
192
193
                            if ($showNotification && $read === false) {
194
                                $notifications[] = [
195
                                    'id' => $id,
196
                                    'title' => $event['title'],
197
                                    'content' => $event['content'],
198
                                    'event_text' => $eventText,
199
                                    'link' => $url,
200
                                    'persistent' => $event['persistent']
201
                                ];
202
                            }
203
                        }
204
                    }
205
                    break;
206
            }
207
        }
208
209
        return $notifications;
210
    }
211
212
    public function isRead($id, $extraData)
213
    {
214
        $userId = api_get_user_id();
215
216
        if (empty($extraData)) {
217
            return false;
218
        }
219
220
        $data = $this->getUserExtraData($userId);
221
        if (empty($data)) {
222
            return false;
223
        }
224
225
        $data = json_decode($data);
226
227
        if (in_array($id, $data)) {
228
            return true;
229
        }
230
231
        return false;
232
    }
233
234
    public function markAsRead($id)
235
    {
236
        if (empty($id)) {
237
            return false;
238
        }
239
        $userId = api_get_user_id();
240
        $data = $this->getUserExtraData($userId);
241
        if (!empty($data)) {
242
            $data = json_decode($data);
243
        } else {
244
            $data = [];
245
        }
246
        $data[] = $id;
247
        $data = json_encode($data);
248
249
        UserManager::update_extra_field_value($userId, $this->extraFieldName, $data);
250
251
        return true;
252
    }
253
254
    public function showNotification($date, $dayDiff)
255
    {
256
        $today = api_get_utc_datetime();
257
        $expiration = api_get_utc_datetime($date, false, true);
258
        $interval = new DateInterval('P'.$dayDiff.'D');
259
        $diff = $expiration->sub($interval);
260
261
        if ($diff->format('Y-m-d H:i:s') < $today) {
262
            return true;
263
        }
264
265
        return false;
266
    }
267
268
    public function install()
269
    {
270
        $sql = "CREATE TABLE IF NOT EXISTS notification_event (
271
            id INT unsigned NOT NULL auto_increment PRIMARY KEY,
272
            title VARCHAR(255),
273
            content TEXT,
274
            link TEXT,
275
            persistent INT,
276
            day_diff INT,
277
            event_type VARCHAR(255)
278
        )";
279
        Database::query($sql);
280
    }
281
}
282