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