xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision ee9498f56bb996332665780f790257bcd010ac3c)
1<?php
2/*
3 *  User Manager
4 *
5 *  Dokuwiki Admin Plugin
6 *
7 *  This version of the user manager has been modified to only work with
8 *  objectified version of auth system
9 *
10 *  @author  neolao <neolao@neolao.com>
11 *  @author  Chris Smith <chris@jalakai.co.uk>
12 */
13// must be run within Dokuwiki
14if(!defined('DOKU_INC')) die();
15
16if(!defined('DOKU_PLUGIN_IMAGES')) define('DOKU_PLUGIN_IMAGES',DOKU_BASE.'lib/plugins/usermanager/images/');
17
18/**
19 * All DokuWiki plugins to extend the admin function
20 * need to inherit from this class
21 */
22class admin_plugin_usermanager extends DokuWiki_Admin_Plugin {
23
24    var $_auth = null;        // auth object
25    var $_user_total = 0;     // number of registered users
26    var $_filter = array();   // user selection filter(s)
27    var $_start = 0;          // index of first user to be displayed
28    var $_last = 0;           // index of the last user to be displayed
29    var $_pagesize = 20;      // number of users to list on one page
30    var $_edit_user = '';     // set to user selected for editing
31    var $_edit_userdata = array();
32    var $_disabled = '';      // if disabled set to explanatory string
33
34    /**
35     * Constructor
36     */
37    function admin_plugin_usermanager(){
38        global $auth;
39
40        $this->setupLocale();
41
42        if (!isset($auth)) {
43          $this->disabled = $this->lang['noauth'];
44        } else if (!$auth->canDo('getUsers')) {
45          $this->disabled = $this->lang['nosupport'];
46        } else {
47
48          // we're good to go
49          $this->_auth = & $auth;
50
51        }
52    }
53
54     /**
55     * return prompt for admin menu
56     */
57    function getMenuText($language) {
58
59        if (!is_null($this->_auth))
60          return parent::getMenuText($language);
61
62        return $this->getLang('menu').' '.$this->disabled;
63    }
64
65    /**
66     * return sort order for position in admin menu
67     */
68    function getMenuSort() {
69        return 2;
70    }
71
72    /**
73     * handle user request
74     */
75    function handle() {
76        global $INPUT;
77        if (is_null($this->_auth)) return false;
78
79        // extract the command and any specific parameters
80        // submit button name is of the form - fn[cmd][param(s)]
81        $fn   = $INPUT->param('fn');
82
83        if (is_array($fn)) {
84            $cmd = key($fn);
85            $param = is_array($fn[$cmd]) ? key($fn[$cmd]) : null;
86        } else {
87            $cmd = $fn;
88            $param = null;
89        }
90
91        if ($cmd != "search") {
92          $this->_start = $INPUT->int('start', 0);
93          $this->_filter = $this->_retrieveFilter();
94        }
95
96        switch($cmd){
97          case "add"    : $this->_addUser(); break;
98          case "delete" : $this->_deleteUser(); break;
99          case "modify" : $this->_modifyUser(); break;
100          case "edit"   : $this->_editUser($param); break;
101          case "search" : $this->_setFilter($param);
102                          $this->_start = 0;
103                          break;
104        }
105
106        $this->_user_total = $this->_auth->canDo('getUserCount') ? $this->_auth->getUserCount($this->_filter) : -1;
107
108        // page handling
109        switch($cmd){
110          case 'start' : $this->_start = 0; break;
111          case 'prev'  : $this->_start -= $this->_pagesize; break;
112          case 'next'  : $this->_start += $this->_pagesize; break;
113          case 'last'  : $this->_start = $this->_user_total; break;
114        }
115        $this->_validatePagination();
116    }
117
118    /**
119     * output appropriate html
120     */
121    function html() {
122        global $ID;
123
124        if(is_null($this->_auth)) {
125            print $this->lang['badauth'];
126            return false;
127        }
128
129        $user_list = $this->_auth->retrieveUsers($this->_start, $this->_pagesize, $this->_filter);
130        $users = array_keys($user_list);
131
132        $page_buttons = $this->_pagination();
133        $delete_disable = $this->_auth->canDo('delUser') ? '' : 'disabled="disabled"';
134
135        $editable = $this->_auth->canDo('UserMod');
136
137        print $this->locale_xhtml('intro');
138        print $this->locale_xhtml('list');
139
140        ptln("<div id=\"user__manager\">");
141        ptln("<div class=\"level2\">");
142
143        if ($this->_user_total > 0) {
144          ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>");
145        } else {
146          ptln("<p>".sprintf($this->lang['nonefound'],$this->_auth->getUserCount())."</p>");
147        }
148        ptln("<form action=\"".wl($ID)."\" method=\"post\">");
149        formSecurityToken();
150        ptln("  <div class=\"table\">");
151        ptln("  <table class=\"inline\">");
152        ptln("    <thead>");
153        ptln("      <tr>");
154        ptln("        <th>&#160;</th><th>".$this->lang["user_id"]."</th><th>".$this->lang["user_name"]."</th><th>".$this->lang["user_mail"]."</th><th>".$this->lang["user_groups"]."</th>");
155        ptln("      </tr>");
156
157        ptln("      <tr>");
158        ptln("        <td class=\"rightalign\"><input type=\"image\" src=\"".DOKU_PLUGIN_IMAGES."search.png\" name=\"fn[search][new]\" title=\"".$this->lang['search_prompt']."\" alt=\"".$this->lang['search']."\" class=\"button\" /></td>");
159        ptln("        <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>");
160        ptln("        <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>");
161        ptln("        <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>");
162        ptln("        <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>");
163        ptln("      </tr>");
164        ptln("    </thead>");
165
166        if ($this->_user_total) {
167          ptln("    <tbody>");
168          foreach ($user_list as $user => $userinfo) {
169            extract($userinfo);
170            $groups = join(', ',$grps);
171            ptln("    <tr class=\"user_info\">");
172            ptln("      <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".$user."]\" ".$delete_disable." /></td>");
173            if ($editable) {
174              ptln("    <td><a href=\"".wl($ID,array('fn[edit]['.hsc($user).']' => 1,
175                                                     'do' => 'admin',
176                                                     'page' => 'usermanager',
177                                                     'sectok' => getSecurityToken())).
178                   "\" title=\"".$this->lang['edit_prompt']."\">".hsc($user)."</a></td>");
179            } else {
180              ptln("    <td>".hsc($user)."</td>");
181            }
182            ptln("      <td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>");
183            ptln("    </tr>");
184          }
185          ptln("    </tbody>");
186        }
187
188        ptln("    <tbody>");
189        ptln("      <tr><td colspan=\"5\" class=\"centeralign\">");
190        ptln("        <span class=\"medialeft\">");
191        ptln("          <input type=\"submit\" name=\"fn[delete]\" ".$delete_disable." class=\"button\" value=\"".$this->lang['delete_selected']."\" id=\"usrmgr__del\" />");
192        ptln("        </span>");
193        ptln("        <span class=\"mediaright\">");
194        ptln("          <input type=\"submit\" name=\"fn[start]\" ".$page_buttons['start']." class=\"button\" value=\"".$this->lang['start']."\" />");
195        ptln("          <input type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev']." class=\"button\" value=\"".$this->lang['prev']."\" />");
196        ptln("          <input type=\"submit\" name=\"fn[next]\" ".$page_buttons['next']." class=\"button\" value=\"".$this->lang['next']."\" />");
197        ptln("          <input type=\"submit\" name=\"fn[last]\" ".$page_buttons['last']." class=\"button\" value=\"".$this->lang['last']."\" />");
198        ptln("        </span>");
199        ptln("        <input type=\"submit\" name=\"fn[search][clear]\" class=\"button\" value=\"".$this->lang['clear']."\" />");
200        ptln("        <input type=\"hidden\" name=\"do\"    value=\"admin\" />");
201        ptln("        <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />");
202
203        $this->_htmlFilterSettings(2);
204
205        ptln("      </td></tr>");
206        ptln("    </tbody>");
207        ptln("  </table>");
208        ptln("  </div>");
209
210        ptln("</form>");
211        ptln("</div>");
212
213        $style = $this->_edit_user ? " class=\"edit_user\"" : "";
214
215        if ($this->_auth->canDo('addUser')) {
216          ptln("<div".$style.">");
217          print $this->locale_xhtml('add');
218          ptln("  <div class=\"level2\">");
219
220          $this->_htmlUserForm('add',null,array(),4);
221
222          ptln("  </div>");
223          ptln("</div>");
224        }
225
226        if($this->_edit_user  && $this->_auth->canDo('UserMod')){
227          ptln("<div".$style." id=\"scroll__here\">");
228          print $this->locale_xhtml('edit');
229          ptln("  <div class=\"level2\">");
230
231          $this->_htmlUserForm('modify',$this->_edit_user,$this->_edit_userdata,4);
232
233          ptln("  </div>");
234          ptln("</div>");
235        }
236        ptln("</div>");
237    }
238
239
240    /**
241     * @todo disable fields which the backend can't change
242     */
243    function _htmlUserForm($cmd,$user='',$userdata=array(),$indent=0) {
244        global $conf;
245        global $ID;
246
247        $name = $mail = $groups = '';
248        $notes = array();
249
250        if ($user) {
251          extract($userdata);
252          if (!empty($grps)) $groups = join(',',$grps);
253        } else {
254          $notes[] = sprintf($this->lang['note_group'],$conf['defaultgroup']);
255        }
256
257        ptln("<form action=\"".wl($ID)."\" method=\"post\">",$indent);
258        formSecurityToken();
259        ptln("  <div class=\"table\">",$indent);
260        ptln("  <table class=\"inline\">",$indent);
261        ptln("    <thead>",$indent);
262        ptln("      <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>",$indent);
263        ptln("    </thead>",$indent);
264        ptln("    <tbody>",$indent);
265
266        $this->_htmlInputField($cmd."_userid",    "userid",    $this->lang["user_id"],    $user,  $this->_auth->canDo("modLogin"), $indent+6);
267        $this->_htmlInputField($cmd."_userpass",  "userpass",  $this->lang["user_pass"],  "",     $this->_auth->canDo("modPass"),  $indent+6);
268        $this->_htmlInputField($cmd."_username",  "username",  $this->lang["user_name"],  $name,  $this->_auth->canDo("modName"),  $indent+6);
269        $this->_htmlInputField($cmd."_usermail",  "usermail",  $this->lang["user_mail"],  $mail,  $this->_auth->canDo("modMail"),  $indent+6);
270        $this->_htmlInputField($cmd."_usergroups","usergroups",$this->lang["user_groups"],$groups,$this->_auth->canDo("modGroups"),$indent+6);
271
272        if ($this->_auth->canDo("modPass")) {
273          if ($cmd == 'add') {
274            $notes[] = $this->lang['note_pass'];
275          }
276          if ($user) {
277            $notes[] = $this->lang['note_notify'];
278          }
279
280          ptln("<tr><td><label for=\"".$cmd."_usernotify\" >".$this->lang["user_notify"].": </label></td><td><input type=\"checkbox\" id=\"".$cmd."_usernotify\" name=\"usernotify\" value=\"1\" /></td></tr>", $indent);
281        }
282
283        ptln("    </tbody>",$indent);
284        ptln("    <tbody>",$indent);
285        ptln("      <tr>",$indent);
286        ptln("        <td colspan=\"2\">",$indent);
287        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
288        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
289
290        // save current $user, we need this to access details if the name is changed
291        if ($user)
292          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
293
294        $this->_htmlFilterSettings($indent+10);
295
296        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
297        ptln("        </td>",$indent);
298        ptln("      </tr>",$indent);
299        ptln("    </tbody>",$indent);
300        ptln("  </table>",$indent);
301        ptln("  </div>",$indent);
302
303        foreach ($notes as $note)
304          ptln("<div class=\"fn\">".$note."</div>",$indent);
305
306        ptln("</form>",$indent);
307    }
308
309    function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
310        $class = $cando ? '' : ' class="disabled"';
311        echo str_pad('',$indent);
312
313        if($name == 'userpass'){
314            $fieldtype = 'password';
315            $autocomp  = 'autocomplete="off"';
316        }elseif($name == 'usermail'){
317            $fieldtype = 'email';
318            $autocomp  = '';
319        }else{
320            $fieldtype = 'text';
321            $autocomp  = '';
322        }
323
324
325        echo "<tr $class>";
326        echo "<td><label for=\"$id\" >$label: </label></td>";
327        echo "<td>";
328        if($cando){
329            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" $autocomp />";
330        }else{
331            echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
332            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />";
333        }
334        echo "</td>";
335        echo "</tr>";
336    }
337
338    function _htmlFilter($key) {
339        if (empty($this->_filter)) return '';
340        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
341    }
342
343    function _htmlFilterSettings($indent=0) {
344
345        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
346
347        foreach ($this->_filter as $key => $filter) {
348          ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
349        }
350    }
351
352    function _addUser(){
353        global $INPUT;
354        if (!checkSecurityToken()) return false;
355        if (!$this->_auth->canDo('addUser')) return false;
356
357        list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser();
358        if (empty($user)) return false;
359
360        if ($this->_auth->canDo('modPass')){
361          if (empty($pass)){
362            if($INPUT->has('usernotify')){
363              $pass = auth_pwgen($user);
364            } else {
365              msg($this->lang['add_fail'], -1);
366              return false;
367            }
368          }
369        } else {
370          if (!empty($pass)){
371            msg($this->lang['add_fail'], -1);
372            return false;
373          }
374        }
375
376        if ($this->_auth->canDo('modName')){
377          if (empty($name)){
378            msg($this->lang['add_fail'], -1);
379            return false;
380          }
381        } else {
382          if (!empty($name)){
383            return false;
384          }
385        }
386
387        if ($this->_auth->canDo('modMail')){
388          if (empty($mail)){
389            msg($this->lang['add_fail'], -1);
390            return false;
391          }
392        } else {
393          if (!empty($mail)){
394            return false;
395          }
396        }
397
398        if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) {
399
400          msg($this->lang['add_ok'], 1);
401
402          if ($INPUT->has('usernotify') && $pass) {
403            $this->_notifyUser($user,$pass);
404          }
405        } else {
406          msg($this->lang['add_fail'], -1);
407        }
408
409        return $ok;
410    }
411
412    /**
413     * Delete user
414     */
415    function _deleteUser(){
416        global $conf, $INPUT;
417
418        if (!checkSecurityToken()) return false;
419        if (!$this->_auth->canDo('delUser')) return false;
420
421        $selected = $INPUT->arr('delete');
422        if (empty($selected)) return false;
423        $selected = array_keys($selected);
424
425        if(in_array($_SERVER['REMOTE_USER'], $selected)) {
426            msg("You can't delete yourself!", -1);
427            return false;
428        }
429
430        $count = $this->_auth->triggerUserMod('delete', array($selected));
431        if ($count == count($selected)) {
432          $text = str_replace('%d', $count, $this->lang['delete_ok']);
433          msg("$text.", 1);
434        } else {
435          $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
436          $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
437          msg("$part1, $part2",-1);
438        }
439
440        // invalidate all sessions
441        io_saveFile($conf['cachedir'].'/sessionpurge',time());
442
443        return true;
444    }
445
446    /**
447     * Edit user (a user has been selected for editing)
448     */
449    function _editUser($param) {
450        if (!checkSecurityToken()) return false;
451        if (!$this->_auth->canDo('UserMod')) return false;
452
453        $user = cleanID(preg_replace('/.*:/','',$param));
454        $userdata = $this->_auth->getUserData($user);
455
456        // no user found?
457        if (!$userdata) {
458          msg($this->lang['edit_usermissing'],-1);
459          return false;
460        }
461
462        $this->_edit_user = $user;
463        $this->_edit_userdata = $userdata;
464
465        return true;
466    }
467
468    /**
469     * Modify user (modified user data has been recieved)
470     */
471    function _modifyUser(){
472        global $conf, $INPUT;
473
474        if (!checkSecurityToken()) return false;
475        if (!$this->_auth->canDo('UserMod')) return false;
476
477        // get currently valid  user data
478        $olduser = cleanID(preg_replace('/.*:/','',$INPUT->str('userid_old')));
479        $oldinfo = $this->_auth->getUserData($olduser);
480
481        // get new user data subject to change
482        list($newuser,$newpass,$newname,$newmail,$newgrps) = $this->_retrieveUser();
483        if (empty($newuser)) return false;
484
485        $changes = array();
486        if ($newuser != $olduser) {
487
488          if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
489            msg($this->lang['update_fail'],-1);
490            return false;
491          }
492
493          // check if $newuser already exists
494          if ($this->_auth->getUserData($newuser)) {
495            msg(sprintf($this->lang['update_exists'],$newuser),-1);
496            $re_edit = true;
497          } else {
498            $changes['user'] = $newuser;
499          }
500        }
501
502        // generate password if left empty and notification is on
503        if($INPUT->has('usernotify') && empty($newpass)){
504            $newpass = auth_pwgen($olduser);
505        }
506
507        if (!empty($newpass) && $this->_auth->canDo('modPass'))
508          $changes['pass'] = $newpass;
509        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name'])
510          $changes['name'] = $newname;
511        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail'])
512          $changes['mail'] = $newmail;
513        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps'])
514          $changes['grps'] = $newgrps;
515
516        if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) {
517          msg($this->lang['update_ok'],1);
518
519          if ($INPUT->has('usernotify') && $newpass) {
520            $notify = empty($changes['user']) ? $olduser : $newuser;
521            $this->_notifyUser($notify,$newpass);
522          }
523
524          // invalidate all sessions
525          io_saveFile($conf['cachedir'].'/sessionpurge',time());
526
527        } else {
528          msg($this->lang['update_fail'],-1);
529        }
530
531        if (!empty($re_edit)) {
532            $this->_editUser($olduser);
533        }
534
535        return $ok;
536    }
537
538    /**
539     * send password change notification email
540     */
541    function _notifyUser($user, $password) {
542
543        if ($sent = auth_sendPassword($user,$password)) {
544          msg($this->lang['notify_ok'], 1);
545        } else {
546          msg($this->lang['notify_fail'], -1);
547        }
548
549        return $sent;
550    }
551
552    /**
553     * retrieve & clean user data from the form
554     *
555     * @return array (user, password, full name, email, array(groups))
556     */
557    function _retrieveUser($clean=true) {
558        global $auth;
559        global $INPUT;
560
561        $user[0] = ($clean) ? $auth->cleanUser($INPUT->str('userid')) : $INPUT->str('userid');
562        $user[1] = $INPUT->str('userpass');
563        $user[2] = $INPUT->str('username');
564        $user[3] = $INPUT->str('usermail');
565        $user[4] = explode(',',$INPUT->str('usergroups'));
566
567        $user[4] = array_map('trim',$user[4]);
568        if($clean) $user[4] = array_map(array($auth,'cleanGroup'),$user[4]);
569        $user[4] = array_filter($user[4]);
570        $user[4] = array_unique($user[4]);
571        if(!count($user[4])) $user[4] = null;
572
573        return $user;
574    }
575
576    function _setFilter($op) {
577
578        $this->_filter = array();
579
580        if ($op == 'new') {
581          list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser(false);
582
583          if (!empty($user)) $this->_filter['user'] = $user;
584          if (!empty($name)) $this->_filter['name'] = $name;
585          if (!empty($mail)) $this->_filter['mail'] = $mail;
586          if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
587        }
588    }
589
590    function _retrieveFilter() {
591        global $INPUT;
592
593        $t_filter = $INPUT->arr('filter');
594
595        // messy, but this way we ensure we aren't getting any additional crap from malicious users
596        $filter = array();
597
598        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
599        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
600        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
601        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
602
603        return $filter;
604    }
605
606    function _validatePagination() {
607
608        if ($this->_start >= $this->_user_total) {
609          $this->_start = $this->_user_total - $this->_pagesize;
610        }
611        if ($this->_start < 0) $this->_start = 0;
612
613        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
614    }
615
616    /*
617     *  return an array of strings to enable/disable pagination buttons
618     */
619    function _pagination() {
620
621        $disabled = 'disabled="disabled"';
622
623        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
624
625        if ($this->_user_total == -1) {
626          $buttons['last'] = $disabled;
627          $buttons['next'] = '';
628        } else {
629          $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
630        }
631
632        return $buttons;
633    }
634}
635