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