Debian Codegraph @

lib/modules/windowsHost.inc

raw
1 <?php
2 /*
3
4 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
5 Copyright (C) 2013 - 2026 Roland Gruber
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21
22 /**
23 * Manages Windows AD (e.g. Samba 4) hosts.
24 *
25 * @package modules
26 * @author Roland Gruber
27 */
28
29 use LAM\TYPES\ConfiguredType;
30 use LAM\TYPES\TypeManager;
31
32 /**
33 * Manages Windows AD (e.g. Samba 4) hosts.
34 *
35 * @package modules
36 */
37 class windowsHost extends baseModule {
38
39 /**
40 * These attributes will be ignored by default if a new account is copied from an existing one.
41 */
42 private const ATTRIBUTES_TO_IGNORE_ON_COPY = ['sAMAccountName', 'pwdLastSet', 'lastLogonTimestamp',
43 'logonCount'];
44
45 /**
46 * {@inheritDoc}
47 */
48 public function can_manage(): bool {
49 return $this->get_scope() === 'host';
50 }
51
52 /**
53 * {@inheritDoc}
54 */
55 public function get_metaData(): array {
56 $return = [];
57 // icon
58 $return['icon'] = 'samba.svg';
59 // this is a base module
60 $return["is_base"] = true;
61 // RDN attribute
62 $return["RDN"] = ["cn" => "high"];
63 // LDAP filter
64 $return["ldap_filter"] = ['and' => "", 'or' => '(objectClass=computer)'];
65 // alias name
66 $return["alias"] = _("Windows");
67 // module dependencies
68 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
69 // managed object classes
70 $return['objectClasses'] = ['computer', 'securityPrincipal'];
71 // managed attributes
72 $return['attributes'] = ['cn', 'description', 'location', 'sAMAccountName', 'managedBy',
73 'operatingSystem', 'operatingSystemVersion', 'dNSHostName', 'pwdLastSet', 'lastLogonTimestamp',
74 'logonCount'];
75 // help Entries
76 $return['help'] = [
77 'cn' => [
78 "Headline" => _('Host name'), 'attr' => 'cn, sAMAccountName',
79 "Text" => _('Please enter the host name.')
80 ],
81 'description' => [
82 "Headline" => _('Description'), 'attr' => 'description',
83 "Text" => _('Please enter a descriptive text for this host.')
84 ],
85 'location' => [
86 "Headline" => _('Location'), 'attr' => 'location',
87 "Text" => _('This is the host\'s location (e.g. Munich, server room 3).')
88 ],
89 'managedBy' => [
90 "Headline" => _('Managed by'), 'attr' => 'managedBy',
91 "Text" => _('The host is managed by this contact person.')
92 ],
93 'pwdLastSet' => [
94 "Headline" => _('Last password change'), 'attr' => 'pwdLastSet',
95 "Text" => _('Time of user\'s last password change.')
96 ],
97 'lastLogonTimestamp' => [
98 "Headline" => _('Last login'), 'attr' => 'lastLogonTimestamp',
99 "Text" => _('Time of user\'s last login.')
100 ],
101 'logonCount' => [
102 "Headline" => _('Logon count'), 'attr' => 'logonCount',
103 "Text" => _('This is the number of logins performed by this account.')
104 ],
105 'filter' => [
106 "Headline" => _("Filter"),
107 "Text" => _("Here you can enter a filter value. Only entries which contain the filter text will be shown.")
108 . ' ' . _('Possible wildcards are: "*" = any character, "^" = line start, "$" = line end')
109 ],
110 ];
111 // upload fields
112 $return['upload_columns'] = [
113 [
114 'name' => 'windowsHost_name',
115 'description' => _('Host name'),
116 'help' => 'cn',
117 'example' => _('PC01'),
118 'required' => true
119 ],
120 [
121 'name' => 'windowsHost_description',
122 'description' => _('Description'),
123 'help' => 'description',
124 ],
125 [
126 'name' => 'windowsHost_location',
127 'description' => _('Location'),
128 'help' => 'location',
129 'example' => _('MyCity'),
130 ],
131 [
132 'name' => 'windowsHost_managedBy',
133 'description' => _('Managed by'),
134 'help' => 'managedBy',
135 'example' => 'cn=user1,o=test',
136 ],
137 ];
138 // available PDF fields
139 $return['PDF_fields'] = [
140 'cn' => _('Host name'),
141 'description' => _('Description'),
142 'location' => _('Location'),
143 'managedBy' => _('Managed by'),
144 ];
145 return $return;
146 }
147
148 /**
149 * {@inheritDoc}
150 */
151 protected function load_Messages(): void {
152 $this->messages['cn'][0] = ['ERROR', _('Host name'), _('Host name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
153 $this->messages['cn'][1] = ['ERROR', _('Account %s:') . ' windowsHost_cn', _('Host name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
154 }
155
156 /**
157 * {@inheritDoc}
158 */
159 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
160 parent::loadAttributesFromAccountCopy($ldapAttributes, array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, self::ATTRIBUTES_TO_IGNORE_ON_COPY));
161 }
162
163 /**
164 * {@inheritDoc}
165 */
166 public function display_html_attributes(): htmlElement|array {
167 $container = new htmlResponsiveRow();
168 $this->addSimpleInputTextField($container, 'cn', _('Host name'), true);
169 $this->addSimpleInputTextField($container, 'description', _('Description'));
170 $this->addSimpleInputTextField($container, 'location', _('Location'));
171 // last password change
172 if (!empty($this->attributes['pwdLastSet'])) {
173 $container->addLabel(new htmlOutputText(_('Last password change')));
174 $pwdLastSetGroup = new htmlGroup();
175 $pwdLastSetGroup->addElement(new htmlOutputText($this->formatFileTime($this->attributes['pwdLastSet'][0])));
176 $pwdLastSetGroup->addElement(new htmlSpacer('0.5rem', null));
177 $pwdLastSetGroup->addElement(new htmlHelpLink('pwdLastSet'));
178 $container->addField($pwdLastSetGroup);
179 }
180 // last login
181 if (!empty($this->attributes['lastLogonTimestamp'])) {
182 $container->addLabel(new htmlOutputText(_('Last login')));
183 $lastLogonTimestampGroup = new htmlGroup();
184 $lastLogonTimestampGroup->addElement(new htmlOutputText($this->formatFileTime($this->attributes['lastLogonTimestamp'][0])));
185 $lastLogonTimestampGroup->addElement(new htmlSpacer('0.5rem', null));
186 $lastLogonTimestampGroup->addElement(new htmlHelpLink('lastLogonTimestamp'));
187 $container->addField($lastLogonTimestampGroup);
188 }
189 // logon count
190 if (!empty($this->attributes['logonCount'])) {
191 $container->addLabel(new htmlOutputText(_('Logon count')));
192 $logonCountGroup = new htmlGroup();
193 $logonCountGroup->addElement(new htmlOutputText($this->attributes['logonCount'][0]));
194 $logonCountGroup->addElement(new htmlSpacer('0.5rem', null));
195 $logonCountGroup->addElement(new htmlHelpLink('logonCount'));
196 $container->addField($logonCountGroup);
197 }
198 // managed by
199 $container->addLabel(new htmlOutputText(_('Managed by')));
200 $managedBy = '-';
201 if (isset($this->attributes['managedBy'][0])) {
202 $managedBy = $this->attributes['managedBy'][0];
203 }
204 $managedByGroup = new htmlGroup();
205 $managedByGroup->addElement(new htmlOutputText(getAbstractDN($managedBy)));
206 $managedByGroup->addElement(new htmlSpacer('0.5rem', null));
207 $managedByGroup->addElement(new htmlHelpLink('managedBy'));
208 $container->addField($managedByGroup);
209 $container->addLabel(new htmlOutputText('&nbsp;', false));
210 $managedByButtons = new htmlGroup();
211 $managedByButtons->addElement(new htmlAccountPageButton(static::class, 'managedBy', 'edit', _('Change')));
212 if (isset($this->attributes['managedBy'][0])) {
213 $managedByButtons->addElement(new htmlSpacer('5px', null));
214 $managedByButtons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'removeManagedBy', _('Remove')));
215 }
216 $container->addField($managedByButtons);
217 return $container;
218 }
219
220 /**
221 * {@inheritDoc}
222 */
223 public function process_attributes(): array {
224 $return = [];
225 // cn
226 $this->attributes['cn'][0] = $_POST['cn'];
227 $this->attributes['sAMAccountName'][0] = $_POST['cn'] . '$';
228 if (!get_preg($_POST['cn'], 'hostname')) {
229 $return[] = $this->messages['cn'][0];
230 }
231 // description
232 $this->attributes['description'][0] = $_POST['description'];
233 // location
234 $this->attributes['location'][0] = $_POST['location'];
235 // managed by
236 if (isset($_POST['form_subpage_' . static::class . '_attributes_removeManagedBy'])) {
237 unset($this->attributes['managedBy']);
238 }
239 if ($this->getAccountContainer()->isNewAccount) {
240 $this->attributes['userAccountControl'][0] = 4128; // machine trust account, no password required
241 }
242 return $return;
243 }
244
245 /**
246 * This function will create the meta HTML code to show a page to change the member attribute.
247 *
248 * @return htmlElement HTML meta data
249 */
250 public function display_html_managedBy(): htmlElement {
251 $return = new htmlResponsiveRow();
252 // show possible managers
253 $options = [];
254 $filter = get_ldap_filter('user');
255 $entries = searchLDAPByFilter($filter, ['dn'], ['user']);
256 for ($i = 0; $i < count($entries); $i++) {
257 $entries[$i] = $entries[$i]['dn'];
258 }
259 // sort by DN
260 usort($entries, compareDN(...));
261 for ($i = 0; $i < count($entries); $i++) {
262 $options[getAbstractDN($entries[$i])] = $entries[$i];
263 }
264 $selected = [];
265 if (isset($this->attributes['managedBy'][0])) {
266 $selected = [$this->attributes['managedBy'][0]];
267 if (!in_array($selected[0], $options)) {
268 $options[getAbstractDN($selected[0])] = $selected[0];
269 }
270 }
271 $membersSelect = new htmlSelect('managedBy', $options, $selected);
272 $membersSelect->setHasDescriptiveElements(true);
273 $membersSelect->setRightToLeftTextDirection(true);
274 $membersSelect->setSortElements(false);
275 $membersSelect->setTransformSingleSelect(false);
276 $return->add($membersSelect);
277 $filterGroup = new htmlGroup();
278 $filterGroup->addElement(new htmlOutputText(_('Filter')));
279 $filterInput = new htmlInputField('filter');
280 $filterInput->filterSelectBox('managedBy');
281 $filterInput->setCSSClasses(['max-width-10']);
282 $filterGroup->addElement($filterInput);
283 $filterGroup->addElement(new htmlHelpLink('filter'));
284 $return->add($filterGroup);
285 $return->addVerticalSpacer('2rem');
286 $buttonTable = new htmlTable();
287 $buttonTable->addElement(new htmlAccountPageButton(static::class, 'attributes', 'set', _('Change')));
288 $buttonTable->addElement(new htmlAccountPageButton(static::class, 'attributes', 'cancel', _('Cancel')));
289 $return->add($buttonTable);
290 return $return;
291 }
292
293 /**
294 * Processes user input of the members page.
295 * It checks if all input values are correct and updates the associated LDAP attributes.
296 *
297 * @return string[][] list of info/error messages
298 */
299 public function process_managedBy(): array {
300 $return = [];
301 if (isset($_POST['form_subpage_' . static::class . '_attributes_set'])) {
302 $this->attributes['managedBy'][0] = $_POST['managedBy'];
303 }
304 return $return;
305 }
306
307 /**
308 * {@inheritDoc}
309 */
310 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
311 $errors = [];
312 for ($i = 0; $i < count($rawAccounts); $i++) {
313 // add object class
314 if (!in_array('computer', $partialAccounts[$i]['objectClass'])) {
315 $partialAccounts[$i]['objectClass'][] = 'computer';
316 }
317 // cn + sAMAccountName
318 if ($rawAccounts[$i][$ids['windowsHost_name']] != "") {
319 if (get_preg($rawAccounts[$i][$ids['windowsHost_name']], 'hostname')) {
320 $partialAccounts[$i]['cn'] = $rawAccounts[$i][$ids['windowsHost_name']];
321 $partialAccounts[$i]['sAMAccountName'] = $rawAccounts[$i][$ids['windowsHost_name']] . '$';
322 }
323 else {
324 $errMsg = $this->messages['cn'][1];
325 $errMsg[] = [$i];
326 $errors[] = $errMsg;
327 }
328 }
329 // description
330 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'windowsHost_description', 'description');
331 // location
332 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'windowsHost_location', 'location');
333 // managed by
334 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'windowsHost_managedBy', 'managedBy');
335 // machine trust account, no password required
336 $partialAccounts[$i]['userAccountControl'][0] = 4128;
337 }
338 return $errors;
339 }
340
341 /**
342 * {@inheritDoc}
343 */
344 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
345 $return = [];
346 $this->addSimplePDFField($return, 'cn', _('Host name'));
347 $this->addSimplePDFField($return, 'description', _('Description'));
348 $this->addSimplePDFField($return, 'location', _('Location'));
349 // managed by
350 $managedBy = '';
351 if (isset($this->attributes['managedBy'][0])) {
352 $managedBy = getAbstractDN($this->attributes['managedBy'][0]);
353 $this->addPDFKeyValue($return, 'managedBy', _('Managed by'), $managedBy);
354 }
355 return $return;
356 }
357
358 /**
359 * Formats a value in file time (100 ns since 1601-01-01).
360 *
361 * @param string $value time value
362 * @return string formatted value
363 */
364 private function formatFileTime($value) {
365 if (empty($value) || ($value == '-1')) {
366 return '';
367 }
368 $seconds = substr($value, 0, -7);
369 $time = new DateTime('1601-01-01', new DateTimeZone('UTC'));
370 $time->add(new DateInterval('PT' . $seconds . 'S'));
371 $time->setTimezone(getTimeZone());
372 return $time->format('Y-m-d H:i:s');
373 }
374
375 /**
376 * @inheritDoc
377 */
378 public function getListAttributeDescriptions(ConfiguredType $type): array {
379 return [
380 'cn' => _('Host name'),
381 'description' => _('Description'),
382 'location' => _('Location'),
383 'managedby' => _('Managed by'),
384 'whencreated' => _('Creation time'),
385 'whenchanged' => _('Change date'),
386 ];
387 }
388
389 /**
390 * @inheritDoc
391 */
392 public function getListRenderFunction(string $attributeName, ConfiguredType $type): ?callable {
393 if (($attributeName === 'whencreated') || ($attributeName === 'whenchanged')) {
394 return function(array $entry, string $attribute): htmlElement {
395 $value = ' - ';
396 if (!empty($entry[$attribute][0])) {
397 $value = formatLDAPTimestamp($entry[$attribute][0]);
398 }
399 return new htmlOutputText($value);
400 };
401 }
402 elseif ($attributeName === 'managedby') {
403 return $this->listRenderDnList(...);
404 }
405 return null;
406 }
407
408 }