xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision 2c5c33084b359f89e534423a600774972e9d84d3)
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 */
13if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../../').'/');
14if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
15if(!defined('DOKU_PLUGIN_IMAGES')) define('DOKU_PLUGIN_IMAGES',DOKU_BASE.'lib/plugins/usermanager/images/');
16require_once(DOKU_PLUGIN.'admin.php');
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 $_user_edit = null;   // set to user selected for editing
31    var $_disabled = '';      // if disabled set to explanatory string
32
33    /**
34     * Constructor
35     */
36    function admin_plugin_usermanager(){
37        global $auth;
38
39        $this->setupLocale();
40
41        if (!isset($auth)) {
42          $this->disabled = $this->lang['noauth'];
43        } else if (!$auth->canDo('getUsers')) {
44          $this->disabled = $this->lang['notsupported'];
45        } else {
46
47          // we're good to go
48          $this->_auth = & $auth;
49
50                }
51    }
52
53    /**
54     * return some info
55     */
56    function getInfo(){
57
58        return array(
59            'author' => 'Chris Smith',
60            'email'  => 'chris@jalakai.co.uk',
61            'date'   => '2005-11-24',
62            'name'   => 'User Manager',
63            'desc'   => 'Manage users '.$this->disabled,
64            'url'    => 'http://wiki.splitbrain.org/plugin:user_manager',
65        );
66    }
67     /**
68     * return prompt for admin menu
69     */
70    function getMenuText($language) {
71
72        if (!is_null($this->_auth))
73          return parent::getMenuText($language);
74
75        return $this->getLang["menu"].' '.$this->disabled;
76    }
77
78    /**
79     * return sort order for position in admin menu
80     */
81    function getMenuSort() {
82        return 2;
83    }
84
85    /**
86     * handle user request
87     */
88    function handle() {
89        global $ID;
90
91        if (is_null($this->_auth)) return false;
92
93        // extract the command and any specific parameters
94        // submit button name is of the form - fn[cmd][param(s)]
95        $fn   = $_REQUEST['fn'];
96
97        if (is_array($fn)) {
98            $cmd = key($fn);
99            $param = is_array($fn[$cmd]) ? key($fn[$cmd]) : null;
100        } else {
101            $cmd = $fn;
102            $param = null;
103        }
104
105        if ($cmd != "search") {
106          if (!empty($_REQUEST['start']))
107            $this->_start = $_REQUEST['start'];
108          $this->_filter = $this->_retrieveFilter();
109        }
110
111        switch($cmd){
112          case "add"    : $this->_addUser(); break;
113          case "delete" : $this->_deleteUser(); break;
114          case "modify" : $this->_modifyUser(); break;
115          case "edit"   : $this->_edit_user = $param; break;     // no extra handling required - only html
116          case "search" : $this->_setFilter($param);
117                          $this->_start = 0;
118                          break;
119        }
120
121        $this->_user_total = $this->_auth->canDo('getUserCount') ? $this->_auth->getUserCount($this->_filter) : -1;
122
123        // page handling
124        switch($cmd){
125          case 'start' : $this->_start = 0; break;
126          case 'prev'  : $this->_start -= $this->_pagesize; break;
127          case 'next'  : $this->_start += $this->_pagesize; break;
128          case 'last'  : $this->_start = $this->_user_total; break;
129        }
130        $this->_validatePagination();
131    }
132
133    /**
134     * output appropriate html
135     */
136    function html() {
137        global $ID;
138
139        if(is_null($this->_auth)) {
140            print $this->lang['badauth'];
141            return false;
142        }
143
144        $user_list = $this->_auth->retrieveUsers($this->_start, $this->_pagesize, $this->_filter);
145        $users = array_keys($user_list);
146
147        $page_buttons = $this->_pagination();
148        $delete_disable = $this->_auth->canDo('delUser') ? '' : 'disabled="disabled"';
149
150        if ($this->_auth->canDo('UserMod')) {
151            $edit_disable = '';
152            $img_useredit = 'user_edit.png';
153        } else {
154            $edit_disable = 'disabled="disabled"';
155            $img_useredit = 'no_user_edit.png';
156        }
157
158        print $this->locale_xhtml('intro');
159        print $this->locale_xhtml('list');
160
161        ptln("<div class=\"level2\" style=\"margin-bottom: 2em;\">");
162
163        if ($this->_user_total > 0) {
164          ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>");
165        } else {
166          ptln("<p>".sprintf($this->lang['nonefound'],$this->_auth->getUserCount())."</p>");
167        }
168        ptln("<form action=\"".wl($ID)."\" method=\"post\">");
169        ptln("  <table class=\"inline\">");
170        ptln("    <thead>");
171        ptln("      <tr>");
172        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>");
173        ptln("      </tr>");
174
175        ptln("      <tr>");
176        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>");
177        ptln("        <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>");
178        ptln("        <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>");
179        ptln("        <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>");
180        ptln("        <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>");
181        ptln("      </tr>");
182        ptln("    </thead>");
183
184        if ($this->_user_total) {
185          ptln("    <tbody>");
186          foreach ($user_list as $user => $userinfo) {
187            extract($userinfo);
188            $groups = join(', ',$grps);
189            ptln("    <tr class=\"user_info\">");
190            ptln("      <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".$user."]\" ".$delete_disable." /></td>");
191            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>");
192            ptln("      <td>".hsc($user)."</td><td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>");
193            ptln("    </tr>");
194          }
195          ptln("    </tbody>");
196        }
197
198        ptln("    <tbody>");
199        ptln("      <tr><td colspan=\"6\" class=\"centeralign\">");
200        ptln("        <span class=\"medialeft\">");
201        ptln("          <input type=\"submit\" name=\"fn[delete]\" ".$delete_disable." class=\"button\" value=\"".$this->lang['delete_selected']."\" id=\"usrmgr__del\" />");
202        ptln("        </span>");
203        ptln("        <span class=\"mediaright\">");
204        ptln("          <input type=\"submit\" name=\"fn[start]\" ".$page_buttons['start']." class=\"button\" value=\"".$this->lang['start']."\" />");
205        ptln("          <input type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev']." class=\"button\" value=\"".$this->lang['prev']."\" />");
206        ptln("          <input type=\"submit\" name=\"fn[next]\" ".$page_buttons['next']." class=\"button\" value=\"".$this->lang['next']."\" />");
207        ptln("          <input type=\"submit\" name=\"fn[last]\" ".$page_buttons['last']." class=\"button\" value=\"".$this->lang['last']."\" />");
208        ptln("        </span>");
209        ptln("        <input type=\"submit\" name=\"fn[search][clear]\" class=\"button\" value=\"".$this->lang['clear']."\" />");
210        ptln("        <input type=\"hidden\" name=\"do\"    value=\"admin\" />");
211        ptln("        <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />");
212        ptln("      </td></tr>");
213        ptln("    </tbody>");
214        ptln("  </table>");
215
216        $this->_htmlFilterSettings(2);
217
218        ptln("</form>");
219        ptln("</div>");
220
221        $style = $this->_edit_user ? " class=\"edit_user\"" : "";
222
223        if ($this->_auth->canDo('addUser')) {
224          ptln("<div".$style.">");
225          print $this->locale_xhtml('add');
226          ptln("  <div class=\"level2\">");
227
228          $this->_htmlUserForm('add',null,4);
229
230          ptln("  </div>");
231          ptln("</div>");
232        }
233
234        if($this->_edit_user  && $this->_auth->canDo('UserMod')){
235          ptln("<div".$style." id=\"scroll__here\">");
236          print $this->locale_xhtml('edit');
237          ptln("  <div class=\"level2\">");
238
239          $this->_htmlUserForm('modify',$this->_edit_user,4);
240
241          ptln("  </div>");
242          ptln("</div>");
243        }
244    }
245
246
247    /**
248     * @todo disable fields which the backend can't change
249     */
250    function _htmlUserForm($cmd,$user=null,$indent=0) {
251
252        if ($user) {
253          extract($this->_auth->getUserData($user));
254          $groups = join(',',$grps);
255        } else {
256          $user = $name = $mail = $groups = '';
257        }
258
259        ptln("<form action=\"".wl($ID)."\" method=\"post\">",$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        ptln("    </tbody>",$indent);
273        ptln("    <tbody>",$indent);
274        ptln("      <tr>",$indent);
275        ptln("        <td colspan=\"2\">",$indent);
276        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
277        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
278
279        // save current $user, we need this to access details if the name is changed
280        if ($user)
281          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
282
283        $this->_htmlFilterSettings($indent+10);
284
285        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
286        ptln("        </td>",$indent);
287        ptln("      </tr>",$indent);
288        ptln("    </tbody>",$indent);
289        ptln("  </table>",$indent);
290        ptln("</form>",$indent);
291    }
292
293    function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
294        $disabled = $cando ? "" : " disabled=\"disabled\"";
295        $class = $cando ? "" : " class=\"disabled\"";
296        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);
297    }
298
299    function _htmlFilter($key) {
300        if (empty($this->_filter)) return '';
301        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
302    }
303
304    function _htmlFilterSettings($indent=0) {
305
306        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
307
308        foreach ($this->_filter as $key => $filter) {
309          ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
310        }
311    }
312
313    function _addUser(){
314
315        if (!$this->_auth->canDo('addUser')) return false;
316
317        list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser();
318        if (empty($user)) return false;
319
320        return $this->_auth->createUser($user,$pass,$name,$mail,$grps);
321    }
322
323    /**
324     * Delete user
325     */
326    function _deleteUser(){
327
328        if (!$this->_auth->canDo('delUser')) return false;
329
330        $selected = $_REQUEST['delete'];
331        if (!is_array($selected) || empty($selected)) return false;
332        $selected = array_keys($selected);
333
334        $count = $this->_auth->deleteUsers($selected);
335        if ($count == count($selected)) {
336          $text = str_replace('%d', $count, $this->lang['delete_ok']);
337          msg("$text.", 1);
338        } else {
339          $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
340          $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
341          msg("$part1, $part2",-1);
342        }
343    }
344
345    /**
346     * Modify user
347     */
348    function _modifyUser(){
349        if (!$this->_auth->canDo('UserMod')) return false;
350
351        // get currently valid  user data
352        $olduser = cleanID(preg_replace('/.*:/','',$_REQUEST['userid_old']));
353        $oldinfo = $this->_auth->getUserData($olduser);
354
355        // get new user data subject to change
356        list($newuser,$newpass,$newname,$newmail,$newgrps) = $this->_retrieveUser();
357        if (empty($newuser)) return false;
358
359        $changes = array();
360        if ($newuser != $olduser) {
361
362          if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
363            msg($this->lang['update_fail'],-1);
364            return false;
365          }
366
367          // check if $newuser already exists
368          if ($this->_auth->getUserData($newuser)) {
369            msg(sprintf($this->lang['update_exists'],$newuser),-1);
370            $this->_edit_user = $olduser;
371          } else {
372            $changes['user'] = $newuser;
373          }
374        }
375
376        if (!empty($newpass) && $this->_auth->canDo('modPass'))
377          $changes['pass'] = $newpass;
378        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name'])
379          $changes['name'] = $newname;
380        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail'])
381          $changes['mail'] = $newmail;
382        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps'])
383          $changes['grps'] = $newgrps;
384
385    if ($this->_auth->modifyUser($olduser, $changes)) {
386          msg($this->lang['update_ok'],1);
387        } else {
388          msg($this->lang['update_fail'],-1);
389        }
390    }
391
392    /*
393     * retrieve & clean user data from the form
394     * return an array(user, password, full name, email, array(groups))
395     */
396    function _retrieveUser($clean=true) {
397
398        $user[0] = ($clean) ? cleanID(preg_replace('/.*:/','',$_REQUEST['userid'])) : $_REQUEST['userid'];
399        $user[1] = $_REQUEST['userpass'];
400        $user[2] = $_REQUEST['username'];
401        $user[3] = $_REQUEST['usermail'];
402        $user[4] = preg_split('/\s*,\s*/',$_REQUEST['usergroups'],-1,PREG_SPLIT_NO_EMPTY);
403
404        if (is_array($user[4]) && (count($user[4]) == 1) && (trim($user[4][0]) == '')) {
405            $user[4] = null;
406        }
407
408        return $user;
409    }
410
411    function _setFilter($op) {
412
413        $this->_filter = array();
414
415        if ($op == 'new') {
416          list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser(false);
417
418          if (!empty($user)) $this->_filter['user'] = $user;
419          if (!empty($name)) $this->_filter['name'] = $name;
420          if (!empty($mail)) $this->_filter['mail'] = $mail;
421          if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
422        }
423    }
424
425    function _retrieveFilter() {
426
427        $t_filter = $_REQUEST['filter'];
428        if (!is_array($t_filter)) return array();
429
430        // messy, but this way we ensure we aren't getting any additional crap from malicious users
431        $filter = array();
432
433        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
434        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
435        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
436        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
437
438        return $filter;
439    }
440
441    function _validatePagination() {
442
443        if ($this->_start >= $this->_user_total) {
444          $this->_start = $this->_user_total - $this->_pagesize;
445        }
446        if ($this->_start < 0) $this->_start = 0;
447
448        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
449    }
450
451    /*
452     *  return an array of strings to enable/disable pagination buttons
453     */
454    function _pagination() {
455
456        $disabled = 'disabled="disabled"';
457
458        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
459
460        if ($this->_user_total == -1) {
461          $buttons['last'] = $disabled;
462          $buttons['next'] = '';
463        } else {
464          $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
465        }
466
467        return $buttons;
468    }
469}
470