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