Apply rector fixes to auth plugins
[dokuwiki.git] / lib / plugins / authplain / auth.php
blob8cfe3511542f07b4275cb333b012aa837e8129bd
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;
19 /** @var array filter pattern */
20 protected $pattern = [];
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 $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 = implode(',', $grps);
111 $userline = [$user, $pass, $name, $mail, $groups];
112 $userline = str_replace('\\', '\\\\', $userline); // escape \ as \\
113 $userline = str_replace(':', '\\:', $userline); // escape : as \:
114 $userline = implode(':', $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 = [$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] = [
162 'pass' => $pass,
163 'name' => $name,
164 'mail' => $mail,
165 'grps' => $grps
167 return $pwd;
171 * Modify user data
173 * @author Chris Smith <chris@jalakai.co.uk>
174 * @param string $user nick of the user to be changed
175 * @param array $changes array of field/value pairs to be changed (password will be clear text)
176 * @return bool
178 public function modifyUser($user, $changes)
180 global $ACT;
181 global $config_cascade;
183 // sanity checks, user must already exist and there must be something to change
184 if (($userinfo = $this->getUserData($user)) === false) {
185 msg($this->getLang('usernotexists'), -1);
186 return false;
189 // don't modify protected users
190 if (!empty($userinfo['protected'])) {
191 msg(sprintf($this->getLang('protected'), hsc($user)), -1);
192 return false;
195 if (!is_array($changes) || $changes === []) return true;
197 // update userinfo with new data, remembering to encrypt any password
198 $newuser = $user;
199 foreach ($changes as $field => $value) {
200 if ($field == 'user') {
201 $newuser = $value;
202 continue;
204 if ($field == 'pass') $value = auth_cryptPassword($value);
205 $userinfo[$field] = $value;
208 $userline = $this->createUserLine(
209 $newuser,
210 $userinfo['pass'],
211 $userinfo['name'],
212 $userinfo['mail'],
213 $userinfo['grps']
216 if (!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^'.$user.':/', $userline, true)) {
217 msg('There was an error modifying your user data. You may need to register again.', -1);
218 // FIXME, io functions should be fail-safe so existing data isn't lost
219 $ACT = 'register';
220 return false;
223 if(isset($this->users[$user])) unset($this->users[$user]);
224 $this->users[$newuser] = $userinfo;
225 return true;
229 * Remove one or more users from the list of registered users
231 * @author Christopher Smith <chris@jalakai.co.uk>
232 * @param array $users array of users to be deleted
233 * @return int the number of users deleted
235 public function deleteUsers($users)
237 global $config_cascade;
239 if (!is_array($users) || $users === []) return 0;
241 if ($this->users === null) $this->loadUserData();
243 $deleted = [];
244 foreach ($users as $user) {
245 // don't delete protected users
246 if (!empty($this->users[$user]['protected'])) {
247 msg(sprintf($this->getLang('protected'), hsc($user)), -1);
248 continue;
250 if (isset($this->users[$user])) $deleted[] = preg_quote($user, '/');
253 if ($deleted === []) return 0;
255 $pattern = '/^('.implode('|', $deleted).'):/';
256 if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) {
257 msg($this->getLang('writefail'), -1);
258 return 0;
261 // reload the user list and count the difference
262 $count = count($this->users);
263 $this->loadUserData();
264 $count -= count($this->users);
265 return $count;
269 * Return a count of the number of user which meet $filter criteria
271 * @author Chris Smith <chris@jalakai.co.uk>
273 * @param array $filter
274 * @return int
276 public function getUserCount($filter = [])
279 if ($this->users === null) $this->loadUserData();
281 if ($filter === []) return count($this->users);
283 $count = 0;
284 $this->constructPattern($filter);
286 foreach ($this->users as $user => $info) {
287 $count += $this->filter($user, $info);
290 return $count;
294 * Bulk retrieval of user data
296 * @author Chris Smith <chris@jalakai.co.uk>
298 * @param int $start index of first user to be returned
299 * @param int $limit max number of users to be returned
300 * @param array $filter array of field/pattern pairs
301 * @return array userinfo (refer getUserData for internal userinfo details)
303 public function retrieveUsers($start = 0, $limit = 0, $filter = [])
306 if ($this->users === null) $this->loadUserData();
308 Sort::ksort($this->users);
310 $i = 0;
311 $count = 0;
312 $out = [];
313 $this->constructPattern($filter);
315 foreach ($this->users as $user => $info) {
316 if ($this->filter($user, $info)) {
317 if ($i >= $start) {
318 $out[$user] = $info;
319 $count++;
320 if (($limit > 0) && ($count >= $limit)) break;
322 $i++;
326 return $out;
330 * Retrieves groups.
331 * Loads complete user data into memory before searching for groups.
333 * @param int $start index of first group to be returned
334 * @param int $limit max number of groups to be returned
335 * @return array
337 public function retrieveGroups($start = 0, $limit = 0)
339 $groups = [];
341 if ($this->users === null) $this->loadUserData();
342 foreach($this->users as $info) {
343 $groups = array_merge($groups, array_diff($info['grps'], $groups));
345 Sort::ksort($groups);
347 if($limit > 0) {
348 return array_splice($groups, $start, $limit);
350 return array_splice($groups, $start);
354 * Only valid pageid's (no namespaces) for usernames
356 * @param string $user
357 * @return string
359 public function cleanUser($user)
361 global $conf;
363 return cleanID(str_replace([':', '/', ';'], $conf['sepchar'], $user));
367 * Only valid pageid's (no namespaces) for groupnames
369 * @param string $group
370 * @return string
372 public function cleanGroup($group)
374 global $conf;
376 return cleanID(str_replace([':', '/', ';'], $conf['sepchar'], $group));
380 * Load all user data
382 * loads the user file into a datastructure
384 * @author Andreas Gohr <andi@splitbrain.org>
386 protected function loadUserData()
388 global $config_cascade;
390 $this->users = $this->readUserFile($config_cascade['plainauth.users']['default']);
392 // support protected users
393 if (!empty($config_cascade['plainauth.users']['protected'])) {
394 $protected = $this->readUserFile($config_cascade['plainauth.users']['protected']);
395 foreach (array_keys($protected) as $key) {
396 $protected[$key]['protected'] = true;
398 $this->users = array_merge($this->users, $protected);
403 * Read user data from given file
405 * ignores non existing files
407 * @param string $file the file to load data from
408 * @return array
410 protected function readUserFile($file)
412 $users = [];
413 if (!file_exists($file)) return $users;
415 $lines = file($file);
416 foreach ($lines as $line) {
417 $line = preg_replace('/#.*$/', '', $line); //ignore comments
418 $line = trim($line);
419 if (empty($line)) continue;
421 $row = $this->splitUserData($line);
422 $row = str_replace('\\:', ':', $row);
423 $row = str_replace('\\\\', '\\', $row);
425 $groups = array_values(array_filter(explode(",", $row[4])));
427 $users[$row[0]]['pass'] = $row[1];
428 $users[$row[0]]['name'] = urldecode($row[2]);
429 $users[$row[0]]['mail'] = $row[3];
430 $users[$row[0]]['grps'] = $groups;
432 return $users;
436 * Get the user line split into it's parts
438 * @param string $line
439 * @return string[]
441 protected function splitUserData($line)
443 $data = preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5); // allow for : escaped as \:
444 if(count($data) < 5) {
445 $data = array_pad($data, 5, '');
446 Logger::error('User line with less than 5 fields. Possibly corruption in your user file', $data);
448 return $data;
452 * return true if $user + $info match $filter criteria, false otherwise
454 * @author Chris Smith <chris@jalakai.co.uk>
456 * @param string $user User login
457 * @param array $info User's userinfo array
458 * @return bool
460 protected function filter($user, $info)
462 foreach ($this->pattern as $item => $pattern) {
463 if ($item == 'user') {
464 if (!preg_match($pattern, $user)) return false;
465 } elseif ($item == 'grps') {
466 if (!count(preg_grep($pattern, $info['grps']))) return false;
467 } elseif (!preg_match($pattern, $info[$item])) {
468 return false;
471 return true;
475 * construct a filter pattern
477 * @param array $filter
479 protected function constructPattern($filter)
481 $this->pattern = [];
482 foreach ($filter as $item => $pattern) {
483 $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters