2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Bulk user registration functions
21 * @subpackage uploaduser
22 * @copyright 2004 onwards Martin Dougiamas (http://dougiamas.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 define('UU_USER_ADDNEW', 0);
29 define('UU_USER_ADDINC', 1);
30 define('UU_USER_ADD_UPDATE', 2);
31 define('UU_USER_UPDATE', 3);
33 define('UU_UPDATE_NOCHANGES', 0);
34 define('UU_UPDATE_FILEOVERRIDE', 1);
35 define('UU_UPDATE_ALLOVERRIDE', 2);
36 define('UU_UPDATE_MISSING', 3);
38 define('UU_BULK_NONE', 0);
39 define('UU_BULK_NEW', 1);
40 define('UU_BULK_UPDATED', 2);
41 define('UU_BULK_ALL', 3);
43 define('UU_PWRESET_NONE', 0);
44 define('UU_PWRESET_WEAK', 1);
45 define('UU_PWRESET_ALL', 2);
48 * Tracking of processed users.
50 * This class prints user information into a html table.
54 * @copyright 2007 Petr Skoda {@link http://skodak.org}
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57 class uu_progress_tracker {
59 public $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'suspended', 'deleted');
65 public function start() {
67 echo '<table id="uuresults" class="generaltable boxaligncenter flexible-wrap" summary="'.get_string('uploadusersresult', 'tool_uploaduser').'">';
68 echo '<tr class="heading r0">';
69 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('status').'</th>';
70 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('uucsvline', 'tool_uploaduser').'</th>';
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>';
79 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('suspended', 'auth').'</th>';
80 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
86 * Flush previous line and start a new one.
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'=>'');
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>';
106 unset($field[$type]);
109 echo '<td class="cell c'.$ci++.'">';
110 if (!empty($field)) {
111 echo implode('<br />', $field);
118 foreach ($this->columns as $col) {
119 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
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
131 public function track($col, $msg, $level = 'normal', $merge = true) {
132 if (empty($this->_row)) {
133 $this->flush(); //init arrays
135 if (!in_array($col, $this->columns)) {
136 debugging('Incorrect column:'.$col);
140 if ($this->_row[$col][$level] != '') {
141 $this->_row[$col][$level] .='<br />';
143 $this->_row[$col][$level] .= $msg;
145 $this->_row[$col][$level] = $msg;
150 * Print the table end
153 public function close() {
160 * Validation callback function - verified the column line of csv file.
161 * Converts standard column names to lowercase.
162 * @param csv_import_reader $cir
163 * @param array $stdfields standard user fields
164 * @param array $profilefields custom profile fields
165 * @param moodle_url $returnurl return url in case of any error
166 * @return array list of fields
168 function uu_validate_user_upload_columns(csv_import_reader $cir, $stdfields, $profilefields, moodle_url $returnurl) {
169 $columns = $cir->get_columns();
171 if (empty($columns)) {
174 print_error('cannotreadtmpfile', 'error', $returnurl);
176 if (count($columns) < 2) {
179 print_error('csvfewcolumns', 'error', $returnurl);
183 $processed = array();
184 foreach ($columns as $key=>$unused) {
185 $field = $columns[$key];
186 $field = trim($field);
187 $lcfield = core_text::strtolower($field);
188 if (in_array($field, $stdfields) or in_array($lcfield, $stdfields)) {
189 // standard fields are only lowercase
190 $newfield = $lcfield;
192 } else if (in_array($field, $profilefields)) {
193 // exact profile field name match - these are case sensitive
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;
200 } else if (preg_match('/^(sysrole|cohort|course|group|type|role|enrolperiod|enrolstatus)\d+$/', $lcfield)) {
201 // special fields for enrolments
202 $newfield = $lcfield;
207 print_error('invalidfieldname', 'error', $returnurl, $field);
209 if (in_array($newfield, $processed)) {
212 print_error('duplicatefieldname', 'error', $returnurl, $newfield);
214 $processed[$key] = $newfield;
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
226 function uu_increment_username($username) {
229 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
230 $username = $username.'2';
232 $username = $matches[1][0].($matches[2][0]+1);
235 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
236 return uu_increment_username($username);
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
248 function uu_process_template($template, $user) {
249 if (is_array($template)) {
250 // hack for for support of text editors with format
251 $t = $template['text'];
255 if (strpos($t, '%') === false) {
259 $username = isset($user->username) ? $user->username : '';
260 $firstname = isset($user->firstname) ? $user->firstname : '';
261 $lastname = isset($user->lastname) ? $user->lastname : '';
263 $callback = partial('uu_process_template_callback', $username, $firstname, $lastname);
265 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', $callback, $t);
267 if (is_null($result)) {
268 return $template; //error during regex processing??
271 if (is_array($template)) {
272 $template['text'] = $result;
280 * Internal callback function.
282 function uu_process_template_callback($username, $firstname, $lastname, $block) {
299 $repl = core_text::strtoupper($repl);
302 $repl = core_text::strtolower($repl);
305 $repl = core_text::strtotitle($repl);
309 if (!empty($block[2])) {
310 $repl = core_text::substr($repl, 0 , $block[2]);
317 * Returns list of auth plugins that are enabled and known to work.
319 * If ppl want to use some other auth type they have to include it
320 * in the CSV file next on each line.
322 * @return array type=>name
324 function uu_supported_auths() {
325 // Get all the enabled plugins.
326 $plugins = get_enabled_auth_plugins();
328 foreach ($plugins as $plugin) {
329 $objplugin = get_auth_plugin($plugin);
330 // If the plugin can not be manually set skip it.
331 if (!$objplugin->can_be_manually_set()) {
334 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
341 * Returns list of roles that are assignable in courses
344 function uu_allowed_roles() {
345 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
346 $roles = get_assignable_roles(context_course::instance(SITEID), ROLENAME_ORIGINALANDSHORT);
347 return array_reverse($roles, true);
351 * Returns mapping of all roles using short role name as index.
354 function uu_allowed_roles_cache() {
355 $allowedroles = get_assignable_roles(context_course::instance(SITEID), ROLENAME_SHORT);
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;
370 * Returns mapping of all system roles using short role name as index.
373 function 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;
389 * Pre process custom profile data, and update it with corrected value
391 * @param stdClass $data user profile data
392 * @return stdClass pre-processed custom profile data
394 function uu_pre_process_custom_profile_data($data) {
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);
416 * Checks if data provided for custom fields is correct
417 * Currently checking for custom profile field or type menu
419 * @param array $data user profile data
420 * @return bool true if no error else false
422 function uu_check_custom_profile_data(&$data) {
427 if (!empty($data['username'])) {
428 if (preg_match('/id=(.*)"/i', $data['username'], $result)) {
429 $testuserid = $result[1];
432 // Find custom profile fields and check if data needs to converted.
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);
446 // Check for duplicate value.
447 if (method_exists($formfield, 'edit_validate_field') ) {
448 $testuser = new stdClass();
449 $testuser->{$key} = $value;
450 $testuser->id = $testuserid;
451 $err = $formfield->edit_validate_field($testuser);
452 if (!empty($err[$key])) {
453 $data['status'][] = $err[$key].' ('.$key.')';