AuthPlain user parsing fix. #3833
[dokuwiki.git] / lib / plugins / authplain / auth.php
blobe0c1b9291ba8a023435f2ebf37ad3245f4877e6a
1 <?php
3 use dokuwiki\Logger;
4 use dokuwiki\Utf8\Sort;
6 /**
7 * Plaintext authentication backend
9 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
10 * @author Andreas Gohr <andi@splitbrain.org>
11 * @author Chris Smith <chris@jalakai.co.uk>
12 * @author Jan Schumann <js@schumann-it.com>
14 class auth_plugin_authplain extends DokuWiki_Auth_Plugin
16 /** @var array user cache */
17 protected $users = null;
19 /** @var array filter pattern */
20 protected $pattern = array();
22 /** @var bool safe version of preg_split */
23 protected $pregsplit_safe = false;
25 /**
26 * Constructor
28 * Carry out sanity checks to ensure the object is
29 * able to operate. Set capabilities.
31 * @author Christopher Smith <chris@jalakai.co.uk>
33 public function __construct()
35 parent::__construct();
36 global $config_cascade;
38 if (!@is_readable($config_cascade['plainauth.users']['default'])) {
39 $this->success = false;
40 } else {
41 if (@is_writable($config_cascade['plainauth.users']['default'])) {
42 $this->cando['addUser'] = true;
43 $this->cando['delUser'] = true;
44 $this->cando['modLogin'] = true;
45 $this->cando['modPass'] = true;
46 $this->cando['modName'] = true;
47 $this->cando['modMail'] = true;
48 $this->cando['modGroups'] = true;
50 $this->cando['getUsers'] = true;
51 $this->cando['getUserCount'] = true;
52 $this->cando['getGroups'] = true;
56 /**
57 * Check user+password
59 * Checks if the given user exists and the given
60 * plaintext password is correct
62 * @author Andreas Gohr <andi@splitbrain.org>
63 * @param string $user
64 * @param string $pass
65 * @return bool
67 public function checkPass($user, $pass)
69 $userinfo = $this->getUserData($user);
70 if ($userinfo === false) return false;
72 return auth_verifyPassword($pass, $this->users[$user]['pass']);
75 /**
76 * Return user info
78 * Returns info about the given user needs to contain
79 * at least these fields:
81 * name string full name of the user
82 * mail string email addres of the user
83 * grps array list of groups the user is in
85 * @author Andreas Gohr <andi@splitbrain.org>
86 * @param string $user
87 * @param bool $requireGroups (optional) ignored by this plugin, grps info always supplied
88 * @return array|false
90 public function getUserData($user, $requireGroups = true)
92 if ($this->users === null) $this->loadUserData();
93 return isset($this->users[$user]) ? $this->users[$user] : false;
96 /**
97 * Creates a string suitable for saving as a line
98 * in the file database
99 * (delimiters escaped, etc.)
101 * @param string $user
102 * @param string $pass
103 * @param string $name
104 * @param string $mail
105 * @param array $grps list of groups the user is in
106 * @return string
108 protected function createUserLine($user, $pass, $name, $mail, $grps)
110 $groups = join(',', $grps);
111 $userline = array($user, $pass, $name, $mail, $groups);
112 $userline = str_replace('\\', '\\\\', $userline); // escape \ as \\
113 $userline = str_replace(':', '\\:', $userline); // escape : as \:
114 $userline = join(':', $userline)."\n";
115 return $userline;
119 * Create a new User
121 * Returns false if the user already exists, null when an error
122 * occurred and true if everything went well.
124 * The new user will be added to the default group by this
125 * function if grps are not specified (default behaviour).
127 * @author Andreas Gohr <andi@splitbrain.org>
128 * @author Chris Smith <chris@jalakai.co.uk>
130 * @param string $user
131 * @param string $pwd
132 * @param string $name
133 * @param string $mail
134 * @param array $grps
135 * @return bool|null|string
137 public function createUser($user, $pwd, $name, $mail, $grps = null)
139 global $conf;
140 global $config_cascade;
142 // user mustn't already exist
143 if ($this->getUserData($user) !== false) {
144 msg($this->getLang('userexists'), -1);
145 return false;
148 $pass = auth_cryptPassword($pwd);
150 // set default group if no groups specified
151 if (!is_array($grps)) $grps = array($conf['defaultgroup']);
153 // prepare user line
154 $userline = $this->createUserLine($user, $pass, $name, $mail, $grps);
156 if (!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) {
157 msg($this->getLang('writefail'), -1);
158 return null;
161 $this->users[$user] = compact('pass', 'name', 'mail', 'grps');
162 return $pwd;
166 * Modify user data
168 * @author Chris Smith <chris@jalakai.co.uk>
169 * @param string $user nick of the user to be changed
170 * @param array $changes array of field/value pairs to be changed (password will be clear text)
171 * @return bool
173 public function modifyUser($user, $changes)
175 global $ACT;
176 global $config_cascade;
178 // sanity checks, user must already exist and there must be something to change
179 if (($userinfo = $this->getUserData($user)) === false) {
180 msg($this->getLang('usernotexists'), -1);
181 return false;
184 // don't modify protected users
185 if (!empty($userinfo['protected'])) {
186 msg(sprintf($this->getLang('protected'), hsc($user)), -1);
187 return false;
190 if (!is_array($changes) || !count($changes)) return true;
192 // update userinfo with new data, remembering to encrypt any password
193 $newuser = $user;
194 foreach ($changes as $field => $value) {
195 if ($field == 'user') {
196 $newuser = $value;
197 continue;
199 if ($field == 'pass') $value = auth_cryptPassword($value);
200 $userinfo[$field] = $value;
203 $userline = $this->createUserLine(
204 $newuser,
205 $userinfo['pass'],
206 $userinfo['name'],
207 $userinfo['mail'],
208 $userinfo['grps']
211 if (!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^'.$user.':/', $userline, true)) {
212 msg('There was an error modifying your user data. You may need to register again.', -1);
213 // FIXME, io functions should be fail-safe so existing data isn't lost
214 $ACT = 'register';
215 return false;
218 if(isset($this->users[$user])) unset($this->users[$user]);
219 $this->users[$newuser] = $userinfo;
220 return true;
224 * Remove one or more users from the list of registered users
226 * @author Christopher Smith <chris@jalakai.co.uk>
227 * @param array $users array of users to be deleted
228 * @return int the number of users deleted
230 public function deleteUsers($users)
232 global $config_cascade;
234 if (!is_array($users) || empty($users)) return 0;
236 if ($this->users === null) $this->loadUserData();
238 $deleted = array();
239 foreach ($users as $user) {
240 // don't delete protected users
241 if (!empty($this->users[$user]['protected'])) {
242 msg(sprintf($this->getLang('protected'), hsc($user)), -1);
243 continue;
245 if (isset($this->users[$user])) $deleted[] = preg_quote($user, '/');
248 if (empty($deleted)) return 0;
250 $pattern = '/^('.join('|', $deleted).'):/';
251 if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) {
252 msg($this->getLang('writefail'), -1);
253 return 0;
256 // reload the user list and count the difference
257 $count = count($this->users);
258 $this->loadUserData();
259 $count -= count($this->users);
260 return $count;
264 * Return a count of the number of user which meet $filter criteria
266 * @author Chris Smith <chris@jalakai.co.uk>
268 * @param array $filter
269 * @return int
271 public function getUserCount($filter = array())
274 if ($this->users === null) $this->loadUserData();
276 if (!count($filter)) return count($this->users);
278 $count = 0;
279 $this->constructPattern($filter);
281 foreach ($this->users as $user => $info) {
282 $count += $this->filter($user, $info);
285 return $count;
289 * Bulk retrieval of user data
291 * @author Chris Smith <chris@jalakai.co.uk>
293 * @param int $start index of first user to be returned
294 * @param int $limit max number of users to be returned
295 * @param array $filter array of field/pattern pairs
296 * @return array userinfo (refer getUserData for internal userinfo details)
298 public function retrieveUsers($start = 0, $limit = 0, $filter = array())
301 if ($this->users === null) $this->loadUserData();
303 Sort::ksort($this->users);
305 $i = 0;
306 $count = 0;
307 $out = array();
308 $this->constructPattern($filter);
310 foreach ($this->users as $user => $info) {
311 if ($this->filter($user, $info)) {
312 if ($i >= $start) {
313 $out[$user] = $info;
314 $count++;
315 if (($limit > 0) && ($count >= $limit)) break;
317 $i++;
321 return $out;
325 * Retrieves groups.
326 * Loads complete user data into memory before searching for groups.
328 * @param int $start index of first group to be returned
329 * @param int $limit max number of groups to be returned
330 * @return array
332 public function retrieveGroups($start = 0, $limit = 0)
334 $groups = [];
336 if ($this->users === null) $this->loadUserData();
337 foreach($this->users as $user => $info) {
338 $groups = array_merge($groups, array_diff($info['grps'], $groups));
340 Sort::ksort($groups);
342 if($limit > 0) {
343 return array_splice($groups, $start, $limit);
345 return array_splice($groups, $start);
349 * Only valid pageid's (no namespaces) for usernames
351 * @param string $user
352 * @return string
354 public function cleanUser($user)
356 global $conf;
358 return cleanID(str_replace([':', '/', ';'], $conf['sepchar'], $user));
362 * Only valid pageid's (no namespaces) for groupnames
364 * @param string $group
365 * @return string
367 public function cleanGroup($group)
369 global $conf;
371 return cleanID(str_replace([':', '/', ';'], $conf['sepchar'], $group));
375 * Load all user data
377 * loads the user file into a datastructure
379 * @author Andreas Gohr <andi@splitbrain.org>
381 protected function loadUserData()
383 global $config_cascade;
385 $this->users = $this->readUserFile($config_cascade['plainauth.users']['default']);
387 // support protected users
388 if (!empty($config_cascade['plainauth.users']['protected'])) {
389 $protected = $this->readUserFile($config_cascade['plainauth.users']['protected']);
390 foreach (array_keys($protected) as $key) {
391 $protected[$key]['protected'] = true;
393 $this->users = array_merge($this->users, $protected);
398 * Read user data from given file
400 * ignores non existing files
402 * @param string $file the file to load data from
403 * @return array
405 protected function readUserFile($file)
407 $users = array();
408 if (!file_exists($file)) return $users;
410 $lines = file($file);
411 foreach ($lines as $line) {
412 $line = preg_replace('/#.*$/', '', $line); //ignore comments
413 $line = trim($line);
414 if (empty($line)) continue;
416 $row = $this->splitUserData($line);
417 $row = str_replace('\\:', ':', $row);
418 $row = str_replace('\\\\', '\\', $row);
420 $groups = array_values(array_filter(explode(",", $row[4])));
422 $users[$row[0]]['pass'] = $row[1];
423 $users[$row[0]]['name'] = urldecode($row[2]);
424 $users[$row[0]]['mail'] = $row[3];
425 $users[$row[0]]['grps'] = $groups;
427 return $users;
431 * Get the user line split into it's parts
433 * @param string $line
434 * @return string[]
436 protected function splitUserData($line)
438 $data = preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5); // allow for : escaped as \:
439 if(count($data) < 5) {
440 $data = array_pad($data, 5, '');
441 Logger::error('User line with less than 5 fields. Possibly corruption in your user file', $data);
443 return $data;
447 * return true if $user + $info match $filter criteria, false otherwise
449 * @author Chris Smith <chris@jalakai.co.uk>
451 * @param string $user User login
452 * @param array $info User's userinfo array
453 * @return bool
455 protected function filter($user, $info)
457 foreach ($this->pattern as $item => $pattern) {
458 if ($item == 'user') {
459 if (!preg_match($pattern, $user)) return false;
460 } elseif ($item == 'grps') {
461 if (!count(preg_grep($pattern, $info['grps']))) return false;
462 } else {
463 if (!preg_match($pattern, $info[$item])) return false;
466 return true;
470 * construct a filter pattern
472 * @param array $filter
474 protected function constructPattern($filter)
476 $this->pattern = array();
477 foreach ($filter as $item => $pattern) {
478 $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters