Debian Codegraph @

lib/modules/fixed_ip.inc

raw
1 <?php
2
3 use LAM\PDF\PDFTable;
4 use LAM\PDF\PDFTableCell;
5 use LAM\PDF\PDFTableRow;
6 use LAM\TYPES\ConfiguredType;
7
8 /*
9
10 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
11 Copyright (C) 2008 Thomas Manninger
12 2008 - 2026 Roland Gruber
13
14 This program is free software; you can redistribute it and/or modify
15 it under the terms of the GNU General Public License as published by
16 the Free Software Foundation; either version 2 of the License, or
17 (at your option) any later version.
18
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27
28 */
29
30
31 /**
32 * Manages DHCP host entries.
33 *
34 * @package modules
35 *
36 * @author Thomas Manninger
37 * @author Roland Gruber
38 */
39
40 /**
41 * Manages DHCP host entries.
42 *
43 * @package modules
44 */
45 class fixed_ip extends baseModule {
46
47 /** @var array<int, array<string, string[]|string|bool>> $fixed_ip fixed ips */
48 public array $fixed_ip = [];
49
50 /** already processed? */
51 public bool $processed = false;
52
53 /** @var string[] $overlapd for check if IPs overlap */
54 public array $overlapd = [];
55
56 /** @var array<string, string>[] $orig_ips original IPs */
57 public array $orig_ips = [];
58
59 /** LDAP attributes */
60 public ?array $attributes = null;
61
62 /** @var array<string, string[]|string>[]|null $hostCache cached host entries (list of array('cn' => ..., 'iphostnumber' => ..., 'macaddress' => ...)) */
63 private ?array $hostCache = null;
64
65 /** @var array<string, string>[]|null $existingDhcpHostsCache cache for existing host entries */
66 private ?array $existingDhcpHostsCache = null;
67
68 /**
69 * {@inheritDoc}
70 */
71 public function can_manage(): bool {
72 return $this->get_scope() === 'dhcp';
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 public function get_metaData(): array {
79 $return = [];
80 // alias name
81 $return["alias"] = _("Hosts");
82 // this is a base module
83 $return["is_base"] = false;
84 // icon
85 $return['icon'] = 'computer.svg';
86 // RDN attribute
87 $return["RDN"] = ["cn" => "high"];
88 // LDAP filter
89 $return["ldap_filter"] = [];
90 // module dependencies
91 $return['dependencies'] = ['depends' => ['dhcp_settings'], 'conflicts' => []];
92 // managed object classes
93 $return['objectClasses'] = [];
94 // managed attributes
95 $return['attributes'] = ['dhcpOption'];
96 // help Entries
97 $return['help'] = [
98 'pc' => [
99 "Headline" => _("PC name"), 'attr' => 'dhcpOption, host-name',
100 "Text" => _("The name of the PC.")
101 ],
102 'mac' => [
103 "Headline" => _("MAC address"), 'attr' => 'dhcpHWAddress',
104 "Text" => _("The MAC address of the PC. Example: 11:22:33:44:55:aa")
105 ],
106 'ip' => [
107 "Headline" => _("IP address"), 'attr' => 'dhcpStatements, fixed-address',
108 "Text" => _("The IP address of the PC.")
109 ],
110 'description' => [
111 "Headline" => _("Description"), 'attr' => 'dhcpComments',
112 "Text" => _("Optional description for the PC.")
113 ],
114 'active' => [
115 "Headline" => _("Active"), 'attr' => 'dhcpStatements, booting',
116 "Text" => _("Inactive hosts will not be able to get an address from the DHCP server.")
117 ],
118 ];
119 // available PDF fields
120 $return['PDF_fields'] = ['IPlist' => _('IP list')];
121 return $return;
122 }
123
124 /**
125 * {@inheritDoc}
126 */
127 protected function load_Messages(): void {
128 $this->messages['errors'][0] = ['ERROR', _('One or more errors occurred. The invalid fields are marked.'), ''];
129 }
130
131 /**
132 * {@inheritDoc}
133 */
134 public function getButtonStatus(): string {
135 if ($this->isRootNode()) {
136 return "hidden";
137 }
138 else {
139 return "enabled";
140 }
141 }
142
143 /**
144 * Checks if IPs are not overlapped.
145 *
146 * @param string $ip IP address
147 * @return bool not overlapped
148 **/
149 private function isNotOverlappedIp($ip) {
150 if (in_array($ip, $this->overlapd)) {
151 return false;
152 }
153
154 $this->overlapd[] = $ip;
155 return true;
156 }
157
158 /**
159 * Reset the overlapped_range() function
160 **/
161 private function reset_overlapped_ip(): void {
162 $this->overlapd = [];
163 }
164
165 /**
166 * Check, if a mac address is invalid
167 *
168 * @param string $mac mac address
169 * @return bool true, if mac is invalid
170 **/
171 public function check_mac($mac): bool {
172 $ex = explode(":", $mac);
173 $invalid = false;
174 if (count($ex) !== 6) {
175 $invalid = true;
176 }
177
178 foreach ($ex as $value) {
179 if (!preg_match("/[0-9a-fA-F][0-9a-fA-F]/", $value) || strlen($value) != "2") {
180 $invalid = true;
181 }
182 }
183 return $invalid;
184 }
185
186 /**
187 *
188 * Adapt the fixed ip with the subnet.
189 *
190 * @return bool true, if ip were edited.
191 *
192 **/
193 public function reload_ips(): bool {
194 $ip_edit = false; // IPs were edited?
195 $ex_subnet = explode(".", $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0]);
196 foreach ($this->fixed_ip as $id => $value) {
197 if (!empty($value['ip']) && !range::check_subnet_range($value['ip'],
198 $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0],
199 $this->getAccountContainer()->getAccountModule('dhcp_settings')->getDHCPOption('subnet-mask'))) {
200 // Range anpassen:
201 $ex = explode(".", $value['ip']);
202 $tmp = $value['ip'];
203 $this->fixed_ip[$id]['ip'] = $ex_subnet[0] . "." . $ex_subnet[1] . "." . $ex_subnet[2] . "." . $ex[3];
204 if ($tmp != $this->fixed_ip[$id]['ip']) {
205 $ip_edit = true;
206 }
207 }
208 }
209 return $ip_edit;
210 }
211
212 /**
213 * {@inheritDoc}
214 */
215 public function load_attributes(array $attributes): void {
216 if (!$this->isRootNode()) {
217 $searchAttributes = ['cn', 'dhcphwaddress', 'dhcpstatements', 'dhcpcomments'];
218 $entries = searchLDAP($this->getAccountContainer()->dn_orig, '(objectClass=dhcpHost)', $searchAttributes);
219 for ($i = 0; $i < count($entries); $i++) {
220 $dhcphwaddress = explode(" ", $entries[$i]['dhcphwaddress'][0]);
221 $dhcphwaddress = array_pop($dhcphwaddress);
222 $dhcpstatements = [];
223 if (isset($entries[$i]['dhcpstatements'][0])) {
224 $dhcpstatements = $entries[$i]['dhcpstatements'];
225 }
226 $this->fixed_ip[$i]['cn'] = $entries[$i]['cn'][0];
227 $this->fixed_ip[$i]['mac'] = $dhcphwaddress;
228 $this->fixed_ip[$i]['ip'] = self::extractIP($dhcpstatements);
229 $this->fixed_ip[$i]['active'] = self::isActive($dhcpstatements);
230 $this->fixed_ip[$i]['dhcpstatements'] = $dhcpstatements;
231 $description = '';
232 if (isset($entries[$i]['dhcpcomments'][0])) {
233 $description = $entries[$i]['dhcpcomments'][0];
234 }
235 $this->fixed_ip[$i]['description'] = $description;
236
237 $this->orig_ips[$i]['cn'] = $entries[$i]['cn'][0];
238 $this->orig_ips[$i]['mac'] = $dhcphwaddress;
239 $this->orig_ips[$i]['ip'] = self::extractIP($dhcpstatements);
240 $this->orig_ips[$i]['active'] = self::isActive($dhcpstatements);
241 $this->orig_ips[$i]['dhcpstatements'] = $dhcpstatements;
242 $this->orig_ips[$i]['description'] = $description;
243 }
244 $this->orderByIP();
245 }
246 }
247
248 /**
249 * Orders the host entries by IP address.
250 */
251 private function orderByIP(): void {
252 // sort by IP
253 $order = [];
254 foreach ($this->fixed_ip as $key => $value) {
255 $order[$key] = '';
256 if (!empty($value['dhcpstatements'])) {
257 $order[$key] = fixed_ip::extractIP($value['dhcpstatements']);
258 }
259 }
260 natcasesort($order);
261 $newVal = [];
262 foreach (array_keys($order) as $index) {
263 $newVal[] = $this->fixed_ip[$index];
264 }
265 $this->fixed_ip = $newVal;
266 }
267
268 /**
269 * {@inheritDoc}
270 */
271 public function process_attributes(): array {
272 $errors = [];
273 if ($this->isRootNode()) {
274 return $errors;
275 }
276 $this->processed = true;
277
278 $this->reset_overlapped_ip();
279
280 if ($this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0] != "") {
281
282 $error = false; // errors by process_attributes()?
283 $pcs = [];
284 foreach (array_keys($this->fixed_ip) as $id) {
285 // Check if ip is to drop
286 if (isset($_POST['drop_ip_' . $id])) {
287 // Drop ip:
288 unset($this->fixed_ip[$id]);
289 continue;
290 }
291
292 // MAC address
293 $_POST['mac_' . $id] = strtolower(trim($_POST['mac_' . $id]));
294
295 $invalid = $this->check_mac($_POST['mac_' . $id]);
296 if ($invalid) {
297 $error = true;
298 }
299 $this->fixed_ip[$id]['mac'] = $_POST['mac_' . $id];
300
301 // description
302 if (!get_preg($_POST['description_' . $id], 'ascii')) {
303 $error = true;
304 }
305 $this->fixed_ip[$id]['description'] = $_POST['description_' . $id];
306
307 // active
308 $this->fixed_ip[$id]['active'] = (isset($_POST['active_' . $id]) && ($_POST['active_' . $id] == 'on'));
309
310 // Ip address
311 if (!empty($_POST['ip_' . $id])) {
312 $_POST['ip_' . $id] = trim($_POST['ip_' . $id]);
313 }
314 if ((!empty($_POST['ip_' . $id]) && !(check_ip($_POST['ip_' . $id])))
315 || (!empty($_POST['ip_' . $id]) && !$this->isNotOverlappedIp($_POST['ip_' . $id]))) {
316 $error = true;
317 }
318 $this->fixed_ip[$id]['ip'] = $_POST['ip_' . $id];
319
320 // Is ip correct with subnet:
321 if (!empty($_POST['ip_' . $id]) && check_ip($_POST['ip_' . $id]) && !range::check_subnet_range($_POST['ip_' . $id],
322 $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0],
323 $this->getAccountContainer()->getAccountModule('dhcp_settings')->getDHCPOption('subnet-mask'))) {
324 $error = true;
325 }
326
327 // cn:
328 if (!empty($_POST['pc_' . $id])) {
329 $_POST['pc_' . $id] = trim($_POST['pc_' . $id]);
330 }
331 if (!empty($_POST['pc_' . $id])) {
332
333 // name already in use
334 if (in_array($_POST['pc_' . $id], $pcs)) {
335 $error = true;
336 }
337 else {
338 $pcs[] = $_POST['pc_' . $id];
339 }
340 }
341 else {
342 $error = true;
343 }
344 if (strlen($_POST['pc_' . $id]) > 30) {
345 $error = true;
346 }
347 if (!preg_match("/^[A-Za-z0-9\\._-]*$/", $_POST['pc_' . $id])) {
348 $error = true;
349 }
350 $this->fixed_ip[$id]['cn'] = $_POST['pc_' . $id];
351 }
352 if ($error) {
353 $errors[] = $this->messages['errors'][0];
354 }
355 }
356
357 // Add new IP
358 if (isset($_POST['add_ip']) || ($_POST['pc_add'] != '') || ($_POST['mac_add'] != '')) {
359 // Add IP:
360 $active = (isset($_POST['active_add']) && ($_POST['active_add'] == 'on'));
361 $dhcpstatements = [];
362 $this->setActive($dhcpstatements, $active);
363 $this->setIP($dhcpstatements, $_POST['ip_add']);
364 $this->fixed_ip[] = [
365 'cn' => $_POST['pc_add'],
366 'mac' => $_POST['mac_add'],
367 'description' => $_POST['description_add'],
368 'ip' => $_POST['ip_add'],
369 'dhcpstatements' => $dhcpstatements,
370 'active' => $active,
371 ];
372 $this->orderByIP();
373 }
374
375 return $errors;
376 }
377
378 /**
379 * {@inheritDoc}
380 */
381 public function display_html_attributes(): htmlElement|array {
382 $return = new htmlResponsiveRow();
383 if ($this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0] == "") {
384 $return->add(new htmlStatusMessage('ERROR', _("Please fill out the DHCP settings first.")));
385 return $return;
386 }
387 $this->initCache();
388 // auto-completion for host names
389 $autoNames = [];
390 if (!empty($this->hostCache) && (count($this->hostCache) < 200)) {
391 foreach ($this->hostCache as $attrs) {
392 if (!empty($attrs['cn'][0])) {
393 $autoNames[] = $attrs['cn'][0];
394 }
395 }
396 $autoNames = array_values(array_unique($autoNames));
397 }
398 $titles = [_('IP address'), _('PC name'), _('MAC address'), _('Description'), _('Active'), ' '];
399 $data = [];
400 // Reset oberlaped ips
401 $this->reset_overlapped_ip();
402
403 // If $ranges is not a array, then create one:
404 $pcs = [];
405 $messages = [];
406 foreach ($this->fixed_ip as $id => $value) {
407 // pc name
408 $existsInDifferentDn = false;
409 if (!empty($_POST['pc_' . $id])) {
410 $existsInDifferentDn = $this->hostNameExists($_POST['pc_' . $id]);
411 }
412 if ($this->processed) {
413 if (strlen($value['cn']) > 20) {
414 $messages[] = new htmlStatusMessage('ERROR', _("The PC name may not be longer than 20 characters."), htmlspecialchars($value['cn']));
415 }
416 elseif (strlen($value['cn']) < 2) {
417 $messages[] = new htmlStatusMessage('ERROR', _("The PC name needs to be at least 2 characters long."), htmlspecialchars($value['cn']));
418 }
419 elseif (in_array($value['cn'], $pcs)) {
420 $messages[] = new htmlStatusMessage('ERROR', _("This PC name already exists."), htmlspecialchars($value['cn']));
421 }
422 elseif (isset($_POST['pc_' . $id]) && !preg_match("/^[A-Za-z0-9\\._-]*$/", $_POST['pc_' . $id])) {
423 $messages[] = new htmlStatusMessage('ERROR', _("The PC name may only contain A-Z, a-z and 0-9."), htmlspecialchars($_POST['pc_' . $id]));
424 }
425 elseif ($existsInDifferentDn !== false) {
426 $messages[] = new htmlStatusMessage('ERROR', sprintf(_('This PC name already exists in %s. Use e.g. %s.'), $existsInDifferentDn[0], $existsInDifferentDn[1]));
427 }
428 }
429 $pcs[] = $value['cn'];
430
431 // MAC address
432 if ($this->processed && $this->check_mac($value['mac'])) {
433 $messages[] = new htmlStatusMessage('ERROR', _("Invalid MAC address."), htmlspecialchars($value['mac']));
434 }
435
436 // description
437 if ($this->processed && !get_preg($value['description'], 'ascii')) {
438 $messages[] = new htmlStatusMessage('ERROR', _("Invalid description."), htmlspecialchars($value['description']));
439 }
440
441 // fixed ip
442 if ($this->processed && !empty($value['ip'])) {
443 if (!check_ip($value['ip'])) {
444 $messages[] = new htmlStatusMessage('ERROR', _("The IP address is invalid."), htmlspecialchars($value['ip']));
445 }
446 elseif (!range::check_subnet_range($value['ip'],
447 $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0],
448 $this->getAccountContainer()->getAccountModule('dhcp_settings')->getDHCPOption('subnet-mask'))) {
449 $messages[] = new htmlStatusMessage('ERROR', _("The IP address does not match the subnet."), htmlspecialchars($value['ip']));
450 }
451 elseif (!$this->isNotOverlappedIp($value['ip'])) {
452 $messages[] = new htmlStatusMessage('ERROR', _("The IP address is already in use."), htmlspecialchars($value['ip']));
453 }
454 }
455 $entry = [];
456 $entry[] = new htmlInputField('ip_' . $id, $value['ip']);
457 $pcInput = new htmlInputField('pc_' . $id, $value['cn']);
458 if (!empty($autoNames)) {
459 $pcInput->enableAutocompletion($autoNames);
460 }
461 $entry[] = $pcInput;
462 $entry[] = new htmlInputField('mac_' . $id, $value['mac']);
463 $entry[] = new htmlInputField('description_' . $id, $value['description']);
464 $entry[] = new htmlInputCheckbox('active_' . $id, $value['active']);
465 $entry[] = new htmlButton('drop_ip_' . $id, 'del.svg', true);
466 $data[] = $entry;
467 }
468 // add host
469 $newEntry = [];
470 $newEntry[] = new htmlInputField('ip_add');
471 $newPCInput = new htmlInputField('pc_add');
472 if (!empty($autoNames)) {
473 $newPCInput->enableAutocompletion($autoNames);
474 }
475 $newEntry[] = $newPCInput;
476 $newEntry[] = new htmlInputField('mac_add');
477 $newEntry[] = new htmlInputField('description_add');
478 $newEntry[] = new htmlInputCheckbox('active_add', true);
479 $newEntry[] = new htmlButton('add_ip', 'add.svg', true);
480 $data[] = $newEntry;
481
482 $table = new htmlResponsiveTable($titles, $data);
483 $table->setWidths(['20%', '20%', '20%', '25%', '10%', '5%']);
484 $table->colspan = 100;
485 $return->add($table);
486
487 foreach ($messages as $message) {
488 $return->add($message);
489 }
490
491 // add existing host entry
492 if (!empty($this->hostCache)) {
493 $return->addVerticalSpacer('2rem');
494 $addHostButton = new htmlAccountPageButton(static::class, 'addHost', 'add', _('Add existing host'));
495 $return->add($addHostButton);
496 }
497 return $return;
498 }
499
500 /**
501 * Checks if the given host name already exists.
502 *
503 * @param string $name host name
504 * @return boolean|string[] false if not exists, DN + new name suggestion if exists
505 */
506 private function hostNameExists($name) {
507 $this->fillExistingDhcpHosts();
508 foreach ($this->existingDhcpHostsCache as &$host) {
509 if ($name === $host['name']) {
510 $dn = $host['dn'];
511 if ($this->getAccountContainer()->isNewAccount || !str_contains($dn, $this->getAccountContainer()->dn_orig)) {
512 return [$dn, $this->getHostNameSuggestion($name)];
513 }
514 }
515 }
516 return false;
517 }
518
519 /**
520 * Returns a suggestion for a free host name.
521 *
522 * @param string $name host name
523 * @return string suggested new name
524 */
525 private function getHostNameSuggestion($name) {
526 $matches = [];
527 $number = 0;
528 $namePrefix = $name;
529 if (preg_match('/(.*[^0-9])(\d+)/', $name, $matches)) {
530 $namePrefix = $matches[1];
531 $number = $matches[2];
532 }
533 while (true) {
534 $number++;
535 $newName = $namePrefix . $number;
536 $found = false;
537 foreach ($this->existingDhcpHostsCache as $host) {
538 if ($host['name'] === $newName) {
539 $found = true;
540 break;
541 }
542 }
543 if (!$found) {
544 return $newName;
545 }
546 }
547 }
548
549 /**
550 * Returns the HTML meta data for the add host page.
551 *
552 * @return htmlElement HTML meta data
553 */
554 public function display_html_addHost(): htmlElement {
555 $return = new htmlResponsiveRow();
556 $this->initCache();
557 $hostNames = [];
558 $spacer = '####';
559 foreach ($this->hostCache as $host) {
560 if (!empty($host['cn'][0])) {
561 $val = $host['cn'][0];
562 if (!empty($host['iphostnumber'][0])) {
563 $val .= $spacer . $host['iphostnumber'][0];
564 }
565 else {
566 $val .= $spacer;
567 }
568 if (!empty($host['macaddress'][0])) {
569 $val .= $spacer . $host['macaddress'][0];
570 }
571 else {
572 $val .= $spacer;
573 }
574 $hostNames[$host['cn'][0]] = $val;
575 }
576 }
577 $select = new htmlResponsiveSelect('host', $hostNames, [], _('Host'));
578 $select->setHasDescriptiveElements(true);
579 $return->add($select);
580 $return->addVerticalSpacer('2rem');
581 $return->addLabel(new htmlAccountPageButton(static::class, 'attributes', 'addHost', _('Add')));
582 $return->addField(new htmlAccountPageButton(static::class, 'attributes', 'cancel', _('Cancel')));
583 return $return;
584 }
585
586 /**
587 * Processes user input of the add host page.
588 * It checks if all input values are correct and updates the associated LDAP attributes.
589 *
590 * @return array<string|string[]>[] list of info/error messages
591 */
592 public function process_addHost(): array {
593 $errors = [];
594 if (isset($_POST['form_subpage_fixed_ip_attributes_addHost'])) {
595 $val = explode('####', $_POST['host']);
596 $dhcpstatements = [];
597 $this->setActive($dhcpstatements, true);
598 $this->setIP($dhcpstatements, $val[1]);
599 $this->fixed_ip[] = [
600 'cn' => $val[0],
601 'mac' => $val[2],
602 'description' => '',
603 'ip' => $val[1],
604 'dhcpstatements' => $dhcpstatements,
605 'active' => true,
606 ];
607 $this->orderByIP();
608 }
609 return $errors;
610 }
611
612 /**
613 * {@inheritDoc}
614 */
615 public function save_attributes(): array {
616 return [];
617 }
618
619 /**
620 * {@inheritDoc}
621 */
622 public function postModifyActions(bool $newAccount, array $attributes): array {
623 if (!$this->isRootNode()) {
624 $ldapSuffix = ',cn=' . $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0] . ',' . $this->getAccountContainer()->get_type()->getSuffix();
625 $add = [];
626 $mod = []; // DN => array(attr => values)
627 $delete = [];
628 // Which dns are to delete and to add
629 foreach (array_keys($this->orig_ips) as $id) {
630 // Exist cn still?
631 $in_arr = false;
632 foreach (array_keys($this->fixed_ip) as $idB) {
633 if ($this->orig_ips[$id]['cn'] == $this->fixed_ip[$idB]['cn']) {
634 $in_arr = true;
635 // check if IP changed
636 if ($this->orig_ips[$id]['ip'] != $this->fixed_ip[$idB]['ip']) {
637 $this->setIP($this->fixed_ip[$idB]['dhcpstatements'], $this->fixed_ip[$idB]['ip']);
638 $mod['cn=' . $this->orig_ips[$id]['cn'] . $ldapSuffix]['dhcpstatements'] = $this->fixed_ip[$idB]['dhcpstatements'];
639 }
640 // check if active changed
641 if ($this->orig_ips[$id]['active'] != $this->fixed_ip[$idB]['active']) {
642 $this->setActive($this->fixed_ip[$idB]['dhcpstatements'], $this->fixed_ip[$idB]['active']);
643 $mod['cn=' . $this->orig_ips[$id]['cn'] . $ldapSuffix]['dhcpstatements'] = $this->fixed_ip[$idB]['dhcpstatements'];
644 }
645 // check if MAC changed
646 if ($this->orig_ips[$id]['mac'] != $this->fixed_ip[$idB]['mac']) {
647 $mod['cn=' . $this->orig_ips[$id]['cn'] . $ldapSuffix]['dhcpHWAddress'] = ['ethernet ' . $this->fixed_ip[$idB]['mac']];
648 }
649 // check if description changed
650 if ($this->orig_ips[$id]['description'] != $this->fixed_ip[$idB]['description']) {
651 $mod['cn=' . $this->orig_ips[$id]['cn'] . $ldapSuffix]['dhcpComments'][] = $this->fixed_ip[$idB]['description'];
652 }
653 break;
654 }
655 }
656 if (!$in_arr) {
657 $delete[] = $this->orig_ips[$id]['cn'];
658 }
659 }
660
661 // Which entries are new:
662 foreach (array_keys($this->fixed_ip) as $id) {
663 $in_arr = false;
664 foreach (array_keys($this->orig_ips) as $idB) {
665 if ($this->orig_ips[$idB]['cn'] == $this->fixed_ip[$id]['cn']) {
666 $in_arr = true;
667 }
668 }
669 if (!$in_arr) {
670 $add[] = $this->fixed_ip[$id];
671 }
672 }
673
674 foreach ($delete as $cn) {
675 ldap_delete($_SESSION['ldap']->server(), 'cn=' . $cn . $ldapSuffix);
676 }
677
678 foreach ($add as $arr) {
679 $attr = [];
680 $attr['cn'] = $arr['cn'];
681 $attr['objectClass'][0] = 'top';
682 $attr['objectClass'][1] = 'dhcpHost';
683 $attr['dhcpHWAddress'] = 'ethernet ' . $arr['mac'];
684 if ($arr['ip'] != '') {
685 $attr['dhcpStatements'][] = 'fixed-address ' . $arr['ip'];
686 }
687 if ($arr['active'] === false) {
688 $attr['dhcpStatements'][] = 'deny booting';
689 }
690 $attr['dhcpOption'] = 'host-name "' . $arr['cn'] . '"';
691 if (!empty($arr['description'])) {
692 $attr['dhcpComments'][] = $arr['description'];
693 }
694 if ($attr['cn'] != "") {
695 ldap_add($_SESSION['ldap']->server(), 'cn=' . $arr['cn'] . $ldapSuffix, $attr);
696 }
697 }
698 // entries to modify
699 foreach ($mod as $dn => $attrs) {
700 ldap_modify($_SESSION['ldap']->server(), $dn, $attrs);
701 }
702 }
703 return [];
704 }
705
706 /**
707 * {@inheritDoc}
708 */
709 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
710 $return = [];
711 if ($this->fixed_ip !== []) {
712 $pdfTable = new PDFTable();
713 $pdfRow = new PDFTableRow();
714 $pdfRow->cells[] = new PDFTableCell(_('PC name'), '20%', null, true);
715 $pdfRow->cells[] = new PDFTableCell(_('IP address'), '20%', null, true);
716 $pdfRow->cells[] = new PDFTableCell(_('MAC address'), '20%', null, true);
717 $pdfRow->cells[] = new PDFTableCell(_('Active'), '10%', null, true);
718 $pdfRow->cells[] = new PDFTableCell(_('Description'), '30%', null, true);
719 $pdfTable->rows[] = $pdfRow;
720 for ($i = 0; $i < count($this->fixed_ip); $i++) {
721 $name = $this->fixed_ip[$i]['cn'];
722 $mac = $this->fixed_ip[$i]['mac'];
723 $ip = $this->fixed_ip[$i]['ip'];
724 $active = _('yes');
725 if (!$this->fixed_ip[$i]['active']) {
726 $active = _('no');
727 }
728 $description = $this->fixed_ip[$i]['description'];
729 $pdfRow = new PDFTableRow();
730 $pdfRow->cells[] = new PDFTableCell($name, '20%');
731 $pdfRow->cells[] = new PDFTableCell($ip, '20%');
732 $pdfRow->cells[] = new PDFTableCell($mac, '20%');
733 $pdfRow->cells[] = new PDFTableCell($active, '10%');
734 $pdfRow->cells[] = new PDFTableCell($description, '30%');
735 $pdfTable->rows[] = $pdfRow;
736 }
737 $this->addPDFTable($return, 'IPlist', $pdfTable);
738 }
739 return $return;
740 }
741
742 /**
743 * Extracts the IP from a list of DHCP statements.
744 *
745 * @param string[]|null $dhcpStatements values of dhcpStatements attribute
746 * @return string|null IP
747 */
748 public static function extractIP($dhcpStatements): ?string {
749 $return = null;
750 if (is_array($dhcpStatements)) {
751 for ($i = 0; $i < count($dhcpStatements); $i++) {
752 if (str_starts_with($dhcpStatements[$i], 'fixed-address ')) {
753 $return = substr($dhcpStatements[$i], strlen('fixed-address') + 1);
754 break;
755 }
756 }
757 }
758 return $return;
759 }
760
761 /**
762 * Sets the IP in a list of DHCP statements.
763 *
764 * @param string[] $dhcpStatements values of dhcpStatements attribute
765 * @param string $ip new IP
766 */
767 private function setIP(&$dhcpStatements, $ip): void {
768 for ($i = 0; $i < count($dhcpStatements); $i++) {
769 if (str_starts_with($dhcpStatements[$i], 'fixed-address ')) {
770 unset($dhcpStatements[$i]);
771 $dhcpStatements = array_values($dhcpStatements);
772 }
773 }
774 if (!empty($ip)) {
775 $dhcpStatements[] = 'fixed-address ' . $ip;
776 }
777 }
778
779 /**
780 * Returns if this host is active.
781 *
782 * @param string[] $dhcpStatements values of dhcpStatements attribute
783 * @return bool is active
784 */
785 public static function isActive(array $dhcpStatements): bool {
786 for ($i = 0; $i < count($dhcpStatements); $i++) {
787 if (strpos($dhcpStatements[$i], ' booting') === (strlen($dhcpStatements[$i]) - strlen(' booting'))) {
788 $val = substr($dhcpStatements[$i], 0, (strlen($dhcpStatements[$i]) - strlen(' booting')));
789 if ($val === 'deny') {
790 return false;
791 }
792 break;
793 }
794 }
795 return true;
796 }
797
798 /**
799 * Sets if this host is active.
800 *
801 * @param string[] $dhcpStatements values of dhcpStatements attribute
802 * @param boolean $active is active
803 */
804 private function setActive(&$dhcpStatements, $active): void {
805 for ($i = 0; $i < count($dhcpStatements); $i++) {
806 if (str_contains($dhcpStatements[$i], ' booting')) {
807 unset($dhcpStatements[$i]);
808 $dhcpStatements = array_values($dhcpStatements);
809 }
810 }
811 $dhcpStatements[] = $active ? 'allow booting' : 'deny booting';
812 }
813
814 /**
815 * Loads cached host data from LDAP.
816 */
817 private function initCache(): void {
818 if ($this->hostCache !== null) {
819 return;
820 }
821 $attrs = ['cn', 'iphostnumber', 'macaddress'];
822 $this->hostCache = [];
823 $result = searchLDAPByAttribute('cn', '*', null, $attrs, ['host']);
824 foreach ($result as $attributes) {
825 $this->hostCache[] = $attributes;
826 }
827 }
828
829 /**
830 * Returns if the current DN is the root entry.
831 *
832 * @return bool is root
833 */
834 private function isRootNode(): bool {
835 $rootSuffix = $this->getAccountContainer()->get_type()->getSuffix();
836 return $this->getAccountContainer()->dn_orig == $rootSuffix;
837 }
838
839 /**
840 * Fills the list of existing DHCP hosts.
841 */
842 private function fillExistingDhcpHosts(): void {
843 if ($this->existingDhcpHostsCache !== null) {
844 return;
845 }
846 $entries = searchLDAPByAttribute('cn', '*', 'dhcpHost', ['cn'], ['dhcp']);
847 $this->existingDhcpHostsCache = [];
848 foreach ($entries as $entry) {
849 $this->existingDhcpHostsCache[] = [
850 'dn' => $entry['dn'],
851 'name' => $entry['cn'][0]
852 ];
853 }
854 }
855
856 /**
857 * @inheritDoc
858 */
859 public function getListAttributeDescriptions(ConfiguredType $type): array {
860 return [
861 "fixed_ips" => _("IP address") . ' / ' . _('MAC address') . ' / ' . _("Description")
862 ];
863 }
864
865 /**
866 * @inheritDoc
867 */
868 public function getListRenderFunction(string $attributeName, ConfiguredType $type): ?callable {
869 if ($attributeName === 'fixed_ips') {
870 return function(array $entry, string $attribute): htmlElement {
871 // find all fixed addresses:
872 $entries = searchLDAP($entry['dn'], 'objectClass=dhcpHost', ['dhcpstatements', 'dhcphwaddress', 'cn']);
873 if (count($entries) > 0) {
874 // sort by IP
875 $order = [];
876 for ($i = 0; $i < count($entries); $i++) {
877 $order[$i] = '';
878 if (!empty($entries[$i]['dhcpstatements'])) {
879 $order[$i] = fixed_ip::extractIP($entries[$i]['dhcpstatements']);
880 }
881 }
882 $group = new htmlGroup();
883 natcasesort($order);
884 for ($i = 0; $i < count($order); $i++) {
885 $dhcpstatements = [];
886 if (isset($entries[$i]['dhcpstatements'][0])) {
887 $dhcpstatements = $entries[$i]['dhcpstatements'];
888 }
889 $cssClasses = ['nowrap'];
890 if (!fixed_ip::isActive($dhcpstatements)) {
891 $cssClasses[] = 'strike-through';
892 }
893 $dhcphwaddress = explode(" ", $entries[$i]['dhcphwaddress'][0]);
894 $ipAddress = fixed_ip::extractIP($dhcpstatements);
895 if (!empty($ipAddress)) {
896 $ip = new htmlOutputText($ipAddress);
897 $ip->setCSSClasses($cssClasses);
898 $group->addElement($ip);
899 $group->addElement(new htmlLineBreak());
900 }
901 $macAddress = array_pop($dhcphwaddress);
902 $mac = new htmlOutputText($macAddress);
903 $mac->setCSSClasses($cssClasses);
904 $group->addElement($mac);
905 if (!empty($macAddress)) {
906 $group->addElement(new htmlLineBreak());
907 }
908 $name = new htmlOutputText($entries[$i]['cn'][0]);
909 $name->setCSSClasses($cssClasses);
910 $group->addElement($name);
911 $group->addElement(new htmlLineBreak());
912 if ($i < (count($order) - 1)) {
913 $group->addElement(new htmlLineBreak());
914 }
915 }
916 return $group;
917 }
918 return new htmlGroup();
919 };
920 }
921 return null;
922 }
923
924 }