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