xref: /dokuwiki/lib/plugins/authplain/auth.php (revision b4f2363aa1360136c8a826f09aaebc6505211c73)
1<?php
2
3/**
4 * Plaintext authentication backend
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 * @author     Chris Smith <chris@jalakai.co.uk>
9 * @author     Jan Schumann <js@schumann-it.com>
10 */
11class auth_plugin_authplain extends DokuWiki_Auth_Plugin {
12    /** @var array user cache */
13    protected $users = null;
14
15    /** @var array filter pattern */
16    protected $_pattern = array();
17
18    /** @var bool safe version of preg_split */
19    protected $_pregsplit_safe = false;
20
21    /**
22     * Constructor
23     *
24     * Carry out sanity checks to ensure the object is
25     * able to operate. Set capabilities.
26     *
27     * @author  Christopher Smith <chris@jalakai.co.uk>
28     */
29    public function __construct() {
30        parent::__construct();
31        global $config_cascade;
32
33        if(!@is_readable($config_cascade['plainauth.users']['default'])) {
34            $this->success = false;
35        } else {
36            if(@is_writable($config_cascade['plainauth.users']['default'])) {
37                $this->cando['addUser']   = true;
38                $this->cando['delUser']   = true;
39                $this->cando['modLogin']  = true;
40                $this->cando['modPass']   = true;
41                $this->cando['modName']   = true;
42                $this->cando['modMail']   = true;
43                $this->cando['modGroups'] = true;
44            }
45            $this->cando['getUsers']     = true;
46            $this->cando['getUserCount'] = true;
47        }
48
49        $this->_pregsplit_safe = version_compare(PCRE_VERSION,'6.7','>=');
50    }
51
52    /**
53     * Check user+password
54     *
55     * Checks if the given user exists and the given
56     * plaintext password is correct
57     *
58     * @author  Andreas Gohr <andi@splitbrain.org>
59     * @param string $user
60     * @param string $pass
61     * @return  bool
62     */
63    public function checkPass($user, $pass) {
64        $userinfo = $this->getUserData($user);
65        if($userinfo === false) return false;
66
67        return auth_verifyPassword($pass, $this->users[$user]['pass']);
68    }
69
70    /**
71     * Return user info
72     *
73     * Returns info about the given user needs to contain
74     * at least these fields:
75     *
76     * name string  full name of the user
77     * mail string  email addres of the user
78     * grps array   list of groups the user is in
79     *
80     * @author  Andreas Gohr <andi@splitbrain.org>
81     * @param string $user
82     * @param bool $requireGroups  (optional) ignored by this plugin, grps info always supplied
83     * @return array|false
84     */
85    public function getUserData($user, $requireGroups=true) {
86        if($this->users === null) $this->_loadUserData();
87        return isset($this->users[$user]) ? $this->users[$user] : false;
88    }
89
90    /**
91     * Creates a string suitable for saving as a line
92     * in the file database
93     * (delimiters escaped, etc.)
94     *
95     * @param string $user
96     * @param string $pass
97     * @param string $name
98     * @param string $mail
99     * @param array  $grps list of groups the user is in
100     * @return string
101     */
102    protected function _createUserLine($user, $pass, $name, $mail, $grps) {
103        $groups   = join(',', $grps);
104        $userline = array($user, $pass, $name, $mail, $groups);
105        $userline = str_replace('\\', '\\\\', $userline); // escape \ as \\
106        $userline = str_replace(':', '\\:', $userline); // escape : as \:
107        $userline = join(':', $userline)."\n";
108        return $userline;
109    }
110
111    /**
112     * Create a new User
113     *
114     * Returns false if the user already exists, null when an error
115     * occurred and true if everything went well.
116     *
117     * The new user will be added to the default group by this
118     * function if grps are not specified (default behaviour).
119     *
120     * @author  Andreas Gohr <andi@splitbrain.org>
121     * @author  Chris Smith <chris@jalakai.co.uk>
122     *
123     * @param string $user
124     * @param string $pwd
125     * @param string $name
126     * @param string $mail
127     * @param array  $grps
128     * @return bool|null|string
129     */
130    public function createUser($user, $pwd, $name, $mail, $grps = null) {
131        global $conf;
132        global $config_cascade;
133
134        // user mustn't already exist
135        if($this->getUserData($user) !== false) {
136            msg($this->getLang('userexists'), -1);
137            return false;
138        }
139
140        $pass = auth_cryptPassword($pwd);
141
142        // set default group if no groups specified
143        if(!is_array($grps)) $grps = array($conf['defaultgroup']);
144
145        // prepare user line
146        $userline = $this->_createUserLine($user, $pass, $name, $mail, $grps);
147
148        if(!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) {
149            msg($this->getLang('writefail'), -1);
150            return null;
151        }
152
153        $this->users[$user] = compact('pass', 'name', 'mail', 'grps');
154        return $pwd;
155    }
156
157    /**
158     * Modify user data
159     *
160     * @author  Chris Smith <chris@jalakai.co.uk>
161     * @param   string $user      nick of the user to be changed
162     * @param   array  $changes   array of field/value pairs to be changed (password will be clear text)
163     * @return  bool
164     */
165    public function modifyUser($user, $changes) {
166        global $ACT;
167        global $config_cascade;
168
169        // sanity checks, user must already exist and there must be something to change
170        if(($userinfo = $this->getUserData($user)) === false) {
171            msg($this->getLang('usernotexists'), -1);
172            return false;
173        }
174
175        // don't modify protected users
176        if(!empty($userinfo['protected'])) {
177            msg(sprintf($this->getLang('protected'), hsc($user)), -1);
178            return false;
179        }
180
181        if(!is_array($changes) || !count($changes)) return true;
182
183        // update userinfo with new data, remembering to encrypt any password
184        $newuser = $user;
185        foreach($changes as $field => $value) {
186            if($field == 'user') {
187                $newuser = $value;
188                continue;
189            }
190            if($field == 'pass') $value = auth_cryptPassword($value);
191            $userinfo[$field] = $value;
192        }
193
194        $userline = $this->_createUserLine($newuser, $userinfo['pass'], $userinfo['name'], $userinfo['mail'], $userinfo['grps']);
195
196        if(!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^'.$user.':/', $userline, true)) {
197            msg('There was an error modifying your user data. You may need to register again.', -1);
198            // FIXME, io functions should be fail-safe so existing data isn't lost
199            $ACT = 'register';
200            return false;
201        }
202
203        $this->users[$newuser] = $userinfo;
204        return true;
205    }
206
207    /**
208     * Remove one or more users from the list of registered users
209     *
210     * @author  Christopher Smith <chris@jalakai.co.uk>
211     * @param   array  $users   array of users to be deleted
212     * @return  int             the number of users deleted
213     */
214    public function deleteUsers($users) {
215        global $config_cascade;
216
217        if(!is_array($users) || empty($users)) return 0;
218
219        if($this->users === null) $this->_loadUserData();
220
221        $deleted = array();
222        foreach($users as $user) {
223            // don't delete protected users
224            if(!empty($this->users[$user]['protected'])) {
225                msg(sprintf($this->getLang('protected'), hsc($user)), -1);
226                continue;
227            }
228            if(isset($this->users[$user])) $deleted[] = preg_quote($user, '/');
229        }
230
231        if(empty($deleted)) return 0;
232
233        $pattern = '/^('.join('|', $deleted).'):/';
234        if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) {
235            msg($this->getLang('writefail'), -1);
236            return 0;
237        }
238
239        // reload the user list and count the difference
240        $count = count($this->users);
241        $this->_loadUserData();
242        $count -= count($this->users);
243        return $count;
244    }
245
246    /**
247     * Return a count of the number of user which meet $filter criteria
248     *
249     * @author  Chris Smith <chris@jalakai.co.uk>
250     *
251     * @param array $filter
252     * @return int
253     */
254    public function getUserCount($filter = array()) {
255
256        if($this->users === null) $this->_loadUserData();
257
258        if(!count($filter)) return count($this->users);
259
260        $count = 0;
261        $this->_constructPattern($filter);
262
263        foreach($this->users as $user => $info) {
264            $count += $this->_filter($user, $info);
265        }
266
267        return $count;
268    }
269
270    /**
271     * Bulk retrieval of user data
272     *
273     * @author  Chris Smith <chris@jalakai.co.uk>
274     *
275     * @param   int   $start index of first user to be returned
276     * @param   int   $limit max number of users to be returned
277     * @param   array $filter array of field/pattern pairs
278     * @return  array userinfo (refer getUserData for internal userinfo details)
279     */
280    public function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
281
282        if($this->users === null) $this->_loadUserData();
283
284        ksort($this->users);
285
286        $i     = 0;
287        $count = 0;
288        $out   = array();
289        $this->_constructPattern($filter);
290
291        foreach($this->users as $user => $info) {
292            if($this->_filter($user, $info)) {
293                if($i >= $start) {
294                    $out[$user] = $info;
295                    $count++;
296                    if(($limit > 0) && ($count >= $limit)) break;
297                }
298                $i++;
299            }
300        }
301
302        return $out;
303    }
304
305    /**
306     * Only valid pageid's (no namespaces) for usernames
307     *
308     * @param string $user
309     * @return string
310     */
311    public function cleanUser($user) {
312        global $conf;
313        return cleanID(str_replace(':', $conf['sepchar'], $user));
314    }
315
316    /**
317     * Only valid pageid's (no namespaces) for groupnames
318     *
319     * @param string $group
320     * @return string
321     */
322    public function cleanGroup($group) {
323        global $conf;
324        return cleanID(str_replace(':', $conf['sepchar'], $group));
325    }
326
327    /**
328     * Load all user data
329     *
330     * loads the user file into a datastructure
331     *
332     * @author  Andreas Gohr <andi@splitbrain.org>
333     */
334    protected function _loadUserData() {
335        global $config_cascade;
336
337        $this->users = $this->_readUserFile($config_cascade['plainauth.users']['default']);
338
339        // support protected users
340        if(!empty($config_cascade['plainauth.users']['protected'])) {
341            $protected = $this->_readUserFile($config_cascade['plainauth.users']['protected']);
342            foreach(array_keys($protected) as $key) {
343                $protected[$key]['protected'] = true;
344            }
345            $this->users = array_merge($this->users, $protected);
346        }
347    }
348
349    /**
350     * Read user data from given file
351     *
352     * ignores non existing files
353     *
354     * @param string $file the file to load data from
355     * @return array
356     */
357    protected function _readUserFile($file) {
358        $users = array();
359        if(!file_exists($file)) return $users;
360
361        $lines = file($file);
362        foreach($lines as $line) {
363            $line = preg_replace('/#.*$/', '', $line); //ignore comments
364            $line = trim($line);
365            if(empty($line)) continue;
366
367            $row = $this->_splitUserData($line);
368            $row = str_replace('\\:', ':', $row);
369            $row = str_replace('\\\\', '\\', $row);
370
371            $groups = array_values(array_filter(explode(",", $row[4])));
372
373            $users[$row[0]]['pass'] = $row[1];
374            $users[$row[0]]['name'] = urldecode($row[2]);
375            $users[$row[0]]['mail'] = $row[3];
376            $users[$row[0]]['grps'] = $groups;
377        }
378        return $users;
379    }
380
381    protected function _splitUserData($line){
382        // due to a bug in PCRE 6.6, preg_split will fail with the regex we use here
383        // refer github issues 877 & 885
384        if ($this->_pregsplit_safe){
385            return preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5);       // allow for : escaped as \:
386        }
387
388        $row = array();
389        $piece = '';
390        $len = strlen($line);
391        for($i=0; $i<$len; $i++){
392            if ($line[$i]=='\\'){
393                $piece .= $line[$i];
394                $i++;
395                if ($i>=$len) break;
396            } else if ($line[$i]==':'){
397                $row[] = $piece;
398                $piece = '';
399                continue;
400            }
401            $piece .= $line[$i];
402        }
403        $row[] = $piece;
404
405        return $row;
406    }
407
408    /**
409     * return true if $user + $info match $filter criteria, false otherwise
410     *
411     * @author   Chris Smith <chris@jalakai.co.uk>
412     *
413     * @param string $user User login
414     * @param array  $info User's userinfo array
415     * @return bool
416     */
417    protected function _filter($user, $info) {
418        foreach($this->_pattern as $item => $pattern) {
419            if($item == 'user') {
420                if(!preg_match($pattern, $user)) return false;
421            } else if($item == 'grps') {
422                if(!count(preg_grep($pattern, $info['grps']))) return false;
423            } else {
424                if(!preg_match($pattern, $info[$item])) return false;
425            }
426        }
427        return true;
428    }
429
430    /**
431     * construct a filter pattern
432     *
433     * @param array $filter
434     */
435    protected function _constructPattern($filter) {
436        $this->_pattern = array();
437        foreach($filter as $item => $pattern) {
438            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
439        }
440    }
441}
442