Merge branch 'MDL-26767' of git://github.com/timhunt/moodle
[moodle.git] / admin / uploaduserlib.php
blob7df9290268f9d248ee319ad94339cda26864d5dc
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 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
167 function uu_validate_user_upload_columns(csv_import_reader $cir, $stdfields, $frofilefields, 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 // 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);
191 if (in_array($field, $processed)) {
192 $cir->close();
193 $cir->cleanup();
194 print_error('duplicatefieldname', 'error', $returnurl, $field);
196 $processed[$key] = $field;
199 return $processed;
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
208 function uu_increment_username($username) {
209 global $DB, $CFG;
211 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
212 $username = $username.'2';
213 } else {
214 $username = $matches[1][0].($matches[2][0]+1);
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;
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
230 function 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;
237 if (strpos($t, '%') === false) {
238 return $template;
241 $username = isset($user->username) ? $user->username : '';
242 $firstname = isset($user->firstname) ? $user->firstname : '';
243 $lastname = isset($user->lastname) ? $user->lastname : '';
245 $callback = partial('uu_process_template_callback', $username, $firstname, $lastname);
247 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', $callback, $t);
249 if (is_null($result)) {
250 return $template; //error during regex processing??
251 } else {
252 if (array($template)) {
253 $template['text'] = $t;
254 return $t;
255 } else {
256 return $t;
262 * Internal callback function.
264 function uu_process_template_callback($block, $username, $firstname, $lastname) {
265 $textlib = textlib_get_instance();
266 $repl = $block[0];
268 switch ($block[3]) {
269 case 'u': $repl = $username; break;
270 case 'f': $repl = $firstname; break;
271 case 'l': $repl = $lastname; break;
273 switch ($block[1]) {
274 case '+': $repl = $textlib->strtoupper($repl); break;
275 case '-': $repl = $textlib->strtolower($repl); break;
276 case '~': $repl = $textlib->strtotitle($repl); break;
278 if (!empty($block[2])) {
279 $repl = $textlib->substr($repl, 0 , $block[2]);
282 return $repl;
286 * Returns list of auth plugins that are enabled and known to work.
288 * If ppl want to use some other auth type they have to include it
289 * in the CSV file next on each line.
291 * @return array type=>name
293 function uu_supported_auths() {
294 // only following plugins are guaranteed to work properly
295 $whitelist = array('manual', 'nologin', 'none', 'email');
296 $plugins = get_enabled_auth_plugins();
297 $choices = array();
298 foreach ($plugins as $plugin) {
299 if (!in_array($plugin, $whitelist)) {
300 continue;
302 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
305 return $choices;
309 * Returns list of roles that are assignable in courses
310 * @return array
312 function uu_allowed_roles() {
313 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
314 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
315 return array_reverse($roles, true);
319 * Returns mapping of all roles using short role name as index.
320 * @return array
322 function uu_allowed_roles_cache() {
323 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
324 foreach ($allowedroles as $rid=>$rname) {
325 $rolecache[$rid] = new stdClass();
326 $rolecache[$rid]->id = $rid;
327 $rolecache[$rid]->name = $rname;
328 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
329 $rolecache[$rname] = new stdClass();
330 $rolecache[$rname]->id = $rid;
331 $rolecache[$rname]->name = $rname;
334 return $rolecache;