Debian Codegraph @

templates/lib/500_lam.js

raw
1 /**
2
3 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
4 Copyright (C) 2003 - 2026 Roland Gruber
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 */
21
22 window.lam = window.lam || {};
23
24 /**
25 * Called when user clicks on a table row. This toggles the checkbox in the row.
26 *
27 * @param box checkbox name
28 */
29 function list_click(box) {
30 var cbox = document.getElementsByName(box)[0];
31 cbox.checked = !cbox.checked;
32 }
33
34 /**
35 * The user changed the value in the OU selection box. This will reload the list view with the new suffix.
36 *
37 * @param type account type
38 * @param element dropdown box
39 */
40 function listOUchanged(type, element) {
41 location.href='list.php?type=' + type + '&suffix=' + element.options[element.selectedIndex].value;
42 }
43
44 /**
45 * The user pressed a key in the page number box. On enter this will reload the list view with the new page.
46 *
47 * @param url target URL
48 * @param e event
49 */
50 function listPageNumberKeyPress(url, e) {
51 const pageNumber = document.getElementById('listNavPage').value;
52 if (e.key === 'Enter') {
53 if (e.preventDefault) {
54 e.preventDefault();
55 }
56 location.href = url + '&page=' + encodeURIComponent(pageNumber);
57 return false;
58 }
59 return true;
60 }
61
62 window.lam.accountLists = window.lam.accountLists || {};
63
64 /**
65 * Shows the dialog to change the list settings.
66 *
67 * @param title dialog title
68 * @param okText text for Ok button
69 * @param cancelText text for Cancel button
70 */
71 window.lam.accountLists.listShowSettingsDialog = function (title, okText, cancelText) {
72 const dialogContent = document.getElementById('settingsDialog').cloneNode(true);
73 dialogContent.classList.remove('hidden');
74 dialogContent.firstElementChild.id = 'settingsDialogForm_dlg';
75 Swal.fire({
76 title: title,
77 confirmButtonText: okText,
78 cancelButtonText: cancelText,
79 showCancelButton: true,
80 html: dialogContent.outerHTML,
81 width: '48em'
82 }).then(result => {
83 if (result.isConfirmed) {
84 document.forms["settingsDialogForm_dlg"].submit();
85 }
86 });
87 }
88
89 /**
90 * Executed when radio buttons change for (un)locking accounts.
91 */
92 window.lam.accountLists.lockUnlockRadioChange = function () {
93 if (document.querySelector('#lam_accountStatusAction0:checked')) {
94 document.getElementById('lam_accountStatusDialogLockDiv').classList.remove('hidden');
95 document.getElementById('lam_accountStatusDialogUnlockDiv').classList.add('hidden');
96 }
97 else {
98 document.getElementById('lam_accountStatusDialogLockDiv').classList.add('hidden');
99 document.getElementById('lam_accountStatusDialogUnlockDiv').classList.remove('hidden');
100 }
101 }
102
103 /**
104 * Submits the form by clicking on the given button if enter was pressed.
105 * Example: SubmitForm('apply_filter', event);
106 *
107 * @param id button ID
108 * @param e event
109 * @returns Boolean result
110 */
111 function SubmitForm(id, e) {
112 if (e.key === 'Enter') {
113 if (e.preventDefault) {
114 e.preventDefault();
115 }
116 if (e.returnValue) {
117 e.returnValue = false;
118 }
119 if (window.lam_lastKey) {
120 // no submit if last key code was arrow key (browser autocompletion)
121 if (window.lam_lastKey === 'ArrowUp' || window.lam_lastKey === 'ArrowDown' ||
122 window.lam_lastKey === 'PageUp' || window.lam_lastKey === 'PageDown'
123 ) {
124 window.lam_lastKey = e.key;
125 return true;
126 }
127 }
128 document.getElementsByName(id)[0].click();
129 return false;
130 }
131 window.lam_lastKey = e.key;
132 return true;
133 }
134
135 /**
136 * Selects/deselects all accounts on the page.
137 */
138 function list_switchAccountSelection() {
139 // set checkbox selection
140 document.querySelectorAll('input.accountBoxUnchecked').forEach(item => {
141 item.checked = true;
142 });
143 document.querySelectorAll('input.accountBoxChecked').forEach(item => {
144 item.checked = false;
145 });
146 // switch CSS class
147 const nowChecked = document.querySelectorAll('input.accountBoxUnchecked');
148 const nowUnchecked = document.querySelectorAll('input.accountBoxChecked');
149 nowChecked.forEach(item => {
150 item.classList.add('accountBoxChecked');
151 item.classList.remove('accountBoxUnchecked');
152 });
153 nowUnchecked.forEach(item => {
154 item.classList.remove('accountBoxChecked');
155 item.classList.add('accountBoxUnchecked');
156 });
157 }
158
159 /**
160 * The user changed the value in the profile selection box. This will reload the login page with the new profile.
161 *
162 * @param element dropdown box
163 */
164 function loginProfileChanged(element) {
165 location.href='login.php?useProfile=' + element.options[element.selectedIndex].value;
166 }
167
168 /**
169 * Shows the dialog to delete a profile.
170 *
171 * @param title dialog title
172 * @param okText text for Ok button
173 * @param cancelText text for Cancel button
174 * @param scope account type (e.g. user)
175 * @param selectFieldName name of select box with profile name
176 */
177 function profileShowDeleteDialog(title, okText, cancelText, scope, selectFieldName) {
178 // get profile name
179 const profileName = document.getElementsByName(selectFieldName)[0].value;
180 // update text
181 document.getElementById('deleteText').textContent = profileName;
182 // update hidden input fields
183 document.getElementById('profileDeleteType').value = scope;
184 document.getElementById('profileDeleteName').value = profileName;
185 const dialogContent = document.getElementById('deleteProfileDialog').cloneNode(true);
186 dialogContent.classList.remove('hidden');
187 dialogContent.firstElementChild.id = 'deleteProfileDialog_dlg';
188 Swal.fire({
189 title: title,
190 confirmButtonText: okText,
191 cancelButtonText: cancelText,
192 showCancelButton: true,
193 html: dialogContent.outerHTML,
194 width: '48em'
195 }).then(result => {
196 if (result.isConfirmed) {
197 document.forms["deleteProfileDialog_dlg"].submit();
198 }
199 });
200 }
201
202 /**
203 * Manages the password change when a button is pressed.
204 *
205 * @param random "true" if random password should be generated
206 * @param ajaxURL URL used for AJAX request
207 * @param tokenName name of CSRF token
208 * @param tokenValue value of CSRF token
209 * @param okText text for ok button
210 */
211 function passwordHandleInput(random, ajaxURL, tokenName, tokenValue, okText) {
212 // get input values
213 let modules = new Array();
214 const passwordDialog = document.getElementById('passwordDialog');
215 passwordDialog.querySelectorAll(':checked').forEach(item => {
216 modules.push(item.name);
217 });
218 const pwd1 = passwordDialog.querySelector('[name=newPassword1]').value;
219 const pwd2 = passwordDialog.querySelector('[name=newPassword2]').value;
220 let forcePasswordChange = false;
221 const lamForcePasswordChangeBox = passwordDialog.querySelector('input[name=lamForcePasswordChange]');
222 if (lamForcePasswordChangeBox && lamForcePasswordChangeBox.checked) {
223 forcePasswordChange = true;
224 }
225 let sendMail = false;
226 const lamPasswordChangeSendMailBox = passwordDialog.querySelector('input[name=lamPasswordChangeSendMail]');
227 if (lamPasswordChangeSendMailBox && lamPasswordChangeSendMailBox.checked) {
228 sendMail = true;
229 }
230 let sendSms = false;
231 const lamPasswordChangeSendSmsBox = passwordDialog.querySelector('input[name=lamPasswordChangeSendSms]');
232 if (lamPasswordChangeSendSmsBox && lamPasswordChangeSendSmsBox.checked) {
233 sendSms = true;
234 }
235
236 let sendMailAlternateAddress = '';
237 const lamPasswordChangeMailAddress = passwordDialog.querySelector('[name=lamPasswordChangeMailAddress]');
238 if (lamPasswordChangeMailAddress) {
239 sendMailAlternateAddress = lamPasswordChangeMailAddress.value;
240 }
241 const pwdJSON = {
242 "modules": modules,
243 "password1": pwd1,
244 "password2": pwd2,
245 "random": random,
246 "forcePasswordChange": forcePasswordChange,
247 "sendMail": sendMail,
248 "sendSms": sendSms,
249 "sendMailAlternateAddress": sendMailAlternateAddress
250 };
251 let data = new FormData();
252 data.append('jsonInput', JSON.stringify(pwdJSON));
253 data.append(tokenName, tokenValue);
254 // make AJAX call
255 fetch(ajaxURL, {
256 method: 'POST',
257 body: data
258 })
259 .then(async response => {
260 const jsonData = await response.json();
261 document.querySelector(".modal").classList.remove("show-modal");
262 Swal.fire({
263 confirmButtonText: okText,
264 html: jsonData.messages
265 });
266 });
267 }
268
269 /**
270 * Appends the input fields of a dialog back to the form and submits it.
271 *
272 * @param dialogDiv ID of dialog div
273 * @param formName name of form
274 */
275 function appendDialogInputsToFormAndSubmit(dialogDiv, formName) {
276 const inputFields = document.getElementById(dialogDiv).querySelectorAll('input');
277 inputFields.forEach(item => {
278 item.classList.add('hidden');
279 document.forms[formName].append(item);
280 });
281 document.forms[formName].submit();
282 }
283
284 /**
285 * Shows a simple confirmation dialog.
286 * If the user presses Cancel then the current action is stopped (event.preventDefault()).
287 *
288 * @param title dialog title
289 * @param text dialog text
290 * @param okText text for OK button
291 * @param cancelText text for cancel button
292 * @param e event
293 */
294 async function confirmLoadProfile(title, text, okText, cancelText, e) {
295 const button = document.getElementById('btn_accountContainerLoadProfileButton');
296 const lastProfile = button.dataset.lastprofile;
297 const profiles = JSON.parse(button.dataset.profiles);
298 const {value: selectedProfile} = await Swal.fire({
299 confirmButtonText: okText,
300 cancelButtonText: cancelText,
301 showCancelButton: true,
302 title: title,
303 text: text,
304 input: 'select',
305 inputValue: lastProfile,
306 inputOptions: profiles
307 });
308 if (selectedProfile) {
309 const form = document.forms["inputForm"];
310 let buttonValue = document.createElement("input");
311 buttonValue.type = "hidden";
312 buttonValue.name = "accountContainerLoadProfile";
313 buttonValue.value = "yes";
314 form.appendChild(buttonValue);
315 let selectValue = document.createElement('input');
316 selectValue.type = 'hidden';
317 selectValue.name = 'accountContainerSelectLoadProfile';
318 selectValue.value = selectedProfile;
319 form.appendChild(selectValue);
320 form.submit();
321 }
322 if (e.preventDefault) {
323 e.preventDefault();
324 }
325 if (e.returnValue) {
326 e.returnValue = false;
327 }
328 return false;
329 }
330
331 window.lam.profilePdfEditor = window.lam.profilePdfEditor || {};
332
333 /**
334 * Shows the dialog to import/export account/PDF profiles.
335 *
336 * @param title dialog title
337 * @param okText text for Ok button
338 * @param cancelText text for Cancel button
339 * @param typeId account type
340 * @param selectFieldName name of select box with profile name
341 */
342 window.lam.profilePdfEditor.showDistributionDialog = function(title, okText, cancelText, typeId, type, selectFieldName) {
343 // show dialog
344 let dialogId = '';
345 let formId = '';
346 if (type == 'export') {
347 document.getElementById('name_' + typeId).value = document.getElementById(selectFieldName).value;
348 dialogId = 'exportDialog_' + typeId;
349 formId = "exportDialogForm_" + typeId;
350 } else if (type == 'import') {
351 dialogId = 'importDialog_' + typeId;
352 formId = "importDialogForm_" + typeId;
353 }
354 const dialogContent = document.getElementById(dialogId).cloneNode(true);
355 dialogContent.classList.remove('hidden');
356 dialogContent.firstElementChild.id = formId + '_dlg';
357 Swal.fire({
358 title: title,
359 confirmButtonText: okText,
360 cancelButtonText: cancelText,
361 showCancelButton: true,
362 html: dialogContent.outerHTML,
363 width: 'auto'
364 }).then(result => {
365 if (result.isConfirmed) {
366 document.forms[formId + "_dlg"].submit();
367 }
368 });
369 }
370
371 /**
372 * Shows the dialog to export PDF logos.
373 *
374 * @param title dialog title
375 * @param okText text for Ok button
376 * @param cancelText text for Cancel button
377 */
378 window.lam.profilePdfEditor.showPdfLogoExportDialog = function(title, okText, cancelText) {
379 var selectedLogo = document.getElementById('logo').value;
380 document.getElementById('exportLogoName').value = selectedLogo;
381 window.lam.dialog.showSimpleDialog(title, okText, cancelText, 'logoExportForm', 'logoExportDiv');
382 }
383
384 /**
385 * Shows the dialog to import PDF logos.
386 *
387 * @param title dialog title
388 * @param okText text for Ok button
389 * @param cancelText text for Cancel button
390 */
391 window.lam.profilePdfEditor.showPdfLogoImportDialog = function(title, okText, cancelText) {
392 window.lam.dialog.showSimpleDialog(title, okText, cancelText, 'logoImportForm', 'logoImportDiv');
393 }
394
395 /**
396 * Shows the dialog to create a DNS zone.
397 *
398 * @param title dialog title
399 * @param okText text for Ok button
400 * @param cancelText text for Cancel button
401 */
402 function bindShowNewZoneDialog(title, okText, cancelText) {
403 window.lam.dialog.showSimpleDialog(title, okText, cancelText, 'newBindZoneDialogForm', 'newBindZoneDialog');
404 }
405
406
407 /**
408 * Checks if the given field has the same value as the reference field.
409 * Field is marked red if different and green if equal.
410 *
411 * @param fieldID ID of field to check
412 * @param fieldIDReference ID of reference field
413 */
414 function checkFieldsHaveSameValues(fieldID, fieldIDReference) {
415 const field = document.getElementById(fieldID);
416 const fieldRef = document.getElementById(fieldIDReference);
417 const check =
418 function() {
419 const value = field.value;
420 const valueRef = fieldRef.value;
421 if ((value == '') && (valueRef == '')) {
422 field.classList.remove('markFail');
423 field.classList.remove('markOk');
424 }
425 else {
426 if (value == valueRef) {
427 field.classList.remove('markFail');
428 field.classList.add('markOk');
429 }
430 else {
431 field.classList.add('markFail');
432 field.classList.remove('markOk');
433 }
434 }
435 };
436 field.addEventListener('keyup', check);
437 fieldRef.addEventListener('keyup', check);
438 }
439
440 /**
441 * Checks if the value of the given password field matches LAM's password policy.
442 * Field is marked red if fail and green if ok.
443 *
444 * @param fieldID ID of field to check
445 * @param tokenName name of CSRF token
446 * @param tokenValue value of CSRF token
447 */
448 function checkPasswordStrength(fieldID, ajaxURL, tokenName, tokenValue) {
449 const field = document.getElementById(fieldID);
450 const check =
451 function() {
452 const value = field.value;
453 const pwdJSON = {
454 "password": value
455 };
456 let data = new FormData();
457 data.append('jsonInput', JSON.stringify(pwdJSON));
458 data.append(tokenName, tokenValue);
459 // make AJAX call
460 fetch(ajaxURL + "&function=passwordStrengthCheck", {
461 method: 'POST',
462 body: data
463 })
464 .then(async response => {
465 const jsonData = await response.json();
466 checkPasswordStrengthHandleReply(jsonData, fieldID);
467 });
468 };
469 field.addEventListener('keyup', check);
470 }
471
472 /**
473 * Manages the server reply to a password strength check request.
474 *
475 * @param data JSON reply
476 * @param fieldID input field ID
477 */
478 function checkPasswordStrengthHandleReply(data, fieldID) {
479 const field = document.getElementById(fieldID);
480 if (data.result === true) {
481 field.classList.remove('markFail');
482 field.classList.add('markOk');
483 field.title = '';
484 }
485 else if (field.value === '') {
486 field.classList.remove('markFail');
487 field.classList.remove('markOk');
488 }
489 else {
490 field.classList.add('markFail');
491 field.classList.remove('markOk');
492 field.title = data.message;
493 }
494 const issuesDiv = document.getElementById(fieldID + '-pwd-strength-issues');
495 issuesDiv.innerHTML = '';
496 if (field.value !== '') {
497 data.issues.forEach(issue => {
498 const line = document.createElement('p');
499 line.classList.add('password-strength');
500 line.classList.add('password-strength-fail');
501 line.innerText = issue;
502 issuesDiv.appendChild(line);
503 });
504 }
505 }
506
507 /**
508 * Updates the positions of a htmlSortable list in a hidden input field.
509 * The positions must be separated by comma (e.g. "0,1,2,3").
510 *
511 * @param inputId HTML ID of hidden input field
512 * @param containerId HTML ID of ul-container
513 */
514 function updateModulePositions(inputId, containerId) {
515 const input = document.getElementById(inputId);
516 let positions = [];
517 const container = document.getElementById(containerId);
518 const childLiElements = container.children;
519 for (let i = 0; i < childLiElements.length; i++) {
520 positions[i] = childLiElements[i].getAttribute('data-position-orig');
521 }
522 input.value = positions.join(',');
523 }
524
525 window.lam.filterSelect = window.lam.filterSelect || {};
526
527 /**
528 * Filters a select box by the value of the filter input field.
529 *
530 * @param filterInput ID of input field for filter
531 * @param select ID of select box to filter
532 * @param event key event
533 */
534 window.lam.filterSelect.activate = function (filterInput, select, event) {
535 const inputField = document.getElementById(filterInput);
536 const selectField = document.getElementById(select);
537 if (selectField.classList.contains('lam-dynamicOptions')) {
538 window.lam.filterSelect.filterDynamic(inputField, selectField);
539 }
540 else {
541 window.lam.filterSelect.filterStandard(inputField, selectField);
542 }
543 }
544
545 /**
546 * Filters a normal select field.
547 *
548 * @param inputField input field with filter value
549 * @param selectField select field
550 */
551 window.lam.filterSelect.filterStandard = function(inputField, selectField) {
552 selectField.classList.add('lam-filteredOptions');
553 // if values were not yet saved, save them
554 if (!selectField.dataset.options) {
555 let options = {};
556 selectField.querySelectorAll('option').forEach((item) => {
557 options[item.value] = {
558 selected: item.selected,
559 text: item.innerText,
560 cssClasses: item.classList
561 };
562 });
563 selectField.dataset.options = JSON.stringify(options);
564 }
565 // save selected values
566 let storedOptions = JSON.parse(selectField.dataset.options);
567 selectField.querySelectorAll('option').forEach((item) => {
568 storedOptions[item.value].selected = item.selected;
569 });
570 selectField.dataset.options = JSON.stringify(storedOptions);
571 // get matching values
572 selectField.innerHTML = '';
573 let search = inputField.value.trim();
574 search = search.replace('*', '.*');
575 const regex = new RegExp(search,'gi');
576 let index = 0;
577 for (const value in storedOptions) {
578 const option = storedOptions[value];
579 if (option.text.match(regex) !== null) {
580 const newOption = document.createElement('option');
581 newOption.innerText = option.text;
582 newOption.value = value;
583 if (option.selected) {
584 newOption.selected = true;
585 if (selectField.size === 1) {
586 selectField.selectedIndex = index;
587 }
588 }
589 if (option.cssClasses) {
590 newOption.classList = option.cssClasses;
591 }
592 selectField.appendChild(newOption);
593 }
594 index++;
595 }
596 // select first entry for single-selects
597 if ((selectField.size === 1) && selectField.onchange) {
598 selectField.onchange();
599 }
600 }
601
602 /**
603 * Adds a form listener to clear the filter on select elements.
604 */
605 window.lam.filterSelect.addFormListener = function() {
606 const forms = Array.from(document.forms);
607 forms.forEach((form) => {
608 form.addEventListener('submit', function () {
609 const selectFields = form.querySelectorAll('.lam-filteredOptions[multiple]');
610 selectFields.forEach((item) => {
611
612 const storedOptions = JSON.parse(item.dataset.options);
613 item.querySelectorAll('option').forEach((optionItem) => {
614 storedOptions[optionItem.value].selected = optionItem.selected;
615 });
616 item.innerHTML = '';
617 for (const value in storedOptions) {
618 const option = storedOptions[value];
619 if (option.selected) {
620 const newOption = document.createElement('option');
621 newOption.innerText = option.text;
622 newOption.value = value;
623 newOption.selected = true;
624 item.appendChild(newOption);
625 }
626 }
627 });
628 })
629 });
630 }
631
632 /**
633 * Filters a select field with dynamic scrolling.
634 *
635 * @param inputField input field with filter value
636 * @param selectField select field
637 */
638 window.lam.filterSelect.filterDynamic = function(inputField, selectField) {
639 let optionsOrig = selectField.dataset.dynamicOptionsOrig;
640 if (optionsOrig === undefined) {
641 selectField.dataset.dynamicOptionsOrig = selectField.dataset.dynamicOptions;
642 optionsOrig = selectField.dataset.dynamicOptionsOrig;
643 }
644 optionsOrig = JSON.parse(optionsOrig);
645 const currentOptions = JSON.parse(selectField.dataset.dynamicOptions);
646 // save selection
647 const optionTags = Array.from(selectField.children);
648 optionTags.forEach((element) => {
649 const index = currentOptions[parseInt(element.dataset.index)].index;
650 optionsOrig[index].selected = element.selected;
651 });
652 selectField.dataset.dynamicOptionsOrig = JSON.stringify(optionsOrig);
653 selectField.innerHTML = '';
654 const newOptions = [];
655 // get matching values
656 let search = inputField.value.trim();
657 search = search.replace('*', '.*');
658 const regex = new RegExp(search,'gi');
659 optionsOrig.forEach(function(option, i) {
660 if(option.label.match(regex) !== null) {
661 newOptions.push(option);
662 }
663 });
664 selectField.dataset.dynamicOptions = JSON.stringify(newOptions);
665 selectField.append(window.lam.dynamicSelect.createOption('#', 0));
666 window.lam.dynamicSelect.initSelect(selectField);
667 }
668
669 window.lam.dynamicSelect = window.lam.dynamicSelect || {};
670
671 /**
672 * Activates dynamic selection for all marked select fields.
673 */
674 window.lam.dynamicSelect.activate = function() {
675 const dynamicSelects = document.querySelectorAll('.lam-dynamicOptions');
676 dynamicSelects.forEach(item => {
677 window.lam.dynamicSelect.initSelect(item);
678 });
679 const forms = Array.from(document.forms);
680 forms.forEach((form) => {
681 form.addEventListener('submit', function () {
682 window.lam.dynamicSelect.formListener(form);
683 })
684 });
685 }
686
687 /**
688 * Restores the right values before submitting a form.
689 *
690 * @param form HTMLFormElement
691 */
692 window.lam.dynamicSelect.formListener = function(form) {
693 form.querySelectorAll('.lam-dynamicOptions').forEach(select => {
694 let dynamicOptions = select.dataset.dynamicOptions;
695 if (select.dataset.dynamicOptionsOrig) {
696 dynamicOptions = select.dataset.dynamicOptionsOrig;
697 }
698 dynamicOptions = JSON.parse(dynamicOptions);
699 if (select.dataset.dynamicOptionsOrig) {
700 // restore selections if list was filtered and selection was removed due to scrolling
701 const dynamicOptionsOld = JSON.parse(select.dataset.dynamicOptions);
702 for (const dynamicOptionOld of dynamicOptionsOld) {
703 dynamicOptions[dynamicOptionOld.index].selected = dynamicOptionOld.selected;
704 }
705 }
706 const children = Array.from(select.children);
707 children.forEach((option) => {
708 // get selection state from currently displayed options
709 dynamicOptions[parseInt(option.dataset.index)].selected = option.selected;
710 });
711 select.innerHTML = '';
712 dynamicOptions.forEach((item) => {
713 if (item.selected) {
714 select.appendChild(window.lam.dynamicSelect.createOption(item, item.index));
715 }
716 });
717 });
718 }
719
720 /**
721 * Sets up a select field for dynamic scrolling.
722 *
723 * @param selectField select
724 */
725 window.lam.dynamicSelect.initSelect = function(selectField) {
726 const optionTag = selectField.querySelector("option");
727 if (optionTag) {
728 selectField.dataset.optionHeight = optionTag.clientHeight;
729 }
730 else {
731 selectField.dataset.optionHeight = 10;
732 }
733 selectField.dataset.selectHeight = selectField.clientHeight;
734 selectField.dataset.selectLastScrollTop = '0';
735 selectField.dataset.selectCurrentScroll = '0';
736 selectField.innerHTML = '';
737 const options = JSON.parse(selectField.dataset.dynamicOptions);
738 const maxOptions = 3000;
739 const numOfOptionBeforeToLoadNextSet = 10;
740 const numberOfOptionsToLoad = 200;
741 for (let i = 0; (i < maxOptions) && (i < options.length); i++) {
742 selectField.append(window.lam.dynamicSelect.createOption(options[i], options[i].index));
743 }
744 if (options.length > maxOptions) {
745 // activate scrolling logic only if enough options are set
746 selectField.onscroll = function() {
747 window.lam.dynamicSelect.onScroll(selectField, maxOptions, numOfOptionBeforeToLoadNextSet, numberOfOptionsToLoad);
748 };
749 }
750 }
751
752 /**
753 * Creates an option field inside the select.
754 *
755 * @param data option data
756 * @param index index in list of all options
757 * @returns HTMLOptionElement
758 */
759 window.lam.dynamicSelect.createOption = function(data, index) {
760 const newOption = document.createElement("option");
761 newOption.setAttribute('value', data.value);
762 newOption.dataset.index = index;
763 newOption.textContent = data.label;
764 if (data.selected) {
765 newOption.selected = true;
766 }
767 return newOption;
768 }
769
770 /**
771 * Onscroll event.
772 *
773 * @param selectField select field
774 * @param maxOptions maximum options to show
775 * @param numOfOptionBeforeToLoadNextSet number of options to reach before end of list
776 * @param numberOfOptionsToLoad number of options to add
777 */
778 window.lam.dynamicSelect.onScroll = function(selectField, maxOptions, numOfOptionBeforeToLoadNextSet, numberOfOptionsToLoad) {
779 const scrollTop = selectField.scrollTop;
780 const totalHeight = selectField.querySelectorAll("option").length * selectField.dataset.optionHeight;
781 const lastScrollTop = parseInt(selectField.dataset.selectLastScrollTop);
782 const selectBoxHeight = parseInt(selectField.dataset.selectHeight);
783 const singleOptionHeight = parseInt(selectField.dataset.optionHeight);
784 const currentScroll = scrollTop + selectBoxHeight;
785 selectField.dataset.selectCurrentScrollTop = scrollTop;
786 if ((scrollTop >= lastScrollTop)
787 && ((currentScroll + (numOfOptionBeforeToLoadNextSet * singleOptionHeight)) >= totalHeight)) {
788 window.lam.dynamicSelect.loadNextOptions(selectField, maxOptions, numberOfOptionsToLoad);
789 }
790 else if ((scrollTop <= lastScrollTop)
791 && ((scrollTop - (numOfOptionBeforeToLoadNextSet * singleOptionHeight)) <= 0)) {
792 window.lam.dynamicSelect.loadPreviousOptions(selectField, maxOptions, numberOfOptionsToLoad);
793 }
794 selectField.dataset.selectLastScrollTop = scrollTop;
795 }
796
797 /**
798 * Loads the next bunch of options at the end.
799 *
800 * @param selectField select field
801 * @param maxOptions maximum options to show
802 * @param numberOfOptionsToLoad number of options to add
803 */
804 window.lam.dynamicSelect.loadNextOptions = function(selectField, maxOptions, numberOfOptionsToLoad) {
805 if (selectField.children.length === 0) {
806 return;
807 }
808 const selectBoxHeight = parseInt(selectField.dataset.selectHeight);
809 const singleOptionHeight = parseInt(selectField.dataset.optionHeight);
810 const currentScrollPosition = parseInt(selectField.dataset.selectCurrentScrollTop) + selectBoxHeight;
811 const options = JSON.parse(selectField.dataset.dynamicOptions);
812 let lastIndex = parseInt(selectField.children[selectField.children.length - 1].dataset.index);
813 for (let i = 0; i < options.length; i++) {
814 if (options[i].index === lastIndex) {
815 lastIndex = i;
816 break;
817 }
818 }
819 for (let toAdd = 0; toAdd < numberOfOptionsToLoad; toAdd++) {
820 const addPos = lastIndex + 1 + toAdd;
821 if (options[addPos] === undefined) {
822 break;
823 }
824 selectField.append(window.lam.dynamicSelect.createOption(options[addPos], options[addPos].index));
825 }
826 const numberOfOptions = selectField.children.length;
827 let toRemove = numberOfOptions - maxOptions;
828 if (toRemove > 0) {
829 for (let i = toRemove; i >= 0; i--) {
830 const optionToRemove = selectField.children[i];
831 const indexToRemove = parseInt(optionToRemove.dataset.index);
832 for (const option of options) {
833 if (option.index === indexToRemove) {
834 option.selected = optionToRemove.selected;
835 }
836 }
837 optionToRemove.remove();
838 }
839 }
840 else {
841 toRemove = 0;
842 }
843 selectField.scrollTop = currentScrollPosition - selectBoxHeight - (toRemove * singleOptionHeight);
844 selectField.dataset.dynamicOptions = JSON.stringify(options);
845 }
846
847 /**
848 * Loads the next bunch of options at the beginning.
849 *
850 * @param selectField select field
851 * @param maxOptions maximum options to show
852 * @param numberOfOptionsToLoad number of options to add
853 */
854 window.lam.dynamicSelect.loadPreviousOptions = function(selectField, maxOptions, numberOfOptionsToLoad) {
855 if (selectField.children.length === 0) {
856 return;
857 }
858 const singleOptionHeight = parseInt(selectField.dataset.optionHeight);
859 const currentScrollPosition = parseInt(selectField.dataset.selectCurrentScrollTop);
860 const options = JSON.parse(selectField.dataset.dynamicOptions);
861 let lastIndex = parseInt(selectField.children[0].dataset.index);
862 for (let i = 0; i < options.length; i++) {
863 if (options[i].index === lastIndex) {
864 lastIndex = i;
865 break;
866 }
867 }
868 let added = 0;
869 for (let toAdd = 0; toAdd < numberOfOptionsToLoad; toAdd++) {
870 const addPos = lastIndex - 1 - toAdd;
871 if (options[addPos] === undefined) {
872 break;
873 }
874 added++;
875 selectField.prepend(window.lam.dynamicSelect.createOption(options[addPos], options[addPos].index));
876 }
877 const numberOfOptions = selectField.children.length;
878 const toRemove = numberOfOptions - maxOptions;
879 if (toRemove > 0) {
880 for (let i = maxOptions; i < selectField.children.length; i++) {
881 const optionToRemove = selectField.children[i];
882 const indexToRemove = parseInt(optionToRemove.dataset.index);
883 for (const option of options) {
884 if (option.index === indexToRemove) {
885 option.selected = optionToRemove.selected;
886 }
887 }
888 optionToRemove.remove();
889 }
890 }
891 selectField.scrollTop = currentScrollPosition + (added * singleOptionHeight);
892 selectField.dataset.dynamicOptions = JSON.stringify(options);
893 }
894
895 window.lam.upload = window.lam.upload || {};
896
897 /**
898 * Toggles the display of selectable modules.
899 *
900 * @param selectBox account type selection
901 */
902 window.lam.upload.changeVisibleModules = function(selectBox) {
903 document.querySelectorAll('div.typeOptions').forEach(item => {
904 item.classList.add('hidden');
905 });
906 document.getElementById(selectBox.options[selectBox.selectedIndex].value).classList.toggle('hidden');
907 }
908
909 /**
910 * Continues a CSV file upload.
911 *
912 * @param url URL where to get status JSON
913 * @param tokenName name of CSRF token
914 * @param tokenValue value of CSRF token
915 */
916 window.lam.upload.continueUpload = function(url, tokenName, tokenValue) {
917 let data = new FormData();
918 data.append(tokenName, tokenValue);
919 fetch(url, {
920 method: 'POST',
921 body: data
922 })
923 .then(async response => {
924 const jsonData = await response.json();
925 if (!jsonData.accountsFinished) {
926 window.lam.upload.printBasicStatus(jsonData);
927 }
928 else if (!jsonData.postActionsFinished) {
929 window.lam.upload.printPostActionStatus(jsonData);
930 }
931 else if (!jsonData.pdfFinished) {
932 window.lam.upload.printPDFStatus(jsonData);
933 }
934 // next call if not finished
935 if (!jsonData.allDone) {
936 window.lam.upload.continueUpload(url, tokenName, tokenValue);
937 }
938 else {
939 window.lam.upload.uploadDone(jsonData);
940 }
941 });
942 };
943
944 /**
945 * Prints the upload status when accounts are still being created.
946 *
947 * @param jsonData status JSON
948 */
949 window.lam.upload.printBasicStatus = function(jsonData) {
950 let htmlOut = '<div class="title">';
951 htmlOut += '<h2 class="titleText">' + jsonData.title + '</h2>';
952 htmlOut += '</div>';
953 htmlOut += window.lam.progressbar.getMarkup('progressbarGeneral');
954 document.getElementById('uploadContent').innerHTML = htmlOut;
955 window.lam.progressbar.setProgress('progressbarGeneral', jsonData.accountsProgress);
956 };
957
958 /**
959 * Prints the upload status when post actions run.
960 *
961 * @param jsonData status JSON
962 */
963 window.lam.upload.printPostActionStatus = function(jsonData) {
964 let htmlOut = '<div class="title">';
965 htmlOut += '<h2 class="titleText">' + jsonData.title + '</h2>';
966 htmlOut += '</div>';
967 htmlOut += window.lam.progressbar.getMarkup('progressbarGeneral');
968 if (jsonData.postActionsTitle) {
969 htmlOut += '<h2>' + jsonData.postActionsTitle + '</h2>';
970 htmlOut += window.lam.progressbar.getMarkup('progressbarPostActions');
971 }
972 document.getElementById('uploadContent').innerHTML = htmlOut;
973 window.lam.progressbar.setProgress('progressbarGeneral', 100);
974 if (jsonData.postActionsTitle) {
975 window.lam.progressbar.setProgress('progressbarPostActions', jsonData.postActionsProgress);
976 }
977 };
978
979 /**
980 * Prints the upload status when PDFs are generated.
981 *
982 * @param jsonData status JSON
983 */
984 window.lam.upload.printPDFStatus = function(jsonData) {
985 let htmlOut = '<div class="title">';
986 htmlOut += '<h2 class="titleText">' + jsonData.title + '</h2>';
987 htmlOut += '</div>';
988 htmlOut += window.lam.progressbar.getMarkup('progressbarGeneral');
989 htmlOut += '<h2>' + jsonData.titlePDF + '</h2>';
990 htmlOut += window.lam.progressbar.getMarkup('progressbarPDF');
991 document.getElementById('uploadContent').innerHTML = htmlOut;
992 window.lam.progressbar.setProgress('progressbarGeneral', 100);
993 window.lam.progressbar.setProgress('progressbarPDF', jsonData.pdfProgress);
994 };
995
996 /**
997 * Upload finished, check for errors.
998 *
999 * @param jsonData status JSON
1000 */
1001 window.lam.upload.uploadDone = function(jsonData) {
1002 if (jsonData.errorHtml) {
1003 let htmlOut = '<div class="subTitle">';
1004 htmlOut += '<h4 class="subTitleText">' + jsonData.titleErrors + '</h4>';
1005 htmlOut += '</div>';
1006 htmlOut += jsonData.errorHtml;
1007 document.getElementById('uploadContent').innerHTML = htmlOut;
1008 }
1009 else {
1010 top.location.href = '../lists/list.php?type=' + jsonData.typeId + '&uploadAllOk';
1011 }
1012 };
1013
1014 window.lam.form = window.lam.form || {};
1015
1016 /**
1017 * Trims all marked input elements on form submission.
1018 */
1019 window.lam.form.autoTrim = function() {
1020 for (let singleForm of document.forms) {
1021 singleForm.addEventListener('submit', function() {
1022 const autoTrimFields = singleForm.querySelectorAll('.lam-autotrim');
1023 autoTrimFields.forEach(item => {
1024 item.value = String(item.value).trim();
1025 });
1026 });
1027 }
1028 };
1029
1030 window.lam.dialog = window.lam.dialog || {};
1031
1032 /**
1033 * Shows a dialog message.
1034 *
1035 * @param text dialog text
1036 * @param okText ok button text
1037 */
1038 window.lam.dialog.showInfo = function(text, okText) {
1039 Swal.fire({
1040 text: text,
1041 confirmButtonText: okText,
1042 width: 'auto'
1043 });
1044 };
1045
1046 /**
1047 * Shows an error dialog.
1048 *
1049 * @param title dialog title
1050 * @param text dialog text
1051 * @param okText ok button text
1052 */
1053 window.lam.dialog.showError = function(title, text, okText) {
1054 Swal.fire({
1055 icon: 'error',
1056 title: title,
1057 text: text,
1058 confirmButtonText: okText,
1059 width: 'auto'
1060 });
1061 };
1062
1063 /**
1064 * Shows a dialog message.
1065 *
1066 * @param title dialog title
1067 * @param okText ok button text
1068 * @param divId DIV id with dialog content
1069 * @param callbackFunction callback function on close (optional)
1070 */
1071 window.lam.dialog.showMessage = function(title, okText, divId, callbackFunction) {
1072 const dialogContent = document.getElementById(divId).cloneNode(true);
1073 dialogContent.classList.remove('hidden');
1074 Swal.fire({
1075 title: title,
1076 confirmButtonText: okText,
1077 html: dialogContent.outerHTML,
1078 width: 'auto'
1079 }).then(result => {
1080 if (callbackFunction) {
1081 callbackFunction();
1082 }
1083 });
1084 };
1085
1086 /**
1087 * Shows a confirmation message.
1088 *
1089 * @param title dialog title
1090 * @param okText ok button text
1091 * @param cancelText cancel button text
1092 * @param divId DIV id with dialog content
1093 * @param callbackFunction callback function (optional, gets result of preConfirmFunction as parameter)
1094 * @param preConfirmFunction preConfirm function (optional)
1095 * @param postDisplayFunction called after dialog gets visible (optional)
1096 */
1097 window.lam.dialog.showConfirmation = async function(title, okText, cancelText, divId, callbackFunction, preConfirmFunction, postDisplayFunction) {
1098 const div = document.getElementById(divId);
1099 const dialogContent = div.cloneNode(true);
1100 const divContent = div.innerHTML;
1101 div.innerHTML = '';
1102 dialogContent.classList.remove('hidden');
1103 let options = {
1104 title: title,
1105 confirmButtonText: okText,
1106 cancelButtonText: cancelText,
1107 showCancelButton: true,
1108 html: dialogContent.outerHTML,
1109 width: 'auto'
1110 };
1111 if (preConfirmFunction) {
1112 options.preConfirm = preConfirmFunction;
1113 }
1114 if (postDisplayFunction) {
1115 options.didOpen = postDisplayFunction;
1116 }
1117 const {value: formValues} = await Swal.fire(options);
1118 if (callbackFunction && formValues) {
1119 callbackFunction(formValues);
1120 }
1121 div.innerHTML = divContent;
1122 };
1123
1124 /**
1125 * Shows a simple dialog.
1126 *
1127 * @param title dialog title
1128 * @param okText text for Ok button (optional, submits form)
1129 * @param cancelText text for Cancel button
1130 * @param formID form ID
1131 * @param dialogDivID ID of div that contains dialog content
1132 */
1133 window.lam.dialog.showSimpleDialog = function(title, okText, cancelText, formID, dialogDivID) {
1134 const dialogContent = document.getElementById(dialogDivID).cloneNode(true);
1135 dialogContent.classList.remove('hidden');
1136 dialogContent.firstElementChild.id = formID + '_dlg';
1137 Swal.fire({
1138 title: title,
1139 confirmButtonText: okText,
1140 cancelButtonText: cancelText,
1141 showCancelButton: true,
1142 showConfirmButton: (okText !== null),
1143 html: dialogContent.outerHTML,
1144 width: 'auto'
1145 }).then(result => {
1146 if (result.isConfirmed) {
1147 document.forms[formID + '_dlg'].submit();
1148 }
1149 });
1150 }
1151
1152 /**
1153 * Shows a dialog message.
1154 *
1155 * @param title dialog title
1156 * @param okText ok button text
1157 * @param cancelText cancel button text
1158 * @param message text message
1159 * @param formId form to submit when confirmed
1160 */
1161 window.lam.dialog.confirmAndSendForm = function(title, okText, cancelText, message, formId) {
1162 Swal.fire({
1163 title: title,
1164 confirmButtonText: okText,
1165 cancelButtonText: cancelText,
1166 showCancelButton: true,
1167 text: message,
1168 width: 'auto'
1169 }).then(result => {
1170 if (result.isConfirmed) {
1171 document.forms[formId].submit();
1172 }
1173 });
1174 };
1175
1176 /**
1177 * Shows a dialog with password input. The password is added to the form when confirmed.
1178 *
1179 * @param title dialog title
1180 * @param okText ok button text
1181 * @param cancelText cancel button text
1182 * @param passwordLabel password label
1183 * @param passwordInputName input field name for password
1184 * @param formId form to submit when confirmed
1185 */
1186 window.lam.dialog.requestPasswordAndSendForm = async function (title, okText, cancelText, passwordLabel, passwordInputName, formId) {
1187 const {value} = await Swal.fire({
1188 title: title,
1189 confirmButtonText: okText,
1190 cancelButtonText: cancelText,
1191 showCancelButton: true,
1192 input: 'password',
1193 inputLabel: passwordLabel,
1194 width: 'auto'
1195 });
1196 if (value) {
1197 let passwordTag = document.createElement('input');
1198 passwordTag.name = passwordInputName;
1199 passwordTag.value = value;
1200 passwordTag.hidden = 'hidden';
1201 document.forms[formId].appendChild(passwordTag);
1202 document.forms[formId].submit();
1203 }
1204 };
1205
1206 /**
1207 * Shows a modal dialog.
1208 *
1209 * @param selector selector to find modal content
1210 */
1211 window.lam.dialog.showModal = function(selector) {
1212 let modal = document.querySelector(selector);
1213 modal.classList.add("show-modal");
1214 window.addEventListener("click", function(event) {
1215 if(event.target === modal) {
1216 modal.classList.remove("show-modal");
1217 }
1218 });
1219 // set focus on password field
1220 let myElement = modal.querySelector('input');
1221 if (!myElement) {
1222 myElement = modal.querySelector('select');
1223 }
1224 if (myElement) {
1225 myElement.focus();
1226 }
1227 }
1228
1229 /**
1230 * Shows a success message and redirects to the given URL when dialog is closed.
1231 * Dialog auto-closes after 3 seconds.
1232 *
1233 * @param title title
1234 * @param message detail message
1235 * @param buttonText text for confirm button
1236 * @param redirectUrl redirect URL
1237 */
1238 window.lam.dialog.showSuccessMessageAndRedirect = function(title, message, buttonText, redirectUrl) {
1239 Swal.fire({
1240 icon: 'success',
1241 title: title,
1242 confirmButtonText: buttonText,
1243 text: message,
1244 width: 'auto',
1245 timer: 3000,
1246 timerProgressBar: true
1247 }).then(result => {
1248 window.location = redirectUrl;
1249 });
1250 }
1251
1252 /**
1253 * Shows an error message and redirects to the given URL when dialog is closed.
1254 *
1255 * @param title title
1256 * @param message detail message
1257 * @param buttonText text for confirm button
1258 * @param redirectUrl redirect URL
1259 */
1260 window.lam.dialog.showErrorMessageAndRedirect = function(title, message, buttonText, redirectUrl) {
1261 Swal.fire({
1262 icon: 'error',
1263 title: title,
1264 confirmButtonText: buttonText,
1265 text: message,
1266 width: 'auto'
1267 }).then(result => {
1268 window.location = redirectUrl;
1269 });
1270 }
1271
1272 window.lam.account = window.lam.account || {};
1273
1274 /**
1275 * Adds a listener on the link to set default profile.
1276 */
1277 window.lam.account.addDefaultProfileListener = function() {
1278 const defaultProfileLink = document.getElementById('lam-make-default-profile');
1279 if (defaultProfileLink) {
1280 defaultProfileLink.addEventListener('click', function() {
1281 const typeId = this.dataset.typeid;
1282 const name = this.dataset.name;
1283 const okText = this.dataset.ok;
1284 let date = new Date();
1285 date.setTime(date.getTime() + (365*24*60*60*1000));
1286 document.cookie = 'defaultProfile_' + typeId + '=' + name + '; expires=' + date.toUTCString();
1287 window.lam.dialog.showMessage(null, okText, 'lam-make-default-profile-dlg');
1288 });
1289 }
1290 };
1291
1292 window.lam.tools = window.lam.tools || {};
1293
1294 /**
1295 * Adds a listener on select lists to store the last value as default in local storage.
1296 * Select lists need to be marked with class "lam-save-selection".
1297 */
1298 window.lam.tools.addSavedSelectListener = function() {
1299 if (!window.localStorage) {
1300 return;
1301 }
1302 const selects = document.querySelectorAll('select.lam-save-selection');
1303 selects.forEach(item => {
1304 const name = item.name;
1305 const storageKey = 'lam_selectionStore_' + name;
1306 // load value from local storage
1307 const storageValue = window.localStorage.getItem(storageKey);
1308 if (storageValue) {
1309 const option = item.querySelector('option[value="' + storageValue + '"]');
1310 if (option) {
1311 item.value = storageValue;
1312 }
1313 }
1314 // add change listener
1315 item.addEventListener('change', function() {
1316 const selectedValue = item.value;
1317 window.localStorage.setItem(storageKey, selectedValue);
1318 });
1319 });
1320 const checkboxes = document.querySelectorAll('input.lam-save-selection');
1321 checkboxes.forEach(item => {
1322 const name = item.name;
1323 const storageKey = 'lam_selectionStore_' + name;
1324 // load value from local storage
1325 const storageValue = window.localStorage.getItem(storageKey);
1326 if (storageValue) {
1327 item.checked = (storageValue === 'true');
1328 }
1329 // add change listener
1330 item.addEventListener('change', function() {
1331 const selectedValue = item.checked;
1332 window.localStorage.setItem(storageKey, selectedValue);
1333 });
1334 });
1335 };
1336
1337 /**
1338 * Sets the focus on the initial field.
1339 */
1340 window.lam.tools.setInitialFocus = function() {
1341 const elementToFocus = document.querySelector('.lam-initial-focus');
1342 if (elementToFocus) {
1343 elementToFocus.focus();
1344 }
1345 };
1346
1347 window.lam.tools.webcam = window.lam.tools.webcam || {};
1348
1349 /**
1350 * Initializes the webcam capture.
1351 */
1352 window.lam.tools.webcam.init = function() {
1353 const contentDiv = document.getElementById('lam_webcam_div');
1354 if (contentDiv && navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
1355 navigator.mediaDevices.enumerateDevices()
1356 .then(function(mediaDevices) {
1357 for (let i = 0; i < mediaDevices.length; i++) {
1358 const mediaDevice = mediaDevices[i];
1359 if (mediaDevice.kind === 'videoinput') {
1360 contentDiv.classList.remove('hidden');
1361 }
1362 }
1363 });
1364 }
1365 };
1366
1367 /**
1368 * Starts the webcam capture.
1369 */
1370 window.lam.tools.webcam.capture = function(event) {
1371 event.preventDefault();
1372 const video = document.getElementById('lam-webcam-video');
1373 const msg = document.querySelector('.lam-webcam-message');
1374 msg.classList.add('hidden');
1375 navigator.mediaDevices.getUserMedia({
1376 video: {
1377 facingMode: 'user',
1378 width: { min: 1024, ideal: 1280, max: 1920 },
1379 height: { min: 576, ideal: 720, max: 1080 }
1380 },
1381 audio: false
1382 })
1383 .then(function(stream) {
1384 video.srcObject = stream;
1385 video.play();
1386 window.lam.tools.webcamStream = stream;
1387 document.getElementById('btn_lam-webcam-capture').classList.add('hidden');
1388 document.querySelector('.btn-lam-webcam-upload').classList.remove('hidden');
1389 document.getElementById('lam-webcam-video').classList.remove('hidden');
1390 })
1391 .catch(function(err) {
1392 msg.querySelector('.statusTitle').textContent = err.message;
1393 msg.classList.remove('hidden');
1394 });
1395 return false;
1396 }
1397
1398 /**
1399 * Starts the webcam upload.
1400 */
1401 window.lam.tools.webcam.upload = function() {
1402 const form = document.getElementById('lam-webcam-canvas').closest('form');
1403 const canvasData = window.lam.tools.webcam.prepareData();
1404 const canvasDataInput = document.createElement('input');
1405 canvasDataInput.setAttribute('name', 'webcamData');
1406 canvasDataInput.setAttribute('id', 'webcamData');
1407 canvasDataInput.setAttribute('type', 'hidden');
1408 canvasDataInput.setAttribute('value', canvasData);
1409 form.append(canvasDataInput);
1410 form.submit();
1411 return true;
1412 }
1413
1414 /**
1415 * Starts the webcam upload.
1416 *
1417 * @param event click event
1418 * @param tokenName security token name
1419 * @param tokenValue security token value
1420 * @param moduleName module name
1421 * @param scope account type
1422 * @param uploadErrorMessage error message if upload fails
1423 * @param contentId id of content to replace
1424 */
1425 window.lam.tools.webcam.uploadSelfService = function(event, tokenName, tokenValue, moduleName, scope, uploadErrorMessage, contentId) {
1426 event.preventDefault();
1427 const msg = document.querySelector('.lam-webcam-message');
1428 const canvasData = window.lam.tools.webcam.prepareData();
1429 let data = new FormData();
1430 data.append('webcamData', canvasData);
1431 data.append(tokenName, tokenValue);
1432 const ajaxURL = '../misc/ajax.php?selfservice=1&action=ajaxPhotoUpload'
1433 + '&module=' + moduleName + '&scope=' + scope;
1434 fetch(ajaxURL, {
1435 method: 'POST',
1436 body: data
1437 })
1438 .then(async response => {
1439 if (response.ok === false) {
1440 msg.querySelector('.statusTitle').innerText = uploadErrorMessage;
1441 msg.classList.remove('hidden');
1442 return;
1443 }
1444 const jsonData = await response.json();
1445 if (jsonData.success) {
1446 if (jsonData.html) {
1447 document.getElementById(contentId).innerHTML = jsonData.html;
1448 window.lam.tools.webcam.init();
1449 window.lam.html.initCropping();
1450 }
1451 }
1452 else if (jsonData.error) {
1453 msg.querySelector('.statusTitle').innerText = jsonData.error;
1454 msg.classList.remove('hidden');
1455 }
1456 });
1457 document.getElementById('btn_lam-webcam-capture').classList.remove('hidden');
1458 document.getElementById('btn-lam-webcam-upload').classList.add('hidden');
1459 return false;
1460 }
1461
1462 /**
1463 * Starts the webcam upload.
1464 *
1465 * @return webcam data as string
1466 */
1467 window.lam.tools.webcam.prepareData = function() {
1468 const canvas = document.getElementById('lam-webcam-canvas');
1469 const video = document.getElementById('lam-webcam-video');
1470 canvas.setAttribute('width', video.videoWidth);
1471 canvas.setAttribute('height', video.videoHeight);
1472 const context = canvas.getContext('2d');
1473 context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
1474 const canvasData = canvas.toDataURL("image/png");
1475 video.pause();
1476 const tracks = window.lam.tools.webcamStream.getTracks();
1477 for (let i = 0; i < tracks.length; i++) {
1478 tracks[i].stop();
1479 }
1480 canvas.classList.add('hidden');
1481 video.classList.add('hidden');
1482 return canvasData;
1483 }
1484
1485 window.lam.tools.schema = window.lam.tools.schema || {};
1486
1487 /**
1488 * Adds the onChange listener to schema selections.
1489 */
1490 window.lam.tools.schema.select = function() {
1491 const select = document.getElementById('lam-schema-select');
1492 if (!select) {
1493 return;
1494 }
1495 const display = select.dataset.display;
1496 select.addEventListener('change', function() {
1497 const value = select.value;
1498 document.location = 'schema.php?display=' + display + '&sel=' + value;
1499 });
1500 };
1501
1502 window.lam.importexport = window.lam.importexport || {};
1503
1504 /**
1505 * Starts the import process.
1506 *
1507 * @param tokenName name of CSRF token
1508 * @param tokenValue value of CSRF token
1509 */
1510 window.lam.importexport.startImport = function(tokenName, tokenValue) {
1511 if (document.readyState === 'loading') {
1512 document.addEventListener('DOMContentLoaded', function() {
1513 window.lam.importexport.startImport(tokenName, tokenValue);
1514 });
1515 return;
1516 }
1517 const output = document.getElementById('importResults');
1518 let data = new FormData();
1519 data.append(tokenName, tokenValue);
1520 const ajaxURL = '../misc/ajax.php?function=import';
1521 fetch(ajaxURL, {
1522 method: 'POST',
1523 body: data
1524 })
1525 .then(async response => {
1526 const jsonData = await response.json();
1527 if (jsonData.data && (jsonData.data !== '')) {
1528 output.innerHTML += jsonData.data;
1529 }
1530 if (jsonData.status == 'done') {
1531 document.getElementById('progressbarImport').classList.add('hidden');
1532 document.getElementById('btn_submitImportCancel').classList.add('hidden');
1533 document.getElementById('statusImportInprogress').classList.add('hidden');
1534 document.getElementById('statusImportDone').classList.remove('hidden');
1535 document.querySelector('.newimport').classList.remove('hidden');
1536 }
1537 else if (jsonData.status == 'failed') {
1538 document.getElementById('btn_submitImportCancel').classList.add('hidden');
1539 document.getElementById('statusImportInprogress').classList.add('hidden');
1540 document.getElementById('statusImportFailed').classList.remove('hidden');
1541 document.querySelector('.newimport').classList.remove('hidden');
1542 }
1543 else {
1544 window.lam.progressbar.setProgress('progressbarImport', jsonData.progress);
1545 window.lam.importexport.startImport(tokenName, tokenValue);
1546 }
1547 });
1548 };
1549
1550 /**
1551 * Starts the export process.
1552 *
1553 * @param tokenName name of CSRF token
1554 * @param tokenValue value of CSRF token
1555 */
1556 window.lam.importexport.startExport = function(tokenName, tokenValue) {
1557 if (document.readyState === 'loading') {
1558 document.addEventListener('DOMContentLoaded', function() {
1559 window.lam.importexport.startExport(tokenName, tokenValue);
1560 });
1561 return;
1562 }
1563 window.lam.progressbar.setProgress('progressbarExport', 50);
1564 const output = document.getElementById('exportResults');
1565 let data = new FormData();
1566 data.append(tokenName, tokenValue);
1567 data.append('baseDn', document.getElementById('baseDn').value);
1568 data.append('searchScope', document.getElementById('searchScope').value);
1569 data.append('filter', document.getElementById('filter').value);
1570 data.append('attributes', document.getElementById('attributes').value);
1571 data.append('format', document.getElementById('format').value);
1572 data.append('ending', document.getElementById('ending').value);
1573 data.append('includeSystem', document.getElementById('includeSystem').value);
1574 data.append('saveAsFile', document.getElementById('saveAsFile').value);
1575 fetch('../misc/ajax.php?function=export', {
1576 method: 'POST',
1577 body: data
1578 })
1579 .then(async response => {
1580 const jsonData = await response.json();
1581 if (jsonData.data && (jsonData.data != '')) {
1582 output.append(jsonData.data);
1583 }
1584 if (jsonData.status == 'done') {
1585 document.getElementById('progressbarExport').classList.add('hidden');
1586 document.getElementById('btn_submitExportCancel').classList.add('hidden');
1587 document.getElementById('statusExportInprogress').classList.add('hidden');
1588 document.getElementById('statusExportDone').classList.remove('hidden');
1589 document.querySelector('.newexport').classList.remove('hidden');
1590 if (jsonData.output) {
1591 document.getElementById('exportResults').querySelector('pre').innerText = jsonData.output;
1592 }
1593 else if (jsonData.file) {
1594 window.open(jsonData.file, '_blank');
1595 }
1596 }
1597 else {
1598 document.getElementById('progressbarExport').classList.add('hidden');
1599 document.getElementById('btn_submitExportCancel').classList.add('hidden');
1600 document.getElementById('statusExportDone').classList.add('hidden');
1601 document.getElementById('statusExportInprogress').classList.add('hidden');
1602 document.getElementById('statusExportFailed').classList.remove('hidden');
1603 document.querySelector('.newexport').classList.remove('hidden');
1604 }
1605 })
1606 .catch((error) => {
1607 document.getElementById('progressbarExport').classList.add('hidden');
1608 document.getElementById('btn_submitExportCancel').classList.add('hidden');
1609 document.getElementById('statusExportDone').classList.add('hidden');
1610 document.getElementById('statusExportInprogress').classList.add('hidden');
1611 document.getElementById('statusExportFailed').classList.remove('hidden');
1612 document.querySelector('.newexport').classList.remove('hidden');
1613 });
1614 };
1615
1616 window.lam.multiedit = window.lam.multiedit || {};
1617
1618 window.lam.multiedit.runActions = function() {
1619 // disable all input elements
1620 document.querySelectorAll('input, select, button').forEach(function (item) {
1621 item.disabled = true;
1622 });
1623 // run actions
1624 fetch('multiEdit.php?ajaxStatus', {
1625 method: 'GET'
1626 })
1627 .then(async response => {
1628 const jsonData = await response.json();
1629 window.lam.multiedit.runActionsHandleReply(jsonData);
1630 });
1631 }
1632
1633 window.lam.multiedit.runActionsHandleReply = function(data) {
1634 window.lam.progressbar.setProgress('progressBar', data.progress);
1635 document.getElementById('progressArea').innerHTML = data.content;
1636 if (data.status != "finished") {
1637 fetch('multiEdit.php?ajaxStatus', {
1638 method: 'GET'
1639 })
1640 .then(async response => {
1641 const jsonData = await response.json();
1642 window.lam.multiedit.runActionsHandleReply(jsonData);
1643 });
1644 }
1645 else {
1646 document.querySelectorAll('input, select, button').forEach(function (item) {
1647 item.disabled = false;
1648 });
1649 document.getElementById('progressBar').classList.add('hidden');
1650 }
1651 }
1652
1653 window.lam.html = window.lam.html || {};
1654
1655 /**
1656 * Shows a DN selection for the given input field.
1657 *
1658 * @param fieldId id of input field
1659 * @param title title of dialog
1660 * @param okText ok button text
1661 * @param cancelText cancel button text
1662 * @param tokenName CSRF token name
1663 * @param tokenValue CSRF token value
1664 */
1665 window.lam.html.showDnSelection = function(fieldId, title, okText, cancelText, tokenName, tokenValue) {
1666 const field = document.getElementById(fieldId);
1667 const dnValue = field.value;
1668 let data = new FormData();
1669 data.append(tokenName, tokenValue);
1670 data.append('fieldId', fieldId);
1671 data.append('dn', dnValue);
1672 fetch('../misc/ajax.php?function=dnselection', {
1673 method: 'POST',
1674 body: data
1675 })
1676 .then(async response => {
1677 const jsonData = await response.json();
1678 const dlgHtml = '<div id="dlg_' + fieldId + '">' + jsonData.dialogData + '</div>';
1679 Swal.fire({
1680 title: title,
1681 cancelButtonText: cancelText,
1682 showCancelButton: true,
1683 showConfirmButton: false,
1684 html: dlgHtml,
1685 width: 'auto'
1686 });
1687 });
1688 };
1689
1690 /**
1691 * Selects the DN from dialog.
1692 *
1693 * @param el ok button in dialog
1694 * @param fieldId field id of input field
1695 * @returns boolean false
1696 */
1697 window.lam.html.selectDn = function(el, fieldId) {
1698 const field = document.getElementById(fieldId);
1699 let parent = el.parentElement;
1700 while (!parent.classList.contains('row')) {
1701 parent = parent.parentElement;
1702 }
1703 const dn = parent.dataset.dn;
1704 field.value = dn;
1705 Swal.close();
1706 return false;
1707 }
1708
1709 /**
1710 * Updates the DN selection.
1711 *
1712 * @param el element
1713 * @param fieldId field id of dialog
1714 * @param tokenName CSRF token name
1715 * @param tokenValue CSRF token value
1716 */
1717 window.lam.html.updateDnSelection = function(el, fieldId, tokenName, tokenValue) {
1718 let parent = el.parentElement;
1719 while (!parent.classList.contains('row')) {
1720 parent = parent.parentElement;
1721 }
1722 const dn = parent.dataset.dn;
1723 let data = new FormData();
1724 data.append(tokenName, tokenValue);
1725 data.append('fieldId', fieldId);
1726 data.append('dn', dn);
1727 fetch('../misc/ajax.php?function=dnselection', {
1728 method: 'POST',
1729 body: data
1730 })
1731 .then(async response => {
1732 const jsonData = await response.json();
1733 document.getElementById('dlg_' + fieldId).innerHTML = jsonData.dialogData;
1734 })
1735 .catch((error) => {
1736 Swal.close();
1737 });
1738 }
1739
1740 /**
1741 * Activates the lightboxes on images.
1742 */
1743 window.lam.html.activateLightboxes = function() {
1744 document.querySelectorAll('.lam-lightbox').forEach(item => {
1745 item.onclick = function() {
1746 Swal.fire({
1747 imageUrl: item.src,
1748 confirmButtonText: item.dataset.lightboxLabelClose,
1749 width: 'auto'
1750 })
1751 };
1752 });
1753 };
1754
1755 /**
1756 * Prevents enter key on input fields with class "lam-prevent-enter".
1757 */
1758 window.lam.html.preventEnter = function() {
1759 document.querySelectorAll('.lam-prevent-enter').forEach(item => {
1760 item.addEventListener('keypress', function (event) {
1761 if (event.key === 'Enter') {
1762 event.preventDefault();
1763 }
1764 });
1765 });
1766 }
1767
1768 /**
1769 * Inits the cropping area on images.
1770 */
1771 window.lam.html.initCropping = function() {
1772 const image = document.querySelector('.cropperjsImage');
1773 new Cropper(image, {
1774 viewMode: 1,
1775 movable: false,
1776 zoomable: false,
1777 crop: function(event) {
1778 document.getElementById('croppingDataX').value = event.detail.x;
1779 document.getElementById('croppingDataY').value = event.detail.y;
1780 document.getElementById('croppingDataWidth').value = event.detail.width;
1781 document.getElementById('croppingDataHeight').value = event.detail.height;
1782 }
1783 });
1784 }
1785
1786 /**
1787 * Updates the field to store the sorting of an accordion.
1788 *
1789 * @param accordionId ID of accordion container
1790 */
1791 window.lam.html.updateAccordionSorting = function (accordionId) {
1792 const positionsField = document.getElementById(accordionId + '_sorting');
1793 let positions = [];
1794 document.getElementById(accordionId).querySelectorAll('.lam-accordion-button').forEach(function (item) {
1795 const index = item.dataset.index;
1796 positions.push(index);
1797 });
1798 positionsField.value = positions.join(',');
1799 }
1800
1801 window.lam.selfservice = window.lam.selfservice || {};
1802
1803 /**
1804 * Deletes a value of a multi-value field.
1805 *
1806 * @param fieldNamePrefix prefix of input field name
1807 * @param delButton delete button that was clicked
1808 */
1809 window.lam.selfservice.delMultiValue = function(fieldNamePrefix, delButton) {
1810 const fields = document.querySelectorAll("input[name^='" + fieldNamePrefix + "'], textarea[name^='" + fieldNamePrefix + "']");
1811 const isOnlyOneField = (fields.length === 1);
1812 if (!isOnlyOneField) {
1813 // move add button if present
1814 const addButton = delButton.nextElementSibling;
1815 if (addButton) {
1816 const lastLastDelLink = fields[fields.length - 2].parentElement.parentElement.querySelector('.del-link');
1817 const lastLastDelLinkParent = lastLastDelLink.parentElement;
1818 lastLastDelLinkParent.append(addButton);
1819 }
1820 // delete row
1821 let parent = delButton.parentElement;
1822 while (!parent.classList.contains('row')) {
1823 parent = parent.parentElement;
1824 }
1825 const row = parent.parentElement;
1826 row.remove();
1827 }
1828 else {
1829 fields[0].value = '';
1830 }
1831 };
1832
1833 /**
1834 * Adds a value to a multi-value field.
1835 *
1836 * @param fieldNamePrefix prefix of input field name
1837 * @param addButton add button that was clicked
1838 */
1839 window.lam.selfservice.addMultiValue = function(fieldNamePrefix, addButton) {
1840 const fields = document.querySelectorAll("input[name^='" + fieldNamePrefix + "'], textarea[name^='" + fieldNamePrefix + "']");
1841 // get next field number
1842 const lastFieldName = fields[fields.length - 1].name;
1843 const lastFieldNameIndex = lastFieldName.substring(fieldNamePrefix.length);
1844 const newFieldNameIndex = parseInt(lastFieldNameIndex) + 1;
1845 // copy row
1846 let parent = addButton.parentElement;
1847 while (!parent.classList.contains('row')) {
1848 parent = parent.parentElement;
1849 }
1850 const row = parent.parentElement;
1851 const clone = row.cloneNode(true);
1852 row.parentElement.append(clone);
1853 const cloneInput = clone.querySelector("input[name^='" + fieldNamePrefix + "'], textarea[name^='" + fieldNamePrefix + "']");
1854 cloneInput.name = fieldNamePrefix + newFieldNameIndex;
1855 cloneInput.id = fieldNamePrefix + newFieldNameIndex;
1856 cloneInput.value = '';
1857 // delete add link from old row
1858 addButton.remove();
1859 };
1860
1861 window.lam.whitePages = window.lam.whitePages || {};
1862
1863 /**
1864 * Shows the detail view for an entry.
1865 *
1866 * @param dn base64 encoded DN
1867 * @param tabIndex tab index
1868 * @param okText label for Ok button
1869 * @param tokenName CSRF token name
1870 * @param tokenValue CSRF token value
1871 * @param dnBefore DN that was opened before, reopen on close
1872 * @param tabIndexBefore tab index of DN that was opened before, reopen on close
1873 */
1874 window.lam.whitePages.showDetailView = function (dn, tabIndex, okText, tokenName, tokenValue, dnBefore, tabIndexBefore) {
1875 let data = new FormData();
1876 data.append(tokenName, tokenValue);
1877 data.append('action', 'displayDetails');
1878 data.append('dn', dn);
1879 data.append('tabIndex', tabIndex);
1880 fetch('../misc/ajax.php?whitepages=1&function=whitePages', {
1881 method: 'POST',
1882 body: data
1883 })
1884 .then(async response => {
1885 const jsonData = await response.json();
1886 if (jsonData.error) {
1887 window.lam.dialog.showError(null, jsonData.error, okText);
1888 return;
1889 }
1890 document.getElementById('detailView').innerHTML = jsonData.content;
1891 window.lam.dialog.showMessage(jsonData.title, okText, 'detailView',
1892 function () {
1893 if (dnBefore) {
1894 window.lam.whitePages.showDetailView(dnBefore, tabIndexBefore, okText, tokenName, tokenValue);
1895 }
1896 });
1897 })
1898 }
1899
1900 /**
1901 * Switches the view to gallery mode.
1902 */
1903 window.lam.whitePages.switchToGallery = function(tabIndex) {
1904 document.getElementById('container-list_' + tabIndex).classList.add('hidden');
1905 document.getElementById('modeSwitchGallery_' + tabIndex).classList.add('hidden');
1906 document.getElementById('modeSwitchList_' + tabIndex).classList.remove('hidden');
1907 document.getElementById('container-gallery_' + tabIndex).classList.remove('hidden');
1908 }
1909
1910 /**
1911 * Switches the view to list mode.
1912 */
1913 window.lam.whitePages.switchToList = function(tabIndex) {
1914 document.getElementById('container-list_' + tabIndex).classList.remove('hidden');
1915 document.getElementById('modeSwitchGallery_' + tabIndex).classList.remove('hidden');
1916 document.getElementById('modeSwitchList_' + tabIndex).classList.add('hidden');
1917 document.getElementById('container-gallery_' + tabIndex).classList.add('hidden');
1918 }
1919
1920 /**
1921 * Adds the search listener for the gallery view.
1922 *
1923 * @param containerId container ID
1924 * @param searchFieldId search field ID
1925 */
1926 window.lam.whitePages.addGallerySearchListener = function(containerId, searchFieldId) {
1927 document.getElementById(searchFieldId).addEventListener('keyup', function(event) {
1928 const container = document.getElementById(containerId);
1929 const cards = container.querySelectorAll('.whitepages-card');
1930 const filterValueString = document.getElementById(searchFieldId).value;
1931 const filterValues = filterValueString.split(/\s+/);
1932 cards.forEach(card => {
1933 let found = true;
1934 const searchData = card.dataset._lam_search_;
1935 filterValues.forEach(value => {
1936 found = found && searchData.toLowerCase().includes(value);
1937 })
1938 if (found && card.classList.contains('hidden')) {
1939 card.classList.remove('hidden');
1940 }
1941 else if (!found && !card.classList.contains('hidden')) {
1942 card.classList.add('hidden');
1943 }
1944 })
1945
1946 });
1947 }
1948
1949 window.lam.webauthn = window.lam.webauthn || {};
1950
1951 /**
1952 * Returns the first unicode character.
1953 *
1954 * @param c char
1955 * @returns {number} character
1956 */
1957 window.lam.webauthn.charAt = function (c) {
1958 return c.charCodeAt(0);
1959 }
1960
1961 /**
1962 * Starts the webauthn process.
1963 *
1964 * @param prefix path prefix for Ajax endpoint
1965 * @param extraParam additional parameter for request (e.g. "selfservice=true")
1966 * @param newDeviceNameTitle title for new device name dialog
1967 * @param newDeviceNameLabel label for new device name
1968 * @param okText text for Ok button
1969 * @param cancelText text for cancelButton
1970 */
1971 window.lam.webauthn.start = function(prefix, extraParam, newDeviceNameTitle, newDeviceNameLabel, okText, cancelText) {
1972 document.addEventListener("DOMContentLoaded", function(){
1973 window.lam.webauthn.run(prefix, extraParam, newDeviceNameTitle, newDeviceNameLabel, okText, cancelText);
1974 });
1975 }
1976
1977 /**
1978 * Checks if the user is registered and starts login/registration.
1979 *
1980 * @param prefix path prefix for Ajax endpoint
1981 * @param extraParam additional parameter for request (e.g. "selfservice=true")
1982 * @param newDeviceNameTitle title for new device name dialog
1983 * @param newDeviceNameLabel label for new device name
1984 * @param okText text for Ok button
1985 * @param cancelText text for cancelButton
1986 */
1987 window.lam.webauthn.run = function(prefix, extraParam, newDeviceNameTitle, newDeviceNameLabel, okText, cancelText) {
1988 const skipButton = document.getElementById('btn_skip_webauthn');
1989 if (skipButton) {
1990 skipButton.onclick = function () {
1991 const form = document.getElementById("2faform");
1992 const hiddenSkip = document.createElement('input');
1993 hiddenSkip.type = 'hidden';
1994 hiddenSkip.name = 'sig_response';
1995 hiddenSkip.value = 'skip';
1996 form.appendChild(hiddenSkip);
1997 form.submit();
1998 };
1999 }
2000 const token = document.getElementById('sec_token').value;
2001 // check for webauthn support
2002 if (!navigator.credentials || (typeof(PublicKeyCredential) === "undefined")) {
2003 document.querySelector('.webauthn-error').classList.remove('hidden');
2004 return;
2005 }
2006
2007 let data = new FormData();
2008 data.append('sec_token', token);
2009 data.append('action', 'status');
2010 extraParam = (extraParam) ? '&' + extraParam : '';
2011 fetch(prefix + 'misc/ajax.php?function=webauthn' + extraParam, {
2012 method: 'POST',
2013 body: data
2014 })
2015 .then(async response => {
2016 const jsonData = await response.json();
2017 if (jsonData.action === 'register') {
2018 const registerFunction = function() {
2019 const successCallback = async function (publicKeyCredential) {
2020 const {value: newName} = await Swal.fire({
2021 title: newDeviceNameTitle,
2022 confirmButtonText: okText,
2023 cancelButtonText: cancelText,
2024 showCancelButton: true,
2025 input: 'text',
2026 inputLabel: newDeviceNameLabel,
2027 width: 'auto'
2028 });
2029 const form = document.getElementById("2faform");
2030 if (newName) {
2031 const newNameElement = document.createElement('input');
2032 newNameElement.type = 'hidden';
2033 newNameElement.name = 'newName';
2034 newNameElement.value = newName;
2035 form.appendChild(newNameElement);
2036 }
2037 const response = btoa(JSON.stringify(publicKeyCredential));
2038 const hiddenResponse = document.createElement('input');
2039 hiddenResponse.type = 'hidden';
2040 hiddenResponse.name = 'sig_response';
2041 hiddenResponse.value = response;
2042 form.appendChild(hiddenResponse);
2043 form.submit();
2044 };
2045 const errorCallback = function(error) {
2046 const errorDiv = document.getElementById('generic-webauthn-error');
2047 const buttonLabel = errorDiv.dataset.button;
2048 const dialogTitle = errorDiv.dataset.title;
2049 errorDiv.innerText = error.message;
2050 window.lam.dialog.showMessage(dialogTitle,
2051 buttonLabel,
2052 'generic-webauthn-error',
2053 function () {
2054 document.getElementById('btn_logout').click();
2055 });
2056 };
2057 window.lam.webauthn.register(jsonData.registration, successCallback, errorCallback);
2058 return false;
2059 }
2060 let registerButton = document.getElementById('btn_register_webauthn');
2061 if (!registerButton) {
2062 registerFunction();
2063 }
2064 else {
2065 registerButton.onclick = registerFunction;
2066 }
2067 }
2068 else if (jsonData.action === 'authenticate') {
2069 window.lam.webauthn.authenticate(jsonData.authentication);
2070 }
2071 })
2072 .catch(function(err) {
2073 console.log('WebAuthn failed: ' + err);
2074 });
2075 }
2076
2077 /**
2078 * Performs a webauthn registration.
2079 *
2080 * @param publicKey registration object
2081 * @param successCallback callback function in case of all went fine
2082 * @param errorCallback callback function in case of an error
2083 */
2084 window.lam.webauthn.register = function(publicKey, successCallback, errorCallback) {
2085 if (!(publicKey.challenge instanceof Uint8Array)) {
2086 publicKey.challenge = Uint8Array.from(window.atob(publicKey.challenge), window.lam.webauthn.charAt);
2087 publicKey.user.id = Uint8Array.from(window.atob(publicKey.user.id), window.lam.webauthn.charAt);
2088 publicKey.rp.icon = window.location.href.substring(0, window.location.href.lastIndexOf("/")) + publicKey.rp.icon;
2089 if (publicKey.excludeCredentials) {
2090 for (var i = 0; i < publicKey.excludeCredentials.length; i++) {
2091 var idOrig = publicKey.excludeCredentials[i]['id'];
2092 idOrig = idOrig.replace(/-/g, "+").replace(/_/g, "/");
2093 var idOrigDecoded = atob(idOrig);
2094 var idArray = Uint8Array.from(idOrigDecoded, window.lam.webauthn.charAt)
2095 publicKey.excludeCredentials[i]['id'] = idArray;
2096 }
2097 }
2098 }
2099 navigator.credentials.create({publicKey: publicKey})
2100 .then(function (data) {
2101 var publicKeyCredential = {
2102 id: data.id,
2103 type: data.type,
2104 rawId: window.lam.webauthn.arrayToBase64String(new Uint8Array(data.rawId)),
2105 response: {
2106 clientDataJSON: window.lam.webauthn.arrayToBase64String(new Uint8Array(data.response.clientDataJSON)),
2107 attestationObject: window.lam.webauthn.arrayToBase64String(new Uint8Array(data.response.attestationObject))
2108 }
2109 };
2110 successCallback(publicKeyCredential);
2111 }, function (error) {
2112 console.log(error.message);
2113 errorCallback(error);
2114 });
2115 }
2116
2117 /**
2118 * Performs a webauthn authentication.
2119 *
2120 * @param publicKey authentication object
2121 */
2122 window.lam.webauthn.authenticate = function(publicKey) {
2123 publicKey.challenge = Uint8Array.from(window.atob(publicKey.challenge), window.lam.webauthn.charAt);
2124 for (var i = 0; i < publicKey.allowCredentials.length; i++) {
2125 let idOrig = publicKey.allowCredentials[i]['id'];
2126 idOrig = idOrig.replace(/-/g, "+").replace(/_/g, "/");
2127 const idOrigDecoded = atob(idOrig);
2128 const idArray = Uint8Array.from(idOrigDecoded, window.lam.webauthn.charAt)
2129 publicKey.allowCredentials[i]['id'] = idArray;
2130 }
2131 navigator.credentials.get({publicKey: publicKey})
2132 .then(function(data) {
2133 const publicKeyCredential = {
2134 id: data.id,
2135 type: data.type,
2136 rawId: window.lam.webauthn.arrayToBase64String(new Uint8Array(data.rawId)),
2137 response: {
2138 authenticatorData: window.lam.webauthn.arrayToBase64String(new Uint8Array(data.response.authenticatorData)),
2139 clientDataJSON: window.lam.webauthn.arrayToBase64String(new Uint8Array(data.response.clientDataJSON)),
2140 signature: window.lam.webauthn.arrayToBase64String(new Uint8Array(data.response.signature)),
2141 userHandle: data.response.userHandle ? window.lam.webauthn.arrayToBase64String(new Uint8Array(data.response.userHandle)) : null
2142 }
2143 };
2144 const form = document.getElementById("2faform");
2145 const response = btoa(JSON.stringify(publicKeyCredential));
2146 const hiddenResponse = document.createElement('input');
2147 hiddenResponse.type = 'hidden';
2148 hiddenResponse.name = 'sig_response';
2149 hiddenResponse.value = response;
2150 form.appendChild(hiddenResponse);
2151 form.submit();
2152 }, function(error) {
2153 console.log(error.message);
2154 const errorDiv = document.getElementById('generic-webauthn-error');
2155 const buttonLabel = errorDiv.dataset.button;
2156 const dialogTitle = errorDiv.dataset.title;
2157 errorDiv.innerText = error.message;
2158 window.lam.dialog.showMessage(dialogTitle,
2159 buttonLabel,
2160 'generic-webauthn-error',
2161 function () {
2162 document.getElementById('btn_logout').click();
2163 });
2164 });
2165 }
2166
2167 /**
2168 * Converts an array to a base64 string.
2169 *
2170 * @param input array
2171 * @returns base64 string
2172 */
2173 window.lam.webauthn.arrayToBase64String = function(input) {
2174 return btoa(String.fromCharCode(...input))
2175 .replaceAll("=", "")
2176 .replaceAll("+", "-")
2177 .replaceAll("/", "_");
2178 }
2179
2180 /**
2181 * Sets up the device management on the main configuration page.
2182 */
2183 window.lam.webauthn.setupDeviceManagement = function() {
2184 const searchButton = document.getElementById('btn_webauthn_search');
2185 if (searchButton) {
2186 searchButton.onclick = window.lam.webauthn.searchDevices;
2187 }
2188 const searchInput = document.getElementById('webauthn_searchTerm');
2189 if (searchInput) {
2190 searchInput.onkeydown = function (event) {
2191 if (event.key === "Enter") {
2192 event.preventDefault();
2193 searchButton.click();
2194 return false;
2195 }
2196 };
2197 }
2198 }
2199
2200 /**
2201 * Searches for devices via Ajax call.
2202 *
2203 * @param event button click event
2204 * @returns {boolean} false
2205 */
2206 window.lam.webauthn.searchDevices = function(event) {
2207 if (event !== null) {
2208 event.preventDefault();
2209 }
2210 const resultDiv = document.getElementById('webauthn_results');
2211 const tokenValue = resultDiv.dataset.sec_token_value;
2212 const searchData = document.getElementById('webauthn_searchTerm').value;
2213 let data = new FormData();
2214 data.append('sec_token', tokenValue);
2215 data.append('action', 'search');
2216 data.append('searchTerm', searchData);
2217 fetch('../misc/ajax.php?function=webauthnDevices', {
2218 method: 'POST',
2219 body: data
2220 })
2221 .then(async response => {
2222 const jsonData = await response.json();
2223 resultDiv.innerHTML = jsonData.content;
2224 window.lam.webauthn.addDeviceActionListeners();
2225 })
2226 .catch(function (error) {
2227 console.log('WebAuthn search failed: ' + error.message);
2228 });
2229 return false;
2230 }
2231
2232 /**
2233 * Adds listeners to the device action buttons.
2234 */
2235 window.lam.webauthn.addDeviceActionListeners = function() {
2236 const inputs = document.querySelectorAll('.webauthn-delete');
2237 inputs.forEach(item => {
2238 item.onclick = function(event) {
2239 window.lam.webauthn.removeDevice(event);
2240 return false;
2241 };
2242 });
2243 }
2244
2245 /**
2246 * Removes a webauthn device.
2247 *
2248 * @param event click event
2249 */
2250 window.lam.webauthn.removeDevice = function(event) {
2251 event.preventDefault();
2252 const element = event.target;
2253 window.lam.webauthn.removeDeviceDialog(element, 'webauthnDevices');
2254 }
2255
2256 /**
2257 * Removes a user's own webauthn device.
2258 *
2259 * @param event click event
2260 * @param isSelfService run in self-service or admin context
2261 */
2262 window.lam.webauthn.removeOwnDevice = function(event, isSelfService) {
2263 event.preventDefault();
2264 const element = event.currentTarget;
2265 let successCallback = null;
2266 if (!isSelfService) {
2267 successCallback = function () {
2268 const form = document.getElementById("webauthnform");
2269 const hiddenRemoved = document.createElement('input');
2270 hiddenRemoved.type = 'hidden';
2271 hiddenRemoved.name = 'removed';
2272 hiddenRemoved.value = 'true';
2273 form.appendChild(hiddenRemoved);
2274 form.submit();
2275 };
2276 }
2277 let action = 'webauthnOwnDevices';
2278 if (isSelfService) {
2279 action = action + '&selfservice=true&module=webauthn&scope=user';
2280 }
2281 window.lam.webauthn.removeDeviceDialog(element, action, successCallback, isSelfService);
2282 return false;
2283 }
2284
2285 /**
2286 * Opens the remove device dialog.
2287 *
2288 * @param element delete button
2289 * @param action action for request (delete|deleteOwn)
2290 * @param successCallback callback if all was fine (optional)
2291 * @param isSelfService run in self-service or admin context
2292 */
2293 window.lam.webauthn.removeDeviceDialog = function(element, action, successCallback, isSelfService) {
2294 const dialogTitle = element.dataset.dialogtitle;
2295 const okText = element.dataset.oktext;
2296 const cancelText = element.dataset.canceltext;
2297 const dialogContent = document.getElementById('webauthnDeleteConfirm').cloneNode(true);
2298 dialogContent.classList.remove('hidden');
2299 Swal.fire({
2300 title: dialogTitle,
2301 confirmButtonText: okText,
2302 cancelButtonText: cancelText,
2303 showCancelButton: true,
2304 html: dialogContent.outerHTML,
2305 width: 'auto'
2306 }).then(result => {
2307 if (result.isConfirmed) {
2308 window.lam.webauthn.sendRemoveDeviceRequest(element, action, successCallback, isSelfService);
2309 }
2310 });
2311 }
2312
2313 /**
2314 * Sends the remove request to server.
2315 *
2316 * @param element button element
2317 * @param action action (delete|deleteOwn)
2318 * @param successCallback callback if all was fine (optional)
2319 * @param isSelfService run in self-service or admin context
2320 */
2321 window.lam.webauthn.sendRemoveDeviceRequest = function(element, action, successCallback, isSelfService) {
2322 const dn = element.dataset.dn;
2323 const credential = element.dataset.credential;
2324 const resultDiv = document.getElementById('webauthn_results');
2325 const tokenValue = resultDiv.dataset.sec_token_value;
2326 let data = new FormData();
2327 data.append('sec_token', tokenValue);
2328 data.append('action', 'delete');
2329 data.append('dn', dn);
2330 data.append('credentialId', credential);
2331 if (isSelfService) {
2332 document.querySelectorAll('.webauthn_device_name').forEach(item => {
2333 data.append(item.name, item.value);
2334 });
2335 }
2336 fetch('../misc/ajax.php?function=' + action, {
2337 method: 'POST',
2338 body: data
2339 })
2340 .then(async response => {
2341 const jsonData = await response.json();
2342 if (successCallback) {
2343 successCallback();
2344 }
2345 else {
2346 resultDiv.innerHTML = jsonData.content;
2347 }
2348 })
2349 .catch(function(err) {
2350 console.log('WebAuthn device deletion failed: ' + err.message);
2351 });
2352 }
2353
2354 /**
2355 * Updates a device name.
2356 *
2357 * @param event click event
2358 */
2359 window.lam.webauthn.updateOwnDeviceName = function(event) {
2360 event.preventDefault();
2361 const element = event.currentTarget;
2362 const dn = element.dataset.dn;
2363 const nameElementId = element.dataset.nameelement;
2364 const nameElement = document.getElementById(nameElementId);
2365 const name = nameElement.value;
2366 const credential = element.dataset.credential;
2367 const resultDiv = document.getElementById('webauthn_results');
2368 const tokenValue = resultDiv.dataset.sec_token_value;
2369 let data = new FormData();
2370 data.append('sec_token', tokenValue);
2371 data.append('action', 'setName');
2372 data.append('dn', dn);
2373 data.append('name', name);
2374 data.append('credentialId', credential);
2375 let action = 'webauthnOwnDevices';
2376 fetch('../misc/ajax.php?function=' + action, {
2377 method: 'POST',
2378 body: data
2379 })
2380 .then(async response => {
2381 window.location.href = 'webauthn.php?updated=' + encodeURIComponent(credential);
2382 })
2383 .catch(function(err) {
2384 console.log('WebAuthn device name change failed: ' + err.message);
2385 });
2386 return false;
2387 }
2388
2389 /**
2390 * Registers a user's own webauthn device.
2391 *
2392 * @param event click event
2393 * @param isSelfService runs in self-service context
2394 */
2395 window.lam.webauthn.registerOwnDevice = function(event, isSelfService) {
2396 event.preventDefault();
2397 const element = event.target;
2398 const dn = element.dataset.dn;
2399 const tokenValue = element.dataset.sec_token_value;
2400 const publicKey = JSON.parse(element.dataset.publickey);
2401 let successCallback = function (publicKeyCredential) {
2402 const form = document.getElementById("webauthnform");
2403 const response = btoa(JSON.stringify(publicKeyCredential));
2404 const registrationData = document.getElementById('registrationData');
2405 registrationData.value = response;
2406 form.submit();
2407 };
2408 if (isSelfService) {
2409 successCallback = function (publicKeyCredential) {
2410 let data = new FormData();
2411 data.append('sec_token', tokenValue);
2412 data.append('action', 'register');
2413 data.append('dn', dn);
2414 data.append('credential', btoa(JSON.stringify(publicKeyCredential)));
2415 document.querySelectorAll('.webauthn_device_name').forEach(item => {
2416 data.append(item.name, item.value);
2417 });
2418 fetch('../misc/ajax.php?selfservice=true&module=webauthn&scope=user', {
2419 method: 'POST',
2420 body: data
2421 })
2422 .then(async response => {
2423 const jsonData = await response.json();
2424 const resultDiv = document.getElementById('webauthn_results');
2425 resultDiv.innerHTML = jsonData.content;
2426 })
2427 .catch((error) => {
2428 console.log('WebAuthn device registration failed: ' + error.message);
2429 });
2430 };
2431 }
2432 const errorCallback = function (error) {
2433 const errorDiv = document.getElementById('generic-webauthn-error');
2434 const buttonLabel = errorDiv.dataset.button;
2435 const dialogTitle = errorDiv.dataset.title;
2436 errorDiv.innerText = error.message;
2437 window.lam.dialog.showMessage(dialogTitle,
2438 buttonLabel,
2439 'generic-webauthn-error'
2440 );
2441 };
2442 window.lam.webauthn.register(publicKey, successCallback, errorCallback);
2443 return false;
2444 }
2445
2446 window.lam.treeview = window.lam.treeview || {};
2447
2448 /**
2449 * Creates a new node in tree view.
2450 *
2451 * @param tokenName security token name
2452 * @param tokenValue security token value
2453 * @param dn base64 encode DN
2454 */
2455 window.lam.treeview.createNode = function (tokenName, tokenValue, dn) {
2456 let data = new FormData();
2457 data.append(tokenName, tokenValue);
2458 data.append('dn', dn);
2459 fetch('../misc/ajax.php?function=treeview&command=createNewNode&step=getObjectClasses', {
2460 method: 'POST',
2461 body: data
2462 })
2463 .then(async response => {
2464 const jsonData = await response.json();
2465 window.lam.treeview.checkSession(jsonData);
2466 document.getElementById('ldap_actionarea').innerHTML = jsonData.content;
2467 });
2468 }
2469
2470 /**
2471 * Selects the object classes.
2472 *
2473 * @param event event
2474 * @param tokenName security token name
2475 * @param tokenValue security token value
2476 */
2477 window.lam.treeview.createNodeSelectObjectClassesStep = function (event, tokenName, tokenValue) {
2478 event.preventDefault();
2479 let data = new FormData();
2480 data.append(tokenName, tokenValue);
2481 data.append('dn', document.getElementById('parentDn').value);
2482 const selectedOptions = document.getElementById('objectClasses').selectedOptions;
2483 let objectClasses = [];
2484 for (const selectedOption of selectedOptions) {
2485 objectClasses.push(selectedOption.value);
2486 }
2487 data.append('objectClasses', objectClasses.join(','))
2488 fetch('../misc/ajax.php?function=treeview&command=createNewNode&step=checkObjectClasses', {
2489 method: 'POST',
2490 body: data
2491 })
2492 .then(async response => {
2493 const jsonData = await response.json();
2494 window.lam.treeview.checkSession(jsonData);
2495 document.getElementById('ldap_actionarea').innerHTML = jsonData.content;
2496 window.lam.treeview.addFileInputListeners();
2497 });
2498 }
2499
2500 /**
2501 * Selects the attributes.
2502 *
2503 * @param event event
2504 * @param tokenName security token name
2505 * @param tokenValue security token value
2506 */
2507 window.lam.treeview.createNodeEnterAttributesStep = function (event, tokenName, tokenValue) {
2508 event.preventDefault();
2509 let data = new FormData();
2510 data.append(tokenName, tokenValue);
2511 const parentDn = document.getElementById('parentDn').value;
2512 data.append('dn', parentDn);
2513 data.append('rdn', document.getElementById('rdn').value);
2514 data.append('objectClasses', document.getElementById('objectClasses').value);
2515 // clear old values in data
2516 document.querySelectorAll('.single-input').forEach(item => {
2517 item.dataset.valueOrig = '';
2518 }
2519 );
2520 document.querySelectorAll('.multi-input').forEach(item => {
2521 item.dataset.valueOrig = '';
2522 }
2523 );
2524 // get attribute values
2525 const attributeChanges = window.lam.treeview.findAttributeChanges();
2526 data.append('attributes', JSON.stringify(attributeChanges));
2527 fetch("../misc/ajax.php?function=treeview&command=createNewNode&step=checkAttributes", {
2528 method: 'POST',
2529 body: data
2530 })
2531 .then(async response => {
2532 const jsonData = await response.json();
2533 window.lam.treeview.checkSession(jsonData);
2534 document.getElementById('ldap_actionarea').innerHTML = jsonData.content;
2535 const tree = mar10.Wunderbaum.getTree("#ldap_tree");
2536 const node = tree.findKey(parentDn);
2537 if (node) {
2538 await node.setExpanded(true);
2539 node.lazy = true;
2540 node.loadLazy(true);
2541 }
2542 window.scrollTo(0, 0);
2543 });
2544 }
2545
2546 /**
2547 * Deletes a node in tree view.
2548 *
2549 * @param tokenName security token name
2550 * @param tokenValue security token value
2551 * @param dn base64 encoded DN
2552 * @param text text for dialog body
2553 * @param okText text for OK button
2554 * @param cancelText text for cancel button
2555 * @param title dialog title
2556 * @param errorOkText text for OK button in error dialog
2557 * @param errorTitle dialog title in case of error
2558 */
2559 window.lam.treeview.deleteNode = function (tokenName, tokenValue, dn, text, okText, cancelText, title, errorOkText, errorTitle) {
2560 const textSpan = document.querySelector('.treeview-delete-entry');
2561 textSpan.innerText = window.atob(text);
2562 const dialogContent = document.getElementById('treeview_delete_dlg').cloneNode(true);
2563 dialogContent.classList.remove('hidden');
2564 Swal.fire({
2565 title: title,
2566 confirmButtonText: okText,
2567 cancelButtonText: cancelText,
2568 showCancelButton: true,
2569 html: dialogContent.outerHTML,
2570 width: '48em'
2571 }).then(result => {
2572 if (result.isConfirmed) {
2573 let data = new FormData();
2574 data.append(tokenName, tokenValue);
2575 data.append('dn', dn)
2576 fetch("../misc/ajax.php?function=treeview&command=deleteNode", {
2577 method: 'POST',
2578 body: data
2579 })
2580 .then(async response => {
2581 const jsonData = await response.json();
2582 window.lam.treeview.checkSession(jsonData);
2583 const tree = mar10.Wunderbaum.getTree("#ldap_tree");
2584 const parentNode = tree.findKey(dn).parent;
2585 await parentNode.setActive();
2586 parentNode.loadLazy(true);
2587 window.lam.treeview.getNodeContent(tokenName, tokenValue, parentNode.key);
2588 if (jsonData['errors']) {
2589 const errTextTitle = jsonData['errors'][0][1];
2590 const textSpanErrorTitle = document.querySelector('.treeview-error-title');
2591 textSpanErrorTitle.innerText = errTextTitle;
2592 const errText = jsonData['errors'][0][2];
2593 const textSpanErrorText = document.querySelector('.treeview-error-text');
2594 textSpanErrorText.innerText = errText;
2595 window.lam.dialog.showSimpleDialog(errorTitle, null, errorOkText, null, 'treeview_error_dlg');
2596 }
2597 });
2598 }
2599 });
2600 }
2601
2602 /**
2603 * Restores a node in tree view.
2604 *
2605 * @param tokenName security token name
2606 * @param tokenValue security token value
2607 * @param dn base64 encoded DN
2608 * @param text text for dialog body
2609 * @param okText text for OK button
2610 * @param cancelText text for cancel button
2611 * @param title dialog title
2612 * @param errorOkText text for OK button in error dialog
2613 * @param errorTitle dialog title in case of error
2614 */
2615 window.lam.treeview.restoreNode = function (tokenName, tokenValue, dn, text, okText, cancelText, title, errorOkText, errorTitle) {
2616 const textSpan = document.querySelector('.treeview-restore-entry');
2617 textSpan.innerText = window.atob(text);
2618 const dialogContent = document.getElementById('treeview_restore_dlg').cloneNode(true);
2619 dialogContent.classList.remove('hidden');
2620 const targetDn = document.getElementById('treeview-restore-dn').value;
2621 Swal.fire({
2622 title: title,
2623 confirmButtonText: okText,
2624 cancelButtonText: cancelText,
2625 showCancelButton: true,
2626 html: dialogContent.outerHTML,
2627 width: '48em'
2628 }).then(result => {
2629 if (result.isConfirmed) {
2630 let data = new FormData();
2631 data.append(tokenName, tokenValue);
2632 data.append('dn', dn)
2633 data.append('targetDn', targetDn)
2634 fetch("../misc/ajax.php?function=treeview&command=restoreNode", {
2635 method: 'POST',
2636 body: data
2637 })
2638 .then(async response => {
2639 const jsonData = await response.json();
2640 window.lam.treeview.checkSession(jsonData);
2641 const tree = mar10.Wunderbaum.getTree("#ldap_tree");
2642 const parentNode = tree.findKey(dn).parent;
2643 await parentNode.setActive();
2644 parentNode.loadLazy(true);
2645 window.lam.treeview.getNodeContent(tokenName, tokenValue, parentNode.key);
2646 if (jsonData['errorTitle']) {
2647 const errTextTitle = jsonData['errorTitle'];
2648 const textSpanErrorTitle = document.querySelector('.treeview-error-title');
2649 textSpanErrorTitle.innerText = errTextTitle;
2650 const errText = jsonData['errorText'];
2651 const textSpanErrorText = document.querySelector('.treeview-error-text');
2652 textSpanErrorText.innerText = errText;
2653 window.lam.dialog.showSimpleDialog(errorTitle, null, errorOkText, null, 'treeview_error_dlg');
2654 }
2655 });
2656 }
2657 });
2658 }
2659
2660 /**
2661 * Returns the node content in tree view action area.
2662 *
2663 * @param tokenName security token name
2664 * @param tokenValue security token value
2665 * @param dn DN (base64 encoded)
2666 * @param messages any messages that should be displayed (HTML code)
2667 * @param attributesToHighlight attributes to highlight
2668 */
2669 window.lam.treeview.getNodeContent = function (tokenName, tokenValue, dn, messages, attributesToHighlight) {
2670 let data = new FormData();
2671 data.append(tokenName, tokenValue);
2672 data.append('dn', dn);
2673 data.append('highlight', (attributesToHighlight) ? attributesToHighlight : '');
2674 fetch("../misc/ajax.php?function=treeview&command=getNodeContent", {
2675 method: 'POST',
2676 body: data
2677 })
2678 .then(async response => {
2679 const jsonData = await response.json();
2680 window.lam.treeview.checkSession(jsonData);
2681 document.getElementById('ldap_actionarea').innerHTML = jsonData.content;
2682 if (messages) {
2683 document.getElementById('ldap_actionarea_messages').innerHTML = messages;
2684 }
2685 window.scrollTo(0, 0);
2686 window.lam.html.activateLightboxes();
2687 window.lam.treeview.addFileInputListeners();
2688 window.lam.treeview.activateSortableInputs();
2689 window.lam.treeview.setActionButtonsVisibility(dn);
2690 });
2691 }
2692
2693 /**
2694 * Adds a listener to each file input to write the file content to a data attribute.
2695 */
2696 window.lam.treeview.addFileInputListeners = function () {
2697 document.querySelectorAll('.image-upload').forEach(input => {
2698 input.addEventListener('change', function () {
2699 const files = input.files;
2700 if (!files[0]) {
2701 return;
2702 }
2703 const reader = new FileReader();
2704 reader.onload = function () {
2705 const content = btoa(reader.result);
2706 input.dataset.dataBinary = content;
2707 };
2708 reader.readAsBinaryString(files[0]);
2709 });
2710 });
2711 }
2712
2713 /**
2714 * Activates the sortable feature for lists.
2715 */
2716 window.lam.treeview.activateSortableInputs = function () {
2717 document.querySelectorAll('.tree-attribute-sorted-list').forEach(list => {
2718 const listId = list.id;
2719 Sortable.create(
2720 document.getElementById(listId),
2721 {
2722 onUpdate: function() {
2723 window.lam.treeview.updateAttributePositionData(listId);
2724 }
2725 }
2726 );
2727 });
2728 }
2729
2730 /**
2731 * Sets the visibility of the action buttons.
2732 *
2733 * @param dn current DN (base64 encoded)
2734 */
2735 window.lam.treeview.setActionButtonsVisibility = function (dn) {
2736 const pasteButton = document.getElementById('action_button_paste');
2737 if (pasteButton) {
2738 const copyPasteDn = window.sessionStorage.getItem('LAM_COPY_PASTE_DN');
2739 if (copyPasteDn === null) {
2740 pasteButton.classList.add('hidden');
2741 }
2742 else {
2743 pasteButton.classList.remove('hidden');
2744 }
2745 }
2746 const addToCompareButton = document.getElementById('action_button_compare_add');
2747 if (addToCompareButton) {
2748 const compareDNs = window.lam.treeview.getComparisonDNs();
2749 if (compareDNs.includes(dn)) {
2750 addToCompareButton.classList.add('hidden');
2751 }
2752 else {
2753 addToCompareButton.classList.remove('hidden');
2754 }
2755 }
2756 const removeFromCompareButton = document.getElementById('action_button_compare_remove');
2757 if (removeFromCompareButton) {
2758 const compareDNs = window.lam.treeview.getComparisonDNs();
2759 if (compareDNs.includes(dn)) {
2760 removeFromCompareButton.classList.remove('hidden');
2761 }
2762 else {
2763 removeFromCompareButton.classList.add('hidden');
2764 }
2765 }
2766 const startCompareButton = document.getElementById('action_button_compare');
2767 if (startCompareButton) {
2768 const compareDNs = window.lam.treeview.getComparisonDNs();
2769 if (compareDNs.length > 1) {
2770 startCompareButton.classList.remove('hidden');
2771 }
2772 else {
2773 startCompareButton.classList.add('hidden');
2774 }
2775 }
2776 }
2777
2778 /**
2779 * Saves the attributes in tree view action area.
2780 *
2781 * @param event event
2782 * @param tokenName security token name
2783 * @param tokenValue security token value
2784 * @param dn DN
2785 */
2786 window.lam.treeview.saveAttributes = function (event, tokenName, tokenValue, dn) {
2787 event.preventDefault();
2788 let data = new FormData();
2789 data.append(tokenName, tokenValue);
2790 data.append('dn', dn);
2791 const attributeChanges = window.lam.treeview.findAttributeChanges();
2792 const attributesToHighlight = Object.keys(attributeChanges).join(',');
2793 data.append('changes', JSON.stringify(attributeChanges));
2794 fetch("../misc/ajax.php?function=treeview&command=saveAttributes", {
2795 method: 'POST',
2796 body: data
2797 })
2798 .then(async response => {
2799 const jsonData = await response.json();
2800 window.lam.treeview.checkSession(jsonData);
2801 if (jsonData.newDn) {
2802 const tree = mar10.Wunderbaum.getTree("#ldap_tree");
2803 tree.findKey(jsonData['parent']).loadLazy(true);
2804 window.lam.treeview.getNodeContent(tokenName, tokenValue, jsonData.newDn, jsonData.result, attributesToHighlight);
2805 }
2806 else {
2807 window.lam.treeview.getNodeContent(tokenName, tokenValue, dn, jsonData.result, attributesToHighlight);
2808 }
2809 });
2810 }
2811
2812 /**
2813 * Finds the attributes that were changed by the user.
2814 *
2815 * @returns list of changes
2816 */
2817 window.lam.treeview.findAttributeChanges = function () {
2818 let attributeChanges = {};
2819 document.querySelectorAll('.single-input').forEach(input => {
2820 if (window.lam.utility.isHidden(input)) {
2821 return;
2822 }
2823 const attrName = input.dataset.attrName;
2824 // avoid type conversion in .data()
2825 const valueOrig = input.dataset.valueOrig;
2826 const valueNew = input.value;
2827 if (valueNew != valueOrig) {
2828 attributeChanges[attrName] = {
2829 old: [valueOrig]
2830 };
2831 if (valueNew == '') {
2832 attributeChanges[attrName]["new"] = [];
2833 }
2834 else {
2835 attributeChanges[attrName]["new"] = [valueNew];
2836 }
2837 }
2838 }
2839 );
2840 let lastAttrName = '';
2841 let lastAttrValuesNew = [];
2842 let lastAttrValuesOld = [];
2843 let lastAttrHasChange = false;
2844 document.querySelectorAll('.multi-input').forEach(input => {
2845 if (window.lam.utility.isHidden(input)) {
2846 return;
2847 }
2848 const attrName = input.dataset.attrName;
2849 if (attrName != lastAttrName) {
2850 if (lastAttrHasChange) {
2851 attributeChanges[lastAttrName] = {
2852 old: lastAttrValuesOld,
2853 new: lastAttrValuesNew
2854 };
2855 }
2856 // reset
2857 lastAttrHasChange = false;
2858 lastAttrName = attrName;
2859 lastAttrValuesNew = [];
2860 lastAttrValuesOld = [];
2861 }
2862 // avoid type conversion in .data()
2863 const valueOrig = input.dataset.valueOrig;
2864 const valueNew = input.value;
2865 if (valueOrig != '') {
2866 lastAttrValuesOld.push(valueOrig);
2867 }
2868 if (valueNew != '') {
2869 lastAttrValuesNew.push(valueNew);
2870 }
2871 if (valueNew != valueOrig) {
2872 lastAttrHasChange = true;
2873 }
2874 }
2875 );
2876 if (lastAttrHasChange) {
2877 attributeChanges[lastAttrName] = {
2878 old: lastAttrValuesOld,
2879 new: lastAttrValuesNew
2880 };
2881 }
2882 document.querySelectorAll('.hash-select').forEach(input => {
2883 const attrName = input.dataset.attrName;
2884 if (!attributeChanges[attrName]) {
2885 return;
2886 }
2887 if (!attributeChanges[attrName]['hash']) {
2888 attributeChanges[attrName]['hash'] = [input.value];
2889 }
2890 else {
2891 attributeChanges[attrName]['hash'].push(input.value);
2892 }
2893 }
2894 );
2895 document.querySelectorAll('.image-input').forEach(input => {
2896 const toDelete = input.dataset.delete;
2897 if (toDelete !== 'true') {
2898 return;
2899 }
2900 const attrName = input.dataset.attrName;
2901 const attrIndex = input.dataset.index;
2902 if (!attrIndex) {
2903 return;
2904 }
2905 if (!attributeChanges[attrName]) {
2906 attributeChanges[attrName] = {delete: [attrIndex]};
2907 }
2908 else {
2909 attributeChanges[attrName]['delete'].push(attrIndex);
2910 }
2911 }
2912 );
2913 document.querySelectorAll('.image-upload').forEach(input => {
2914 const content = input.dataset.dataBinary;
2915 if (!content) {
2916 return;
2917 }
2918 const attrName = input.dataset.attrName;
2919 if (!attrName) {
2920 return;
2921 }
2922 if (!attributeChanges[attrName]) {
2923 attributeChanges[attrName] = {upload: content};
2924 }
2925 else {
2926 attributeChanges[attrName]['upload'] = content;
2927 }
2928 }
2929 );
2930 return attributeChanges;
2931 }
2932
2933 /**
2934 * Clears an LDAP attribute input field.
2935 *
2936 * @param event event
2937 * @param link link object
2938 */
2939 window.lam.treeview.clearValue = function (event, link) {
2940 event.preventDefault();
2941 const parentTr = link.closest('tr');
2942 const input = parentTr.querySelector('input, textarea');
2943 if (input !== null) {
2944 input.value = '';
2945 }
2946 const image = parentTr.querySelector('.image-input');
2947 if (image) {
2948 parentTr.classList.add('hidden');
2949 image.dataset.delete = 'true';
2950 }
2951 }
2952
2953 /**
2954 * Adds an LDAP attribute input field.
2955 *
2956 * @param event event
2957 * @param link link object
2958 */
2959 window.lam.treeview.addValue = function (event, link) {
2960 event.preventDefault();
2961 const parentTr = link.closest('tr');
2962 const newTr = parentTr.cloneNode(true);
2963 const newField = newTr.querySelector('input, textarea');
2964 newField.value = '';
2965 newField.dataset.valueOrig = '';
2966 parentTr.after(newTr);
2967 }
2968
2969 /**
2970 * Updates the list of possible new attributes to add.
2971 *
2972 * @param tokenName security token name
2973 * @param tokenValue security token value
2974 */
2975 window.lam.treeview.updatePossibleNewAttributes = function(tokenName, tokenValue) {
2976 // cancel running request
2977 if (window.lam.treeview.updatePossibleNewAttributesRequest) {
2978 window.lam.treeview.updatePossibleNewAttributesRequest.abort();
2979 window.lam.treeview.updatePossibleNewAttributesRequest = null;
2980 }
2981 const fields = document.querySelectorAll('.lam-attr-objectclass');
2982 // setup listener
2983 const listener = function() {
2984 window.lam.treeview.updatePossibleNewAttributes(tokenName, tokenValue);
2985 };
2986 fields.forEach(function(field) {
2987 field.removeEventListener('change', listener)
2988 field.addEventListener('change', listener);
2989 });
2990 let objectCLasses = [];
2991 fields.forEach(function(field) {
2992 objectCLasses.push(field.value);
2993 });
2994 let data = new FormData();
2995 data.append('dn', 'none');
2996 data.append(tokenName, tokenValue);
2997 data.append('objectClasses', JSON.stringify(objectCLasses));
2998 fetch("../misc/ajax.php?function=treeview&command=getPossibleNewAttributes", {
2999 method: 'POST',
3000 body: data
3001 })
3002 .then(async response => {
3003 const jsonData = await response.json();
3004 window.lam.treeview.checkSession(jsonData);
3005 const select = document.getElementById('newAttribute');
3006 select.innerHTML = '';
3007 const existingAttributeFieldNames = [];
3008 document.querySelectorAll('.attribute-field').forEach(input => {
3009 if (input.dataset.attrName) {
3010 existingAttributeFieldNames.push(input.dataset.attrName);
3011 }
3012 });
3013 const data = jsonData['data'];
3014 for (const attributeName in data) {
3015 if (existingAttributeFieldNames.includes(attributeName)) {
3016 continue;
3017 }
3018 const option = document.createElement('option');
3019 option.value = data[attributeName];
3020 option.innerText = attributeName;
3021 select.appendChild(option);
3022 }
3023 window.lam.treeview.updatePossibleNewAttributesRequest = null;
3024 });
3025 }
3026
3027 window.lam.treeview.updatePossibleNewAttributesRequest = null;
3028
3029 /**
3030 * Adds the input field for a new attribute.
3031 *
3032 * @param event event
3033 * @param select select object
3034 */
3035 window.lam.treeview.addAttributeField = function (event, select) {
3036 event.preventDefault();
3037 let attributeParts = select.value;
3038 if (attributeParts == '') {
3039 return;
3040 }
3041 select.options.remove(select.options.selectedIndex);
3042 attributeParts = attributeParts.split('__#__');
3043 const attributeName = attributeParts[0];
3044 const isSingleValue = attributeParts[1];
3045 const fieldType = attributeParts[2];
3046 const placeHolderId = 'new-attributes-' + isSingleValue + '-' + fieldType;
3047 let newContent = document.getElementById(placeHolderId).querySelector('.row').cloneNode(true);
3048 newContent.children[0].innerText = attributeName;
3049 const inputField = newContent.querySelector('input, textarea');
3050 inputField.dataset.attrName = attributeName;
3051 inputField.name = 'lam_attr_' + attributeName;
3052 inputField.id = 'lam_attr_' + attributeName;
3053 const hashSelect = newContent.querySelector('.hash-select');
3054 if (hashSelect) {
3055 hashSelect.id = 'lam_hash_' + attributeName;
3056 hashSelect.name = 'lam_hash_' + attributeName;
3057 hashSelect.dataset.attrName = attributeName;
3058 }
3059 newContent = [...newContent.children];
3060 while (newContent.length > 0) {
3061 select.closest('div').after(newContent.pop());
3062 }
3063 window.lam.treeview.addFileInputListeners();
3064 }
3065
3066 /**
3067 * Returns the internal attributes content in tree view action area.
3068 *
3069 * @param event event
3070 * @param tokenName security token name
3071 * @param tokenValue security token value
3072 * @param dn DN
3073 */
3074 window.lam.treeview.getInternalAttributesContent = function (event, tokenName, tokenValue, dn) {
3075 event.preventDefault();
3076 let data = new FormData();
3077 data.append(tokenName, tokenValue);
3078 data.append('dn', dn);
3079 fetch("../misc/ajax.php?function=treeview&command=getInternalAttributesContent", {
3080 method: 'POST',
3081 body: data
3082 })
3083 .then(async response => {
3084 const jsonData = await response.json();
3085 window.lam.treeview.checkSession(jsonData);
3086 document.getElementById('actionarea-internal-attributes').innerHTML = jsonData.content;
3087 });
3088 }
3089
3090 /**
3091 * Searches the LDAP tree.
3092 *
3093 * @param tokenName security token name
3094 * @param tokenValue security token value
3095 * @param dn DN (base64 encoded)
3096 */
3097 window.lam.treeview.search = function (tokenName, tokenValue, dn) {
3098 let data = new FormData();
3099 data.append(tokenName, tokenValue);
3100 data.append('dn', dn);
3101 fetch("../misc/ajax.php?function=treeview&command=search", {
3102 method: 'POST',
3103 body: data
3104 })
3105 .then(async response => {
3106 const jsonData = await response.json();
3107 window.lam.treeview.checkSession(jsonData);
3108 document.getElementById('ldap_actionarea').innerHTML = jsonData.content;
3109 window.scrollTo(0, 0);
3110 });
3111 }
3112
3113 /**
3114 * Displays the search results.
3115 *
3116 * @param event event
3117 * @param tokenName security token name
3118 * @param tokenValue security token value
3119 * @param dn DN (base64 encoded)
3120 */
3121 window.lam.treeview.searchResults = function (event, tokenName, tokenValue, dn) {
3122 event.preventDefault();
3123 let data = new FormData();
3124 data.append(tokenName, tokenValue);
3125 data.append('dn', dn);
3126 data.append('scope', document.getElementById('scope').value);
3127 data.append('filter', document.getElementById('filter').value);
3128 data.append('attributes', document.getElementById('attributes').value);
3129 data.append('orderBy', document.getElementById('orderBy').value);
3130 data.append('limit', document.getElementById('limit').value);
3131 data.append('format', document.getElementById('format').value);
3132 fetch("../misc/ajax.php?function=treeview&command=searchResults", {
3133 method: 'POST',
3134 body: data
3135 })
3136 .then(async response => {
3137 const jsonData = await response.json();
3138 window.lam.treeview.checkSession(jsonData);
3139 document.getElementById('ldap_actionarea').innerHTML = jsonData.content;
3140 window.scrollTo(0, 0);
3141 });
3142 }
3143
3144 /**
3145 * Opens the given node IDs.
3146 *
3147 * @param tree tree object
3148 * @param ids array of node IDs.
3149 */
3150 window.lam.treeview.openInitial = async function (tree, ids) {
3151 if (ids.length === 0) {
3152 return;
3153 }
3154 let lastNode = null;
3155 for (const id of ids) {
3156 const node = tree.findKey(id);
3157 if (node) {
3158 await node.setExpanded();
3159 lastNode = node;
3160 }
3161 }
3162 if (lastNode) {
3163 await lastNode.setActive();
3164 }
3165 }
3166
3167 /**
3168 * Copies a node in the tree.
3169 *
3170 * @param dn base64 encoded DN
3171 */
3172 window.lam.treeview.copyNode = function(dn) {
3173 if (!window.sessionStorage) {
3174 return;
3175 }
3176 const tree = mar10.Wunderbaum.getTree("#ldap_tree");
3177 const node = tree.findKey(dn);
3178 window.sessionStorage.setItem('LAM_COPY_PASTE_ACTION', 'COPY');
3179 const oldNodeDn = window.sessionStorage.getItem('LAM_COPY_PASTE_DN');
3180 if (oldNodeDn) {
3181 const oldNode = tree.findKey(oldNodeDn);
3182 if (oldNode) {
3183 oldNode.data.badge = null;
3184 oldNode.update();
3185 }
3186 }
3187 window.sessionStorage.setItem('LAM_COPY_PASTE_DN', node.key);
3188 node.data.badge = '../../graphics/copy.svg';
3189 node.update();
3190 window.lam.treeview.setActionButtonsVisibility(dn);
3191 }
3192
3193 /**
3194 * Cuts a node in the tree.
3195 *
3196 * @param dn base64 encoded DN
3197 */
3198 window.lam.treeview.cutNode = function(dn) {
3199 if (!window.sessionStorage) {
3200 return;
3201 }
3202 const tree = mar10.Wunderbaum.getTree("#ldap_tree");
3203 const node = tree.findKey(dn);
3204 window.sessionStorage.setItem('LAM_COPY_PASTE_ACTION', 'CUT');
3205 const oldNodeDn = window.sessionStorage.getItem('LAM_COPY_PASTE_DN');
3206 if (oldNodeDn) {
3207 const oldNode = tree.findKey(oldNodeDn);
3208 if (oldNode) {
3209 oldNode.data.badge = null;
3210 oldNode.update();
3211 }
3212 }
3213 window.sessionStorage.setItem('LAM_COPY_PASTE_DN', node.key);
3214 node.data.badge = '../../graphics/cut.svg';
3215 node.update();
3216 window.lam.treeview.setActionButtonsVisibility(dn);
3217 }
3218
3219 /**
3220 * Pastes a copied/cut node.
3221 *
3222 * @param tokenName security token name
3223 * @param tokenValue security token value
3224 * @param destinationDn base64 encoded DN
3225 */
3226 window.lam.treeview.pasteNode = function (tokenName, tokenValue, destinationDn) {
3227 const dn = window.sessionStorage.getItem('LAM_COPY_PASTE_DN');
3228 if (!dn) {
3229 return;
3230 }
3231 const tree = mar10.Wunderbaum.getTree("#ldap_tree");
3232 const action = window.sessionStorage.getItem('LAM_COPY_PASTE_ACTION');
3233 let data = new FormData();
3234 data.append(tokenName, tokenValue);
3235 data.append('dn', dn);
3236 data.append('targetDn', destinationDn);
3237 data.append('action', action);
3238 fetch('../misc/ajax.php?function=treeview&command=paste', {
3239 method: 'POST',
3240 body: data
3241 })
3242 .then(async response => {
3243 const jsonData = await response.json();
3244 window.lam.treeview.checkSession(jsonData);
3245 if (jsonData.error) {
3246 document.getElementById('ldap_actionarea_messages').innerHTML = jsonData.error;
3247 return;
3248 }
3249 window.sessionStorage.removeItem('LAM_COPY_PASTE_ACTION');
3250 window.sessionStorage.removeItem('LAM_COPY_PASTE_DN');
3251 const oldNode = tree.findKey(dn);
3252 if (action == 'CUT') {
3253 const parentNode = oldNode.parent;
3254 parentNode.loadLazy(true);
3255 }
3256 else {
3257 oldNode.data.badge = null;
3258 oldNode.update();
3259 }
3260 const newParentNode = tree.findKey(destinationDn);
3261 newParentNode.lazy = true;
3262 newParentNode.expanded = true;
3263 newParentNode.loadLazy(true);
3264 window.lam.treeview.setActionButtonsVisibility(dn);
3265 });
3266 }
3267
3268 /**
3269 * Adds a DN to the comparison.
3270 *
3271 * @param dn DN (base64 encoded)
3272 */
3273 window.lam.treeview.addToComparison = function(dn) {
3274 let comparisonDNs = window.lam.treeview.getComparisonDNs();
3275 if (comparisonDNs.includes(dn)) {
3276 return;
3277 }
3278 comparisonDNs.push(dn);
3279 window.lam.treeview.setComparisonDNs(comparisonDNs);
3280 window.lam.treeview.setActionButtonsVisibility(dn);
3281 }
3282
3283 /**
3284 * Removes a DN from the comparison.
3285 *
3286 * @param dn DN (base64 encoded)
3287 */
3288 window.lam.treeview.removeFromComparison = function(dn) {
3289 let comparisonDNs = window.lam.treeview.getComparisonDNs();
3290 if (!comparisonDNs.includes(dn)) {
3291 return;
3292 }
3293 comparisonDNs.splice(comparisonDNs.indexOf(dn), 1);
3294 window.lam.treeview.setComparisonDNs(comparisonDNs);
3295 window.lam.treeview.setActionButtonsVisibility(dn);
3296 }
3297
3298 /**
3299 * Compares the selected DNs.
3300 *
3301 * @param tokenName security token name
3302 * @param tokenValue security token value
3303 * @param dn DN
3304 */
3305 window.lam.treeview.openComparison = function(tokenName, tokenValue, dn) {
3306 const comparisonDNs = window.lam.treeview.getComparisonDNs();
3307 if (comparisonDNs.length < 2) {
3308 return;
3309 }
3310 let data = new FormData();
3311 data.append(tokenName, tokenValue);
3312 data.append('dnList', comparisonDNs.join(','));
3313 data.append('dn', dn);
3314 fetch("../misc/ajax.php?function=treeview&command=compare", {
3315 method: 'POST',
3316 body: data
3317 })
3318 .then(async response => {
3319 const jsonData = await response.json();
3320 window.lam.treeview.checkSession(jsonData);
3321 document.getElementById('ldap_actionarea').innerHTML = jsonData.content;
3322 window.scrollTo(0, 0);
3323 });
3324 }
3325
3326 /**
3327 * Returns the comparison DNs.
3328 *
3329 * @return the comparison DNs
3330 */
3331 window.lam.treeview.getComparisonDNs = function() {
3332 const comparisonDNs = window.sessionStorage.getItem('LAM_COMPARE_DNS');
3333 return (comparisonDNs) ? comparisonDNs.split(',') : [];
3334 }
3335
3336 /**
3337 * Sets the comparison DNs.
3338 *
3339 * @param dnList the comparison DNs
3340 */
3341 window.lam.treeview.setComparisonDNs = function(dnList) {
3342 window.sessionStorage.setItem('LAM_COMPARE_DNS', dnList.join(','));
3343 }
3344
3345 /**
3346 * Checks if the session expired and redirects to login.
3347 *
3348 * @param json JSON response
3349 */
3350 window.lam.treeview.checkSession = function(json) {
3351 if (json && (json.sessionExpired == 'true')) {
3352 location.href = '../login.php?expired=yes';
3353 }
3354 }
3355
3356 /**
3357 * Checks if the password matches a given value.
3358 *
3359 * @param event event
3360 * @param element element
3361 * @param tokenName security token name
3362 * @param tokenValue security token value
3363 * @param title dialog title
3364 * @param checkText label for check button
3365 * @param cancelText label for cancel button
3366 * @param okText label for ok button
3367 */
3368 window.lam.treeview.checkPassword = function(event, element, tokenName, tokenValue, title,
3369 checkText, cancelText, okText) {
3370 event.preventDefault();
3371 const outputDiv = document.getElementById('lam-pwd-check-dialog-result');
3372 outputDiv.innerHTML = '';
3373 const dialogContent = document.getElementById('lam-pwd-check-dialog').cloneNode(true);
3374 dialogContent.classList.remove('hidden');
3375 dialogContent.querySelector('.lam_pwd_check').classList.add('lam_pwd_check_dlg');
3376 Swal.fire({
3377 title: title,
3378 confirmButtonText: checkText,
3379 cancelButtonText: cancelText,
3380 showCancelButton: true,
3381 html: dialogContent.outerHTML,
3382 width: '48em'
3383 }).then(result => {
3384 if (result.isConfirmed) {
3385 const hashValue = element.closest('table').querySelector('input[type=password]').value;
3386 const checkValue = document.querySelector('.lam_pwd_check_dlg').value;
3387 let data = new FormData();
3388 data.append('jsonInput', '');
3389 data.append(tokenName, tokenValue);
3390 data.append('hashValue', hashValue);
3391 data.append('checkValue', checkValue);
3392 fetch("../misc/ajax.php?function=checkPassword", {
3393 method: 'POST',
3394 body: data
3395 })
3396 .then(async response => {
3397 const jsonData = await response.json();
3398 if (jsonData.resultHtml) {
3399 outputDiv.innerHTML = jsonData.resultHtml;
3400 window.lam.dialog.showSimpleDialog(null, null, okText, null, 'lam-pwd-check-dialog-result');
3401 }
3402 });
3403 }
3404 });
3405 }
3406
3407 /**
3408 * Updates the positions of a sorted list of LDAP values.
3409 *
3410 * @param containerId HTML ID of ul-container
3411 */
3412 window.lam.treeview.updateAttributePositionData = function(containerId) {
3413 const container = document.getElementById(containerId);
3414 const childLiElements = container.children;
3415 for (let i = 0; i < childLiElements.length; i++) {
3416 let inputField = childLiElements[i].querySelector('input');
3417 if (inputField === null) {
3418 inputField = childLiElements[i].querySelector('textarea');
3419 }
3420 inputField.value = '{' + i + '}' + inputField.value.replace(/^\{[0-9]+\}/, '');
3421 }
3422 }
3423
3424 window.lam.topmenu = window.lam.topmenu || {};
3425
3426 /**
3427 * Toggles the top navigation menu.
3428 */
3429 window.lam.topmenu.toggle = function() {
3430 var topnav = document.getElementById('lam-topnav');
3431 if (topnav.className == 'lam-header') {
3432 topnav.className = 'lam-header lam-header-open';
3433 }
3434 else {
3435 topnav.className = 'lam-header';
3436 }
3437 }
3438
3439 /**
3440 * Opens a submenu of the top navigation.
3441 *
3442 * @param event event
3443 * @param layerId layer ID
3444 * @param listener close listener
3445 */
3446 window.lam.topmenu.openSubmenu = function(event, layerId, listener) {
3447 const layer = document.getElementById(layerId);
3448 if (layer.style.height && (layer.style.height !== '0px')) {
3449 // no action if already open
3450 return;
3451 }
3452 document.removeEventListener("click", listener);
3453 document.removeEventListener("mouseover", listener);
3454 event.preventDefault();
3455 event.stopImmediatePropagation();
3456 let layers = document.getElementsByClassName('lam-navigation-layer');
3457 for (let i = 0; i < layers.length; i++) {
3458 layers[i].style.height = "0px";
3459 }
3460 const height = layer.getElementsByClassName('lam-navigation-layer-content')[0].offsetHeight;
3461 layer.style.height = height + 'px';
3462 window.lam.topmenu.lastOpened = new Date().getTime();
3463 document.addEventListener("click", listener);
3464 document.addEventListener("mouseover", listener);
3465 }
3466
3467 /**
3468 * Close listener for tools flyout.
3469 *
3470 * @param event event
3471 */
3472 window.lam.topmenu.subMenuCloseListenerTools = function (event) {
3473 const timeLimit = new Date().getTime() - 100;
3474 if (!window.lam.topmenu.lastOpened || (timeLimit < window.lam.topmenu.lastOpened)) {
3475 return;
3476 }
3477 if ((event.type == 'click') && !event.target.closest('#lam-navigation-tools')) {
3478 document.getElementById('lam-navigation-tools').style.height = "0px";
3479 }
3480 if ((event.type == 'mouseover') && !event.target.closest('#lam-topnav')) {
3481 document.getElementById('lam-navigation-tools').style.height = "0px";
3482 }
3483 }
3484
3485 /**
3486 * Close listener for account types flyout.
3487 *
3488 * @param event event
3489 */
3490 window.lam.topmenu.subMenuCloseListenerTypes = function (event) {
3491 const timeLimit = new Date().getTime() - 100;
3492 if (!window.lam.topmenu.lastOpened || (timeLimit < window.lam.topmenu.lastOpened)) {
3493 return;
3494 }
3495 if ((event.type == 'click') && !event.target.closest('#lam-navigation-types')) {
3496 document.getElementById('lam-navigation-types').style.height = "0px";
3497 }
3498 if ((event.type == 'mouseover') && !event.target.closest('#lam-topnav')) {
3499 document.getElementById('lam-navigation-types').style.height = "0px";
3500 }
3501 }
3502
3503 window.lam.tabs = window.lam.tabs || {};
3504
3505 window.lam.tabs.init = function() {
3506 const tabs = document.querySelectorAll('li.lam-tab');
3507 tabs.forEach(function(element) {
3508 if (element.dataset.tabid) {
3509 element.onclick = function() {
3510 window.lam.tabs.tabClick(element);
3511 return false;
3512 };
3513 }
3514 });
3515 }
3516
3517 window.lam.tabs.tabClick = function(element) {
3518 const tabId = element.dataset.tabid;
3519 const contents = document.querySelectorAll('div.lam-tab-content');
3520 contents.forEach(function (element) {
3521 if (element.dataset.tabid == tabId) {
3522 element.classList.add('lam-tab-active');
3523 } else {
3524 element.classList.remove('lam-tab-active');
3525 }
3526 });
3527 const tabs = document.querySelectorAll('li.lam-tab');
3528 tabs.forEach(function (element) {
3529 if (element.dataset.tabid == tabId) {
3530 element.classList.add('lam-tab-active');
3531 }
3532 else {
3533 element.classList.remove('lam-tab-active');
3534 }
3535 });
3536 const selectedTabInput = document.querySelector('#selectedTab');
3537 if (selectedTabInput) {
3538 selectedTabInput.value = tabId;
3539 }
3540 }
3541
3542 window.lam.progressbar = window.lam.progressbar || {};
3543
3544 /**
3545 * Updates a progress bar.
3546 *
3547 * @param htmlId HTML id
3548 * @param progress new progress value (0..100)
3549 */
3550 window.lam.progressbar.setProgress = function(htmlId, progress) {
3551 const bar = document.getElementById(htmlId).querySelector('.lam-progressbar-bar');
3552 bar.style.width = progress + '%';
3553 }
3554
3555 /**
3556 * Creates the markup for a progress bar.
3557 *
3558 * @param htmlId HTML id
3559 */
3560 window.lam.progressbar.getMarkup = function(htmlId) {
3561 return '<div id="' + htmlId + '" class="lam-progressbar">' +
3562 '<div class="lam-progressbar-bar" style="width: 0%"></div>' +
3563 '</div>';
3564 }
3565
3566 window.lam.accordion = window.lam.accordion || {};
3567
3568 /**
3569 * Initializes the accordions.
3570 */
3571 window.lam.accordion.init = function() {
3572 const accordionButtons = document.getElementsByClassName('lam-accordion-button');
3573 Array.from(accordionButtons).forEach(function (button) {
3574 button.addEventListener('click', function(event) {
3575 window.lam.accordion.onClick(event, this);
3576 return false;
3577 });
3578 });
3579 const accordions = document.getElementsByClassName('lam-accordion-container');
3580 Array.from(accordions).forEach(function (accordion) {
3581 const isSaveState = accordion.dataset.savestate && (accordion.dataset.savestate === 'true');
3582 let openInitial = false;
3583 const storageKey = 'lam_accordionStore_' + accordion.id;
3584 if (isSaveState && window.localStorage.getItem(storageKey)) {
3585 // load value from local storage
3586 openInitial = window.localStorage.getItem(storageKey);
3587 }
3588 else if (accordion.dataset.openinitial) {
3589 openInitial = accordion.dataset.openinitial;
3590 }
3591 if (openInitial !== false) {
3592 accordion.querySelectorAll('.lam-accordion-button').forEach(item => {
3593 const buttonIndex = item.dataset.index;
3594 if (openInitial === buttonIndex) {
3595 item.classList.add('lam-accordion-button-active');
3596 }
3597 });
3598 accordion.querySelectorAll('.lam-accordion-content').forEach(item => {
3599 const contentIndex = item.dataset.index;
3600 if (openInitial === contentIndex) {
3601 item.style.maxHeight = null;
3602 item.classList.add('lam-accordion-content-active')
3603 item.style.maxHeight = item.scrollHeight + 'px';
3604 }
3605 });
3606 }
3607 });
3608 }
3609
3610 /**
3611 * Onclick handler for accordion element.
3612 *
3613 * @param event event
3614 * @param button button that was clicked
3615 */
3616 window.lam.accordion.onClick = function(event, button) {
3617 event.preventDefault();
3618 // mark button active
3619 button.classList.toggle('lam-accordion-button-active');
3620 // open corresponding content area
3621 const content = button.nextElementSibling;
3622 if (content.style.maxHeight) {
3623 content.style.maxHeight = null;
3624 content.classList.remove('lam-accordion-content-active')
3625 }
3626 else {
3627 content.style.maxHeight = content.scrollHeight + 'px';
3628 content.classList.add('lam-accordion-content-active')
3629 }
3630 const indexActive = button.dataset.index;
3631 const accordion = button.parentElement;
3632 const isSaveState = accordion.dataset.savestate && (accordion.dataset.savestate === 'true');
3633 if (isSaveState) {
3634 const storageKey = 'lam_accordionStore_' + accordion.id;
3635 window.localStorage.setItem(storageKey, indexActive);
3636 }
3637 // deactivate other buttons
3638 accordion.querySelectorAll('.lam-accordion-button').forEach(item => {
3639 const buttonIndex = item.dataset.index;
3640 if (indexActive !== buttonIndex) {
3641 item.classList.remove('lam-accordion-button-active');
3642 }
3643 });
3644 // close other content areas
3645 accordion.querySelectorAll('.lam-accordion-content').forEach(item => {
3646 const contentIndex = item.dataset.index;
3647 if (indexActive !== contentIndex) {
3648 item.style.maxHeight = null;
3649 item.classList.remove('lam-accordion-content-active')
3650 }
3651 });
3652 }
3653
3654 window.lam.tooltip = window.lam.tooltip || {};
3655
3656 /**
3657 * Creates the tooltips for help buttons.
3658 */
3659 window.lam.tooltip.init = function() {
3660 document.querySelectorAll('[helpdata]').forEach(item => {
3661 let helpString = "<div class='lam-tooltip'><h4 class=\"lam-tooltip-title\">";
3662 helpString += item.attributes.helptitle.value;
3663 helpString += "</h4><div class=\"lam-tooltip-content\">";
3664 helpString += item.attributes.helpdata.value;
3665 helpString += "</div></h4></div>";
3666 tippy(item, {
3667 content: helpString,
3668 allowHTML: true,
3669 arrow: false,
3670 delay: [100, 20]
3671 });
3672 });
3673 }
3674
3675 window.lam.smtp = window.lam.smtp || {};
3676
3677 /**
3678 * Tests the SMTP settings.
3679 *
3680 * @param event event
3681 * @param tokenName security token name
3682 * @param tokenValue security token value
3683 * @param okText text to close dialog
3684 * @param cancelText text to cancel test
3685 * @param title dialog title
3686 */
3687 window.lam.smtp.test = function(event, tokenName, tokenValue, okText, cancelText, title) {
3688 event.preventDefault();
3689 const runTestPreCallback = function() {
3690 const mailFrom = document.getElementById('testSmtpFrom').value;
3691 const mailTo = document.getElementById('testSmtpTo').value;
3692 if (!mailFrom || !mailTo) {
3693 return false;
3694 }
3695 return {
3696 mailFrom: mailFrom,
3697 mailTo: mailTo
3698 }
3699 }
3700 const runTestCallback = function(formData) {
3701 document.getElementById('btn_testSmtp').disabled = true;
3702 let data = new FormData();
3703 data.append(tokenName, tokenValue);
3704 data.append('server', document.getElementById('mailServer').value);
3705 data.append('user', document.getElementById('mailUser').value);
3706 data.append('password', document.getElementById('mailPassword').value);
3707 data.append('encryption', document.getElementById('mailEncryption').value);
3708 data.append('mailFrom', formData.mailFrom);
3709 data.append('mailTo', formData.mailTo);
3710 const url = '../misc/ajax.php?function=testSmtp';
3711 fetch(url, {
3712 method: 'POST',
3713 body: data
3714 })
3715 .then(async response => {
3716 const jsonData = await response.json();
3717 if (jsonData.info) {
3718 window.lam.dialog.showInfo(jsonData.info, okText);
3719 }
3720 else if (jsonData.error) {
3721 window.lam.dialog.showError(jsonData.error, jsonData.details, okText);
3722 }
3723 document.getElementById('btn_testSmtp').disabled = false;
3724 });
3725 }
3726 window.lam.dialog.showConfirmation(title, okText, cancelText, 'smtpTestDialogDiv', runTestCallback, runTestPreCallback);
3727 }
3728
3729 window.lam.sms = window.lam.sms || {};
3730
3731 /**
3732 * Tests the SMS settings.
3733 *
3734 * @param event event
3735 * @param tokenName security token name
3736 * @param tokenValue security token value
3737 * @param okText text to close dialog
3738 * @param cancelText text to cancel test
3739 * @param title dialog title
3740 */
3741 window.lam.sms.test = function(event, tokenName, tokenValue, okText, cancelText, title) {
3742 event.preventDefault();
3743 const runTestPreCallback = function() {
3744 const number = document.getElementById('testSmsNumber').value;
3745 if (!number) {
3746 return false;
3747 }
3748 return {
3749 number: number
3750 }
3751 }
3752 const runTestCallback = function(formData) {
3753 document.getElementById('btn_testSms').disabled = true;
3754 let data = new FormData();
3755 data.append(tokenName, tokenValue);
3756 data.append('provider', document.getElementById('smsProvider').value);
3757 data.append('apiKey', document.getElementById('smsApiKey').value);
3758 data.append('apiToken', document.getElementById('smsApiToken').value);
3759 data.append('accountId', document.getElementById('smsAccountId').value);
3760 data.append('region', document.getElementById('smsRegion').value);
3761 data.append('from', document.getElementById('smsFrom').value);
3762 data.append('subject', document.getElementById('smsSubject').value);
3763 data.append('number', formData.number);
3764 const url = '../misc/ajax.php?function=testSms';
3765 fetch(url, {
3766 method: 'POST',
3767 body: data
3768 })
3769 .then(async response => {
3770 const jsonData = await response.json();
3771 if (jsonData.info) {
3772 window.lam.dialog.showInfo(jsonData.info, okText);
3773 }
3774 else if (jsonData.error) {
3775 window.lam.dialog.showError(jsonData.error, jsonData.details, okText);
3776 }
3777 document.getElementById('btn_testSms').disabled = false;
3778 });
3779 }
3780 window.lam.dialog.showConfirmation(title, okText, cancelText, 'smsTestDialogDiv', runTestCallback, runTestPreCallback);
3781 }
3782
3783 window.lam.config = window.lam.config || {};
3784
3785 window.lam.config.updateModuleFilter = function(inputField) {
3786 const filterValue = inputField.value.toLowerCase();
3787 const table = inputField.parentElement.parentElement.querySelector('table');
3788 table.querySelectorAll('tr').forEach(row => {
3789 let matches = false;
3790 for (let i = 0; i < row.children.length; i++) {
3791 const cell = row.children[i];
3792 if (cell.children.length > 0) {
3793 continue;
3794 }
3795 if (cell.innerText.toLowerCase().includes(filterValue)) {
3796 matches = true;
3797 }
3798 }
3799 if (matches) {
3800 row.classList.remove('hidden');
3801 }
3802 else {
3803 row.classList.add('hidden');
3804 }
3805 });
3806 }
3807
3808 window.lam.richEdit = window.lam.richEdit || {};
3809
3810 /**
3811 * Inits the rich-text editors.
3812 */
3813 window.lam.richEdit.init = function() {
3814 document.querySelectorAll('.lam-rich-edit').forEach(textarea => {
3815 Jodit.make(textarea, {
3816 beautifyHTML: false,
3817 sourceEditorCDNUrlsJS: [],
3818 sourceEditor: 'area',
3819 uploader: {
3820 "insertImageAsBase64URI": true
3821 }
3822 });
3823 });
3824 }
3825
3826 window.lam.datatable = window.lam.datatable || {};
3827 window.lam.datatable.tables = window.lam.datatable.tables || {};
3828 window.lam.datatable.unfinishedTables = window.lam.datatable.unfinishedTables || {};
3829
3830 window.lam.datatable.init = function(id, table) {
3831 window.lam.datatable.tables[id] = table;
3832 window.lam.datatable.unfinishedTables[id] = true;
3833 table.on("tableBuilt", () => {
3834 window.lam.datatable.unfinishedTables[id] = false;
3835 });
3836 }
3837
3838 /**
3839 * Refreshes the data of a datatable using the AjaxURL.
3840 *
3841 * @param id table ID
3842 */
3843 window.lam.datatable.refreshTableData = function(id) {
3844 const tableDiv = document.getElementById(id);
3845 if (!tableDiv) {
3846 return;
3847 }
3848 const ajaxUrl = tableDiv.dataset.ajaxurl;
3849 const tokenName = tableDiv.dataset.tokenname;
3850 const tokenValue = tableDiv.dataset.tokenvalue;
3851 const action = tableDiv.dataset.action;
3852 const okText = tableDiv.dataset.oktext;
3853 let data = new FormData();
3854 data.append(tokenName, tokenValue);
3855 data.append("action", action);
3856 fetch(ajaxUrl, {
3857 method: "POST",
3858 body: data
3859 })
3860 .then(async response => {
3861 const jsonData = await response.json();
3862 if (jsonData.message) {
3863 window.lam.dialog.showError(jsonData.message, okText);
3864 }
3865 else {
3866 window.lam.datatable.setData(id, jsonData);
3867 }
3868 });
3869 }
3870
3871 /**
3872 * Sets the data of a datatable.
3873 *
3874 * @param id table ID
3875 * @param data list of rows ([{firstName:"Steve", lastName:"Miller"}])
3876 */
3877 window.lam.datatable.setData = function(id, data) {
3878 const table = window.lam.datatable.tables[id];
3879 for (let i = 0; i < data.length; i++) {
3880 data[i].id = i;
3881 }
3882 if (window.lam.datatable.unfinishedTables[id] === false) {
3883 table.replaceData(data);
3884 }
3885 else {
3886 table.on("tableBuilt", () => {
3887 window.lam.datatable.unfinishedTables[id] = false;
3888 table.replaceData(data);
3889 });
3890 }
3891 }
3892
3893 /**
3894 * Adds a search field to the data table.
3895 *
3896 * @param tableId table ID
3897 * @param fieldId field ID
3898 */
3899 window.lam.datatable.addSearchField = function(tableId, fieldId) {
3900 const table = window.lam.datatable.tables[tableId];
3901 const field = document.getElementById(fieldId);
3902 field.addEventListener('keyup', function() {
3903 const filter = field.value.toLowerCase();
3904 table.clearFilter();
3905 if (filter === '') {
3906 return;
3907 }
3908 table.setFilter(function(data, filterValue) {
3909 const filterValues = filterValue.split(/\s+/);
3910 let found = true;
3911 filterValues.forEach(value => {
3912 found = found && data['_lam_search_'].toLowerCase().includes(value);
3913 })
3914 return found;
3915 }, filter);
3916 });
3917 }
3918
3919 window.lam.loadingIndicator = window.lam.loadingIndicator || {};
3920
3921 /**
3922 * Starts the loading indicator.
3923 */
3924 window.lam.loadingIndicator.start = function() {
3925 Swal.fire({
3926 title:"",
3927 imageUrl: "../../style/loading.gif",
3928 showConfirmButton: false,
3929 allowOutsideClick: false,
3930 timer: 60000,
3931 });
3932 }
3933
3934 /**
3935 * Stops the loading indicator.
3936 */
3937 window.lam.loadingIndicator.stop = function() {
3938 Swal.close();
3939 }
3940
3941 window.lam.utility = window.lam.utility || {};
3942
3943 /**
3944 * Run actions on document ready.
3945 *
3946 * @param callback callback function
3947 */
3948 window.lam.utility.documentReady = function(callback) {
3949 if (document.readyState !== 'loading') {
3950 callback();
3951 } else {
3952 document.addEventListener('DOMContentLoaded', callback);
3953 }
3954 }
3955
3956 /**
3957 * Stores the current scroll position in the form.
3958 *
3959 * @param formName ID of form
3960 */
3961 window.lam.utility.saveScrollPosition = function(formName) {
3962 const top = window.scrollY;
3963 const left = window.scrollX;
3964 let scrollPositionTop = document.createElement('input');
3965 scrollPositionTop.name = 'scrollPositionTop';
3966 scrollPositionTop.value = top;
3967 scrollPositionTop.hidden = 'hidden';
3968 document.forms[formName].appendChild(scrollPositionTop);
3969 let scrollPositionLeft = document.createElement('input');
3970 scrollPositionLeft.name = 'scrollPositionLeft';
3971 scrollPositionLeft.value = left;
3972 scrollPositionLeft.hidden = 'hidden';
3973 document.forms[formName].appendChild(scrollPositionLeft);
3974 }
3975
3976 /**
3977 * Restores the scroll position.
3978 *
3979 * @param topValue top value
3980 * @param leftValue left value
3981 */
3982 window.lam.utility.restoreScrollPosition = function(topValue, leftValue) {
3983 window.lam.utility.documentReady(function() {
3984 window.scrollTo(leftValue, topValue);
3985 });
3986 }
3987
3988 /**
3989 * Checks if an element is hidden.
3990 *
3991 * @param element element
3992 */
3993 window.lam.utility.isHidden = function(element) {
3994 return !element.offsetWidth || !element.offsetHeight || (element.getClientRects().length == 0);
3995 }
3996
3997
3998 window.lam.utility.documentReady(function() {
3999 window.lam.form.autoTrim();
4000 window.lam.account.addDefaultProfileListener();
4001 window.lam.tools.addSavedSelectListener();
4002 window.lam.tools.setInitialFocus();
4003 window.lam.tools.webcam.init();
4004 window.lam.tools.schema.select();
4005 window.lam.html.activateLightboxes();
4006 window.lam.html.preventEnter();
4007 window.lam.filterSelect.addFormListener();
4008 window.lam.dynamicSelect.activate();
4009 window.lam.webauthn.setupDeviceManagement();
4010 window.lam.tabs.init();
4011 window.lam.accordion.init();
4012 window.lam.tooltip.init();
4013 window.lam.richEdit.init();
4014 });
4015
4016 /**
4017 * Setup service worker.
4018 */
4019 if ("serviceWorker" in navigator) {
4020 if (!navigator.serviceWorker.controller) {
4021 var basePath = document.currentScript.src;
4022 basePath = basePath.replace(/\/[^/]+\.js/gi, '');
4023 var workerJS = basePath + '/../../pwa_worker.js';
4024 navigator.serviceWorker.register(workerJS, {
4025 scope : basePath + "../../"
4026 });
4027 }
4028 }