Passed
Push — 1.11.x ( 9cc1fc...47fc14 )
by Julito
21:20 queued 07:34
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
            'allow_notifications',
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_allow_notifications'];
65
        if (empty($notification)) {
66
            $valuesToUpdate['extra_allow_notifications'] = 0;
67
        } else {
68
            $valuesToUpdate['extra_allow_notifications'] = [];
69
            $valuesToUpdate['extra_allow_notifications']['extra_allow_notifications'] = $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
        $loginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
123
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
124
        $now = api_get_utc_datetime();
125
        $usersNotificationPerDay = [];
126
        $users = [];
127
        foreach ($enableDaysList as $day) {
128
            $day = (int) $day;
129
130
            $sql = "SELECT
131
                    stats_login.user_id,
132
                    MAX(stats_login.login_course_date) max_date
133
                    FROM $loginTable stats_login
134
                    INNER JOIN $userTable u
135
                    ON (u.id = stats_login.user_id)
136
                    WHERE
137
                        u.status <> ".ANONYMOUS." AND
138
                        u.active = 1
139
                    GROUP BY stats_login.user_id
140
                    HAVING DATE_SUB('$now', INTERVAL '$day' DAY) > max_date ";
141
142
            $rs = Database::query($sql);
143
            while ($user = Database::fetch_array($rs)) {
144
                $userId = $user['user_id'];
145
146
                if (in_array($userId, $users)) {
147
                    continue;
148
                }
149
                $users[] = $userId;
150
                $usersNotificationPerDay[$day][] = $userId;
151
            }
152
        }
153
154
        if (!empty($usersNotificationPerDay)) {
155
            ksort($usersNotificationPerDay);
156
            $extraFieldValue = new ExtraFieldValue('user');
157
            foreach ($usersNotificationPerDay as $day => $userList) {
158
                $template = new Template();
159
                $title = sprintf($this->get_lang('InactivityXDays'), $day);
160
161
                foreach ($userList as $userId) {
162
                    $userInfo = api_get_user_info($userId);
163
                    $template->assign('days', $day);
164
                    $template->assign('user', $userInfo);
165
                    $content = $template->fetch('pausetraining/view/notification_content.tpl');
166
                    MessageManager::send_message_simple($userId, $title, $content, $senderId);
167
                }
168
            }
169
        }
170
    }
171
172
    public function install()
173
    {
174
        UserManager::create_extra_field(
175
            'pause_formation',
176
            ExtraField::FIELD_TYPE_CHECKBOX,
177
            $this->get_lang('PauseFormation'),
178
            ''
179
        );
180
181
        UserManager::create_extra_field(
182
            'start_pause_date',
183
            ExtraField::FIELD_TYPE_DATETIME,
184
            $this->get_lang('StartPauseDateTime'),
185
            ''
186
        );
187
188
        UserManager::create_extra_field(
189
            'end_pause_date',
190
            ExtraField::FIELD_TYPE_DATETIME,
191
            $this->get_lang('EndPauseDateTime'),
192
            ''
193
        );
194
195
        UserManager::create_extra_field(
196
            'allow_notifications',
197
            ExtraField::FIELD_TYPE_CHECKBOX,
198
            $this->get_lang('AllowEmailNotification'),
199
            ''
200
        );
201
    }
202
203
    public function uninstall()
204
    {
205
    }
206
}
207