xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision 20e29859d7134c28e50a97c828f78aa7fe719352)
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        if ($this->_auth->canDo('UserMod')) {
154            $edit_disable = '';
155            $img_useredit = 'user_edit.png';
156        } else {
157            $edit_disable = 'disabled="disabled"';
158            $img_useredit = 'no_user_edit.png';
159        }
160
161        print $this->locale_xhtml('intro');
162        print $this->locale_xhtml('list');
163
164        ptln("<div id=\"user__manager\">");
165        ptln("<div class=\"level2\">");
166
167        if ($this->_user_total > 0) {
168          ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>");
169        } else {
170          ptln("<p>".sprintf($this->lang['nonefound'],$this->_auth->getUserCount())."</p>");
171        }
172        ptln("<form action=\"".wl($ID)."\" method=\"post\">");
173        formSecurityToken();
174        ptln("  <table class=\"inline\">");
175        ptln("    <thead>");
176        ptln("      <tr>");
177        ptln("        <th colspan=\"2\">&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>");
178        ptln("      </tr>");
179
180        ptln("      <tr>");
181        ptln("        <td colspan=\"2\" class=\"rightalign\"><input type=\"image\" src=\"".DOKU_PLUGIN_IMAGES."search.png\" name=\"fn[search][new]\" title=\"".$this->lang['search_prompt']."\" alt=\"".$this->lang['search']."\" /></td>");
182        ptln("        <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>");
183        ptln("        <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>");
184        ptln("        <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>");
185        ptln("        <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>");
186        ptln("      </tr>");
187        ptln("    </thead>");
188
189        if ($this->_user_total) {
190          ptln("    <tbody>");
191          foreach ($user_list as $user => $userinfo) {
192            extract($userinfo);
193            $groups = join(', ',$grps);
194            ptln("    <tr class=\"user_info\">");
195            ptln("      <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".$user."]\" ".$delete_disable." /></td>");
196            ptln("      <td class=\"centeralign\"><input type=\"image\" name=\"fn[edit][".$user."]\" ".$edit_disable." src=\"".DOKU_PLUGIN_IMAGES.$img_useredit."\" title=\"".$this->lang['edit_prompt']."\" alt=\"".$this->lang['edit']."\"/></td>");
197            ptln("      <td>".hsc($user)."</td><td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>");
198            ptln("    </tr>");
199          }
200          ptln("    </tbody>");
201        }
202
203        ptln("    <tbody>");
204        ptln("      <tr><td colspan=\"6\" class=\"centeralign\">");
205        ptln("        <span class=\"medialeft\">");
206        ptln("          <input type=\"submit\" name=\"fn[delete]\" ".$delete_disable." class=\"button\" value=\"".$this->lang['delete_selected']."\" id=\"usrmgr__del\" />");
207        ptln("        </span>");
208        ptln("        <span class=\"mediaright\">");
209        ptln("          <input type=\"submit\" name=\"fn[start]\" ".$page_buttons['start']." class=\"button\" value=\"".$this->lang['start']."\" />");
210        ptln("          <input type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev']." class=\"button\" value=\"".$this->lang['prev']."\" />");
211        ptln("          <input type=\"submit\" name=\"fn[next]\" ".$page_buttons['next']." class=\"button\" value=\"".$this->lang['next']."\" />");
212        ptln("          <input type=\"submit\" name=\"fn[last]\" ".$page_buttons['last']." class=\"button\" value=\"".$this->lang['last']."\" />");
213        ptln("        </span>");
214        ptln("        <input type=\"submit\" name=\"fn[search][clear]\" class=\"button\" value=\"".$this->lang['clear']."\" />");
215        ptln("        <input type=\"hidden\" name=\"do\"    value=\"admin\" />");
216        ptln("        <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />");
217
218        $this->_htmlFilterSettings(2);
219
220        ptln("      </td></tr>");
221        ptln("    </tbody>");
222        ptln("  </table>");
223
224        ptln("</form>");
225        ptln("</div>");
226
227        $style = $this->_edit_user ? " class=\"edit_user\"" : "";
228
229        if ($this->_auth->canDo('addUser')) {
230          ptln("<div".$style.">");
231          print $this->locale_xhtml('add');
232          ptln("  <div class=\"level2\">");
233
234          $this->_htmlUserForm('add',null,array(),4);
235
236          ptln("  </div>");
237          ptln("</div>");
238        }
239
240        if($this->_edit_user  && $this->_auth->canDo('UserMod')){
241          ptln("<div".$style." id=\"scroll__here\">");
242          print $this->locale_xhtml('edit');
243          ptln("  <div class=\"level2\">");
244
245          $this->_htmlUserForm('modify',$this->_edit_user,$this->_edit_userdata,4);
246
247          ptln("  </div>");
248          ptln("</div>");
249        }
250        ptln("</div>");
251    }
252
253
254    /**
255     * @todo disable fields which the backend can't change
256     */
257    function _htmlUserForm($cmd,$user='',$userdata=array(),$indent=0) {
258        global $conf;
259        global $ID;
260
261        $name = $mail = $groups = '';
262        $notes = array();
263
264        if ($user) {
265          extract($userdata);
266          if (!empty($grps)) $groups = join(',',$grps);
267        } else {
268          $notes[] = sprintf($this->lang['note_group'],$conf['defaultgroup']);
269        }
270
271        ptln("<form action=\"".wl($ID)."\" method=\"post\">",$indent);
272        formSecurityToken();
273        ptln("  <table class=\"inline\">",$indent);
274        ptln("    <thead>",$indent);
275        ptln("      <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>",$indent);
276        ptln("    </thead>",$indent);
277        ptln("    <tbody>",$indent);
278
279        $this->_htmlInputField($cmd."_userid",    "userid",    $this->lang["user_id"],    $user,  $this->_auth->canDo("modLogin"), $indent+6);
280        $this->_htmlInputField($cmd."_userpass",  "userpass",  $this->lang["user_pass"],  "",     $this->_auth->canDo("modPass"),  $indent+6);
281        $this->_htmlInputField($cmd."_username",  "username",  $this->lang["user_name"],  $name,  $this->_auth->canDo("modName"),  $indent+6);
282        $this->_htmlInputField($cmd."_usermail",  "usermail",  $this->lang["user_mail"],  $mail,  $this->_auth->canDo("modMail"),  $indent+6);
283        $this->_htmlInputField($cmd."_usergroups","usergroups",$this->lang["user_groups"],$groups,$this->_auth->canDo("modGroups"),$indent+6);
284
285        if ($this->_auth->canDo("modPass")) {
286          $notes[] = $this->lang['note_pass'];
287          if ($user) {
288            $notes[] = $this->lang['note_notify'];
289          }
290
291          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);
292        }
293
294        ptln("    </tbody>",$indent);
295        ptln("    <tbody>",$indent);
296        ptln("      <tr>",$indent);
297        ptln("        <td colspan=\"2\">",$indent);
298        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
299        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
300
301        // save current $user, we need this to access details if the name is changed
302        if ($user)
303          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
304
305        $this->_htmlFilterSettings($indent+10);
306
307        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
308        ptln("        </td>",$indent);
309        ptln("      </tr>",$indent);
310        ptln("    </tbody>",$indent);
311        ptln("  </table>",$indent);
312
313        foreach ($notes as $note)
314          ptln("<div class=\"fn\">".$note."</div>",$indent);
315
316        ptln("</form>",$indent);
317    }
318
319    function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
320        $class = $cando ? '' : ' class="disabled"';
321        $disabled = $cando ? '' : ' disabled="disabled"';
322        echo str_pad('',$indent);
323
324        echo "<tr $class>";
325        echo "<td><label for=\"$id\" >$label: </label></td>";
326        echo "<td>";
327        if($cando){
328            echo "<input type=\"text\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" />";
329        }else{
330            echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
331            echo "<input type=\"text\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />";
332        }
333        echo "</td>";
334        echo "</tr>";
335    }
336
337    function _htmlFilter($key) {
338        if (empty($this->_filter)) return '';
339        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
340    }
341
342    function _htmlFilterSettings($indent=0) {
343
344        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
345
346        foreach ($this->_filter as $key => $filter) {
347          ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
348        }
349    }
350
351    function _addUser(){
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        if (empty($pass)){
358          if(!empty($_REQUEST['usernotify'])){
359            $pass = auth_pwgen();
360          } else {
361            return false;
362          }
363        }
364        if (empty($name) || empty($mail)){
365          msg($this->lang['add_fail'], -1);
366          return false;
367        }
368
369        if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) {
370
371          msg($this->lang['add_ok'], 1);
372
373          if (!empty($_REQUEST['usernotify']) && $pass) {
374            $this->_notifyUser($user,$pass);
375          }
376        } else {
377          msg($this->lang['add_fail'], -1);
378        }
379
380        return $ok;
381    }
382
383    /**
384     * Delete user
385     */
386    function _deleteUser(){
387        global $conf;
388
389        if (!checkSecurityToken()) return false;
390        if (!$this->_auth->canDo('delUser')) return false;
391
392        $selected = $_REQUEST['delete'];
393        if (!is_array($selected) || empty($selected)) return false;
394        $selected = array_keys($selected);
395
396		if(in_array($_SERVER['REMOTE_USER'], $selected)) {
397			msg("You can't delete yourself!", -1);
398			return false;
399		}
400
401        $count = $this->_auth->triggerUserMod('delete', array($selected));
402        if ($count == count($selected)) {
403          $text = str_replace('%d', $count, $this->lang['delete_ok']);
404          msg("$text.", 1);
405        } else {
406          $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
407          $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
408          msg("$part1, $part2",-1);
409        }
410
411        // invalidate all sessions
412        io_saveFile($conf['cachedir'].'/sessionpurge',time());
413
414        return true;
415    }
416
417    /**
418     * Edit user (a user has been selected for editing)
419     */
420    function _editUser($param) {
421        if (!checkSecurityToken()) return false;
422        if (!$this->_auth->canDo('UserMod')) return false;
423
424        $user = cleanID(preg_replace('/.*:/','',$param));
425        $userdata = $this->_auth->getUserData($user);
426
427        // no user found?
428        if (!$userdata) {
429          msg($this->lang['edit_usermissing'],-1);
430          return false;
431        }
432
433        $this->_edit_user = $user;
434        $this->_edit_userdata = $userdata;
435
436        return true;
437    }
438
439    /**
440     * Modify user (modified user data has been recieved)
441     */
442    function _modifyUser(){
443        global $conf;
444
445        if (!checkSecurityToken()) return false;
446        if (!$this->_auth->canDo('UserMod')) return false;
447
448        // get currently valid  user data
449        $olduser = cleanID(preg_replace('/.*:/','',$_REQUEST['userid_old']));
450        $oldinfo = $this->_auth->getUserData($olduser);
451
452        // get new user data subject to change
453        list($newuser,$newpass,$newname,$newmail,$newgrps) = $this->_retrieveUser();
454        if (empty($newuser)) return false;
455
456        $changes = array();
457        if ($newuser != $olduser) {
458
459          if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
460            msg($this->lang['update_fail'],-1);
461            return false;
462          }
463
464          // check if $newuser already exists
465          if ($this->_auth->getUserData($newuser)) {
466            msg(sprintf($this->lang['update_exists'],$newuser),-1);
467            $re_edit = true;
468          } else {
469            $changes['user'] = $newuser;
470          }
471        }
472
473        if (!empty($newpass) && $this->_auth->canDo('modPass'))
474          $changes['pass'] = $newpass;
475        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name'])
476          $changes['name'] = $newname;
477        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail'])
478          $changes['mail'] = $newmail;
479        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps'])
480          $changes['grps'] = $newgrps;
481
482        if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) {
483          msg($this->lang['update_ok'],1);
484
485          if (!empty($_REQUEST['usernotify']) && $newpass) {
486            $notify = empty($changes['user']) ? $olduser : $newuser;
487            $this->_notifyUser($notify,$newpass);
488          }
489
490          // invalidate all sessions
491          io_saveFile($conf['cachedir'].'/sessionpurge',time());
492
493        } else {
494          msg($this->lang['update_fail'],-1);
495        }
496
497        if (!empty($re_edit)) {
498            $this->_editUser($olduser);
499        }
500
501        return $ok;
502    }
503
504    /**
505     * send password change notification email
506     */
507    function _notifyUser($user, $password) {
508
509        if ($sent = auth_sendPassword($user,$password)) {
510          msg($this->lang['notify_ok'], 1);
511        } else {
512          msg($this->lang['notify_fail'], -1);
513        }
514
515        return $sent;
516    }
517
518    /**
519     * retrieve & clean user data from the form
520     *
521     * @return  array(user, password, full name, email, array(groups))
522     */
523    function _retrieveUser($clean=true) {
524
525        $user[0] = ($clean) ? cleanID(preg_replace('/.*:/','',$_REQUEST['userid'])) : $_REQUEST['userid'];
526        $user[1] = $_REQUEST['userpass'];
527        $user[2] = $_REQUEST['username'];
528        $user[3] = $_REQUEST['usermail'];
529        $user[4] = preg_split('/\s*,\s*/',$_REQUEST['usergroups'],-1,PREG_SPLIT_NO_EMPTY);
530
531        if (empty($user[4]) || (is_array($user[4]) && (count($user[4]) == 1) && (trim($user[4][0]) == ''))) {
532            $user[4] = null;
533        }
534
535        return $user;
536    }
537
538    function _setFilter($op) {
539
540        $this->_filter = array();
541
542        if ($op == 'new') {
543          list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser(false);
544
545          if (!empty($user)) $this->_filter['user'] = $user;
546          if (!empty($name)) $this->_filter['name'] = $name;
547          if (!empty($mail)) $this->_filter['mail'] = $mail;
548          if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
549        }
550    }
551
552    function _retrieveFilter() {
553
554        $t_filter = $_REQUEST['filter'];
555        if (!is_array($t_filter)) return array();
556
557        // messy, but this way we ensure we aren't getting any additional crap from malicious users
558        $filter = array();
559
560        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
561        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
562        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
563        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
564
565        return $filter;
566    }
567
568    function _validatePagination() {
569
570        if ($this->_start >= $this->_user_total) {
571          $this->_start = $this->_user_total - $this->_pagesize;
572        }
573        if ($this->_start < 0) $this->_start = 0;
574
575        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
576    }
577
578    /*
579     *  return an array of strings to enable/disable pagination buttons
580     */
581    function _pagination() {
582
583        $disabled = 'disabled="disabled"';
584
585        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
586
587        if ($this->_user_total == -1) {
588          $buttons['last'] = $disabled;
589          $buttons['next'] = '';
590        } else {
591          $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
592        }
593
594        return $buttons;
595    }
596}
597