xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision 8e455cddd749f1ea627e47e5ff5b910b7443d561)
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_IMAGES')) define('DOKU_PLUGIN_IMAGES',DOKU_BASE.'lib/plugins/usermanager/images/');
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    protected $_auth = null;        // auth object
25    protected $_user_total = 0;     // number of registered users
26    protected $_filter = array();   // user selection filter(s)
27    protected $_start = 0;          // index of first user to be displayed
28    protected $_last = 0;           // index of the last user to be displayed
29    protected $_pagesize = 20;      // number of users to list on one page
30    protected $_edit_user = '';     // set to user selected for editing
31    protected $_edit_userdata = array();
32    protected $_disabled = '';      // if disabled set to explanatory string
33    protected $_import_failures = array();
34    protected $_lastdisabled = false; // set to true if last user is unknown and last button is hence buggy
35
36    /**
37     * Constructor
38     */
39    public function admin_plugin_usermanager(){
40        /** @var DokuWiki_Auth_Plugin $auth */
41        global $auth;
42
43        $this->setupLocale();
44
45        if (!isset($auth)) {
46            $this->_disabled = $this->lang['noauth'];
47        } else if (!$auth->canDo('getUsers')) {
48            $this->_disabled = $this->lang['nosupport'];
49        } else {
50
51            // we're good to go
52            $this->_auth = & $auth;
53
54        }
55
56        // attempt to retrieve any import failures from the session
57        if (!empty($_SESSION['import_failures'])){
58            $this->_import_failures = $_SESSION['import_failures'];
59        }
60    }
61
62    /**
63     * Return prompt for admin menu
64     *
65     * @param string $language
66     * @return string
67     */
68    public function getMenuText($language) {
69
70        if (!is_null($this->_auth))
71          return parent::getMenuText($language);
72
73        return $this->getLang('menu').' '.$this->_disabled;
74    }
75
76    /**
77     * return sort order for position in admin menu
78     *
79     * @return int
80     */
81    public function getMenuSort() {
82        return 2;
83    }
84
85    /**
86     * @return int current start value for pageination
87     */
88    public function getStart() {
89        return $this->_start;
90    }
91
92    /**
93     * @return int number of users per page
94     */
95    public function getPagesize() {
96        return $this->_pagesize;
97    }
98
99    /**
100     * @param boolean $lastdisabled
101     */
102    public function setLastdisabled($lastdisabled) {
103        $this->_lastdisabled = $lastdisabled;
104    }
105
106    /**
107     * Handle user request
108     *
109     * @return bool
110     */
111    public function handle() {
112        global $INPUT;
113        if (is_null($this->_auth)) return false;
114
115        // extract the command and any specific parameters
116        // submit button name is of the form - fn[cmd][param(s)]
117        $fn   = $INPUT->param('fn');
118
119        if (is_array($fn)) {
120            $cmd = key($fn);
121            $param = is_array($fn[$cmd]) ? key($fn[$cmd]) : null;
122        } else {
123            $cmd = $fn;
124            $param = null;
125        }
126
127        if ($cmd != "search") {
128            $this->_start = $INPUT->int('start', 0);
129            $this->_filter = $this->_retrieveFilter();
130        }
131
132        switch($cmd){
133            case "add"    : $this->_addUser(); break;
134            case "delete" : $this->_deleteUser(); break;
135            case "modify" : $this->_modifyUser(); break;
136            case "edit"   : $this->_editUser($param); break;
137            case "search" : $this->_setFilter($param);
138                            $this->_start = 0;
139                            break;
140            case "export" : $this->_export(); break;
141            case "import" : $this->_import(); break;
142            case "importfails" : $this->_downloadImportFailures(); break;
143        }
144
145        $this->_user_total = $this->_auth->canDo('getUserCount') ? $this->_auth->getUserCount($this->_filter) : -1;
146
147        // page handling
148        switch($cmd){
149            case 'start' : $this->_start = 0; break;
150            case 'prev'  : $this->_start -= $this->_pagesize; break;
151            case 'next'  : $this->_start += $this->_pagesize; break;
152            case 'last'  : $this->_start = $this->_user_total; break;
153        }
154        $this->_validatePagination();
155        return true;
156    }
157
158    /**
159     * Output appropriate html
160     *
161     * @return bool
162     */
163    public function html() {
164        global $ID;
165
166        if(is_null($this->_auth)) {
167            print $this->lang['badauth'];
168            return false;
169        }
170
171        $user_list = $this->_auth->retrieveUsers($this->_start, $this->_pagesize, $this->_filter);
172
173        $page_buttons = $this->_pagination();
174        $delete_disable = $this->_auth->canDo('delUser') ? '' : 'disabled="disabled"';
175
176        $editable = $this->_auth->canDo('UserMod');
177        $export_label = empty($this->_filter) ? $this->lang['export_all'] : $this->lang['export_filtered'];
178
179        print $this->locale_xhtml('intro');
180        print $this->locale_xhtml('list');
181
182        ptln("<div id=\"user__manager\">");
183        ptln("<div class=\"level2\">");
184
185        if ($this->_user_total > 0) {
186            ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>");
187        } else {
188            if($this->_user_total < 0) {
189                $allUserTotal = 0;
190            } else {
191                $allUserTotal = $this->_auth->getUserCount();
192            }
193            ptln("<p>".sprintf($this->lang['nonefound'], $allUserTotal)."</p>");
194        }
195        ptln("<form action=\"".wl($ID)."\" method=\"post\">");
196        formSecurityToken();
197        ptln("  <div class=\"table\">");
198        ptln("  <table class=\"inline\">");
199        ptln("    <thead>");
200        ptln("      <tr>");
201        ptln("        <th>&#160;</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>");
202        ptln("      </tr>");
203
204        ptln("      <tr>");
205        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>");
206        ptln("        <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>");
207        ptln("        <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>");
208        ptln("        <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>");
209        ptln("        <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>");
210        ptln("      </tr>");
211        ptln("    </thead>");
212
213        if ($this->_user_total) {
214            ptln("    <tbody>");
215            foreach ($user_list as $user => $userinfo) {
216                extract($userinfo);
217                /**
218                 * @var string $name
219                 * @var string $pass
220                 * @var string $mail
221                 * @var array  $grps
222                 */
223                $groups = join(', ',$grps);
224                ptln("    <tr class=\"user_info\">");
225                ptln("      <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".$user."]\" ".$delete_disable." /></td>");
226                if ($editable) {
227                    ptln("    <td><a href=\"".wl($ID,array('fn[edit]['.hsc($user).']' => 1,
228                                                           'do' => 'admin',
229                                                           'page' => 'usermanager',
230                                                           'sectok' => getSecurityToken())).
231                         "\" title=\"".$this->lang['edit_prompt']."\">".hsc($user)."</a></td>");
232                } else {
233                    ptln("    <td>".hsc($user)."</td>");
234                }
235                ptln("      <td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>");
236                ptln("    </tr>");
237            }
238            ptln("    </tbody>");
239        }
240
241        ptln("    <tbody>");
242        ptln("      <tr><td colspan=\"5\" class=\"centeralign\">");
243        ptln("        <span class=\"medialeft\">");
244        ptln("          <input type=\"submit\" name=\"fn[delete]\" ".$delete_disable." class=\"button\" value=\"".$this->lang['delete_selected']."\" id=\"usrmgr__del\" />");
245        ptln("        </span>");
246        ptln("        <span class=\"mediaright\">");
247        ptln("          <input type=\"submit\" name=\"fn[start]\" ".$page_buttons['start']." class=\"button\" value=\"".$this->lang['start']."\" />");
248        ptln("          <input type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev']." class=\"button\" value=\"".$this->lang['prev']."\" />");
249        ptln("          <input type=\"submit\" name=\"fn[next]\" ".$page_buttons['next']." class=\"button\" value=\"".$this->lang['next']."\" />");
250        ptln("          <input type=\"submit\" name=\"fn[last]\" ".$page_buttons['last']." class=\"button\" value=\"".$this->lang['last']."\" />");
251        ptln("        </span>");
252        if (!empty($this->_filter)) {
253            ptln("    <input type=\"submit\" name=\"fn[search][clear]\" class=\"button\" value=\"".$this->lang['clear']."\" />");
254        }
255        ptln("        <input type=\"submit\" name=\"fn[export]\" class=\"button\" value=\"".$export_label."\" />");
256        ptln("        <input type=\"hidden\" name=\"do\"    value=\"admin\" />");
257        ptln("        <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />");
258
259        $this->_htmlFilterSettings(2);
260
261        ptln("      </td></tr>");
262        ptln("    </tbody>");
263        ptln("  </table>");
264        ptln("  </div>");
265
266        ptln("</form>");
267        ptln("</div>");
268
269        $style = $this->_edit_user ? " class=\"edit_user\"" : "";
270
271        if ($this->_auth->canDo('addUser')) {
272            ptln("<div".$style.">");
273            print $this->locale_xhtml('add');
274            ptln("  <div class=\"level2\">");
275
276            $this->_htmlUserForm('add',null,array(),4);
277
278            ptln("  </div>");
279            ptln("</div>");
280        }
281
282        if($this->_edit_user  && $this->_auth->canDo('UserMod')){
283            ptln("<div".$style." id=\"scroll__here\">");
284            print $this->locale_xhtml('edit');
285            ptln("  <div class=\"level2\">");
286
287            $this->_htmlUserForm('modify',$this->_edit_user,$this->_edit_userdata,4);
288
289            ptln("  </div>");
290            ptln("</div>");
291        }
292
293        if ($this->_auth->canDo('addUser')) {
294            $this->_htmlImportForm();
295        }
296        ptln("</div>");
297        return true;
298    }
299
300    /**
301     * Display form to add or modify a user
302     *
303     * @param string $cmd 'add' or 'modify'
304     * @param string $user id of user
305     * @param array  $userdata array with name, mail, pass and grps
306     * @param int    $indent
307     */
308    protected function _htmlUserForm($cmd,$user='',$userdata=array(),$indent=0) {
309        global $conf;
310        global $ID;
311        global $lang;
312
313        $name = $mail = $groups = '';
314        $notes = array();
315
316        if ($user) {
317            extract($userdata);
318            if (!empty($grps)) $groups = join(',',$grps);
319        } else {
320            $notes[] = sprintf($this->lang['note_group'],$conf['defaultgroup']);
321        }
322
323        ptln("<form action=\"".wl($ID)."\" method=\"post\">",$indent);
324        formSecurityToken();
325        ptln("  <div class=\"table\">",$indent);
326        ptln("  <table class=\"inline\">",$indent);
327        ptln("    <thead>",$indent);
328        ptln("      <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>",$indent);
329        ptln("    </thead>",$indent);
330        ptln("    <tbody>",$indent);
331
332        $this->_htmlInputField($cmd."_userid",    "userid",    $this->lang["user_id"],    $user,  $this->_auth->canDo("modLogin"), $indent+6);
333        $this->_htmlInputField($cmd."_userpass",  "userpass",  $this->lang["user_pass"],  "",     $this->_auth->canDo("modPass"),  $indent+6);
334        $this->_htmlInputField($cmd."_userpass2", "userpass2", $lang["passchk"],          "",     $this->_auth->canDo("modPass"),  $indent+6);
335        $this->_htmlInputField($cmd."_username",  "username",  $this->lang["user_name"],  $name,  $this->_auth->canDo("modName"),  $indent+6);
336        $this->_htmlInputField($cmd."_usermail",  "usermail",  $this->lang["user_mail"],  $mail,  $this->_auth->canDo("modMail"),  $indent+6);
337        $this->_htmlInputField($cmd."_usergroups","usergroups",$this->lang["user_groups"],$groups,$this->_auth->canDo("modGroups"),$indent+6);
338
339        if ($this->_auth->canDo("modPass")) {
340            if ($cmd == 'add') {
341                $notes[] = $this->lang['note_pass'];
342            }
343            if ($user) {
344                $notes[] = $this->lang['note_notify'];
345            }
346
347            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);
348        }
349
350        ptln("    </tbody>",$indent);
351        ptln("    <tbody>",$indent);
352        ptln("      <tr>",$indent);
353        ptln("        <td colspan=\"2\">",$indent);
354        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
355        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
356
357        // save current $user, we need this to access details if the name is changed
358        if ($user)
359          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
360
361        $this->_htmlFilterSettings($indent+10);
362
363        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
364        ptln("        </td>",$indent);
365        ptln("      </tr>",$indent);
366        ptln("    </tbody>",$indent);
367        ptln("  </table>",$indent);
368
369        if ($notes) {
370            ptln("    <ul class=\"notes\">");
371            foreach ($notes as $note) {
372                ptln("      <li><span class=\"li\">".$note."</span></li>",$indent);
373            }
374            ptln("    </ul>");
375        }
376        ptln("  </div>",$indent);
377        ptln("</form>",$indent);
378    }
379
380    /**
381     * Prints a inputfield
382     *
383     * @param string $id
384     * @param string $name
385     * @param string $label
386     * @param string $value
387     * @param bool   $cando whether auth backend is capable to do this action
388     * @param int $indent
389     */
390    protected function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
391        $class = $cando ? '' : ' class="disabled"';
392        echo str_pad('',$indent);
393
394        if($name == 'userpass' || $name == 'userpass2'){
395            $fieldtype = 'password';
396            $autocomp  = 'autocomplete="off"';
397        }elseif($name == 'usermail'){
398            $fieldtype = 'email';
399            $autocomp  = '';
400        }else{
401            $fieldtype = 'text';
402            $autocomp  = '';
403        }
404
405        echo "<tr $class>";
406        echo "<td><label for=\"$id\" >$label: </label></td>";
407        echo "<td>";
408        if($cando){
409            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" $autocomp />";
410        }else{
411            echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
412            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />";
413        }
414        echo "</td>";
415        echo "</tr>";
416    }
417
418    /**
419     * Returns htmlescaped filter value
420     *
421     * @param string $key name of search field
422     * @return string html escaped value
423     */
424    protected function _htmlFilter($key) {
425        if (empty($this->_filter)) return '';
426        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
427    }
428
429    /**
430     * Print hidden inputs with the current filter values
431     *
432     * @param int $indent
433     */
434    protected function _htmlFilterSettings($indent=0) {
435
436        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
437
438        foreach ($this->_filter as $key => $filter) {
439            ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
440        }
441    }
442
443    /**
444     * Print import form and summary of previous import
445     *
446     * @param int $indent
447     */
448    protected function _htmlImportForm($indent=0) {
449        global $ID;
450
451        $failure_download_link = wl($ID,array('do'=>'admin','page'=>'usermanager','fn[importfails]'=>1));
452
453        ptln('<div class="level2 import_users">',$indent);
454        print $this->locale_xhtml('import');
455        ptln('  <form action="'.wl($ID).'" method="post" enctype="multipart/form-data">',$indent);
456        formSecurityToken();
457        ptln('    <label>'.$this->lang['import_userlistcsv'].'<input type="file" name="import" /></label>',$indent);
458        ptln('    <input type="submit" name="fn[import]" value="'.$this->lang['import'].'" />',$indent);
459        ptln('    <input type="hidden" name="do"    value="admin" />',$indent);
460        ptln('    <input type="hidden" name="page"  value="usermanager" />',$indent);
461
462        $this->_htmlFilterSettings($indent+4);
463        ptln('  </form>',$indent);
464        ptln('</div>');
465
466        // list failures from the previous import
467        if ($this->_import_failures) {
468            $digits = strlen(count($this->_import_failures));
469            ptln('<div class="level3 import_failures">',$indent);
470            ptln('  <h3>'.$this->lang['import_header'].'</h3>');
471            ptln('  <table class="import_failures">',$indent);
472            ptln('    <thead>',$indent);
473            ptln('      <tr>',$indent);
474            ptln('        <th class="line">'.$this->lang['line'].'</th>',$indent);
475            ptln('        <th class="error">'.$this->lang['error'].'</th>',$indent);
476            ptln('        <th class="userid">'.$this->lang['user_id'].'</th>',$indent);
477            ptln('        <th class="username">'.$this->lang['user_name'].'</th>',$indent);
478            ptln('        <th class="usermail">'.$this->lang['user_mail'].'</th>',$indent);
479            ptln('        <th class="usergroups">'.$this->lang['user_groups'].'</th>',$indent);
480            ptln('      </tr>',$indent);
481            ptln('    </thead>',$indent);
482            ptln('    <tbody>',$indent);
483            foreach ($this->_import_failures as $line => $failure) {
484                ptln('      <tr>',$indent);
485                ptln('        <td class="lineno"> '.sprintf('%0'.$digits.'d',$line).' </td>',$indent);
486                ptln('        <td class="error">' .$failure['error'].' </td>', $indent);
487                ptln('        <td class="field userid"> '.hsc($failure['user'][0]).' </td>',$indent);
488                ptln('        <td class="field username"> '.hsc($failure['user'][2]).' </td>',$indent);
489                ptln('        <td class="field usermail"> '.hsc($failure['user'][3]).' </td>',$indent);
490                ptln('        <td class="field usergroups"> '.hsc($failure['user'][4]).' </td>',$indent);
491                ptln('      </tr>',$indent);
492            }
493            ptln('    </tbody>',$indent);
494            ptln('  </table>',$indent);
495            ptln('  <p><a href="'.$failure_download_link.'">'.$this->lang['import_downloadfailures'].'</a></p>');
496            ptln('</div>');
497        }
498
499    }
500
501    /**
502     * Add an user to auth backend
503     *
504     * @return bool whether succesful
505     */
506    protected function _addUser(){
507        global $INPUT;
508        if (!checkSecurityToken()) return false;
509        if (!$this->_auth->canDo('addUser')) return false;
510
511        list($user,$pass,$name,$mail,$grps,$passconfirm) = $this->_retrieveUser();
512        if (empty($user)) return false;
513
514        if ($this->_auth->canDo('modPass')){
515            if (empty($pass)){
516                if($INPUT->has('usernotify')){
517                    $pass = auth_pwgen($user);
518                } else {
519                    msg($this->lang['add_fail'], -1);
520                    return false;
521                }
522            } else {
523                if (!$this->_verifyPassword($pass,$passconfirm)) {
524                    return false;
525                }
526            }
527        } else {
528            if (!empty($pass)){
529                msg($this->lang['add_fail'], -1);
530                return false;
531            }
532        }
533
534        if ($this->_auth->canDo('modName')){
535            if (empty($name)){
536                msg($this->lang['add_fail'], -1);
537                return false;
538            }
539        } else {
540            if (!empty($name)){
541                return false;
542            }
543        }
544
545        if ($this->_auth->canDo('modMail')){
546            if (empty($mail)){
547                msg($this->lang['add_fail'], -1);
548                return false;
549            }
550        } else {
551            if (!empty($mail)){
552                return false;
553            }
554        }
555
556        if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) {
557
558            msg($this->lang['add_ok'], 1);
559
560            if ($INPUT->has('usernotify') && $pass) {
561                $this->_notifyUser($user,$pass);
562            }
563        } else {
564            msg($this->lang['add_fail'], -1);
565        }
566
567        return $ok;
568    }
569
570    /**
571     * Delete user from auth backend
572     *
573     * @return bool whether succesful
574     */
575    protected function _deleteUser(){
576        global $conf, $INPUT;
577
578        if (!checkSecurityToken()) return false;
579        if (!$this->_auth->canDo('delUser')) return false;
580
581        $selected = $INPUT->arr('delete');
582        if (empty($selected)) return false;
583        $selected = array_keys($selected);
584
585        if(in_array($_SERVER['REMOTE_USER'], $selected)) {
586            msg("You can't delete yourself!", -1);
587            return false;
588        }
589
590        $count = $this->_auth->triggerUserMod('delete', array($selected));
591        if ($count == count($selected)) {
592            $text = str_replace('%d', $count, $this->lang['delete_ok']);
593            msg("$text.", 1);
594        } else {
595            $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
596            $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
597            msg("$part1, $part2",-1);
598        }
599
600        // invalidate all sessions
601        io_saveFile($conf['cachedir'].'/sessionpurge',time());
602
603        return true;
604    }
605
606    /**
607     * Edit user (a user has been selected for editing)
608     *
609     * @param string $param id of the user
610     * @return bool whether succesful
611     */
612    protected function _editUser($param) {
613        if (!checkSecurityToken()) return false;
614        if (!$this->_auth->canDo('UserMod')) return false;
615        $user = $this->_auth->cleanUser(preg_replace('/.*[:\/]/','',$param));
616        $userdata = $this->_auth->getUserData($user);
617
618        // no user found?
619        if (!$userdata) {
620            msg($this->lang['edit_usermissing'],-1);
621            return false;
622        }
623
624        $this->_edit_user = $user;
625        $this->_edit_userdata = $userdata;
626
627        return true;
628    }
629
630    /**
631     * Modify user in the auth backend (modified user data has been recieved)
632     *
633     * @return bool whether succesful
634     */
635    protected function _modifyUser(){
636        global $conf, $INPUT;
637
638        if (!checkSecurityToken()) return false;
639        if (!$this->_auth->canDo('UserMod')) return false;
640
641        // get currently valid  user data
642        $olduser = $this->_auth->cleanUser(preg_replace('/.*[:\/]/','',$INPUT->str('userid_old')));
643        $oldinfo = $this->_auth->getUserData($olduser);
644
645        // get new user data subject to change
646        list($newuser,$newpass,$newname,$newmail,$newgrps,$passconfirm) = $this->_retrieveUser();
647        if (empty($newuser)) return false;
648
649        $changes = array();
650        if ($newuser != $olduser) {
651
652            if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
653                msg($this->lang['update_fail'],-1);
654                return false;
655            }
656
657            // check if $newuser already exists
658            if ($this->_auth->getUserData($newuser)) {
659                msg(sprintf($this->lang['update_exists'],$newuser),-1);
660                $re_edit = true;
661            } else {
662                $changes['user'] = $newuser;
663            }
664        }
665        if ($this->_auth->canDo('modPass')) {
666            if ($newpass || $passconfirm) {
667                if ($this->_verifyPassword($newpass,$passconfirm)) {
668                    $changes['pass'] = $newpass;
669                } else {
670                    return false;
671                }
672            } else {
673                // no new password supplied, check if we need to generate one (or it stays unchanged)
674                if ($INPUT->has('usernotify')) {
675                    $changes['pass'] = auth_pwgen($olduser);
676                }
677            }
678        }
679
680        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name']) {
681            $changes['name'] = $newname;
682        }
683        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail']) {
684            $changes['mail'] = $newmail;
685        }
686        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps']) {
687            $changes['grps'] = $newgrps;
688        }
689
690        if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) {
691            msg($this->lang['update_ok'],1);
692
693            if ($INPUT->has('usernotify') && !empty($changes['pass'])) {
694                $notify = empty($changes['user']) ? $olduser : $newuser;
695                $this->_notifyUser($notify,$changes['pass']);
696            }
697
698            // invalidate all sessions
699            io_saveFile($conf['cachedir'].'/sessionpurge',time());
700
701        } else {
702            msg($this->lang['update_fail'],-1);
703        }
704
705        if (!empty($re_edit)) {
706            $this->_editUser($olduser);
707        }
708
709        return $ok;
710    }
711
712    /**
713     * Send password change notification email
714     *
715     * @param string $user         id of user
716     * @param string $password     plain text
717     * @param bool   $status_alert whether status alert should be shown
718     * @return bool whether succesful
719     */
720    protected function _notifyUser($user, $password, $status_alert=true) {
721
722        if ($sent = auth_sendPassword($user,$password)) {
723            if ($status_alert) {
724                msg($this->lang['notify_ok'], 1);
725            }
726        } else {
727            if ($status_alert) {
728                msg($this->lang['notify_fail'], -1);
729            }
730        }
731
732        return $sent;
733    }
734
735    /**
736     * Verify password meets minimum requirements
737     * :TODO: extend to support password strength
738     *
739     * @param string  $password   candidate string for new password
740     * @param string  $confirm    repeated password for confirmation
741     * @return bool   true if meets requirements, false otherwise
742     */
743    protected function _verifyPassword($password, $confirm) {
744        global $lang;
745
746        if (empty($password) && empty($confirm)) {
747            return false;
748        }
749
750        if ($password !== $confirm) {
751            msg($lang['regbadpass'], -1);
752            return false;
753        }
754
755        // :TODO: test password for required strength
756
757        // if we make it this far the password is good
758        return true;
759    }
760
761    /**
762     * Retrieve & clean user data from the form
763     *
764     * @param bool $clean whether the cleanUser method of the authentication backend is applied
765     * @return array (user, password, full name, email, array(groups))
766     */
767    protected function _retrieveUser($clean=true) {
768        /** @var DokuWiki_Auth_Plugin $auth */
769        global $auth;
770        global $INPUT;
771
772        $user = array();
773        $user[0] = ($clean) ? $auth->cleanUser($INPUT->str('userid')) : $INPUT->str('userid');
774        $user[1] = $INPUT->str('userpass');
775        $user[2] = $INPUT->str('username');
776        $user[3] = $INPUT->str('usermail');
777        $user[4] = explode(',',$INPUT->str('usergroups'));
778        $user[5] = $INPUT->str('userpass2');                // repeated password for confirmation
779
780        $user[4] = array_map('trim',$user[4]);
781        if($clean) $user[4] = array_map(array($auth,'cleanGroup'),$user[4]);
782        $user[4] = array_filter($user[4]);
783        $user[4] = array_unique($user[4]);
784        if(!count($user[4])) $user[4] = null;
785
786        return $user;
787    }
788
789    /**
790     * Set the filter with the current search terms or clear the filter
791     *
792     * @param string $op 'new' or 'clear'
793     */
794    protected function _setFilter($op) {
795
796        $this->_filter = array();
797
798        if ($op == 'new') {
799            list($user,/* $pass */,$name,$mail,$grps) = $this->_retrieveUser(false);
800
801            if (!empty($user)) $this->_filter['user'] = $user;
802            if (!empty($name)) $this->_filter['name'] = $name;
803            if (!empty($mail)) $this->_filter['mail'] = $mail;
804            if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
805        }
806    }
807
808    /**
809     * Get the current search terms
810     *
811     * @return array
812     */
813    protected function _retrieveFilter() {
814        global $INPUT;
815
816        $t_filter = $INPUT->arr('filter');
817
818        // messy, but this way we ensure we aren't getting any additional crap from malicious users
819        $filter = array();
820
821        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
822        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
823        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
824        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
825
826        return $filter;
827    }
828
829    /**
830     * Validate and improve the pagination values
831     */
832    protected function _validatePagination() {
833
834        if ($this->_start >= $this->_user_total) {
835            $this->_start = $this->_user_total - $this->_pagesize;
836        }
837        if ($this->_start < 0) $this->_start = 0;
838
839        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
840    }
841
842    /**
843     * Return an array of strings to enable/disable pagination buttons
844     *
845     * @return array with enable/disable attributes
846     */
847    protected function _pagination() {
848
849        $disabled = 'disabled="disabled"';
850
851        $buttons = array();
852        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
853
854        if ($this->_user_total == -1) {
855            $buttons['last'] = $disabled;
856            $buttons['next'] = '';
857        } else {
858            $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
859        }
860
861        if ($this->_lastdisabled) {
862            $buttons['last'] = $disabled;
863        }
864
865        return $buttons;
866    }
867
868    /**
869     * Export a list of users in csv format using the current filter criteria
870     */
871    protected function _export() {
872        // list of users for export - based on current filter criteria
873        $user_list = $this->_auth->retrieveUsers(0, 0, $this->_filter);
874        $column_headings = array(
875            $this->lang["user_id"],
876            $this->lang["user_name"],
877            $this->lang["user_mail"],
878            $this->lang["user_groups"]
879        );
880
881        // ==============================================================================================
882        // GENERATE OUTPUT
883        // normal headers for downloading...
884        header('Content-type: text/csv;charset=utf-8');
885        header('Content-Disposition: attachment; filename="wikiusers.csv"');
886#       // for debugging assistance, send as text plain to the browser
887#       header('Content-type: text/plain;charset=utf-8');
888
889        // output the csv
890        $fd = fopen('php://output','w');
891        fputcsv($fd, $column_headings);
892        foreach ($user_list as $user => $info) {
893            $line = array($user, $info['name'], $info['mail'], join(',',$info['grps']));
894            fputcsv($fd, $line);
895        }
896        fclose($fd);
897        if (defined('DOKU_UNITTEST')){ return; }
898
899        die;
900    }
901
902    /**
903     * Import a file of users in csv format
904     *
905     * csv file should have 4 columns, user_id, full name, email, groups (comma separated)
906     *
907     * @return bool whether successful
908     */
909    protected function _import() {
910        // check we are allowed to add users
911        if (!checkSecurityToken()) return false;
912        if (!$this->_auth->canDo('addUser')) return false;
913
914        // check file uploaded ok.
915        if (empty($_FILES['import']['size']) || !empty($_FILES['import']['error']) && $this->_isUploadedFile($_FILES['import']['tmp_name'])) {
916            msg($this->lang['import_error_upload'],-1);
917            return false;
918        }
919        // retrieve users from the file
920        $this->_import_failures = array();
921        $import_success_count = 0;
922        $import_fail_count = 0;
923        $line = 0;
924        $fd = fopen($_FILES['import']['tmp_name'],'r');
925        if ($fd) {
926            while($csv = fgets($fd)){
927                if (!utf8_check($csv)) {
928                    $csv = utf8_encode($csv);
929                }
930                $raw = $this->_getcsv($csv);
931                $error = '';                        // clean out any errors from the previous line
932                // data checks...
933                if (1 == ++$line) {
934                    if ($raw[0] == 'user_id' || $raw[0] == $this->lang['user_id']) continue;    // skip headers
935                }
936                if (count($raw) < 4) {                                        // need at least four fields
937                    $import_fail_count++;
938                    $error = sprintf($this->lang['import_error_fields'], count($raw));
939                    $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
940                    continue;
941                }
942                array_splice($raw,1,0,auth_pwgen());                          // splice in a generated password
943                $clean = $this->_cleanImportUser($raw, $error);
944                if ($clean && $this->_addImportUser($clean, $error)) {
945                    $sent = $this->_notifyUser($clean[0],$clean[1],false);
946                    if (!$sent){
947                        msg(sprintf($this->lang['import_notify_fail'],$clean[0],$clean[3]),-1);
948                    }
949                    $import_success_count++;
950                } else {
951                    $import_fail_count++;
952                    array_splice($raw, 1, 1);                                  // remove the spliced in password
953                    $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
954                }
955            }
956            msg(sprintf($this->lang['import_success_count'], ($import_success_count+$import_fail_count), $import_success_count),($import_success_count ? 1 : -1));
957            if ($import_fail_count) {
958                msg(sprintf($this->lang['import_failure_count'], $import_fail_count),-1);
959            }
960        } else {
961            msg($this->lang['import_error_readfail'],-1);
962        }
963
964        // save import failures into the session
965        if (!headers_sent()) {
966            session_start();
967            $_SESSION['import_failures'] = $this->_import_failures;
968            session_write_close();
969        }
970        return true;
971    }
972
973    /**
974     * Returns cleaned user data
975     *
976     * @param array $candidate raw values of line from input file
977     * @param string $error
978     * @return array|false cleaned data or false
979     */
980    protected function _cleanImportUser($candidate, & $error){
981        global $INPUT;
982
983        // kludgy ....
984        $INPUT->set('userid', $candidate[0]);
985        $INPUT->set('userpass', $candidate[1]);
986        $INPUT->set('username', $candidate[2]);
987        $INPUT->set('usermail', $candidate[3]);
988        $INPUT->set('usergroups', $candidate[4]);
989
990        $cleaned = $this->_retrieveUser();
991        list($user,/* $pass */,$name,$mail,/* $grps */) = $cleaned;
992        if (empty($user)) {
993            $error = $this->lang['import_error_baduserid'];
994            return false;
995        }
996
997        // no need to check password, handled elsewhere
998
999        if (!($this->_auth->canDo('modName') xor empty($name))){
1000            $error = $this->lang['import_error_badname'];
1001            return false;
1002        }
1003
1004        if ($this->_auth->canDo('modMail')) {
1005            if (empty($mail) || !mail_isvalid($mail)) {
1006                $error = $this->lang['import_error_badmail'];
1007                return false;
1008            }
1009        } else {
1010            if (!empty($mail)) {
1011                $error = $this->lang['import_error_badmail'];
1012                return false;
1013            }
1014        }
1015
1016        return $cleaned;
1017    }
1018
1019    /**
1020     * Adds imported user to auth backend
1021     *
1022     * Required a check of canDo('addUser') before
1023     *
1024     * @param array  $user   data of user
1025     * @param string &$error reference catched error message
1026     * @return bool whether successful
1027     */
1028    protected function _addImportUser($user, & $error){
1029        if (!$this->_auth->triggerUserMod('create', $user)) {
1030            $error = $this->lang['import_error_create'];
1031            return false;
1032        }
1033
1034        return true;
1035    }
1036
1037    /**
1038     * Downloads failures as csv file
1039     */
1040    protected function _downloadImportFailures(){
1041
1042        // ==============================================================================================
1043        // GENERATE OUTPUT
1044        // normal headers for downloading...
1045        header('Content-type: text/csv;charset=utf-8');
1046        header('Content-Disposition: attachment; filename="importfails.csv"');
1047#       // for debugging assistance, send as text plain to the browser
1048#       header('Content-type: text/plain;charset=utf-8');
1049
1050        // output the csv
1051        $fd = fopen('php://output','w');
1052        foreach ($this->_import_failures as $fail) {
1053            fputs($fd, $fail['orig']);
1054        }
1055        fclose($fd);
1056        die;
1057    }
1058
1059    /**
1060     * wrapper for is_uploaded_file to facilitate overriding by test suite
1061     *
1062     * @param string $file filename
1063     * @return bool
1064     */
1065    protected function _isUploadedFile($file) {
1066        return is_uploaded_file($file);
1067    }
1068
1069    /**
1070     * wrapper for str_getcsv() to simplify maintaining compatibility with php 5.2
1071     *
1072     * @deprecated    remove when dokuwiki php requirement increases to 5.3+
1073     *                also associated unit test & mock access method
1074     *
1075     * @param string $csv string to parse
1076     * @return array
1077     */
1078    protected function _getcsv($csv) {
1079        return function_exists('str_getcsv') ? str_getcsv($csv) : $this->str_getcsv($csv);
1080    }
1081
1082    /**
1083     * replacement str_getcsv() function for php < 5.3
1084     * loosely based on www.php.net/str_getcsv#88311
1085     *
1086     * @deprecated    remove when dokuwiki php requirement increases to 5.3+
1087     *
1088     * @param string $str string to parse
1089     * @return array
1090     */
1091    protected function str_getcsv($str) {
1092        $fp = fopen("php://temp/maxmemory:1048576", 'r+');    // 1MiB
1093        fputs($fp, $str);
1094        rewind($fp);
1095
1096        $data = fgetcsv($fp);
1097
1098        fclose($fp);
1099        return $data;
1100    }
1101}
1102