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