_updateUsers()   F
last analyzed

Complexity

Conditions 26
Paths 11524

Size

Total Lines 151
Code Lines 96

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 96
c 1
b 0
f 0
dl 0
loc 151
rs 0
cc 26
nc 11524
nop 4

How to fix   Long Method    Complexity   

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
/**
6
 * This tool allows platform admins to add users by uploading a CSV or XML file.
7
 */
8
$cidReset = true;
9
require_once __DIR__.'/../inc/global.inc.php';
10
11
// Set this option to true to enforce strict purification for usernames.
12
$purification_option_for_usernames = false;
13
14
/**
15
 * @param array $users
16
 *
17
 * @return array
18
 */
19
function validate_data($users)
20
{
21
    global $defined_auth_sources;
22
    $errors = [];
23
    $usernames = [];
24
    $classExistList = [];
25
    $usergroup = new UserGroup();
26
27
    foreach ($users as $user) {
28
        // 2. Check username, first, check whether it is empty.
29
        if (isset($user['NewUserName'])) {
30
            if (!UserManager::is_username_empty($user['NewUserName'])) {
31
                // 2.1. Check whether username is too long.
32
                if (UserManager::is_username_too_long($user['NewUserName'])) {
33
                    $errors[$user['UserName']][] = get_lang('UserNameTooLong');
34
                }
35
                // 2.2. Check whether the username was used twice in import file.
36
                if (isset($usernames[$user['NewUserName']])) {
37
                    $errors[$user['UserName']][] = get_lang('UserNameUsedTwice');
38
                }
39
                $usernames[$user['UserName']] = 1;
40
                // 2.3. Check whether username is allready occupied.
41
                if (!UserManager::is_username_available($user['NewUserName']) &&
42
                    $user['NewUserName'] != $user['UserName']
43
                ) {
44
                    $errors[$user['UserName']][] = get_lang('UserNameNotAvailable');
45
                }
46
            }
47
        }
48
49
        // 3. Check status.
50
        if (isset($user['Status']) && !api_status_exists($user['Status'])) {
51
            $errors[$user['UserName']][] = get_lang('WrongStatus');
52
        }
53
54
        // 4. Check ClassId
55
        if (!empty($user['ClassId'])) {
56
            $classId = explode('|', trim($user['ClassId']));
57
            foreach ($classId as $id) {
58
                if (in_array($id, $classExistList)) {
59
                    continue;
60
                }
61
                $info = $usergroup->get($id);
62
                if (empty($info)) {
63
                    $errors[$user['UserName']][] = sprintf(get_lang('ClassIdDoesntExists'), $id);
64
                } else {
65
                    $classExistList[] = $info['id'];
66
                }
67
            }
68
        }
69
70
        // 5. Check authentication source
71
        if (!empty($user['AuthSource'])) {
72
            if (!in_array($user['AuthSource'], $defined_auth_sources)) {
73
                $errors[$user['UserName']][] = get_lang('AuthSourceNotAvailable');
74
            }
75
        }
76
    }
77
78
    return $errors;
79
}
80
81
/**
82
 * Update users from the imported data.
83
 *
84
 * @param array $users         List of users.
85
 * @param bool  $resetPassword Optional.
86
 * @param bool  $sendEmail     Optional.
87
 */
