xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision 7b3674bd7a2b20df3ba37b32b7cc33f574a95dc5)
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          $notes[] = $this->lang['note_pass'];
274          if ($user) {
275            $notes[] = $this->lang['note_notify'];
276          }
277
278          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);
279        }
280
281        ptln("    </tbody>",$indent);
282        ptln("    <tbody>",$indent);
283        ptln("      <tr>",$indent);
284        ptln("        <td colspan=\"2\">",$indent);
285        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
286        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
287
288        // save current $user, we need this to access details if the name is changed
289        if ($user)
290          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
291
292        $this->_htmlFilterSettings($indent+10);
293
294        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
295        ptln("        </td>",$indent);
296        ptln("      </tr>",$indent);
297        ptln("    </tbody>",$indent);
298        ptln("  </table>",$indent);
299        ptln("  </div>",$indent);
300
301        foreach ($notes as $note)
302          ptln("<div class=\"fn\">".$note."</div>",$indent);
303
304        ptln("</form>",$indent);
305    }
306
307    function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
308        $class = $cando ? '' : ' class="disabled"';
309        echo str_pad('',$indent);
310
311        if($name == 'userpass'){
312            $fieldtype = 'password';
313            $autocomp  = 'autocomplete="off"';
314        }elseif($name == 'usermail'){
315            $fieldtype = 'email';
316            $autocomp  = '';
317        }else{
318            $fieldtype = 'text';
319            $autocomp  = '';
320        }
321
322
323        echo "<tr $class>";
324        echo "<td><label for=\"$id\" >$label: </label></td>";
325        echo "<td>";
326        if($cando){
327            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" $autocomp />";
328        }else{
329            echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
330            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />";
331        }
332        echo "</td>";
333        echo "</tr>";
334    }
335
336    function _htmlFilter($key) {
337        if (empty($this->_filter)) return '';
338        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
339    }
340
341    function _htmlFilterSettings($indent=0) {
342
343        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
344
345        foreach ($this->_filter as $key => $filter) {
346          ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
347        }
348    }
349
350    function _addUser(){
351        global $INPUT;
352        if (!checkSecurityToken()) return false;
353        if (!$this->_auth->canDo('addUser')) return false;
354
355        list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser();
356        if (empty($user)) return false;
357
358        if ($this->_auth->canDo('modPass')){
359          if (empty($pass)){
360            if($INPUT->has('usernotify')){
361              $pass = auth_pwgen($user);
362            } else {
363              msg($this->lang['add_fail'], -1);
364              return false;
365            }
366          }
367        } else {
368          if (!empty($pass)){
369            msg($this->lang['add_fail'], -1);
370            return false;
371          }
372        }
373
374        if ($this->_auth->canDo('modName')){
375          if (empty($name)){
376            msg($this->lang['add_fail'], -1);
377            return false;
378          }
379        } else {
380          if (!empty($name)){
381            return false;
382          }
383        }
384
385        if ($this->_auth->canDo('modMail')){
386          if (empty($mail)){
387            msg($this->lang['add_fail'], -1);
388            return false;
389          }
390        } else {
391          if (!empty($mail)){
392            return false;
393          }
394        }
395
396        if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) {
397
398          msg($this->lang['add_ok'], 1);
399
400          if ($INPUT->has('usernotify') && $pass) {
401            $this->_notifyUser($user,$pass);
402          }
403        } else {
404          msg($this->lang['add_fail'], -1);
405        }
406
407        return $ok;
408    }
409
410    /**
411     * Delete user
412     */
413    function _deleteUser(){
414        global $conf, $INPUT;
415
416        if (!checkSecurityToken()) return false;
417        if (!$this->_auth->canDo('delUser')) return false;
418
419        $selected = $INPUT->arr('delete');
420        if (empty($selected)) return false;
421        $selected = array_keys($selected);
422
423        if(in_array($_SERVER['REMOTE_USER'], $selected)) {
424            msg("You can't delete yourself!", -1);
425            return false;
426        }
427
428        $count = $this->_auth->triggerUserMod('delete', array($selected));
429        if ($count == count($selected)) {
430          $text = str_replace('%d', $count, $this->lang['delete_ok']);
431          msg("$text.", 1);
432        } else {
433          $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
434          $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
435          msg("$part1, $part2",-1);
436        }
437
438        // invalidate all sessions
439        io_saveFile($conf['cachedir'].'/sessionpurge',time());
440
441        return true;
442    }
443
444    /**
445     * Edit user (a user has been selected for editing)
446     */
447    function _editUser($param) {
448        if (!checkSecurityToken()) return false;
449        if (!$this->_auth->canDo('UserMod')) return false;
450
451        $user = cleanID(preg_replace('/.*:/','',$param));
452        $userdata = $this->_auth->getUserData($user);
453
454        // no user found?
455        if (!$userdata) {
456          msg($this->lang['edit_usermissing'],-1);
457          return false;
458        }
459
460        $this->_edit_user = $user;
461        $this->_edit_userdata = $userdata;
462
463        return true;
464    }
465
466    /**
467     * Modify user (modified user data has been recieved)
468     */
469    function _modifyUser(){
470        global $conf, $INPUT;
471
472        if (!checkSecurityToken()) return false;
473        if (!$this->_auth->canDo('UserMod')) return false;
474
475        // get currently valid  user data
476        $olduser = cleanID(preg_replace('/.*:/','',$INPUT->str('userid_old')));
477        $oldinfo = $this->_auth->getUserData($olduser);
478
479        // get new user data subject to change
480        list($newuser,$newpass,$newname,$newmail,$newgrps) = $this->_retrieveUser();
481        if (empty($newuser)) return false;
482
483        $changes = array();
484        if ($newuser != $olduser) {
485
486          if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
487            msg($this->lang['update_fail'],-1);
488            return false;
489          }
490
491          // check if $newuser already exists
492          if ($this->_auth->getUserData($newuser)) {
493            msg(sprintf($this->lang['update_exists'],$newuser),-1);
494            $re_edit = true;
495          } else {
496            $changes['user'] = $newuser;
497          }
498        }
499
500        // generate password if left empty and notification is on
501        if($INPUT->has('usernotify') && empty($newpass)){
502            $newpass = auth_pwgen($olduser);
503        }
504
505        if (!empty($newpass) && $this->_auth->canDo('modPass'))
506          $changes['pass'] = $newpass;
507        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name'])
508          $changes['name'] = $newname;
509        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail'])
510          $changes['mail'] = $newmail;
511        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps'])
512          $changes['grps'] = $newgrps;
513
514        if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) {
515          msg($this->lang['update_ok'],1);
516
517          if ($INPUT->has('usernotify') && $newpass) {
518            $notify = empty($changes['user']) ? $olduser : $newuser;
519            $this->_notifyUser($notify,$newpass);
520          }
521
522          // invalidate all sessions
523          io_saveFile($conf['cachedir'].'/sessionpurge',time());
524
525        } else {
526          msg($this->lang['update_fail'],-1);
527        }
528
529        if (!empty($re_edit)) {
530            $this->_editUser($olduser);
531        }
532
533        return $ok;
534    }
535
536    /**
537     * send password change notification email
538     */
539    function _notifyUser($user, $password) {
540
541        if ($sent = auth_sendPassword($user,$password)) {
542          msg($this->lang['notify_ok'], 1);
543        } else {
544          msg($this->lang['notify_fail'], -1);
545        }
546
547        return $sent;
548    }
549
550    /**
551     * retrieve & clean user data from the form
552     *
553     * @return array (user, password, full name, email, array(groups))
554     */
555    function _retrieveUser($clean=true) {
556        global $auth;
557        global $INPUT;
558
559        $user[0] = ($clean) ? $auth->cleanUser($INPUT->str('userid')) : $INPUT->str('userid');
560        $user[1] = $INPUT->str('userpass');
561        $user[2] = $INPUT->str('username');
562        $user[3] = $INPUT->str('usermail');
563        $user[4] = explode(',',$INPUT->str('usergroups'));
564
565        $user[4] = array_map('trim',$user[4]);
566        if($clean) $user[4] = array_map(array($auth,'cleanGroup'),$user[4]);
567        $user[4] = array_filter($user[4]);
568        $user[4] = array_unique($user[4]);
569        if(!count($user[4])) $user[4] = null;
570
571        return $user;
572    }
573
574    function _setFilter($op) {
575
576        $this->_filter = array();
577
578        if ($op == 'new') {
579          list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser(false);
580
581          if (!empty($user)) $this->_filter['user'] = $user;
582          if (!empty($name)) $this->_filter['name'] = $name;
583          if (!empty($mail)) $this->_filter['mail'] = $mail;
584          if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
585        }
586    }
587
588    function _retrieveFilter() {
589        global $INPUT;
590
591        $t_filter = $INPUT->arr('filter');
592
593        // messy, but this way we ensure we aren't getting any additional crap from malicious users
594        $filter = array();
595
596        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
597        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
598        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
599        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
600
601        return $filter;
602    }
603
604    function _validatePagination() {
605
606        if ($this->_start >= $this->_user_total) {
607          $this->_start = $this->_user_total - $this->_pagesize;
608        }
609        if ($this->_start < 0) $this->_start = 0;
610
611        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
612    }
613
614    /*
615     *  return an array of strings to enable/disable pagination buttons
616     */
617    function _pagination() {
618
619        $disabled = 'disabled="disabled"';
620
621        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
622
623        if ($this->_user_total == -1) {
624          $buttons['last'] = $disabled;
625          $buttons['next'] = '';
626        } else {
627          $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
628        }
629
630        return $buttons;
631    }
632}
633