Passed
Push — 1.11.x ( e08fc6...31b6b5 )
by Julito
13:28
created

PauseTraining::create()   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 0
dl 0
loc 5
rs 10
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
class PauseTraining extends Plugin
6
{
7
    protected function __construct()
8
    {
9
        parent::__construct(
10
            '0.1',
11
            'Julio Montoya',
12
            [
13
                'tool_enable' => 'boolean',
14
                'allow_users_to_edit_pause_formation' => 'boolean',
15
                'cron_alert_users_if_inactive_days' => 'text', // Example: "5" or "5,10,15"
16
                'sender_id' => 'user',
17
            ]
18
        );
19
    }
20
21
    public static function create()
22
    {
23
        static $result = null;
24
25
        return $result ? $result : $result = new self();
26
    }
27
28
    public function updateUserPauseTraining($userId, $values)
29
    {
30
        $userInfo = api_get_user_info($userId);
31
        if (empty($userInfo)) {
32
            throw new Exception("User #$userId does not exists");
33
        }
34
35
        $variables = [
36
            'pause_formation',
37
            'start_pause_date',
38
            'end_pause_date',
39
            'disable_emails',
40
        ];
41
42
        $valuesToUpdate = [
43
            'item_id' => $userId,
44
        ];
45
46
        // Check if variables exist.
47
        foreach ($variables as $variable) {
48
            if (!isset($values[$variable])) {
49
                throw new Exception("Variable '$variable' is missing. Cannot updated.");
50
            }
51
52
            $valuesToUpdate['extra_'.$variable] = $values[$variable];
53
        }
54
55
        // Clean variables
56
        $pause = (int) $valuesToUpdate['extra_pause_formation'];
57
        if (empty($pause)) {
58
            $valuesToUpdate['extra_pause_formation'] = 0;
59
        } else {
60
            $valuesToUpdate['extra_pause_formation'] = [];
61
            $valuesToUpdate['extra_pause_formation']['extra_pause_formation'] = $pause;
62
        }
63
64
        $notification = (int) $valuesToUpdate['extra_disable_emails'];
65
        if (empty($notification)) {
66
            $valuesToUpdate['extra_disable_emails'] = 0;
67
        } else {
68
            $valuesToUpdate['extra_disable_emails'] = [];
69
            $valuesToUpdate['extra_disable_emails']['extra_disable_emails'] = $notification;
70
        }
71
72
        $check = DateTime::createFromFormat('Y-m-d H:i', $valuesToUpdate['extra_start_pause_date']);
73
74
        if (false === $check) {
75
            throw new Exception("start_pause_date is not valid date time format should be: Y-m-d H:i");
76
        }
77
78
        $check = DateTime::createFromFormat('Y-m-d H:i', $valuesToUpdate['extra_end_pause_date']);
79
        if (false === $check) {
80
            throw new Exception("end_pause_date is not valid date time format should be: Y-m-d H:i");
81
        }
82
83
        if (api_strtotime($valuesToUpdate['extra_start_pause_date']) > api_strtotime($valuesToUpdate['extra_end_pause_date'])) {
84
            throw new Exception("end_pause_date must be bigger than start_pause_date");
85
        }
86
87
        $extraField = new ExtraFieldValue('user');
88
        $extraField->saveFieldValues($valuesToUpdate, true, false, [], [], true);
89
90
        return (int) $userId;
91
    }
92
93
    public function runCron($date = '', $isTest = false)
94
    {
95
        $enable = $this->get('tool_enable');
96
        $senderId = $this->get('sender_id');
97
        $enableDays = $this->get('cron_alert_users_if_inactive_days');
98
99
        if ('true' !== $enable) {
100
            echo 'Plugin not enabled';
101
102
            return false;
103
        }
104
105
        if (empty($senderId)) {
106
            echo 'Sender id not configured';
107
108
            return false;
109
        }
110
111
        $senderInfo = api_get_user_info($senderId);
112
113
        if (empty($senderInfo)) {
114
            echo "Sender #$senderId not found in Chamilo";
115
116
            return false;
117
        }
118
119
        $enableDaysList = explode(',', $enableDays);
120
        rsort($enableDaysList);
121
122
        $track = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
123
        $login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
124
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
125
        $usersNotificationPerDay = [];
126
        $users = [];
127
128
        $now = api_get_utc_datetime();
129
        if (!empty($date)) {
130
            $now = $date;
131
        }
132
133
        if ($isTest) {
134
            echo "-------------------------------------------".PHP_EOL;
135
            echo "----- Testing date $now ----".PHP_EOL;
136
            echo "-------------------------------------------".PHP_EOL;
137
        }
138
139
        $extraFieldValue = new ExtraFieldValue('user');
140
        foreach ($enableDaysList as $day) {
141
            $day = (int) $day;
142
143
            if (0 === $day) {
144
                echo 'Day = 0 avoided '.PHP_EOL;
145
                continue;
146
            }
147
148
            $hourStart = $day * 24;
149
            $hourEnd = ($day - 1) * 24;
150
151
            $date = new DateTime($now);
152
            $date->sub(new DateInterval('PT'.$hourStart.'H'));
153
            $hourStart = $date->format('Y-m-d H:i:s');
154
155
            $date = new DateTime($now);
156
            $date->sub(new DateInterval('PT'.$hourEnd.'H'));
157
            $hourEnd = $date->format('Y-m-d H:i:s');
158
159
            $sql = "SELECT
160
                    t.user_id,
161
                    MAX(t.logout_course_date) max_course_date,
162
                    MAX(l.logout_date) max_login_date
163
                    FROM $track t
164
                    INNER JOIN $userTable u
165
                    ON (u.id = t.user_id)
166
                    INNER JOIN $login l
167
                    ON (u.id = l.login_user_id)
168
                    WHERE
169
                        u.status <> ".ANONYMOUS." AND
170
                        u.active = 1
171
                    GROUP BY t.user_id
172
                    HAVING
173
                        (max_course_date BETWEEN '$hourStart' AND '$hourEnd') AND
174
                        (max_login_date BETWEEN '$hourStart' AND '$hourEnd')
175
                    ";
176
177
            $rs = Database::query($sql);
178
            if (!Database::num_rows($rs)) {
179
                echo "No users to process for day $day".PHP_EOL.PHP_EOL;
180
                continue;
181
            }
182
183
            echo "Processing day $day".PHP_EOL.PHP_EOL;
184
185
            while ($user = Database::fetch_array($rs)) {
186
                $userId = $user['user_id'];
187
                if (in_array($userId, $users)) {
188
                    continue;
189
                }
190
191
                // Take max date value.
192
                $maxCourseDate = $user['max_course_date'];
193
                $maxLoginDate = $user['max_login_date'];
194
                $maxDate = $maxCourseDate;
195
                if ($maxLoginDate > $maxCourseDate) {
196
                    $maxDate = $maxLoginDate;
197
                }
198
199
                // Check if user has selected to pause formation.
200
                $pause = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'pause_formation');
201
                if (!empty($pause) && isset($pause['value']) && 1 == $pause['value']) {
202
                    $startDate = $extraFieldValue->get_values_by_handler_and_field_variable(
203
                        $userId,
204
                        'start_pause_date'
205
                    );
206
                    $endDate = $extraFieldValue->get_values_by_handler_and_field_variable(
207
                        $userId,
208
                        'end_pause_date'
209
                    );
210
211
                    if (
212
                        !empty($startDate) && isset($startDate['value']) && !empty($startDate['value']) &&
213
                        !empty($endDate) && isset($endDate['value']) && !empty($endDate['value'])
214
                    ) {
215
                        $startDate = $startDate['value'];
216
                        $endDate = $endDate['value'];
217
218
                        // Ignore date if is between the pause formation.
219
                        if ($maxDate > $startDate && $maxDate < $endDate) {
220
                            echo "Message skipped for user #$userId because latest login is $maxDate and pause formation between $startDate - $endDate ".PHP_EOL;
221
                            continue;
222
                        }
223
                    }
224
                }
225
226
                echo "User #$userId added to message queue because latest login is $maxDate between $hourStart AND $hourEnd".PHP_EOL;
227
228
                $users[] = $userId;
229
                $usersNotificationPerDay[$day][] = $userId;
230
            }
231
        }
232
233
        if (!empty($usersNotificationPerDay)) {
234
            echo 'Now processing messages ...'.PHP_EOL;
235
236
            ksort($usersNotificationPerDay);
237
            foreach ($usersNotificationPerDay as $day => $userList) {
238
                $template = new Template(
239
                    '',
240
                    true,
241
                    true,
242
                    false,
243
                    false,
244
                    true,
245
                    false
246
                );
247
                $title = sprintf($this->get_lang('InactivityXDays'), $day);
248
249
                foreach ($userList as $userId) {
250
                    $userInfo = api_get_user_info($userId);
251
                    $template->assign('days', $day);
252
                    $template->assign('user', $userInfo);
253
                    $content = $template->fetch('pausetraining/view/notification_content.tpl');
254
                    echo 'Ready to send a message "'.$title.'" to user #'.$userId.' '.$userInfo['complete_name'].PHP_EOL;
255
                    if (false === $isTest) {
256
                        MessageManager::send_message_simple($userId, $title, $content, $senderId);
257
                    } else {
258
                        echo 'Message not send because is in test mode.'.PHP_EOL;
259
                    }
260
                }
261
            }
262
        }
263
    }