88
function _updateUsers(
89
    $users,
90
    $resetPassword = false,
91
    $sendEmail = false,
92
    $askNewPassword = false
93
) {
94
    $usergroup = new UserGroup();
95
    $extraFieldValue = new ExtraFieldValue('user');
96
    if (is_array($users)) {
97
        foreach ($users as $user) {
98
            if (isset($user['Status'])) {
99
                $user['Status'] = api_status_key($user['Status']);
100
            }
101
102
            $userInfo = api_get_user_info_from_username($user['UserName']);
103
104
            if (empty($userInfo)) {
105
                continue;
106
            }
107
            /*
108
            // In specific cases, you might want to only update if the e-mail
109
            // in the CSV is different from the e-mail in the database
110
            if (!empty($user['Email'])) {
111
                if ($user['Email'] == $userInfo['email']) {
112
                    continue;
113
                }
114
            }
115
            */
116
117
            $user_id = $userInfo['user_id'];
118
            $firstName = $user['FirstName'] ?? $userInfo['firstname'];
119
            $lastName = $user['LastName'] ?? $userInfo['lastname'];
120
            $userName = $user['NewUserName'] ?? $userInfo['username'];
121
            $changePassMethod = 0;
122
            $password = null;
123
            $authSource = $userInfo['auth_source'];
124
125
            if ($resetPassword) {
126
                $changePassMethod = 1;
127
            } else {
128
                if (isset($user['Password'])) {
129
                    $changePassMethod = 2;
130
                    $password = $user['Password'];
131
                }
132
133
                if (isset($user['AuthSource']) && $user['AuthSource'] != $authSource) {
134
                    $authSource = $user['AuthSource'];
135
                    $changePassMethod = 3;
136
                }
137
            }
138
139
            $email = $user['Email'] ?? $userInfo['email'];
140
            $status = $user['Status'] ?? $userInfo['status'];
141
            $officialCode = $user['OfficialCode'] ?? $userInfo['official_code'];
142
            $phone = $user['PhoneNumber'] ?? $userInfo['phone'];
143
            $pictureUrl = $user['PictureUri'] ?? $userInfo['picture_uri'];
144
            $expirationDate = $user['ExpiryDate'] ?? $userInfo['expiration_date'];
145
            // Fix wrong date in DB for old users (sometimes would be expiration_date = '9999-12-31 ********') where it should be null
146
            if (substr($expirationDate, 0, 4) === '9999') {
147
                $expirationDate = null;
148
            }
149
            $active = $userInfo['active'];
150
            if (isset($user['Active'])) {
151
                $user['Active'] = (int) $user['Active'];
152
                if (-1 === $user['Active']) {
153
                    $user['Active'] = 0;
154
                }
155
                $active = $user['Active'];
156
            }
157
158
            $creatorId = $userInfo['creator_id'];
159
            $hrDeptId = $userInfo['hr_dept_id'];
160
            $language = $user['Language'] ?? $userInfo['language'];
161
            //$sendEmail = isset($user['SendEmail']) ? $user['SendEmail'] : $userInfo['language'];
162
            //$sendEmail = false;
163
            // see BT#17893
164
            if ($resetPassword && $sendEmail == false) {
165
                $sendEmail = true;
166
            }
167
            $extra = [];
168
            if ($askNewPassword) {
169
                $extra['ask_new_password'] = 1;
170
            }
171
172
            UserManager::update_user(
173
                $user_id,
174
                $firstName,
175
                $lastName,
176
                $userName,
177
                $password,
178
                $authSource,
179
                $email,
180
                $status,
181
                $officialCode,
182
                $phone,
183
                $pictureUrl,
184
                $expirationDate,
185
                $active,
186
                $creatorId,
187
                $hrDeptId,
188
                $extra,
189
                $language,
190
                '',
191
                $sendEmail,
192
                $changePassMethod
193
            );
194
195
            if (!empty($user['Courses']) && !is_array($user['Courses'])) {
196
                $user['Courses'] = [$user['Courses']];
197
            }
198
            if (!empty($user['Courses']) && is_array($user['Courses'])) {
199
                foreach ($user['Courses'] as $course) {
200
                    if (CourseManager::course_exists($course)) {
201
                        CourseManager::subscribeUser($user_id, $course, $user['Status']);
202
                    }
203
                }
204
            }
205
            if (!empty($user['ClassId'])) {
206
                $classId = explode('|', trim($user['ClassId']));
207
                foreach ($classId as $id) {
208
                    $usergroup->subscribe_users_to_usergroup(
209
                        $id,
210
                        [$user_id],
211
                        false
212
                    );
213
                }
214
            }
215
216
            // Saving extra fields.
217
            global $extra_fields;
218
219
            // We are sure that the extra field exists.
220
            $userExtraFields = [
221
                'item_id' => $user_id,
222
            ];
223
            $add = false;
224
            foreach ($extra_fields as $extras) {
225
                if (isset($user[$extras[1]])) {
226
                    $key = $extras[1];
227
                    $value = $user[$extras[1]];
228
                    $userExtraFields["extra_$key"] = $value;
229
                    $add = true;
230
                }
231
            }
232
            if ($add) {
233
                $extraFieldValue->saveFieldValues($userExtraFields, true);
234
            }
235
236
            $userUpdated = api_get_user_info($user_id);
237
            Display::addFlash(
238
                Display::return_message(get_lang('UserUpdated').': '.$userUpdated['complete_name_with_username'])
239
            );
240
        }
241
    }
242
}
243
244
/**
245
 * Read the CSV-file.
246
 *
247
 * @param string $file Path to the CSV-file
248
 *
249
 * @throws Exception
250
 *
251
 * @return array All userinformation read from the file
252
 */
