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