264
265
    public function runCronTest()
266
    {
267
        $now = api_get_utc_datetime();
268
        $days = 30;
269
        $before = new DateTime($now);
270
        $before->sub(new DateInterval('P'.$days.'D'));
271
272
        $after = new DateTime($now);
273
        $after->add(new DateInterval('P'.$days.'D'));
274
275
        $period = new DatePeriod(
276
            $before,
277
            new DateInterval('P1D'),
278
            new $after
279
        );
280
281
        foreach ($period as $key => $value) {
282
            self::runCron($value->format('Y-m-d H:i:s'), true);
283
        }
284
    }
285
286
    public function install()
287
    {
288
        UserManager::create_extra_field(
289
            'pause_formation',
290
            ExtraField::FIELD_TYPE_CHECKBOX,
291
            $this->get_lang('PauseFormation'),
292
            ''
293
        );
294
295
        UserManager::create_extra_field(
296
            'start_pause_date',
297
            ExtraField::FIELD_TYPE_DATETIME,
298
            $this->get_lang('StartPauseDateTime'),
299
            ''
300
        );
301
302
        UserManager::create_extra_field(
303
            'end_pause_date',
304
            ExtraField::FIELD_TYPE_DATETIME,
305
            $this->get_lang('EndPauseDateTime'),
306
            ''
307
        );
308
309
        UserManager::create_extra_field(
310
            'disable_emails',
311
            ExtraField::FIELD_TYPE_CHECKBOX,
312
            $this->get_lang('DisableEmails'),
313
            ''
314
        );
315
    }
316
317
    public function uninstall()
318
    {
319
    }
320
}
321