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