1<?php 2/* 3 * User Manager 4 * 5 * Dokuwiki Admin Plugin 6 * 7 * This version of the user manager has been modified to only work with 8 * objectified version of auth system 9 * 10 * @author neolao <neolao@neolao.com> 11 * @author Chris Smith <chris@jalakai.co.uk> 12 */ 13// must be run within Dokuwiki 14if(!defined('DOKU_INC')) die(); 15 16if(!defined('DOKU_PLUGIN_IMAGES')) define('DOKU_PLUGIN_IMAGES',DOKU_BASE.'lib/plugins/usermanager/images/'); 17 18/** 19 * All DokuWiki plugins to extend the admin function 20 * need to inherit from this class 21 */ 22class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { 23 24 protected $_auth = null; // auth object 25 protected $_user_total = 0; // number of registered users 26 protected $_filter = array(); // user selection filter(s) 27 protected $_start = 0; // index of first user to be displayed 28 protected $_last = 0; // index of the last user to be displayed 29 protected $_pagesize = 20; // number of users to list on one page 30 protected $_edit_user = ''; // set to user selected for editing 31 protected $_edit_userdata = array(); 32 protected $_disabled = ''; // if disabled set to explanatory string 33 protected $_import_failures = array(); 34 35 /** 36 * Constructor 37 */ 38 public function admin_plugin_usermanager(){ 39 /** @var DokuWiki_Auth_Plugin $auth */ 40 global $auth; 41 42 $this->setupLocale(); 43 44 if (!isset($auth)) { 45 $this->_disabled = $this->lang['noauth']; 46 } else if (!$auth->canDo('getUsers')) { 47 $this->_disabled = $this->lang['nosupport']; 48 } else { 49 50 // we're good to go 51 $this->_auth = & $auth; 52 53 } 54 55 // attempt to retrieve any import failures from the session 56 if (!empty($_SESSION['import_failures'])){ 57 $this->_import_failures = $_SESSION['import_failures']; 58 } 59 } 60 61 /** 62 * Return prompt for admin menu 63 * 64 * @param string $language 65 * @return string 66 */ 67 public function getMenuText($language) { 68 69 if (!is_null($this->_auth)) 70 return parent::getMenuText($language); 71 72 return $this->getLang('menu').' '.$this->_disabled; 73 } 74 75 /** 76 * return sort order for position in admin menu 77 * 78 * @return int 79 */ 80 public function getMenuSort() { 81 return 2; 82 } 83 84 /** 85 * @return int current start value for pageination 86 */ 87 public function getStart() { 88 return $this->_start; 89 } 90 91 /** 92 * @return int number of users per page 93 */ 94 public function getPagesize() { 95 return $this->_pagesize; 96 } 97 98 /** 99 * Handle user request 100 * 101 * @return bool 102 */ 103 public function handle() { 104 global $INPUT; 105 if (is_null($this->_auth)) return false; 106 107 // extract the command and any specific parameters 108 // submit button name is of the form - fn[cmd][param(s)] 109 $fn = $INPUT->param('fn'); 110 111 if (is_array($fn)) { 112 $cmd = key($fn); 113 $param = is_array($fn[$cmd]) ? key($fn[$cmd]) : null; 114 } else { 115 $cmd = $fn; 116 $param = null; 117 } 118 119 if ($cmd != "search") { 120 $this->_start = $INPUT->int('start', 0); 121 $this->_filter = $this->_retrieveFilter(); 122 } 123 124 switch($cmd){ 125 case "add" : $this->_addUser(); break; 126 case "delete" : $this->_deleteUser(); break; 127 case "modify" : $this->_modifyUser(); break; 128 case "edit" : $this->_editUser($param); break; 129 case "search" : $this->_setFilter($param); 130 $this->_start = 0; 131 break; 132 case "export" : $this->_export(); break; 133 case "import" : $this->_import(); break; 134 case "importfails" : $this->_downloadImportFailures(); break; 135 } 136 137 $this->_user_total = $this->_auth->canDo('getUserCount') ? $this->_auth->getUserCount($this->_filter) : -1; 138 139 // page handling 140 switch($cmd){ 141 case 'start' : $this->_start = 0; break; 142 case 'prev' : $this->_start -= $this->_pagesize; break; 143 case 'next' : $this->_start += $this->_pagesize; break; 144 case 'last' : $this->_start = $this->_user_total; break; 145 } 146 $this->_validatePagination(); 147 return true; 148 } 149 150 /** 151 * Output appropriate html 152 * 153 * @return bool 154 */ 155 public function html() { 156 global $ID; 157 158 if(is_null($this->_auth)) { 159 print $this->lang['badauth']; 160 return false; 161 } 162 163 $user_list = $this->_auth->retrieveUsers($this->_start, $this->_pagesize, $this->_filter); 164 165 $page_buttons = $this->_pagination(); 166 $delete_disable = $this->_auth->canDo('delUser') ? '' : 'disabled="disabled"'; 167 168 $editable = $this->_auth->canDo('UserMod'); 169 $export_label = empty($this->_filter) ? $this->lang['export_all'] : $this->lang['export_filtered']; 170 171 print $this->locale_xhtml('intro'); 172 print $this->locale_xhtml('list'); 173 174 ptln("<div id=\"user__manager\">"); 175 ptln("<div class=\"level2\">"); 176 177 if ($this->_user_total > 0) { 178 ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>"); 179 } else { 180 if($this->_user_total < 0) { 181 $allUserTotal = 0; 182 } else { 183 $allUserTotal = $this->_auth->getUserCount(); 184 } 185 ptln("<p>".sprintf($this->lang['nonefound'], $allUserTotal)."</p>"); 186 } 187 ptln("<form action=\"".wl($ID)."\" method=\"post\">"); 188 formSecurityToken(); 189 ptln(" <div class=\"table\">"); 190 ptln(" <table class=\"inline\">"); 191 ptln(" <thead>"); 192 ptln(" <tr>"); 193 ptln(" <th> </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>"); 194 ptln(" </tr>"); 195 196 ptln(" <tr>"); 197 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>"); 198 ptln(" <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>"); 199 ptln(" <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>"); 200 ptln(" <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>"); 201 ptln(" <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>"); 202 ptln(" </tr>"); 203 ptln(" </thead>"); 204 205 if ($this->_user_total) { 206 ptln(" <tbody>"); 207 foreach ($user_list as $user => $userinfo) { 208 extract($userinfo); 209 /** 210 * @var string $name 211 * @var string $pass 212 * @var string $mail 213 * @var array $grps 214 */ 215 $groups = join(', ',$grps); 216 ptln(" <tr class=\"user_info\">"); 217 ptln(" <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".$user."]\" ".$delete_disable." /></td>"); 218 if ($editable) { 219 ptln(" <td><a href=\"".wl($ID,array('fn[edit]['.hsc($user).']' => 1, 220 'do' => 'admin', 221 'page' => 'usermanager', 222 'sectok' => getSecurityToken())). 223 "\" title=\"".$this->lang['edit_prompt']."\">".hsc($user)."</a></td>"); 224 } else { 225 ptln(" <td>".hsc($user)."</td>"); 226 } 227 ptln(" <td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>"); 228 ptln(" </tr>"); 229 } 230 ptln(" </tbody>"); 231 } 232 233 ptln(" <tbody>"); 234 ptln(" <tr><td colspan=\"5\" class=\"centeralign\">"); 235 ptln(" <span class=\"medialeft\">"); 236 ptln(" <input type=\"submit\" name=\"fn[delete]\" ".$delete_disable." class=\"button\" value=\"".$this->lang['delete_selected']."\" id=\"usrmgr__del\" />"); 237 ptln(" </span>"); 238 ptln(" <span class=\"mediaright\">"); 239 ptln(" <input type=\"submit\" name=\"fn[start]\" ".$page_buttons['start']." class=\"button\" value=\"".$this->lang['start']."\" />"); 240 ptln(" <input type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev']." class=\"button\" value=\"".$this->lang['prev']."\" />"); 241 ptln(" <input type=\"submit\" name=\"fn[next]\" ".$page_buttons['next']." class=\"button\" value=\"".$this->lang['next']."\" />"); 242 ptln(" <input type=\"submit\" name=\"fn[last]\" ".$page_buttons['last']." class=\"button\" value=\"".$this->lang['last']."\" />"); 243 ptln(" </span>"); 244 if (!empty($this->_filter)) { 245 ptln(" <input type=\"submit\" name=\"fn[search][clear]\" class=\"button\" value=\"".$this->lang['clear']."\" />"); 246 } 247 ptln(" <input type=\"submit\" name=\"fn[export]\" class=\"button\" value=\"".$export_label."\" />"); 248 ptln(" <input type=\"hidden\" name=\"do\" value=\"admin\" />"); 249 ptln(" <input type=\"hidden\" name=\"page\" value=\"usermanager\" />"); 250 251 $this->_htmlFilterSettings(2); 252 253 ptln(" </td></tr>"); 254 ptln(" </tbody>"); 255 ptln(" </table>"); 256 ptln(" </div>"); 257 258 ptln("</form>"); 259 ptln("</div>"); 260 261 $style = $this->_edit_user ? " class=\"edit_user\"" : ""; 262 263 if ($this->_auth->canDo('addUser')) { 264 ptln("<div".$style.">"); 265 print $this->locale_xhtml('add'); 266 ptln(" <div class=\"level2\">"); 267 268 $this->_htmlUserForm('add',null,array(),4); 269 270 ptln(" </div>"); 271 ptln("</div>"); 272 } 273 274 if($this->_edit_user && $this->_auth->canDo('UserMod')){ 275 ptln("<div".$style." id=\"scroll__here\">"); 276 print $this->locale_xhtml('edit'); 277 ptln(" <div class=\"level2\">"); 278 279 $this->_htmlUserForm('modify',$this->_edit_user,$this->_edit_userdata,4); 280 281 ptln(" </div>"); 282 ptln("</div>"); 283 } 284 285 if ($this->_auth->canDo('addUser')) { 286 $this->_htmlImportForm(); 287 } 288 ptln("</div>"); 289 return true; 290 } 291 292 /** 293 * Display form to add or modify a user 294 * 295 * @param string $cmd 'add' or 'modify' 296 * @param string $user id of user 297 * @param array $userdata array with name, mail, pass and grps 298 * @param int $indent 299 */ 300 protected function _htmlUserForm($cmd,$user='',$userdata=array(),$indent=0) { 301 global $conf; 302 global $ID; 303 global $lang; 304 305 $name = $mail = $groups = ''; 306 $notes = array(); 307 308 if ($user) { 309 extract($userdata); 310 if (!empty($grps)) $groups = join(',',$grps); 311 } else { 312 $notes[] = sprintf($this->lang['note_group'],$conf['defaultgroup']); 313 } 314 315 ptln("<form action=\"".wl($ID)."\" method=\"post\">",$indent); 316 formSecurityToken(); 317 ptln(" <div class=\"table\">",$indent); 318 ptln(" <table class=\"inline\">",$indent); 319 ptln(" <thead>",$indent); 320 ptln(" <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>",$indent); 321 ptln(" </thead>",$indent); 322 ptln(" <tbody>",$indent); 323 324 $this->_htmlInputField($cmd."_userid", "userid", $this->lang["user_id"], $user, $this->_auth->canDo("modLogin"), $indent+6); 325 $this->_htmlInputField($cmd."_userpass", "userpass", $this->lang["user_pass"], "", $this->_auth->canDo("modPass"), $indent+6); 326 $this->_htmlInputField($cmd."_userpass2", "userpass2", $lang["passchk"], "", $this->_auth->canDo("modPass"), $indent+6); 327 $this->_htmlInputField($cmd."_username", "username", $this->lang["user_name"], $name, $this->_auth->canDo("modName"), $indent+6); 328 $this->_htmlInputField($cmd."_usermail", "usermail", $this->lang["user_mail"], $mail, $this->_auth->canDo("modMail"), $indent+6); 329 $this->_htmlInputField($cmd."_usergroups","usergroups",$this->lang["user_groups"],$groups,$this->_auth->canDo("modGroups"),$indent+6); 330 331 if ($this->_auth->canDo("modPass")) { 332 if ($cmd == 'add') { 333 $notes[] = $this->lang['note_pass']; 334 } 335 if ($user) { 336 $notes[] = $this->lang['note_notify']; 337 } 338 339 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); 340 } 341 342 ptln(" </tbody>",$indent); 343 ptln(" <tbody>",$indent); 344 ptln(" <tr>",$indent); 345 ptln(" <td colspan=\"2\">",$indent); 346 ptln(" <input type=\"hidden\" name=\"do\" value=\"admin\" />",$indent); 347 ptln(" <input type=\"hidden\" name=\"page\" value=\"usermanager\" />",$indent); 348 349 // save current $user, we need this to access details if the name is changed 350 if ($user) 351 ptln(" <input type=\"hidden\" name=\"userid_old\" value=\"".$user."\" />",$indent); 352 353 $this->_htmlFilterSettings($indent+10); 354 355 ptln(" <input type=\"submit\" name=\"fn[".$cmd."]\" class=\"button\" value=\"".$this->lang[$cmd]."\" />",$indent); 356 ptln(" </td>",$indent); 357 ptln(" </tr>",$indent); 358 ptln(" </tbody>",$indent); 359 ptln(" </table>",$indent); 360 361 if ($notes) { 362 ptln(" <ul class=\"notes\">"); 363 foreach ($notes as $note) { 364 ptln(" <li><span class=\"li\">".$note."</span></li>",$indent); 365 } 366 ptln(" </ul>"); 367 } 368 ptln(" </div>",$indent); 369 ptln("</form>",$indent); 370 } 371 372 /** 373 * Prints a inputfield 374 * 375 * @param string $id 376 * @param string $name 377 * @param string $label 378 * @param string $value 379 * @param bool $cando whether auth backend is capable to do this action 380 * @param int $indent 381 */ 382 protected function _htmlInputField($id, $name, $label, $value, $cando, $indent=0) { 383 $class = $cando ? '' : ' class="disabled"'; 384 echo str_pad('',$indent); 385 386 if($name == 'userpass' || $name == 'userpass2'){ 387 $fieldtype = 'password'; 388 $autocomp = 'autocomplete="off"'; 389 }elseif($name == 'usermail'){ 390 $fieldtype = 'email'; 391 $autocomp = ''; 392 }else{ 393 $fieldtype = 'text'; 394 $autocomp = ''; 395 } 396 397 echo "<tr $class>"; 398 echo "<td><label for=\"$id\" >$label: </label></td>"; 399 echo "<td>"; 400 if($cando){ 401 echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" $autocomp />"; 402 }else{ 403 echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />"; 404 echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />"; 405 } 406 echo "</td>"; 407 echo "</tr>"; 408 } 409 410 /** 411 * Returns htmlescaped filter value 412 * 413 * @param string $key name of search field 414 * @return string html escaped value 415 */ 416 protected function _htmlFilter($key) { 417 if (empty($this->_filter)) return ''; 418 return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : ''); 419 } 420 421 /** 422 * Print hidden inputs with the current filter values 423 * 424 * @param int $indent 425 */ 426 protected function _htmlFilterSettings($indent=0) { 427 428 ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent); 429 430 foreach ($this->_filter as $key => $filter) { 431 ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent); 432 } 433 } 434 435 /** 436 * Print import form and summary of previous import 437 * 438 * @param int $indent 439 */ 440 protected function _htmlImportForm($indent=0) { 441 global $ID; 442 443 $failure_download_link = wl($ID,array('do'=>'admin','page'=>'usermanager','fn[importfails]'=>1)); 444 445 ptln('<div class="level2 import_users">',$indent); 446 print $this->locale_xhtml('import'); 447 ptln(' <form action="'.wl($ID).'" method="post" enctype="multipart/form-data">',$indent); 448 formSecurityToken(); 449 ptln(' <label>'.$this->lang['import_userlistcsv'].'<input type="file" name="import" /></label>',$indent); 450 ptln(' <input type="submit" name="fn[import]" value="'.$this->lang['import'].'" />',$indent); 451 ptln(' <input type="hidden" name="do" value="admin" />',$indent); 452 ptln(' <input type="hidden" name="page" value="usermanager" />',$indent); 453 454 $this->_htmlFilterSettings($indent+4); 455 ptln(' </form>',$indent); 456 ptln('</div>'); 457 458 // list failures from the previous import 459 if ($this->_import_failures) { 460 $digits = strlen(count($this->_import_failures)); 461 ptln('<div class="level3 import_failures">',$indent); 462 ptln(' <h3>'.$this->lang['import_header'].'</h3>'); 463 ptln(' <table class="import_failures">',$indent); 464 ptln(' <thead>',$indent); 465 ptln(' <tr>',$indent); 466 ptln(' <th class="line">'.$this->lang['line'].'</th>',$indent); 467 ptln(' <th class="error">'.$this->lang['error'].'</th>',$indent); 468 ptln(' <th class="userid">'.$this->lang['user_id'].'</th>',$indent); 469 ptln(' <th class="username">'.$this->lang['user_name'].'</th>',$indent); 470 ptln(' <th class="usermail">'.$this->lang['user_mail'].'</th>',$indent); 471 ptln(' <th class="usergroups">'.$this->lang['user_groups'].'</th>',$indent); 472 ptln(' </tr>',$indent); 473 ptln(' </thead>',$indent); 474 ptln(' <tbody>',$indent); 475 foreach ($this->_import_failures as $line => $failure) { 476 ptln(' <tr>',$indent); 477 ptln(' <td class="lineno"> '.sprintf('%0'.$digits.'d',$line).' </td>',$indent); 478 ptln(' <td class="error">' .$failure['error'].' </td>', $indent); 479 ptln(' <td class="field userid"> '.hsc($failure['user'][0]).' </td>',$indent); 480 ptln(' <td class="field username"> '.hsc($failure['user'][2]).' </td>',$indent); 481 ptln(' <td class="field usermail"> '.hsc($failure['user'][3]).' </td>',$indent); 482 ptln(' <td class="field usergroups"> '.hsc($failure['user'][4]).' </td>',$indent); 483 ptln(' </tr>',$indent); 484 } 485 ptln(' </tbody>',$indent); 486 ptln(' </table>',$indent); 487 ptln(' <p><a href="'.$failure_download_link.'">'.$this->lang['import_downloadfailures'].'</a></p>'); 488 ptln('</div>'); 489 } 490 491 } 492 493 /** 494 * Add an user to auth backend 495 * 496 * @return bool whether succesful 497 */ 498 protected function _addUser(){ 499 global $INPUT; 500 if (!checkSecurityToken()) return false; 501 if (!$this->_auth->canDo('addUser')) return false; 502 503 list($user,$pass,$name,$mail,$grps,$passconfirm) = $this->_retrieveUser(); 504 if (empty($user)) return false; 505 506 if ($this->_auth->canDo('modPass')){ 507 if (empty($pass)){ 508 if($INPUT->has('usernotify')){ 509 $pass = auth_pwgen($user); 510 } else { 511 msg($this->lang['add_fail'], -1); 512 return false; 513 } 514 } else { 515 if (!$this->_verifyPassword($pass,$passconfirm)) { 516 return false; 517 } 518 } 519 } else { 520 if (!empty($pass)){ 521 msg($this->lang['add_fail'], -1); 522 return false; 523 } 524 } 525 526 if ($this->_auth->canDo('modName')){ 527 if (empty($name)){ 528 msg($this->lang['add_fail'], -1); 529 return false; 530 } 531 } else { 532 if (!empty($name)){ 533 return false; 534 } 535 } 536 537 if ($this->_auth->canDo('modMail')){ 538 if (empty($mail)){ 539 msg($this->lang['add_fail'], -1); 540 return false; 541 } 542 } else { 543 if (!empty($mail)){ 544 return false; 545 } 546 } 547 548 if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) { 549 550 msg($this->lang['add_ok'], 1); 551 552 if ($INPUT->has('usernotify') && $pass) { 553 $this->_notifyUser($user,$pass); 554 } 555 } else { 556 msg($this->lang['add_fail'], -1); 557 } 558 559 return $ok; 560 } 561 562 /** 563 * Delete user from auth backend 564 * 565 * @return bool whether succesful 566 */ 567 protected function _deleteUser(){ 568 global $conf, $INPUT; 569 570 if (!checkSecurityToken()) return false; 571 if (!$this->_auth->canDo('delUser')) return false; 572 573 $selected = $INPUT->arr('delete'); 574 if (empty($selected)) return false; 575 $selected = array_keys($selected); 576 577 if(in_array($_SERVER['REMOTE_USER'], $selected)) { 578 msg("You can't delete yourself!", -1); 579 return false; 580 } 581 582 $count = $this->_auth->triggerUserMod('delete', array($selected)); 583 if ($count == count($selected)) { 584 $text = str_replace('%d', $count, $this->lang['delete_ok']); 585 msg("$text.", 1); 586 } else { 587 $part1 = str_replace('%d', $count, $this->lang['delete_ok']); 588 $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']); 589 msg("$part1, $part2",-1); 590 } 591 592 // invalidate all sessions 593 io_saveFile($conf['cachedir'].'/sessionpurge',time()); 594 595 return true; 596 } 597 598 /** 599 * Edit user (a user has been selected for editing) 600 * 601 * @param string $param id of the user 602 * @return bool whether succesful 603 */ 604 protected function _editUser($param) { 605 if (!checkSecurityToken()) return false; 606 if (!$this->_auth->canDo('UserMod')) return false; 607 $user = $this->_auth->cleanUser(preg_replace('/.*[:\/]/','',$param)); 608 $userdata = $this->_auth->getUserData($user); 609 610 // no user found? 611 if (!$userdata) { 612 msg($this->lang['edit_usermissing'],-1); 613 return false; 614 } 615 616 $this->_edit_user = $user; 617 $this->_edit_userdata = $userdata; 618 619 return true; 620 } 621 622 /** 623 * Modify user in the auth backend (modified user data has been recieved) 624 * 625 * @return bool whether succesful 626 */ 627 protected function _modifyUser(){ 628 global $conf, $INPUT; 629 630 if (!checkSecurityToken()) return false; 631 if (!$this->_auth->canDo('UserMod')) return false; 632 633 // get currently valid user data 634 $olduser = $this->_auth->cleanUser(preg_replace('/.*[:\/]/','',$INPUT->str('userid_old'))); 635 $oldinfo = $this->_auth->getUserData($olduser); 636 637 // get new user data subject to change 638 list($newuser,$newpass,$newname,$newmail,$newgrps,$passconfirm) = $this->_retrieveUser(); 639 if (empty($newuser)) return false; 640 641 $changes = array(); 642 if ($newuser != $olduser) { 643 644 if (!$this->_auth->canDo('modLogin')) { // sanity check, shouldn't be possible 645 msg($this->lang['update_fail'],-1); 646 return false; 647 } 648 649 // check if $newuser already exists 650 if ($this->_auth->getUserData($newuser)) { 651 msg(sprintf($this->lang['update_exists'],$newuser),-1); 652 $re_edit = true; 653 } else { 654 $changes['user'] = $newuser; 655 } 656 } 657 if ($this->_auth->canDo('modPass')) { 658 if ($newpass || $passconfirm) { 659 if ($this->_verifyPassword($newpass,$passconfirm)) { 660 $changes['pass'] = $newpass; 661 } else { 662 return false; 663 } 664 } else { 665 // no new password supplied, check if we need to generate one (or it stays unchanged) 666 if ($INPUT->has('usernotify')) { 667 $changes['pass'] = auth_pwgen($olduser); 668 } 669 } 670 } 671 672 if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name']) { 673 $changes['name'] = $newname; 674 } 675 if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail']) { 676 $changes['mail'] = $newmail; 677 } 678 if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps']) { 679 $changes['grps'] = $newgrps; 680 } 681 682 if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) { 683 msg($this->lang['update_ok'],1); 684 685 if ($INPUT->has('usernotify') && !empty($changes['pass'])) { 686 $notify = empty($changes['user']) ? $olduser : $newuser; 687 $this->_notifyUser($notify,$changes['pass']); 688 } 689 690 // invalidate all sessions 691 io_saveFile($conf['cachedir'].'/sessionpurge',time()); 692 693 } else { 694 msg($this->lang['update_fail'],-1); 695 } 696 697 if (!empty($re_edit)) { 698 $this->_editUser($olduser); 699 } 700 701 return $ok; 702 } 703 704 /** 705 * Send password change notification email 706 * 707 * @param string $user id of user 708 * @param string $password plain text 709 * @param bool $status_alert whether status alert should be shown 710 * @return bool whether succesful 711 */ 712 protected function _notifyUser($user, $password, $status_alert=true) { 713 714 if ($sent = auth_sendPassword($user,$password)) { 715 if ($status_alert) { 716 msg($this->lang['notify_ok'], 1); 717 } 718 } else { 719 if ($status_alert) { 720 msg($this->lang['notify_fail'], -1); 721 } 722 } 723 724 return $sent; 725 } 726 727 /** 728 * Verify password meets minimum requirements 729 * :TODO: extend to support password strength 730 * 731 * @param string $password candidate string for new password 732 * @param string $confirm repeated password for confirmation 733 * @return bool true if meets requirements, false otherwise 734 */ 735 protected function _verifyPassword($password, $confirm) { 736 global $lang; 737 738 if (empty($password) && empty($confirm)) { 739 return false; 740 } 741 742 if ($password !== $confirm) { 743 msg($lang['regbadpass'], -1); 744 return false; 745 } 746 747 // :TODO: test password for required strength 748 749 // if we make it this far the password is good 750 return true; 751 } 752 753 /** 754 * Retrieve & clean user data from the form 755 * 756 * @param bool $clean whether the cleanUser method of the authentication backend is applied 757 * @return array (user, password, full name, email, array(groups)) 758 */ 759 protected function _retrieveUser($clean=true) { 760 /** @var DokuWiki_Auth_Plugin $auth */ 761 global $auth; 762 global $INPUT; 763 764 $user = array(); 765 $user[0] = ($clean) ? $auth->cleanUser($INPUT->str('userid')) : $INPUT->str('userid'); 766 $user[1] = $INPUT->str('userpass'); 767 $user[2] = $INPUT->str('username'); 768 $user[3] = $INPUT->str('usermail'); 769 $user[4] = explode(',',$INPUT->str('usergroups')); 770 $user[5] = $INPUT->str('userpass2'); // repeated password for confirmation 771 772 $user[4] = array_map('trim',$user[4]); 773 if($clean) $user[4] = array_map(array($auth,'cleanGroup'),$user[4]); 774 $user[4] = array_filter($user[4]); 775 $user[4] = array_unique($user[4]); 776 if(!count($user[4])) $user[4] = null; 777 778 return $user; 779 } 780 781 /** 782 * Set the filter with the current search terms or clear the filter 783 * 784 * @param string $op 'new' or 'clear' 785 */ 786 protected function _setFilter($op) { 787 788 $this->_filter = array(); 789 790 if ($op == 'new') { 791 list($user,/* $pass */,$name,$mail,$grps) = $this->_retrieveUser(false); 792 793 if (!empty($user)) $this->_filter['user'] = $user; 794 if (!empty($name)) $this->_filter['name'] = $name; 795 if (!empty($mail)) $this->_filter['mail'] = $mail; 796 if (!empty($grps)) $this->_filter['grps'] = join('|',$grps); 797 } 798 } 799 800 /** 801 * Get the current search terms 802 * 803 * @return array 804 */ 805 protected function _retrieveFilter() { 806 global $INPUT; 807 808 $t_filter = $INPUT->arr('filter'); 809 810 // messy, but this way we ensure we aren't getting any additional crap from malicious users 811 $filter = array(); 812 813 if (isset($t_filter['user'])) $filter['user'] = $t_filter['user']; 814 if (isset($t_filter['name'])) $filter['name'] = $t_filter['name']; 815 if (isset($t_filter['mail'])) $filter['mail'] = $t_filter['mail']; 816 if (isset($t_filter['grps'])) $filter['grps'] = $t_filter['grps']; 817 818 return $filter; 819 } 820 821 /** 822 * Validate and improve the pagination values 823 */ 824 protected function _validatePagination() { 825 826 if ($this->_start >= $this->_user_total) { 827 $this->_start = $this->_user_total - $this->_pagesize; 828 } 829 if ($this->_start < 0) $this->_start = 0; 830 831 $this->_last = min($this->_user_total, $this->_start + $this->_pagesize); 832 } 833 834 /** 835 * Return an array of strings to enable/disable pagination buttons 836 * 837 * @return array with enable/disable attributes 838 */ 839 protected function _pagination() { 840 841 $disabled = 'disabled="disabled"'; 842 843 $buttons = array(); 844 $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : ''; 845 846 if ($this->_user_total == -1) { 847 $buttons['last'] = $disabled; 848 $buttons['next'] = ''; 849 } else { 850 $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : ''; 851 } 852 853 return $buttons; 854 } 855 856 /** 857 * Export a list of users in csv format using the current filter criteria 858 */ 859 protected function _export() { 860 // list of users for export - based on current filter criteria 861 $user_list = $this->_auth->retrieveUsers(0, 0, $this->_filter); 862 $column_headings = array( 863 $this->lang["user_id"], 864 $this->lang["user_name"], 865 $this->lang["user_mail"], 866 $this->lang["user_groups"] 867 ); 868 869 // ============================================================================================== 870 // GENERATE OUTPUT 871 // normal headers for downloading... 872 header('Content-type: text/csv;charset=utf-8'); 873 header('Content-Disposition: attachment; filename="wikiusers.csv"'); 874# // for debugging assistance, send as text plain to the browser 875# header('Content-type: text/plain;charset=utf-8'); 876 877 // output the csv 878 $fd = fopen('php://output','w'); 879 fputcsv($fd, $column_headings); 880 foreach ($user_list as $user => $info) { 881 $line = array($user, $info['name'], $info['mail'], join(',',$info['grps'])); 882 fputcsv($fd, $line); 883 } 884 fclose($fd); 885 if (defined('DOKU_UNITTEST')){ return; } 886 887 die; 888 } 889 890 /** 891 * Import a file of users in csv format 892 * 893 * csv file should have 4 columns, user_id, full name, email, groups (comma separated) 894 * 895 * @return bool whether successful 896 */ 897 protected function _import() { 898 // check we are allowed to add users 899 if (!checkSecurityToken()) return false; 900 if (!$this->_auth->canDo('addUser')) return false; 901 902 // check file uploaded ok. 903 if (empty($_FILES['import']['size']) || !empty($_FILES['import']['error']) && $this->_isUploadedFile($_FILES['import']['tmp_name'])) { 904 msg($this->lang['import_error_upload'],-1); 905 return false; 906 } 907 // retrieve users from the file 908 $this->_import_failures = array(); 909 $import_success_count = 0; 910 $import_fail_count = 0; 911 $line = 0; 912 $fd = fopen($_FILES['import']['tmp_name'],'r'); 913 if ($fd) { 914 while($csv = fgets($fd)){ 915 if (!utf8_check($csv)) { 916 $csv = utf8_encode($csv); 917 } 918 $raw = $this->_getcsv($csv); 919 $error = ''; // clean out any errors from the previous line 920 // data checks... 921 if (1 == ++$line) { 922 if ($raw[0] == 'user_id' || $raw[0] == $this->lang['user_id']) continue; // skip headers 923 } 924 if (count($raw) < 4) { // need at least four fields 925 $import_fail_count++; 926 $error = sprintf($this->lang['import_error_fields'], count($raw)); 927 $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv); 928 continue; 929 } 930 array_splice($raw,1,0,auth_pwgen()); // splice in a generated password 931 $clean = $this->_cleanImportUser($raw, $error); 932 if ($clean && $this->_addImportUser($clean, $error)) { 933 $sent = $this->_notifyUser($clean[0],$clean[1],false); 934 if (!$sent){ 935 msg(sprintf($this->lang['import_notify_fail'],$clean[0],$clean[3]),-1); 936 } 937 $import_success_count++; 938 } else { 939 $import_fail_count++; 940 array_splice($raw, 1, 1); // remove the spliced in password 941 $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv); 942 } 943 } 944 msg(sprintf($this->lang['import_success_count'], ($import_success_count+$import_fail_count), $import_success_count),($import_success_count ? 1 : -1)); 945 if ($import_fail_count) { 946 msg(sprintf($this->lang['import_failure_count'], $import_fail_count),-1); 947 } 948 } else { 949 msg($this->lang['import_error_readfail'],-1); 950 } 951 952 // save import failures into the session 953 if (!headers_sent()) { 954 session_start(); 955 $_SESSION['import_failures'] = $this->_import_failures; 956 session_write_close(); 957 } 958 return true; 959 } 960 961 /** 962 * Returns cleaned user data 963 * 964 * @param array $candidate raw values of line from input file 965 * @param string $error 966 * @return array|false cleaned data or false 967 */ 968 protected function _cleanImportUser($candidate, & $error){ 969 global $INPUT; 970 971 // kludgy .... 972 $INPUT->set('userid', $candidate[0]); 973 $INPUT->set('userpass', $candidate[1]); 974 $INPUT->set('username', $candidate[2]); 975 $INPUT->set('usermail', $candidate[3]); 976 $INPUT->set('usergroups', $candidate[4]); 977 978 $cleaned = $this->_retrieveUser(); 979 list($user,/* $pass */,$name,$mail,/* $grps */) = $cleaned; 980 if (empty($user)) { 981 $error = $this->lang['import_error_baduserid']; 982 return false; 983 } 984 985 // no need to check password, handled elsewhere 986 987 if (!($this->_auth->canDo('modName') xor empty($name))){ 988 $error = $this->lang['import_error_badname']; 989 return false; 990 } 991 992 if ($this->_auth->canDo('modMail')) { 993 if (empty($mail) || !mail_isvalid($mail)) { 994 $error = $this->lang['import_error_badmail']; 995 return false; 996 } 997 } else { 998 if (!empty($mail)) { 999 $error = $this->lang['import_error_badmail']; 1000 return false; 1001 } 1002 } 1003 1004 return $cleaned; 1005 } 1006 1007 /** 1008 * Adds imported user to auth backend 1009 * 1010 * Required a check of canDo('addUser') before 1011 * 1012 * @param array $user data of user 1013 * @param string &$error reference catched error message 1014 * @return bool whether successful 1015 */ 1016 protected function _addImportUser($user, & $error){ 1017 if (!$this->_auth->triggerUserMod('create', $user)) { 1018 $error = $this->lang['import_error_create']; 1019 return false; 1020 } 1021 1022 return true; 1023 } 1024 1025 /** 1026 * Downloads failures as csv file 1027 */ 1028 protected function _downloadImportFailures(){ 1029 1030 // ============================================================================================== 1031 // GENERATE OUTPUT 1032 // normal headers for downloading... 1033 header('Content-type: text/csv;charset=utf-8'); 1034 header('Content-Disposition: attachment; filename="importfails.csv"'); 1035# // for debugging assistance, send as text plain to the browser 1036# header('Content-type: text/plain;charset=utf-8'); 1037 1038 // output the csv 1039 $fd = fopen('php://output','w'); 1040 foreach ($this->_import_failures as $fail) { 1041 fputs($fd, $fail['orig']); 1042 } 1043 fclose($fd); 1044 die; 1045 } 1046 1047 /** 1048 * wrapper for is_uploaded_file to facilitate overriding by test suite 1049 * 1050 * @param string $file filename 1051 * @return bool 1052 */ 1053 protected function _isUploadedFile($file) { 1054 return is_uploaded_file($file); 1055 } 1056 1057 /** 1058 * wrapper for str_getcsv() to simplify maintaining compatibility with php 5.2 1059 * 1060 * @deprecated remove when dokuwiki php requirement increases to 5.3+ 1061 * also associated unit test & mock access method 1062 * 1063 * @param string $csv string to parse 1064 * @return array 1065 */ 1066 protected function _getcsv($csv) { 1067 return function_exists('str_getcsv') ? str_getcsv($csv) : $this->str_getcsv($csv); 1068 } 1069 1070 /** 1071 * replacement str_getcsv() function for php < 5.3 1072 * loosely based on www.php.net/str_getcsv#88311 1073 * 1074 * @deprecated remove when dokuwiki php requirement increases to 5.3+ 1075 * 1076 * @param string $str string to parse 1077 * @return array 1078 */ 1079 protected function str_getcsv($str) { 1080 $fp = fopen("php://temp/maxmemory:1048576", 'r+'); // 1MiB 1081 fputs($fp, $str); 1082 rewind($fp); 1083 1084 $data = fgetcsv($fp); 1085 1086 fclose($fp); 1087 return $data; 1088 } 1089} 1090