xref: /dokuwiki/lib/plugins/usermanager/admin.php (revision ae1afd2f6529e4d07b18317304e5e2c302d783ce)
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          $notes[] = $this->lang['note_pass'];
291          if ($user) {
292            $notes[] = $this->lang['note_notify'];
293          }
294
295          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);
296        }
297
298        ptln("    </tbody>",$indent);
299        ptln("    <tbody>",$indent);
300        ptln("      <tr>",$indent);
301        ptln("        <td colspan=\"2\">",$indent);
302        ptln("          <input type=\"hidden\" name=\"do\"    value=\"admin\" />",$indent);
303        ptln("          <input type=\"hidden\" name=\"page\"  value=\"usermanager\" />",$indent);
304
305        // save current $user, we need this to access details if the name is changed
306        if ($user)
307          ptln("          <input type=\"hidden\" name=\"userid_old\"  value=\"".$user."\" />",$indent);
308
309        $this->_htmlFilterSettings($indent+10);
310
311        ptln("          <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent);
312        ptln("        </td>",$indent);
313        ptln("      </tr>",$indent);
314        ptln("    </tbody>",$indent);
315        ptln("  </table>",$indent);
316        ptln("  </div>",$indent);
317
318        foreach ($notes as $note)
319          ptln("<div class=\"fn\">".$note."</div>",$indent);
320
321        ptln("</form>",$indent);
322    }
323
324    function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) {
325        $class = $cando ? '' : ' class="disabled"';
326        echo str_pad('',$indent);
327
328        if($name == 'userpass'){
329            $fieldtype = 'password';
330            $autocomp  = 'autocomplete="off"';
331        }elseif($name == 'usermail'){
332            $fieldtype = 'email';
333            $autocomp  = '';
334        }else{
335            $fieldtype = 'text';
336            $autocomp  = '';
337        }
338
339
340        echo "<tr $class>";
341        echo "<td><label for=\"$id\" >$label: </label></td>";
342        echo "<td>";
343        if($cando){
344            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" $autocomp />";
345        }else{
346            echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
347            echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />";
348        }
349        echo "</td>";
350        echo "</tr>";
351    }
352
353    function _htmlFilter($key) {
354        if (empty($this->_filter)) return '';
355        return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : '');
356    }
357
358    function _htmlFilterSettings($indent=0) {
359
360        ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent);
361
362        foreach ($this->_filter as $key => $filter) {
363          ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent);
364        }
365    }
366
367    function _htmlImportForm($indent=0) {
368        global $ID;
369
370        $failure_download_link = wl($ID,array('do'=>'admin','page'=>'usermanager','fn[importfails]'=>1));
371
372        ptln('<div class="level2 import_users">',$indent);
373        print $this->locale_xhtml('import');
374        ptln('  <form action="'.wl($ID).'" method="post" enctype="multipart/form-data">',$indent);
375        formSecurityToken();
376        ptln('    <label>User list file (csv):  <input type="file" name="import" /></label>',$indent);
377        ptln('    <input type="submit" name="fn[import]" value="'.$this->lang['import'].'" />',$indent);
378        ptln('    <input type="hidden" name="do"    value="admin" />',$indent);
379        ptln('    <input type="hidden" name="page"  value="usermanager" />',$indent);
380
381        $this->_htmlFilterSettings($indent+4);
382        ptln('  </form>',$indent);
383        ptln('</div>');
384
385        // list failures from the previous import
386        if ($this->_import_failures) {
387            $digits = strlen(count($this->_import_failures));
388            ptln('<div class="level3 import_failures">',$indent);
389            ptln('  <h3>Most Recent Import - Failures</h3>');
390            ptln('  <table class="import_failures">',$indent);
391            ptln('    <thead>',$indent);
392            ptln('      <tr>',$indent);
393            ptln('        <th class="line">'.$this->lang['line'].'</th>',$indent);
394            ptln('        <th class="error">'.$this->lang['error'].'</th>',$indent);
395            ptln('        <th class="userid">'.$this->lang['user_id'].'</th>',$indent);
396            ptln('        <th class="username">'.$this->lang['user_name'].'</th>',$indent);
397            ptln('        <th class="usermail">'.$this->lang['user_mail'].'</th>',$indent);
398            ptln('        <th class="usergroups">'.$this->lang['user_groups'].'</th>',$indent);
399            ptln('      </tr>',$indent);
400            ptln('    </thead>',$indent);
401            ptln('    <tbody>',$indent);
402            foreach ($this->_import_failures as $line => $failure) {
403                ptln('      <tr>',$indent);
404                ptln('        <td class="lineno"> '.sprintf('%0'.$digits.'d',$line).' </td>',$indent);
405                ptln('        <td class="error">' .$failure['error'].' </td>', $indent);
406                ptln('        <td class="field userid"> '.hsc($failure['user'][0]).' </td>',$indent);
407                ptln('        <td class="field username"> '.hsc($failure['user'][2]).' </td>',$indent);
408                ptln('        <td class="field usermail"> '.hsc($failure['user'][3]).' </td>',$indent);
409                ptln('        <td class="field usergroups"> '.hsc($failure['user'][4]).' </td>',$indent);
410                ptln('      </tr>',$indent);
411            }
412            ptln('    </tbody>',$indent);
413            ptln('  </table>',$indent);
414            ptln('  <p><a href="'.$failure_download_link.'">Download Failures as CSV for correction</a></p>');
415            ptln('</div>');
416        }
417
418    }
419
420    function _addUser(){
421        global $INPUT;
422        if (!checkSecurityToken()) return false;
423        if (!$this->_auth->canDo('addUser')) return false;
424
425        list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser();
426        if (empty($user)) return false;
427
428        if ($this->_auth->canDo('modPass')){
429          if (empty($pass)){
430            if($INPUT->has('usernotify')){
431              $pass = auth_pwgen($user);
432            } else {
433              msg($this->lang['add_fail'], -1);
434              return false;
435            }
436          }
437        } else {
438          if (!empty($pass)){
439            msg($this->lang['add_fail'], -1);
440            return false;
441          }
442        }
443
444        if ($this->_auth->canDo('modName')){
445          if (empty($name)){
446            msg($this->lang['add_fail'], -1);
447            return false;
448          }
449        } else {
450          if (!empty($name)){
451            return false;
452          }
453        }
454
455        if ($this->_auth->canDo('modMail')){
456          if (empty($mail)){
457            msg($this->lang['add_fail'], -1);
458            return false;
459          }
460        } else {
461          if (!empty($mail)){
462            return false;
463          }
464        }
465
466        if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) {
467
468          msg($this->lang['add_ok'], 1);
469
470          if ($INPUT->has('usernotify') && $pass) {
471            $this->_notifyUser($user,$pass);
472          }
473        } else {
474          msg($this->lang['add_fail'], -1);
475        }
476
477        return $ok;
478    }
479
480    /**
481     * Delete user
482     */
483    function _deleteUser(){
484        global $conf, $INPUT;
485
486        if (!checkSecurityToken()) return false;
487        if (!$this->_auth->canDo('delUser')) return false;
488
489        $selected = $INPUT->arr('delete');
490        if (empty($selected)) return false;
491        $selected = array_keys($selected);
492
493        if(in_array($_SERVER['REMOTE_USER'], $selected)) {
494            msg("You can't delete yourself!", -1);
495            return false;
496        }
497
498        $count = $this->_auth->triggerUserMod('delete', array($selected));
499        if ($count == count($selected)) {
500          $text = str_replace('%d', $count, $this->lang['delete_ok']);
501          msg("$text.", 1);
502        } else {
503          $part1 = str_replace('%d', $count, $this->lang['delete_ok']);
504          $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']);
505          msg("$part1, $part2",-1);
506        }
507
508        // invalidate all sessions
509        io_saveFile($conf['cachedir'].'/sessionpurge',time());
510
511        return true;
512    }
513
514    /**
515     * Edit user (a user has been selected for editing)
516     */
517    function _editUser($param) {
518        if (!checkSecurityToken()) return false;
519        if (!$this->_auth->canDo('UserMod')) return false;
520
521        $user = cleanID(preg_replace('/.*:/','',$param));
522        $userdata = $this->_auth->getUserData($user);
523
524        // no user found?
525        if (!$userdata) {
526          msg($this->lang['edit_usermissing'],-1);
527          return false;
528        }
529
530        $this->_edit_user = $user;
531        $this->_edit_userdata = $userdata;
532
533        return true;
534    }
535
536    /**
537     * Modify user (modified user data has been recieved)
538     */
539    function _modifyUser(){
540        global $conf, $INPUT;
541
542        if (!checkSecurityToken()) return false;
543        if (!$this->_auth->canDo('UserMod')) return false;
544
545        // get currently valid  user data
546        $olduser = cleanID(preg_replace('/.*:/','',$INPUT->str('userid_old')));
547        $oldinfo = $this->_auth->getUserData($olduser);
548
549        // get new user data subject to change
550        list($newuser,$newpass,$newname,$newmail,$newgrps) = $this->_retrieveUser();
551        if (empty($newuser)) return false;
552
553        $changes = array();
554        if ($newuser != $olduser) {
555
556          if (!$this->_auth->canDo('modLogin')) {        // sanity check, shouldn't be possible
557            msg($this->lang['update_fail'],-1);
558            return false;
559          }
560
561          // check if $newuser already exists
562          if ($this->_auth->getUserData($newuser)) {
563            msg(sprintf($this->lang['update_exists'],$newuser),-1);
564            $re_edit = true;
565          } else {
566            $changes['user'] = $newuser;
567          }
568        }
569
570        // generate password if left empty and notification is on
571        if($INPUT->has('usernotify') && empty($newpass)){
572            $newpass = auth_pwgen($olduser);
573        }
574
575        if (!empty($newpass) && $this->_auth->canDo('modPass'))
576          $changes['pass'] = $newpass;
577        if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name'])
578          $changes['name'] = $newname;
579        if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail'])
580          $changes['mail'] = $newmail;
581        if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps'])
582          $changes['grps'] = $newgrps;
583
584        if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) {
585          msg($this->lang['update_ok'],1);
586
587          if ($INPUT->has('usernotify') && $newpass) {
588            $notify = empty($changes['user']) ? $olduser : $newuser;
589            $this->_notifyUser($notify,$newpass);
590          }
591
592          // invalidate all sessions
593          io_saveFile($conf['cachedir'].'/sessionpurge',time());
594
595        } else {
596          msg($this->lang['update_fail'],-1);
597        }
598
599        if (!empty($re_edit)) {
600            $this->_editUser($olduser);
601        }
602
603        return $ok;
604    }
605
606    /**
607     * send password change notification email
608     */
609    function _notifyUser($user, $password) {
610
611        if ($sent = auth_sendPassword($user,$password)) {
612          msg($this->lang['notify_ok'], 1);
613        } else {
614          msg($this->lang['notify_fail'], -1);
615        }
616
617        return $sent;
618    }
619
620    /**
621     * retrieve & clean user data from the form
622     *
623     * @return array (user, password, full name, email, array(groups))
624     */
625    function _retrieveUser($clean=true) {
626        global $auth;
627        global $INPUT;
628
629        $user[0] = ($clean) ? $auth->cleanUser($INPUT->str('userid')) : $INPUT->str('userid');
630        $user[1] = $INPUT->str('userpass');
631        $user[2] = $INPUT->str('username');
632        $user[3] = $INPUT->str('usermail');
633        $user[4] = explode(',',$INPUT->str('usergroups'));
634
635        $user[4] = array_map('trim',$user[4]);
636        if($clean) $user[4] = array_map(array($auth,'cleanGroup'),$user[4]);
637        $user[4] = array_filter($user[4]);
638        $user[4] = array_unique($user[4]);
639        if(!count($user[4])) $user[4] = null;
640
641        return $user;
642    }
643
644    function _setFilter($op) {
645
646        $this->_filter = array();
647
648        if ($op == 'new') {
649          list($user,$pass,$name,$mail,$grps) = $this->_retrieveUser(false);
650
651          if (!empty($user)) $this->_filter['user'] = $user;
652          if (!empty($name)) $this->_filter['name'] = $name;
653          if (!empty($mail)) $this->_filter['mail'] = $mail;
654          if (!empty($grps)) $this->_filter['grps'] = join('|',$grps);
655        }
656    }
657
658    function _retrieveFilter() {
659        global $INPUT;
660
661        $t_filter = $INPUT->arr('filter');
662
663        // messy, but this way we ensure we aren't getting any additional crap from malicious users
664        $filter = array();
665
666        if (isset($t_filter['user'])) $filter['user'] = $t_filter['user'];
667        if (isset($t_filter['name'])) $filter['name'] = $t_filter['name'];
668        if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail'];
669        if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps'];
670
671        return $filter;
672    }
673
674    function _validatePagination() {
675
676        if ($this->_start >= $this->_user_total) {
677          $this->_start = $this->_user_total - $this->_pagesize;
678        }
679        if ($this->_start < 0) $this->_start = 0;
680
681        $this->_last = min($this->_user_total, $this->_start + $this->_pagesize);
682    }
683
684    /*
685     *  return an array of strings to enable/disable pagination buttons
686     */
687    function _pagination() {
688
689        $disabled = 'disabled="disabled"';
690
691        $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : '';
692
693        if ($this->_user_total == -1) {
694          $buttons['last'] = $disabled;
695          $buttons['next'] = '';
696        } else {
697          $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : '';
698        }
699
700        return $buttons;
701    }
702
703    /*
704     *  export a list of users in csv format using the current filter criteria
705     */
706    function _export() {
707        // list of users for export - based on current filter criteria
708        $user_list = $this->_auth->retrieveUsers(0, 0, $this->_filter);
709        $column_headings = array(
710            $this->lang["user_id"],
711            $this->lang["user_name"],
712            $this->lang["user_mail"],
713            $this->lang["user_groups"]
714        );
715
716        // ==============================================================================================
717        // GENERATE OUTPUT
718        // normal headers for downloading...
719        header('Content-type: text/csv;charset=utf-8');
720        header('Content-Disposition: attachment; filename="wikiusers.csv"');
721#       // for debugging assistance, send as text plain to the browser
722#       header('Content-type: text/plain;charset=utf-8');
723
724        // output the csv
725        $fd = fopen('php://output','w');
726        fputcsv($fd, $column_headings);
727        foreach ($user_list as $user => $info) {
728            $line = array($user, $info['name'], $info['mail'], join(',',$info['grps']));
729            fputcsv($fd, $line);
730        }
731        fclose($fd);
732        die;
733    }
734
735    /*
736     * import a file of users in csv format
737     *
738     * csv file should have 4 columns, user_id, full name, email, groups (comma separated)
739     */
740    function _import() {
741        // check we are allowed to add users
742        if (!checkSecurityToken()) return false;
743        if (!$this->_auth->canDo('addUser')) return false;
744
745        // check file uploaded ok.
746        if (empty($_FILES['import']['size']) || !empty($FILES['import']['error']) && is_uploaded_file($FILES['import']['tmp_name'])) {
747            msg($this->lang['import_error_upload'],-1);
748            return false;
749        }
750        // retrieve users from the file
751        $this->_import_failures = array();
752        $import_success_count = 0;
753        $import_fail_count = 0;
754        $line = 0;
755        $fd = fopen($_FILES['import']['tmp_name'],'r');
756        if ($fd) {
757            while($csv = fgets($fd)){
758                $raw = str_getcsv($csv);
759                $error = '';                        // clean out any errors from the previous line
760                // data checks...
761                if (1 == ++$line) {
762                    if ($raw[0] == 'user_id' || $raw[0] == $this->lang['user_id']) continue;    // skip headers
763                }
764                if (count($raw) < 4) {                                        // need at least four fields
765                    $import_fail_count++;
766                    $error = sprintf($this->lang['import_error_fields'], count($raw));
767                    $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
768                    continue;
769                }
770                array_splice($raw,1,0,auth_pwgen());                          // splice in a generated password
771                $clean = $this->_cleanImportUser($raw, $error);
772                if ($clean && $this->_addImportUser($clean, $error)) {
773#                    $this->_notifyUser($clean[0],$clean[1]);
774                    $import_success_count++;
775                } else {
776                    $import_fail_count++;
777                    $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv);
778                }
779            }
780            msg(sprintf($this->lang['import_success_count'], ($import_success_count+$import_fail_count), $import_success_count),($import_success_count ? 1 : -1));
781            if ($import_fail_count) {
782                msg(sprintf($this->lang['import_failure_count'], $import_fail_count),-1);
783            }
784        } else {
785            msg($this->lang['import_error_readfail'],-1);
786        }
787
788        // save import failures into the session
789        if (!headers_sent()) {
790          session_start();
791          $_SESSION['import_failures'] = $this->_import_failures;
792          session_write_close();
793        }
794    }
795
796    function _cleanImportUser($candidate, & $error){
797        global $INPUT;
798
799        // kludgy ....
800        $INPUT->set('userid', $candidate[0]);
801        $INPUT->set('userpass', $candidate[1]);
802        $INPUT->set('username', $candidate[2]);
803        $INPUT->set('usermail', $candidate[3]);
804        $INPUT->set('usergroups', $candidate[4]);
805
806        $cleaned = $this->_retrieveUser();
807        list($user,$pass,$name,$mail,$grps) = $cleaned;
808        if (empty($user)) {
809            $error = $this->lang['import_error_baduserid'];
810            return false;
811        }
812
813        // no need to check password, handled elsewhere
814
815        if (!($this->_auth->canDo('modName') xor empty($name))){
816            $error = $this->lang['import_error_badname'];
817            return false;
818        }
819
820        if (!($this->_auth->canDo('modMail') xor empty($mail))){
821            $error = $this->lang['import_error_badmail'];
822            return false;
823        }
824
825        return $cleaned;
826    }
827
828    function _addImportUser($user, & $error){
829        if (!$this->_auth->triggerUserMod('create', $user)) {
830            $error = $this->lang['import_error_create'];
831            return false;
832        }
833
834        return true;
835    }
836
837    function _downloadImportFailures(){
838
839        // ==============================================================================================
840        // GENERATE OUTPUT
841        // normal headers for downloading...
842        header('Content-type: text/csv;charset=utf-8');
843        header('Content-Disposition: attachment; filename="importfails.csv"');
844#       // for debugging assistance, send as text plain to the browser
845#       header('Content-type: text/plain;charset=utf-8');
846
847        // output the csv
848        $fd = fopen('php://output','w');
849        foreach ($this->_import_failures as $line => $fail) {
850            fputs($fd, $fail['orig']);
851        }
852        fclose($fd);
853        die;
854    }
855
856}
857