Passed
Push — 1.11.x ( 11f1f3...aae5bd )
by Julito
14:12
created

PauseTraining::updateUserPauseTraining()   B

Complexity

Conditions 9
Paths 34

Size

Total Lines 63
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 37
c 1
b 0
f 0
nc 34
nop 2
dl 0
loc 63
rs 7.7724

How to fix   Long Method   

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
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()
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";
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
        $now = api_get_utc_datetime();
126
        $usersNotificationPerDay = [];
127
        $users = [];
128
129
        $extraFieldValue = new ExtraFieldValue('user');
130
131
        foreach ($enableDaysList as $day) {
132
            $day = (int) $day;
133
134
            if (0 === $day) {
135
                echo 'Day = 0 avoided '.PHP_EOL;
136
                continue;
137
            }
138
139
            $hourStart = $day * 24;
140
            $hourEnd = $day + 1 * 24;
141
142
            $date = new DateTime($now);
143
            $date->sub(new DateInterval('P'.$hourStart.'H'));
144
            $hourStart = $date->format('Y-m-d H:i:s');
145
146
            $date = new DateTime($now);
147
            $date->sub(new DateInterval('P'.$hourEnd.'H'));
148
            $hourEnd = $date->format('Y-m-d H:i:s');
149
150
            $sql = "SELECT
151
                    t.user_id,
152
                    MAX(t.logout_course_date) max_course_date,
153
                    MAX(l.logout_date) max_login_date
154
                    FROM $track t
155
                    INNER JOIN $userTable u
156
                    ON (u.id = t.user_id)
157
                    INNER JOIN $login l
158
                    ON (u.id = l.login_user_id)
159
                    WHERE
160
                        u.status <> ".ANONYMOUS." AND
161
                        u.active = 1
162
                    GROUP BY t.user_id
163
                    HAVING
164
                        (max_course_date BETWEEN '$hourStart' AND '$hourEnd') AND
165
                        (max_login_date BETWEEN '$hourStart' AND '$hourEnd')
166
                    ";
167
168
            $rs = Database::query($sql);
169
            while ($user = Database::fetch_array($rs)) {
170
                $userId = $user['user_id'];
171
                if (in_array($userId, $users)) {
172
                    continue;
173
                }
174
175
                // Take max date value.
176
                $maxCourseDate = $user['max_course_date'];
177
                $maxLoginDate = $user['max_login_date'];
178
                $maxDate = $maxCourseDate;
179
                if ($maxLoginDate > $maxCourseDate) {
180
                    $maxDate = $maxLoginDate;
181
                }
182
183
                // Check if user has selected to pause formation.
184
                $pause = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'pause_formation');
185
                if (!empty($pause) && isset($pause['value']) && 1 == $pause['value']) {
186
                    $startDate = $extraFieldValue->get_values_by_handler_and_field_variable(
187
                        $userId,
188
                        'start_pause_date'
189
                    );
190
                    $endDate = $extraFieldValue->get_values_by_handler_and_field_variable(
191
                        $userId,
192
                        'end_pause_date'
193
                    );
194
195
                    if (
196
                        !empty($startDate) && isset($startDate['value']) && !empty($startDate['value']) &&
197
                        !empty($endDate) && isset($endDate['value']) && !empty($endDate['value'])
198
                    ) {
199
                        $startDate = $startDate['value'];
200
                        $endDate = $endDate['value'];
201
202
                        // Ignore date if is between the pause formation.
203
                        if ($maxDate > $startDate && $maxDate < $endDate) {
204
                            echo "Message skipped for user #$userId because latest login is $maxDate and pause formation between $startDate - $endDate ".PHP_EOL;
205
                            continue;
206
                        }
207
                    }
208
                }
209
210
                echo "User #$userId added to message queue because latest login is $maxDate between $hourStart AND $hourEnd".PHP_EOL;
211
212
                $users[] = $userId;
213
                $usersNotificationPerDay[$day][] = $userId;
214
            }
215
        }
216
217
        if (!empty($usersNotificationPerDay)) {
218
            echo 'Now processing messages ...'.PHP_EOL;
219
220
            ksort($usersNotificationPerDay);
221
            foreach ($usersNotificationPerDay as $day => $userList) {
222
                $template = new Template();
223
                $title = sprintf($this->get_lang('InactivityXDays'), $day);
224
225
                foreach ($userList as $userId) {
226
                    $userInfo = api_get_user_info($userId);
227
                    $template->assign('days', $day);
228
                    $template->assign('user', $userInfo);
229
                    $content = $template->fetch('pausetraining/view/notification_content.tpl');
230
                    echo 'Ready to send a message "'.$title.'" to user #'.$userId.' '.$userInfo['complete_name'].PHP_EOL;
231
                    MessageManager::send_message_simple($userId, $title, $content, $senderId);
232
                }
233
            }
234
        }
235
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
236
    }
237
238
    public function install()
239
    {
240
        UserManager::create_extra_field(
241
            'pause_formation',
242
            ExtraField::FIELD_TYPE_CHECKBOX,
243
            $this->get_lang('PauseFormation'),
244
            ''
245
        );
246
247
        UserManager::create_extra_field(
248
            'start_pause_date',
249
            ExtraField::FIELD_TYPE_DATETIME,
250
            $this->get_lang('StartPauseDateTime'),
251
            ''
252
        );
253
254
        UserManager::create_extra_field(
255
            'end_pause_date',
256
            ExtraField::FIELD_TYPE_DATETIME,
257
            $this->get_lang('EndPauseDateTime'),
258
            ''
259
        );
260
261
        UserManager::create_extra_field(
262
            'disable_emails',
263
            ExtraField::FIELD_TYPE_CHECKBOX,
264
            $this->get_lang('DisableEmails'),
265
            ''
266
        );
267
    }
268
269
    public function uninstall()
270
    {
271
    }
272
}
273