253
function parse_csv_data($file)
254
{
255
    $data = Import::csv_reader($file);
256
    if (empty($data)) {
257
        throw new Exception(get_lang('NoDataAvailable'));
258
    }
259
    $users = [];
260
    foreach ($data as $row) {
261
        if (isset($row['Courses'])) {
262
            $row['Courses'] = explode('|', trim($row['Courses']));
263
        }
264
        if (!isset($row['UserName'])) {
265
            throw new Exception(get_lang('ThisFieldIsRequired').': UserName');
266
        }
267
        $users[] = $row;
268
    }
269
270
    return $users;
271
}
272
273
function parse_xml_data($file)
274
{
275
    $crawler = Import::xml($file);
276
    $crawler = $crawler->filter('Contacts > Contact ');
277
    $array = [];
278
    foreach ($crawler as $domElement) {
279
        $row = [];
280
        foreach ($domElement->childNodes as $node) {
281
            if ($node->nodeName != '#text') {
282
                $row[$node->nodeName] = $node->nodeValue;
283
            }
284
        }
285
        if (!empty($row)) {
286
            $array[] = $row;
287
        }
288
    }
289
290
    return $array;
291
}
292
293
$this_section = SECTION_PLATFORM_ADMIN;
294
api_protect_admin_script(true, null);
295
296
$defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
297
if (isset($extAuthSource) && is_array($extAuthSource)) {
298
    $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
299
}
300
301
$tool_name = get_lang('UpdateUserListXMLCSV');
302
$interbreadcrumb[] = ["url" => 'index.php', "name" => get_lang('PlatformAdmin')];
303
304
set_time_limit(0);
305
$extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
306
307
$form = new FormValidator('user_update_import', 'post', api_get_self());
308
$form->addHeader($tool_name);
309
$form->addFile('import_file', get_lang('ImportFileLocation'), ['accept' => 'text/csv', 'id' => 'import_file']);
310
$form->addCheckBox('reset_password', '', get_lang('AutoGeneratePassword'));
311
if (api_get_configuration_value('force_renew_password_at_first_login') == true) {
312
    $form->addElement(
313
        'checkbox',
314
        'ask_new_password',
315
        '',
316
        get_lang('FirstLoginForceUsersToChangePassword')
317
    );
318
}
319
320
$group = [
321
    $form->createElement('radio', 'sendMail', '', get_lang('Yes'), 1),
322
    $form->createElement('radio', 'sendMail', null, get_lang('No'), 0),
323
];
324
$form->addGroup($group, '', get_lang('SendMailToUsers'));
325
$defaults['sendMail'] = 0;
326
327
if ($form->validate()) {
328
    if (Security::check_token()) {
329
        Security::clear_token();
330
        $formValues = $form->exportValues();
331
332
        if (empty($_FILES['import_file']) || empty($_FILES['import_file']['size'])) {
333
            header('Location: '.api_get_self());
334
            exit;
335
        }
336
337
        $uploadInfo = pathinfo($_FILES['import_file']['name']);
338
339
        if ($uploadInfo['extension'] !== 'csv') {
340
            Display::addFlash(
341
                Display::return_message(get_lang('YouMustImportAFileAccordingToSelectedOption'), 'error')
342
            );
343
344
            header('Location: '.api_get_self());
345
            exit;
346
        }
347
348
        try {
349
            $users = parse_csv_data($_FILES['import_file']['tmp_name']);
350
        } catch (Exception $exception) {
351
            Display::addFlash(
352
                Display::return_message($exception->getMessage(), 'error')
353
            );
354
355
            header('Location: '.api_get_self());
356
            exit;
357
        }
358
359
        $errors = validate_data($users);
360
        $errorUsers = array_keys($errors);
361
        $usersToUpdate = [];
362
363
        foreach ($users as $user) {
364
            if (!in_array($user['UserName'], $errorUsers)) {
365
                $usersToUpdate[] = $user;
366
            }
367
        }
368
369
        $sendEmail = $_POST['sendMail'] ? true : false;
370
        $askNewPassword = isset($formValues['ask_new_password']);
371
372
        _updateUsers($usersToUpdate, isset($formValues['reset_password']), $sendEmail, $askNewPassword);
373
374
        if (empty($errors)) {
375
            Display::addFlash(
376
                Display::return_message(get_lang('FileImported'), 'success')
377
            );
378
        } else {
379
            $warningMessage = '';
380
            foreach ($errors as $errorUsername => $errorUserMessages) {
381
                $warningMessage .= "<strong>$errorUsername</strong>";
382
                $warningMessage .= '<ul><li>'.implode('</li><li>', $errorUserMessages).'</li></ul>';
383
            }
384
385
            Display::addFlash(
386
                Display::return_message(get_lang('FileImportedJustUsersThatAreNotRegistered'), 'warning')
387
            );
388
            Display::addFlash(Display::return_message($warningMessage, 'warning', false));
389
        }
390
    } else {
391
        Display::addFlash(Display::return_message(get_lang('LinkExpired'), 'warning', false));
392
    }
393
394
    header('Location: '.api_get_self());
395
    exit;
396
}
397
398
Display::display_header($tool_name);
399
$token = Security::get_token();
400
401
$form->setDefaults($defaults);
402
$form->addHidden('sec_token', $token);
403
$form->addButtonImport(get_lang('Import'));
404
$form->display();
405
406
$list = [];
407
$list_reponse = [];
408
$result_xml = '';
409
$i = 0;
410
$count_fields = count($extra_fields);
411
if ($count_fields > 0) {
412
    foreach ($extra_fields as $extra) {
413
        $list[] = $extra[1];
414
        $list_reponse[] = 'xxx';
415
        $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
416
        $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
417
        if ($i != $count_fields - 1) {
418
            $result_xml .= '<br/>';
419
        }
420
        $i++;
421
    }
422
}
423
424
?>
425
    <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
426
    <blockquote>
427
    <pre>
428
        <b>UserName</b>;LastName;FirstName;Email;NewUserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;ExpiryDate;Active;Language;<span style="color:red;"><?php if (count($list) > 0) {
429
    echo implode(';', $list).';';
430
} ?></span>Courses;ClassId;
431
        xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;user/teacher/drh;YYYY-MM-DD 00:00:00;0/1;xxx;<span
432
            style="color:red;"><?php if (count($list_reponse) > 0) {
433
    echo implode(';', $list_reponse).';';
434
} ?></span>xxx1|xxx2|xxx3;1;<br/>
435
    </pre>
436
    </blockquote>
437
    <p>
438
<?php
439
Display::display_footer();
440