xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision 58dde80d4add67c5251ac3f0107968131fb471b3)
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 id=\"user__manager\">");
162        ptln("<div class=\"level2\">");
163
164        if ($this->_user_total > 0) {
165          ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>");
166        } else {
167          ptln("<p>".sprintf($this->lang['nonefound'],$this->_auth->getUserCount())."</p>");
168        }
169        ptln("<form action=\"".wl($ID)."\" method=\"post\">");
170        ptln("  <table class=\"inline\">");
171        ptln("    <thead>");
172        ptln("      <tr>");
173        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>");
174        ptln("      </tr>");
175
176        ptln("      <tr>");
177        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>");
178        ptln("        <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>");
179        ptln("        <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>");
180        ptln("        <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>");
181        ptln("        <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>");
182        ptln("      </tr>");
183        ptln("    </thead>");
184
185        if ($this->_user_total) {
186          ptln("    <tbody>");
187          foreach ($user_list as $user => $userinfo) {
188            extract($userinfo);
189            $groups = join(', ',$grps);
190            ptln("    <tr class=\"user_info\">");
191            ptln("      <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".$user."]\" ".$delete_disable." /></td>");
192            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>");
193            ptln("      <td>".hsc($user)."</td><td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>");
194            ptln("    </tr>");
195          }
196          ptln("    </tbody>");
197        }
198
199        ptln("    <tbody>");
200        ptln("      <tr><td colspan=\"6\" class=\"centeralign\">");
201        ptln("        <span class=\"medialeft\">");
202        ptln("          <input type=\"submit\" name=\"fn[delete]\" ".$delete_disable." class=\"button\" value=\"".$this->lang['delete_selected']."\" id=\"usrmgr__del\" />");
203        ptln("        </span>");
204        ptln("        <span class=\"mediaright\">");
205        ptln("          <input type=\"submit\" name=\"fn[start]\" ".$page_buttons['start']." class=\"button\" value=\"".$this->lang['start']."\" />");
206        ptln("          <input type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev']." class=\"button\" value=\"".$this->lang['prev']."\" />");
207        ptln("          <input type=\"submit\" name=\"fn[next]\" ".$page_buttons['next']." class=\"button\" value=\"".$this->lang['next']."\" />");
208        ptln("          <input type=\"submit\" name=\"fn[last]\" ".$page_buttons['last']." class=\"button\" value=\"".$this->lang['last']."\" />");
209        ptln("        </span>");
210        ptln("        <input type=\"submit\" name=\"fn[search][clear]\" class=\"button\" value=\"".$this->lang['clear']."\" />");
211        ptln("        <input type=\"hidden\" name=\"do\"    value=\"admin\" />");
212        ptln("        <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />");
213        ptln("      </td></tr>");
214        ptln("    </tbody>");
215        ptln("  </table>");
216
217        $this->_htmlFilterSettings(2);
218
219        ptln("</form>");
220        ptln("</div>");
221
222        $style = $this->_edit_user ? " class=\"edit_user\"" : "";
223
224        if ($this->_auth->canDo('addUser')) {
225          ptln("<div".$style.">");
226          print $this->locale_xhtml('add');
227          ptln("  <div class=\"level2\">");
228
229          $this->_htmlUserForm('add',null,4);
230
231          ptln("  </div>");
232          ptln("</div>");
233        }
234
235        if($this->_edit_user  && $this->_auth->canDo('UserMod')){
236          ptln("<div".$style." id=\"scroll__here\">");
237          print $this->locale_xhtml('edit');
238          ptln("  <div class=\"level2\">");
239
240          $this->_htmlUserForm('modify',$this->_edit_user,4);
241
242          ptln("  </div>");
243          ptln("</div>");
244        }
245        ptln("</div>");
246    }
247
248
249    /**
250     * @todo disable fields which the backend can't change
251     */
252    function _htmlUserForm($cmd,$user=null,$indent=0) {
253
254        if ($user) {
255          extract($this->_auth->getUserData($user));
256          $groups = join(',',$grps);
257        } else {
258          $user = $name = $mail = $groups = '';
259        }
260
261        ptln("<form action=\"".wl($ID)."\" method=\"post\">",$indent);
262        ptln("  <table class=\"inline\">",$indent);
263        ptln("    <thead>",$indent);
264        ptln("      <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>",$indent);
265        ptln("    </thead>",$indent);
266        ptln("    <tbody>",$indent);
267
268        $this->_htmlInputField($cmd."_userid",    "userid",    $this->lang["user_id"],    $user,  $this->_auth->canDo("modLogin"), $indent+6);
269        $this->_htmlInputField($cmd."_userpass",  "userpass",  $this->lang["user_pass"],  "",     $this->_auth->canDo("modPass"),  $indent+6);
270        $this->_htmlInputField($cmd."_username",  "username",  $this->lang["user_name"],  $name,  $this->_auth->canDo("modName"),  $indent+6);
271        $this->_htmlInputField($cmd."_usermail",  "usermail",  $this->lang["user_mail"],  $mail,  $this->_auth->canDo("modMail"),  $indent+6);
272        $this->_htmlInputField($cmd."_usergroups","usergroups",$this->lang["user_groups"],$groups,$this->_auth->canDo("modGroups"),$indent+6);
273
274        ptln("    </tbody>",$indent);
275        ptln("    <tbody>",$indent);
276        ptln("      <tr>",$indent);
277        ptln("        <td colspan=\"2\">",$indent);
278        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
279        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
280
281        // save current $user, we need this to access details if the name is changed
282        if ($user)
283          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
284
285        $this->_htmlFilterSettings($indent+10);
286
287        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
288        ptln("        </td>",$indent);
289        ptln("      </tr>",$indent);
290        ptln("    </tbody>",$indent);
291        ptln("  </table>",$indent);
292        ptln("</form>",$indent);
293    }
294
295    function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
296        $disabled = $cando ? "" : " disabled=\"disabled\"";
297        $class = $cando ? "" : " class=\"disabled\"";
298        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);
299    }
300
301    function _htmlFilter($key) {
302        if (empty($this->_filter)) return '';
303        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
304    }
305
306    function _htmlFilterSettings($indent=0) {
307
308        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
309
310        foreach ($this->_filter as $key => $filter) {
311          ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
312        }
313    }
314
315    function _addUser(){
316
317        if (!$this->_auth->canDo('addUser')) return false;
318
319        list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser();
320        if (empty($user)) return false;
321
322        return $this->_auth->createUser($user,$pass,$name,$mail,$grps);
323    }
324
325    /**
326     * Delete user
327     */
328    function _deleteUser(){
329
330        if (!$this->_auth->canDo('delUser')) return false;
331
332        $selected = $_REQUEST['delete'];
333        if (!is_array($selected) || empty($selected)) return false;
334        $selected = array_keys($selected);
335
336        $count = $this->_auth->deleteUsers($selected);
337        if ($count == count($selected)) {
338          $text = str_replace('%d', $count, $this->lang['delete_ok']);
339          msg("$text.", 1);
340        } else {
341          $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
342          $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
343          msg("$part1, $part2",-1);
344        }
345    }
346
347    /**
348     * Modify user
349     */
350    function _modifyUser(){
351        if (!$this->_auth->canDo('UserMod')) return false;
352
353        // get currently valid  user data
354        $olduser = cleanID(preg_replace('/.*:/','',$_REQUEST['userid_old']));
355        $oldinfo = $this->_auth->getUserData($olduser);
356
357        // get new user data subject to change
358        list($newuser,$newpass,$newname,$newmail,$newgrps) = $this->_retrieveUser();
359        if (empty($newuser)) return false;
360
361        $changes = array();
362        if ($newuser != $olduser) {
363
364          if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
365            msg($this->lang['update_fail'],-1);
366            return false;
367          }
368
369          // check if $newuser already exists
370          if ($this->_auth->getUserData($newuser)) {
371            msg(sprintf($this->lang['update_exists'],$newuser),-1);
372            $this->_edit_user = $olduser;
373          } else {
374            $changes['user'] = $newuser;
375          }
376        }
377
378        if (!empty($newpass) && $this->_auth->canDo('modPass'))
379          $changes['pass'] = $newpass;
380        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name'])
381          $changes['name'] = $newname;
382        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail'])
383          $changes['mail'] = $newmail;
384        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps'])
385          $changes['grps'] = $newgrps;
386
387    if ($this->_auth->modifyUser($olduser, $changes)) {
388          msg($this->lang['update_ok'],1);
389        } else {
390          msg($this->lang['update_fail'],-1);
391        }
392    }
393
394    /*
395     * retrieve & clean user data from the form
396     * return an array(user, password, full name, email, array(groups))
397     */
398    function _retrieveUser($clean=true) {
399
400        $user[0] = ($clean) ? cleanID(preg_replace('/.*:/','',$_REQUEST['userid'])) : $_REQUEST['userid'];
401        $user[1] = $_REQUEST['userpass'];
402        $user[2] = $_REQUEST['username'];
403        $user[3] = $_REQUEST['usermail'];
404        $user[4] = preg_split('/\s*,\s*/',$_REQUEST['usergroups'],-1,PREG_SPLIT_NO_EMPTY);
405
406        if (is_array($user[4]) && (count($user[4]) == 1) && (trim($user[4][0]) == '')) {
407            $user[4] = null;
408        }
409
410        return $user;
411    }
412
413    function _setFilter($op) {
414
415        $this->_filter = array();
416
417        if ($op == 'new') {
418          list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser(false);
419
420          if (!empty($user)) $this->_filter['user'] = $user;
421          if (!empty($name)) $this->_filter['name'] = $name;
422          if (!empty($mail)) $this->_filter['mail'] = $mail;
423          if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
424        }
425    }
426
427    function _retrieveFilter() {
428
429        $t_filter = $_REQUEST['filter'];
430        if (!is_array($t_filter)) return array();
431
432        // messy, but this way we ensure we aren't getting any additional crap from malicious users
433        $filter = array();
434
435        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
436        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
437        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
438        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
439
440        return $filter;
441    }
442
443    function _validatePagination() {
444
445        if ($this->_start >= $this->_user_total) {
446          $this->_start = $this->_user_total - $this->_pagesize;
447        }
448        if ($this->_start < 0) $this->_start = 0;
449
450        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
451    }
452
453    /*
454     *  return an array of strings to enable/disable pagination buttons
455     */
456    function _pagination() {
457
458        $disabled = 'disabled="disabled"';
459
460        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
461
462        if ($this->_user_total == -1) {
463          $buttons['last'] = $disabled;
464          $buttons['next'] = '';
465        } else {
466          $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
467        }
468
469        return $buttons;
470    }
471}
472