Debian Codegraph @

lib/modules/sambaSamAccount.inc

raw
1 <?php
2
3 use LAM\REMOTE\Remote;
4 use LAM\TYPES\ConfiguredType;
5 use LDAP\Connection;
6
7 /*
8
9 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
10 Copyright (C) 2003 - 2006 Tilo Lutz
11 2005 - 2026 Roland Gruber
12
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 */
27
28 /**
29 * Manages Samba 3 accounts for users and hosts.
30 *
31 * @package modules
32 *
33 * @author Tilo Lutz
34 * @author Roland Gruber
35 * @author Michael Duergner
36 */
37
38 /** terminals server options */
39
40 include_once(__DIR__ . '/sambaSamAccount/sambaMungedDial.inc');
41
42 /**
43 * Manages the object class "sambaSamAccount" for users and hosts.
44 *
45 * @package modules
46 */
47 class sambaSamAccount extends baseModule implements passwordService, AccountStatusProvider {
48
49 /**
50 * ID for locked account status.
51 */
52 private const STATUS_ACCOUNT_LOCKED = "SAMBA_ACCOUNT_LOCKED";
53
54 /**
55 * ID for locked account status.
56 */
57 private const STATUS_ACCOUNT_DEACTIVATED = "SAMBA_ACCOUNT_DEACTIVATED";
58
59 /**
60 * These attributes will be ignored by default if a new account is copied from an existing one.
61 */
62 private const ATTRIBUTES_TO_IGNORE_ON_COPY = ['sambaSID', 'sambaNTPassword',
63 'sambaPwdLastSet', 'displayName', 'sambaHomePath', 'sambaProfilePath',
64 'sambaPasswordHistory', 'sambaPwdCanChange', 'sambaPwdMustChange', 'sambaKickoffTime',
65 'sambaLogonTime', 'sambaLogoffTime'];
66
67 // Variables
68 /** use no password? */
69 private bool $nopwd = false;
70 /** password does not expire? */
71 private bool $noexpire = true;
72 /** @var array<string, int> $groupRids array of well known group rids */
73 private array $groupRids;
74 /** @var array<string, int> $userRids array of well known user rids */
75 private array $userRids;
76 /** @var array<string|int, string> $hex2bitstring HEX to binary conversion table */
77 private array $hex2bitstring = ['0' => '0000', '1' => '0001', '2' => '0010', '3' => '0011', '4' => '0100',
78 '5' => '0101', '6' => '0110', '7' => '0111', '8' => '1000', '9' => '1001', 'A' => '1010',
79 'B' => '1011', 'C' => '1100', 'D' => '1101', 'E' => '1110', 'F' => '1111'];
80 /** specifies if the password should be expired */
81 private bool $expirePassword = false;
82 /** @var string[]|null host cache to reduce LDAP queries */
83 private ?array $cachedHostList = null;
84 /** @var array<string, string>|null $cachedGroupSIDList group cache to reduce LDAP queries */
85 private ?array $cachedGroupSIDList = null;
86 /** @var samba3domain[]|null $cachedDomainList cache for domain list */
87 private ?array $cachedDomainList = null;
88 /** delimiter for remote commands */
89 private static string $SPLIT_DELIMITER = "###x##y##x###";
90
91
92 /**
93 * Creates a new sambaSamAccount object.
94 *
95 * @param string $scope account type (user, group, host)
96 */
97 public function __construct($scope) {
98 // List of well known group rids
99 $this->groupRids = [
100 _('Domain admins') => 512, _('Domain users') => 513, _('Domain guests') => 514,
101 _('Domain computers') => 515, _('Domain controllers') => 516, _('Domain certificate admins') => 517,
102 _('Domain schema admins') => 518, _('Domain enterprise admins') => 519, _('Domain policy admins') => 520];
103 // List of well known user rids
104 $this->userRids = [
105 _('Domain admins') => 500, _('Domain guests') => 501, _('Domain KRBTGT') => 502];
106 // call parent constructor
107 parent::__construct($scope);
108 $this->autoAddObjectClasses = false;
109 }
110
111 /**
112 * {@inheritDoc}
113 */
114 protected function load_Messages(): void {
115 // error messages for input checks
116 $this->messages['homePath'][0] = ['ERROR', _('Home path'), _('Home path is invalid.')];
117 $this->messages['homePath'][1] = ['INFO', _('Home path'), _('Inserted user or group name in home path.')];
118 $this->messages['homePath'][2] = ['ERROR', _('Account %s:') . ' sambaSamAccount_homePath', _('Home path is invalid.')];
119 $this->messages['profilePath'][0] = ['ERROR', _('Profile path'), _('Profile path is invalid!')];
120 $this->messages['profilePath'][1] = ['INFO', _('Profile path'), _('Inserted user or group name in profile path.')];
121 $this->messages['profilePath'][2] = ['ERROR', _('Account %s:') . ' sambaSamAccount_profilePath', _('Profile path is invalid!')];
122 $this->messages['logonScript'][0] = ['ERROR', _('Logon script'), _('Logon script is invalid!')];
123 $this->messages['logonScript'][1] = ['INFO', _('Logon script'), _('Inserted user or group name in logon script.')];
124 $this->messages['logonScript'][2] = ['ERROR', _('Account %s:') . ' sambaSamAccount_logonScript', _('Logon script is invalid!')];
125 $this->messages['workstations'][0] = ['ERROR', _('Samba workstations'), _('Please enter a comma separated list of host names!')];
126 $this->messages['workstations'][1] = ['ERROR', _('Account %s:') . ' sambaSamAccount_workstations', _('Please enter a comma separated list of host names!')];
127 $this->messages['sambaNTPassword'][0] = ['ERROR', _('Password'), _('Please enter the same password in both password fields.')];
128 $this->messages['sambaNTPassword'][1] = ['ERROR', _('Password'), _('Password contains invalid characters. Valid characters are:') . ' a-z, A-Z, 0-9 and #*,.;:_-+!%&/|?{[()]}=@$ §°!'];
129 $this->messages['sambaNTPassword'][2] = ['ERROR', _('Account %s:') . ' sambaSamAccount_password', _('Password contains invalid characters. Valid characters are:') . ' a-z, A-Z, 0-9 and #*,.;:_-+!%&/|?{[()]}=@$ §°!'];
130 $this->messages['rid'][2] = ['ERROR', _('Account %s:') . ' sambaSamAccount_rid', _('Please enter a RID number or the name of a special account!')];
131 $this->messages['rid'][3] = ['ERROR', _('Account %s:') . ' sambaSamAccount_rid', _('This is not a valid RID number!')];
132 $this->messages['displayName'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_displayName', _('Please enter a valid display name!')];
133 $this->messages['displayName'][1] = ['ERROR', _('Display name'), _('Please enter a valid display name!')];
134 $this->messages['pwdUnix'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_pwdUnix', _('This value can only be "true" or "false".')];
135 $this->messages['noPassword'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_noPassword', _('This value can only be "true" or "false".')];
136 $this->messages['noExpire'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_noExpire', _('This value can only be "true" or "false".')];
137 $this->messages['deactivated'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_deactivated', _('This value can only be "true" or "false".')];
138 $this->messages['expireDate'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_expireDate', _('Please enter a valid date in format DD-MM-YYYY.')];
139 $this->messages['homeDrive'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_homeDrive', _('Please enter a valid drive letter.')];
140 $this->messages['domain'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_domain', _('LAM was unable to find a domain with this name!')];
141 $this->messages['logonHours'][0] = ['ERROR', _('Logon hours'), _('The format of the logon hours field is invalid!')];
142 $this->messages['logonHours'][1] = ['ERROR', _('Account %s:') . ' sambaSamAccount_logonHours', _('The format of the logon hours field is invalid!')];
143 $this->messages['group'][0] = ['ERROR', _('Account %s:') . ' sambaSamAccount_group', _('Please enter a valid group name!')];
144 $this->messages['profileCanMustChange'][0] = ['ERROR', _('The value for the Samba 3 field "User can/must change password" needs to be a number.')];
145 }
146
147 /**
148 * {@inheritDoc}
149 */
150 public function can_manage(): bool {
151 return in_array($this->get_scope(), ['user', 'host']);
152 }
153
154 /**
155 * {@inheritDoc}
156 */
157 public function get_metaData(): array {
158 $return = [];
159 // icon
160 $return['icon'] = 'samba.svg';
161 // alias name
162 $return["alias"] = _('Samba 3');
163 // RDN attribute
164 $return["RDN"] = ["sambaSID" => "low"];
165 // module dependencies
166 $return['dependencies'] = ['depends' => ['posixAccount'], 'conflicts' => []];
167 // LDAP filter
168 $return["ldap_filter"] = ['or' => "(objectClass=sambaSamAccount)"];
169 // managed object classes
170 $return['objectClasses'] = ['sambaSamAccount'];
171 // managed attributes
172 $return['attributes'] = ['uid', 'sambaSID', 'sambaNTPassword', 'sambaPwdLastSet',
173 'sambaLogonTime', 'sambaLogoffTime', 'sambaKickoffTime', 'sambaacctflags',
174 'sambaPwdLastSet', 'displayName', 'sambaHomePath', 'sambaHomeDrive', 'sambaLogonScript', 'sambaProfilePath',
175 'sambaUserWorkstations', 'sambaPrimaryGroupSID', 'sambaDomainName', 'sambaLogonHours', 'sambaMungedDial',
176 'sambaPasswordHistory', 'sambaPwdCanChange', 'sambaPwdMustChange']; // sambaPwdCanChange/sambaPwdMustChange only for extension removal
177 // profile options
178 $profileContainer = new htmlResponsiveRow();
179 $profileContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_addExt', false, _('Automatically add this extension'), 'autoAdd'));
180 $return['profile_options'] = $profileContainer;
181 // profile checks
182 $return['profile_checks']['sambaSamAccount_smbhome'] = [
183 'type' => 'ext_preg',
184 'regex' => 'UNC',
185 'error_message' => $this->messages['homePath'][0]];
186 $return['profile_checks']['sambaSamAccount_profilePath'] = [
187 'type' => 'ext_preg',
188 'regex' => 'UNC',
189 'error_message' => $this->messages['profilePath'][0]];
190 $return['profile_checks']['sambaSamAccount_logonScript'] = [
191 'type' => 'ext_preg',
192 'regex' => 'logonscript',
193 'error_message' => $this->messages['logonScript'][0]];
194 $return['profile_checks']['sambaSamAccount_userWorkstations'] = [
195 'type' => 'ext_preg',
196 'regex' => 'unixhost',
197 'error_message' => $this->messages['workstations'][0]];
198 $return['profile_checks']['sambaSamAccount_logonHours'] = [
199 'type' => 'ext_preg',
200 'regex' => 'sambaLogonHours',
201 'error_message' => $this->messages['logonHours'][0]];
202 // profile mappings
203 $return['profile_mappings'] = [
204 'sambaSamAccount_sambaDomainName' => 'sambaDomainName',
205 'sambaSamAccount_displayName' => 'displayName',
206 ];
207 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomePath')) {
208 $return['profile_mappings']['sambaSamAccount_smbhome'] = 'sambaHomePath';
209 }
210 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideProfilePath')) {
211 $return['profile_mappings']['sambaSamAccount_profilePath'] = 'sambaProfilePath';
212 }
213 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonScript')) {
214 $return['profile_mappings']['sambaSamAccount_logonScript'] = 'sambaLogonScript';
215 }
216 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideWorkstations')) {
217 $return['profile_mappings']['sambaSamAccount_userWorkstations'] = 'sambaUserWorkstations';
218 }
219 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonHours')) {
220 $return['profile_mappings']['sambaSamAccount_logonHours'] = 'sambaLogonHours';
221 }
222 // available PDF fields
223 $return['PDF_fields'] = [
224 'displayName' => _('Display name'),
225 'sambaKickoffTime' => _('Account expiration date'),
226 'sambaDomainName' => _('Domain'),
227 'sambaPrimaryGroupSID' => _('Windows group')
228 ];
229 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomeDrive')) {
230 $return['PDF_fields']['sambaHomeDrive'] = _('Home drive');
231 }
232 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomePath')) {
233 $return['PDF_fields']['sambaHomePath'] = _('Home path');
234 }
235 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideProfilePath')) {
236 $return['PDF_fields']['sambaProfilePath'] = _('Profile path');
237 }
238 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonScript')) {
239 $return['PDF_fields']['sambaLogonScript'] = _('Logon script');
240 }
241 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideWorkstations')) {
242 $return['PDF_fields']['sambaUserWorkstations'] = _('Samba workstations');
243 }
244 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideTerminalServer')) {
245 $return['PDF_fields']['tsAllowLogin'] = _('Allow terminal server login');
246 $return['PDF_fields']['tsHomeDir'] = _('Home directory') . ' (TS)';
247 $return['PDF_fields']['tsHomeDrive'] = _('Home drive') . ' (TS)';
248 $return['PDF_fields']['tsProfilePath'] = _('Profile path') . ' (TS)';
249 $return['PDF_fields']['tsInherit'] = _('Inherit client startup configuration') . ' (TS)';
250 $return['PDF_fields']['tsInitialProgram'] = _('Initial program') . ' (TS)';
251 $return['PDF_fields']['tsWorkDirectory'] = _('Working directory') . ' (TS)';
252 $return['PDF_fields']['tsConnectionLimit'] = _('Connection time limit') . ' (TS)';
253 $return['PDF_fields']['tsDisconnectionLimit'] = _('Disconnection time limit') . ' (TS)';
254 $return['PDF_fields']['tsIdleLimit'] = _('Idle time limit') . ' (TS)';
255 $return['PDF_fields']['tsConnectDrives'] = _('Connect client drives') . ' (TS)';
256 $return['PDF_fields']['tsConnectPrinters'] = _('Connect client printers') . ' (TS)';
257 $return['PDF_fields']['tsClientPrinterDefault'] = _('Client printer is default') . ' (TS)';
258 $return['PDF_fields']['tsShadowing'] = _('Shadowing') . ' (TS)';
259 $return['PDF_fields']['tsBrokenConn'] = _('On broken or timed out connection') . ' (TS)';
260 $return['PDF_fields']['tsReconnect'] = _('Reconnect if disconnected') . ' (TS)';
261 }
262 $return['selfServiceFieldSettings'] = [
263 'syncNTPassword' => _('Sync Samba NT password with Unix password'),
264 'syncSambaPwdLastSet' => _('Update attribute "sambaPwdLastSet" on password change'),
265 'password' => _('Password'),
266 'sambaPwdLastSet' => _('Last password change (read-only)'),
267 ];
268 // self-service: fields that cannot be relabeled
269 $return['selfServiceNoRelabelFields'] = ['syncNTPassword', 'syncSambaPwdLastSet'];
270 // help Entries
271 $return['help'] = [
272 "displayName" => [
273 "Headline" => _("Display name"), 'attr' => 'displayName',
274 "Text" => _("This is the account's full name on Windows systems.")],
275 "password" => [
276 "Headline" => _("Samba password"),
277 "Text" => _("This is the account's Windows password.")],
278 "resetPassword" => [
279 "Headline" => _("Reset password"),
280 "Text" => _("This will reset the host's password to a default value.")],
281 "pwdUnix" => [
282 "Headline" => _("Use Unix password"),
283 "Text" => _("If checked Unix password will also be used as Samba password.")],
284 "pwdUnixUpload" => [
285 "Headline" => _("Use Unix password"),
286 "Text" => _("If set to \"true\" Unix password will also be used as Samba password.")],
287 "noPassword" => [
288 "Headline" => _("Use no password"),
289 "Text" => _("If checked no password will be used.")],
290 "noPasswordUpload" => [
291 "Headline" => _("Use no password"),
292 "Text" => _("If set to \"true\" no password will be used.")],
293 "noExpire" => [
294 "Headline" => _("Password does not expire"),
295 "Text" => _("If checked password does not expire. (Setting X-Flag)")],
296 "noExpireUpload" => [
297 "Headline" => _("Password does not expire"),
298 "Text" => _("If set to \"true\" password does not expire. (Setting X-Flag)")],
299 "deactivated" => [
300 "Headline" => _("Account is deactivated"),
301 "Text" => _("If checked then the account will be deactivated. (Setting D-Flag)")],
302 "locked" => [
303 "Headline" => _("Account is locked"),
304 "Text" => _("If checked then the account will be locked (setting L-Flag). You usually want to use this setting to unlock user accounts which were locked because of failed login attempts.")],
305 "deactivatedUpload" => [
306 "Headline" => _("Account is deactivated"),
307 "Text" => _("If set to \"true\" account will be deactivated. (Setting D-Flag)")],
308 "passwordIsExpired" => [
309 "Headline" => _("Password change at next login"),
310 "Text" => _("If you set this option then the user has to change his password at the next login.")],
311 "pwdCanChange" => [
312 "Headline" => _("User can change password"),
313 "Text" => _("Date after the user is able to change his password.")],
314 "pwdMustChange" => ["Headline" => _("User must change password"),
315 "Text" => _("Date after the user must change his password.")],
316 "homeDrive" => [
317 "Headline" => _("Home drive"), 'attr' => 'sambaHomeDrive',
318 "Text" => _("The home directory will be connected under this drive letter.")],
319 "homePath" => [
320 "Headline" => _("Home path"), 'attr' => 'sambaHomePath',
321 "Text" => _('UNC-path (\\\\server\\share) of homedirectory. $user and $group are replaced with user and group name.') . ' ' . _("Can be left empty.")],
322 "profilePath" => [
323 "Headline" => _("Profile path"), 'attr' => 'sambaProfilePath',
324 "Text" => _('Path of the user profile. Can be a local absolute path or a UNC-path (\\\\server\\share). $user and $group are replaced with user and group name.') . ' ' . _("Can be left empty.")],
325 "scriptPath" => [
326 "Headline" => _("Logon script"), 'attr' => 'sambaLogonScript',
327 "Text" => _('File name and path relative to netlogon-share which should be executed on logon. $user and $group are replaced with user and group name.') . ' ' . _("Can be left empty.")],
328 "userWorkstations" => [
329 "Headline" => _("Samba workstations"), 'attr' => 'sambaUserWorkstations',
330 "Text" => _("List of Samba workstations the user is allowed to login. Empty means every workstation.")],
331 "workstations" => [
332 "Headline" => _("Samba workstations"), 'attr' => 'sambaUserWorkstations',
333 "Text" => _("Comma separated list of Samba workstations the user is allowed to login. Empty means every workstation.") . ' ' . _("Can be left empty.")],
334 "group" => [
335 "Headline" => _("Windows primary group"), 'attr' => 'sambaPrimaryGroupSID',
336 "Text" => _("This is the user's primary Windows group.")],
337 "groupUpload" => [
338 "Headline" => _("Windows primary group SID"), 'attr' => 'sambaPrimaryGroupSID',
339 "Text" => _("This is the SID of the user's primary Windows group.")],
340 "specialUser" => [
341 "Headline" => _("Special user"),
342 "Text" => _("This allows you to define this account as a special user like administrator or guest.")],
343 "ridUpload" => [
344 "Headline" => _("Samba RID"),
345 "Text" => _("This is the relative ID number for your Windows account. You can either enter a number or one of these special accounts: ") .
346 implode(", ", array_keys($this->userRids)) . "<br><br>" . _("If you leave this empty LAM will use: uidNumber*2 + sambaAlgorithmicRidBase.")],
347 "ridUploadHost" => [
348 "Headline" => _("Samba RID"),
349 "Text" => _("This is the relative ID number for your host account. If you leave this empty LAM will use: uidNumber*2 + sambaAlgorithmicRidBase.")],
350 "domain" => [
351 "Headline" => _("Domain"), 'attr' => 'sambaDomainName',
352 "Text" => _("Windows domain name of account.")],
353 "logonHours" => [
354 "Headline" => _("Logon hours"), 'attr' => 'sambaLogonHours',
355 "Text" => _("This option defines the allowed logon hours for this account.")],
356 "logonHoursUpload" => [
357 "Headline" => _("Logon hours"), 'attr' => 'sambaLogonHours',
358 "Text" => _("This option defines the allowed logon hours for this account. The format is the same as for the LDAP attribute. The 24*7 hours are represented as 168 bit which are saved as 21 hex (21*8 = 168) values. The first bit represents Sunday 0:00 - 0:59 in GMT.")],
359 'expireDate' => [
360 "Headline" => _("Account expiration date"), 'attr' => 'sambaKickoffTime',
361 "Text" => _("This is the date when the account will expire. Format: DD-MM-YYYY")],
362 'timeZone' => [
363 "Headline" => _("Time zone"),
364 "Text" => _("This is the time zone of your Samba server. LAM needs this information to display the logon hours correctly.")],
365 'tsAllowLogin' => [
366 "Headline" => _("Allow terminal server login"),
367 "Text" => _("Activate this checkbox to allow this user to use the terminal service.")],
368 'tsHomeDir' => [
369 "Headline" => _("Home directory"),
370 "Text" => _("This is the path to the user's home directory.")],
371 'tsProfilePath' => [
372 "Headline" => _("Profile path"),
373 "Text" => _("Path of the user profile.")],
374 'tsInherit' => [
375 "Headline" => _("Inherit client startup configuration"),
376 "Text" => _("Activate this checkbox to inherit the initial program and working directory from the client machine.")],
377 'tsInitialProgram' => [
378 "Headline" => _("Initial program"),
379 "Text" => _("This program is run after the login.")],
380 'tsWorkDirectory' => [
381 "Headline" => _("Working directory"),
382 "Text" => _("Working directory of initial program.")],
383 'tsTimeLimit' => [
384 "Headline" => _("Time limit"),
385 "Text" => _("Please enter the time limit in minutes. 0 means unlimited.")],
386 'tsConnectDrives' => [
387 "Headline" => _("Connect client drives"),
388 "Text" => _("Activate this checkbox to connect drives from the client machine.")],
389 'tsConnectPrinters' => [
390 "Headline" => _("Connect client printers"),
391 "Text" => _("Activate this checkbox to connect printers from the client machine.")],
392 'tsClientPrinterDefault' => [
393 "Headline" => _("Client printer is default"),
394 "Text" => _("Activate this checkbox to set the client's printer as default printer.")],
395 'tsShadowing' => [
396 "Headline" => _("Shadowing"),
397 "Text" => _("Here you can specify the shadowing mode.")],
398 'tsBrokenConn' => [
399 "Headline" => _("On broken or timed out connection"),
400 "Text" => _("This specifies what to do when the client connection is broken.")],
401 'tsReconnect' => [
402 "Headline" => _("Reconnect if disconnected"),
403 "Text" => _("This specifies the reconnect policy.")],
404 'terminalServer' => [
405 "Headline" => _("Terminal server options"),
406 "Text" => _("Here you can change the settings for the terminal server access.")],
407 'sambaPwdLastSet' => [
408 "Headline" => _("Last password change"), 'attr' => 'sambaPwdLastSet',
409 "Text" => _("This is the date when the user changed his password.")],
410 'hiddenOptions' => [
411 "Headline" => _("Hidden options"),
412 "Text" => _("The selected options will not be managed inside LAM. You can use this to reduce the number of displayed input fields.")],
413 'autoAdd' => [
414 "Headline" => _("Automatically add this extension"),
415 "Text" => _("This will enable the extension automatically if this profile is loaded.")],
416 'domainSuffix' => [
417 "Headline" => _("Domain suffix"),
418 "Text" => _("Please enter the LDAP suffix where your Samba domain entries are stored.")],
419 'history' => [
420 "Headline" => _("Password history"),
421 "Text" => _("Enables password history. Depending on your LDAP server you need to select the right server-side ordering (switch ordering here if old passwords are not removed from history).")],
422 ];
423 // upload dependencies
424 $return['upload_preDepends'] = ['posixAccount', 'inetOrgPerson'];
425 // upload options
426 if ($this->get_scope() == "user") {
427 $return['upload_columns'] = [
428 [
429 'name' => 'sambaSamAccount_domain',
430 'description' => _('Domain'),
431 'required' => true,
432 'help' => 'domain',
433 'example' => _('mydomain')
434 ],
435 [
436 'name' => 'sambaSamAccount_displayName',
437 'description' => _('Display name'),
438 'help' => 'displayName',
439 'example' => _('Steve Miller')
440 ],
441 [
442 'name' => 'sambaSamAccount_password',
443 'description' => _('Password'),
444 'help' => 'password',
445 'example' => _('secret')
446 ],
447 [
448 'name' => 'sambaSamAccount_pwdUnix',
449 'description' => _('Use Unix password'),
450 'help' => 'pwdUnixUpload',
451 'default' => 'true',
452 'values' => 'true, false',
453 'example' => 'true'
454 ],
455 [
456 'name' => 'sambaSamAccount_noPassword',
457 'description' => _('Use no password'),
458 'help' => 'noPasswordUpload',
459 'default' => 'false',
460 'values' => 'true, false',
461 'example' => 'false'
462 ],
463 [
464 'name' => 'sambaSamAccount_noExpire',
465 'description' => _('Password does not expire'),
466 'help' => 'noExpireUpload',
467 'default' => 'true',
468 'values' => 'true, false',
469 'example' => 'true'
470 ],
471 [
472 'name' => 'sambaSamAccount_deactivated',
473 'description' => _('Account is deactivated'),
474 'help' => 'deactivatedUpload',
475 'default' => 'false',
476 'values' => 'true, false',
477 'example' => 'false'
478 ],
479 [
480 'name' => 'sambaSamAccount_expireDate',
481 'description' => _('Account expiration date'),
482 'help' => 'expireDate',
483 'default' => '31-12-2030',
484 'example' => '15-10-2020'
485 ],
486 [
487 'name' => 'sambaSamAccount_group',
488 'description' => _('Windows group'),
489 'help' => 'groupUpload',
490 'example' => _('mygroup'),
491 'default' => 'Domain Users'
492 ],
493 [
494 'name' => 'sambaSamAccount_rid',
495 'description' => _('Samba RID'),
496 'help' => 'ridUpload',
497 'example' => '1235',
498 'default' => '{uidNumber}*2 + {sambaAlgorithmicRidBase}'
499 ],
500 ];
501 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomeDrive')) {
502 $return['upload_columns'][] = [
503 'name' => 'sambaSamAccount_homeDrive',
504 'description' => _('Home drive'),
505 'help' => 'homeDrive',
506 'example' => 'k:'
507 ];
508 }
509 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomePath')) {
510 $return['upload_columns'][] = [
511 'name' => 'sambaSamAccount_homePath',
512 'description' => _('Home path'),
513 'help' => 'homePath',
514 'example' => _('\\\\server\\homes\\smiller')
515 ];
516 }
517 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideProfilePath')) {
518 $return['upload_columns'][] = [
519 'name' => 'sambaSamAccount_profilePath',
520 'description' => _('Profile path'),
521 'help' => 'profilePath',
522 'example' => _('\\\\server\\profiles\\smiller')
523 ];
524 }
525 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonScript')) {
526 $return['upload_columns'][] = [
527 'name' => 'sambaSamAccount_logonScript',
528 'description' => _('Logon script'),
529 'help' => 'scriptPath',
530 'example' => 'logon.bat'
531 ];
532 }
533 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideWorkstations')) {
534 $return['upload_columns'][] = [
535 'name' => 'sambaSamAccount_workstations',
536 'description' => _('Samba workstations'),
537 'help' => 'workstations',
538 'example' => 'PC01,PC02,PC03'
539 ];
540 }
541 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonHours')) {
542 $return['upload_columns'][] = [
543 'name' => 'sambaSamAccount_logonHours',
544 'description' => _('Logon hours'),
545 'help' => 'logonHoursUpload',
546 'example' => 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF'
547 ];
548 }
549 }
550 elseif ($this->get_scope() == "host") {
551 $return['upload_columns'] = [
552 [
553 'name' => 'sambaSamAccount_domain',
554 'description' => _('Domain'),
555 'required' => true,
556 'help' => 'domain',
557 'example' => _('mydomain')
558 ],
559 [
560 'name' => 'sambaSamAccount_rid',
561 'description' => _('Samba RID'),
562 'help' => 'ridUploadHost',
563 'example' => '1235',
564 'default' => '{uidNumber}*2 + {sambaAlgorithmicRidBase}'
565 ]
566 ];
567 }
568 return $return;
569 }
570
571 /**
572 * {@inheritDoc}
573 */
574 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
575 parent::loadAttributesFromAccountCopy($ldapAttributes, array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, self::ATTRIBUTES_TO_IGNORE_ON_COPY));
576 }
577
578 /**
579 * {@inheritDoc}
580 */
581 public function module_ready(): bool {
582 $attrs = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
583 return isset($attrs['gidNumber'][0]) && isset($attrs['uidNumber'][0]) && isset($attrs['uid'][0]);
584 }
585
586 /**
587 * {@inheritDoc}
588 */
589 public function module_complete(): bool {
590 if (!$this->isExtensionEnabled()) {
591 return true;
592 }
593 if ($this->get_scope() == "host") {
594 $attrs = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
595 if (!str_ends_with($attrs['uid'][0], '$')) {
596 return false;
597 }
598 }
599 return isset($this->attributes['sambaSID']) && ($this->attributes['sambaSID'] != '');
600 }
601
602
603 /**
604 * {@inheritDoc}
605 */
606 public function load_attributes(array $attributes): void {
607 parent::load_attributes($attributes);
608 if (isset($this->attributes['sambaacctflags'][0])) {
609 $this->nopwd = str_contains($this->attributes['sambaacctflags'][0], "N");
610 $this->noexpire = str_contains($this->attributes['sambaacctflags'][0], "X");
611 }
612 if (isset($this->attributes['sambaPwdLastSet'][0]) && ($this->attributes['sambaPwdLastSet'][0] === '0')) {
613 $this->expirePassword = true;
614 }
615 }
616
617 /**
618 * {@inheritDoc}
619 */
620 public function save_attributes(): array {
621 if (!in_array('sambaSamAccount', $this->attributes['objectClass']) && !in_array('sambaSamAccount', $this->orig['objectClass'])) {
622 // skip saving if the extension was not added/modified
623 return [];
624 }
625 if ($this->isExtensionEnabled()) {
626 if ($this->expirePassword) {
627 $this->attributes['sambaPwdLastSet'][0] = '0';
628 }
629 elseif ((isset($this->attributes['sambaPwdLastSet'][0])) && ($this->attributes['sambaPwdLastSet'][0] == '0')) {
630 $this->attributes['sambaPwdLastSet'][0] = (string) time();
631 }
632 }
633 return parent::save_attributes();
634 }
635
636 /**
637 * {@inheritdoc}
638 */
639 public function getWildcardTargetAttributeNames(): array {
640 return ['displayName', 'sambaHomePath', 'sambaLogonScript', 'sambaProfilePath'];
641 }
642
643 /**
644 * {@inheritDoc}
645 */
646 public function process_attributes(): array {
647 // add extension
648 if (isset($_POST['addObjectClass'])) {
649 $this->attributes['objectClass'][] = 'sambaSamAccount';
650 return [];
651 }
652 // remove extension
653 elseif (isset($_POST['remObjectClass'])) {
654 $this->attributes['objectClass'] = array_delete(['sambaSamAccount'], $this->attributes['objectClass']);
655 $attrKeys = array_keys($this->attributes);
656 for ($k = 0; $k < count($attrKeys); $k++) {
657 if (strpos($attrKeys[$k], 'samba') > -1) {
658 unset($this->attributes[$attrKeys[$k]]);
659 }
660 }
661 if (isset($this->attributes['displayName'])) {
662 unset($this->attributes['displayName']);
663 }
664 return [];
665 }
666 // skip processing if extension is not active
667 if (!$this->isExtensionEnabled()) {
668 return [];
669 }
670 $this->getAccountContainer()->replaceWildcardsInPOST($this->getWildcardTargetAttributeNames());
671 $errors = [];
672 $sambaDomains = $this->getDomains();
673 if (count($sambaDomains) === 0) {
674 return [];
675 }
676 $unixAttributes = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
677 // Save attributes
678 $this->attributes['sambaDomainName'][0] = $_POST['sambaDomainName'];
679 // Get Domain SID from name
680 $SID = '';
681 $RIDbase = 1000;
682 for ($i = 0; $i < count($sambaDomains); $i++) {
683 if ($this->attributes['sambaDomainName'][0] == $sambaDomains[$i]->name) {
684 $SID = $sambaDomains[$i]->SID;
685 $RIDbase = $sambaDomains[$i]->RIDbase;
686 break;
687 }
688 }
689 $flag = "[";
690 if (isset($_POST['sambaAcctFlagsD'])) {
691 $flag .= "D";
692 }
693 if (isset($_POST['sambaAcctFlagsX'])) {
694 $flag .= "X";
695 $this->noexpire = true;
696 }
697 else {
698 $this->noexpire = false;
699 }
700 if (isset($_POST['sambaAcctFlagsN'])) {
701 $flag .= "N";
702 $this->nopwd = true;
703 }
704 else {
705 $this->nopwd = false;
706 }
707 if (isset($_POST['sambaAcctFlagsS'])) {
708 $flag .= "S";
709 }
710 if (isset($_POST['sambaAcctFlagsW'])) {
711 $flag .= "W";
712 }
713 if (isset($_POST['sambaAcctFlagsU'])) {
714 $flag .= "U";
715 }
716 if (isset($_POST['sambaAcctFlagsL'])) {
717 $flag .= "L";
718 }
719 // Expand string to fixed length
720 $flag = str_pad($flag, 12);
721 // End character
722 $flag .= "]";
723 $this->attributes['sambaacctflags'][0] = $flag;
724
725 // display name
726 $this->attributes['displayName'][0] = $_POST['displayName'];
727 if (($this->attributes['displayName'][0] != '') && !get_preg($this->attributes['displayName'][0], 'realname')) {
728 $errors[] = $this->messages['displayName'][1];
729 }
730
731 // host attributes
732 if ($this->get_scope() == 'host') {
733 $this->attributes['sambaPrimaryGroupSID'][0] = $SID . "-" . $this->groupRids[_('Domain computers')];
734 if (isset($_POST['ResetSambaPassword']) || !isset($this->attributes['sambaNTPassword'][0])) {
735 $hostname = $unixAttributes['uid'][0];
736 $hostname = substr($hostname, 0, strlen($hostname) - 1);
737 $this->attributes['sambaNTPassword'][0] = ntPassword($hostname);
738 $this->attributes['sambaPwdLastSet'][0] = time();
739 }
740 }
741 // user attributes
742 if ($this->get_scope() == 'user') {
743 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomePath')) {
744 $this->attributes['sambaHomePath'][0] = $_POST['sambaHomePath'];
745 if ($this->attributes['sambaHomePath'][0] != $_POST['sambaHomePath']) {
746 $errors[] = $this->messages['homePath'][1];
747 }
748 if ((!$this->attributes['sambaHomePath'][0] == '') && (!get_preg($this->attributes['sambaHomePath'][0], 'UNC'))) {
749 $errors[] = $this->messages['homePath'][0];
750 }
751 }
752 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomeDrive')) {
753 $this->attributes['sambaHomeDrive'][0] = ($_POST['sambaHomeDrive'] === "-") ? '' : $_POST['sambaHomeDrive'];
754 }
755 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonScript')) {
756 $this->attributes['sambaLogonScript'][0] = $_POST['sambaLogonScript'];
757 if ($this->attributes['sambaLogonScript'][0] != $_POST['sambaLogonScript']) {
758 $errors[] = $this->messages['logonScript'][1];
759 }
760 if ((!$this->attributes['sambaLogonScript'][0] == '') && (!get_preg($this->attributes['sambaLogonScript'][0], 'logonscript'))) {
761 $errors[] = $this->messages['logonScript'][0];
762 }
763 }
764 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideProfilePath')) {
765 $this->attributes['sambaProfilePath'][0] = $_POST['sambaProfilePath'];
766 if ($this->attributes['sambaProfilePath'][0] != $_POST['sambaProfilePath']) {
767 $errors[] = $this->messages['profilePath'][1];
768 }
769 if (($this->attributes['sambaProfilePath'][0] != '') &&
770 !(get_preg($this->attributes['sambaProfilePath'][0], 'UNC') xor get_preg($this->attributes['sambaProfilePath'][0], 'homeDirectory'))) {
771 $errors[] = $this->messages['profilePath'][0];
772 }
773 }
774 $rids = array_keys($this->groupRids);
775 $wrid = false;
776 for ($i = 0; $i < count($rids); $i++) {
777 if ($_POST['sambaPrimaryGroupSID'] == $rids[$i]) {
778 $wrid = true;
779 // Get Domain SID
780 $this->attributes['sambaPrimaryGroupSID'][0] = $SID . "-" . $this->groupRids[$rids[$i]];
781 }
782 }
783 if (!$wrid) {
784 $gidnumber = $unixAttributes['gidNumber'][0];
785 $groups = $this->getGroupSIDList();
786 if (isset($groups[$gidnumber]) && ($groups[$gidnumber] != '')) {
787 $this->attributes['sambaPrimaryGroupSID'][0] = $groups[$gidnumber];
788 }
789 }
790 $specialRids = array_flip($this->userRids);
791 // set special RID if selected
792 if (in_array($_POST['sambaSID'], $specialRids)) {
793 $this->attributes['sambaSID'][0] = $SID . '-' . $this->userRids[$_POST['sambaSID']];
794 }
795 // standard RID
796 elseif ($_POST['sambaSID'] == "-") {
797 $rid = '';
798 if (isset($this->attributes['sambaSID'][0])) {
799 $rid = substr($this->attributes['sambaSID'][0], strrpos($this->attributes['sambaSID'][0], '-') + 1, strlen($this->attributes['sambaSID'][0]));
800 }
801 // change only if not yet set, previously set to special SID or domain changed
802 if (!isset($this->attributes['sambaSID'][0])
803 || in_array($rid, $this->userRids)
804 || (!str_contains($this->attributes['sambaSID'][0], $SID))) {
805 $this->attributes['sambaSID'][0] = $SID . "-" . ((intval($unixAttributes['uidNumber'][0]) * 2) + $RIDbase);
806 }
807 }
808 }
809 elseif (!isset($this->attributes['sambaSID'][0])) {
810 // host
811 $this->attributes['sambaSID'][0] = $SID . "-" . ((intval($unixAttributes['uidNumber'][0]) * 2) + $RIDbase);
812 }
813 $this->expirePassword = isset($_POST['forcePasswordChangeOption']);
814 return $errors;
815 }
816
817 /**
818 * Processes user input of the primary module page.
819 * It checks if all input values are correct and updates the associated LDAP attributes.
820 *
821 * @return string[][] list of info/error messages
822 */
823 public function process_sambaUserWorkstations(): array {
824 // Load attributes
825 if ($this->get_scope() == 'user') {
826 if (isset($_POST['workstations_2']) && isset($_POST['workstations_left'])) { // Add workstations to list
827 $workstations = [];
828 if (isset($this->attributes['sambaUserWorkstations'][0])) {
829 $temp = str_replace(' ', '', $this->attributes['sambaUserWorkstations'][0]);
830 $workstations = explode(',', $temp);
831 for ($i = 0; $i < count($workstations); $i++) {
832 if ($workstations[$i] === '') {
833 unset($workstations[$i]);
834 }
835 }
836 $workstations = array_values($workstations);
837 }
838 // Add new // Add workstations
839 $workstations = array_merge($workstations, $_POST['workstations_2']);
840 // remove doubles
841 $workstations = array_flip($workstations);
842 $workstations = array_unique($workstations);
843 $workstations = array_flip($workstations);
844 // sort workstations
845 sort($workstations);
846 // Recreate workstation string
847 $this->attributes['sambaUserWorkstations'][0] = $workstations[0];
848 for ($i = 1; $i < count($workstations); $i++) {
849 $this->attributes['sambaUserWorkstations'][0] = $this->attributes['sambaUserWorkstations'][0] . "," . $workstations[$i];
850 }
851 }
852 elseif (isset($_POST['workstations_1']) && isset($_POST['workstations_right'])) { // remove // Add workstations from list
853 // Put all workstations in array
854 $temp = str_replace(' ', '', $this->attributes['sambaUserWorkstations'][0]);
855 $workstations = explode(',', $temp);
856 for ($i = 0; $i < count($workstations); $i++) {
857 if ($workstations[$i] === '') {
858 unset($workstations[$i]);
859 }
860 }
861 $workstations = array_values($workstations);
862 // Remove unwanted workstations from array
863 $workstations = array_delete($_POST['workstations_1'], $workstations);
864 // Recreate workstation string
865 unset($this->attributes['sambaUserWorkstations'][0]);
866 if (count($workstations) > 0) {
867 $this->attributes['sambaUserWorkstations'][0] = $workstations[0];
868 for ($i = 1; $i < count($workstations); $i++) {
869 $this->attributes['sambaUserWorkstations'][0] = $this->attributes['sambaUserWorkstations'][0] . "," . $workstations[$i];
870 }
871 }
872 }
873 }
874 return [];
875 }
876
877 /**
878 * Processes user input of the logon hours page.
879 * It checks if all input values are correct and updates the associated LDAP attributes.
880 *
881 * @return string[][] list of info/error messages
882 */
883 public function process_logonHours(): array {
884 if (isset($_POST['form_subpage_sambaSamAccount_attributes_abort'])) {
885 return [];
886 }
887 // set new logon hours
888 $logonHours = '';
889 for ($i = 0; $i < 24 * 7; $i++) {
890 $logonHours .= isset($_POST['lh_' . $i]) ? '1' : '0';
891 }
892 // reconstruct HEX string
893 $bitstring2hex = array_flip($this->hex2bitstring);
894 $logonHoursNew = '';
895 for ($i = 0; $i < 21; $i++) {
896 $part = strrev(substr($logonHours, $i * 8, 8));
897 $byte['hi'] = substr($part, 0, 4);
898 $byte['low'] = substr($part, 4, 4);
899 $hex = $bitstring2hex[$byte['hi']] . $bitstring2hex[$byte['low']];
900 $logonHoursNew .= $hex;
901 }
902 $this->attributes['sambaLogonHours'][0] = $logonHoursNew;
903 return [];
904 }
905
906 /**
907 * Processes user input of the time selection page.
908 *
909 * @return string[][] list of info/error messages
910 */
911 public function process_time(): array {
912 $return = [];
913 // find button name
914 $buttonName = '';
915 $postKeys = array_keys($_POST);
916 for ($i = 0; $i < count($postKeys); $i++) {
917 if (str_contains($postKeys[$i], 'form_subpage_sambaSamAccount_attributes_')) {
918 $buttonName = $postKeys[$i];
919 }
920 }
921 if (($buttonName == '') || (str_contains($buttonName, '_back'))) {
922 return [];
923 }
924 // get attribute name
925 $attr = '';
926 if (str_contains($buttonName, 'sambaKickoffTime')) {
927 $attr = 'sambaKickoffTime';
928 }
929 if ($attr === '') {
930 return [];
931 }
932 // determine action
933 if (str_contains($buttonName, '_change')) {
934 // set new time
935 $this->setExpirationDate($_POST['expire_yea'], $_POST['expire_mon'], $_POST['expire_day']);
936 // sync other modules
937 if (isset($_POST['syncShadow']) && ($_POST['syncShadow'] == 'on')) {
938 $this->getAccountContainer()->getAccountModule('shadowAccount')->setExpirationDate(
939 $_POST['expire_yea'], $_POST['expire_mon'], $_POST['expire_day']);
940 }
941 if (isset($_POST['syncHeimdal']) && ($_POST['syncHeimdal'] == 'on')) {
942 $this->getAccountContainer()->getAccountModule('heimdalKerberos')->setExpirationDate(
943 $_POST['expire_yea'], $_POST['expire_mon'], $_POST['expire_day']);
944 }
945 if (isset($_POST['syncMIT']) && ($_POST['syncMIT'] == 'on')) {
946 $this->getAccountContainer()->getAccountModule('mitKerberos')->setExpirationDate(
947 $_POST['expire_yea'], $_POST['expire_mon'], $_POST['expire_day']);
948 }
949 if (isset($_POST['syncMITStructural']) && ($_POST['syncMITStructural'] == 'on')) {
950 $this->getAccountContainer()->getAccountModule('mitKerberosStructural')->setExpirationDate(
951 $_POST['expire_yea'], $_POST['expire_mon'], $_POST['expire_day']);
952 }
953 }
954 elseif (str_contains($buttonName, '_del')) {
955 // remove attribute value
956 unset($this->attributes[$attr]);
957 // sync other modules
958 if (isset($_POST['syncShadow']) && ($_POST['syncShadow'] == 'on')) {
959 $this->getAccountContainer()->getAccountModule('shadowAccount')->setExpirationDate(
960 null, null, null);
961 }
962 if (isset($_POST['syncHeimdal']) && ($_POST['syncHeimdal'] == 'on')) {
963 $this->getAccountContainer()->getAccountModule('heimdalKerberos')->setExpirationDate(
964 null, null, null);
965 }
966 if (isset($_POST['syncMIT']) && ($_POST['syncMIT'] == 'on')) {
967 $this->getAccountContainer()->getAccountModule('mitKerberos')->setExpirationDate(
968 null, null, null);
969 }
970 if (isset($_POST['syncMITStructural']) && ($_POST['syncMITStructural'] == 'on')) {
971 $this->getAccountContainer()->getAccountModule('mitKerberosStructural')->setExpirationDate(
972 null, null, null);
973 }
974 }
975 return $return;
976 }
977
978 /**
979 * Processes user input of the terminal server page.
980 * It checks if all input values are correct and updates the associated LDAP attributes.
981 *
982 * @return string[][] list of info/error messages
983 */
984 public function process_terminalServer(): array {
985 if (isset($_POST['form_subpage_sambaSamAccount_attributes_abort'])) {
986 return [];
987 }
988 $mDial = new sambaMungedDial();
989 if (isset($this->attributes['sambaMungedDial'][0])) {
990 $mDial->load($this->attributes['sambaMungedDial'][0]);
991 }
992 $mDial->setTsLogin(!isset($_POST['tsAllowLogin']));
993 $mDial->ctx['CtxWFHomeDir'] = $_POST['tsHomeDir'];
994 $mDial->ctx['CtxWFHomeDirDrive'] = $_POST['tsHomeDrive'];
995 $mDial->ctx['CtxWFProfilePath'] = $_POST['tsProfilePath'];
996 $mDial->setInheritMode(isset($_POST['tsInherit']));
997 $mDial->ctx['CtxInitialProgram'] = $_POST['tsInitialProgram'];
998 $mDial->ctx['CtxWorkDirectory'] = $_POST['tsWorkDirectory'];
999 $mDial->ctx['CtxMaxConnectionTime'] = $_POST['tsConnectionLimit'];
1000 $mDial->ctx['CtxMaxDisconnectionTime'] = $_POST['tsDisconnectionLimit'];
1001 $mDial->ctx['CtxMaxIdleTime'] = $_POST['tsIdleLimit'];
1002 $mDial->setConnectClientDrives(isset($_POST['tsConnectDrives']));
1003 $mDial->setConnectClientPrinters(isset($_POST['tsConnectPrinters']));
1004 $mDial->setDefaultPrinter(isset($_POST['tsClientPrinterDefault']));
1005 $mDial->setShadow(true, $_POST['tsShadowing']);
1006 $mDial->setBrokenConn($_POST['tsBrokenConn']);
1007 $mDial->setReConn($_POST['tsReconnect']);
1008 $this->attributes['sambaMungedDial'][0] = $mDial->getMunged();
1009 return [];
1010 }
1011
1012 /**
1013 * {@inheritDoc}
1014 */
1015 public function display_html_attributes(): htmlElement|array {
1016 $return = new htmlResponsiveRow();
1017 if ($this->isExtensionEnabled()) {
1018 $this->getAccountContainer()->replaceWildcardsInArray($this->getWildcardTargetAttributeNames(), $this->attributes);
1019 $unixAttributes = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
1020 if (($this->get_scope() == "host") && !str_ends_with($unixAttributes['uid'][0], '$')) {
1021 $return->add(new htmlStatusMessage("ERROR", _('Host name must end with $!'), _('Please check your settings on the Unix page!')));
1022 }
1023 $personalAttributes = [];
1024 if ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) {
1025 $personalAttributes = $this->getAccountContainer()->getAccountModule('inetOrgPerson')->getAttributes();
1026 }
1027 // Get Domain SID from user SID
1028 $sambaDomains = $this->getDomains();
1029 if (count($sambaDomains) === 0) {
1030 $return->add(new htmlStatusMessage("ERROR", _('No Samba 3 domains found in LDAP! Please create one first.')));
1031 return $return;
1032 }
1033 if (isset($this->attributes['sambaSID'][0]) && $this->attributes['sambaSID'][0] != '') {
1034 $domainSID = substr($this->attributes['sambaSID'][0], 0, strrpos($this->attributes['sambaSID'][0], "-"));
1035 }
1036 $sel_domain = null;
1037 $SID = '';
1038 for ($i = 0; $i < count($sambaDomains); $i++) {
1039 $sambaDomainNames[] = $sambaDomains[$i]->name;
1040 if (isset($domainSID)) {
1041 if ($domainSID == $sambaDomains[$i]->SID) {
1042 $SID = $domainSID;
1043 $sel_domain = $sambaDomains[$i]->name;
1044 }
1045 }
1046 elseif (isset($this->attributes['sambaDomainName'][0]) && ($this->attributes['sambaDomainName'][0] != '')) {
1047 if ($this->attributes['sambaDomainName'][0] == $sambaDomains[$i]->name) {
1048 $SID = $sambaDomains[$i]->SID;
1049 $sel_domain = $sambaDomains[$i]->name;
1050 }
1051 }
1052 }
1053 // display name
1054 $displayName = '';
1055 if (!empty($this->attributes['displayName'][0])) {
1056 $displayName = $this->attributes['displayName'][0];
1057 }
1058 elseif ($this->getAccountContainer()->isNewAccount && empty($this->attributes['displayName'][0])) {
1059 if (isset($personalAttributes['givenName'][0]) && $personalAttributes['givenName'][0] && isset($personalAttributes['sn'][0]) && $personalAttributes['sn'][0]) {
1060 $displayName = $personalAttributes['givenName'][0] . " " . $personalAttributes['sn'][0];
1061 }
1062 elseif (isset($personalAttributes['sn'][0])) {
1063 $displayName = $personalAttributes['sn'][0];
1064 }
1065 }
1066 $return->add(new htmlResponsiveInputField(_('Display name'), 'displayName', $displayName, 'displayName'));
1067 if ($this->get_scope() == 'user') {
1068 // user account
1069 $return->add(new htmlHiddenInput('sambaAcctFlagsU', 'true'));
1070 // no password
1071 $return->add(new htmlResponsiveInputCheckbox('sambaAcctFlagsN', $this->nopwd, _('Use no password'), 'noPassword'));
1072 // no password expiry
1073 $return->add(new htmlResponsiveInputCheckbox('sambaAcctFlagsX', $this->noexpire, _('Password does not expire'), 'noExpire'));
1074 // account deactivated
1075 $return->add(new htmlResponsiveInputCheckbox('sambaAcctFlagsD', $this->isDeactivated(), _('Account is deactivated'), 'deactivated'));
1076 // account locked
1077 $return->add(new htmlResponsiveInputCheckbox('sambaAcctFlagsL', $this->isLocked(), _('Account is locked'), 'locked'));
1078 // password change at next login
1079 $return->add(new htmlResponsiveInputCheckbox('forcePasswordChangeOption', $this->expirePassword, _('Password change at next login'), 'passwordIsExpired'));
1080 // last password change
1081 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideSambaPwdLastSet')) {
1082 $sambaPwdLastSet = null;
1083 if (!empty($this->attributes['sambaPwdLastSet'][0])) {
1084 $time = new DateTime('@' . $this->attributes['sambaPwdLastSet'][0], new DateTimeZone('UTC'));
1085 $time->setTimezone(getTimeZone());
1086 $sambaPwdLastSet = $time->format('d.m.Y H:i');
1087 }
1088 if ($sambaPwdLastSet !== null) {
1089 $return->addLabel(new htmlOutputText(_('Last password change')));
1090 $sambaPwdLastSetGroup = new htmlGroup();
1091 $sambaPwdLastSetGroup->addElement(new htmlOutputText($sambaPwdLastSet));
1092 $sambaPwdLastSetGroup->addElement(new htmlHelpLink('sambaPwdLastSet'));
1093 $return->addField($sambaPwdLastSetGroup);
1094 }
1095 }
1096 // password can be changed
1097 $return->addLabel(new htmlOutputText(_('User can change password')));
1098 $pwdCanChangeGroup = new htmlGroup();
1099 $pwdCanChangeGroup->addElement(new htmlOutputText($this->getPasswordCanChangeTime($sambaDomains, $sel_domain), false));
1100 $pwdCanChangeGroup->addElement(new htmlSpacer('0.5rem', null));
1101 $pwdCanChangeGroup->addElement(new htmlHelpLink('pwdCanChange'));
1102 $return->addField($pwdCanChangeGroup);
1103 // password must be changed
1104 $return->addLabel(new htmlOutputText(_('User must change password')));
1105 $pwdMustChangeGroup = new htmlGroup();
1106 $pwdMustChangeGroup->addElement(new htmlOutputText($this->getPasswordMustChangeTime($sambaDomains, $sel_domain), false));
1107 $pwdMustChangeGroup->addElement(new htmlSpacer('0.5rem', null));
1108 $pwdMustChangeGroup->addElement(new htmlHelpLink('pwdMustChange'));
1109 $return->addField($pwdMustChangeGroup);
1110 // account expiration time
1111 $dateValue = $this->formatAccountExpirationDate();
1112 $return->addLabel(new htmlOutputText(_('Account expiration date')));
1113 $expireDateGroup = new htmlGroup();
1114 $expireDateGroup->addElement(new htmlOutputText($dateValue, false));
1115 $expireDateGroup->addElement(new htmlSpacer('0.5rem', null));
1116 $expireDateGroup->addElement(new htmlAccountPageButton(static::class, 'time', 'sambaKickoffTime', _('Change')));
1117 $expireDateGroup->addElement(new htmlSpacer('0.5rem', null));
1118 $expireDateGroup->addElement(new htmlHelpLink('expireDate'));
1119 $return->addField($expireDateGroup);
1120 // home drive
1121 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomeDrive')) {
1122 $drives = ['-'];
1123 for ($i = 90; $i > 67; $i--) {
1124 $drives[] = chr($i) . ':';
1125 }
1126 $selected = isset($this->attributes['sambaHomeDrive'][0]) ? [$this->attributes['sambaHomeDrive'][0]] : ['-'];
1127 $return->add(new htmlResponsiveSelect('sambaHomeDrive', $drives, $selected, _('Home drive'), 'homeDrive'));
1128 }
1129 // home path
1130 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomePath')) {
1131 $sambaHomePath = '';
1132 if (isset($this->attributes['sambaHomePath'][0])) {
1133 $sambaHomePath = $this->attributes['sambaHomePath'][0];
1134 }
1135 $return->add(new htmlResponsiveInputField(_('Home path'), 'sambaHomePath', $sambaHomePath, 'homePath'));
1136 }
1137 // profile path
1138 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideProfilePath')) {
1139 $sambaProfilePath = '';
1140 if (isset($this->attributes['sambaProfilePath'][0])) {
1141 $sambaProfilePath = $this->attributes['sambaProfilePath'][0];
1142 }
1143 $return->addLabel(new htmlOutputText(_('Profile path')));
1144 $sambaProfilePathGroup = new htmlGroup();
1145 $sambaProfilePathGroup->addElement(new htmlInputField('sambaProfilePath', $sambaProfilePath));
1146 if (($_SESSION['config']->get_scriptPath() != null)
1147 && ($_SESSION['config']->get_scriptPath() != '')
1148 && get_preg($sambaProfilePath, 'homeDirectory')) {
1149 $sambaProfilePathButton = new htmlAccountPageButton(static::class, 'profilePath', 'manage', '../graphics/folder.svg', true);
1150 $sambaProfilePathButton->setTitle(_('Manage profile directory'));
1151 $sambaProfilePathGroup->addElement($sambaProfilePathButton);
1152 }
1153 $sambaProfilePathGroup->addElement(new htmlHelpLink('profilePath'));
1154 $return->addField($sambaProfilePathGroup);
1155 }
1156 // logon script
1157 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonScript')) {
1158 $sambaLogonScript = '';
1159 if (isset($this->attributes['sambaLogonScript'][0])) {
1160 $sambaLogonScript = $this->attributes['sambaLogonScript'][0];
1161 }
1162 $return->add(new htmlResponsiveInputField(_('Logon script'), 'sambaLogonScript', $sambaLogonScript, 'scriptPath'));
1163 }
1164 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideWorkstations')) {
1165 $return->addLabel(new htmlOutputText(_('Samba workstations')));
1166 $userWorkstationsGroup = new htmlGroup();
1167 $userWorkstationsGroup->addElement(new htmlAccountPageButton(static::class, 'sambaUserWorkstations', 'open', _('Edit workstations')));
1168 $userWorkstationsGroup->addElement(new htmlSpacer('0.5rem', null));
1169 $userWorkstationsGroup->addElement(new htmlHelpLink('userWorkstations'));
1170 $return->addField($userWorkstationsGroup);
1171 }
1172 // Windows group
1173 $names = array_keys($this->groupRids);
1174 $wrid = false;
1175 $options = [];
1176 $selected = [];
1177 for ($i = 0; $i < count($names); $i++) {
1178 if (isset($this->attributes['sambaPrimaryGroupSID'][0]) && ($this->attributes['sambaPrimaryGroupSID'][0] == $SID . "-" . $this->groupRids[$names[$i]])) {
1179 $selected[] = $names[$i];
1180 $wrid = true;
1181 }
1182 $options[] = $names[$i];
1183 }
1184 $options[] = $this->getGroupName($unixAttributes['gidNumber'][0]);
1185 if (!$wrid) {
1186 $selected[] = $this->getGroupName($unixAttributes['gidNumber'][0]);
1187 }
1188 $return->add(new htmlResponsiveSelect('sambaPrimaryGroupSID', $options, $selected, _('Windows group'), 'group'));
1189 // display if group SID should be mapped to a well known SID
1190 $options = array_keys($this->userRids);
1191 $options[] = '-';
1192 $selected = [];
1193 if (isset($this->attributes['sambaSID'][0]) && ($this->attributes['sambaSID'][0] != '')) {
1194 $rid = substr($this->attributes['sambaSID'][0], strrpos($this->attributes['sambaSID'][0], '-') + 1, strlen($this->attributes['sambaSID'][0]));
1195 $specialRids = array_flip($this->userRids);
1196 $selected = in_array($rid, $this->userRids) ? [$specialRids[$rid]] : ['-'];
1197 }
1198 else {
1199 $selected[] = "-";
1200 }
1201 $return->add(new htmlResponsiveSelect('sambaSID', $options, $selected, _('Special user'), 'specialUser'));
1202 }
1203 // domain
1204 $return->add(new htmlResponsiveSelect('sambaDomainName', $sambaDomainNames, [$sel_domain], _('Domain'), 'domain'));
1205 // logon hours and terminal server options
1206 if ($this->get_scope() == 'user') {
1207 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonHours')) {
1208 $return->addLabel(new htmlOutputText(_('Logon hours')));
1209 $logonHoursGroup = new htmlGroup();
1210 $logonHoursGroup->addElement(new htmlAccountPageButton(static::class, 'logonHours', 'open', _('Edit')));
1211 $logonHoursGroup->addElement(new htmlSpacer('0.5rem', null));
1212 $logonHoursGroup->addElement(new htmlHelpLink('logonHours'));
1213 $return->addField($logonHoursGroup);
1214 }
1215 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideTerminalServer')) {
1216 $return->addLabel(new htmlOutputText(_('Terminal server options')));
1217 $terminalServerGroup = new htmlGroup();
1218 $terminalServerGroup->addElement(new htmlAccountPageButton(static::class, 'terminalServer', 'open', _('Edit')));
1219 $terminalServerGroup->addElement(new htmlSpacer('0.5rem', null));
1220 $terminalServerGroup->addElement(new htmlHelpLink('terminalServer'));
1221 $return->addField($terminalServerGroup);
1222 }
1223 }
1224 // reset host password
1225 if ($this->get_scope() == 'host') {
1226 // host account
1227 $return->add(new htmlHiddenInput('sambaAcctFlagsW', 'true'));
1228 // password reset
1229 $return->addLabel(new htmlOutputText(_('Reset password')));
1230 $resetPasswordGroup = new htmlGroup();
1231 $resetPasswordGroup->addElement(new htmlButton('ResetSambaPassword', _('Reset')));
1232 $resetPasswordGroup->addElement(new htmlSpacer('0.5rem', null));
1233 $resetPasswordGroup->addElement(new htmlHelpLink('resetPassword'));
1234 $return->addField($resetPasswordGroup);
1235 }
1236
1237 $return->addVerticalSpacer('2rem');
1238
1239 $remButton = new htmlButton('remObjectClass', _('Remove Samba 3 extension'));
1240 $remButton->setCSSClasses(['lam-danger']);
1241 $return->add($remButton, 12, 12, 12, 'text-center');
1242 }
1243 else {
1244 $return->add(new htmlButton('addObjectClass', _('Add Samba 3 extension')));
1245 }
1246 return $return;
1247 }
1248
1249 /**
1250 * Returns the account expiration date in printable form.
1251 *
1252 * @return string expiration date
1253 */
1254 private function formatAccountExpirationDate() {
1255 $dateValue = "-";
1256 if (isset($this->attributes['sambaKickoffTime'][0])) {
1257 if ($this->attributes['sambaKickoffTime'][0] > 2147483648) {
1258 $dateValue = "∞";
1259 }
1260 else {
1261 $date = new DateTime('@' . $this->attributes['sambaKickoffTime'][0], new DateTimeZone('UTC'));
1262 $dateValue = $date->format('d.m.Y');
1263 }
1264 }
1265 return $dateValue;
1266 }
1267
1268 /**
1269 * This function will create the HTML page to edit the allowed workstations.
1270 *
1271 * @return htmlElement meta HTML code
1272 */
1273 public function display_html_sambaUserWorkstations() {
1274 $return = new htmlResponsiveRow();
1275 if ($this->get_scope() == 'user') {
1276 // Get list of all hosts.
1277 $userWorkstations = [];
1278 $availableUserWorkstations = [];
1279
1280 $result = $this->getHostList();
1281 foreach ($result as $host) {
1282 $availableUserWorkstations[] = str_replace("$", '', $host);
1283 }
1284 sort($availableUserWorkstations, SORT_STRING);
1285 if (isset($this->attributes['sambaUserWorkstations'][0])) {
1286 $wsAttr = str_replace(' ', '', $this->attributes['sambaUserWorkstations'][0]);
1287 $userWorkstations = explode(',', $wsAttr);
1288 }
1289 $availableUserWorkstations = array_delete($userWorkstations, $availableUserWorkstations);
1290
1291 $return->add(new htmlSubTitle(_("Allowed workstations")));
1292
1293 $userWorkstationsOptions = [];
1294 foreach ($userWorkstations as $userWorkstation) {
1295 $userWorkstationsOptions[$userWorkstation] = $userWorkstation;
1296 }
1297 $availableUserWorkstationsOptions = [];
1298 foreach ($availableUserWorkstations as $availableUserWorkstation) {
1299 $availableUserWorkstationsOptions[$availableUserWorkstation] = $availableUserWorkstation;
1300 }
1301 $this->addDoubleSelectionArea($return, _("Allowed workstations"), _("Available workstations"), $userWorkstationsOptions, [], $availableUserWorkstationsOptions, [], 'workstations', false, true);
1302
1303 $return->addVerticalSpacer('2rem');
1304
1305 $backButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back'));
1306 $return->add($backButton);
1307 }
1308 return $return;
1309 }
1310
1311 /**
1312 * This function will create the HTML page to edit logon hours.
1313 *
1314 * @return htmlElement meta HTML code
1315 */
1316 public function display_html_logonHours() {
1317 $return = new htmlResponsiveRow();
1318 $timeZone = getTimeZoneOffsetHours();
1319 $titles = [_('Time'), _('Sunday'), _('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'),
1320 _('Friday'), _('Saturday')];
1321 $data = [];
1322 if (!isset($this->attributes['sambaLogonHours'][0]) || ($this->attributes['sambaLogonHours'][0] == '')) {
1323 $this->attributes['sambaLogonHours'][0] = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
1324 }
1325 // convert existing logonHours string to bit array
1326 $logonHours = $this->attributes['sambaLogonHours'][0];
1327 $temp = [];
1328 for ($i = 0; $i < strlen($logonHours); $i++) {
1329 $temp[] = $this->hex2bitstring[$logonHours[$i]];
1330 }
1331 $logonHoursRev = implode('', $temp);
1332 // reverse bits low to high (1 is 0:00 sunday, 2 is 1:00 sunday, etc)
1333 $logonHours = "";
1334 for ($i = 0; $i < 21; $i++) {
1335 $logonHours .= strrev(substr($logonHoursRev, $i * 8, 8));
1336 }
1337 $hour = [];
1338 for ($i = 0; $i < 24 * 7; $i++) {
1339 $hour[$i] = substr($logonHours, $i, 1);
1340 }
1341 // display input
1342 $boxes = [];
1343 // dynamically place boxes depending on time zone
1344 for ($i = 0; $i < 24 * 7; $i++) {
1345 $hr = $i + $timeZone;
1346 if ($hr < 0) {
1347 $hr += 24 * 7;
1348 }
1349 elseif ($hr >= 24 * 7) {
1350 $hr -= 24 * 7;
1351 }
1352 $checkbox = new htmlInputCheckbox('lh_' . $hr, (bool) $hour[(int) $hr]);
1353 $boxes[$i % 24][(int) floor($i / 24)] = $checkbox;
1354 }
1355 for ($h = 0; $h < 24; $h++) {
1356 $hour = $h;
1357 if ($h < 10) {
1358 $hour = '0' . $h;
1359 }
1360 $row = [];
1361 $row[] = new htmlOutputText("$hour:00 - $hour:59");
1362 for ($d = 0; $d < 7; $d++) {
1363 $row[] = $boxes[$h][$d];
1364 }
1365 $data[] = $row;
1366 }
1367 $return->add(new htmlResponsiveTable($titles, $data));
1368
1369 $return->addVerticalSpacer('2rem');
1370 $return->addLabel(new htmlAccountPageButton(static::class, 'attributes', 'submit', _('Ok')));
1371 $return->addField(new htmlAccountPageButton(static::class, 'attributes', 'abort', _('Cancel')));
1372 return $return;
1373 }
1374
1375 /**
1376 * This function will create the meta HTML code to show a page to change time values.
1377 *
1378 * @return htmlElement meta HTML code
1379 */
1380 public function display_html_time() {
1381 $return = new htmlResponsiveRow();
1382 $attr = 'sambaKickoffTime';
1383 $text = _('Account expiration date');
1384 $help = "expireDate";
1385 $time = time() + 3600 * 24 * 365;
1386 if (isset($this->attributes[$attr][0])) {
1387 $time = $this->attributes[$attr][0];
1388 }
1389 $date = new DateTime('@' . $time, new DateTimeZone('UTC'));
1390 for ($i = 1; $i <= 31; $i++) {
1391 $mday[] = (string) $i;
1392 }
1393 for ($i = 1; $i <= 12; $i++) {
1394 $mon[] = (string) $i;
1395 }
1396 for ($i = 2003; $i <= 2050; $i++) {
1397 $year[] = (string) $i;
1398 }
1399 $return->addLabel(new htmlOutputText($text));
1400 $dateGroup = new htmlGroup();
1401 $daySelect = new htmlSelect('expire_day', $mday, [$date->format('j')]);
1402 $daySelect->setWidth('3rem');
1403 $dateGroup->addElement($daySelect);
1404 $monthSelect = new htmlSelect('expire_mon', $mon, [$date->format('n')]);
1405 $monthSelect->setWidth('3rem');
1406 $dateGroup->addElement($monthSelect);
1407 $yearSelect = new htmlSelect('expire_yea', $year, [$date->format('Y')]);
1408 $yearSelect->setWidth('5rem');
1409 $dateGroup->addElement($yearSelect);
1410 $dateGroup->addElement(new htmlHelpLink($help));
1411 $return->addField($dateGroup);
1412 if ($this->getAccountContainer()->getAccountModule('shadowAccount') != null) {
1413 $return->add(new htmlResponsiveInputCheckbox('syncShadow', false, _('Set also for Shadow')));
1414 }
1415 if ($this->getAccountContainer()->getAccountModule('heimdalKerberos') != null) {
1416 $return->add(new htmlResponsiveInputCheckbox('syncHeimdal', false, _('Set also for Kerberos')));
1417 }
1418 if ($this->getAccountContainer()->getAccountModule('mitKerberos') != null) {
1419 $return->add(new htmlResponsiveInputCheckbox('syncMIT', false, _('Set also for Kerberos')));
1420 }
1421 if ($this->getAccountContainer()->getAccountModule('mitKerberosStructural') != null) {
1422 $return->add(new htmlResponsiveInputCheckbox('syncMITStructural', false, _('Set also for Kerberos')));
1423 }
1424 $return->addVerticalSpacer('2rem');
1425 $buttons = new htmlGroup();
1426 $buttons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'change' . $attr, _('Change')));
1427 $buttons->addElement(new htmlSpacer('0.5rem', null));
1428 if (isset($this->attributes[$attr][0])) {
1429 $buttons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'del' . $attr, _('Remove')));
1430 $buttons->addElement(new htmlSpacer('0.5rem', null));
1431 }
1432 $buttons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'back' . $attr, _('Cancel')));
1433 $return->add($buttons, 12, 12, 12, 'text-center');
1434 return $return;
1435 }
1436
1437 /**
1438 * This function will create the HTML page to edit the terminal server options.
1439 *
1440 * @return htmlElement meta HTML code
1441 */
1442 public function display_html_terminalServer() {
1443 $return = new htmlResponsiveRow();
1444 $mDial = new sambaMungedDial();
1445 if (isset($this->attributes['sambaMungedDial'][0])) {
1446 $mDial->load($this->attributes['sambaMungedDial'][0]);
1447 }
1448 // terminal server login
1449 $return->add(new htmlResponsiveInputCheckbox('tsAllowLogin', $mDial->getTsLogin(), _('Allow terminal server login'), 'tsAllowLogin'));
1450 // home directory
1451 $return->add(new htmlResponsiveInputField(_('Home directory'), 'tsHomeDir', $mDial->ctx['CtxWFHomeDir'], 'tsHomeDir'));
1452 // home drive
1453 $drives = [];
1454 for ($i = 90; $i > 67; $i--) {
1455 $drives[] = chr($i) . ':';
1456 }
1457 $selTsDrive = [];
1458 if (isset($mDial->ctx['CtxWFHomeDirDrive'])) {
1459 $selTsDrive = [$mDial->ctx['CtxWFHomeDirDrive']];
1460 }
1461 $return->add(new htmlResponsiveSelect('tsHomeDrive', $drives, $selTsDrive, _('Home drive'), 'homeDrive'));
1462 // profile path
1463 $return->add(new htmlResponsiveInputField(_('Profile path'), 'tsProfilePath', $mDial->ctx['CtxWFProfilePath'], 'tsProfilePath'));
1464 // use startup program and working dir from client
1465 $return->add(new htmlResponsiveInputCheckbox('tsInherit', $mDial->getInheritMode(), _('Inherit client startup configuration'), 'tsInherit'));
1466 // startup program
1467 $return->add(new htmlResponsiveInputField(_('Initial program'), 'tsInitialProgram', $mDial->ctx['CtxInitialProgram'], 'tsInitialProgram'));
1468 // working dir
1469 $return->add(new htmlResponsiveInputField(_('Working directory'), 'tsWorkDirectory', $mDial->ctx['CtxWorkDirectory'], 'tsWorkDirectory'));
1470 // connection time limit
1471 $tsConnectionLimit = new htmlResponsiveInputField(_('Connection time limit'), 'tsConnectionLimit', $mDial->ctx['CtxMaxConnectionTime'], 'tsTimeLimit');
1472 $tsConnectionLimit->setType('number');
1473 $return->add($tsConnectionLimit);
1474 // disconnection time limit
1475 $tsDisconnectionLimit = new htmlResponsiveInputField(_('Disconnection time limit'), 'tsDisconnectionLimit', $mDial->ctx['CtxMaxDisconnectionTime'], 'tsTimeLimit');
1476 $tsDisconnectionLimit->setType('number');
1477 $return->add($tsDisconnectionLimit);
1478 // idle time limit
1479 $tsIdleLimit = new htmlResponsiveInputField(_('Idle time limit'), 'tsIdleLimit', $mDial->ctx['CtxMaxIdleTime'], 'tsTimeLimit');
1480 $tsIdleLimit->setType('number');
1481 $return->add($tsIdleLimit);
1482 // connect client drives
1483 $return->add(new htmlResponsiveInputCheckbox('tsConnectDrives', (bool) $mDial->getConnectClientDrives(), _('Connect client drives'), 'tsConnectDrives'));
1484 // connect client printers
1485 $return->add(new htmlResponsiveInputCheckbox('tsConnectPrinters', (bool) $mDial->getConnectClientPrinters(), _('Connect client printers'), 'tsConnectPrinters'));
1486 // client printer is default
1487 $return->add(new htmlResponsiveInputCheckbox('tsClientPrinterDefault', (bool) $mDial->getDefaultPrinter(), _('Client printer is default'), 'tsClientPrinterDefault'));
1488 // shadowing
1489 $shadowOptions = [
1490 _("disabled") => "0",
1491 _("input on, notify on") => "1",
1492 _("input on, notify off") => "2",
1493 _("input off, notify on") => "3",
1494 _("input off, notify off") => "4"];
1495 $selShadow = [$mDial->getShadow()];
1496 $shadowSelect = new htmlResponsiveSelect('tsShadowing', $shadowOptions, $selShadow, _('Shadowing'), 'tsShadowing');
1497 $shadowSelect->setHasDescriptiveElements(true);
1498 $return->add($shadowSelect);
1499 // broken connection
1500 $brokenConnOptions = [
1501 _("disconnect") => "0",
1502 _("reset") => "1"];
1503 $selbrokenConn = [$mDial->getBrokenConn()];
1504 $brokenConnSelect = new htmlResponsiveSelect('tsBrokenConn', $brokenConnOptions, $selbrokenConn, _('On broken or timed out connection'), 'tsBrokenConn');
1505 $brokenConnSelect->setHasDescriptiveElements(true);
1506 $return->add($brokenConnSelect);
1507 // reconnect
1508 $reconnectOptions = [
1509 _("from any client") => "0",
1510 _("from previous client only") => "1"];
1511 $selReconnect = [$mDial->getReConn()];
1512 $reconnectSelect = new htmlResponsiveSelect('tsReconnect', $reconnectOptions, $selReconnect, _('Reconnect if disconnected'), 'tsReconnect');
1513 $reconnectSelect->setHasDescriptiveElements(true);
1514 $return->add($reconnectSelect);
1515 // buttons
1516 $return->addVerticalSpacer('2rem');
1517 $return->addLabel(new htmlAccountPageButton(static::class, 'attributes', 'submit', _('Ok')));
1518 $return->addField(new htmlAccountPageButton(static::class, 'attributes', 'abort', _('Cancel')));
1519 return $return;
1520 }
1521
1522 /**
1523 * Displays manage profile path page.
1524 *
1525 * @return htmlElement meta HTML code
1526 */
1527 public function display_html_profilePath(): htmlElement {
1528 $return = new htmlResponsiveRow();
1529 $return->addLabel(new htmlOutputText(_('Profile path')));
1530 $return->addField(new htmlOutputText($this->attributes['sambaProfilePath'][0]));
1531 $return->addVerticalSpacer('2rem');
1532 // get list of remote servers
1533 $remoteServers = $_SESSION['config']->getConfiguredScriptServers();
1534 for ($i = 0; $i < count($remoteServers); $i++) {
1535 $remoteServer = $remoteServers[$i];
1536 $label = $remoteServer->getLabel();
1537 $remote = new Remote();
1538 try {
1539 $remote->connect($remoteServer);
1540 }
1541 catch (LAMException $e) {
1542 $return->add(new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage()));
1543 continue;
1544 }
1545 $result = $remote->execute(
1546 implode(
1547 self::$SPLIT_DELIMITER,
1548 [
1549 $this->attributes['uid'][0],
1550 "home",
1551 "check",
1552 $remoteServer->getHomeDirPrefix() . $this->attributes['sambaProfilePath'][0]]
1553 ));
1554 $remote->disconnect();
1555 // remote command results
1556 if (!empty($result)) {
1557 $returnValue = trim($result);
1558 if ($returnValue === 'ok') {
1559 $return->addLabel(new htmlOutputText($label));
1560 $editGroup = new htmlGroup();
1561 $editGroup->addElement(new htmlImage('../../graphics/pass.svg', '16', '16'));
1562 $editGroup->addElement(new htmlSpacer('0.5rem', null));
1563 $editGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'delete_' . $i, _('Delete')));
1564 $return->addField($editGroup);
1565 }
1566 elseif ($returnValue === 'missing') {
1567 $return->addLabel(new htmlOutputText($label));
1568 $editGroup = new htmlGroup();
1569 $editGroup->addElement(new htmlImage('../../graphics/del.svg', '16', '16'));
1570 $editGroup->addElement(new htmlSpacer('0.5rem', null));
1571 $editGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'create_' . $i, _('Create')));
1572 $return->addField($editGroup);
1573 }
1574 elseif (trim($returnValue) !== '') {
1575 $messageParams = explode(",", $returnValue);
1576 if (isset($messageParams[2])) {
1577 $message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]), htmlspecialchars($messageParams[2]));
1578 }
1579 elseif (in_array($messageParams[0], ['ERROR', 'WARN', 'INFO'], true)) {
1580 $message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]));
1581 }
1582 else {
1583 $message = new htmlStatusMessage('WARN', htmlspecialchars($messageParams[0]));
1584 }
1585 $return->add($message);
1586 }
1587 }
1588 }
1589 $return->addVerticalSpacer('2rem');
1590 $return->add(new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back')), 12, 12, 12, 'text-center');
1591 return $return;
1592 }
1593
1594 /**
1595 * Processes user input of the profile path check page.
1596 * It checks if all input values are correct and updates the associated LDAP attributes.
1597 *
1598 * @return string[][] list of info/error messages
1599 */
1600 public function process_profilePath(): array {
1601 $return = [];
1602 $unixAttrs = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
1603 $uidNumber = $unixAttrs['uidNumber'][0];
1604 $gidNumber = $unixAttrs['gidNumber'][0];
1605 if (empty($uidNumber) || empty($gidNumber)) {
1606 return $return;
1607 }
1608 // get list of remote servers
1609 $remoteServers = $_SESSION['config']->getConfiguredScriptServers();
1610 for ($i = 0; $i < count($remoteServers); $i++) {
1611 $remoteServer = $remoteServers[$i];
1612 if (isset($_POST['form_subpage_' . static::class . '_homedir_create_' . $i])) {
1613 $remote = new Remote();
1614 try {
1615 $remote->connect($remoteServer);
1616 }
1617 catch (LAMException $e) {
1618 $return[] = ['ERROR', $e->getTitle(), $e->getMessage()];
1619 continue;
1620 }
1621 $result = $remote->execute(
1622 implode(
1623 self::$SPLIT_DELIMITER,
1624 [
1625 $this->attributes['uid'][0],
1626 "directory",
1627 "add",
1628 $remoteServer->getHomeDirPrefix() . $this->attributes['sambaProfilePath'][0],
1629 "0" . $_SESSION['config']->get_scriptRights(),
1630 $uidNumber,
1631 $gidNumber]
1632 ));
1633 $remote->disconnect();
1634 // remote command results
1635 if (!empty($result)) {
1636 $singleresult = explode(",", $result);
1637 if (in_array($singleresult[0], ['ERROR', 'WARN', 'INFO'], true)) {
1638 $return[] = $singleresult;
1639 }
1640 }
1641 }
1642 elseif (isset($_POST['form_subpage_' . static::class . '_homedir_delete_' . $i])) {
1643 $remote = new Remote();
1644 try {
1645 $remote->connect($remoteServer);
1646 }
1647 catch (LAMException $e) {
1648 $return[] = ['ERROR', $e->getTitle(), $e->getMessage()];
1649 continue;
1650 }
1651 $result = $remote->execute(
1652 implode(
1653 self::$SPLIT_DELIMITER,
1654 [
1655 $this->attributes['uid'][0],
1656 "home",
1657 "rem",
1658 $remoteServer->getHomeDirPrefix() . $this->attributes['sambaProfilePath'][0],
1659 $uidNumber
1660 ]
1661 ));
1662 $remote->disconnect();
1663 // remote command results
1664 if (!empty($result)) {
1665 $singleresult = explode(",", $result);
1666 if (in_array($singleresult[0], ['ERROR', 'WARN', 'INFO'], true)) {
1667 $return[] = $singleresult;
1668 }
1669 }
1670 }
1671 }
1672 return $return;
1673 }
1674
1675 /**
1676 * {@inheritDoc}
1677 */
1678 public function get_profileOptions(string $typeId): ?htmlResponsiveRow {
1679 $return = parent::get_profileOptions($typeId);
1680 if ($this->get_scope() == 'user') {
1681 // lists for expiration date
1682 $day = [];
1683 $mon = [];
1684 $year = [];
1685 for ($i = 1; $i <= 31; $i++) {
1686 $day[] = (string) $i;
1687 }
1688 for ($i = 1; $i <= 12; $i++) {
1689 $mon[] = (string) $i;
1690 }
1691 for ($i = 2003; $i <= 2030; $i++) {
1692 $year[] = (string) $i;
1693 }
1694 // display name
1695 $return->add(new htmlResponsiveInputField(_('Display name'), 'sambaSamAccount_displayName', '', 'displayName'));
1696 // use no password at all
1697 $return->add(new htmlResponsiveInputCheckbox('sambaSamAccount_sambaAcctFlagsN', false, _('Use no password'), 'noPassword'));
1698 // account deactivation
1699 $return->add(new htmlResponsiveInputCheckbox('sambaSamAccount_sambaAcctFlagsD', false, _('Account is deactivated'), 'deactivated'));
1700 // password never expires
1701 $return->add(new htmlResponsiveInputCheckbox('sambaSamAccount_sambaAcctFlagsX', false, _('Password does not expire'), 'noExpire'));
1702 // expiration date
1703 $return->addLabel(new htmlOutputText(_('Account expiration date')));
1704 $expireContainer = new htmlResponsiveRow();
1705 $expireContainer->add(new htmlSelect('sambaSamAccount_expire_day', $day, ['1']), 2, 2, 2, 'padding-right05');
1706 $expireContainer->add(new htmlSelect('sambaSamAccount_expire_mon', $mon, ['1']), 2, 2, 2, 'padding-left-right05');
1707 $expireContainer->add(new htmlSelect('sambaSamAccount_expire_yea', $year, ['2030']), 6, 6, 6, 'padding-left-right05');
1708 $expireContainer->add(new htmlHelpLink('expireDate'), 2, 2, 2, 'padding-left-right05');
1709 $return->addField($expireContainer);
1710 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomeDrive')) {
1711 // letter of home drive
1712 $drives = ['-'];
1713 for ($i = 90; $i > 67; $i--) {
1714 $drives[] = chr($i) . ':';
1715 }
1716 $return->add(new htmlResponsiveSelect('sambaSamAccount_sambaHomeDrive', $drives, ['-'], _('Home drive'), 'homeDrive'));
1717 }
1718 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomePath')) {
1719 // path to home directory
1720 $return->add(new htmlResponsiveInputField(_('Home path'), 'sambaSamAccount_smbhome', '', 'homePath'));
1721 }
1722 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideProfilePath')) {
1723 // profile path
1724 $return->add(new htmlResponsiveInputField(_('Profile path'), 'sambaSamAccount_profilePath', '', 'profilePath'));
1725 }
1726 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonScript')) {
1727 // logon script
1728 $return->add(new htmlResponsiveInputField(_('Logon script'), 'sambaSamAccount_logonScript', '', 'scriptPath'));
1729 }
1730 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideWorkstations')) {
1731 // allowed workstations
1732 $return->add(new htmlResponsiveInputField(_('Samba workstations'), 'sambaSamAccount_userWorkstations', '', 'workstations'));
1733 }
1734 // domains
1735 $sambaDomains = $this->getDomains();
1736 $sambaDomainNames = [];
1737 for ($i = 0; $i < count($sambaDomains); $i++) {
1738 $sambaDomainNames[] = $sambaDomains[$i]->name;
1739 }
1740 $return->add(new htmlResponsiveSelect('sambaSamAccount_sambaDomainName', $sambaDomainNames, [], _('Domain'), 'domain'));
1741 // Windows group
1742 $groups = [];
1743 foreach ($this->groupRids as $key => $value) {
1744 $groups[$key] = $value;
1745 }
1746 $groups["-"] = "-";
1747 $groupSelect = new htmlResponsiveSelect('sambaSamAccount_group', $groups, ['513'], _('Windows group'), 'group');
1748 $groupSelect->setHasDescriptiveElements(true);
1749 $return->add($groupSelect);
1750 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonHours')) {
1751 // logon hours
1752 $return->add(new htmlResponsiveInputField(_('Logon hours'), 'sambaSamAccount_logonHours', '', 'logonHoursUpload'));
1753 }
1754 }
1755 elseif ($this->get_scope() == 'host') {
1756 // domains
1757 $sambaDomains = $this->getDomains();
1758 $sambaDomainNames = [];
1759 for ($i = 0; $i < count($sambaDomains); $i++) {
1760 $sambaDomainNames[] = $sambaDomains[$i]->name;
1761 }
1762 $return->add(new htmlResponsiveSelect('sambaSamAccount_sambaDomainName', $sambaDomainNames, [], _('Domain'), 'domain'));
1763 }
1764 return $return;
1765 }
1766
1767 /**
1768 * {@inheritDoc}
1769 */
1770 public function load_profile(array $profile): void {
1771 // profile mappings in meta data
1772 parent::load_profile($profile);
1773 // add extension
1774 if (isset($profile['sambaSamAccount_addExt'][0])
1775 && ($profile['sambaSamAccount_addExt'][0] == "true")
1776 && !in_array('sambaSamAccount', $this->attributes['objectClass'])) {
1777 $this->attributes['objectClass'][] = 'sambaSamAccount';
1778 }
1779 // use no password
1780 if (isset($profile['sambaSamAccount_sambaAcctFlagsN'][0]) && ($profile['sambaSamAccount_sambaAcctFlagsN'][0] == "true")) {
1781 $this->nopwd = true;
1782 }
1783 elseif (isset($profile['sambaSamAccount_sambaAcctFlagsN'][0]) && ($profile['sambaSamAccount_sambaAcctFlagsN'][0] == "false")) {
1784 $this->nopwd = false;
1785 }
1786 // password expiration
1787 if (isset($profile['sambaSamAccount_sambaAcctFlagsX'][0]) && ($profile['sambaSamAccount_sambaAcctFlagsX'][0] == "true")) {
1788 $this->noexpire = true;
1789 }
1790 elseif (isset($profile['sambaSamAccount_sambaAcctFlagsX'][0]) && ($profile['sambaSamAccount_sambaAcctFlagsX'][0] == "false")) {
1791 $this->noexpire = false;
1792 }
1793 // deactivation
1794 if (isset($profile['sambaSamAccount_sambaAcctFlagsD'][0]) && ($profile['sambaSamAccount_sambaAcctFlagsD'][0] == "true")) {
1795 $this->deactivate($this->attributes);
1796 }
1797 elseif (isset($profile['sambaSamAccount_sambaAcctFlagsD'][0]) && ($profile['sambaSamAccount_sambaAcctFlagsD'][0] == "false")) {
1798 $this->activate($this->attributes);
1799 }
1800 if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomeDrive')) {
1801 // home drive
1802 if (isset($profile['sambaSamAccount_sambaHomeDrive'][0]) && ($profile['sambaSamAccount_sambaHomeDrive'][0] == "-")) {
1803 $this->attributes['sambaHomeDrive'][0] = '';
1804 }
1805 elseif (isset($profile['sambaSamAccount_sambaHomeDrive'][0])) {
1806 $this->attributes['sambaHomeDrive'][0] = $profile['sambaSamAccount_sambaHomeDrive'][0];
1807 }
1808 }
1809 // expiration date
1810 if (isset($profile['sambaSamAccount_expire_day'][0]) && ($profile['sambaSamAccount_expire_day'][0] != "")) {
1811 $date = DateTime::createFromFormat('j.n.Y', $profile['sambaSamAccount_expire_day'][0] . '.' . $profile['sambaSamAccount_expire_mon'][0] . '.' . $profile['sambaSamAccount_expire_yea'][0], getTimeZone());
1812 $this->attributes['sambaKickoffTime'][0] = $date->format('U');
1813 }
1814 // domain -> change SID
1815 if (isset($this->attributes['sambaSID'][0])
1816 && isset($profile['sambaSamAccount_sambaDomainName'][0])
1817 && ($profile['sambaSamAccount_sambaDomainName'][0] != "")) {
1818 $domains = $this->getDomains();
1819 $domSID = '';
1820 // find domain SID
1821 for ($i = 0; $i < count($domains); $i++) {
1822 if ($domains[$i]->name == $profile['sambaSamAccount_sambaDomainName'][0]) {
1823 $domSID = $domains[$i]->SID;
1824 break;
1825 }
1826 }
1827 // replace domain part of SID
1828 if ($domSID != '') {
1829 $SID = $this->attributes['sambaSID'][0];
1830 $rid = substr($SID, strrpos($SID, '-') + 1);
1831 $SID = $domSID . '-' . $rid;
1832 $this->attributes['sambaSID'][0] = $SID;
1833 }
1834 }
1835 // primary group
1836 if (isset($profile['sambaSamAccount_sambaDomainName'][0])) {
1837 $domains = $this->getDomains();
1838 $domSID = '';
1839 // find domain SID
1840 for ($i = 0; $i < count($domains); $i++) {
1841 if ($domains[$i]->name == $profile['sambaSamAccount_sambaDomainName'][0]) {
1842 $domSID = $domains[$i]->SID;
1843 break;
1844 }
1845 }
1846 // set primary group if selected
1847 if (($domSID != '')
1848 && isset($profile['sambaSamAccount_group'][0])
1849 && ($profile['sambaSamAccount_group'][0] != "-")) {
1850 $this->attributes['sambaPrimaryGroupSID'][0] = $domSID . "-" . $profile['sambaSamAccount_group'][0];
1851 }
1852 }
1853 }
1854
1855 /**
1856 * {@inheritDoc}
1857 */
1858 public function get_configOptions(array $scopes, array $allScopes): htmlElement|array {
1859 $return = parent::get_configOptions($scopes, $allScopes);
1860 if (!in_array('user', $scopes)) {
1861 return $return;
1862 }
1863 $configContainer = new htmlResponsiveRow();
1864 // password history
1865 $historyOptions = [
1866 _('yes - ordered ascending') => 'yes_deleteLast',
1867 _('yes - ordered descending') => 'yes_deleteFirst',
1868 _('no') => 'no'
1869 ];
1870 $historySelect = new htmlResponsiveSelect('sambaSamAccount_history', $historyOptions, ['yes_deleteLast'], _("Password history"), 'history');
1871 $historySelect->setHasDescriptiveElements(true);
1872 $configContainer->add($historySelect);
1873 // hidden options
1874 $configContainer->addVerticalSpacer('1rem');
1875 $configHiddenLabelGroup = new htmlGroup();
1876 $configHiddenLabelGroup->addElement(new htmlOutputText(_('Hidden options') . ' '));
1877 $configHiddenLabelGroup->addElement(new htmlHelpLink('hiddenOptions'));
1878 $configContainer->add($configHiddenLabelGroup);
1879 $configContainer->addVerticalSpacer('0.5rem');
1880 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideHomeDrive', false, _('Home drive'), null, true), 12, 4);
1881 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideHomePath', false, _('Home path'), null, true), 12, 4);
1882 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideProfilePath', false, _('Profile path'), null, true), 12, 4);
1883 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideLogonScript', false, _('Logon script'), null, true), 12, 4);
1884 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideSambaPwdLastSet', false, _('Last password change'), null, true), 12, 4);
1885 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideWorkstations', false, _('Samba workstations'), null, true), 12, 4);
1886 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideLogonHours', false, _('Logon hours'), null, true), 12, 4);
1887 $configContainer->add(new htmlResponsiveInputCheckbox('sambaSamAccount_hideTerminalServer', false, _('Terminal server options'), null, true), 12, 4);
1888 $configContainer->add(new htmlOutputText(''), 12, 4);
1889 $return[] = $configContainer;
1890 return $return;
1891 }
1892
1893 /**
1894 * {@inheritDoc}
1895 */
1896 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
1897 $return = [];
1898 $this->addSimplePDFField($return, 'displayName', _('Display name'));
1899 $this->addSimplePDFField($return, 'sambaHomePath', _('Home path'));
1900 $this->addSimplePDFField($return, 'sambaHomeDrive', _('Home drive'));
1901 $this->addSimplePDFField($return, 'sambaLogonScript', _('Logon script'));
1902 $this->addSimplePDFField($return, 'sambaProfilePath', _('Profile path'));
1903 $this->addSimplePDFField($return, 'sambaUserWorkstations', _('Samba workstations'));
1904 $this->addSimplePDFField($return, 'sambaDomainName', _('Domain'));
1905 $this->addSimplePDFField($return, 'sambaPrimaryGroupSID', _('Windows group'));
1906 $this->addPDFKeyValue($return, 'sambaKickoffTime', _('Account expiration date'), $this->formatAccountExpirationDate());
1907 // terminal server options
1908 if (isset($this->attributes['sambaMungedDial'][0])) {
1909 $mDial = new sambaMungedDial();
1910 $mDial->load($this->attributes['sambaMungedDial'][0]);
1911 $tsAllowLogin = _('yes');
1912 if (!$mDial->getTsLogin()) {
1913 $tsAllowLogin = _('no');
1914 }
1915 $this->addPDFKeyValue($return, 'tsAllowLogin', _('Allow terminal server login'), $tsAllowLogin);
1916 $this->addPDFKeyValue($return, 'tsHomeDir', _('Home directory') . ' (TS)', $mDial->ctx['CtxWFHomeDir']);
1917 $this->addPDFKeyValue($return, 'tsHomeDrive', _('Home drive') . ' (TS)', $mDial->ctx['CtxWFHomeDirDrive']);
1918 $this->addPDFKeyValue($return, 'tsProfilePath', _('Profile path') . ' (TS)', $mDial->ctx['CtxWFProfilePath']);
1919 $tsInherit = _('yes');
1920 if (!$mDial->getInheritMode()) {
1921 $tsInherit = _('no');
1922 }
1923 $this->addPDFKeyValue($return, 'tsInherit', _('Inherit client startup configuration') . ' (TS)', $tsInherit);
1924 $this->addPDFKeyValue($return, 'tsInitialProgram', _('Initial program') . ' (TS)', $mDial->ctx['CtxInitialProgram']);
1925 $this->addPDFKeyValue($return, 'tsWorkDirectory', _('Working directory') . ' (TS)', $mDial->ctx['CtxWorkDirectory']);
1926 $this->addPDFKeyValue($return, 'tsConnectionLimit', _('Connection time limit') . ' (TS)', $mDial->ctx['CtxMaxConnectionTime']);
1927 $this->addPDFKeyValue($return, 'tsDisconnectionLimit', _('Disconnection time limit') . ' (TS)', $mDial->ctx['CtxMaxDisconnectionTime']);
1928 $this->addPDFKeyValue($return, 'tsIdleLimit', _('Idle time limit') . ' (TS)', $mDial->ctx['CtxMaxIdleTime']);
1929 $tsConnectDrives = _('yes');
1930 if (!$mDial->getConnectClientDrives()) {
1931 $tsConnectDrives = _('no');
1932 }
1933 $this->addPDFKeyValue($return, 'tsConnectDrives', _('Connect client drives') . ' (TS)', $tsConnectDrives);
1934 $tsConnectPrinters = _('yes');
1935 if (!$mDial->getConnectClientPrinters()) {
1936 $tsConnectPrinters = _('no');
1937 }
1938 $this->addPDFKeyValue($return, 'tsConnectPrinters', _('Connect client printers') . ' (TS)', $tsConnectPrinters);
1939 $tsClientPrinterDefault = _('yes');
1940 if (!$mDial->getDefaultPrinter()) {
1941 $tsClientPrinterDefault = _('no');
1942 }
1943 $this->addPDFKeyValue($return, 'tsClientPrinterDefault', _('Client printer is default') . ' (TS)', $tsClientPrinterDefault);
1944 $shadowOptions = [
1945 '0' => _("disabled"),
1946 '1' => _("input on, notify on"),
1947 '2' => _("input on, notify off"),
1948 '3' => _("input off, notify on"),
1949 '4' => _("input off, notify off")];
1950 $tsShadowing = '';
1951 if (($mDial->getShadow() != null) && is_numeric($mDial->getShadow())) {
1952 $tsShadowing = $shadowOptions[$mDial->getShadow()];
1953 }
1954 $this->addPDFKeyValue($return, 'tsShadowing', _('Shadowing') . ' (TS)', $tsShadowing);
1955 $brokenConnOptions = [
1956 '0' => _("disconnect"),
1957 '1' => _("reset")];
1958 $tsBrokenConn = '';
1959 if (($mDial->getBrokenConn() != null) && is_numeric($mDial->getBrokenConn())) {
1960 $tsBrokenConn = $brokenConnOptions[$mDial->getBrokenConn()];
1961 }
1962 $this->addPDFKeyValue($return, 'tsBrokenConn', _('On broken or timed out connection') . ' (TS)', $tsBrokenConn);
1963 $reconnectOptions = [
1964 '0' => _("from any client"),
1965 '1' => _("from previous client only")];
1966 $tsReconnect = '';
1967 if (($mDial->getReConn() != null) && is_numeric($mDial->getReConn())) {
1968 $tsReconnect = $reconnectOptions[$mDial->getReConn()];
1969 }
1970 $this->addPDFKeyValue($return, 'tsReconnect', _('Reconnect if disconnected') . ' (TS)', $tsReconnect);
1971 }
1972 return $return;
1973 }
1974
1975 /**
1976 * {@inheritDoc}
1977 */
1978 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
1979 $errors = [];
1980 // get list of Samba 3 domains
1981 $domains = $this->getDomains();
1982 // get list of Unix groups and their sambaSID + gidNumber
1983 $groupList = searchLDAPByFilter('objectClass=posixGroup', ['cn', 'sambaSID', 'gidNumber'], ['group']);
1984 $groups_cn = [];
1985 for ($i = 0; $i < count($groupList); $i++) {
1986 if (isset($groupList[$i]['sambasid'][0])) {
1987 $groups_cn[$groupList[$i]['cn'][0]]['SID'] = $groupList[$i]['sambasid'][0];
1988 }
1989 if (isset($groupList[$i]['gidnumber'][0])) {
1990 $groups_cn[$groupList[$i]['cn'][0]]['gid'] = $groupList[$i]['gidnumber'][0];
1991 }
1992 }
1993 if ($this->get_scope() == 'user') {
1994 for ($i = 0; $i < count($rawAccounts); $i++) {
1995 if (!in_array("sambaSamAccount", $partialAccounts[$i]['objectClass'])) {
1996 $partialAccounts[$i]['objectClass'][] = "sambaSamAccount";
1997 }
1998 // displayName
1999 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'sambaSamAccount_displayName', 'displayName',
2000 'realname', $this->messages['displayName'][0], $errors);
2001 // password
2002 $partialAccounts[$i]['sambaPwdLastSet'] = time();
2003 if (!get_preg($rawAccounts[$i][$ids['sambaSamAccount_password']], 'password')) {
2004 $errMsg = $this->messages['sambaNTPassword'][2];
2005 $errMsg[] = [$i];
2006 $errors[] = $errMsg;
2007 }
2008 // use Unix password
2009 if ($rawAccounts[$i][$ids['sambaSamAccount_pwdUnix']] == "") { // default: use Unix
2010 $partialAccounts[$i]['sambaNTPassword'] = ntPassword($rawAccounts[$i][$ids['posixAccount_password']]);
2011 }
2012 elseif (in_array($rawAccounts[$i][$ids['sambaSamAccount_pwdUnix']], ['true', 'false'])) {
2013 if ($rawAccounts[$i][$ids['sambaSamAccount_pwdUnix']] == 'true') { // use Unix
2014 $partialAccounts[$i]['sambaNTPassword'] = ntPassword($rawAccounts[$i][$ids['posixAccount_password']]);
2015 }
2016 else { // use given password
2017 $partialAccounts[$i]['sambaNTPassword'] = ntPassword($rawAccounts[$i][$ids['sambaSamAccount_password']]);
2018 }
2019 }
2020 else {
2021 $errMsg = $this->messages['pwdUnix'][0];
2022 $errMsg[] = [$i];
2023 $errors[] = $errMsg;
2024 }
2025 // use no password
2026 if ($rawAccounts[$i][$ids['sambaSamAccount_noPassword']] != "") {
2027 if (in_array($rawAccounts[$i][$ids['sambaSamAccount_noPassword']], ['true', 'false'])) {
2028 if ($rawAccounts[$i][$ids['sambaSamAccount_noPassword']] == 'true') {
2029 $partialAccounts[$i]['sambaNTPassword'] = 'NO PASSWORD*****';
2030 }
2031 }
2032 else {
2033 $errMsg = $this->messages['noPassword'][0];
2034 $errMsg[] = [$i];
2035 $errors[] = $errMsg;
2036 }
2037 }
2038 // account flags
2039 $flag_expire = false;
2040 $flag_deactivated = false;
2041 // password does not expire
2042 if ($rawAccounts[$i][$ids['sambaSamAccount_noExpire']] != "") {
2043 if (in_array($rawAccounts[$i][$ids['sambaSamAccount_noExpire']], ['true', 'false'])) {
2044 if ($rawAccounts[$i][$ids['sambaSamAccount_noExpire']] == 'false') {
2045 $flag_expire = true;
2046 }
2047 }
2048 else {
2049 $errMsg = $this->messages['noExpire'][0];
2050 $errMsg[] = [$i];
2051 $errors[] = $errMsg;
2052 }
2053 }
2054 // account is deactivated
2055 if ($rawAccounts[$i][$ids['sambaSamAccount_deactivated']] != "") {
2056 if (in_array($rawAccounts[$i][$ids['sambaSamAccount_deactivated']], ['true', 'false'])) {
2057 if ($rawAccounts[$i][$ids['sambaSamAccount_deactivated']] == 'true') {
2058 $flag_deactivated = true;
2059 }
2060 }
2061 else {
2062 $errMsg = $this->messages['deactivated'][0];
2063 $errMsg[] = [$i];
2064 $errors[] = $errMsg;
2065 }
2066 }
2067 // set flags
2068 $flags = "[";
2069 if ($flag_deactivated) {
2070 $flags .= "D";
2071 }
2072 if (!$flag_expire) {
2073 $flags .= "X";
2074 }
2075 $flags .= "U";
2076 // Expand string to fixed length
2077 $flags = str_pad($flags, 12);
2078 // End character
2079 $flags .= "]";
2080 $partialAccounts[$i]['sambaacctflags'] = $flags;
2081 // expiration date
2082 if ($rawAccounts[$i][$ids['sambaSamAccount_expireDate']] != "") {
2083 if (get_preg($rawAccounts[$i][$ids['sambaSamAccount_expireDate']], 'date')) {
2084 $parts = explode("-", $rawAccounts[$i][$ids['sambaSamAccount_expireDate']]);
2085 $date = DateTime::createFromFormat('j.n.Y', $parts[0] . '.' . $parts[1] . '.' . $parts[2], getTimeZone());
2086 $partialAccounts[$i]['sambaKickoffTime'] = $date->format('U');
2087 }
2088 else {
2089 $errMsg = $this->messages['expireDate'][0];
2090 $errMsg[] = [$i];
2091 $errors[] = $errMsg;
2092 }
2093 }
2094 // home drive
2095 if ($rawAccounts[$i][$ids['sambaSamAccount_homeDrive']] != "") {
2096 if (preg_match("/[d-z]:/i", $rawAccounts[$i][$ids['sambaSamAccount_homeDrive']])) {
2097 $partialAccounts[$i]['sambaHomeDrive'] = $rawAccounts[$i][$ids['sambaSamAccount_homeDrive']];
2098 }
2099 else {
2100 $errMsg = $this->messages['homeDrive'][0];
2101 $errMsg[] = [$i];
2102 $errors[] = $errMsg;
2103 }
2104 }
2105 // home path
2106 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'sambaSamAccount_homePath', 'sambaHomePath',
2107 'UNC', $this->messages['homePath'][2], $errors);
2108 // profile path
2109 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'sambaSamAccount_profilePath', 'sambaProfilePath',
2110 'UNC', $this->messages['profilePath'][2], $errors);
2111 // logon script
2112 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'sambaSamAccount_logonScript', 'sambaLogonScript',
2113 'logonscript', $this->messages['logonScript'][2], $errors);
2114 // workstations
2115 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'sambaSamAccount_workstations', 'sambaUserWorkstations',
2116 'workstations', $this->messages['workstations'][1], $errors);
2117 // domain
2118 $domIndex = -1;
2119 for ($d = 0; $d < count($domains); $d++) {
2120 if ($domains[$d]->name == $rawAccounts[$i][$ids['sambaSamAccount_domain']]) {
2121 $domIndex = $d;
2122 break;
2123 }
2124 }
2125 if ($domIndex > -1) {
2126 $partialAccounts[$i]['sambaDomainName'] = $domains[$domIndex]->name;
2127 $partialAccounts[$i]['sambaSID'] = $domains[$domIndex]->SID;
2128 }
2129 else {
2130 $errMsg = $this->messages['domain'][0];
2131 $errMsg[] = [$i];
2132 $errors[] = $errMsg;
2133 }
2134 // group
2135 if ($rawAccounts[$i][$ids['sambaSamAccount_group']] != "") {
2136 if (get_preg($rawAccounts[$i][$ids['sambaSamAccount_group']], 'groupname')
2137 && (isset($groups_cn[$rawAccounts[$i][$ids['sambaSamAccount_group']]]))) {
2138 if (isset($groups_cn[$rawAccounts[$i][$ids['sambaSamAccount_group']]]['SID'])) {
2139 $partialAccounts[$i]['sambaPrimaryGroupSID'] = $groups_cn[$rawAccounts[$i][$ids['sambaSamAccount_group']]]['SID'];
2140 }
2141 else {
2142 $partialAccounts[$i]['sambaPrimaryGroupSID'] = $domains[$domIndex]->SID . '-' .
2143 (intval($groups_cn[$rawAccounts[$i][$ids['sambaSamAccount_group']]]['gid']) * 2 +
2144 $domains[$domIndex]->RIDbase + 1);
2145 }
2146 }
2147 elseif (in_array($rawAccounts[$i][$ids['sambaSamAccount_group']], array_keys($this->groupRids))) {
2148 $partialAccounts[$i]['sambaPrimaryGroupSID'] = $domains[$domIndex]->SID . '-' . $this->groupRids[$rawAccounts[$i][$ids['sambaSamAccount_group']]];
2149 }
2150 else {
2151 $errMsg = $this->messages['group'][0];
2152 $errMsg[] = [$i];
2153 $errors[] = $errMsg;
2154 }
2155 }
2156 else {
2157 // default domain users
2158 $partialAccounts[$i]['sambaPrimaryGroupSID'] = $domains[$domIndex]->SID . '-' . $this->groupRids[_('Domain users')];
2159 }
2160 // special user
2161 if ($rawAccounts[$i][$ids['sambaSamAccount_rid']] != "") {
2162 if (in_array($rawAccounts[$i][$ids['sambaSamAccount_rid']], array_keys($this->userRids))) {
2163 $partialAccounts[$i]['sambaSID'] .= '-' . $this->userRids[$rawAccounts[$i][$ids['sambaSamAccount_rid']]];
2164 }
2165 elseif (get_preg($rawAccounts[$i][$ids['sambaSamAccount_rid']], 'digit')) {
2166 $partialAccounts[$i]['sambaSID'] .= '-' . $rawAccounts[$i][$ids['sambaSamAccount_rid']];
2167 }
2168 else {
2169 $errMsg = $this->messages['rid'][2];
2170 $errMsg[] = [$i];
2171 $errors[] = $errMsg;
2172 }
2173 }
2174 else {
2175 // default RID uid*2 + RIDBase
2176 $partialAccounts[$i]['sambaSID'] .= '-' . ($partialAccounts[$i]['uidNumber'] * 2 + $domains[$domIndex]->RIDbase);
2177 }
2178 // logon hours
2179 $partialAccounts[$i]['sambaLogonHours'] = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
2180 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'sambaSamAccount_logonHours', 'sambaLogonHours',
2181 'sambaLogonHours', $this->messages['logonHours'][1], $errors);
2182 }
2183 }
2184 else { // hosts
2185 for ($i = 0; $i < count($rawAccounts); $i++) {
2186 if (!in_array("sambaSamAccount", $partialAccounts[$i]['objectClass'])) {
2187 $partialAccounts[$i]['objectClass'][] = "sambaSamAccount";
2188 }
2189 // domain
2190 $domIndex = -1;
2191 for ($d = 0; $d < count($domains); $d++) {
2192 if ($domains[$d]->name == $rawAccounts[$i][$ids['sambaSamAccount_domain']]) {
2193 $domIndex = $d;
2194 break;
2195 }
2196 }
2197 if ($domIndex > -1) {
2198 $partialAccounts[$i]['sambaDomainName'] = $domains[$domIndex]->name;
2199 $partialAccounts[$i]['sambaSID'] = $domains[$domIndex]->SID;
2200 $partialAccounts[$i]['sambaPrimaryGroupSID'] = $domains[$domIndex]->SID . " - 515";
2201 }
2202 else {
2203 $errMsg = $this->messages['domain'][0];
2204 $errMsg[] = [$i];
2205 $errors[] = $errMsg;
2206 }
2207 // RID
2208 if ($rawAccounts[$i][$ids['sambaSamAccount_rid']] != "") {
2209 if (get_preg($rawAccounts[$i][$ids['sambaSamAccount_rid']], 'digit')) {
2210 $partialAccounts[$i]['sambaSID'] .= '-' . $rawAccounts[$i][$ids['sambaSamAccount_rid']];
2211 }
2212 else {
2213 $errMsg = $this->messages['rid'][3];
2214 $errMsg[] = [$i];
2215 $errors[] = $errMsg;
2216 }
2217 }
2218 else {
2219 // default RID uid*2 + RIDBase
2220 $partialAccounts[$i]['sambaSID'] .= '-' . ($partialAccounts[$i]['uidNumber'] * 2 + $domains[$domIndex]->RIDbase);
2221 }
2222 // passwords ( = host name)
2223 $partialAccounts[$i]['sambaPwdLastSet'] = time();
2224 $partialAccounts[$i]['sambaNTPassword'] = ntPassword(substr($partialAccounts[$i]['uid'], 0, strlen($partialAccounts[$i]['uid']) - 1));
2225 // flags
2226 $partialAccounts[$i]['sambaacctflags'] = "[W ]";
2227 }
2228 }
2229 return $errors;
2230 }
2231
2232 /**
2233 * {@inheritDoc}
2234 */
2235 public function getSelfServiceSettings(selfServiceProfile $profile): ?htmlElement {
2236 $selfServiceContainer = new htmlResponsiveRow();
2237 // domain suffix
2238 $selfServiceDomainSuffix = new htmlResponsiveInputField(_('Domain suffix'), 'sambaSamAccount_domainSuffix', null, ['domainSuffix', static::class]);
2239 $selfServiceContainer->add($selfServiceDomainSuffix);
2240 // password history
2241 $historyOptions = [
2242 _('yes - ordered ascending') => 'yes_deleteLast',
2243 _('yes - ordered descending') => 'yes_deleteFirst',
2244 _('no') => 'no'
2245 ];
2246 $historySelect = new htmlResponsiveSelect('sambaSamAccount_history', $historyOptions, ['yes_deleteLast'], _("Password history"), ['history', static::class]);
2247 $historySelect->setHasDescriptiveElements(true);
2248 $selfServiceContainer->add($historySelect);
2249 return $selfServiceContainer;
2250 }
2251
2252 /**
2253 * {@inheritDoc}
2254 */
2255 public function getSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
2256 $return = [];
2257 if ($passwordChangeOnly) {
2258 return $return; // no input fields as long no LDAP content can be read
2259 }
2260 if (!isset($attributes['objectClass']) || !in_array_ignore_case('sambaSamAccount', $attributes['objectClass'])) {
2261 return $return;
2262 }
2263 if (in_array('password', $fields)) {
2264 $group = new htmlGroup();
2265 $pwd1 = new htmlResponsiveInputField($this->getSelfServiceLabel('password', _('New password')), 'sambaSamAccount_password');
2266 $pwd1->setIsPassword(true, true);
2267 $group->addElement($pwd1);
2268 $pwd2 = new htmlResponsiveInputField(_('Reenter password'), 'sambaSamAccount_password2');
2269 $pwd2->setIsPassword(true);
2270 $pwd2->setSameValueFieldID('sambaSamAccount_password');
2271 $group->addElement($pwd2);
2272 $row = new htmlResponsiveRow();
2273 $row->add($group);
2274 $return['password'] = $row;
2275 }
2276 if (in_array('sambaPwdLastSet', $fields)) {
2277 $sambaPwdLastSet = '';
2278 if (isset($attributes['sambaPwdLastSet'][0])) {
2279 $time = new DateTime('@' . $attributes['sambaPwdLastSet'][0], new DateTimeZone('UTC'));
2280 $time->setTimezone(getTimeZone());
2281 $sambaPwdLastSet = $time->format('d.m.Y H:i');
2282 }
2283 $row = new htmlResponsiveRow();
2284 $row->addLabel(new htmlOutputText($this->getSelfServiceLabel('sambaPwdLastSet', _('Last password change'))));
2285 $row->addField(new htmlOutputText($sambaPwdLastSet));
2286 $return['sambaPwdLastSet'] = $row;
2287 }
2288 return $return;
2289 }
2290
2291 /**
2292 * {@inheritDoc}
2293 */
2294 public function checkSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
2295 $return = ['messages' => [], 'add' => [], 'del' => [], 'mod' => [], 'info' => []];
2296 if (!isset($attributes['objectClass']) || !in_array_ignore_case('sambaSamAccount', $attributes['objectClass'])) {
2297 return $return;
2298 }
2299 if (in_array('password', $fields)
2300 && isset($_POST['sambaSamAccount_password'])
2301 && ($_POST['sambaSamAccount_password'] != '')) {
2302 if ($_POST['sambaSamAccount_password'] != $_POST['sambaSamAccount_password2']) {
2303 $return['messages'][] = $this->messages['sambaNTPassword'][0];
2304 }
2305 elseif (!get_preg($_POST['sambaSamAccount_password'], 'password')) {
2306 $return['messages'][] = $this->messages['sambaNTPassword'][1];
2307 }
2308 else {
2309 $userName = empty($attributes['uid'][0]) ? null : $attributes['uid'][0];
2310 $additionalAttrs = [];
2311 if (!empty($attributes['sn'][0])) {
2312 $additionalAttrs[] = $attributes['sn'][0];
2313 }
2314 if (!empty($attributes['givenName'][0])) {
2315 $additionalAttrs[] = $attributes['givenName'][0];
2316 }
2317 $pwdPolicyResult = checkPasswordStrength($_POST['sambaSamAccount_password'], $userName, $additionalAttrs);
2318 if ($pwdPolicyResult->isValid()) {
2319 $return['mod']['sambaNTPassword'][0] = ntPassword($_POST['sambaSamAccount_password']);
2320 $return['info']['sambaUserPasswordClearText'][0] = $_POST['sambaSamAccount_password'];
2321 $this->doSelfServicePasswordHistoryAndMinAge($attributes, $return);
2322 if (array_key_exists('sambaPwdLastSet', $attributes)) {
2323 $return['mod']['sambaPwdLastSet'][0] = time();
2324 }
2325 }
2326 else {
2327 $return['messages'][] = ['ERROR', $pwdPolicyResult->getTextMessage()];
2328 }
2329 }
2330 }
2331 if (isset($_POST['posixAccount_password']) && ($_POST['posixAccount_password'] != '')) {
2332 if ($_POST['posixAccount_password'] != $_POST['posixAccount_password2']) {
2333 return $return;
2334 }
2335 elseif (!get_preg($_POST['posixAccount_password'], 'password')) {
2336 return $return;
2337 }
2338 else {
2339 $setPassword = false;
2340 // sync password
2341 if (in_array('syncNTPassword', $fields)) {
2342 $return['mod']['sambaNTPassword'][0] = ntPassword($_POST['posixAccount_password']);
2343 $setPassword = true;
2344 }
2345 if ($setPassword) {
2346 $return['info']['sambaUserPasswordClearText'][0] = $_POST['posixAccount_password'];
2347 $this->doSelfServicePasswordHistoryAndMinAge($attributes, $return);
2348 if (in_array('syncSambaPwdLastSet', $fields)) {
2349 $return['mod']['sambaPwdLastSet'][0] = time();
2350 }
2351 }
2352 }
2353 }
2354 return $return;
2355 }
2356
2357 /**
2358 * Checks password history and password minimum age and updates history.
2359 *
2360 * @param array<string, string[]|string> $attributes LDAP attributes of current account
2361 * @param array<string, mixed> $return return object of checkSelfServiceOptions()
2362 */
2363 private function doSelfServicePasswordHistoryAndMinAge($attributes, &$return): void {
2364 if (!empty($this->selfServiceSettings->moduleSettings['sambaSamAccount_domainSuffix'][0])) {
2365 $sambaDomain = $this->getUserDomain($attributes, $_SESSION['ldapHandle']->getServer(), $this->selfServiceSettings->moduleSettings['sambaSamAccount_domainSuffix'][0]);
2366 if ($sambaDomain == null) {
2367 return;
2368 }
2369 if (!empty($sambaDomain->pwdHistoryLength)
2370 && ($sambaDomain->pwdHistoryLength > 0)) {
2371 if (sambaSamAccount::oldPasswordUsed($return['info']['sambaUserPasswordClearText'][0], $attributes, $sambaDomain)) {
2372 $return['messages'][] = ['ERROR', _('You are reusing an old password. Please choose a different password.')];
2373 }
2374 elseif (sambaSamAccount::isPasswordHistoryEnabled($this->selfServiceSettings->moduleSettings)) {
2375 // update password history
2376 $sambaPasswordHistory = empty($attributes['sambaPasswordHistory']) ? [] : $attributes['sambaPasswordHistory'];
2377 while (count($sambaPasswordHistory) > ($sambaDomain->pwdHistoryLength - 1)) {
2378 if (empty($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0]) || ($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
2379 array_pop($sambaPasswordHistory);
2380 }
2381 else {
2382 array_shift($sambaPasswordHistory);
2383 }
2384 }
2385 if (empty($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0]) || ($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
2386 array_unshift($sambaPasswordHistory, sambaSamAccount::createHistoryEntry($return['info']['sambaUserPasswordClearText'][0]));
2387 }
2388 else {
2389 $sambaPasswordHistory[] = sambaSamAccount::createHistoryEntry($return['info']['sambaUserPasswordClearText'][0]);
2390 }
2391 $sambaPasswordHistory = array_values($sambaPasswordHistory);
2392 if (empty($attributes['sambaPasswordHistory'])) {
2393 $return['add']['sambaPasswordHistory'] = $sambaPasswordHistory;
2394 }
2395 else {
2396 $return['mod']['sambaPasswordHistory'] = $sambaPasswordHistory;
2397 }
2398 }
2399 }
2400 // check min age
2401 if (!empty($sambaDomain->minPwdAge) && ($sambaDomain->minPwdAge > 0) && !empty($attributes['sambaPwdLastSet'][0])) {
2402 $timeVal = intval($attributes['sambaPwdLastSet'][0]) + $sambaDomain->minPwdAge;
2403 $time = new DateTime('@' . $timeVal, new DateTimeZone('UTC'));
2404 $time->setTimezone(getTimeZone());
2405 $now = new DateTime('now', getTimeZone());
2406 if ($time > $now) {
2407 $return['messages'][] = ['ERROR', _('You are not yet allowed to change your password.')];
2408 }
2409 }
2410 }
2411 }
2412
2413 /**
2414 * {@inheritDoc}
2415 */
2416 public function managesPasswordAttributes(): bool {
2417 return ($this->get_scope() === "user");
2418 }
2419
2420 /**
2421 * {@inheritDoc}
2422 */
2423 public function supportsForcePasswordChange(): bool {
2424 return true;
2425 }
2426
2427 /**
2428 * {@inheritDoc}
2429 */
2430 public function passwordChangeRequested(string $password, array $modules, bool $forcePasswordChange): array {
2431 if (!in_array(static::class, $modules)) {
2432 return [];
2433 }
2434 $errors = [];
2435 $this->attributes['sambaNTPassword'][0] = ntPassword($password);
2436 $this->attributes['sambaPwdLastSet'][0] = time();
2437 if ($forcePasswordChange) {
2438 $this->attributes['sambaPwdLastSet'][0] = '0';
2439 }
2440 // password history entry
2441 $sambaDomain = $this->getUserDomain($this->attributes);
2442 if ($sambaDomain != null) {
2443 // password history check
2444 $oldPasswordUsed = sambaSamAccount::oldPasswordUsed($password, $this->orig, $sambaDomain);
2445 if ($oldPasswordUsed) {
2446 $errors[] = ['ERROR', _('You are reusing an old password. Please choose a different password.')];
2447 }
2448 // set new history entry
2449 $historyLength = $sambaDomain->pwdHistoryLength;
2450 if (sambaSamAccount::isPasswordHistoryEnabled($this->moduleSettings) && !$oldPasswordUsed && !empty($historyLength) && ($historyLength > 0)) {
2451 if (!empty($this->orig['sambaPasswordHistory'][0])) {
2452 $this->attributes['sambaPasswordHistory'] = $this->orig['sambaPasswordHistory'];
2453 }
2454 else {
2455 $this->attributes['sambaPasswordHistory'] = [];
2456 }
2457 while (count($this->attributes['sambaPasswordHistory']) > ($historyLength - 1)) {
2458 if (empty($this->moduleSettings['sambaSamAccount_history'][0]) || ($this->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
2459 array_pop($this->attributes['sambaPasswordHistory']);
2460 }
2461 else {
2462 array_shift($this->attributes['sambaPasswordHistory']);
2463 }
2464 }
2465 if (empty($this->moduleSettings['sambaSamAccount_history'][0]) || ($this->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
2466 array_unshift($this->attributes['sambaPasswordHistory'], sambaSamAccount::createHistoryEntry($password));
2467 }
2468 else {
2469 $this->attributes['sambaPasswordHistory'][] = sambaSamAccount::createHistoryEntry($password);
2470 }
2471 $this->attributes['sambaPasswordHistory'] = array_values($this->attributes['sambaPasswordHistory']);
2472 }
2473 }
2474 return $errors;
2475 }
2476
2477 /**
2478 * Returns if an old password is used.
2479 *
2480 * @param string $password new password
2481 * @param array<string, string[]|string> $attributes LDAP attributes
2482 * @param samba3domain|null $sambaDomain domain
2483 * @return bool old password used
2484 */
2485 public static function oldPasswordUsed($password, $attributes, $sambaDomain): bool {
2486 $attributes = array_change_key_case($attributes);
2487 if (empty($attributes['sambapasswordhistory'][0]) || ($sambaDomain === null)
2488 || !is_numeric($sambaDomain->pwdHistoryLength) || ($sambaDomain->pwdHistoryLength < 1)) {
2489 return false;
2490 }
2491 foreach ($attributes['sambapasswordhistory'] as $historyEntry) {
2492 if (sambaSamAccount::validateHistoryEntry($password, $historyEntry)) {
2493 return true;
2494 }
2495 }
2496 return false;
2497 }
2498
2499 /**
2500 * Returns the domain object of the user's domain.
2501 *
2502 * @param array<string, string[]|string> $attributes LDAP attributes
2503 * @param Connection|null $server LDAP connection (leave empty for admin interface)
2504 * @param string $suffix LDAP search suffix (leave empty for admin interface)
2505 * @return samba3domain|null domain
2506 */
2507 public function getUserDomain($attributes, $server = null, $suffix = null): ?samba3domain {
2508 $attributes = array_change_key_case($attributes);
2509 $sambaDomains = $this->getDomains($server, $suffix);
2510 if (count($sambaDomains) > 0) {
2511 $domainSID = null;
2512 if (isset($attributes['sambasid'][0]) && $attributes['sambasid'][0] != '') {
2513 $domainSID = substr($attributes['sambasid'][0], 0, strrpos($attributes['sambasid'][0], "-"));
2514 }
2515 for ($i = 0; $i < count($sambaDomains); $i++) {
2516 if (!empty($domainSID)) {
2517 if (($domainSID == $sambaDomains[$i]->SID) && !empty($sambaDomains[$i]->pwdHistoryLength)) {
2518 return $sambaDomains[$i];
2519 }
2520 }
2521 elseif (isset($attributes['sambadomainname'][0]) && ($attributes['sambadomainname'][0] != '')) {
2522 if (($attributes['sambadomainname'][0] == $sambaDomains[$i]->name) && !empty($sambaDomains[$i]->pwdHistoryLength)) {
2523 return $sambaDomains[$i];
2524 }
2525 }
2526 }
2527 }
2528 return null;
2529 }
2530
2531 /**
2532 * Returns the group name of the group with the given group ID.
2533 *
2534 * @param string $groupID group ID
2535 * @return string|null group name
2536 */
2537 private function getGroupName($groupID) {
2538 $results = searchLDAPByAttribute('gidNumber', $groupID, 'posixGroup', ['cn'], ['group']);
2539 if ((count($results) > 0) && isset($results[0]['cn'][0])) {
2540 return $results[0]['cn'][0];
2541 }
2542 return null;
2543 }
2544
2545 /**
2546 * Returns the time when the user needs to change his password.
2547 *
2548 * @param samba3domain[] $domains list of domain objects
2549 * @param string|null $selectedDomain selected domain name
2550 * @return string formatted time
2551 */
2552 private function getPasswordMustChangeTime($domains, $selectedDomain): string {
2553 $return = '-';
2554 // check if password expires at all
2555 if ($this->noexpire) {
2556 return $return;
2557 }
2558 // check if there is a time set for the last password change
2559 if (!isset($this->attributes['sambaPwdLastSet'][0])) {
2560 return $return;
2561 }
2562 for ($i = 0; $i < count($domains); $i++) {
2563 if ($domains[$i]->name == $selectedDomain) {
2564 // check if a domain policy is set
2565 if (!isset($domains[$i]->maxPwdAge) || ($domains[$i]->maxPwdAge < 0)) {
2566 return $return;
2567 }
2568 $timeVal = intval($this->attributes['sambaPwdLastSet'][0]) + $domains[$i]->maxPwdAge;
2569 $time = new DateTime('@' . $timeVal, new DateTimeZone('UTC'));
2570 $time->setTimezone(getTimeZone());
2571 return $time->format('d.m.Y H:i');
2572 }
2573 }
2574 return $return;
2575 }
2576
2577 /**
2578 * Returns the time when the user can change his password.
2579 *
2580 * @param samba3domain[] $domains list of domain objects
2581 * @param string $selectedDomain selected domain name
2582 * @return string formatted time
2583 */
2584 private function getPasswordCanChangeTime($domains, $selectedDomain): string {
2585 $return = '-';
2586 // check if there is a time set for the last password change
2587 if (!isset($this->attributes['sambaPwdLastSet'][0])) {
2588 return $return;
2589 }
2590 for ($i = 0; $i < count($domains); $i++) {
2591 if ($domains[$i]->name == $selectedDomain) {
2592 // check if a domain policy is set
2593 if (!isset($domains[$i]->minPwdAge) || ($domains[$i]->minPwdAge < 0)) {
2594 return $return;
2595 }
2596 $timeVal = intval($this->attributes['sambaPwdLastSet'][0]) + $domains[$i]->minPwdAge;
2597 $time = new DateTime('@' . $timeVal, new DateTimeZone('UTC'));
2598 $time->setTimezone(getTimeZone());
2599 return $time->format('d.m.Y H:i');
2600 }
2601 }
2602 return $return;
2603 }
2604
2605 /**
2606 * Returns a list of existing hosts.
2607 *
2608 * @return string[] host names
2609 */
2610 private function getHostList(): array {
2611 if ($this->cachedHostList !== null) {
2612 return $this->cachedHostList;
2613 }
2614 $this->cachedHostList = [];
2615 $entries = searchLDAPByAttribute('uid', '*', 'sambaSamAccount', ['uid'], ['host']);
2616 foreach ($entries as $entry) {
2617 $this->cachedHostList[] = $entry['uid'][0];
2618 }
2619 return $this->cachedHostList;
2620 }
2621
2622 /**
2623 * Returns a list of existing hosts.
2624 *
2625 * @return array<string, string> GID => sambaSID
2626 */
2627 private function getGroupSIDList(): array {
2628 if ($this->cachedGroupSIDList !== null) {
2629 return $this->cachedGroupSIDList;
2630 }
2631 $this->cachedGroupSIDList = [];
2632 $result = searchLDAPByAttribute('sambaSID', '*', 'sambaGroupMapping', ['gidNumber', 'sambaSID'], ['group']);
2633 for ($i = 0; $i < count($result); $i++) {
2634 if (isset($result[$i]['gidnumber'][0])) {
2635 $this->cachedGroupSIDList[$result[$i]['gidnumber'][0]] = $result[$i]['sambasid'][0];
2636 }
2637 }
2638 return $this->cachedGroupSIDList;
2639 }
2640
2641 /**
2642 * Returns a list of existing Samba 3 domains.
2643 *
2644 * @param Connection|null $server LDAP connection (leave empty for admin interface)
2645 * @param String $suffix LDAP search suffix (leave empty for admin interface)
2646 * @return samba3domain[] list of samba3domain objects
2647 */
2648 private function getDomains($server = null, $suffix = null): array {
2649 if ($this->cachedDomainList !== null) {
2650 return $this->cachedDomainList;
2651 }
2652 $this->cachedDomainList = search_domains($server, $suffix);
2653 return $this->cachedDomainList;
2654 }
2655
2656 /**
2657 * Sets the expiration date of this account.
2658 * If all parameters are null the expiration date will be removed.
2659 *
2660 * @param int|null $year year (e.g. 2040)
2661 * @param int|null $month month (e.g. 8)
2662 * @param int|null $day day (e.g. 27)
2663 */
2664 public function setExpirationDate($year, $month, $day): void {
2665 if (($year == null) && ($month == null) && ($day == null)) {
2666 unset($this->attributes['sambaKickoffTime']);
2667 return;
2668 }
2669 $date = DateTime::createFromFormat('j.n.Y', $day . '.' . $month . '.' . $year, getTimeZone());
2670 $this->attributes['sambaKickoffTime'][0] = $date->format('U');
2671 }
2672
2673 /**
2674 * Returns if the Samba extension is enabled.
2675 *
2676 * @return bool Samba extension is active
2677 */
2678 public function isExtensionEnabled(): bool {
2679 return in_array('sambaSamAccount', $this->attributes['objectClass']);
2680 }
2681
2682 /**
2683 * Returns if the Samba part of the current account is locked.
2684 *
2685 * @param array<string, string[]|string>|null $attributes LDAP attributes
2686 * @return bool account is locked
2687 */
2688 public function isLocked(?array $attributes = null): bool {
2689 if ($attributes === null) {
2690 $attributes = $this->attributes;
2691 }
2692 if (!isset($attributes['sambaacctflags'][0])) {
2693 return false;
2694 }
2695 return str_contains($attributes['sambaacctflags'][0], 'L');
2696 }
2697
2698 /**
2699 * Returns if the Samba part of the current account is deactivated.
2700 *
2701 * @param array<string, string[]|string>|null $attributes LDAP attributes
2702 * @return bool account is deactivated
2703 */
2704 public function isDeactivated(?array $attributes = null): bool {
2705 if ($attributes === null) {
2706 $attributes = $this->attributes;
2707 }
2708 if (!isset($attributes['sambaacctflags'][0])) {
2709 return false;
2710 }
2711 return str_contains($attributes['sambaacctflags'][0], 'D');
2712 }
2713
2714 /**
2715 * Deactivates this account.
2716 *
2717 * @param array<string, string[]|string> $attributes LDAP attributes
2718 */
2719 public function deactivate(array &$attributes): void {
2720 if (!isset($attributes['sambaacctflags'][0])) {
2721 $attributes['sambaacctflags'][0] = ($this->get_scope() === 'host') ? '[W ]' : '[ XU ]';
2722 }
2723 $flags = $attributes['sambaacctflags'][0];
2724 if (!str_contains($flags, 'D')) {
2725 $flags[strpos($flags, ' ')] = 'D';
2726 }
2727 $attributes['sambaacctflags'][0] = (string) $flags;
2728 }
2729
2730 /**
2731 * Activates this account.
2732 *
2733 * @param array<string, string[]|string> $attributes LDAP attributes
2734 */
2735 public function activate(array &$attributes): void {
2736 if (!isset($attributes['sambaacctflags'][0])) {
2737 $attributes['sambaacctflags'][0] = ($this->get_scope() === 'host') ? '[W ]' : '[ XU ]';
2738 }
2739 $attributes['sambaacctflags'][0] = str_replace('D', ' ', $attributes['sambaacctflags'][0]);
2740 }
2741
2742 /**
2743 * Unlocks this account.
2744 *
2745 * @param array<string, string[]|string> $attributes LDAP attributes
2746 */
2747 public function unlock(array &$attributes): void {
2748 $attributes['sambaacctflags'][0] = str_replace('L', ' ', $attributes['sambaacctflags'][0]);
2749 }
2750
2751 /**
2752 * Creates the value to store in sambaPasswordHistory attribute.
2753 *
2754 * @param string $password password
2755 * @return string|null value for sambaPasswordHistory
2756 */
2757 public static function createHistoryEntry($password) {
2758 if (empty($password)) {
2759 return null;
2760 }
2761 $salt = generateSalt(16);
2762 $saltHex = bin2hex($salt);
2763 $md4hash = ntPassword($password);
2764 $md5hash = md5($salt . hex2bin($md4hash));
2765 return strtoupper($saltHex . $md5hash);
2766 }
2767
2768 /**
2769 * Checks if the given password matches the history entry.
2770 *
2771 * @param String $password password
2772 * @param String $historyEntry sambaPasswordHistory entry
2773 * @return Boolean entry matches password
2774 */
2775 public static function validateHistoryEntry($password, $historyEntry) {
2776 if (empty($historyEntry) || (strlen($historyEntry) !== 64)) {
2777 return false;
2778 }
2779 $salt = hex2bin(substr($historyEntry, 0, 32));
2780 $hash = substr($historyEntry, 32, 32);
2781 $md4hash = ntPassword($password);
2782 $md5hash = md5($salt . hex2bin($md4hash));
2783 return strtolower($md5hash) === strtolower($hash);
2784 }
2785
2786 /**
2787 * Returns if password history is enabled.
2788 *
2789 * @param array<string, string[]> $settings server profile or self-service settings
2790 * @return bool enabled
2791 */
2792 public static function isPasswordHistoryEnabled($settings): bool {
2793 return empty($settings['sambaSamAccount_history']) || ($settings['sambaSamAccount_history'][0] != 'no');
2794 }
2795
2796 /**
2797 * @inheritDoc
2798 */
2799 public function supportsPasswordQuickChangePage(): bool {
2800 return true;
2801 }
2802
2803 /**
2804 * @inheritDoc
2805 */
2806 public function addPasswordQuickChangeAccountDetails(htmlResponsiveRow $row): void {
2807 // no details
2808 }
2809
2810 /**
2811 * @inheritDoc
2812 */
2813 public function getPasswordQuickChangeOptions(bool $forcePasswordChangeByDefault): array {
2814 $options = [];
2815 if (isset($this->attributes['sambaacctflags'][0])
2816 && (str_contains($this->attributes['sambaacctflags'][0], 'L')
2817 || str_contains($this->attributes['sambaacctflags'][0], 'D'))) {
2818 $options[] = new PasswordQuickChangeOption('unlockAccountSamba', _('Unlock Samba account'));
2819 }
2820 if (in_array_ignore_case('sambaSamAccount', $this->attributes['objectClass'])) {
2821 $options[] = new PasswordQuickChangeOption('syncSambaNT', _('Change Samba NT password'));
2822 $options[] = new PasswordQuickChangeOption('forcePasswordChangeSamba', _('Force Samba password change'), $forcePasswordChangeByDefault);
2823 }
2824 if (isset($this->attributes['sambaPwdLastSet'][0])) {
2825 $options[] = new PasswordQuickChangeOption('updateSambaTimestamps', _('Update Samba password timestamp'));
2826 }
2827 return $options;
2828 }
2829
2830 /**
2831 * @inheritDoc
2832 */
2833 public function getPasswordQuickChangeChanges(string $password): array {
2834 $attrs = [];
2835 if (isset($_POST['unlockAccountSamba'])
2836 && isset($this->attributes['sambaacctflags'][0])
2837 && ((str_contains($this->attributes['sambaacctflags'][0], 'L')) || (str_contains($this->attributes['sambaacctflags'][0], 'D')))) {
2838 $sambaFlags = $this->attributes['sambaacctflags'][0];
2839 $sambaFlags = str_replace('L', ' ', $sambaFlags);
2840 $sambaFlags = str_replace('D', ' ', $sambaFlags);
2841 $attrs['sambaacctflags'][0] = $sambaFlags;
2842 }
2843 if (isset($_POST['syncSambaNT'])) {
2844 $attrs['sambaNTPassword'][0] = ntPassword($password);
2845 }
2846 // update Samba password timestamps
2847 if (isset($_POST['updateSambaTimestamps'])) {
2848 $attrs['sambaPwdLastSet'][0] = time();
2849 }
2850 // password history
2851 if (isset($_POST['syncSambaLM']) || isset($_POST['syncSambaNT'])) {
2852 $domain = $this->getUserDomain($this->attributes);
2853 if (($domain != null) && !empty($domain->pwdHistoryLength) && ($domain->pwdHistoryLength > 0)) {
2854 if (!empty($this->attributes['sambaPasswordHistory'][0])) {
2855 $attrs['sambaPasswordHistory'] = $this->attributes['sambaPasswordHistory'];
2856 }
2857 else {
2858 $attrs['sambaPasswordHistory'] = [];
2859 }
2860 while (count($attrs['sambaPasswordHistory']) > ($domain->pwdHistoryLength - 1)) {
2861 array_pop($attrs['sambaPasswordHistory']);
2862 }
2863 array_unshift($attrs['sambaPasswordHistory'], self::createHistoryEntry($password));
2864 $attrs['sambaPasswordHistory'] = array_values($attrs['sambaPasswordHistory']);
2865 }
2866 }
2867 // force password change
2868 if (isset($_POST['forcePasswordChangeSamba'])) {
2869 $attrs['sambaPwdLastSet'][0] = '0';
2870 }
2871 return $attrs;
2872 }
2873
2874 /**
2875 * @inheritDoc
2876 */
2877 public function getPasswordQuickChangePasswordStrengthUserName(): ?string {
2878 return $this->attributes['uid'][0] ?? null;
2879 }
2880
2881 /**
2882 * @inheritDoc
2883 */
2884 public function getPasswordQuickChangePasswordStrengthAttributes(): array {
2885 return [];
2886 }
2887
2888 /**
2889 * @inheritDoc
2890 */
2891 public function getPasswordQuickChangeIsPasswordInHistory(string $password): bool {
2892 // skip if no password was set
2893 if (!isset($_POST['syncSambaLM']) && !isset($_POST['syncSambaNT'])) {
2894 return false;
2895 }
2896 $sambaDomain = $this->getUserDomain($this->attributes);
2897 if ($sambaDomain == null) {
2898 return false;
2899 }
2900 if (!empty($sambaDomain->pwdHistoryLength)
2901 && ($sambaDomain->pwdHistoryLength > 0)) {
2902 return sambaSamAccount::oldPasswordUsed($password, $this->attributes, $sambaDomain);
2903 }
2904 return false;
2905 }
2906
2907 /**
2908 * @inheritDoc
2909 */
2910 public function getAccountStatusDetails(ConfiguredType $type, ?array &$attributes): array {
2911 if ($attributes === null) {
2912 $attributes = $this->attributes;
2913 }
2914 $details = [];
2915 if (self::isDeactivated($attributes)) {
2916 $details[] = AccountStatusDetails::newPartiallyLocked(_('Samba') . ': ' . _('Deactivated'), self::STATUS_ACCOUNT_DEACTIVATED);
2917 }
2918 if (self::isLocked($attributes)) {
2919 $details[] = AccountStatusDetails::newPartiallyLocked(_('Samba') . ': ' . _('Locked'), self::STATUS_ACCOUNT_LOCKED);
2920 }
2921 return $details;
2922 }
2923
2924 /**
2925 * @inheritDoc
2926 */
2927 public function getAccountStatusRequiredAttributes(ConfiguredType $type): array {
2928 return ['sambaacctflags'];
2929 }
2930
2931 /**
2932 * @inheritDoc
2933 */
2934 public function getAccountStatusPossibleLockOptions(ConfiguredType $type, ?array &$attributes): array {
2935 if ($attributes === null) {
2936 $attributes = $this->attributes;
2937 }
2938 $options = [];
2939 if (!self::isDeactivated($attributes)) {
2940 $options[] = AccountStatusDetails::newPartiallyLocked(_('Samba'), self::STATUS_ACCOUNT_DEACTIVATED);
2941 }
2942 return $options;
2943 }
2944
2945 /**
2946 * @inheritDoc
2947 */
2948 public function accountStatusPerformLock(ConfiguredType $type, ?array &$attributes, array $lockIds): void {
2949 if ($attributes === null) {
2950 $attributes = &$this->attributes;
2951 }
2952 if (in_array(self::STATUS_ACCOUNT_DEACTIVATED, $lockIds)) {
2953 self::deactivate($attributes);
2954 }
2955 }
2956
2957 /**
2958 * @inheritDoc
2959 */
2960 public function accountStatusPerformUnlock(ConfiguredType $type, ?array &$attributes, array $lockIds): void {
2961 if ($attributes === null) {
2962 $attributes = &$this->attributes;
2963 }
2964 if (in_array(self::STATUS_ACCOUNT_DEACTIVATED, $lockIds)) {
2965 self::activate($attributes);
2966 }
2967 if (in_array(self::STATUS_ACCOUNT_LOCKED, $lockIds)) {
2968 self::unlock($attributes);
2969 }
2970 }
2971
2972 /**
2973 * @inheritDoc
2974 */
2975 public function getListFilterFunction(string $attributeName): ?callable {
2976 if ($attributeName === 'sambakickofftime') {
2977 return function(?array $values, ?string $filterValue): bool {
2978 $regex = str_replace(['*'], ['.*'], $filterValue);
2979 $regex = '/' . $regex . '/i';
2980 if (!empty($values[0])) {
2981 if ($values[0] > 2147483648) {
2982 $time = "∞";
2983 }
2984 else {
2985 $date = new DateTime('@' . $values[0], new DateTimeZone('UTC'));
2986 $time = $date->format('d.m.Y');
2987 }
2988 return preg_match($regex, $time) || ($time === $filterValue);
2989 }
2990 return false;
2991 };
2992 }
2993 return null;
2994 }
2995
2996 /**
2997 * @inheritDoc
2998 */
2999 public function getListRenderFunction(string $attributeName, ConfiguredType $type): ?callable {
3000 if ($attributeName === 'sambakickofftime') {
3001 return function(array $entry, string $attribute): htmlElement {
3002 if (!empty($entry[$attribute][0])) {
3003 if ($entry[$attribute][0] > 2147483648) {
3004 return new htmlOutputText("∞");
3005 }
3006 else {
3007 $date = new DateTime('@' . $entry[$attribute][0], new DateTimeZone('UTC'));
3008 return new htmlOutputText($date->format('d.m.Y'));
3009 }
3010 }
3011 return new htmlGroup();
3012 };
3013 }
3014 return null;
3015 }
3016
3017 /**
3018 * @inheritDoc
3019 */
3020 public function getListAttributeDescriptions(ConfiguredType $type): array {
3021 return [
3022 'displayname' => _('Display name'),
3023 'sambakickofftime' => _('Account expiration date'),
3024 'sambadomainname' => _('Domain'),
3025 'sambaprimarygroupsid' => _('Windows group')
3026 ];
3027 }
3028
3029 }