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