MDL-29912 course search - oracle inabilities with concats, empties, nulls and type...
[moodle.git] / admin / uploaduserlib.php
blob5fde2edd185a9b7f89687ed568aea26d58bd4ab6
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.
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/>.
17 /**
18 * Bulk user registration functions
20 * @package core
21 * @subpackage admin
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);
47 /**
48 * Tracking of processed users.
50 * This class prints user information into a html table.
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
57 class uu_progress_tracker {
58 private $_row;
59 public $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'deleted');
61 /**
62 * Print table header.
63 * @return void
65 public function start() {
66 $ci = 0;
67 echo '<table id="uuresults" class="generaltable boxaligncenter flexible-wrap" summary="'.get_string('uploadusersresult', 'admin').'">';
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', 'admin').'</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('delete').'</th>';
80 echo '</tr>';
81 $this->_row = null;
84 /**
85 * Flush previous line and start a new one.
86 * @return void
88 public function flush() {
89 if (empty($this->_row) or empty($this->_row['line']['normal'])) {
90 // Nothing to print - each line has to have at least number
91 $this->_row = array();
92 foreach ($this->columns as $col) {
93 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
95 return;
97 $ci = 0;
98 $ri = 1;
99 echo '<tr class="r'.$ri.'">';
100 foreach ($this->_row as $key=>$field) {
101 foreach ($field as $type=>$content) {
102 if ($field[$type] !== '') {
103 $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
104 } else {
105 unset($field[$type]);
108 echo '<td class="cell c'.$ci++.'">';
109 if (!empty($field)) {
110 echo implode('<br />', $field);
111 } else {
112 echo '&nbsp;';
114 echo '</td>';
116 echo '</tr>';
117 foreach ($this->columns as $col) {
118 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
123 * Add tracking info
124 * @param string $col name of column
125 * @param string $msg message
126 * @param string $level 'normal', 'warning' or 'error'
127 * @param bool $merge true means add as new line, false means override all previous text of the same type
128 * @return void
130 public function track($col, $msg, $level = 'normal', $merge = true) {
131 if (empty($this->_row)) {
132 $this->flush(); //init arrays
134 if (!in_array($col, $this->columns)) {
135 debugging('Incorrect column:'.$col);
136 return;
138 if ($merge) {
139 if ($this->_row[$col][$level] != '') {
140 $this->_row[$col][$level] .='<br />';
142 $this->_row[$col][$level] .= $msg;
143 } else {
144 $this->_row[$col][$level] = $msg;
149 * Print the table end
150 * @return void
152 public function close() {
153 $this->flush();
154 echo '</table>';
159 * Validation callback function - verified the column line of csv file.
160 * Converts standard column names to lowercase.
161 * @param csv_import_reader $cir
162 * @param array $stdfields standard user fields
163 * @param array $profilefields custom profile fields
164 * @param moodle_url $returnurl return url in case of any error
165 * @return array list of fields
167 function uu_validate_user_upload_columns(csv_import_reader $cir, $stdfields, $profilefields, moodle_url $returnurl) {
168 $columns = $cir->get_columns();
170 if (empty($columns)) {
171 $cir->close();
172 $cir->cleanup();
173 print_error('cannotreadtmpfile', 'error', $returnurl);
175 if (count($columns) < 2) {
176 $cir->close();
177 $cir->cleanup();
178 print_error('csvfewcolumns', 'error', $returnurl);
181 $textlib = textlib_get_instance(); // profile fields may contain unicode chars
183 // test columns
184 $processed = array();
185 foreach ($columns as $key=>$unused) {
186 $field = $columns[$key];
187 $lcfield = $textlib->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
194 $newfield = $field;
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('/^(course|group|type|role|enrolperiod)\d+$/', $lcfield)) {
201 // special fields for enrolments
202 $newfield = $lcfield;
204 } else {
205 $cir->close();
206 $cir->cleanup();
207 print_error('invalidfieldname', 'error', $returnurl, $field);
209 if (in_array($newfield, $processed)) {
210 $cir->close();
211 $cir->cleanup();
212 print_error('duplicatefieldname', 'error', $returnurl, $newfield);
214 $processed[$key] = $newfield;
217 return $processed;
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) {
227 global $DB, $CFG;
229 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
230 $username = $username.'2';
231 } else {
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);
237 } else {
238 return $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'];
252 } else {
253 $t = $template;
255 if (strpos($t, '%') === false) {
256 return $template;
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;
273 return $t;
274 } else {
275 return $result;
280 * Internal callback function.
282 function uu_process_template_callback($username, $firstname, $lastname, $block) {
283 $textlib = textlib_get_instance();
285 switch ($block[3]) {
286 case 'u':
287 $repl = $username;
288 break;
289 case 'f':
290 $repl = $firstname;
291 break;
292 case 'l':
293 $repl = $lastname;
294 break;
295 default:
296 return $block[0];
299 switch ($block[1]) {
300 case '+':
301 $repl = $textlib->strtoupper($repl);
302 break;
303 case '-':
304 $repl = $textlib->strtolower($repl);
305 break;
306 case '~':
307 $repl = $textlib->strtotitle($repl);
308 break;
311 if (!empty($block[2])) {
312 $repl = $textlib->substr($repl, 0 , $block[2]);
315 return $repl;
319 * Returns list of auth plugins that are enabled and known to work.
321 * If ppl want to use some other auth type they have to include it
322 * in the CSV file next on each line.
324 * @return array type=>name
326 function uu_supported_auths() {
327 // only following plugins are guaranteed to work properly
328 $whitelist = array('manual', 'nologin', 'none', 'email');
329 $plugins = get_enabled_auth_plugins();
330 $choices = array();
331 foreach ($plugins as $plugin) {
332 if (!in_array($plugin, $whitelist)) {
333 continue;
335 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
338 return $choices;
342 * Returns list of roles that are assignable in courses
343 * @return array
345 function uu_allowed_roles() {
346 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
347 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
348 return array_reverse($roles, true);
352 * Returns mapping of all roles using short role name as index.
353 * @return array
355 function uu_allowed_roles_cache() {
356 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
357 foreach ($allowedroles as $rid=>$rname) {
358 $rolecache[$rid] = new stdClass();
359 $rolecache[$rid]->id = $rid;
360 $rolecache[$rid]->name = $rname;
361 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
362 $rolecache[$rname] = new stdClass();
363 $rolecache[$rname]->id = $rid;
364 $rolecache[$rname]->name = $rname;
367 return $rolecache;