weekly release 2.1dev
[moodle.git] / admin / uploaduserlib.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 *
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
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;
59 public $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'deleted');
60
61 /**
62 * Print table header.
63 * @return void
64 */
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;
82 }
83
84 /**
85 * Flush previous line and start a new one.
86 * @return void
87 */
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'=>'');
94 }
95 return;
96 }
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]);
106 }
107 }
108 echo '<td class="cell c'.$ci++.'">';
109 if (!empty($field)) {
110 echo implode('<br />', $field);
111 } else {
112 echo '&nbsp;';
113 }
114 echo '</td>';
115 }
116 echo '</tr>';
117 foreach ($this->columns as $col) {
118 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
119 }
120 }
121
122 /**
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
129 */
130 public function track($col, $msg, $level = 'normal', $merge = true) {
131 if (empty($this->_row)) {
132 $this->flush(); //init arrays
133 }
134 if (!in_array($col, $this->columns)) {
135 debugging('Incorrect column:'.$col);
136 return;
137 }
138 if ($merge) {
139 if ($this->_row[$col][$level] != '') {
140 $this->_row[$col][$level] .='<br />';
141 }
142 $this->_row[$col][$level] .= $msg;
143 } else {
144 $this->_row[$col][$level] = $msg;
145 }
146 }
147
148 /**
149 * Print the table end
150 * @return void
151 */
152 public function close() {
153 $this->flush();
154 echo '</table>';
155 }
156}
157
158/**
159 * Validation callback function - verified the column line of csv file.
160 * Converts column names to lowercase too.
161 * @param csv_import_reader $cir
162 * @param array standard user fields
163 * @param array custom profile fields
164 * @param moodle_url $returnurl return url in case of any error
165 * @return array list of fields
166 */
167function uu_validate_user_upload_columns(csv_import_reader $cir, $stdfields, $frofilefields, moodle_url $returnurl) {
168 $columns = $cir->get_columns();
169
170 if (empty($columns)) {
171 $cir->close();
172 $cir->cleanup();
173 print_error('cannotreadtmpfile', 'error', $returnurl);
174 }
175 if (count($columns) < 2) {
176 $cir->close();
177 $cir->cleanup();
178 print_error('csvfewcolumns', 'error', $returnurl);
179 }
180
181 // test columns
182 $processed = array();
183 foreach ($columns as $key=>$unused) {
184 $field = strtolower($columns[$key]); // no unicode expected here, ignore case
185 if (!in_array($field, $stdfields) && !in_array($field, $frofilefields) &&// if not a standard field and not an enrolment field, then we have an error
186 !preg_match('/^course\d+$/', $field) && !preg_match('/^group\d+$/', $field) &&
187 !preg_match('/^type\d+$/', $field) && !preg_match('/^role\d+$/', $field) &&
188 !preg_match('/^enrolperiod\d+$/', $field)) {
189 print_error('invalidfieldname', 'error', $returnurl, $field);
190 }
191 if (in_array($field, $processed)) {
192 $cir->close();
193 $cir->cleanup();
194 print_error('duplicatefieldname', 'error', $returnurl, $field);
195 }
196 $processed[$key] = $field;
197 }
198
199 return $processed;
200}
201
202/**
203 * Increments username - increments trailing number or adds it if not present.
204 * Varifies that the new username does not exist yet
205 * @param string $username
206 * @return incremented username which does not exist yet
207 */
208function uu_increment_username($username) {
209 global $DB, $CFG;
210
211 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
212 $username = $username.'2';
213 } else {
214 $username = $matches[1][0].($matches[2][0]+1);
215 }
216
217 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
218 return uu_increment_username($username);
219 } else {
220 return $username;
221 }
222}
223
224/**
225 * Check if default field contains templates and apply them.
226 * @param string template - potential tempalte string
227 * @param object user object- we need username, firstname and lastname
228 * @return string field value
229 */
230function uu_process_template($template, $user) {
231 if (is_array($template)) {
232 // hack for for support of text editors with format
233 $t = $template['text'];
234 } else {
235 $t = $template;
236 }
237 if (strpos($t, '%') === false) {
238 return $template;
239 }
240
241 $username = isset($user->username) ? $user->username : '';
242 $firstname = isset($user->firstname) ? $user->firstname : '';
243 $lastname = isset($user->lastname) ? $user->lastname : '';
244
245 $callback = partial('uu_process_template_callback', $username, $firstname, $lastname);
246
247 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', $callback, $t);
248
249 if (is_null($result)) {
250 return $template; //error during regex processing??
43070e61
PS
251 }
252
253 if (is_array($template)) {
254 $template['text'] = $result;
255 return $t;
8bdb31ed 256 } else {
43070e61 257 return $result;
8bdb31ed
PS
258 }
259}
260
261/**
262 * Internal callback function.
263 */
43070e61 264function uu_process_template_callback($username, $firstname, $lastname, $block) {
8bdb31ed 265 $textlib = textlib_get_instance();
8bdb31ed
PS
266
267 switch ($block[3]) {
43070e61
PS
268 case 'u':
269 $repl = $username;
270 break;
271 case 'f':
272 $repl = $firstname;
273 break;
274 case 'l':
275 $repl = $lastname;
276 break;
277 default:
278 return $block[0];
8bdb31ed 279 }
43070e61 280
8bdb31ed 281 switch ($block[1]) {
43070e61
PS
282 case '+':
283 $repl = $textlib->strtoupper($repl);
284 break;
285 case '-':
286 $repl = $textlib->strtolower($repl);
287 break;
288 case '~':
289 $repl = $textlib->strtotitle($repl);
290 break;
8bdb31ed 291 }
43070e61 292
8bdb31ed
PS
293 if (!empty($block[2])) {
294 $repl = $textlib->substr($repl, 0 , $block[2]);
295 }
296
297 return $repl;
298}
299
300/**
301 * Returns list of auth plugins that are enabled and known to work.
302 *
303 * If ppl want to use some other auth type they have to include it
304 * in the CSV file next on each line.
305 *
306 * @return array type=>name
307 */
308function uu_supported_auths() {
309 // only following plugins are guaranteed to work properly
310 $whitelist = array('manual', 'nologin', 'none', 'email');
311 $plugins = get_enabled_auth_plugins();
312 $choices = array();
313 foreach ($plugins as $plugin) {
314 if (!in_array($plugin, $whitelist)) {
315 continue;
316 }
317 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
318 }
319
320 return $choices;
321}
322
323/**
324 * Returns list of roles that are assignable in courses
325 * @return array
326 */
327function uu_allowed_roles() {
328 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
329 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
330 return array_reverse($roles, true);
331}
332
333/**
334 * Returns mapping of all roles using short role name as index.
335 * @return array
336 */
337function uu_allowed_roles_cache() {
338 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
339 foreach ($allowedroles as $rid=>$rname) {
340 $rolecache[$rid] = new stdClass();
341 $rolecache[$rid]->id = $rid;
342 $rolecache[$rid]->name = $rname;
343 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
344 $rolecache[$rname] = new stdClass();
345 $rolecache[$rname]->id = $rid;
346 $rolecache[$rname]->name = $rname;
347 }
348 }
349 return $rolecache;
350}