Debian Codegraph @

lib/treeview.inc

raw
1 <?php
2
3 namespace LAM\TOOLS\TREEVIEW;
4
5 use htmlButton;
6 use htmlDiv;
7 use htmlElement;
8 use htmlGroup;
9 use htmlHiddenInput;
10 use htmlImage;
11 use htmlInputField;
12 use htmlInputFileUpload;
13 use htmlInputTextarea;
14 use htmlLink;
15 use htmlList;
16 use htmlOutputText;
17 use htmlResponsiveInputField;
18 use htmlResponsiveRow;
19 use htmlResponsiveSelect;
20 use htmlResponsiveTable;
21 use htmlSelect;
22 use htmlSortableList;
23 use htmlSpacer;
24 use htmlStatusMessage;
25 use htmlSubTitle;
26 use htmlTable;
27 use htmlTitle;
28 use LAM\SCHEMA\AttributeType;
29 use LAM\SCHEMA\ObjectClass;
30 use LAMException;
31 use LamTemporaryFilesManager;
32 use function LAM\SCHEMA\get_schema_attributes;
33 use function LAM\SCHEMA\get_schema_objectclasses;
34
35
36 /*
37
38 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
39 Copyright (C) 2021 - 2026 Roland Gruber
40
41 This program is free software; you can redistribute it and/or modify
42 it under the terms of the GNU General Public License as published by
43 the Free Software Foundation; either version 2 of the License, or
44 (at your option) any later version.
45
46 This program is distributed in the hope that it will be useful,
47 but WITHOUT ANY WARRANTY; without even the implied warranty of
48 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
49 GNU General Public License for more details.
50
51 You should have received a copy of the GNU General Public License
52 along with this program; if not, write to the Free Software
53 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
54
55 */
56
57 /**
58 * Tree view functions.
59 *
60 * @author Roland Gruber
61 */
62
63 include_once __DIR__ . '/account.inc';
64 include_once __DIR__ . '/tools.inc';
65 include_once __DIR__ . '/tools/treeview.inc';
66
67 /**
68 * Tree view functions.
69 *
70 * @package LAM\TOOLS\TREEVIEW
71 */
72 class TreeView {
73 const AD_DELETED_DELIMITER = '\0ADEL:';
74
75 /**
76 * @var AttributeType[] schema attributes
77 */
78 private $schemaAttributes;
79
80 /**
81 * @var ObjectClass[] schema object classes
82 */
83 private $schemaObjectClasses;
84
85 /**
86 * Returns the JSON to answer an AJAX request.
87 *
88 * @return string JSON data
89 */
90 public function answerAjaxCall(): string {
91 if (empty($_GET['command'])) {
92 logNewMessage(LOG_ERR, 'No command given for tree view.');
93 die();
94 }
95 $command = $_GET['command'];
96 switch ($command) {
97 case 'getRootNodes':
98 return $this->getRootNodes();
99 case 'getNodes':
100 return $this->getSubNodes(base64_decode($_GET['dn']));
101 }
102 if (empty($_POST['dn'])) {
103 logNewMessage(LOG_ERR, 'No dn for tree view.');
104 die;
105 }
106 $dn = ($_POST['dn'] === '#') ? '#' : base64_decode($_POST['dn']);
107 switch ($command) {
108 case 'getNodeContent':
109 $this->validateDn($dn);
110 return $this->getNodeContent($dn);
111 case 'getInternalAttributesContent':
112 $this->validateDn($dn);
113 return $this->getInternalAttributesContent($dn);
114 case 'getPossibleNewAttributes':
115 return $this->getPossibleNewAttributeNameOptionsJson();
116 case 'saveAttributes':
117 $this->ensureWriteAccess();
118 $this->validateDn($dn);
119 return $this->saveAttributes($dn);
120 case 'createNewNode':
121 $this->ensureWriteAccess();
122 $this->validateDn($dn);
123 return $this->createNewNode($dn);
124 case 'deleteNode':
125 $this->ensureWriteAccess();
126 $this->validateDn($dn);
127 return $this->deleteNode($dn);
128 case 'restoreNode':
129 $this->ensureWriteAccess();
130 $this->validateDn($dn);
131 return $this->restoreNode($dn);
132 case 'search':
133 $this->validateDn($dn);
134 return $this->search($dn);
135 case 'searchResults':
136 $this->validateDn($dn);
137 return $this->searchResults($dn);
138 case 'paste':
139 $this->ensureWriteAccess();
140 $this->validateDn($dn);
141 return $this->paste($dn);
142 case 'compare':
143 $this->validateDn($dn);
144 return $this->compare();
145 default:
146 logNewMessage(LOG_ERR, 'Invalid command for tree view: ' . $command);
147 die;
148 }
149 }
150
151 /**
152 * Returns the JSON for the possible new attributes select.
153 *
154 * @return string JSON
155 */
156 private function getPossibleNewAttributeNameOptionsJson() {
157 $objectClasses = json_decode($_POST['objectClasses'], true);
158 $attributeNames = $this->getPossibleNewAttributeNameOptions($objectClasses, true);
159 natcasesort($attributeNames);
160 return json_encode(['data' => $attributeNames]);
161 }
162
163 /**
164 * Returns a list of root nodes for the tree view.
165 *
166 * @return string JSON data
167 */
168 private function getRootNodes(): string {
169 $rootDns = TreeViewTool::getRootDns();
170 $result = [];
171 foreach ($rootDns as $rootDn) {
172 logNewMessage(LOG_DEBUG, 'Getting tree nodes for ' . $rootDn);
173 $rootData = ldapGetDN($rootDn, ['objectClass']);
174 if ($rootData === null) {
175 continue;
176 }
177 $children = ldapListDN($rootDn, '(objectClass=*)', ['objectClass', 'hassubordinates']);
178 $nodeData = $this->createNodeData($rootData, true, true, $children);
179 $result[] = $nodeData;
180 }
181 return json_encode($result);
182 }
183
184 /**
185 * Returns the subnodes of the given DN.
186 *
187 * @param string $dn DN
188 * @return string JSON data
189 */
190 private function getSubNodes(string $dn): string {
191 $this->validateDn($dn);
192 logNewMessage(LOG_DEBUG, 'Getting tree nodes for ' . $dn);
193 $children = ldapListDN($dn, '(objectClass=*)', ['objectClass', 'hassubordinates']);
194 $childNodes = [];
195 foreach ($children as $child) {
196 $childHasChildren = !isset($child['hassubordinates'][0]) || ($child['hassubordinates'][0] === 'TRUE');
197 $childNodes[] = $this->createNodeData($child, false, false, [], $childHasChildren);
198 }
199 $this->sortNodes($childNodes);
200 return json_encode($childNodes);
201 }
202
203 /**
204 * Creates the node data for the tree view.
205 *
206 * @param array<string, string[]|string> $attributes LDAP data
207 * @param bool $open open node
208 * @param bool $noShortenFirst do not shorten DN
209 * @param array<string, string[]|string>[] $children child LDAP data
210 * @param bool $hasChildren indicates that the entry has children
211 * @return array<string, string|true|array<array<string, string>|bool>> node data
212 */
213 private function createNodeData(array $attributes, bool $open = false, bool $noShortenFirst = false, array $children = [], bool $hasChildren = true): array {
214 $text = ($noShortenFirst) ? $attributes['dn'] : extractRDN($attributes['dn']);
215 $data = [
216 'key' => base64_encode($attributes['dn']),
217 'title' => unescapeLdapSpecialCharacters($text),
218 'icon' => $this->getNodeIcon($attributes),
219 ];
220 if ($hasChildren) {
221 $data['lazy'] = true;
222 }
223 if (!empty($children)) {
224 $childData = [];
225 foreach ($children as $child) {
226 $childHasChildren = !isset($child['hassubordinates'][0]) || ($child['hassubordinates'][0] === 'TRUE');
227 $childData[] = $this->createNodeData($child, false, false, [], $childHasChildren);
228 }
229 $this->sortNodes($childData);
230 $data['children'] = $childData;
231 }
232 if ($open) {
233 $data['state'] = [
234 'expanded' => true
235 ];
236 }
237 return $data;
238 }
239
240 /**
241 * Returns the node's icon.
242 *
243 * @param array<string, string[]|string> $attributes LDAP data
244 * @return string icon
245 */
246 private function getNodeIcon(array $attributes): string {
247 $base = '../../graphics/';
248 $icon = 'object.svg';
249 $objectClasses = array_map(strtolower(...), $attributes['objectclass']);
250 $rdn = extractRDNValue($attributes['dn']);
251 if (in_array('sambasamaccount', $objectClasses) &&
252 '$' == $rdn[strlen($rdn) - 1]) {
253 $icon = 'samba.svg';
254 }
255 if (in_array('sambasamaccount', $objectClasses)) {
256 $icon = 'samba.svg';
257 }
258 elseif (in_array('pwdpolicy', $objectClasses)) {
259 $icon = 'locked.svg';
260 }
261 elseif (in_array('person', $objectClasses) ||
262 in_array('organizationalperson', $objectClasses) ||
263 in_array('inetorgperson', $objectClasses) ||
264 in_array('account', $objectClasses) ||
265 in_array('posixaccount', $objectClasses) ||
266 in_array('organizationalrole', $objectClasses)) {
267 $icon = 'user.svg';
268 }
269 elseif (in_array('organization', $objectClasses)) {
270 $icon = 'world-color.svg';
271 }
272 elseif (in_array('organizationalunit', $objectClasses)) {
273 $icon = 'folder.svg';
274 }
275 elseif (in_array('dcobject', $objectClasses) ||
276 in_array('domainrelatedobject', $objectClasses) ||
277 in_array('domain', $objectClasses) ||
278 in_array('builtindomain', $objectClasses)) {
279 $icon = 'world-color.svg';
280 }
281 elseif (in_array('alias', $objectClasses)) {
282 $icon = 'link.svg';
283 }
284 elseif (in_array('document', $objectClasses)) {
285 $icon = 'txt.svg';
286 }
287 elseif (in_array('country', $objectClasses)) {
288 $icon = 'world-color.svg';
289 }
290 elseif (in_array('locality', $objectClasses)) {
291 $icon = 'location.svg';
292 }
293 elseif (in_array('posixgroup', $objectClasses) ||
294 in_array('groupofnames', $objectClasses) ||
295 in_array('groupofuniquenames', $objectClasses) ||
296 in_array('group', $objectClasses)) {
297 $icon = 'group.svg';
298 }
299 elseif (in_array('iphost', $objectClasses)) {
300 $icon = 'computer-small.svg';
301 }
302 elseif (in_array('device', $objectClasses)) {
303 $icon = 'device.svg';
304 }
305 elseif (in_array('server', $objectClasses)) {
306 $icon = 'computer-small.svg';
307 }
308 elseif (in_array('volume', $objectClasses)) {
309 $icon = 'hard-drive.svg';
310 }
311 elseif (in_array('container', $objectClasses)) {
312 $icon = 'folder.svg';
313 }
314 return $base . $icon;
315 }
316
317 /**
318 * Sorts the given node array by DN.
319 *
320 * @param array<string, string>[] $nodes nodes
321 */
322 private function sortNodes(array &$nodes): void {
323 usort($nodes, compareNodeByIdAsDn(...));
324 }
325
326 /**
327 * Returns the options for the drop-down to add a new attribute.
328 *
329 * @param string[] $objectClasses object classes
330 * @param bool $includeMustAttributes include required attributes
331 * @return array<string, string> list of options
332 */
333 private function getPossibleNewAttributeNameOptions(array $objectClasses, bool $includeMustAttributes = false): array {
334 $schemaObjectClasses = $this->getSchemaObjectClasses();
335 $schemaAttributes = $this->getSchemaAttributes();
336 $possibleNewAttributes = [];
337 foreach ($objectClasses as $objectClass) {
338 $objectClass = strtolower($objectClass);
339 if (empty($schemaObjectClasses[$objectClass])) {
340 continue;
341 }
342 $attributes = $schemaObjectClasses[$objectClass]->getMayAttrs();
343 if ($includeMustAttributes) {
344 $attributes = array_merge($attributes, $schemaObjectClasses[$objectClass]->getMustAttrs());
345 }
346 foreach ($attributes as $attribute) {
347 $attributeName = $attribute->getName();
348 if (!isset($attributes[strtolower($attributeName)])) {
349 $schemaAttribute = $schemaAttributes[strtolower($attributeName)];
350 $single = $schemaAttribute->getIsSingleValue() ? 'single' : 'multi';
351 $type = $this->isMultiLineAttribute($attributeName, $schemaAttribute) ? 'textarea' : 'input';
352 if ($this->isPasswordAttribute($attributeName)) {
353 $type = 'password';
354 }
355 elseif ($this->isJpegAttribute($attributeName, $schemaAttribute)) {
356 $type = 'jpeg';
357 }
358 $possibleNewAttributes[$attributeName] = $attributeName . '__#__' . $single . '__#__' . $type;
359 }
360 }
361 }
362 ksort($possibleNewAttributes);
363 return $possibleNewAttributes;
364 }
365
366 /**
367 * Returns the node content with the attribute listing.
368 *
369 * @param htmlStatusMessage|null $message message to display
370 * @return string JSON
371 */
372 private function getNodeContent(string $dn, ?htmlStatusMessage $message = null): string {
373 $row = new htmlResponsiveRow();
374 if ($message !== null) {
375 $row->add($message);
376 $row->addVerticalSpacer('1rem');
377 }
378 $row->add(new htmlTitle(unescapeLdapSpecialCharacters($dn)));
379 $attributes = ldapGetDN($dn, ['*']);
380 $this->addActionBar($row, $dn, $attributes);
381 $row->add(new htmlDiv('ldap_actionarea_messages', new htmlOutputText('')));
382 $row->add(new htmlSubTitle(_('Attributes')));
383 unset($attributes['dn']);
384 ksort($attributes);
385 logNewMessage(LOG_DEBUG, 'LDAP attributes for ' . $dn . ': ' . print_r($attributes, true));
386 $schemaAttributes = $this->getSchemaAttributes();
387 $objectClasses = $attributes['objectclass'];
388 $highlighted = (empty($_POST['highlight'])) ? [] : explode(',', $_POST['highlight']);
389 foreach ($attributes as $attributeName => $values) {
390 $schemaAttribute = null;
391 if (str_contains($attributeName, ';binary')) {
392 $attributeName = substr($attributeName, 0, -1 * strlen(';binary'));
393 }
394 if (isset($schemaAttributes[$attributeName])) {
395 $schemaAttribute = $schemaAttributes[$attributeName];
396 $attributeName = $schemaAttribute->getName();
397 }
398 $this->addAttributeContent($row, $attributeName, $values, $schemaAttribute, $objectClasses, $dn, $highlighted);
399 }
400 $row->addVerticalSpacer('1rem');
401
402 // add new attributes
403 $possibleNewAttributes = $this->getPossibleNewAttributeNameOptions($objectClasses);
404 foreach (array_keys($attributes) as $attributeName) {
405 if (isset($possibleNewAttributes[$attributeName])) {
406 unset($possibleNewAttributes[$attributeName]);
407 }
408 }
409 logNewMessage(LOG_DEBUG, 'Possible new attributes for ' . $dn . ': ' . implode('; ', $possibleNewAttributes));
410 $possibleNewAttributes = ['' => ''] + $possibleNewAttributes;
411 $row->add(new htmlSubTitle(_('Add new attribute')));
412 $newAttributeSelect = new htmlResponsiveSelect('newAttribute', $possibleNewAttributes, [], _('Attribute'));
413 $newAttributeSelect->setHasDescriptiveElements(true);
414 $newAttributeSelect->setTransformSingleSelect(false);
415 $newAttributeSelect->setOnchangeEvent('window.lam.treeview.addAttributeField(event, this);');
416 $row->add($newAttributeSelect);
417 $newAttributesContentSingleInput = new htmlResponsiveRow();
418 $newAttributesContentSingleInput->addLabel(new htmlOutputText('PLACEHOLDER_SINGLE_INPUT_LABEL'));
419 $newAttributesContentSingleInput->addField($this->getAttributeContentField('placeholder' . generateRandomText(), [''], false, false, false, null));
420 $row->add(new htmlDiv('new-attributes-single-input', $newAttributesContentSingleInput, ['hidden']));
421 $newAttributesContentMultiInput = new htmlResponsiveRow();
422 $newAttributesContentMultiInput->addLabel(new htmlOutputText('PLACEHOLDER_MULTI_INPUT_LABEL'));
423 $newAttributesContentMultiInput->addField($this->getAttributeContentField('placeholder' . generateRandomText(), [''], false, true, false, null));
424 $row->add(new htmlDiv('new-attributes-multi-input', $newAttributesContentMultiInput, ['hidden']));
425 $newAttributesContentSingleTextarea = new htmlResponsiveRow();
426 $newAttributesContentSingleTextarea->addLabel(new htmlOutputText('PLACEHOLDER_SINGLE_TEXTAREA_LABEL'));
427 $newAttributesContentSingleTextarea->addField($this->getAttributeContentField('placeholder' . generateRandomText(), [''], false, false, true, null));
428 $row->add(new htmlDiv('new-attributes-single-textarea', $newAttributesContentSingleTextarea, ['hidden']));
429 $newAttributesContentMultiTextarea = new htmlResponsiveRow();
430 $newAttributesContentMultiTextarea->addLabel(new htmlOutputText('PLACEHOLDER_MULTI_TEXTAREA_LABEL'));
431 $newAttributesContentMultiTextarea->addField($this->getAttributeContentField('placeholder' . generateRandomText(), [''], false, true, true, null));
432 $row->add(new htmlDiv('new-attributes-multi-textarea', $newAttributesContentMultiTextarea, ['hidden']));
433 $newAttributesContentSinglePassword = new htmlResponsiveRow();
434 $newAttributesContentSinglePassword->addLabel(new htmlOutputText('PLACEHOLDER_SINGLE_PASSWORD_LABEL'));
435 $newAttributesContentSinglePassword->addField($this->getAttributeContentField('userpassword' . generateRandomText(), [''], false, false, false, null));
436 $row->add(new htmlDiv('new-attributes-single-password', $newAttributesContentSinglePassword, ['hidden']));
437 $newAttributesContentMultiPassword = new htmlResponsiveRow();
438 $newAttributesContentMultiPassword->addLabel(new htmlOutputText('PLACEHOLDER_MULTI_PASSWORD_LABEL'));
439 $newAttributesContentMultiPassword->addField($this->getAttributeContentField('userpassword' . generateRandomText(), [''], false, true, false, null));
440 $row->add(new htmlDiv('new-attributes-multi-password', $newAttributesContentMultiPassword, ['hidden']));
441 $newAttributesContentSingleJpeg = new htmlResponsiveRow();
442 $newAttributesContentSingleJpeg->addLabel(new htmlOutputText('PLACEHOLDER_SINGLE_JPEG_LABEL'));
443 $newAttributesContentSingleJpeg->addField($this->getAttributeContentField('jpegphoto' . generateRandomText(), [''], false, false, false, null));
444 $row->add(new htmlDiv('new-attributes-single-jpeg', $newAttributesContentSingleJpeg, ['hidden']));
445 $newAttributesContentMultiJpeg = new htmlResponsiveRow();
446 $newAttributesContentMultiJpeg->addLabel(new htmlOutputText('PLACEHOLDER_MULTI_JPEG_LABEL'));
447 $newAttributesContentMultiJpeg->addField($this->getAttributeContentField('jpegphoto' . generateRandomText(), [''], false, true, true, null));
448 $row->add(new htmlDiv('new-attributes-multi-jpeg', $newAttributesContentMultiJpeg, ['hidden']));
449
450 if (checkIfWriteAccessIsAllowed()) {
451 $row->addVerticalSpacer('2rem');
452 $saveButton = new htmlButton('savebutton', _('Save'));
453 $saveButton->setOnClick('window.lam.treeview.saveAttributes(event, '
454 . "'" . getSecurityTokenName() . "', "
455 . "'" . getSecurityTokenValue() . "', "
456 . "'" . base64_encode($dn) . "');");
457 $saveButton->setCSSClasses(['lam-primary']);
458 $row->add($saveButton, 12, 12, 12, 'text-center');
459 }
460
461 $internalAttributesContent = new htmlResponsiveRow();
462 $internalAttributesContent->add(new htmlSubTitle(_('Internal attributes')));
463 $internalAttributesButton = new htmlLink(_('Show internal attributes'), '#', null);
464 $internalAttributesButton->setOnClick('window.lam.treeview.getInternalAttributesContent(event,
465 "' . getSecurityTokenName() . '",
466 "' . getSecurityTokenValue() . '",
467 "' . base64_encode($dn) . '");');
468 $internalAttributesButton->setId('internalAttributesButton');
469 $internalAttributesContent->add($internalAttributesButton);
470 $internalAttributesDiv = new htmlDiv('actionarea-internal-attributes', $internalAttributesContent);
471 $row->add($internalAttributesDiv);
472 ob_start();
473 parseHtml(null, $row, [], false);
474 $content = ob_get_contents();
475 ob_end_clean();
476 return json_encode(['content' => $content]);
477 }
478
479 /**
480 * Adds the action buttons.
481 *
482 * @param htmlResponsiveRow $row container
483 * @param string $dn entry DN
484 * @param array<string, string[]|string> $attributes LDAP attributes
485 */
486 private function addActionBar(htmlResponsiveRow $row, string $dn, array $attributes): void {
487 $buttonGroup = new htmlGroup();
488 $buttonSize = '16px';
489 $buttonClasses = ['clickable', 'lam-margin-small', 'icon'];
490 $isRestorable = isset($attributes['isdeleted'][0]) && ($attributes['isdeleted'][0] === 'TRUE') && str_contains($dn, '\0ADEL');
491
492 if (checkIfWriteAccessIsAllowed()) {
493 $createButton = new htmlImage('../../graphics/add.svg', $buttonSize, $buttonSize, _('Create a child entry'), _('Create a child entry'));
494 $createButton->setOnClick('window.lam.treeview.createNode(\'' . getSecurityTokenName() . '\', '
495 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
496 $createButton->setCSSClasses($buttonClasses);
497 $buttonGroup->addElement($createButton);
498
499 if (!$isRestorable) {
500 $deleteButton = new htmlImage('../../graphics/delete.svg', $buttonSize, $buttonSize, _('Delete'), _('Delete'));
501 $deleteButton->setOnClick('window.lam.treeview.deleteNode(\'' . getSecurityTokenName() . '\', '
502 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\', \'' . base64_encode(htmlspecialchars(extractRDN($dn))) . '\', '
503 . '\'' . addslashes(_('Delete')) . '\', \'' . addslashes(_('Cancel')) . '\', \'' . addslashes(_('Delete this entry')) . '\', \'' . addslashes(_('Ok')) . '\', '
504 . '\'' . addslashes(_('Error')) . '\');');
505 $deleteButton->setCSSClasses($buttonClasses);
506 $buttonGroup->addElement($deleteButton);
507 }
508 }
509
510 $refreshButton = new htmlImage('../../graphics/refresh.svg', $buttonSize, $buttonSize, _('Refresh'), _('Refresh'));
511 $refreshButton->setOnClick('mar10.Wunderbaum.getTree(\'#ldap_tree\').findKey(\'' . base64_encode($dn) . '\').loadLazy(true); '
512 . 'window.lam.treeview.getNodeContent(\'' . getSecurityTokenName() . '\', '
513 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
514 $refreshButton->setCSSClasses($buttonClasses);
515 $buttonGroup->addElement($refreshButton);
516
517 $buttonGroup->addElement(new htmlSpacer('0.5rem'));
518
519 if (checkIfWriteAccessIsAllowed()) {
520 $copyButton = new htmlImage('../../graphics/copy.svg', $buttonSize, $buttonSize, _('Copy'), _('Copy'));
521 $copyButton->setOnClick('window.lam.treeview.copyNode(\'' . base64_encode($dn) . '\');');
522 $copyButton->setCSSClasses($buttonClasses);
523 $buttonGroup->addElement($copyButton);
524
525 $cutButton = new htmlImage('../../graphics/cut.svg', $buttonSize, $buttonSize, _('Cut'), _('Cut'));
526 $cutButton->setOnClick('window.lam.treeview.cutNode(\'' . base64_encode($dn) . '\');');
527 $cutButton->setCSSClasses($buttonClasses);
528 $buttonGroup->addElement($cutButton);
529
530 $pasteButton = new htmlImage('../../graphics/paste.svg', $buttonSize, $buttonSize, _('Paste as new child entry'), _('Paste as new child entry'));
531 $pasteButton->setOnClick('window.lam.treeview.pasteNode(\'' . getSecurityTokenName() . '\', '
532 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
533 $pasteButton->setCSSClasses($buttonClasses);
534 $pasteButton->setId('action_button_paste');
535 $buttonGroup->addElement($pasteButton);
536
537 $buttonGroup->addElement(new htmlSpacer('0.5rem'));
538 }
539
540 $searchButton = new htmlImage('../../graphics/search.svg', $buttonSize, $buttonSize, _('Search'), _('Search'));
541 $searchButton->setOnClick('window.lam.treeview.search(\'' . getSecurityTokenName() . '\', '
542 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
543 $searchButton->setCSSClasses($buttonClasses);
544 $buttonGroup->addElement($searchButton);
545
546 if ($_SESSION['config']->isToolActive('ImportExport')) {
547 $exportButton = new htmlImage('../../graphics/export.svg', $buttonSize, $buttonSize, _('Export'), _('Export'));
548 $exportButton->setOnClick('window.location.href = \'../tools/importexport.php?tab=export&dn=' . base64_encode($dn) . '\';');
549 $exportButton->setCSSClasses($buttonClasses);
550 $buttonGroup->addElement($exportButton);
551 }
552
553 $buttonGroup->addElement(new htmlSpacer('0.5rem'));
554
555 $addToComparisonButton = new htmlImage('../../graphics/list-add.svg', $buttonSize, $buttonSize, _('Add to comparison'), _('Add to comparison'));
556 $addToComparisonButton->setOnClick('window.lam.treeview.addToComparison(\'' . base64_encode($dn) . '\');');
557 $addToComparisonButton->setCSSClasses($buttonClasses);
558 $addToComparisonButton->setId('action_button_compare_add');
559 $buttonGroup->addElement($addToComparisonButton);
560
561 $removeFromComparisonButton = new htmlImage('../../graphics/list-remove.svg', $buttonSize, $buttonSize, _('Remove from comparison'), _('Remove from comparison'));
562 $removeFromComparisonButton->setOnClick('window.lam.treeview.removeFromComparison(\'' . base64_encode($dn) . '\');');
563 $removeFromComparisonButton->setCSSClasses($buttonClasses);
564 $removeFromComparisonButton->setId('action_button_compare_remove');
565 $buttonGroup->addElement($removeFromComparisonButton);
566
567 $startComparisonButton = new htmlImage('../../graphics/compare.svg', $buttonSize, $buttonSize, _('Open comparison'), _('Open comparison'));
568 $startComparisonButton->setOnClick('window.lam.treeview.openComparison(\'' . getSecurityTokenName() . '\', '
569 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
570 $startComparisonButton->setCSSClasses($buttonClasses);
571 $startComparisonButton->setId('action_button_compare');
572 $buttonGroup->addElement($startComparisonButton);
573
574 $row->add($buttonGroup);
575
576 if (checkIfWriteAccessIsAllowed() && $isRestorable) {
577 $row->addVerticalSpacer('1rem');
578 $row->add(new htmlSubTitle(_('Restore')));
579 $targetDn = extractDNSuffix(extractDNSuffix($dn));
580 if (!empty($attributes['lastknownparent'][0]) && !str_contains($attributes['lastknownparent'][0], self::AD_DELETED_DELIMITER)) {
581 $targetDn = $attributes['lastknownparent'][0];
582 }
583 $restoreTargetDn = new htmlResponsiveInputField(_('Target DN'), 'treeview-restore-dn', $targetDn);
584 $restoreTargetDn->showDnSelection();
585 $row->add($restoreTargetDn);
586 $row->addVerticalSpacer('0.5rem');
587 $restoreButton = new htmlButton('restorebutton', _('Restore'));
588 $rdn = explode(self::AD_DELETED_DELIMITER, $dn)[0];
589 $restoreButton->setOnClick('window.lam.treeview.restoreNode(\'' . getSecurityTokenName() . '\', '
590 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\', \'' . base64_encode(htmlspecialchars($rdn)) . '\', '
591 . '\'' . addslashes(_('Restore')) . '\', \'' . addslashes(_('Cancel')) . '\', \'' . addslashes(_('Restore this entry')) . '\', \'' . addslashes(_('Ok')) . '\', '
592 . '\'' . addslashes(_('Error')) . '\');');
593 $restoreButton->setCSSClasses(['lam-secondary']);
594 $row->add($restoreButton, 12, 12, 12, 'text-center');
595 }
596 }
597
598 /**
599 * Adds the content part for one attribute.
600 *
601 * @param htmlResponsiveRow $row container where to add content
602 * @param string $attributeName attribute name
603 * @param string[] $values values
604 * @param AttributeType|null $schemaAttribute schema attribute
605 * @param string[] $objectClasses object classes
606 * @param string|null $dn DN
607 * @param string[] $highlighted list of highlighted attribute names
608 */
609 private function addAttributeContent(htmlResponsiveRow $row, string $attributeName, array $values,
610 ?AttributeType $schemaAttribute, array $objectClasses, ?string $dn,
611 array $highlighted): void {
612 $schemaObjectClasses = $this->getSchemaObjectClasses();
613 $label = new htmlOutputText($attributeName);
614 $rdnAttribute = ($dn !== null) ? strtolower(extractRDNAttribute($dn)) : '';
615 $attributeNameLowerCase = strtolower($attributeName);
616 $required = ($attributeNameLowerCase === $rdnAttribute) || ($attributeNameLowerCase === 'objectclass');
617 if (($schemaAttribute !== null) && $this->isAttributeRequired($schemaObjectClasses, $schemaAttribute, $objectClasses)) {
618 $required = true;
619 }
620 $label->setMarkAsRequired($required);
621 $isHighlighted = in_array_ignore_case($attributeName, $highlighted);
622 $cssClasses = ($isHighlighted) ? 'tree-highlight' : '';
623 $row->addLabel($label, $cssClasses);
624 if (($schemaAttribute !== null) && !empty($schemaAttribute->getDescription())) {
625 $label->setTitle($schemaAttribute->getDescription());
626 }
627 $isMultiValue = $this->isMultiValueAttribute($values, $schemaAttribute);
628 $isMultiLine = $this->isMultiLineAttribute($attributeName, $schemaAttribute);
629 $row->addField($this->getAttributeContentField($attributeName, $values, $required, $isMultiValue, $isMultiLine, $schemaAttribute), $cssClasses);
630 $row->addVerticalSpacer('0.5rem');
631 }
632
633 /**
634 * Returns if the given attribute is a multi-value one.
635 *
636 * @param string[]|null $values attribute values
637 * @param AttributeType|null $schemaAttribute schema attribute
638 * @return bool is multi-value
639 */
640 private function isMultiValueAttribute(?array $values, ?AttributeType $schemaAttribute): bool {
641 return (count($values) > 1) || (($schemaAttribute !== null) && ($schemaAttribute->getIsSingleValue() !== true));
642 }
643
644 /**
645 * Returns the input fields for the attribute.
646 *
647 * @param string $attributeName attribute name
648 * @param string[] $values values
649 * @param bool $required is required
650 * @param bool $isMultiValue multi-value attribute
651 * @param bool $isMultiLine textarea attribute
652 * @param AttributeType|null $schemaAttribute schema attribute
653 * @param bool $readOnly render read-only
654 * @return htmlElement content
655 */
656 private function getAttributeContentField(string $attributeName, array $values, bool $required, bool $isMultiValue,
657 bool $isMultiLine, ?AttributeType $schemaAttribute, bool $readOnly = false): htmlElement {
658 if (!$isMultiValue) {
659 $field = $this->getAttributeInputField($attributeName, $values[0], $required, $isMultiLine, true, $schemaAttribute, 0, $readOnly);
660 if (!$readOnly) {
661 $field = $this->addExtraAttributeContent($field, $attributeName, $schemaAttribute);
662 }
663 return $field;
664 }
665 $valueListContents = [];
666 $autoCompleteValues = [];
667 $onInput = null;
668 $safeAttributeName = htmlspecialchars(strtolower($attributeName));
669 if ($safeAttributeName === 'objectclass') {
670 $schemaObjectClasses = $this->getSchemaObjectClasses();
671 foreach ($schemaObjectClasses as $schemaObjectClass) {
672 if (!in_array_ignore_case($schemaObjectClass->getName(), $values)) {
673 $autoCompleteValues[] = $schemaObjectClass->getName();
674 }
675 }
676 $onInput = "window.lam.treeview.updatePossibleNewAttributes('" . getSecurityTokenName() . "', '" . getSecurityTokenValue() . "');";
677 }
678 foreach ($values as $index => $value) {
679 $inputField = $this->getAttributeInputField($attributeName, $value, $required, $isMultiLine, false, $schemaAttribute, $index, $readOnly);
680 $cssClasses = $inputField->getCSSClasses();
681 $cssClasses[] = 'lam-attr-' . $safeAttributeName;
682 $inputField->setCSSClasses($cssClasses);
683 if ($inputField instanceof htmlInputField) {
684 if (!empty($autoCompleteValues)) {
685 $inputField->enableAutocompletion($autoCompleteValues);
686 $inputField->setId($attributeName . $index);
687 }
688 if (($onInput !== null) && !$readOnly) {
689 $inputField->setOnInput($onInput);
690 }
691 }
692 $valueLine = new htmlTable();
693 $valueLine->setCSSClasses(['fullwidth']);
694 $valueLine->addElement($inputField);
695 if (checkIfWriteAccessIsAllowed() && !$readOnly) {
696 if (!$this->isJpegAttribute($attributeName, $schemaAttribute)) {
697 $addButton = new htmlLink(null, '#', '../../graphics/add.svg');
698 $addButton->setCSSClasses(['margin2']);
699 $addButton->setOnClick('window.lam.treeview.addValue(event, this);');
700 $valueLine->addElement($addButton);
701 }
702 if (!$this->isJpegAttribute($attributeName, $schemaAttribute) || ($value !== '')) {
703 $clearButton = new htmlLink(null, '#', '../../graphics/del.svg');
704 $clearButton->setCSSClasses(['margin2']);
705 $clearButton->setOnClick('window.lam.treeview.clearValue(event, this);');
706 $valueLine->addElement($clearButton);
707 }
708 }
709 $valueListContents[] = $valueLine;
710 }
711 $listClasses = ['nowrap unstyled-list'];
712 if ($this->isOrderedAttribute($values)) {
713 $listId = 'attributeList_' . $safeAttributeName;
714 $valueList = new htmlSortableList($valueListContents, $listId);
715 $listClasses[] = 'tree-attribute-sorted-list';
716 $valueList->setOnUpdate('function() {window.lam.treeview.updateAttributePositionData(\'' . $listId . '\');}');
717 }
718 else {
719 $valueList = new htmlList($valueListContents, 'attributeList_' . $safeAttributeName);
720 }
721 $valueList->setCSSClasses($listClasses);
722 if (!$readOnly) {
723 $valueList = $this->addExtraAttributeContent($valueList, $attributeName, $schemaAttribute);
724 }
725 return $valueList;
726 }
727
728 /**
729 * Returns if the attribute has ordered values.
730 *
731 * @param string[] $values values
732 * @return bool is ordered
733 */
734 private function isOrderedAttribute(array $values): bool {
735 if (empty($values)) {
736 return false;
737 }
738 $regex = '/^\{\d+\}/';
739 foreach ($values as $value) {
740 if (!preg_match($regex, $value)) {
741 return false;
742 }
743 }
744 return true;
745 }
746
747 /**
748 * Adds any additional entry content to the element.
749 *
750 * @param htmlElement $element original element
751 * @param string $attributeName attribute name
752 * @param AttributeType|null $schemaAttribute schema attribute
753 * @return htmlElement enhanced element
754 */
755 private function addExtraAttributeContent(htmlElement $element, string $attributeName, ?AttributeType $schemaAttribute): htmlElement {
756 if ($this->isJpegAttribute($attributeName, $schemaAttribute)) {
757 $row = new htmlResponsiveRow();
758 $row->add($element);
759 $upload = new htmlInputFileUpload('lam_attr_' . $attributeName);
760 $upload->addDataAttribute('attr-name', $attributeName);
761 $upload->setCSSClasses(['image-upload']);
762
763 $row->add($upload);
764 return $row;
765 }
766 return $element;
767 }
768
769 /**
770 * Returns an input field for an LDAP attribute.
771 *
772 * @param string $attributeName attribute name
773 * @param string $value value
774 * @param bool $required required
775 * @param bool $isMultiLine is multi-line attribute
776 * @param bool $isSingleValue is single value attribute
777 * @param AttributeType|null $schemaAttribute schema attribute
778 * @param int $index value position
779 * @param bool $readOnly render read-only
780 * @return htmlElement input field
781 * @throws LAMException error generating field
782 */
783 private function getAttributeInputField(string $attributeName, string $value, bool $required, bool $isMultiLine,
784 bool $isSingleValue, ?AttributeType $schemaAttribute, int $index, bool $readOnly): htmlElement {
785 if ($this->isPasswordAttribute($attributeName)) {
786 return $this->getAttributePasswordInputField($attributeName, $value, $required, $isSingleValue, $readOnly);
787 }
788 if ($this->isJpegAttribute($attributeName, $schemaAttribute)) {
789 return $this->getAttributeJpegInputField($attributeName, $value, $index);
790 }
791 if (($schemaAttribute !== null) && $schemaAttribute->isBinary()) {
792 $value = base64_encode($value);
793 }
794 $value = $this->preProcessValue(strtolower($attributeName), $value);
795 if ($isMultiLine || $this->isPseudoMultiLine(strtolower($attributeName))) {
796 if ($readOnly) {
797 $text = new htmlOutputText(chunk_split($value, 40));
798 $text->setPreformatted();
799 return $text;
800 }
801 $inputField = new htmlInputTextarea('lam_attr_' . $attributeName, $value, 50, 5);
802 }
803 else {
804 if ($readOnly) {
805 $text = new htmlOutputText(chunk_split($value, 40));
806 if (strlen($value) > 40) {
807 $text->setPreformatted();
808 }
809 return $text;
810 }
811 $inputField = new htmlInputField('lam_attr_' . $attributeName, $value);
812 }
813 $inputField->addDataAttribute('value-orig', $value);
814 $inputField->addDataAttribute('attr-name', $attributeName);
815 $cssClass = ($isSingleValue) ? 'single-input' : 'multi-input';
816 $inputField->setCSSClasses([$cssClass, 'attribute-field']);
817 if ($required) {
818 $inputField->setRequired(true);
819 }
820 return $inputField;
821 }
822
823 /**
824 * Returns if the given attribute is a (hashable) password.
825 *
826 * @param string $attributeName attribute name
827 * @return bool is password
828 */
829 private function isPasswordAttribute(string $attributeName): bool {
830 return stripos($attributeName, 'userpassword') === 0;
831 }
832
833 /**
834 * Returns if the given attribute is a JPG image.
835 *
836 * @param string $attributeName attribute name
837 * @param AttributeType|null $schemaAttribute schema attribute
838 * @return bool is password
839 */
840 private function isJpegAttribute(string $attributeName, ?AttributeType $schemaAttribute): bool {
841 if (stripos($attributeName, 'jpegphoto') === 0) {
842 return true;
843 }
844 return ($schemaAttribute !== null) && ($schemaAttribute->getType() === 'JPEG');
845 }
846
847 /**
848 * Returns an input field for a password attribute.
849 *
850 * @param string $attributeName attribute name
851 * @param string $value value
852 * @param bool $required required
853 * @param bool $isSingleValue is single value attribute
854 * @param bool $readOnly render read-only
855 * @return htmlElement input field
856 */
857 private function getAttributePasswordInputField(string $attributeName, string $value, bool $required, bool $isSingleValue, bool $readOnly): htmlElement {
858 if ($readOnly) {
859 return new htmlOutputText('*******');
860 }
861 $inputField = new htmlInputField('lam_attr_' . $attributeName, $value);
862 $inputField->addDataAttribute('value-orig', $value);
863 $inputField->addDataAttribute('attr-name', $attributeName);
864 $cssClass = ($isSingleValue) ? 'single-input' : 'multi-input';
865 $inputField->setCSSClasses([$cssClass, 'attribute-field']);
866 if ($required) {
867 $inputField->setRequired(true);
868 }
869 $inputField->setIsPassword(true);
870 $group = new htmlGroup();
871 $table = new htmlTable();
872 $table->addElement($inputField);
873 $hashes = getSupportedHashTypes();
874 $selectedHash = [getHashType($value)];
875 $hashSelect = new htmlSelect('lam_hash_' . $attributeName, $hashes, $selectedHash);
876 $hashSelect->addDataAttribute('attr-name', $attributeName);
877 $hashSelect->setCSSClasses(['hash-select']);
878 $table->addElement($hashSelect);
879 $checkPassword = new htmlLink(null, '#', '../../graphics/light.svg');
880 $checkPassword->setTitle(_('Check password'));
881 $checkPassword->setOnClick("window.lam.treeview.checkPassword(event, this," .
882 " '" . getSecurityTokenName() . "', '" . getSecurityTokenValue() . "'," .
883 " '" . _('Check password') . "', '" . _('Check') . "', '" . _('Cancel') . "', '" . _('Ok') . "');");
884 $table->addElement($checkPassword);
885 $group->addElement($table);
886 return $group;
887 }
888
889 /**
890 * Returns an input field for a JPG image attribute.
891 *
892 * @param string $attributeName attribute name
893 * @param string $value value
894 * @param int $index index
895 * @return htmlElement input field
896 * @throws LAMException error writing image file
897 */
898 private function getAttributeJpegInputField(string $attributeName, string $value, int $index): htmlElement {
899 $tempFilesManager = new LamTemporaryFilesManager();
900 $fileName = $tempFilesManager->registerTemporaryFile('.jpg');
901 $handle = $tempFilesManager->openTemporaryFileForWrite($fileName);
902 fwrite($handle, $value);
903 fclose($handle);
904 $image = new htmlImage($tempFilesManager->getResourceLink($fileName));
905 $image->enableLightbox();
906 $image->setCSSClasses(['thumbnail', 'image-input', 'attribute-field']);
907 $image->addDataAttribute('attr-name', $attributeName);
908 $image->addDataAttribute('index', (string) $index);
909 return $image;
910 }
911
912 /**
913 * Returns if the given attribute is multi-line.
914 *
915 * @param string $attributeName attribute name
916 * @param AttributeType|null $schemaAttribute schema attribute
917 * @return bool is multi-line
918 */
919 private function isMultiLineAttribute(string $attributeName, ?AttributeType $schemaAttribute): bool {
920 $knownAttributes = ['postalAddress1', 'homePostalAddress', 'personalSignature', 'description', 'mailReplyText'];
921 if (in_array_ignore_case($attributeName, $knownAttributes)) {
922 return true;
923 }
924 if ($schemaAttribute === null) {
925 return false;
926 }
927 $knownSyntaxOIDs = [
928 // octet string syntax OID:
929 '1.3.6.1.4.1.1466.115.121.1.40',
930 // postal address syntax OID:
931 '1.3.6.1.4.1.1466.115.121.1.41'];
932 return in_array($schemaAttribute->getSyntaxOID(), $knownSyntaxOIDs);
933 }
934
935 /**
936 * Returns if the attribute is required for the given list of object classes.
937 *
938 * @param ObjectClass[] $schemaObjectClasses object class definitions
939 * @param AttributeType $schemaAttribute schema attribute
940 * @param string[] $objectClasses list of object classes
941 * @return bool is required
942 */
943 private function isAttributeRequired(array $schemaObjectClasses, AttributeType $schemaAttribute, array $objectClasses): bool {
944 foreach ($objectClasses as $objectClass) {
945 $objectClass = strtolower($objectClass);
946 if (!isset($schemaObjectClasses[$objectClass])) {
947 continue;
948 }
949 $schemaObjectClass = $schemaObjectClasses[$objectClass];
950 $requiredAttributes = $schemaObjectClass->getMustAttrNames();
951 if (in_array_ignore_case($schemaAttribute->getName(), $requiredAttributes)) {
952 return true;
953 }
954 if (!empty($schemaObjectClass->getSupClasses())
955 && $this->isAttributeRequired($schemaObjectClasses, $schemaAttribute, $schemaObjectClass->getSupClasses())) {
956 return true;
957 }
958 }
959 return false;
960 }
961
962 /**
963 * Returns the internal attributes.
964 *
965 * @param string $dn DN
966 * @return string JSON
967 */
968 private function getInternalAttributesContent(string $dn): string {
969 $row = new htmlResponsiveRow();
970 $row->add(new htmlSubTitle(_('Internal attributes')));
971 $attributes = ldapGetDN($dn, ['+', 'creatorsName', 'createTimestamp', 'modifiersName',
972 'modifyTimestamp', 'hasSubordinates', 'pwdChangedTime', 'passwordRetryCount', 'accountUnlockTime', 'nsAccountLock',
973 'nsRoleDN', 'passwordExpirationTime']);
974 unset($attributes['dn']);
975 ksort($attributes);
976 foreach ($attributes as $attributeName => $values) {
977 $row->addLabel(new htmlOutputText($this->getProperAttributeName($attributeName)));
978 $row->addField(new htmlOutputText(implode(', ', $values)));
979 $row->addVerticalSpacer('0.5rem');
980 }
981 ob_start();
982 parseHtml(null, $row, [], false);
983 $content = ob_get_contents();
984 ob_end_clean();
985 return json_encode(['content' => $content]);
986 }
987
988 /**
989 * Returns the node content with the attribute listing.
990 *
991 * @return string JSON
992 */
993 private function saveAttributes(string $dn): string {
994 $schemaAttributes = $this->getSchemaAttributes();
995 $attributes = ldapGetDN($dn, ['*']);
996 unset($attributes['dn']);
997 $attributes = array_change_key_case($attributes);
998 $changes = json_decode($_POST['changes'], true);
999 $changes = array_change_key_case($changes);
1000 logNewMessage(LOG_DEBUG, 'LDAP changes for ' . $dn . ': ' . print_r($changes, true));
1001 $ldapChanges = [];
1002 foreach ($changes as $attrName => $change) {
1003 $schemaAttribute = $schemaAttributes[$attrName] ?? null;
1004 if (isset($change['new'])) {
1005 $newValues = $change['new'];
1006 if (isset($change['hash'])) {
1007 $newValues = $this->applyPasswordHash($newValues, $change['hash']);
1008 }
1009 elseif (($schemaAttribute !== null) && $schemaAttribute->isBinary()) {
1010 $newValues = $this->decodeBinaryAttributeValues($newValues);
1011 }
1012 $ldapChanges[$attrName] = $newValues;
1013 }
1014 if (isset($change['delete']) && isset($attributes[$attrName])) {
1015 $oldValues = $attributes[$attrName];
1016 $changed = false;
1017 foreach ($change['delete'] as $index) {
1018 if (isset($oldValues[$index])) {
1019 unset($oldValues[$index]);
1020 $changed = true;
1021 }
1022 }
1023 if ($changed) {
1024 if (($schemaAttribute !== null) && $schemaAttribute->isBinary()) {
1025 $oldValues = $this->decodeBinaryAttributeValues($oldValues);
1026 }
1027 $ldapChanges[$attrName] = array_values($oldValues);
1028 }
1029 }
1030 if (!empty($change['upload'])) {
1031 if (!isset($ldapChanges[$attrName]) && !empty($attributes[$attrName])) {
1032 $ldapChanges[$attrName] = $attributes[$attrName];
1033 }
1034 $oldValues = empty($attributes[$attrName]) ? [] : $attributes[$attrName];
1035 if ($this->isMultiValueAttribute($oldValues, $schemaAttribute)) {
1036 $ldapChanges[$attrName][] = base64_decode($change['upload']);
1037 }
1038 else {
1039 $ldapChanges[$attrName][0] = base64_decode($change['upload']);
1040 }
1041 }
1042 }
1043 $message = new htmlStatusMessage('INFO', _('You made no changes'));
1044 $jsonData = [];
1045 // rename DN if RDN attribute changed
1046 $rdnAttribute = strtolower(extractRDNAttribute($dn));
1047 $rdnValue = extractRDNValue($dn);
1048 if (isset($ldapChanges[$rdnAttribute][0]) && !in_array($rdnValue, $ldapChanges[$rdnAttribute])) {
1049 $pos = 0;
1050 $oldPos = array_search($rdnValue, $changes[$rdnAttribute]['old']);
1051 if (($oldPos !== false) && isset($ldapChanges[$rdnAttribute][$oldPos])) {
1052 $pos = $oldPos;
1053 }
1054 $newRdnValue = $ldapChanges[$rdnAttribute][$pos];
1055 $newRdn = $rdnAttribute . '=' . ldap_escape($newRdnValue, '', LDAP_ESCAPE_DN);
1056 $parent = extractDNSuffix($dn);
1057 $renameOk = ldap_rename($_SESSION['ldap']->server(), $dn, $newRdn, $parent, $_SESSION['ldap']->isActiveDirectory());
1058 $newDn = $newRdn . ',' . $parent;
1059 if ($renameOk) {
1060 logNewMessage(LOG_DEBUG, 'Renamed ' . $dn . ' to ' . $newDn);
1061 $dn = $newDn;
1062 $jsonData['newDn'] = base64_encode($newDn);
1063 $jsonData['parent'] = base64_encode($parent);
1064 unset($ldapChanges[$rdnAttribute]);
1065 $message = new htmlStatusMessage('INFO', _('All changes were successful.'));
1066 }
1067 else {
1068 logNewMessage(LOG_ERR, 'Renaming ' . $dn . ' to ' . $newDn . ' failed: ' . getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
1069 $message = new htmlStatusMessage('ERROR', sprintf(_('Was unable to rename DN: %s.'), $dn), getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
1070 // skip other changes
1071 $ldapChanges = [];
1072 }
1073 }
1074 if (!empty($ldapChanges)) {
1075 $this->handleSpecialAttributes($dn, $ldapChanges, $attributes, $schemaAttributes);
1076 logNewMessage(LOG_DEBUG, 'LDAP changes to DN ' . $dn . ': ' . print_r($ldapChanges, true));
1077 $saved = ldap_modify($_SESSION['ldap']->server(), $dn, $ldapChanges);
1078 if ($saved) {
1079 $message = new htmlStatusMessage('INFO', _('All changes were successful.'));
1080 }
1081 else {
1082 $message = new htmlStatusMessage('ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $dn), getDefaultLDAPErrorString($_SESSION['ldap']->server()));
1083 }
1084 }
1085 ob_start();
1086 parseHtml(null, $message, [], true);
1087 $messageContent = ob_get_contents();
1088 ob_end_clean();
1089 $jsonData['result'] = $messageContent;
1090 return json_encode($jsonData);
1091 }
1092
1093 /**
1094 * Handles attributes that require specific operations.
1095 *
1096 * @param string $dn DN
1097 * @param array<string, string[]|string> $ldapChanges changes
1098 * @param array<string, string[]|string> $attributes original attributes
1099 * @param array<string, AttributeType> $schemaAttributes schema definition for attributes
1100 */
1101 private function handleSpecialAttributes(string $dn, array &$ldapChanges, array $attributes, array $schemaAttributes): void {
1102 // olcModuleLoad is add-only
1103 if (isset($ldapChanges['olcmoduleload']) && isset($attributes['olcmoduleload'])) {
1104 $newModules = array_delete($attributes['olcmoduleload'], $ldapChanges['olcmoduleload']);
1105 unset($ldapChanges['olcmoduleload']);
1106 if (!empty($newModules)) {
1107 $isOk = ldap_mod_add($_SESSION['ldap']->server(), $dn, ['olcmoduleload' => $newModules]);
1108 if (!$isOk) {
1109 logNewMessage(LOG_ERR, 'Changing olcmoduleload at ' . $dn . ' failed: ' . getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
1110 }
1111 }
1112 }
1113 // olcAccess needs removal of newlines
1114 if (isset($ldapChanges['olcaccess'])) {
1115 for ($i = 0; $i < count($ldapChanges['olcaccess']); $i++) {
1116 $ldapChanges['olcaccess'][$i] = str_replace("\n", ' ', $ldapChanges['olcaccess'][$i]);
1117 }
1118 }
1119 // add ";binary" to binary attributes
1120 foreach ($ldapChanges as $attributeName => $value) {
1121 if (!isset($schemaAttributes[$attributeName])) {
1122 continue;
1123 }
1124 $schemaAttribute = $schemaAttributes[$attributeName];
1125 if ($schemaAttribute->isBinary()
1126 && (!str_contains($attributeName, ';binary'))
1127 && ($schemaAttribute->getSyntaxOID() === '1.3.6.1.4.1.1466.115.121.1.8')) {
1128 $ldapChanges[$attributeName . ';binary'] = $value;
1129 unset($ldapChanges[$attributeName]);
1130 }
1131 }
1132 }
1133
1134 /**
1135 * Base 64 decodes attribute values.
1136 *
1137 * @param string[] $encoded encoded data
1138 * @return string[] binary data
1139 */
1140 private function decodeBinaryAttributeValues(array $encoded): array {
1141 $binaryValues = [];
1142 foreach ($encoded as $value) {
1143 $decoded = base64_decode($value, true);
1144 $binaryValues[] = ($decoded !== false) ? $decoded : $value;
1145 }
1146 return $binaryValues;
1147 }
1148
1149 /**
1150 * Applies password hashing on the provided values.
1151 *
1152 * @param string[] $values values
1153 * @param string[] $hash hash types
1154 * @return string[] hashed values
1155 */
1156 private function applyPasswordHash(array $values, array $hash): array {
1157 $result = [];
1158 for ($i = 0; $i < count($values); $i++) {
1159 $oldType = getHashType($values[$i]);
1160 $result[] = (($oldType === 'PLAIN') && ($hash[$i] !== 'PLAIN')) ? pwd_hash($values[$i], true, $hash[$i]) : $values[$i];
1161 }
1162 return $result;
1163 }
1164
1165 /**
1166 * Displays the content to create a new subnode.
1167 *
1168 * @param string $dn DN
1169 * @return string JSON data
1170 */
1171 private function createNewNode(string $dn): string {
1172 $step = $_GET['step'];
1173 switch ($step) {
1174 case 'getObjectClasses':
1175 return $this->createNewNodeGetObjectClassesStep($dn);
1176 case 'checkObjectClasses':
1177 return $this->createNewNodeCheckObjectClassesStep($dn);
1178 case 'checkAttributes':
1179 return $this->createNewNodeCheckAttributesStep($dn);
1180 }
1181 logNewMessage(LOG_ERR, 'Invalid create new node step: ' . $step);
1182 return '';
1183 }
1184
1185 /**
1186 * Returns the content to select the object classes.
1187 *
1188 * @param string $dn DN
1189 * @param string|null $errorMessage error if any
1190 * @return string JSON data
1191 */
1192 private function createNewNodeGetObjectClassesStep(string $dn, ?string $errorMessage = null): string {
1193 $row = new htmlResponsiveRow();
1194 $row->add(new htmlTitle(_('Create a child entry')));
1195 if ($errorMessage !== null) {
1196 $row->add(new htmlStatusMessage('ERROR', $errorMessage));
1197 }
1198 $row->addLabel(new htmlOutputText(_('Parent')));
1199 $row->addField(new htmlOutputText($dn));
1200 $row->addVerticalSpacer('1rem');
1201 $schemaObjectClasses = $this->getSchemaObjectClasses();
1202 $objectClassOptions = [];
1203 $selectCssClasses = [];
1204 foreach ($schemaObjectClasses as $schemaObjectClass) {
1205 $name = $schemaObjectClass->getName();
1206 $objectClassOptions[$name] = $name;
1207 if ($schemaObjectClass->getType() === 'structural') {
1208 $selectCssClasses[$name] = 'bold';
1209 }
1210 }
1211 $objectClassSelect = new htmlResponsiveSelect('objectClasses', $objectClassOptions, [], _('Object classes'), null, 10);
1212 $objectClassSelect->setHasDescriptiveElements(true);
1213 $objectClassSelect->setMultiSelect(true);
1214 $objectClassSelect->setOptionCssClasses($selectCssClasses);
1215 $row->add($objectClassSelect);
1216 $row->addVerticalSpacer('0.5rem');
1217 $filterGroup = new htmlGroup();
1218 $filterGroup->addElement(new htmlOutputText(_('Filter') . ' '));
1219 $filterInput = new htmlInputField('filter', '');
1220 $filterInput->filterSelectBox('objectClasses');
1221 $filterGroup->addElement($filterInput);
1222 $row->addLabel(new htmlOutputText('&nbsp;', false));
1223 $row->addField($filterGroup);
1224 $row->addVerticalSpacer('1rem');
1225 $nextButton = new htmlButton('next', _('Next'));
1226 $nextButton->setCSSClasses(['lam-primary']);
1227 $nextButton->setOnClick('window.lam.treeview.createNodeSelectObjectClassesStep(event, \'' . getSecurityTokenName() . '\', \'' . getSecurityTokenValue() . '\');');
1228 $row->add($nextButton, 12, 12, 12, 'text-center');
1229 $row->addVerticalSpacer('2rem');
1230 $row->add(new htmlOutputText(_('Hint: You must choose exactly one structural object class (shown in bold above)')));
1231 $row->add(new htmlHiddenInput('parentDn', base64_encode($dn)));
1232 ob_start();
1233 parseHtml(null, $row, [], false);
1234 $content = ob_get_contents();
1235 ob_end_clean();
1236 return json_encode(['content' => $content]);
1237 }
1238
1239 /**
1240 * Returns the content to select the object classes.
1241 *
1242 * @param string $dn DN
1243 * @param string|null $errorMessage error if any
1244 * @param string|null $rdnAttribute RDN attribute name
1245 * @param array<string, string[]|string>|null $attributes attribute values
1246 * @return string JSON data
1247 */
1248 private function createNewNodeCheckObjectClassesStep(string $dn, ?string $errorMessage = null, ?string $rdnAttribute = null, ?array $attributes = null): string {
1249 $objectClasses = ($attributes === null) ? explode(',', $_POST['objectClasses']) : $attributes['objectClass'];
1250 $structuralObjectClassesCount = 0;
1251 $schemaObjectClasses = $this->getSchemaObjectClasses();
1252 foreach ($objectClasses as $objectClass) {
1253 $objectClassLower = strtolower($objectClass);
1254 if (!isset($schemaObjectClasses[$objectClassLower])) {
1255 logNewMessage(LOG_ERR, 'Tree view new node, invalid object class: ' . $objectClass);
1256 return $this->createNewNodeGetObjectClassesStep($dn, _('Invalid object class.'));
1257 }
1258 if ($schemaObjectClasses[$objectClassLower]->getType() === 'structural') {
1259 $structuralObjectClassesCount++;
1260 }
1261 }
1262 if ($structuralObjectClassesCount === 0) {
1263 return $this->createNewNodeGetObjectClassesStep($dn, _('No structural object class selected.'));
1264 }
1265 elseif ($structuralObjectClassesCount > 1) {
1266 return $this->createNewNodeGetObjectClassesStep($dn, _('Multiple structural object classes selected.'));
1267 }
1268 $row = new htmlResponsiveRow();
1269 $row->add(new htmlTitle(_('Create a child entry')));
1270 if ($errorMessage !== null) {
1271 $row->add(new htmlStatusMessage('ERROR', $errorMessage));
1272 $row->addVerticalSpacer('0.5rem');
1273 }
1274 $row->addLabel(new htmlOutputText(_('Parent')));
1275 $row->addField(new htmlOutputText($dn));
1276 $row->addVerticalSpacer('1rem');
1277 $row->addLabel(new htmlOutputText(_('Object classes')));
1278 $row->addField(new htmlOutputText(implode(', ', $objectClasses)));
1279 $row->addVerticalSpacer('1rem');
1280 $schemaAttributes = $this->getSchemaAttributes();
1281 $mustAttributes = [];
1282 $mayAttributes = [];
1283 foreach ($objectClasses as $objectClass) {
1284 $classMustAttributeNames = $this->getMustAttributeNamesRecursive($schemaObjectClasses, $objectClass);
1285 foreach ($classMustAttributeNames as $classMustAttributeName) {
1286 $attrNameLower = strtolower($classMustAttributeName);
1287 if (!isset($schemaAttributes[$attrNameLower])) {
1288 logNewMessage(LOG_ERR, 'Tree view new node, invalid attribute: ' . $classMustAttributeName);
1289 return $this->createNewNodeGetObjectClassesStep($dn, _('Invalid object class.'));
1290 }
1291 $mustAttributes[$attrNameLower] = $schemaAttributes[$attrNameLower];
1292 }
1293 }
1294 foreach ($objectClasses as $objectClass) {
1295 $classMayAttributeNames = $this->getMayAttributeNamesRecursive($schemaObjectClasses, $objectClass);
1296 foreach ($classMayAttributeNames as $classMayAttributeName) {
1297 $attrNameLower = strtolower($classMayAttributeName);
1298 if (!isset($schemaAttributes[$attrNameLower])) {
1299 logNewMessage(LOG_ERR, 'Tree view new node, invalid attribute: ' . $classMayAttributeName);
1300 return $this->createNewNodeGetObjectClassesStep($dn, _('Invalid object class.'));
1301 }
1302 if (array_key_exists($attrNameLower, $mustAttributes)) {
1303 continue;
1304 }
1305 $mayAttributes[$attrNameLower] = $schemaAttributes[$attrNameLower];
1306 }
1307 }
1308 if (isset($mustAttributes['objectclass'])) {
1309 unset($mustAttributes['objectclass']);
1310 }
1311 ksort($mustAttributes);
1312 ksort($mayAttributes);
1313 $allAttributes = array_merge($mustAttributes, $mayAttributes);
1314 ksort($allAttributes);
1315 $rdnOptions = [];
1316 foreach ($allAttributes as $attribute) {
1317 $rdnOptions[] = $attribute->getName();
1318 }
1319 $rdnOptionsSelected = [];
1320 if ($rdnAttribute !== null) {
1321 $rdnOptionsSelected[] = $rdnAttribute;
1322 }
1323 elseif (isset($allAttributes['cn'])) {
1324 $rdnOptionsSelected[] = $allAttributes['cn']->getName();
1325 }
1326 elseif (isset($allAttributes['ou'])) {
1327 $rdnOptionsSelected[] = $allAttributes['ou']->getName();
1328 }
1329 $row->add(new htmlResponsiveSelect('rdn', $rdnOptions, $rdnOptionsSelected, _('RDN identifier')));
1330 if (!empty($mustAttributes)) {
1331 $row->add(new htmlSubTitle(_('Required attributes')));
1332 }
1333 foreach ($mustAttributes as $mustAttribute) {
1334 $values = empty($attributes[$mustAttribute->getName()]) ? [''] : $attributes[$mustAttribute->getName()];
1335 $this->addAttributeContent($row, $mustAttribute->getName(), $values, $mustAttribute, $objectClasses, null, []);
1336 }
1337 if (!empty($mayAttributes)) {
1338 $row->add(new htmlSubTitle(_('Optional attributes')));
1339 }
1340 foreach ($mayAttributes as $mayAttribute) {
1341 $values = empty($attributes[$mayAttribute->getName()]) ? [''] : $attributes[$mayAttribute->getName()];
1342 $this->addAttributeContent($row, $mayAttribute->getName(), $values, $mayAttribute, $objectClasses, null, []);
1343 }
1344 $row->addVerticalSpacer('1rem');
1345 $nextButton = new htmlButton('save', _('Create'));
1346 $nextButton->setCSSClasses(['lam-primary']);
1347 $nextButton->setOnClick('window.lam.treeview.createNodeEnterAttributesStep(event, \'' . getSecurityTokenName() . '\', \'' . getSecurityTokenValue() . '\');');
1348 $row->add($nextButton, 12, 12, 12, 'text-center');
1349 $row->add(new htmlHiddenInput('objectClasses', implode(',', $objectClasses)));
1350 $row->add(new htmlHiddenInput('parentDn', base64_encode($dn)));
1351 ob_start();
1352 parseHtml(null, $row, [], false);
1353 $content = ob_get_contents();
1354 ob_end_clean();
1355 return json_encode(['content' => $content]);
1356 }
1357
1358 /**
1359 * Gets a recursive list of must attribute names.
1360 *
1361 * @param ObjectClass[] $objectClasses schema object classes
1362 * @param string $objectClass object class
1363 * @return string[] attribute names
1364 */
1365 private function getMustAttributeNamesRecursive(array $objectClasses, string $objectClass): array {
1366 $objectClassLower = strtolower($objectClass);
1367 $objectClassObject = $objectClasses[$objectClassLower];
1368 $attributeNames = $objectClassObject->getMustAttrNames();
1369 foreach ($objectClassObject->getSupClasses() as $superClass) {
1370 $attributeNames = array_merge($attributeNames, $this->getMustAttributeNamesRecursive($objectClasses, $superClass));
1371 }
1372 $attributeNames = array_map(strtolower(...), $attributeNames);
1373 return array_unique($attributeNames);
1374 }
1375
1376 /**
1377 * Gets a recursive list of may attribute names.
1378 *
1379 * @param ObjectClass[] $objectClasses schema object classes
1380 * @param string $objectClass object class
1381 * @return string[] attribute names
1382 */
1383 private function getMayAttributeNamesRecursive(array $objectClasses, string $objectClass): array {
1384 $objectClassLower = strtolower($objectClass);
1385 $objectClassObject = $objectClasses[$objectClassLower];
1386 $attributeNames = $objectClassObject->getMayAttrNames();
1387 foreach ($objectClassObject->getSupClasses() as $superClass) {
1388 $attributeNames = array_merge($attributeNames, $this->getMayAttributeNamesRecursive($objectClasses, $superClass));
1389 }
1390 $attributeNames = array_map(strtolower(...), $attributeNames);
1391 return array_unique($attributeNames);
1392 }
1393
1394 /**
1395 * Returns the content for the check attributes step of node creation.
1396 *
1397 * @param string $dn DN
1398 * @return string JSON data
1399 */
1400 private function createNewNodeCheckAttributesStep(string $dn): string {
1401 $objectClasses = $_POST['objectClasses'];
1402 $rdnAttribute = $_POST['rdn'];
1403 $attributeChanges = json_decode($_POST['attributes'], true);
1404 $attributes = ['objectClass' => explode(',', $objectClasses)];
1405 foreach ($attributeChanges as $attributeName => $attributeChange) {
1406 if (isset($attributeChange['new'])) {
1407 $attributes[$attributeName] = $attributeChange['new'];
1408 if (isset($attributeChange['hash'])) {
1409 $attributes[$attributeName] = $this->applyPasswordHash($attributes[$attributeName], $attributeChange['hash']);
1410 }
1411 }
1412 if (isset($attributeChange['upload'])) {
1413 $attributes[$attributeName][] = base64_decode($attributeChange['upload']);
1414 }
1415 }
1416 if (!isset($attributes[$rdnAttribute][0])) {
1417 return $this->createNewNodeCheckObjectClassesStep($dn, _('The RDN field is empty.'), $rdnAttribute, $attributes);
1418 }
1419 $rdn = $rdnAttribute . '=' . ldap_escape($attributes[$rdnAttribute][0], '', LDAP_ESCAPE_DN);
1420 $newDn = $rdn . ',' . $dn;
1421 $success = ldap_add($_SESSION['ldap']->server(), $newDn, $attributes);
1422 if (!$success) {
1423 return $this->createNewNodeCheckObjectClassesStep($dn, getExtendedLDAPErrorMessage($_SESSION['ldap']->server()), $rdnAttribute, $attributes);
1424 }
1425 return $this->getNodeContent($newDn, new htmlStatusMessage('INFO',
1426 sprintf(_('Creation successful. DN <b>%s</b> has been created.'),
1427 htmlspecialchars(unescapeLdapSpecialCharacters($newDn)))));
1428 }
1429
1430 /**
1431 * Deletes a node in LDAP.
1432 *
1433 * @param string $dn DN
1434 * @return string JSON
1435 */
1436 private function deleteNode(string $dn): string {
1437 $errors = deleteDN($dn, true);
1438 foreach ($errors as $error) {
1439 logNewMessage(LOG_ERR, 'Tree view delete node failed: ' . $error[0] . ' ' . $error[1]);
1440 }
1441 if (!empty($errors)) {
1442 return json_encode(['errors' => $errors]);
1443 }
1444 return json_encode([]);
1445 }
1446
1447 /**
1448 * Restores a node in LDAP.
1449 *
1450 * @param string $dn DN
1451 * @return string JSON
1452 */
1453 private function restoreNode(string $dn): string {
1454 $rdn = explode(self::AD_DELETED_DELIMITER, $dn)[0];
1455 $targetDn = $_POST['targetDn'];
1456 $changes = [
1457 [
1458 'attrib' => 'isDeleted',
1459 'modtype' => LDAP_MODIFY_BATCH_REMOVE_ALL
1460 ],
1461 [
1462 'attrib' => 'distinguishedName',
1463 'modtype' => LDAP_MODIFY_BATCH_REPLACE,
1464 'values' => [$rdn . ',' . $targetDn]
1465 ],
1466 ];
1467 $success = ldap_modify_batch(getLDAPServerHandle(), $dn, $changes, getCommonLdapControls());
1468 if ($success) {
1469 return json_encode([]);
1470 }
1471 $error = getDefaultLDAPErrorString(getLDAPServerHandle());
1472 logNewMessage(LOG_ERR, 'Tree view restore node failed: ' . $error);
1473 return json_encode([
1474 'errorTitle' => htmlspecialchars(sprintf(_('Was unable to restore %s.'), $rdn)),
1475 'errorText' => $error
1476 ]);
1477 }
1478
1479 /**
1480 * Stops processing if DN is invalid.
1481 *
1482 * @param string $dn DN
1483 * @return bool DN is valid
1484 */
1485 private function validateDn(string $dn, bool $die = true): bool {
1486 $dn = strtolower($dn);
1487 $rootDns = TreeViewTool::getRootDns();
1488 foreach ($rootDns as $rootDn) {
1489 $rootDn = strtolower($rootDn);
1490 if (str_ends_with($dn, $rootDn)) {
1491 return true;
1492 }
1493 }
1494 if (!$die) {
1495 return false;
1496 }
1497 logNewMessage(LOG_ERR, 'Invalid DN for tree view: ' . $dn);
1498 die();
1499 }
1500
1501 /**
1502 * Returns the proper spelling of the attribute name.
1503 *
1504 * @param string $attributeName attribute name in lower-case
1505 * @return string proper attribute name
1506 */
1507 private function getProperAttributeName(string $attributeName): string {
1508 $schemaAttributes = $this->getSchemaAttributes();
1509 if (isset($schemaAttributes[$attributeName])) {
1510 return $schemaAttributes[$attributeName]->getName();
1511 }
1512 return $attributeName;
1513 }
1514
1515 /**
1516 * Returns the schema attributes.
1517 *
1518 * @return AttributeType[] attributes
1519 */
1520 private function getSchemaAttributes(): array {
1521 if ($this->schemaAttributes === null) {
1522 $this->schemaAttributes = get_schema_attributes();
1523 }
1524 return $this->schemaAttributes;
1525 }
1526
1527 /**
1528 * Returns the schema object classes.
1529 *
1530 * @return ObjectClass[] object classes
1531 */
1532 private function getSchemaObjectClasses(): array {
1533 if ($this->schemaObjectClasses === null) {
1534 $this->schemaObjectClasses = get_schema_objectclasses();
1535 }
1536 return $this->schemaObjectClasses;
1537 }
1538
1539 /**
1540 * Stops processing if no write access is allowed.
1541 */
1542 private function ensureWriteAccess(): void {
1543 if (!checkIfWriteAccessIsAllowed()) {
1544 logNewMessage(LOG_ERR, 'Write operation denied for tree view.');
1545 die();
1546 }
1547 }
1548
1549 /**
1550 * Renders the search mask.
1551 *
1552 * @param string $dn DN
1553 * @return string JSON
1554 */
1555 private function search(string $dn): string {
1556 $row = new htmlResponsiveRow();
1557 $row->add(new htmlTitle(_('Search')));
1558 $row->addLabel(new htmlOutputText(_('Base DN')));
1559 $row->addField(new htmlOutputText(unescapeLdapSpecialCharacters($dn)));
1560 $row->addVerticalSpacer('1rem');
1561 $scopeOptions = [
1562 _('Sub (entire subtree)') => 'sub',
1563 _('One (one level beneath base)') => 'one',
1564 ];
1565 $scopeSelect = new htmlResponsiveSelect('scope', $scopeOptions, [], _('Search scope'));
1566 $scopeSelect->setSortElements(false);
1567 $scopeSelect->setHasDescriptiveElements(true);
1568 $row->add($scopeSelect);
1569 $filterInput = new htmlResponsiveInputField(_('Search filter'), 'filter', '(objectClass=*)', null, true);
1570 $row->add($filterInput);
1571 $row->add(new htmlResponsiveInputField(_('Attributes'), 'attributes', 'cn, givenName, sn, uid', null, true));
1572 $row->add(new htmlResponsiveInputField(_('Order by'), 'orderBy', 'dn'));
1573 $resultCountInput = new htmlResponsiveInputField(_('LDAP search limit'), 'limit', '50');
1574 $resultCountInput->setMinimumAndMaximumNumber();
1575 $row->add($resultCountInput);
1576 $displayFormat = [
1577 _('List') => 'list',
1578 _('Table') => 'table'
1579 ];
1580 $formatSelect = new htmlResponsiveSelect('format', $displayFormat, ['list'], _('Display format'));
1581 $formatSelect->setHasDescriptiveElements(true);
1582 $row->add($formatSelect);
1583 $row->addVerticalSpacer('2rem');
1584 $nextButton = new htmlButton('search', _('Search'));
1585 $nextButton->setCSSClasses(['lam-primary']);
1586 $nextButton->setOnClick('window.lam.treeview.searchResults(event, \'' . getSecurityTokenName() . '\', \'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
1587 $row->add($nextButton, 12, 12, 12, 'text-center');
1588 ob_start();
1589 parseHtml(null, $row, [], false);
1590 $content = ob_get_contents();
1591 ob_end_clean();
1592 return json_encode(['content' => $content]);
1593 }
1594
1595 /**
1596 * Renders the search results.
1597 *
1598 * @param string $dn DN
1599 * @return string JSON
1600 */
1601 private function searchResults(string $dn): string {
1602 $scope = $_POST['scope'];
1603 if (!in_array($scope, ['sub', 'one'])) {
1604 logNewMessage(LOG_ERR, 'Invalid search scope: ' . $scope);
1605 die();
1606 }
1607 $format = $_POST['format'];
1608 if (!in_array($format, ['list', 'table'])) {
1609 logNewMessage(LOG_ERR, 'Invalid search format: ' . $format);
1610 die();
1611 }
1612 $filter = empty($_POST['filter']) ? '(objectClass=*)' : $_POST['filter'];
1613 $attributes = preg_split('/,[ ]*/', $_POST['attributes']);
1614 $searchAttributes = $attributes;
1615 if (!in_array_ignore_case('objectClass', $searchAttributes)) {
1616 $searchAttributes[] = 'objectClass';
1617 }
1618 global $lamOrderByAttribute;
1619 $lamOrderByAttribute = empty($_POST['orderBy']) ? 'dn' : strtolower($_POST['orderBy']);
1620 $limit = empty($_POST['limit']) ? 0 : intval($_POST['limit']);
1621 $results = match ($scope) {
1622 'sub' => searchLDAP($dn, $filter, $searchAttributes, $limit),
1623 default => ldapListDN($dn, $filter, $searchAttributes, null, $limit),
1624 };
1625 usort($results, compareByAttributes(...));
1626 $row = $this->searchResultsHeader($dn, $filter);
1627 if ($format === 'list') {
1628 return $this->searchResultsAsList($results, $attributes, $row);
1629 }
1630 return $this->searchResultsAsTable($results, $attributes, $row);
1631 }
1632
1633 /**
1634 * Creates the header part of the search results.
1635 *
1636 * @param string $dn search base
1637 * @param string $filter LDAP filter
1638 * @return htmlResponsiveRow content
1639 */
1640 private function searchResultsHeader(string $dn, string $filter): htmlResponsiveRow {
1641 $row = new htmlResponsiveRow();
1642 $row->add(new htmlTitle(_('Search Results')));
1643 $row->addLabel(new htmlOutputText(_('Base DN')));
1644 $row->addField(new htmlOutputText(unescapeLdapSpecialCharacters($dn)));
1645 $row->addVerticalSpacer('0.5rem');
1646 $row->addLabel(new htmlOutputText(_('Search filter')));
1647 $row->addField(new htmlOutputText($filter));
1648 $row->addVerticalSpacer('2rem');
1649 return $row;
1650 }
1651
1652 /**
1653 * Returns the search results as list.
1654 *
1655 * @param array<string, string[]|string>[] $results results
1656 * @param string[] $attributes attribute list to show
1657 * @param htmlResponsiveRow $row content
1658 * @return string JSON
1659 */
1660 private function searchResultsAsList(array $results, array $attributes, htmlResponsiveRow $row): string {
1661 foreach ($results as $result) {
1662 $row->add(new htmlSubTitle(getAbstractDN($result['dn']), $this->getNodeIcon($result)));
1663 $row->addLabel(new htmlOutputText('dn'));
1664 $row->addField(new htmlLink(unescapeLdapSpecialCharacters($result['dn']), 'treeView.php?dn=' . base64_encode($result['dn'])));
1665 $result = array_change_key_case($result);
1666 foreach ($attributes as $attribute) {
1667 $attributeLower = strtolower($attribute);
1668 if (!empty($result[$attributeLower])) {
1669 $row->addLabel(new htmlOutputText($attribute));
1670 $row->addField(new htmlOutputText(implode(', ', $result[$attributeLower])));
1671 }
1672 }
1673 $row->addVerticalSpacer('1rem');
1674 }
1675 ob_start();
1676 parseHtml(null, $row, [], false);
1677 $content = ob_get_contents();
1678 ob_end_clean();
1679 return json_encode(['content' => $content]);
1680 }
1681
1682 /**
1683 * Returns the search results as table.
1684 *
1685 * @param array<string, string[]|string>[] $results results
1686 * @param string[] $attributes attribute list to show
1687 * @param htmlResponsiveRow $row content
1688 * @return string JSON
1689 */
1690 private function searchResultsAsTable(array $results, array $attributes, htmlResponsiveRow $row) {
1691 $titles = array_merge(['', 'dn'], $attributes);
1692 $data = [];
1693 foreach ($results as $result) {
1694 $dataEntry = [$this->getNodeIcon($result), new htmlLink(unescapeLdapSpecialCharacters($result['dn']), 'treeView.php?dn=' . base64_encode($result['dn']))];
1695 $result = array_change_key_case($result);
1696 foreach ($attributes as $attribute) {
1697 $attributeLower = strtolower($attribute);
1698 if (!empty($result[$attributeLower])) {
1699 $dataEntry[] = new htmlOutputText(implode(', ', $result[$attributeLower]));
1700 }
1701 else {
1702 $dataEntry[] = new htmlOutputText('');
1703 }
1704 }
1705 $data[] = $dataEntry;
1706 }
1707 $table = new htmlResponsiveTable($titles, $data);
1708 $table->setCSSClasses(['colored--table']);
1709 $row->add($table);
1710 ob_start();
1711 parseHtml(null, $row, [], false);
1712 $content = ob_get_contents();
1713 ob_end_clean();
1714 return json_encode(['content' => $content]);
1715 }
1716
1717 /**
1718 * Performs paste operations.
1719 *
1720 * @param string $dn DN to paste
1721 * @return string JSON data
1722 */
1723 private function paste(string $dn): string {
1724 $targetDn = base64_decode($_POST['targetDn']);
1725 $this->validateDn($targetDn);
1726 $action = $_POST['action'];
1727 if (!in_array($action, ['COPY', 'CUT'])) {
1728 logNewMessage(LOG_ERR, 'Invalid tree paste action: ' . $action);
1729 die();
1730 }
1731 try {
1732 if (strtolower($dn) === strtolower($targetDn)) {
1733 throw new LAMException(_('Entry cannot be inserted into itself.'));
1734 }
1735 $entryAndChildren = ldapListDN($dn);
1736 $childrenCount = count($entryAndChildren);
1737 logNewMessage(LOG_DEBUG, 'Paste operation for entry with ' . $childrenCount . ' child entries.');
1738 if (($childrenCount === 0) && ($action === 'CUT')) {
1739 // do LDAP move for entries without children and CUT operation
1740 moveDn($dn, $targetDn);
1741 return json_encode([]);
1742 }
1743 copyDnRecursive($dn, $targetDn);
1744 if ($action === 'CUT') {
1745 $errors = deleteDN($dn, true);
1746 if (!empty($errors)) {
1747 $row = new htmlResponsiveRow();
1748 foreach ($errors as $error) {
1749 $row->add(new htmlStatusMessage($error[0], $error[1], $error[2] ?? null));
1750 }
1751 ob_start();
1752 parseHtml(null, $row, [], false);
1753 $content = ob_get_contents();
1754 ob_end_clean();
1755 return json_encode(['error' => $content]);
1756 }
1757 }
1758 }
1759 catch (LAMException $e) {
1760 $message = new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
1761 ob_start();
1762 parseHtml(null, $message, [], false);
1763 $content = ob_get_contents();
1764 ob_end_clean();
1765 return json_encode(['error' => $content]);
1766 }
1767 return json_encode([]);
1768 }
1769
1770 /**
1771 * Starts the DN comparison.
1772 *
1773 * @return string JSON data
1774 */
1775 private function compare(): string {
1776 $dnListToCheck = explode(',', $_POST['dnList']);
1777 $dnList = [];
1778 foreach ($dnListToCheck as $dn) {
1779 $dn = base64_decode($dn);
1780 if ($this->validateDn($dn, false)) {
1781 $dnList[] = $dn;
1782 }
1783 }
1784 natcasesort($dnList);
1785 try {
1786 $row = new htmlResponsiveRow();
1787 $row->add(new htmlTitle(_('Comparison')));
1788 $attributeData = [];
1789 foreach ($dnList as $dn) {
1790 $attributes = ldapGetDN($dn, ['*']);
1791 unset($attributes['dn']);
1792 $attributeData[$dn] = $attributes;
1793 }
1794 $this->addCompareArea($row, $attributeData, _('Attributes'), true);
1795 $attributeData = [];
1796 foreach ($dnList as $dn) {
1797 $attributes = ldapGetDN($dn, ['+', 'creatorsName', 'createTimestamp', 'modifiersName',
1798 'modifyTimestamp', 'hasSubordinates', 'pwdChangedTime', 'passwordRetryCount', 'accountUnlockTime', 'nsAccountLock',
1799 'nsRoleDN', 'passwordExpirationTime']);
1800 unset($attributes['dn']);
1801 $attributeData[$dn] = $attributes;
1802 }
1803 $this->addCompareArea($row, $attributeData, _('Internal attributes'), false);
1804 ob_start();
1805 parseHtml(null, $row, [], false);
1806 $content = ob_get_contents();
1807 ob_end_clean();
1808 return json_encode(['content' => $content]);
1809 }
1810 catch (LAMException $e) {
1811 logNewMessage(LOG_ERR, $e->getMessage());
1812 $message = new htmlStatusMessage('ERROR', _('Comparison failed'));
1813 ob_start();
1814 parseHtml(null, $message, [], false);
1815 $content = ob_get_contents();
1816 ob_end_clean();
1817 return json_encode(['content' => $content]);
1818 }
1819 }
1820
1821 /**
1822 * Adds a comparison area.
1823 *
1824 * @param htmlResponsiveRow $row row
1825 * @param array<string, array<string, string[]|string>> $attributeData dn => attributes
1826 * @param string $title table title
1827 * @param bool $showActions show action icons
1828 */
1829 private function addCompareArea(htmlResponsiveRow $row, array $attributeData, string $title, bool $showActions): void {
1830 $attributeNames = [];
1831 $labels = [];
1832 foreach ($attributeData as $dn => $data) {
1833 $attributeNames = array_merge($attributeNames, array_keys($data));
1834 $labels[] = $dn;
1835 }
1836 array_unshift($labels, _('Attribute'));
1837 $attributeNames = array_values(array_unique($attributeNames));
1838 natcasesort($attributeNames);
1839 $data = [];
1840 $differentValueIndexes = [];
1841 $schemaAttributes = $this->getSchemaAttributes();
1842 for ($i = 0; $i < count($attributeNames); $i++) {
1843 $attributeName = $attributeNames[$i];
1844 $dataEntry = [new htmlOutputText($this->getProperAttributeName($attributeName))];
1845 $allValues = [];
1846 foreach ($attributeData as $singleData) {
1847 $schemaAttribute = $schemaAttributes[$attributeName] ?? null;
1848 $attributeNameSchema = ($schemaAttribute === null) ? $attributeName : $schemaAttribute->getName();
1849 $values = $singleData[$attributeName] ?? [''];
1850 $isMultiValue = $this->isMultiValueAttribute($values, $schemaAttribute);
1851 $isMultiLine = $this->isMultiLineAttribute($attributeName, $schemaAttribute);
1852 $dataEntry[] = $this->getAttributeContentField($attributeNameSchema, $values, false, $isMultiValue, $isMultiLine, $schemaAttribute, true);
1853 $allValues[] = implode(', ', $values);
1854 }
1855 $data[] = $dataEntry;
1856 $allValues = array_unique($allValues);
1857 if (count($allValues) > 1) {
1858 $differentValueIndexes[] = $i;
1859 }
1860 }
1861 if ($showActions) {
1862 $actionsRow = [new htmlOutputText('')];
1863 foreach (array_keys($attributeData) as $dn) {
1864 $buttonClasses = ['clickable', 'lam-margin-small', 'icon'];
1865 $removeFromComparisonButton = new htmlImage('../../graphics/list-remove.svg', '16px', '16px', _('Remove from comparison'), _('Remove from comparison'));
1866 if (count($attributeData) > 2) {
1867 $removeFromComparisonButton->setOnClick('window.lam.treeview.removeFromComparison(\'' . base64_encode($dn) . '\'); window.lam.treeview.openComparison(\'' . getSecurityTokenName() . '\', '
1868 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
1869 }
1870 else {
1871 $removeFromComparisonButton->setOnClick('window.lam.treeview.removeFromComparison(\'' . base64_encode($dn) . '\'); window.lam.treeview.getNodeContent(\'' . getSecurityTokenName() . '\', '
1872 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
1873 }
1874 $removeFromComparisonButton->setCSSClasses($buttonClasses);
1875 $linkButton = new htmlImage('../../graphics/link.svg', '16px', '16px', _('Open entry'), _('Open entry'));
1876 $linkButton->setOnClick('window.lam.treeview.getNodeContent(\'' . getSecurityTokenName() . '\', '
1877 . '\'' . getSecurityTokenValue() . '\', \'' . base64_encode($dn) . '\');');
1878 $linkButton->setCSSClasses($buttonClasses);
1879 $actionsGroup = new htmlGroup();
1880 $actionsGroup->addElement($removeFromComparisonButton);
1881 $actionsGroup->addElement($linkButton);
1882 $actionsRow[] = $actionsGroup;
1883 }
1884 $data[] = $actionsRow;
1885 }
1886 $attributeTable = new htmlResponsiveTable($labels, $data, $differentValueIndexes);
1887 $attributeTable->setCSSClasses(['colored--table', 'no-wrap-first-column']);
1888 $row->add(new htmlSubTitle($title));
1889 $row->add($attributeTable);
1890 }
1891
1892 /**
1893 * Returns if the attribute should be rendered multi-line even if it is single-line defined in schema.
1894 *
1895 * @param string $attributeName attribute name
1896 * @return bool render multi-line
1897 */
1898 private function isPseudoMultiLine(string $attributeName): bool {
1899 return ($attributeName === 'olcaccess');
1900 }
1901
1902 /**
1903 * Preprocesses the value before rendering.
1904 *
1905 * @param string $attributeName attribute name
1906 * @param string $value value
1907 * @return string preprocessed value
1908 */
1909 private function preProcessValue(string $attributeName, string $value): string {
1910 if ($attributeName === 'olcaccess') {
1911 return preg_replace('/\s+by\s+/', "\r\nby ", $value);
1912 }
1913 return $value;
1914 }
1915
1916 }
1917
1918 /**
1919 * Compares two nodes by interpreting their ID as DN.
1920 *
1921 * @param array<string, string> $a first node
1922 * @param array<string, string> $b second node
1923 * @return int result
1924 */
1925 function compareNodeByIdAsDn($a, $b): int {
1926 return strnatcasecmp(extractRDN(base64_decode($a['key'])), extractRDN(base64_decode($b['key'])));
1927 }
1928
1929 /**
1930 * Compares two arrays with LDAP attributes by global $lamOrderByAttribute.
1931 *
1932 * @param array<string, string[]|string> $a first node
1933 * @param array<string, string[]|string> $b second node
1934 * @return int result
1935 */
1936 function compareByAttributes($a, $b): int {
1937 global $lamOrderByAttribute;
1938 if ($lamOrderByAttribute === 'dn') {
1939 return compareDN($a['dn'], $b['dn']);
1940 }
1941 $a = array_change_key_case($a);
1942 $b = array_change_key_case($b);
1943 if (!isset($a[$lamOrderByAttribute]) && !isset($b[$lamOrderByAttribute])) {
1944 return 0;
1945 }
1946 if (!empty($a[$lamOrderByAttribute]) && empty($b[$lamOrderByAttribute])) {
1947 return 1;
1948 }
1949 if (empty($a[$lamOrderByAttribute]) && !empty($b[$lamOrderByAttribute])) {
1950 return -1;
1951 }
1952 natcasesort($a[$lamOrderByAttribute]);
1953 natcasesort($b[$lamOrderByAttribute]);
1954 $maxA = array_pop($a[$lamOrderByAttribute]);
1955 $maxB = array_pop($b[$lamOrderByAttribute]);
1956 return strnatcasecmp($maxA, $maxB);
1957 }