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