xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision e12412a22fc56a88b5c40cfc0d15a718dbba425e)
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    var $_auth = null;        // auth object
25    var $_user_total = 0;     // number of registered users
26    var $_filter = array();   // user selection filter(s)
27    var $_start = 0;          // index of first user to be displayed
28    var $_last = 0;           // index of the last user to be displayed
29    var $_pagesize = 20;      // number of users to list on one page
30    var $_edit_user = '';     // set to user selected for editing
31    var $_edit_userdata = array();
32    var $_disabled = '';      // if disabled set to explanatory string
33    var $_import_failures = array();
34
35    /**
36     * Constructor
37     */
38    function admin_plugin_usermanager(){
39        global $auth;
40
41        $this->setupLocale();
42
43        if (!isset($auth)) {
44            $this->disabled = $this->lang['noauth'];
45        } else if (!$auth->canDo('getUsers')) {
46            $this->disabled = $this->lang['nosupport'];
47        } else {
48
49            // we're good to go
50            $this->_auth = & $auth;
51
52        }
53
54        // attempt to retrieve any import failures from the session
55        if ($_SESSION['import_failures']){
56            $this->_import_failures = $_SESSION['import_failures'];
57        }
58    }
59
60     /**
61      * return prompt for admin menu
62      */
63    function getMenuText($language) {
64
65        if (!is_null($this->_auth))
66          return parent::getMenuText($language);
67
68        return $this->getLang('menu').' '.$this->disabled;
69    }
70
71    /**
72     * return sort order for position in admin menu
73     */
74    function getMenuSort() {
75        return 2;
76    }
77
78    /**
79     * handle user request
80     */
81    function handle() {
82        global $INPUT;
83        if (is_null($this->_auth)) return false;
84
85        // extract the command and any specific parameters
86        // submit button name is of the form - fn[cmd][param(s)]
87        $fn   = $INPUT->param('fn');
88
89        if (is_array($fn)) {
90            $cmd = key($fn);
91            $param = is_array($fn[$cmd]) ? key($fn[$cmd]) : null;
92        } else {
93            $cmd = $fn;
94            $param = null;
95        }
96
97        if ($cmd != "search") {
98            $this->_start = $INPUT->int('start', 0);
99            $this->_filter = $this->_retrieveFilter();
100        }
101
102        switch($cmd){
103            case "add"    : $this->_addUser(); break;
104            case "delete" : $this->_deleteUser(); break;
105            case "modify" : $this->_modifyUser(); break;
106            case "edit"   : $this->_editUser($param); break;
107            case "search" : $this->_setFilter($param);
108                            $this->_start = 0;
109                            break;
110            case "export" : $this->_export(); break;
111            case "import" : $this->_import(); break;
112            case "importfails" : $this->_downloadImportFailures(); break;
113        }
114
115        $this->_user_total = $this->_auth->canDo('getUserCount') ? $this->_auth->getUserCount($this->_filter) : -1;
116
117        // page handling
118        switch($cmd){
119            case 'start' : $this->_start = 0; break;
120            case 'prev'  : $this->_start -= $this->_pagesize; break;
121            case 'next'  : $this->_start += $this->_pagesize; break;
122            case 'last'  : $this->_start = $this->_user_total; break;
123        }
124        $this->_validatePagination();
125    }
126
127    /**
128     * output appropriate html
129     */
130    function html() {
131        global $ID;
132
133        if(is_null($this->_auth)) {
134            print $this->lang['badauth'];
135            return false;
136        }
137
138        $user_list = $this->_auth->retrieveUsers($this->_start, $this->_pagesize, $this->_filter);
139        $users = array_keys($user_list);
140
141        $page_buttons = $this->_pagination();
142        $delete_disable = $this->_auth->canDo('delUser') ? '' : 'disabled="disabled"';
143
144        $editable = $this->_auth->canDo('UserMod');
145        $export_label = empty($this->_filter) ? $this->lang['export_all'] : $this->lang[export_filtered];
146
147        print $this->locale_xhtml('intro');
148        print $this->locale_xhtml('list');
149
150        ptln("<div id=\"user__manager\">");
151        ptln("<div class=\"level2\">");
152
153        if ($this->_user_total > 0) {
154            ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>");
155        } else {
156            ptln("<p>".sprintf($this->lang['nonefound'],$this->_auth->getUserCount())."</p>");
157        }
158        ptln("<form action=\"".wl($ID)."\" method=\"post\">");
159        formSecurityToken();
160        ptln("  <div class=\"table\">");
161        ptln("  <table class=\"inline\">");
162        ptln("    <thead>");
163        ptln("      <tr>");
164        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>");
165        ptln("      </tr>");
166
167        ptln("      <tr>");
168        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>");
169        ptln("        <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>");
170        ptln("        <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>");
171        ptln("        <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>");
172        ptln("        <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>");
173        ptln("      </tr>");
174        ptln("    </thead>");
175
176        if ($this->_user_total) {
177            ptln("    <tbody>");
178            foreach ($user_list as $user => $userinfo) {
179                extract($userinfo);
180                $groups = join(', ',$grps);
181                ptln("    <tr class=\"user_info\">");
182                ptln("      <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".$user."]\" ".$delete_disable." /></td>");
183                if ($editable) {
184                    ptln("    <td><a href=\"".wl($ID,array('fn[edit]['.hsc($user).']' => 1,
185                                                           'do' => 'admin',
186                                                           'page' => 'usermanager',
187                                                           'sectok' => getSecurityToken())).
188                         "\" title=\"".$this->lang['edit_prompt']."\">".hsc($user)."</a></td>");
189                } else {
190                    ptln("    <td>".hsc($user)."</td>");
191                }
192                ptln("      <td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>");
193                ptln("    </tr>");
194            }
195            ptln("    </tbody>");
196        }
197
198        ptln("    <tbody>");
199        ptln("      <tr><td colspan=\"5\" class=\"centeralign\">");
200        ptln("        <span class=\"medialeft\">");
201        ptln("          <input type=\"submit\" name=\"fn[delete]\" ".$delete_disable." class=\"button\" value=\"".$this->lang['delete_selected']."\" id=\"usrmgr__del\" />");
202        ptln("        </span>");
203        ptln("        <span class=\"mediaright\">");
204        ptln("          <input type=\"submit\" name=\"fn[start]\" ".$page_buttons['start']." class=\"button\" value=\"".$this->lang['start']."\" />");
205        ptln("          <input type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev']." class=\"button\" value=\"".$this->lang['prev']."\" />");
206        ptln("          <input type=\"submit\" name=\"fn[next]\" ".$page_buttons['next']." class=\"button\" value=\"".$this->lang['next']."\" />");
207        ptln("          <input type=\"submit\" name=\"fn[last]\" ".$page_buttons['last']." class=\"button\" value=\"".$this->lang['last']."\" />");
208        ptln("        </span>");
209        if (!empty($this->_filter)) {
210            ptln("    <input type=\"submit\" name=\"fn[search][clear]\" class=\"button\" value=\"".$this->lang['clear']."\" />");
211        }
212        ptln("        <input type=\"submit\" name=\"fn[export]\" class=\"button\" value=\"".$export_label."\" />");
213        ptln("        <input type=\"hidden\" name=\"do\"    value=\"admin\" />");
214        ptln("        <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />");
215
216        $this->_htmlFilterSettings(2);
217
218        ptln("      </td></tr>");
219        ptln("    </tbody>");
220        ptln("  </table>");
221        ptln("  </div>");
222
223        ptln("</form>");
224        ptln("</div>");
225
226        $style = $this->_edit_user ? " class=\"edit_user\"" : "";
227
228        if ($this->_auth->canDo('addUser')) {
229            ptln("<div".$style.">");
230            print $this->locale_xhtml('add');
231            ptln("  <div class=\"level2\">");
232
233            $this->_htmlUserForm('add',null,array(),4);
234
235            ptln("  </div>");
236            ptln("</div>");
237        }
238
239        if($this->_edit_user  && $this->_auth->canDo('UserMod')){
240            ptln("<div".$style." id=\"scroll__here\">");
241            print $this->locale_xhtml('edit');
242            ptln("  <div class=\"level2\">");
243
244            $this->_htmlUserForm('modify',$this->_edit_user,$this->_edit_userdata,4);
245
246            ptln("  </div>");
247            ptln("</div>");
248        }
249
250        if ($this->_auth->canDo('addUser')) {
251            $this->_htmlImportForm();
252        }
253        ptln("</div>");
254    }
255
256
257    /**
258     * @todo disable fields which the backend can't change
259     */
260    function _htmlUserForm($cmd,$user='',$userdata=array(),$indent=0) {
261        global $conf;
262        global $ID;
263
264        $name = $mail = $groups = '';
265        $notes = array();
266
267        if ($user) {
268            extract($userdata);
269            if (!empty($grps)) $groups = join(',',$grps);
270        } else {
271            $notes[] = sprintf($this->lang['note_group'],$conf['defaultgroup']);
272        }
273
274        ptln("<form action=\"".wl($ID)."\" method=\"post\">",$indent);
275        formSecurityToken();
276        ptln("  <div class=\"table\">",$indent);
277        ptln("  <table class=\"inline\">",$indent);
278        ptln("    <thead>",$indent);
279        ptln("      <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>",$indent);
280        ptln("    </thead>",$indent);
281        ptln("    <tbody>",$indent);
282
283        $this->_htmlInputField($cmd."_userid",    "userid",    $this->lang["user_id"],    $user,  $this->_auth->canDo("modLogin"), $indent+6);
284        $this->_htmlInputField($cmd."_userpass",  "userpass",  $this->lang["user_pass"],  "",     $this->_auth->canDo("modPass"),  $indent+6);
285        $this->_htmlInputField($cmd."_username",  "username",  $this->lang["user_name"],  $name,  $this->_auth->canDo("modName"),  $indent+6);
286        $this->_htmlInputField($cmd."_usermail",  "usermail",  $this->lang["user_mail"],  $mail,  $this->_auth->canDo("modMail"),  $indent+6);
287        $this->_htmlInputField($cmd."_usergroups","usergroups",$this->lang["user_groups"],$groups,$this->_auth->canDo("modGroups"),$indent+6);
288
289        if ($this->_auth->canDo("modPass")) {
290            if ($cmd == 'add') {
291                $notes[] = $this->lang['note_pass'];
292            }
293            if ($user) {
294                $notes[] = $this->lang['note_notify'];
295            }
296
297            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);
298        }
299
300        ptln("    </tbody>",$indent);
301        ptln("    <tbody>",$indent);
302        ptln("      <tr>",$indent);
303        ptln("        <td colspan=\"2\">",$indent);
304        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
305        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
306
307        // save current $user, we need this to access details if the name is changed
308        if ($user)
309          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
310
311        $this->_htmlFilterSettings($indent+10);
312
313        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
314        ptln("        </td>",$indent);
315        ptln("      </tr>",$indent);
316        ptln("    </tbody>",$indent);
317        ptln("  </table>",$indent);
318
319        if ($notes) {
320            ptln("    <ul class=\"notes\">");
321            foreach ($notes as $note) {
322                ptln("      <li><span class=\"li\">".$note."</span></li>",$indent);
323            }
324            ptln("    </ul>");
325        }
326        ptln("  </div>",$indent);
327        ptln("</form>",$indent);
328    }
329
330    function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
331        $class = $cando ? '' : ' class="disabled"';
332        echo str_pad('',$indent);
333
334        if($name == 'userpass'){
335            $fieldtype = 'password';
336            $autocomp  = 'autocomplete="off"';
337        }elseif($name == 'usermail'){
338            $fieldtype = 'email';
339            $autocomp  = '';
340        }else{
341            $fieldtype = 'text';
342            $autocomp  = '';
343        }
344
345        echo "<tr $class>";
346        echo "<td><label for=\"$id\" >$label: </label></td>";
347        echo "<td>";
348        if($cando){
349            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" $autocomp />";
350        }else{
351            echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
352            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />";
353        }
354        echo "</td>";
355        echo "</tr>";
356    }
357
358    function _htmlFilter($key) {
359        if (empty($this->_filter)) return '';
360        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
361    }
362
363    function _htmlFilterSettings($indent=0) {
364
365        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
366
367        foreach ($this->_filter as $key => $filter) {
368            ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
369        }
370    }
371
372    function _htmlImportForm($indent=0) {
373        global $ID;
374
375        $failure_download_link = wl($ID,array('do'=>'admin','page'=>'usermanager','fn[importfails]'=>1));
376
377        ptln('<div class="level2 import_users">',$indent);
378        print $this->locale_xhtml('import');
379        ptln('  <form action="'.wl($ID).'" method="post" enctype="multipart/form-data">',$indent);
380        formSecurityToken();
381        ptln('    <label>User list file (csv):  <input type="file" name="import" /></label>',$indent);
382        ptln('    <input type="submit" name="fn[import]" value="'.$this->lang['import'].'" />',$indent);
383        ptln('    <input type="hidden" name="do"    value="admin" />',$indent);
384        ptln('    <input type="hidden" name="page"  value="usermanager" />',$indent);
385
386        $this->_htmlFilterSettings($indent+4);
387        ptln('  </form>',$indent);
388        ptln('</div>');
389
390        // list failures from the previous import
391        if ($this->_import_failures) {
392            $digits = strlen(count($this->_import_failures));
393            ptln('<div class="level3 import_failures">',$indent);
394            ptln('  <h3>Most Recent Import - Failures</h3>');
395            ptln('  <table class="import_failures">',$indent);
396            ptln('    <thead>',$indent);
397            ptln('      <tr>',$indent);
398            ptln('        <th class="line">'.$this->lang['line'].'</th>',$indent);
399            ptln('        <th class="error">'.$this->lang['error'].'</th>',$indent);
400            ptln('        <th class="userid">'.$this->lang['user_id'].'</th>',$indent);
401            ptln('        <th class="username">'.$this->lang['user_name'].'</th>',$indent);
402            ptln('        <th class="usermail">'.$this->lang['user_mail'].'</th>',$indent);
403            ptln('        <th class="usergroups">'.$this->lang['user_groups'].'</th>',$indent);
404            ptln('      </tr>',$indent);
405            ptln('    </thead>',$indent);
406            ptln('    <tbody>',$indent);
407            foreach ($this->_import_failures as $line => $failure) {
408                ptln('      <tr>',$indent);
409                ptln('        <td class="lineno"> '.sprintf('%0'.$digits.'d',$line).' </td>',$indent);
410                ptln('        <td class="error">' .$failure['error'].' </td>', $indent);
411                ptln('        <td class="field userid"> '.hsc($failure['user'][0]).' </td>',$indent);
412                ptln('        <td class="field username"> '.hsc($failure['user'][2]).' </td>',$indent);
413                ptln('        <td class="field usermail"> '.hsc($failure['user'][3]).' </td>',$indent);
414                ptln('        <td class="field usergroups"> '.hsc($failure['user'][4]).' </td>',$indent);
415                ptln('      </tr>',$indent);
416            }
417            ptln('    </tbody>',$indent);
418            ptln('  </table>',$indent);
419            ptln('  <p><a href="'.$failure_download_link.'">Download Failures as CSV for correction</a></p>');
420            ptln('</div>');
421        }
422
423    }
424
425    function _addUser(){
426        global $INPUT;
427        if (!checkSecurityToken()) return false;
428        if (!$this->_auth->canDo('addUser')) return false;
429
430        list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser();
431        if (empty($user)) return false;
432
433        if ($this->_auth->canDo('modPass')){
434            if (empty($pass)){
435                if($INPUT->has('usernotify')){
436                    $pass = auth_pwgen($user);
437                } else {
438                    msg($this->lang['add_fail'], -1);
439                    return false;
440                }
441            }
442        } else {
443            if (!empty($pass)){
444                msg($this->lang['add_fail'], -1);
445                return false;
446            }
447        }
448
449        if ($this->_auth->canDo('modName')){
450            if (empty($name)){
451                msg($this->lang['add_fail'], -1);
452                return false;
453            }
454        } else {
455            if (!empty($name)){
456                return false;
457            }
458        }
459
460        if ($this->_auth->canDo('modMail')){
461            if (empty($mail)){
462                msg($this->lang['add_fail'], -1);
463                return false;
464            }
465        } else {
466            if (!empty($mail)){
467                return false;
468            }
469        }
470
471        if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) {
472
473            msg($this->lang['add_ok'], 1);
474
475            if ($INPUT->has('usernotify') && $pass) {
476                $this->_notifyUser($user,$pass);
477            }
478        } else {
479            msg($this->lang['add_fail'], -1);
480        }
481
482        return $ok;
483    }
484
485    /**
486     * Delete user
487     */
488    function _deleteUser(){
489        global $conf, $INPUT;
490
491        if (!checkSecurityToken()) return false;
492        if (!$this->_auth->canDo('delUser')) return false;
493
494        $selected = $INPUT->arr('delete');
495        if (empty($selected)) return false;
496        $selected = array_keys($selected);
497
498        if(in_array($_SERVER['REMOTE_USER'], $selected)) {
499            msg("You can't delete yourself!", -1);
500            return false;
501        }
502
503        $count = $this->_auth->triggerUserMod('delete', array($selected));
504        if ($count == count($selected)) {
505            $text = str_replace('%d', $count, $this->lang['delete_ok']);
506            msg("$text.", 1);
507        } else {
508            $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
509            $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
510            msg("$part1, $part2",-1);
511        }
512
513        // invalidate all sessions
514        io_saveFile($conf['cachedir'].'/sessionpurge',time());
515
516        return true;
517    }
518
519    /**
520     * Edit user (a user has been selected for editing)
521     */
522    function _editUser($param) {
523        if (!checkSecurityToken()) return false;
524        if (!$this->_auth->canDo('UserMod')) return false;
525
526        $user = cleanID(preg_replace('/.*:/','',$param));
527        $userdata = $this->_auth->getUserData($user);
528
529        // no user found?
530        if (!$userdata) {
531            msg($this->lang['edit_usermissing'],-1);
532            return false;
533        }
534
535        $this->_edit_user = $user;
536        $this->_edit_userdata = $userdata;
537
538        return true;
539    }
540
541    /**
542     * Modify user (modified user data has been recieved)
543     */
544    function _modifyUser(){
545        global $conf, $INPUT;
546
547        if (!checkSecurityToken()) return false;
548        if (!$this->_auth->canDo('UserMod')) return false;
549
550        // get currently valid  user data
551        $olduser = cleanID(preg_replace('/.*:/','',$INPUT->str('userid_old')));
552        $oldinfo = $this->_auth->getUserData($olduser);
553
554        // get new user data subject to change
555        list($newuser,$newpass,$newname,$newmail,$newgrps) = $this->_retrieveUser();
556        if (empty($newuser)) return false;
557
558        $changes = array();
559        if ($newuser != $olduser) {
560
561            if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
562                msg($this->lang['update_fail'],-1);
563                return false;
564            }
565
566            // check if $newuser already exists
567            if ($this->_auth->getUserData($newuser)) {
568                msg(sprintf($this->lang['update_exists'],$newuser),-1);
569                $re_edit = true;
570            } else {
571                $changes['user'] = $newuser;
572            }
573        }
574
575        // generate password if left empty and notification is on
576        if($INPUT->has('usernotify') && empty($newpass)){
577            $newpass = auth_pwgen($olduser);
578        }
579
580        if (!empty($newpass) && $this->_auth->canDo('modPass'))
581          $changes['pass'] = $newpass;
582        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name'])
583          $changes['name'] = $newname;
584        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail'])
585          $changes['mail'] = $newmail;
586        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps'])
587          $changes['grps'] = $newgrps;
588
589        if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) {
590            msg($this->lang['update_ok'],1);
591
592            if ($INPUT->has('usernotify') && $newpass) {
593                $notify = empty($changes['user']) ? $olduser : $newuser;
594                $this->_notifyUser($notify,$newpass);
595            }
596
597            // invalidate all sessions
598            io_saveFile($conf['cachedir'].'/sessionpurge',time());
599
600        } else {
601            msg($this->lang['update_fail'],-1);
602        }
603
604        if (!empty($re_edit)) {
605            $this->_editUser($olduser);
606        }
607
608        return $ok;
609    }
610
611    /**
612     * send password change notification email
613     */
614    function _notifyUser($user, $password, $status_alert=true) {
615
616        if ($sent = auth_sendPassword($user,$password)) {
617            if ($status_alert) {
618                msg($this->lang['notify_ok'], 1);
619            }
620        } else {
621            if ($status_alert) {
622                msg($this->lang['notify_fail'], -1);
623            }
624        }
625
626        return $sent;
627    }
628
629    /**
630     * retrieve & clean user data from the form
631     *
632     * @return array (user, password, full name, email, array(groups))
633     */
634    function _retrieveUser($clean=true) {
635        global $auth;
636        global $INPUT;
637
638        $user[0] = ($clean) ? $auth->cleanUser($INPUT->str('userid')) : $INPUT->str('userid');
639        $user[1] = $INPUT->str('userpass');
640        $user[2] = $INPUT->str('username');
641        $user[3] = $INPUT->str('usermail');
642        $user[4] = explode(',',$INPUT->str('usergroups'));
643
644        $user[4] = array_map('trim',$user[4]);
645        if($clean) $user[4] = array_map(array($auth,'cleanGroup'),$user[4]);
646        $user[4] = array_filter($user[4]);
647        $user[4] = array_unique($user[4]);
648        if(!count($user[4])) $user[4] = null;
649
650        return $user;
651    }
652
653    function _setFilter($op) {
654
655        $this->_filter = array();
656
657        if ($op == 'new') {
658            list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser(false);
659
660            if (!empty($user)) $this->_filter['user'] = $user;
661            if (!empty($name)) $this->_filter['name'] = $name;
662            if (!empty($mail)) $this->_filter['mail'] = $mail;
663            if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
664        }
665    }
666
667    function _retrieveFilter() {
668        global $INPUT;
669
670        $t_filter = $INPUT->arr('filter');
671
672        // messy, but this way we ensure we aren't getting any additional crap from malicious users
673        $filter = array();
674
675        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
676        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
677        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
678        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
679
680        return $filter;
681    }
682
683    function _validatePagination() {
684
685        if ($this->_start >= $this->_user_total) {
686            $this->_start = $this->_user_total - $this->_pagesize;
687        }
688        if ($this->_start < 0) $this->_start = 0;
689
690        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
691    }
692
693    /*
694     *  return an array of strings to enable/disable pagination buttons
695     */
696    function _pagination() {
697
698        $disabled = 'disabled="disabled"';
699
700        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
701
702        if ($this->_user_total == -1) {
703            $buttons['last'] = $disabled;
704            $buttons['next'] = '';
705        } else {
706            $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
707        }
708
709        return $buttons;
710    }
711
712    /*
713     *  export a list of users in csv format using the current filter criteria
714     */
715    function _export() {
716        // list of users for export - based on current filter criteria
717        $user_list = $this->_auth->retrieveUsers(0, 0, $this->_filter);
718        $column_headings = array(
719            $this->lang["user_id"],
720            $this->lang["user_name"],
721            $this->lang["user_mail"],
722            $this->lang["user_groups"]
723        );
724
725        // ==============================================================================================
726        // GENERATE OUTPUT
727        // normal headers for downloading...
728        header('Content-type: text/csv;charset=utf-8');
729        header('Content-Disposition: attachment; filename="wikiusers.csv"');
730#       // for debugging assistance, send as text plain to the browser
731#       header('Content-type: text/plain;charset=utf-8');
732
733        // output the csv
734        $fd = fopen('php://output','w');
735        fputcsv($fd, $column_headings);
736        foreach ($user_list as $user => $info) {
737            $line = array($user, $info['name'], $info['mail'], join(',',$info['grps']));
738            fputcsv($fd, $line);
739        }
740        fclose($fd);
741        die;
742    }
743
744    /*
745     * import a file of users in csv format
746     *
747     * csv file should have 4 columns, user_id, full name, email, groups (comma separated)
748     */
749    function _import() {
750        // check we are allowed to add users
751        if (!checkSecurityToken()) return false;
752        if (!$this->_auth->canDo('addUser')) return false;
753
754        // check file uploaded ok.
755        if (empty($_FILES['import']['size']) || !empty($FILES['import']['error']) && is_uploaded_file($FILES['import']['tmp_name'])) {
756            msg($this->lang['import_error_upload'],-1);
757            return false;
758        }
759        // retrieve users from the file
760        $this->_import_failures = array();
761        $import_success_count = 0;
762        $import_fail_count = 0;
763        $line = 0;
764        $fd = fopen($_FILES['import']['tmp_name'],'r');
765        if ($fd) {
766            while($csv = fgets($fd)){
767                if (!utf8_check($csv)) {
768                    $csv = utf8_encode($csv);
769                }
770                $raw = str_getcsv($csv);
771                $error = '';                        // clean out any errors from the previous line
772                // data checks...
773                if (1 == ++$line) {
774                    if ($raw[0] == 'user_id' || $raw[0] == $this->lang['user_id']) continue;    // skip headers
775                }
776                if (count($raw) < 4) {                                        // need at least four fields
777                    $import_fail_count++;
778                    $error = sprintf($this->lang['import_error_fields'], count($raw));
779                    $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
780                    continue;
781                }
782                array_splice($raw,1,0,auth_pwgen());                          // splice in a generated password
783                $clean = $this->_cleanImportUser($raw, $error);
784                if ($clean && $this->_addImportUser($clean, $error)) {
785                    $sent = $this->_notifyUser($clean[0],$clean[1],false);
786                    if (!$sent){
787                        msg(sprintf($this->lang['import_notify_fail'],$clean[0],$clean[3]),-1);
788                    }
789                    $import_success_count++;
790                } else {
791                    $import_fail_count++;
792                    $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
793                }
794            }
795            msg(sprintf($this->lang['import_success_count'], ($import_success_count+$import_fail_count), $import_success_count),($import_success_count ? 1 : -1));
796            if ($import_fail_count) {
797                msg(sprintf($this->lang['import_failure_count'], $import_fail_count),-1);
798            }
799        } else {
800            msg($this->lang['import_error_readfail'],-1);
801        }
802
803        // save import failures into the session
804        if (!headers_sent()) {
805            session_start();
806            $_SESSION['import_failures'] = $this->_import_failures;
807            session_write_close();
808        }
809    }
810
811    function _cleanImportUser($candidate, & $error){
812        global $INPUT;
813
814        // kludgy ....
815        $INPUT->set('userid', $candidate[0]);
816        $INPUT->set('userpass', $candidate[1]);
817        $INPUT->set('username', $candidate[2]);
818        $INPUT->set('usermail', $candidate[3]);
819        $INPUT->set('usergroups', $candidate[4]);
820
821        $cleaned = $this->_retrieveUser();
822        list($user,$pass,$name,$mail,$grps) = $cleaned;
823        if (empty($user)) {
824            $error = $this->lang['import_error_baduserid'];
825            return false;
826        }
827
828        // no need to check password, handled elsewhere
829
830        if (!($this->_auth->canDo('modName') xor empty($name))){
831            $error = $this->lang['import_error_badname'];
832            return false;
833        }
834
835        if ($this->_auth->canDo('modMail')) {
836            if (empty($mail) || !mail_isvalid($mail)) {
837                $error = $this->lang['import_error_badmail'];
838                return false;
839            }
840        } else {
841            if (!empty($mail)) {
842                $error = $this->lang['import_error_badmail'];
843                return false;
844            }
845        }
846
847        return $cleaned;
848    }
849
850    function _addImportUser($user, & $error){
851        if (!$this->_auth->triggerUserMod('create', $user)) {
852            $error = $this->lang['import_error_create'];
853            return false;
854        }
855
856        return true;
857    }
858
859    function _downloadImportFailures(){
860
861        // ==============================================================================================
862        // GENERATE OUTPUT
863        // normal headers for downloading...
864        header('Content-type: text/csv;charset=utf-8');
865        header('Content-Disposition: attachment; filename="importfails.csv"');
866#       // for debugging assistance, send as text plain to the browser
867#       header('Content-type: text/plain;charset=utf-8');
868
869        // output the csv
870        $fd = fopen('php://output','w');
871        foreach ($this->_import_failures as $line => $fail) {
872            fputs($fd, $fail['orig']);
873        }
874        fclose($fd);
875        die;
876    }
877
878}
879