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