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