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