Merge branch 'MDL-64959_master' of https://github.com/abhimanyuZ/moodle
[moodle.git] / admin / tool / uploaduser / locallib.php
CommitLineData
8bdb31ed
PS
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Bulk user registration functions
19 *
ce15d56d
PS
20 * @package tool
21 * @subpackage uploaduser
8bdb31ed
PS
22 * @copyright 2004 onwards Martin Dougiamas (http://dougiamas.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28define('UU_USER_ADDNEW', 0);
29define('UU_USER_ADDINC', 1);
30define('UU_USER_ADD_UPDATE', 2);
31define('UU_USER_UPDATE', 3);
32
33define('UU_UPDATE_NOCHANGES', 0);
34define('UU_UPDATE_FILEOVERRIDE', 1);
35define('UU_UPDATE_ALLOVERRIDE', 2);
36define('UU_UPDATE_MISSING', 3);
37
38define('UU_BULK_NONE', 0);
39define('UU_BULK_NEW', 1);
40define('UU_BULK_UPDATED', 2);
41define('UU_BULK_ALL', 3);
42
43define('UU_PWRESET_NONE', 0);
44define('UU_PWRESET_WEAK', 1);
45define('UU_PWRESET_ALL', 2);
46
47/**
48 * Tracking of processed users.
49 *
50 * This class prints user information into a html table.
51 *
52 * @package core
53 * @subpackage admin
54 * @copyright 2007 Petr Skoda {@link http://skodak.org}
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 */
57class uu_progress_tracker {
58 private $_row;
08157bfe 59 public $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'suspended', 'deleted');
8bdb31ed
PS
60
61 /**
62 * Print table header.
63 * @return void
64 */
65 public function start() {
66 $ci = 0;
ce15d56d 67 echo '<table id="uuresults" class="generaltable boxaligncenter flexible-wrap" summary="'.get_string('uploadusersresult', 'tool_uploaduser').'">';
8bdb31ed
PS
68 echo '<tr class="heading r0">';
69 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('status').'</th>';
ce15d56d 70 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('uucsvline', 'tool_uploaduser').'</th>';
8bdb31ed
PS
71 echo '<th class="header c'.$ci++.'" scope="col">ID</th>';
72 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('username').'</th>';
73 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('firstname').'</th>';
74 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('lastname').'</th>';
75 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('email').'</th>';
76 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('password').'</th>';
77 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('authentication').'</th>';
78 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
08157bfe 79 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('suspended', 'auth').'</th>';
8bdb31ed
PS
80 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
81 echo '</tr>';
82 $this->_row = null;
83 }
84
85 /**
86 * Flush previous line and start a new one.
87 * @return void
88 */
89 public function flush() {
90 if (empty($this->_row) or empty($this->_row['line']['normal'])) {
91 // Nothing to print - each line has to have at least number
92 $this->_row = array();
93 foreach ($this->columns as $col) {
94 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
95 }
96 return;
97 }
98 $ci = 0;
99 $ri = 1;
100 echo '<tr class="r'.$ri.'">';
101 foreach ($this->_row as $key=>$field) {
102 foreach ($field as $type=>$content) {
103 if ($field[$type] !== '') {
104 $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
105 } else {
106 unset($field[$type]);
107 }
108 }
109 echo '<td class="cell c'.$ci++.'">';
110 if (!empty($field)) {
111 echo implode('<br />', $field);
112 } else {
113 echo '&nbsp;';
114 }
115 echo '</td>';
116 }
117 echo '</tr>';
118 foreach ($this->columns as $col) {
119 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
120 }
121 }
122
123 /**
124 * Add tracking info
125 * @param string $col name of column
126 * @param string $msg message
127 * @param string $level 'normal', 'warning' or 'error'
128 * @param bool $merge true means add as new line, false means override all previous text of the same type
129 * @return void
130 */
131 public function track($col, $msg, $level = 'normal', $merge = true) {
132 if (empty($this->_row)) {
133 $this->flush(); //init arrays
134 }
135 if (!in_array($col, $this->columns)) {
136 debugging('Incorrect column:'.$col);
137 return;
138 }
139 if ($merge) {
140 if ($this->_row[$col][$level] != '') {
141 $this->_row[$col][$level] .='<br />';
142 }
143 $this->_row[$col][$level] .= $msg;
144 } else {
145 $this->_row[$col][$level] = $msg;
146 }
147 }
148
149 /**
150 * Print the table end
151 * @return void
152 */
153 public function close() {
154 $this->flush();
155 echo '</table>';
156 }
157}
158
159/**
160 * Validation callback function - verified the column line of csv file.
623966a3 161 * Converts standard column names to lowercase.
8bdb31ed 162 * @param csv_import_reader $cir
623966a3
PS
163 * @param array $stdfields standard user fields
164 * @param array $profilefields custom profile fields
8bdb31ed
PS
165 * @param moodle_url $returnurl return url in case of any error
166 * @return array list of fields
167 */
623966a3 168function uu_validate_user_upload_columns(csv_import_reader $cir, $stdfields, $profilefields, moodle_url $returnurl) {
8bdb31ed
PS
169 $columns = $cir->get_columns();
170
171 if (empty($columns)) {
172 $cir->close();
173 $cir->cleanup();
174 print_error('cannotreadtmpfile', 'error', $returnurl);
175 }
176 if (count($columns) < 2) {
177 $cir->close();
178 $cir->cleanup();
179 print_error('csvfewcolumns', 'error', $returnurl);
180 }
181
182 // test columns
183 $processed = array();
184 foreach ($columns as $key=>$unused) {
623966a3 185 $field = $columns[$key];
9fff4ebb 186 $field = trim($field);
2f1e464a 187 $lcfield = core_text::strtolower($field);
623966a3
PS
188 if (in_array($field, $stdfields) or in_array($lcfield, $stdfields)) {
189 // standard fields are only lowercase
190 $newfield = $lcfield;
191
192 } else if (in_array($field, $profilefields)) {
193 // exact profile field name match - these are case sensitive
194 $newfield = $field;
195
196 } else if (in_array($lcfield, $profilefields)) {
197 // hack: somebody wrote uppercase in csv file, but the system knows only lowercase profile field
198 $newfield = $lcfield;
199
2a34360e 200 } else if (preg_match('/^(sysrole|cohort|course|group|type|role|enrolperiod|enrolstatus)\d+$/', $lcfield)) {
623966a3
PS
201 // special fields for enrolments
202 $newfield = $lcfield;
203
204 } else {
205 $cir->close();
206 $cir->cleanup();
8bdb31ed
PS
207 print_error('invalidfieldname', 'error', $returnurl, $field);
208 }
623966a3 209 if (in_array($newfield, $processed)) {
8bdb31ed
PS
210 $cir->close();
211 $cir->cleanup();
623966a3 212 print_error('duplicatefieldname', 'error', $returnurl, $newfield);
8bdb31ed 213 }
623966a3 214 $processed[$key] = $newfield;
8bdb31ed
PS
215 }
216
217 return $processed;
218}
219
220/**
221 * Increments username - increments trailing number or adds it if not present.
222 * Varifies that the new username does not exist yet
223 * @param string $username
224 * @return incremented username which does not exist yet
225 */
226function uu_increment_username($username) {
227 global $DB, $CFG;
228
229 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
230 $username = $username.'2';
231 } else {
232 $username = $matches[1][0].($matches[2][0]+1);
233 }
234
235 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
236 return uu_increment_username($username);
237 } else {
238 return $username;
239 }
240}
241
242/**
243 * Check if default field contains templates and apply them.
244 * @param string template - potential tempalte string
245 * @param object user object- we need username, firstname and lastname
246 * @return string field value
247 */
248function uu_process_template($template, $user) {
249 if (is_array($template)) {
250 // hack for for support of text editors with format
251 $t = $template['text'];
252 } else {
253 $t = $template;
254 }
255 if (strpos($t, '%') === false) {
256 return $template;
257 }
258
259 $username = isset($user->username) ? $user->username : '';
260 $firstname = isset($user->firstname) ? $user->firstname : '';
261 $lastname = isset($user->lastname) ? $user->lastname : '';
262
263 $callback = partial('uu_process_template_callback', $username, $firstname, $lastname);
264
265 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', $callback, $t);
266
267 if (is_null($result)) {
268 return $template; //error during regex processing??
43070e61
PS
269 }
270
271 if (is_array($template)) {
272 $template['text'] = $result;
273 return $t;
8bdb31ed 274 } else {
43070e61 275 return $result;
8bdb31ed
PS
276 }
277}
278
279/**
280 * Internal callback function.
281 */
43070e61 282function uu_process_template_callback($username, $firstname, $lastname, $block) {
8bdb31ed 283 switch ($block[3]) {
43070e61
PS
284 case 'u':
285 $repl = $username;
286 break;
287 case 'f':
288 $repl = $firstname;
289 break;
290 case 'l':
291 $repl = $lastname;
292 break;
293 default:
294 return $block[0];
8bdb31ed 295 }
43070e61 296
8bdb31ed 297 switch ($block[1]) {
43070e61 298 case '+':
2f1e464a 299 $repl = core_text::strtoupper($repl);
43070e61
PS
300 break;
301 case '-':
2f1e464a 302 $repl = core_text::strtolower($repl);
43070e61
PS
303 break;
304 case '~':
2f1e464a 305 $repl = core_text::strtotitle($repl);
43070e61 306 break;
8bdb31ed 307 }
43070e61 308
8bdb31ed 309 if (!empty($block[2])) {
2f1e464a 310 $repl = core_text::substr($repl, 0 , $block[2]);
8bdb31ed
PS
311 }
312
313 return $repl;
314}
315
316/**
317 * Returns list of auth plugins that are enabled and known to work.
318 *
319 * If ppl want to use some other auth type they have to include it
320 * in the CSV file next on each line.
321 *
322 * @return array type=>name
323 */
324function uu_supported_auths() {
9b29f686 325 // Get all the enabled plugins.
8bdb31ed
PS
326 $plugins = get_enabled_auth_plugins();
327 $choices = array();
328 foreach ($plugins as $plugin) {
9b29f686
MN
329 $objplugin = get_auth_plugin($plugin);
330 // If the plugin can not be manually set skip it.
331 if (!$objplugin->can_be_manually_set()) {
8bdb31ed
PS
332 continue;
333 }
334 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
335 }
336
337 return $choices;
338}
339
340/**
341 * Returns list of roles that are assignable in courses
342 * @return array
343 */
344function uu_allowed_roles() {
345 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
bf006d2c 346 $roles = get_assignable_roles(context_course::instance(SITEID), ROLENAME_ORIGINALANDSHORT);
8bdb31ed
PS
347 return array_reverse($roles, true);
348}
349
350/**
351 * Returns mapping of all roles using short role name as index.
352 * @return array
353 */
354function uu_allowed_roles_cache() {
bf006d2c 355 $allowedroles = get_assignable_roles(context_course::instance(SITEID), ROLENAME_SHORT);
8bdb31ed
PS
356 foreach ($allowedroles as $rid=>$rname) {
357 $rolecache[$rid] = new stdClass();
358 $rolecache[$rid]->id = $rid;
359 $rolecache[$rid]->name = $rname;
360 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
361 $rolecache[$rname] = new stdClass();
362 $rolecache[$rname]->id = $rid;
363 $rolecache[$rname]->name = $rname;
364 }
365 }
366 return $rolecache;
367}
bd8dc9ba 368
2a34360e
SP
369/**
370 * Returns mapping of all system roles using short role name as index.
371 * @return array
372 */
373function uu_allowed_sysroles_cache() {
374 $allowedroles = get_assignable_roles(context_system::instance(), ROLENAME_SHORT);
375 foreach ($allowedroles as $rid => $rname) {
376 $rolecache[$rid] = new stdClass();
377 $rolecache[$rid]->id = $rid;
378 $rolecache[$rid]->name = $rname;
379 if (!is_numeric($rname)) { // Only non-numeric shortnames are supported!
380 $rolecache[$rname] = new stdClass();
381 $rolecache[$rname]->id = $rid;
382 $rolecache[$rname]->name = $rname;
383 }
384 }
385 return $rolecache;
386}
387
bd8dc9ba
RT
388/**
389 * Pre process custom profile data, and update it with corrected value
390 *
391 * @param stdClass $data user profile data
392 * @return stdClass pre-processed custom profile data
393 */
394function uu_pre_process_custom_profile_data($data) {
395 global $CFG, $DB;
396 // find custom profile fields and check if data needs to converted.
397 foreach ($data as $key => $value) {
398 if (preg_match('/^profile_field_/', $key)) {
399 $shortname = str_replace('profile_field_', '', $key);
400 if ($fields = $DB->get_records('user_info_field', array('shortname' => $shortname))) {
401 foreach ($fields as $field) {
402 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
403 $newfield = 'profile_field_'.$field->datatype;
404 $formfield = new $newfield($field->id, $data->id);
405 if (method_exists($formfield, 'convert_external_data')) {
406 $data->$key = $formfield->convert_external_data($value);
407 }
408 }
409 }
410 }
411 }
412 return $data;
413}
1b4d2d56
RT
414
415/**
416 * Checks if data provided for custom fields is correct
417 * Currently checking for custom profile field or type menu
418 *
419 * @param array $data user profile data
420 * @return bool true if no error else false
421 */
422function uu_check_custom_profile_data(&$data) {
423 global $CFG, $DB;
424 $noerror = true;
ada40715 425 $testuserid = null;
1b4d2d56 426
ada40715
NK
427 if (!empty($data['username'])) {
428 if (preg_match('/id=(.*)"/i', $data['username'], $result)) {
429 $testuserid = $result[1];
430 }
431 }
432 // Find custom profile fields and check if data needs to converted.
1b4d2d56
RT
433 foreach ($data as $key => $value) {
434 if (preg_match('/^profile_field_/', $key)) {
435 $shortname = str_replace('profile_field_', '', $key);
436 if ($fields = $DB->get_records('user_info_field', array('shortname' => $shortname))) {
437 foreach ($fields as $field) {
438 require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
439 $newfield = 'profile_field_'.$field->datatype;
440 $formfield = new $newfield($field->id, 0);
441 if (method_exists($formfield, 'convert_external_data') &&
442 is_null($formfield->convert_external_data($value))) {
443 $data['status'][] = get_string('invaliduserfield', 'error', $shortname);
444 $noerror = false;
445 }
ada40715
NK
446 // Check for duplicate value.
447 if (method_exists($formfield, 'edit_validate_field') ) {
68665272
AN
448 $testuser = new stdClass();
449 $testuser->{$key} = $value;
450 $testuser->id = $testuserid;
ada40715
NK
451 $err = $formfield->edit_validate_field($testuser);
452 if (!empty($err[$key])) {
453 $data['status'][] = $err[$key].' ('.$key.')';
454 $noerror = false;
455 }
456 }
1b4d2d56
RT
457 }
458 }
459 }
460 }
461 return $noerror;
68665272 462}