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