1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
|
<?php
use function LAM\ACCOUNTLIST\isPasswordChangeByDefault;
use LAM\TYPES\ConfiguredType;
/*
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Tilo Lutz
Copyright (C) 2007 - 2024 Roland Gruber
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Manages Unix shadow accounts for users.
*
* @package modules
*
* @author Tilo Lutz
* @author Roland Gruber
* @author Michael Duergner
*/
/**
* Manages the object class "shadowAccount" for users.
*
* @package modules
*/
class shadowAccount extends baseModule implements passwordService, AccountStatusProvider {
/**
* These attributes will be ignored by default if a new account is copied from an existing one.
*/
private const ATTRIBUTES_TO_IGNORE_ON_COPY = ['shadowlastchange', 'shadowexpire'];
/**
* ID for expired account status.
*/
private const STATUS_ACCOUNT_EXPIRED = "SHADOW_ACCOUNT_EXPIRED";
/**
* ID for expired password status.
*/
private const STATUS_PASSWORD_EXPIRED = "SHADOW_PASSWORD_EXPIRED";
/**
* Creates a new shadowAccount object.
*
* @param string $scope account type (user, group, host)
*/
function __construct($scope) {
// call parent constructor
parent::__construct($scope);
$this->autoAddObjectClasses = false;
}
/**
* This function builds up the message array.
*/
function load_Messages() {
// error messages for input checks
$this->messages['shadowmin'][0] = ['ERROR', _('Minimum password age'), _('Password minimum age must be are natural number.')];
$this->messages['shadowmin'][1] = ['ERROR', _('Account %s:') . ' shadowAccount_minAge', _('Password minimum age must be are natural number.')];
$this->messages['shadowmax'][0] = ['ERROR', _('Maximum password age'), _('Password maximum age must be are natural number.')];
$this->messages['shadowmax'][1] = ['ERROR', _('Account %s:') . ' shadowAccount_maxAge', _('Password maximum age must be are natural number.')];
$this->messages['inactive'][0] = ['ERROR', _('Password expiration'), _('Password expiration must be are natural number or -1.')];
$this->messages['inactive'][1] = ['ERROR', _('Account %s:') . ' shadowAccount_ignoreExpire', _('Password expiration must be are natural number or -1.')];
$this->messages['shadowwarning'][0] = ['ERROR', _('Password warning'), _('Password warning must be are natural number.')];
$this->messages['shadowwarning'][1] = ['ERROR', _('Account %s:') . ' shadowAccount_warning', _('Password warning must be are natural number.')];
$this->messages['shadow_cmp'][0] = ['ERROR', _('Maximum password age'), _('Password maximum age must be bigger than password minimum age.')];
$this->messages['shadow_cmp'][1] = ['ERROR', _('Account %s:') . ' shadowAccount_min/maxAge', _('Password maximum age must be bigger as password minimum age.')];
$this->messages['shadow_expireDate'][0] = ['ERROR', _('Account %s:') . ' shadowAccount_expireDate', _('The expiration date is invalid.')];
$this->messages['shadow_lastChange'][0] = ['ERROR', _('Account %s:') . ' shadowAccount_lastChange', _('The last password change date is invalid.')];
}
/**
* Returns true if this module can manage accounts of the current type, otherwise false.
*
* @return boolean true if module fits
*/
public function can_manage() {
return $this->get_scope() === 'user';
}
/**
* Returns meta data that is interpreted by parent class
*
* @return array array with meta data
*
* @see baseModule::get_metaData()
*/
function get_metaData() {
$return = [];
// icon
$return['icon'] = 'key.svg';
// alias name
$return["alias"] = _('Shadow');
// module dependencies
$return['dependencies'] = ['depends' => ['posixAccount'], 'conflicts' => []];
// managed object classes
$return['objectClasses'] = ['shadowAccount'];
// managed attributes
$return['attributes'] = ['shadowlastchange', 'shadowmin', 'shadowmax', 'shadowwarning',
'shadowinactive', 'shadowexpire', 'shadowflag'];
// lists for expiration date
$day = ['-'];
$mon = ['-'];
$year = ['-'];
for ($i = 1; $i <= 31; $i++) {
$day[] = $i;
}
for ($i = 1; $i <= 12; $i++) {
$mon[] = $i;
}
for ($i = 2003; $i <= 2030; $i++) {
$year[] = $i;
}
$profileOptionsTable = new htmlResponsiveRow();
// auto add extension
$profileOptionsTable->add(new htmlResponsiveInputCheckbox('shadowAccount_addExt', false, _('Automatically add this extension'), 'autoAdd'));
// password warning
$profilePwdWarning = new htmlResponsiveInputField(_('Password warning'), 'shadowAccount_shadowWarning', null, 'shadowwarning');
$profilePwdWarning->setFieldMaxLength(4);
$profileOptionsTable->add($profilePwdWarning);
// password expiration
$profilePwdExpiration = new htmlResponsiveInputField(_('Password expiration'), 'shadowAccount_shadowInactive', null, 'shadowinactive');
$profilePwdExpiration->setFieldMaxLength(4);
$profileOptionsTable->add($profilePwdExpiration);
// minimum password age
$profilePwdMinAge = new htmlResponsiveInputField(_('Minimum password age'), 'shadowAccount_shadowMin', null, 'shadowmin');
$profilePwdMinAge->setFieldMaxLength(5);
$profileOptionsTable->add($profilePwdMinAge);
// maximum password age
$profilePwdMinAge = new htmlResponsiveInputField(_('Maximum password age'), 'shadowAccount_shadowMax', null, 'shadowmax');
$profilePwdMinAge->setFieldMaxLength(5);
$profileOptionsTable->add($profilePwdMinAge);
// expiration date
$profileOptionsTable->addLabel(new htmlOutputText(_('Account expiration date')));
$profileOptionsExpire = new htmlResponsiveRow();
$profileOptionsExpire->add(new htmlSelect('shadowAccount_shadowExpire_day', $day, ['-']), 2, 2, 2, 'padding-right05');
$profileOptionsExpire->add(new htmlSelect('shadowAccount_shadowExpire_mon', $mon, ['-']), 2, 2, 2, 'padding-left-right05');
$profileOptionsExpire->add(new htmlSelect('shadowAccount_shadowExpire_yea', $year, ['-']), 6, 6, 6, 'padding-left-right05');
$profileOptionsExpire->add(new htmlHelpLink('shadowexpire'), 2, 2, 2, 'padding-left-right05');
$profileOptionsTable->addField($profileOptionsExpire);
$return['profile_options'] = $profileOptionsTable;
// profile checks
$return['profile_checks']['shadowAccount_shadowMin'] = [
'type' => 'ext_preg',
'regex' => 'digit',
'error_message' => $this->messages['shadowmin'][0]];
$return['profile_checks']['shadowAccount_shadowMax'] = [
'type' => 'ext_preg',
'regex' => 'digit',
'error_message' => $this->messages['shadowmax'][0]];
$return['profile_checks']['shadowAccount_cmp'] = [
'type' => 'int_greater',
'cmp_name1' => 'shadowAccount_shadowMax',
'cmp_name2' => 'shadowAccount_shadowMin',
'error_message' => $this->messages['shadow_cmp'][0]];
$return['profile_checks']['shadowAccount_shadowInactive'] = [
'type' => 'ext_preg',
'regex' => 'digit2',
'error_message' => $this->messages['inactive'][0]];
$return['profile_checks']['shadowAccount_shadowWarning'] = [
'type' => 'ext_preg',
'regex' => 'digit',
'error_message' => $this->messages['shadowwarning'][0]];
// profile mappings
$return['profile_mappings'] = [
'shadowAccount_shadowWarning' => 'shadowwarning',
'shadowAccount_shadowInactive' => 'shadowinactive',
'shadowAccount_shadowMin' => 'shadowmin',
'shadowAccount_shadowMax' => 'shadowmax'
];
// available PDF fields
$return['PDF_fields'] = [
'shadowLastChange' => _('Last password change'),
'shadowWarning' => _('Password warning'),
'shadowInactive' => _('Password expiration'),
'shadowExpire' => _('Account expiration date'),
'shadowMinAge' => _('Minimum password age'),
'shadowMaxAge' => _('Maximum password age'),
];
// help Entries
$return['help'] = [
'shadowwarning' => [
"Headline" => _("Password warning"), 'attr' => 'shadowWarning',
"Text" => _("Days before password is to expire that user is warned of pending password expiration. If set value must be >0.") . ' ' . _("Can be left empty.")
],
'shadowinactive' => [
"Headline" => _("Password expiration"), 'attr' => 'shadowInactive',
"Text" => _("Number of days a user can login even his password has expired. -1=always.") . ' ' . _("Can be left empty.")
],
'shadowmin' => [
"Headline" => _("Minimum password age"), 'attr' => 'shadowMin',
"Text" => _("Number of days a user has to wait until he is allowed to change his password again. If set value must be >0.") . ' ' . _("Can be left empty.")
],
'shadowmax' => [
"Headline" => _("Maximum password age"), 'attr' => 'shadowMax',
"Text" => _("Number of days after a user has to change his password again. If set value must be >0.") . ' ' . _("Can be left empty.")
],
'shadowexpire' => [
"Headline" => _("Account expiration date"), 'attr' => 'shadowExpire',
"Text" => _("This is the date when the account will expire. Format: DD-MM-YYYY")
],
'autoAdd' => [
"Headline" => _("Automatically add this extension"),
"Text" => _("This will enable the extension automatically if this profile is loaded.")
],
'shadowlastchange' => [
"Headline" => _("Last password change"), 'attr' => 'shadowLastChange',
"Text" => _("This is the date when the user changed his password. If you specify a maximum password age then you can force a password change here.")
],
'cronAddWarningPeriod' => [
"Headline" => _('Add expiration warning time'), 'attr' => 'shadowWarning',
"Text" => _('This will add the warning period for password expiration on top.')
]
];
// upload fields
$return['upload_columns'] = [
[
'name' => 'shadowAccount_warning',
'description' => _('Password warning'),
'help' => 'shadowwarning',
'example' => '14'
],
[
'name' => 'shadowAccount_ignoreExpire',
'description' => _('Password expiration'),
'help' => 'shadowinactive',
'example' => '7'
],
[
'name' => 'shadowAccount_minAge',
'description' => _('Minimum password age'),
'help' => 'shadowmin',
'example' => '1'
],
[
'name' => 'shadowAccount_maxAge',
'description' => _('Maximum password age'),
'help' => 'shadowmax',
'example' => '365'
],
[
'name' => 'shadowAccount_expireDate',
'description' => _('Account expiration date'),
'help' => 'shadowexpire',
'example' => '17-07-2011'
],
[
'name' => 'shadowAccount_lastChange',
'description' => _('Last password change'),
'help' => 'shadowlastchange',
'example' => '17-07-2011'
]
];
// self service fields
$return['selfServiceFieldSettings'] = [
'shadowLastChange' => _('Last password change (read-only)'),
'shadowExpire' => _('Account expiration date (read-only)')
];
return $return;
}
/**
* {@inheritDoc}
*/
public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
$attributesToIgnore = array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, self::ATTRIBUTES_TO_IGNORE_ON_COPY);
parent::loadAttributesFromAccountCopy($ldapAttributes, $attributesToIgnore);
}
/**
* Returns a list of modifications which have to be made to the LDAP account.
*
* @return array list of modifications
* <br>This function returns an array with 3 entries:
* <br>array( DN1 ('add' => array($attr), 'remove' => array($attr), 'modify' => array($attr)), DN2 .... )
* <br>DN is the DN to change. It may be possible to change several DNs (e.g. create a new user and add him to some groups via attribute memberUid)
* <br>"add" are attributes which have to be added to LDAP entry
* <br>"remove" are attributes which have to be removed from LDAP entry
* <br>"modify" are attributes which have to been modified in LDAP entry
* <br>"info" are values with informational value (e.g. to be used later by pre/postModify actions)
*/
function save_attributes() {
if (!in_array('shadowAccount', $this->attributes['objectClass']) && !in_array('shadowAccount', $this->orig['objectClass'])) {
// skip saving if the extension was not added/modified
return [];
}
return parent::save_attributes();
}
/**
* Processes user input of the primary module page.
* It checks if all input values are correct and updates the associated LDAP attributes.
*
* @return array list of info/error messages
*/
function process_attributes() {
if (isset($_POST['form_subpage_shadowAccount_attributes_remObjectClass'])) {
$this->attributes['objectClass'] = array_delete(['shadowAccount'], $this->attributes['objectClass']);
if (isset($this->attributes['shadowmin'])) {
unset($this->attributes['shadowmin']);
}
if (isset($this->attributes['shadowmax'])) {
unset($this->attributes['shadowmax']);
}
if (isset($this->attributes['shadowwarning'])) {
unset($this->attributes['shadowwarning']);
}
if (isset($this->attributes['shadowinactive'])) {
unset($this->attributes['shadowinactive']);
}
if (isset($this->attributes['shadowlastchange'])) {
unset($this->attributes['shadowlastchange']);
}
if (isset($this->attributes['shadowexpire'])) {
unset($this->attributes['shadowexpire']);
}
if (isset($this->attributes['shadowflag'])) {
unset($this->attributes['shadowflag']);
}
return [];
}
if (!in_array('shadowAccount', $this->attributes['objectClass'])) {
return [];
}
$errors = [];
// Load attributes
$this->attributes['shadowmin'][0] = $_POST['shadowmin'];
$this->attributes['shadowmax'][0] = $_POST['shadowmax'];
$this->attributes['shadowwarning'][0] = $_POST['shadowwarning'];
$this->attributes['shadowinactive'][0] = $_POST['shadowinactive'];
if (!get_preg($this->attributes['shadowmin'][0], 'digit')) {
$errors[] = $this->messages['shadowmin'][0];
}
if (!get_preg($this->attributes['shadowmax'][0], 'digit')) {
$errors[] = $this->messages['shadowmax'][0];
}
if ($this->attributes['shadowmin'][0] > $this->attributes['shadowmax'][0]) {
$errors[] = $this->messages['shadow_cmp'][0];
}
if (!get_preg($this->attributes['shadowinactive'][0], 'digit2')) {
$errors[] = $this->messages['inactive'][0];
}
if (!get_preg($this->attributes['shadowwarning'][0], 'digit')) {
$errors[] = $this->messages['shadowwarning'][0];
}
if (isset($_POST['form_subpage_shadowAccount_attributes_expirePassword']) && isset($this->attributes['shadowmax'][0]) && ($this->attributes['shadowmax'][0] != 0)) {
$this->attributes['shadowlastchange'][0] = intval(time() / 3600 / 24) - $this->attributes['shadowmax'][0] - 1;
}
return $errors;
}
/**
* This function will create the meta HTML code to show a page with all attributes.
*
* @return array meta HTML code
*/
function display_html_attributes() {
if (isset($_POST['form_subpage_shadowAccount_attributes_addObjectClass'])) {
$this->attributes['objectClass'][] = 'shadowAccount';
}
$return = new htmlResponsiveRow();
if (in_array('shadowAccount', $this->attributes['objectClass'])) {
$pwdWarnInput = $this->addSimpleInputTextField($return, 'shadowwarning', _('Password warning'));
$pwdWarnInput->setType('number');
$pwdExpInput = $this->addSimpleInputTextField($return, 'shadowinactive', _('Password expiration'));
$pwdExpInput->setType('number');
$minAgeInput = $this->addSimpleInputTextField($return, 'shadowmin', _('Minimum password age'));
$minAgeInput->setType('number');
$maxAgeInput = $this->addSimpleInputTextField($return, 'shadowmax', _('Maximum password age'));
$maxAgeInput->setType('number');
$expirationDate = " - ";
if (isset($this->attributes['shadowexpire'][0])) {
$shAccExpirationDate = $this->attributes['shadowexpire'][0];
$date = new DateTime('@' . $shAccExpirationDate * 3600 * 24, new DateTimeZone('UTC'));
$expirationDate = $date->format('d.m.Y');
}
$return->addLabel(new htmlOutputText(_('Account expiration date')));
$expireTable = new htmlGroup();
$expireTable->addElement(new htmlOutputText($expirationDate, false));
$expireTable->addElement(new htmlAccountPageButton('shadowAccount', 'expire', 'open', 'edit-document.svg', true, _('Change')));
$expireTable->addElement(new htmlHelpLink('shadowexpire'));
$return->addField($expireTable);
$pwdChangeDate = " - ";
if (isset($this->attributes['shadowlastchange'][0])) {
$shPwdChangeDate = $this->attributes['shadowlastchange'][0];
$date = new DateTime('@' . $shPwdChangeDate * 3600 * 24, new DateTimeZone('UTC'));
$pwdChangeDate = $date->format('d.m.Y');
}
$return->addLabel(new htmlOutputText(_('Last password change')));
$pwdChangeTable = new htmlGroup();
$pwdChangeTable->addElement(new htmlOutputText($pwdChangeDate, false));
$pwdChangeTable->addElement(new htmlAccountPageButton('shadowAccount', 'pwdChange', 'open', 'edit-document.svg', true, _('Change')));
if (isset($this->attributes['shadowmax'][0]) && ($this->attributes['shadowmax'][0] != '')) {
$pwdChangeTable->addElement(new htmlAccountPageButton('shadowAccount', 'attributes', 'expirePassword', _('Force password change')));
}
$pwdChangeTable->addElement(new htmlHelpLink('shadowlastchange'));
$return->addField($pwdChangeTable);
$return->addVerticalSpacer('2rem');
$remButton = new htmlAccountPageButton('shadowAccount', 'attributes', 'remObjectClass', _('Remove Shadow account extension'));
$remButton->setCSSClasses(['lam-danger']);
$return->add($remButton, 12, 12, 12, 'text-center');
}
else {
$return->add(new htmlAccountPageButton('shadowAccount', 'attributes', 'addObjectClass', _('Add Shadow account extension')));
}
return $return;
}
/**
* Processes user input of the expiration page.
* It checks if all input values are correct and updates the associated LDAP attributes.
*
* @return array list of info/error messages
*/
function process_expire() {
$errors = [];
// set expiration date
if (isset($_POST['form_subpage_shadowAccount_attributes_change']) && !empty($_POST['shadowexpire'])) {
$date = DateTime::createFromFormat('d.m.Y', $_POST['shadowexpire'], new DateTimeZone('UTC'));
$this->attributes['shadowexpire'][0] = intval($date->format('U') / 3600 / 24);
// sync other modules
if (isset($_POST['syncSamba']) && ($_POST['syncSamba'] == 'on')) {
$this->getAccountContainer()->getAccountModule('sambaSamAccount')->setExpirationDate(
$_POST['shadowExpire_yea'], $_POST['shadowExpire_mon'], $_POST['shadowExpire_day']);
}
if (isset($_POST['syncWindows']) && ($_POST['syncWindows'] == 'on')) {
$this->getAccountContainer()->getAccountModule('windowsUser')->setExpirationDate(
$_POST['shadowExpire_yea'], $_POST['shadowExpire_mon'], $_POST['shadowExpire_day']);
}
if (isset($_POST['syncHeimdal']) && ($_POST['syncHeimdal'] == 'on')) {
$this->getAccountContainer()->getAccountModule('heimdalKerberos')->setExpirationDate(
$_POST['shadowExpire_yea'], $_POST['shadowExpire_mon'], $_POST['shadowExpire_day']);
}
if (isset($_POST['syncMIT']) && ($_POST['syncMIT'] == 'on')) {
$this->getAccountContainer()->getAccountModule('mitKerberos')->setExpirationDate(
$_POST['shadowExpire_yea'], $_POST['shadowExpire_mon'], $_POST['shadowExpire_day']);
}
if (isset($_POST['syncMITStructural']) && ($_POST['syncMITStructural'] == 'on')) {
$this->getAccountContainer()->getAccountModule('mitKerberosStructural')->setExpirationDate(
$_POST['shadowExpire_yea'], $_POST['shadowExpire_mon'], $_POST['shadowExpire_day']);
}
}
// remove expiration date
elseif (isset($_POST['form_subpage_shadowAccount_attributes_del'])
|| (empty($_POST['shadowexpire']) && isset($this->attributes['shadowexpire']))) {
unset($this->attributes['shadowexpire']);
// sync other modules
if (isset($_POST['syncWindows']) && ($_POST['syncWindows'] == 'on')) {
$this->getAccountContainer()->getAccountModule('windowsUser')->setExpirationDate(
null, null, null);
}
if (isset($_POST['syncSamba']) && ($_POST['syncSamba'] == 'on')) {
$this->getAccountContainer()->getAccountModule('sambaSamAccount')->setExpirationDate(
null, null, null);
}
if (isset($_POST['syncHeimdal']) && ($_POST['syncHeimdal'] == 'on')) {
$this->getAccountContainer()->getAccountModule('heimdalKerberos')->setExpirationDate(
null, null, null);
}
if (isset($_POST['syncMIT']) && ($_POST['syncMIT'] == 'on')) {
$this->getAccountContainer()->getAccountModule('mitKerberos')->setExpirationDate(
null, null, null);
}
if (isset($_POST['syncMITStructural']) && ($_POST['syncMITStructural'] == 'on')) {
$this->getAccountContainer()->getAccountModule('mitKerberosStructural')->setExpirationDate(
null, null, null);
}
}
return $errors;
}
/**
* This function will create the meta HTML code to show a page with the expiration date.
*
* @return array meta HTML code
*/
function display_html_expire() {
$return = new htmlResponsiveRow();
$shAccExpirationDate = time() / (3600 * 24) + 365;
if (isset($this->attributes['shadowexpire'][0])) {
$shAccExpirationDate = $this->attributes['shadowexpire'][0];
}
$date = new DateTime('@' . $shAccExpirationDate * 3600 * 24, new DateTimeZone('UTC'));
$dateField = new htmlResponsiveInputField(_('Account expiration date'), 'shadowexpire', $date->format('d.m.Y'), 'shadowexpire');
$dateField->showCalendar('d.m.Y');
$return->add($dateField);
if ($this->getAccountContainer()->getAccountModule('sambaSamAccount') != null) {
$return->add(new htmlResponsiveInputCheckbox('syncSamba', false, _('Set also for Samba 3')));
}
if ($this->getAccountContainer()->getAccountModule('windowsUser') != null) {
$return->add(new htmlResponsiveInputCheckbox('syncWindows', false, _('Set also for Windows')));
}
if ($this->getAccountContainer()->getAccountModule('heimdalKerberos') != null) {
$return->add(new htmlResponsiveInputCheckbox('syncHeimdal', false, _('Set also for Kerberos')));
}
if ($this->getAccountContainer()->getAccountModule('mitKerberos') != null) {
$return->add(new htmlResponsiveInputCheckbox('syncMIT', false, _('Set also for Kerberos')));
}
if ($this->getAccountContainer()->getAccountModule('mitKerberosStructural') != null) {
$return->add(new htmlResponsiveInputCheckbox('syncMITStructural', false, _('Set also for Kerberos')));
}
$return->addVerticalSpacer('2rem');
$buttonTable = new htmlGroup();
$buttonTable->addElement(new htmlAccountPageButton('shadowAccount', 'attributes', 'change', _('Change')));
if (isset($this->attributes['shadowexpire'][0])) {
$buttonTable->addElement(new htmlSpacer('0.5rem', null));
$buttonTable->addElement(new htmlAccountPageButton('shadowAccount', 'attributes', 'del', _('Remove')));
}
$buttonTable->addElement(new htmlSpacer('0.5rem', null));
$buttonTable->addElement(new htmlAccountPageButton('shadowAccount', 'attributes', 'back', _('Cancel')));
$return->add($buttonTable, 12, 12, 12, 'text-center');
return $return;
}
/**
* Processes user input of the last password change page.
* It checks if all input values are correct and updates the associated LDAP attributes.
*
* @return array list of info/error messages
*/
function process_pwdChange() {
$errors = [];
// set last change date
if (isset($_POST['form_subpage_shadowAccount_attributes_changePwdChange']) && !empty($_POST['shadowlastchange'])) {
$date = DateTime::createFromFormat('d.m.Y', $_POST['shadowlastchange'], new DateTimeZone('UTC'));
$this->attributes['shadowlastchange'][0] = intval($date->format('U') / 3600 / 24);
}
// remove last change date
elseif (isset($_POST['form_subpage_shadowAccount_attributes_delPwdChange'])
|| (empty($_POST['shadowlastchange']) && isset($this->attributes['shadowlastchange']))) {
unset($this->attributes['shadowlastchange']);
}
return $errors;
}
/**
* This function will create the meta HTML code to show a page with the password change date.
*
* @return array meta HTML code
*/
function display_html_pwdChange() {
$return = new htmlResponsiveRow();
$shLastChange = time() / (3600 * 24);
if (isset($this->attributes['shadowlastchange'][0])) {
$shLastChange = $this->attributes['shadowlastchange'][0];
}
$date = new DateTime('@' . $shLastChange * 3600 * 24, new DateTimeZone('UTC'));
$dateField = new htmlResponsiveInputField(_('Last password change'), 'shadowlastchange', $date->format('d.m.Y'), 'shadowlastchange');
$dateField->showCalendar('d.m.Y');
$return->add($dateField);
$return->addVerticalSpacer('2rem');
$buttonTable = new htmlGroup();
$buttonTable->addElement(new htmlAccountPageButton('shadowAccount', 'attributes', 'changePwdChange', _('Change')));
if (isset($this->attributes['shadowlastchange'][0])) {
$buttonTable->addElement(new htmlSpacer('0.5rem', null));
$buttonTable->addElement(new htmlAccountPageButton('shadowAccount', 'attributes', 'delPwdChange', _('Remove')));
}
$buttonTable->addElement(new htmlSpacer('0.5rem', null));
$buttonTable->addElement(new htmlAccountPageButton('shadowAccount', 'attributes', 'back', _('Cancel')));
$return->add($buttonTable, 12, 12, 12, 'text-center');
return $return;
}
/**
* {@inheritDoc}
* @see baseModule::get_pdfEntries()
*/
function get_pdfEntries($pdfKeys, $typeId) {
$timeZone = getTimeZone();
$shadowLastChange = '';
if (!empty($this->attributes['shadowlastchange'][0])) {
$time = new DateTime('@' . $this->attributes['shadowlastchange'][0] * 24 * 3600, $timeZone);
$shadowLastChange = $time->format('d.m.Y');
}
$shadowExpire = '';
if (!empty($this->attributes['shadowexpire'][0])) {
$time = new DateTime('@' . $this->attributes['shadowexpire'][0] * 24 * 3600);
$shadowExpire = $time->format('d.m.Y');
}
$return = [];
$this->addPDFKeyValue($return, 'shadowLastChange', _('Last password change'), $shadowLastChange);
$this->addPDFKeyValue($return, 'shadowExpire', _('Account expiration date'), $shadowExpire);
$this->addSimplePDFField($return, 'shadowWarning', _('Password warning'));
$this->addSimplePDFField($return, 'shadowInactive', _('Password expiration'));
$this->addSimplePDFField($return, 'shadowMinAge', _('Minimum password age'), 'shadowmin');
$this->addSimplePDFField($return, 'shadowMaxAge', _('Maximum password age'), 'shadowmax');
return $return;
}
/**
* {@inheritDoc}
* @see baseModule::build_uploadAccounts()
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
// add object class
if (!in_array("shadowAccount", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "shadowAccount";
}
// password warning
$this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'shadowAccount_warning', 'shadowwarning',
'digit', $this->messages['shadowwarning'][1], $messages);
// password expire ignoration
$this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'shadowAccount_ignoreExpire', 'shadowinactive',
'digit2', $this->messages['inactive'][1], $messages);
// password minAge
$this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'shadowAccount_minAge', 'shadowmin',
'digit', $this->messages['shadowmin'][1], $messages);
// password maxAge
$this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'shadowAccount_maxAge', 'shadowmax',
'digit', $this->messages['shadowmax'][1], $messages);
// minAge <= maxAge
if ((($rawAccounts[$i][$ids['shadowAccount_minAge']] != '') || ($rawAccounts[$i][$ids['shadowAccount_maxAge']] != '')) && // if at least one is set
(($rawAccounts[$i][$ids['shadowAccount_minAge']] == '') || ($rawAccounts[$i][$ids['shadowAccount_maxAge']] == '') || // and one is not set
($rawAccounts[$i][$ids['shadowAccount_minAge']] > $rawAccounts[$i][$ids['shadowAccount_maxAge']]))) { // or minAge > maxAge
$errMsg = $this->messages['shadow_cmp'][1];
$errMsg[] = [$i];
$messages[] = $errMsg;
}
// expiration date
if ($rawAccounts[$i][$ids['shadowAccount_expireDate']] != '') {
if (get_preg($rawAccounts[$i][$ids['shadowAccount_expireDate']], 'date')) {
$parts = explode('-', $rawAccounts[$i][$ids['shadowAccount_expireDate']]);
$date = DateTime::createFromFormat('j.n.Y', $parts[0] . '.' . $parts[1] . '.' . $parts[2], new DateTimeZone('UTC'));
$partialAccounts[$i]['shadowexpire'][] = intval($date->format('U') / 3600 / 24);
}
else {
$errMsg = $this->messages['shadow_expireDate'][0];
$errMsg[] = [$i];
$messages[] = $errMsg;
}
}
// shadow last change
if ($rawAccounts[$i][$ids['shadowAccount_lastChange']] != '') {
if (get_preg($rawAccounts[$i][$ids['shadowAccount_lastChange']], 'date')) {
$parts = explode('-', $rawAccounts[$i][$ids['shadowAccount_lastChange']]);
$date = DateTime::createFromFormat('j.n.Y', $parts[0] . '.' . $parts[1] . '.' . $parts[2], new DateTimeZone('UTC'));
$partialAccounts[$i]['shadowlastchange'][] = intval($date->format('U') / 3600 / 24);
}
else {
$errMsg = $this->messages['shadow_lastChange'][0];
$errMsg[] = [$i];
$messages[] = $errMsg;
}
}
else {
$date = new DateTime('now', new DateTimeZone('UTC'));
$partialAccounts[$i]['shadowlastchange'][] = intval($date->format('U') / 3600 / 24);
}
}
return $messages;
}
/**
* Loads the values of an account profile into internal variables.
*
* @param array $profile hash array with profile values (identifier => value)
*/
function load_profile($profile) {
// profile mappings in meta data
parent::load_profile($profile);
// add extension
if (isset($profile['shadowAccount_addExt'][0]) && ($profile['shadowAccount_addExt'][0] == "true")) {
if (!in_array('shadowAccount', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'shadowAccount';
}
}
// expiration date
if (!empty($profile['shadowAccount_shadowExpire_day'][0])) {
$day = $profile['shadowAccount_shadowExpire_day'][0];
$mon = $profile['shadowAccount_shadowExpire_mon'][0];
$year = $profile['shadowAccount_shadowExpire_yea'][0];
if (!(($day == '-') && ($mon == '-') && ($year == '-'))) {
$day = ($day == '-') ? 1 : $day;
$mon = ($mon == '-') ? 1 : $mon;
$year = ($year == '-') ? 2030 : $year;
$this->setExpirationDate($year, $mon, $day);
}
}
}
/**
* This method specifies if a module manages password attributes.
* @return boolean true if this module manages password attributes
* @see passwordService::managesPasswordAttributes
*
*/
public function managesPasswordAttributes() {
// only listen to password changes
return false;
}
/**
* Specifies if this module supports to force that a user must change his password on next login.
*
* @return boolean force password change supported
*/
public function supportsForcePasswordChange() {
return true;
}
/**
* This function is called whenever the password should be changed. Account modules
* must change their password attributes only if the modules list contains their module name.
*
* @param String $password new password
* @param $modules list of modules for which the password should be changed
* @param boolean $forcePasswordChange force the user to change his password at next login
* @return array list of error messages if any as parameter array for StatusMessage
* e.g. return array(array('ERROR', 'Password change failed.'))
* @see passwordService::passwordChangeRequested
*/
public function passwordChangeRequested($password, $modules, $forcePasswordChange) {
// update password timestamp when Unix password was updated
if (!in_array('posixAccount', $modules)) {
return [];
}
if (in_array_ignore_case('shadowAccount', $this->attributes['objectClass'])) {
$this->attributes['shadowlastchange'][0] = intval(time() / 3600 / 24);
if ($forcePasswordChange && isset($this->attributes['shadowmax'][0]) && ($this->attributes['shadowmax'][0] != 0)) {
$this->attributes['shadowlastchange'][0] = intval(time() / 3600 / 24) - $this->attributes['shadowmax'][0] - 1;
}
}
return [];
}
/**
* Sets the expiration date of this account.
* If all parameters are null the expiration date will be removed.
*
* @param String $year year (e.g. 2040)
* @param String $month month (e.g. 8)
* @param String $day day (e.g. 27)
*/
public function setExpirationDate($year, $month, $day) {
if (($year == null) && ($month == null) && ($day == null)) {
unset($this->attributes['shadowexpire']);
return;
}
$date = DateTime::createFromFormat('j.n.Y', $day . '.' . $month . '.' . $year, new DateTimeZone('UTC'));
$this->attributes['shadowexpire'][0] = intval($date->format('U') / 3600 / 24);
}
/**
* Sets the last password change date of this account.
* If all parameters are null the password change date will be removed.
*
* @param String $year year (e.g. 2040)
* @param String $month month (e.g. 8)
* @param String $day day (e.g. 27)
*/
public function setLastChangeDate($year, $month, $day) {
if (($year == null) && ($month == null) && ($day == null)) {
unset($this->attributes['shadowlastchange']);
return;
}
$date = DateTime::createFromFormat('j.n.Y', $day . '.' . $month . '.' . $year, new DateTimeZone('UTC'));
$this->attributes['shadowlastchange'][0] = intval($date->format('U') / 3600 / 24);
}
/**
* Returns the meta HTML code for each input field.
* format: array(<field1> => array(<META HTML>), ...)
* It is not possible to display help links.
*
* @param array $fields list of active fields
* @param array $attributes attributes of LDAP account
* @param boolean $passwordChangeOnly indicates that the user is only allowed to change his password and no LDAP content is readable
* @param array $readOnlyFields list of read-only fields
* @return array list of meta HTML elements (field name => htmlResponsiveRow)
*/
function getSelfServiceOptions($fields, $attributes, $passwordChangeOnly, $readOnlyFields) {
$return = [];
if ($passwordChangeOnly) {
return $return; // no fields as long no LDAP content can be read
}
if (in_array('shadowLastChange', $fields)) {
$shadowLastChange = '';
if (isset($attributes['shadowlastchange'][0])) {
$date = new DateTime('@' . $attributes['shadowlastchange'][0] * 3600 * 24, new DateTimeZone('UTC'));
$shadowLastChange = $date->format('d.m.Y');
}
$row = new htmlResponsiveRow();
$row->addLabel(new htmlOutputText($this->getSelfServiceLabel('shadowLastChange', _('Last password change'))));
$row->addField(new htmlOutputText($shadowLastChange));
$return['shadowLastChange'] = $row;
}
if (in_array('shadowExpire', $fields)) {
$shadowExpire = '';
if (isset($attributes['shadowexpire'][0])) {
$date = new DateTime('@' . $attributes['shadowexpire'][0] * 3600 * 24, new DateTimeZone('UTC'));
$shadowExpire = $date->format('d.m.Y');
}
$row = new htmlResponsiveRow();
$row->addLabel(new htmlOutputText($this->getSelfServiceLabel('shadowExpire', _('Account expiration date'))));
$row->addField(new htmlOutputText($shadowExpire));
$return['shadowExpire'] = $row;
}
return $return;
}
/**
* Returns a list of jobs that can be run.
*
* @param LAMConfig $config configuration
* @return array list of jobs
*/
public function getSupportedJobs(&$config) {
return [
new ShadowAccountPasswordNotifyJob(),
new ShadowAccountExpirationCleanupJob(),
new ShadowAccountExpirationNotifyJob()
];
}
/**
* Returns if the given account is expired.
*
* @param array $attrs LDAP attributes
* @return bool expired
*/
public static function isAccountExpired($attrs) {
if (empty($attrs['shadowexpire'][0])) {
return false;
}
$time = new DateTime('@' . $attrs['shadowexpire'][0] * 24 * 3600, new DateTimeZone('UTC'));
$now = new DateTime('now', getTimeZone());
return ($time < $now);
}
/**
* Returns if the given password is expired.
*
* @param array $attrs LDAP attributes
* @return bool expired
*/
public static function isPasswordExpired($attrs) {
if (empty($attrs['shadowlastchange'][0]) || empty($attrs['shadowmax'][0])) {
return false;
}
if (($attrs['shadowlastchange'][0] < 1) || ($attrs['shadowmax'][0] < 1)) {
return false;
}
$time = new DateTime('@' . $attrs['shadowlastchange'][0] * 24 * 3600, new DateTimeZone('UTC'));
$time = $time->add(new DateInterval('P' . $attrs['shadowmax'][0] . 'D'));
if (!empty($attrs['shadowinactive'][0]) && ($attrs['shadowinactive'][0] > 0)) {
$time = $time->add(new DateInterval('P' . $attrs['shadowinactive'][0] . 'D'));
}
$now = new DateTime('now', getTimeZone());
return ($time < $now);
}
/**
* @inheritDoc
*/
public function supportsPasswordQuickChangePage(): bool {
return true;
}
/**
* @inheritDoc
*/
public function addPasswordQuickChangeAccountDetails(htmlResponsiveRow $row): void {
// no details
}
/**
* @inheritDoc
*/
public function getPasswordQuickChangeOptions(): array {
$options = [];
if (in_array_ignore_case('shadowAccount', $this->attributes['objectClass'])) {
$options[] = new PasswordQuickChangeOption('forcePasswordChangeUnix', _('Force Unix password change'), isPasswordChangeByDefault());
}
return $options;
}
/**
* @inheritDoc
*/
public function getPasswordQuickChangeChanges(string $password): array {
if (!in_array_ignore_case('shadowAccount', $this->attributes['objectClass'])) {
return [];
}
$attrs = [];
if (isset($this->attributes['shadowlastchange'][0]) && isset($_POST['updateUnixPwd'])) {
$attrs['shadowlastchange'][0] = intval(time() / 3600 / 24);
}
if (isset($_POST['forcePasswordChangeUnix'])
&& isset($this->attributes['shadowmax'][0])
&& ($this->attributes['shadowmax'][0] != 0)) {
$attrs['shadowlastchange'][0] = intval(time() / 3600 / 24) - $this->attributes['shadowmax'][0] - 1;
}
return $attrs;
}
/**
* @inheritDoc
*/
public function getPasswordQuickChangePasswordStrengthUserName(): ?string {
return null;
}
/**
* @inheritDoc
*/
public function getPasswordQuickChangePasswordStrengthAttributes(): array {
return [];
}
/**
* @inheritDoc
*/
public function getPasswordQuickChangeIsPasswordInHistory(string $password): bool {
return false;
}
/**
* @inheritDoc
*/
public function getAccountStatusDetails(ConfiguredType $type, ?array &$attributes): array {
if ($attributes === null) {
$attributes = $this->attributes;
}
$details = [];
if (self::isAccountExpired($attributes)) {
$details[] = AccountStatusDetails::newPartiallyExpired(_('Shadow') . ': ' . _('Account expiration'), self::STATUS_ACCOUNT_EXPIRED);
}
if (self::isPasswordExpired($attributes)) {
$details[] = AccountStatusDetails::newPartiallyExpired(_('Shadow') . ': ' . _('Password expiration'), self::STATUS_PASSWORD_EXPIRED);
}
return $details;
}
/**
* @inheritDoc
*/
public function getAccountStatusRequiredAttributes(ConfiguredType $type): array {
return ['shadowexpire', 'shadowlastchange', 'shadowmax', 'shadowinactive'];
}
/**
* @inheritDoc
*/
public function getAccountStatusPossibleLockOptions(ConfiguredType $type, ?array &$attributes): array {
if ($attributes === null) {
$attributes = $this->attributes;
}
$options = [];
if (!self::isAccountExpired($attributes)) {
$options[] = AccountStatusDetails::newPartiallyExpired(_('Shadow') . ': ' . _('Account expiration'), self::STATUS_ACCOUNT_EXPIRED);
}
if (!empty($attributes['shadowmax'][0]) && !self::isPasswordExpired($attributes)) {
$options[] = AccountStatusDetails::newPartiallyExpired(_('Shadow') . ': ' . _('Password expiration'), self::STATUS_PASSWORD_EXPIRED);
}
return $options;
}
/**
* @inheritDoc
*/
public function accountStatusPerformLock(ConfiguredType $type, ?array &$attributes, array $lockIds): void {
if ($attributes === null) {
$attributes = &$this->attributes;
}
if (in_array(self::STATUS_ACCOUNT_EXPIRED, $lockIds)) {
$attributes['shadowexpire'][0] = '1';
}
if (in_array(self::STATUS_PASSWORD_EXPIRED, $lockIds)) {
$inactive = !empty($attributes['shadowinactive'][0]) ? $attributes['shadowinactive'][0] : 0;
$attributes['shadowlastchange'][0] = intval(time() / 3600 / 24) - $attributes['shadowmax'][0] - $inactive - 1;
}
}
/**
* @inheritDoc
*/
public function accountStatusPerformUnlock(ConfiguredType $type, ?array &$attributes, array $lockIds): void {
if ($attributes === null) {
$attributes = &$this->attributes;
}
if (in_array(self::STATUS_ACCOUNT_EXPIRED, $lockIds)) {
unset($attributes['shadowexpire']);
}
if (in_array(self::STATUS_PASSWORD_EXPIRED, $lockIds)) {
$attributes['shadowlastchange'][0] = intval(time() / 3600 / 24);
}
}
/**
* @inheritDoc
*/
public function getListFilterFunction(string $attributeName): ?callable {
if (($attributeName == 'shadowexpire') || ($attributeName == 'shadowlastchange')) {
return function(?array $values, ?string $filterValue): bool {
$regex = str_replace(['*'], ['.*'], $filterValue);
$regex = '/' . $regex . '/i';
if (!empty($values[0])) {
$time = new DateTime('@' . $values[0] * 24 * 3600, getTimeZone());
$formattedTime = $time->format('d.m.Y');
return preg_match($regex, $formattedTime);
}
return false;
};
}
return null;
}
/**
* @inheritDoc
*/
public function getListRenderFunction(string $attributeName): ?callable {
if (($attributeName === 'shadowexpire') || ($attributeName === 'shadowlastchange')) {
return function(array $entry, string $attribute): ?htmlElement {
if (!empty($entry[$attribute][0])) {
$time = new DateTime('@' . $entry[$attribute][0] * 24 * 3600, getTimeZone());
return new htmlOutputText($time->format('d.m.Y'));
}
return null;
};
}
return null;
}
/**
* @inheritDoc
*/
public function getListAttributeDescriptions(ConfiguredType $type): array {
return [
'shadowlastchange' => _('Last password change'),
'shadowwarning' => _('Password warning'),
'shadowinactive' => _('Password expiration'),
'shadowexpire' => _('Account expiration date'),
'shadowminage' => _('Minimum password age'),
'shadowmaxage' => _('Maximum password age'),
];
}
}
if (interface_exists('\LAM\JOB\Job', false)) {
include_once __DIR__ . '/../passwordExpirationJob.inc';
/**
* Job to notify users about password expiration.
*
* @package jobs
*/
class ShadowAccountPasswordNotifyJob extends \LAM\JOB\PasswordExpirationJob {
/**
* Returns the alias name of the job.
*
* @return String name
*/
public function getAlias() {
return _('Shadow') . ': ' . _('Notify users about password expiration');
}
/**
* {@inheritDoc}
* @see \LAM\JOB\PasswordExpirationJob::getConfigOptions()
*/
public function getConfigOptions($jobID) {
$container = parent::getConfigOptions($jobID);
$container->add(new htmlResponsiveInputCheckbox($this->getConfigPrefix() . '_addWarningPeriod' . $jobID, true, _('Add expiration warning time'), ['cronAddWarningPeriod', 'shadowAccount']));
return $container;
}
/**
* Searches for users in LDAP.
*
* @param String $jobID unique job identifier
* @param array $options config options (name => value)
* @return array list of user attributes
*/
protected function findUsers($jobID, $options) {
// read users
$sysattrs = [$_SESSION['cfgMain']->getMailAttribute(), 'shadowlastchange', 'shadowwarning', 'shadowmax', 'userPassword'];
$attrs = $this->getAttrWildcards($jobID, $options);
$attrs = array_values(array_unique(array_merge($attrs, $sysattrs)));
return searchLDAPByFilter('(&(shadowlastchange=*)(shadowmax=*)(' . $_SESSION['cfgMain']->getMailAttribute() . '=*))', $attrs, ['user']);
}
/**
* Checks if a user needs to change his password.
*
* @param integer $jobID job ID
* @param array $options job settings
* @param PDO $pdo PDO
* @param DateTime $now current time
* @param array $policyOptions list of max age values (policy DN => maxAge)
* @param array $user user attributes
* @param boolean $isDryRun just do a dry run, nothing is modified
*/
protected function checkSingleUser($jobID, $options, &$pdo, $now, $policyOptions, $user, $isDryRun) {
// skip if user is locked
if (!empty($user['userpassword'][0]) && !pwd_is_enabled($user['userpassword'][0])) {
$this->jobResultLog->logDebug($user['dn'] . ' is locked.');
return;
}
if ($user['shadowmax'][0] < 1) {
$this->jobResultLog->logDebug($user['dn'] . ' does not expire.');
return;
}
// calculate time when password expires
$lastPwdTimeUnix = $user['shadowlastchange'][0] * 3600 * 24;
$lastPwdTime = new DateTime('@' . $lastPwdTimeUnix, new DateTimeZone('UTC'));
$this->jobResultLog->logDebug("Last password change on " . $lastPwdTime->format('Y-m-d'));
$numDaysToWarn = $options[$this->getConfigPrefix() . '_mailNotificationPeriod' . $jobID][0];
$addPasswordWarningTime = !isset($options[$this->getConfigPrefix() . '_addWarningPeriod' . $jobID][0])
|| ($options[$this->getConfigPrefix() . '_addWarningPeriod' . $jobID][0] === 'true');
if ($addPasswordWarningTime && !empty($user['shadowwarning'][0]) && ($user['shadowwarning'][0] > 0)) {
$numDaysToWarn += $user['shadowwarning'][0];
}
$this->jobResultLog->logDebug("Number of days before warning " . $numDaysToWarn);
$numDaysToExpire = $user['shadowmax'][0];
$expireTime = $lastPwdTime->add(new DateInterval('P' . $numDaysToExpire . 'D'));
$this->jobResultLog->logDebug("Password expires on " . $expireTime->format('Y-m-d'));
// skip already expired accounts
if ($expireTime <= $now) {
$this->jobResultLog->logDebug($user['dn'] . ' already expired');
return;
}
// calculate time of notification
$notifyTime = clone $expireTime;
$notifyTime->sub(new DateInterval('P' . $numDaysToWarn . 'D'));
$notifyTime->setTimeZone(getTimeZone());
$this->jobResultLog->logDebug("Password notification on " . $notifyTime->format('Y-m-d H:i'));
// skip if notification is in the future
if ($notifyTime > $now) {
$this->jobResultLog->logDebug($user['dn'] . ' does not need notification yet.');
return;
}
$dbLastChange = $this->getDBLastPwdChangeTime($jobID, $pdo, $user['dn']);
// skip entries where mail was already sent
if ($dbLastChange == $user['shadowlastchange'][0]) {
$this->jobResultLog->logDebug($user['dn'] . ' was already notified.');
return;
}
if ($isDryRun) {
// no action for dry run
$this->jobResultLog->logInfo('Not sending email to ' . $user['dn'] . ' because of dry run.');
return;
}
// send email
$success = $this->sendMail($options, $jobID, $user, $expireTime);
// update DB if mail was sent successfully
if ($success) {
$this->setDBLastPwdChangeTime($jobID, $pdo, $user['dn'], $user['shadowlastchange'][0]);
}
}
}
/**
* Job to notify users about account expiration.
*
* @package jobs
*/
class ShadowAccountExpirationNotifyJob extends \LAM\JOB\PasswordExpirationJob {
/**
* Returns the alias name of the job.
*
* @return String name
*/
public function getAlias() {
return _('Shadow') . ': ' . _('Notify users about account expiration');
}
/**
* {@inheritDoc}
* @see \LAM\JOB\PasswordExpirationJob::getDescription()
*/
public function getDescription() {
return _('This job sends out emails to inform your users that their account will expire soon.');
}
/**
* Searches for users in LDAP.
*
* @param String $jobID unique job identifier
* @param array $options config options (name => value)
* @return array list of user attributes
*/
protected function findUsers($jobID, $options) {
// read users
$sysattrs = [$_SESSION['cfgMain']->getMailAttribute(), 'shadowexpire'];
$attrs = $this->getAttrWildcards($jobID, $options);
$attrs = array_values(array_unique(array_merge($attrs, $sysattrs)));
return searchLDAPByFilter('(&(shadowexpire=*)(' . $_SESSION['cfgMain']->getMailAttribute() . '=*))', $attrs, ['user']);
}
/**
* Checks if a user needs to change his password.
*
* @param integer $jobID job ID
* @param array $options job settings
* @param PDO $pdo PDO
* @param DateTime $now current time
* @param array $policyOptions list of max age values (policy DN => maxAge)
* @param array $user user attributes
* @param boolean $isDryRun just do a dry run, nothing is modified
*/
protected function checkSingleUser($jobID, $options, &$pdo, $now, $policyOptions, $user, $isDryRun) {
$dn = $user['dn'];
$expireTimeUnix = $user['shadowexpire'][0] * 3600 * 24;
$expireTime = new DateTime('@' . $expireTimeUnix, new DateTimeZone('UTC'));
$this->jobResultLog->logDebug("Expiration on " . $expireTime->format('Y-m-d'));
if ($expireTime <= $now) {
$this->jobResultLog->logDebug($dn . ' already expired');
return;
}
$numDaysToWarn = 0;
if (!empty($options[$this->getConfigPrefix() . '_mailNotificationPeriod' . $jobID][0])) {
$numDaysToWarn = $options[$this->getConfigPrefix() . '_mailNotificationPeriod' . $jobID][0];
}
$actionTime = clone $expireTime;
if ($numDaysToWarn != 0) {
$actionTime->sub(new DateInterval('P' . $numDaysToWarn . 'D'));
}
$actionTime->setTimeZone(getTimeZone());
$this->jobResultLog->logDebug("Action time on " . $actionTime->format('Y-m-d'));
if ($actionTime > $now) {
$this->jobResultLog->logDebug($dn . ' does not need notification yet.');
return;
}
$dbLastChange = $this->getDBLastPwdChangeTime($jobID, $pdo, $user['dn']);
// skip entries where mail was already sent
if ($dbLastChange == $user['shadowexpire'][0]) {
$this->jobResultLog->logDebug($dn . ' was already notified.');
return;
}
if ($isDryRun) {
// no action for dry run
$this->jobResultLog->logInfo('Not sending email to ' . $dn . ' because of dry run.');
return;
}
// send email
$success = $this->sendMail($options, $jobID, $user, $expireTime);
// update DB if mail was sent successfully
if ($success) {
$this->setDBLastPwdChangeTime($jobID, $pdo, $dn, $user['shadowexpire'][0]);
}
}
}
/**
* Job to delete or move users on account expiration.
*
* @package jobs
*/
class ShadowAccountExpirationCleanupJob extends \LAM\JOB\AccountExpirationCleanupJob {
/**
* Returns the alias name of the job.
*
* @return String name
*/
public function getAlias() {
return _('Shadow') . ': ' . _('Cleanup expired user accounts');
}
/**
* Returns the description of the job.
*
* @return String description
*/
public function getDescription() {
return _('This job deletes or moves user accounts when they expire.');
}
/**
* Searches for users in LDAP.
*
* @param String $jobID unique job identifier
* @param array $options config options (name => value)
* @return array list of user attributes
*/
protected function findUsers($jobID, $options) {
// read users
$attrs = ['shadowexpire'];
return searchLDAPByFilter('(shadowexpire=*)', $attrs, ['user']);
}
/**
* Checks if a user is expired.
*
* @param integer $jobID job ID
* @param array $options job settings
* @param PDO $pdo PDO
* @param DateTime $now current time
* @param array $policyOptions list of policy options by getPolicyOptions()
* @param array $user user attributes
* @param boolean $isDryRun just do a dry run, nothing is modified
*/
protected function checkSingleUser($jobID, $options, &$pdo, $now, $policyOptions, $user, $isDryRun) {
$expireTimeUnix = $user['shadowexpire'][0] * 3600 * 24;
$expireTime = new DateTime('@' . $expireTimeUnix, new DateTimeZone('UTC'));
$this->jobResultLog->logDebug("Expiration on " . $expireTime->format('Y-m-d'));
$delay = 0;
if (!empty($options[$this->getConfigPrefix() . '_delay' . $jobID][0])) {
$delay = $options[$this->getConfigPrefix() . '_delay' . $jobID][0];
}
$actionTime = clone $expireTime;
if ($delay != 0) {
$actionTime->add(new DateInterval('P' . $delay . 'D'));
}
$actionTime->setTimeZone(getTimeZone());
$this->jobResultLog->logDebug("Action time on " . $actionTime->format('Y-m-d'));
if ($actionTime <= $now) {
$this->performAction($jobID, $options, $user, $isDryRun);
}
}
}
}
|