Debian Codegraph @

lib/lists.inc

raw
1 <?php
2
3 use LAM\PDF\PdfStructurePersistenceManager;
4 use LAM\TYPES\ConfiguredType;
5 use function LAM\PDF\createModulePDF;
6 use function LAM\PDF\getPdfFonts;
7
8 /*
9
10 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
11 Copyright (C) 2003 - 2026 Roland Gruber
12
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26
27
28 */
29
30 /**
31 * This file includes functions to manage the list views.
32 *
33 * @package lists
34 * @author Roland Gruber
35 */
36
37 /** Used to get type information. */
38 include_once(__DIR__ . "/types.inc");
39 /** Used to get PDF information. */
40 include_once(__DIR__ . "/pdfstruct.inc");
41 /** Used to create PDF files. */
42 include_once(__DIR__ . "/pdf.inc");
43
44
45 /**
46 * Generates the list view.
47 *
48 * @package lists
49 * @author Roland Gruber
50 *
51 */
52 class lamList {
53
54 /** ID for config option to show account status */
55 private const ACCOUNT_STATUS_OPTION_NAME = "LU_AS";
56
57 /** virtual attribute name for account status column */
58 private const ATTR_ACCOUNT_STATUS = 'lam_virtual_account_status';
59
60 /** filter value for expired accounts */
61 private const FILTER_EXPIRED = 1;
62 /** filter value for locked accounts */
63 private const FILTER_LOCKED = 2;
64 /** filter value for partially locked accounts */
65 private const FILTER_SEMILOCKED = 3;
66 /** filter value for unlocked accounts */
67 private const FILTER_UNLOCKED = 4;
68
69 /** ID for list size config option */
70 private const LIST_SIZE_OPTION_NAME = "L_SIZE";
71
72 /** prefix for virtual (non-LDAP) attributes */
73 private const VIRTUAL_ATTRIBUTE_PREFIX = 'lam_virtual_';
74
75 /** Controls if the account status is shown */
76 protected bool $showAccountStatus = false;
77
78 /** Account type */
79 protected ConfiguredType $type;
80
81 /** current page number */
82 protected int $page = 1;
83
84 /** @var string[] $attrArray list of LDAP attributes */
85 protected array $attrArray = [];
86
87 /** @var string[] $descArray list of attribute descriptions */
88 protected array $descArray = [];
89
90 /** maximum count of entries per page */
91 protected int $maxPageEntries = 30;
92
93 /** sort column name */
94 protected ?string $sortColumn = null;
95
96 /** sort direction: 1 for ascending, -1 for descending */
97 protected int $sortDirection = 1;
98
99 /** LDAP suffix */
100 protected ?string $suffix = null;
101
102 /** refresh page switch */
103 protected bool $refresh = true;
104
105 /** @var int[] $entries entries to show */
106 protected array $entries = [];
107
108 /** @var array<int, array<string, string[]|string>> $ldapEntries entries from LDAP */
109 protected array $ldapEntries = [];
110
111 /** @var array<int, int> $sortMapping sort mapping for entries array(original index => sorted index) */
112 protected array $sortMapping = [];
113
114 /** @var array<string, string> $filters list of filters (attribute name => filter input) */
115 protected array $filters = [];
116
117 /** @var string[] $possibleSuffixes list of possible LDAP suffixes(organizational units) */
118 protected array $possibleSuffixes = [];
119
120 /** @var array<string, string> $labels list of account specific labels */
121 protected array $labels;
122
123 /** @var lamListOption[] $configOptions configuration options */
124 private array $configOptions;
125
126 /** defines if the server side filter changed */
127 protected bool $serverSideFilterChanged = false;
128
129 /**
130 * @var bool supports the quick change
131 */
132 private bool $supportsPasswordQuickChange;
133
134 /**
135 * List of attributes to filter on server side.
136 *
137 * @var string[]
138 */
139 protected array $serverSideFilterAttributes = [
140 'cn', 'commonname', 'uid', 'description',
141 'sn', 'surname', 'gn', 'givenname', 'company', 'mail'
142 ];
143
144 /**
145 * Constructor
146 *
147 * @param LAM\TYPES\ConfiguredType $type account type
148 */
149 public function __construct(ConfiguredType $type) {
150 $this->type = $type;
151 $this->labels = [
152 'nav' => _("Object count: %s"),
153 'error_noneFound' => _("No objects found!"),
154 'newEntry' => _("New object"),
155 'deleteEntry' => _("Delete selected objects")];
156 $this->configOptions = $this->listGetAllConfigOptions();
157 $this->listReadOptionsFromCookie();
158 $this->supportsPasswordQuickChange = $this->isSupportingPasswordQuickChange();
159 }
160
161 /**
162 * Reads the list options from the cookie value.
163 */
164 private function listReadOptionsFromCookie(): void {
165 if ((count($this->configOptions) > 0)
166 && isset($_COOKIE["ListOptions_" . $this->type->getId()])) {
167 $cookieValue = $_COOKIE["ListOptions_" . $this->type->getId()];
168 $valueParts = explode(";", $cookieValue);
169 $values = [];
170 for ($i = 0; $i < count($valueParts); $i++) {
171 $key_value = explode('=', $valueParts[$i]);
172 if (count($key_value) === 2) {
173 $values[$key_value[0]] = $key_value[1];
174 }
175 }
176 for ($i = 0; $i < count($this->configOptions); $i++) {
177 if (isset($values[$this->configOptions[$i]->getID()])) {
178 $this->configOptions[$i]->setValue($values[$this->configOptions[$i]->getID()]);
179 }
180 }
181 // notify subclasses
182 $this->listConfigurationChanged();
183 }
184 }
185
186 /**
187 * Prints the HTML code to display the list view.
188 */
189 public function showPage(): void {
190 // do POST actions
191 $postFragment = $this->listDoPost();
192 // update filter
193 $this->listBuildFilter();
194 // get some parameters
195 $this->listGetParams();
196 // print HTML head
197 $this->printHeader();
198 // print messages when redirected from other pages
199 $this->listPrintRedirectMessages();
200 // refresh data if needed
201 if ($this->refresh) {
202 $this->listRefreshData();
203 }
204 // local filtering
205 $this->applyLocalFilters();
206 // sort rows by sort column
207 if (!empty($this->entries)) {
208 $this->listCreateSortMapping($this->entries);
209 }
210 // insert HTML fragment from listDoPost
211 if ($postFragment !== null) {
212 parseHtml('', $postFragment, [], true);
213 }
214 // config dialog
215 $this->listPrintConfigurationPage();
216 // show form
217 echo "<form action=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true\" method=\"post\">\n";
218 // draw account list if accounts were found
219 if (!empty($this->entries)) {
220 // buttons
221 $this->listPrintButtons(false);
222 // navigation bar
223 $this->listDrawNavigationBar(count($this->entries));
224 $this->printAccountTable($this->entries);
225 }
226 else {
227 // buttons
228 $this->listPrintButtons(true);
229 // navigation bar
230 $this->listDrawNavigationBar(count($this->entries));
231 $accounts = [];
232 $this->printAccountTable($accounts);
233 echo "</table><br>\n";
234 }
235 $this->printFooter();
236 }
237
238 /**
239 * Builds the regular expressions from the filter values.
240 */
241 protected function listBuildFilter(): void {
242 if (isset($_GET['accountEditBack'])) {
243 return;
244 }
245 $oldFilter = $this->filters;
246 $this->serverSideFilterChanged = false;
247 $this->filters = [];
248 if (!isset($_POST['clear_filter'])) {
249 // build filter array
250 for ($i = 0; $i < count($this->attrArray); $i++) {
251 $foundFilter = null;
252 if (isset($_GET["filter" . strtolower($this->attrArray[$i])])) {
253 $foundFilter = $_GET["filter" . strtolower($this->attrArray[$i])];
254 }
255 if (isset($_POST["filter" . strtolower($this->attrArray[$i])])) {
256 $foundFilter = $_POST["filter" . strtolower($this->attrArray[$i])];
257 }
258 if (isset($foundFilter) && ($foundFilter != '')) {
259 if (preg_match('/^[\\^]?([\p{L}\p{N} _\\*\\$\\.:@∞-])+[\\$]?$/iu', $foundFilter)) { // \p{L} matches any Unicode letter
260 $this->filters[strtolower($this->attrArray[$i])] = $foundFilter;
261 }
262 else {
263 StatusMessage('ERROR', _('Please enter a valid filter. Only letters, numbers and " _*$.@-" are allowed.'), htmlspecialchars($foundFilter));
264 }
265 }
266 }
267 }
268 $filterAttrs = array_merge(array_keys($oldFilter), array_keys($this->filters));
269 $filterAttrs = array_unique($filterAttrs);
270 foreach ($filterAttrs as $attrName) {
271 if (!$this->isAttributeFilteredByServer($attrName)) {
272 continue;
273 }
274 if (!isset($oldFilter[$attrName]) || !isset($this->filters[$attrName]) || ($oldFilter[$attrName] != $this->filters[$attrName])) {
275 $this->serverSideFilterChanged = true;
276 break;
277 }
278 }
279 }
280
281 /**
282 * Determines the sort mapping and stores it in $this->sortMapping.
283 * The sort mapping is used to display the right rows when the account table is created.
284 *
285 * @param int[] $indexes the account list indexes
286 */
287 protected function listCreateSortMapping(array $indexes): void {
288 if (!is_string($this->sortColumn)) {
289 return;
290 }
291 $toSort = [];
292 if ($this->sortColumn !== 'dn') {
293 foreach ($indexes as $index) {
294 // sort by first attribute with name $sort
295 $toSort[] = $this->ldapEntries[$index][$this->sortColumn][0] ?? '';
296 }
297 }
298 else {
299 foreach ($indexes as $index) {
300 $toSort[] = $this->ldapEntries[$index][$this->sortColumn] ?? '';
301 }
302 }
303 natcasesort($toSort);
304 $sortResult = [];
305 if ($this->sortDirection === 1) {
306 foreach (array_keys($toSort) as $orig) {
307 $sortResult[] = $orig;
308 }
309 }
310 else {
311 $counter = count($toSort);
312 foreach (array_keys($toSort) as $orig) {
313 $counter--;
314 $sortResult[$counter] = $orig;
315 }
316 }
317 $this->sortMapping = &$sortResult;
318 }
319
320 /**
321 * Draws a navigation bar to switch between pages
322 *
323 * @param int $count number of account entries
324 */
325 protected function listDrawNavigationBar($count): void {
326 $filter = $this->getFilterAsTextForURL();
327 $row = new htmlResponsiveRow();
328 $row->setCSSClasses(['maxrow']);
329 $countLabel = new htmlOutputText(sprintf($this->labels['nav'], $count));
330 $row->add($countLabel, 12, 6, 6);
331 $navGroup = new htmlGroup();
332 if ($count > $this->maxPageEntries) {
333 if ($this->page !== 1) {
334 $linkHref = "list.php?type=" . $this->type->getId() . "&norefresh=true&page=1" .
335 "&sort=" . $this->sortColumn . "&sortdirection=" . $this->sortDirection . $filter;
336 $link = new htmlLink(null, $linkHref, '../../graphics/go-first.svg');
337 $link->setTitle(_('Jump to first page'));
338 $link->setCSSClasses(['icon']);
339 $navGroup->addElement($link);
340 }
341 if ($this->page > 11) {
342 $linkHref = "list.php?type=" . $this->type->getId() . "&norefresh=true&page=" . ($this->page - 10) .
343 "&sort=" . $this->sortColumn . "&sortdirection=" . $this->sortDirection . $filter;
344 $link = new htmlLink(null, $linkHref, '../../graphics/go-previous.svg');
345 $link->setTitle(_('Jump 10 pages backward'));
346 $link->setCSSClasses(['icon']);
347 $navGroup->addElement($link);
348 }
349 $pageCount = (int) ceil($count / $this->maxPageEntries);
350 for ($i = $this->page - 6; $i < ($this->page + 5); $i++) {
351 if ($i >= $pageCount) {
352 break;
353 }
354 elseif ($i < 0) {
355 continue;
356 }
357 if ($i === $this->page - 1) {
358 $url = "list.php?type=" . $this->type->getId() . "&norefresh=true" .
359 "&sort=" . $this->sortColumn . "&sortdirection=" . $this->sortDirection . $filter;
360 $navInput = new htmlInputField('listNavPage', (string) ($i + 1));
361 $navInput->setMinimumAndMaximumNumber(1, $pageCount);
362 $navInput->setCSSClasses(['listPageInput']);
363 $navInput->setOnKeyPress('listPageNumberKeyPress(\'' . $url . '\', event);');
364 $navInput->setAccessibilityLabel(_('Page'));
365 $navGroup->addElement($navInput);
366 }
367 else {
368 $linkHref = "list.php?type=" . $this->type->getId() . "&norefresh=true&page=" . ($i + 1) .
369 "&sort=" . $this->sortColumn . "&sortdirection=" . $this->sortDirection . $filter;
370 $link = new htmlLink((string) ($i + 1), $linkHref);
371 $navGroup->addElement($link);
372 }
373 }
374 if ($this->page < ($pageCount - 10)) {
375 $linkHref = "list.php?type=" . $this->type->getId() . "&norefresh=true&page=" . ($this->page + 10) .
376 "&sort=" . $this->sortColumn . "&sortdirection=" . $this->sortDirection . $filter;
377 $link = new htmlLink(null, $linkHref, '../../graphics/go-next.svg');
378 $link->setTitle(_('Jump 10 pages forward'));
379 $link->setCSSClasses(['icon']);
380 $navGroup->addElement($link);
381 }
382 if ($this->page < $pageCount) {
383 $linkHref = "list.php?type=" . $this->type->getId() . "&norefresh=true&page=" . $pageCount .
384 "&sort=" . $this->sortColumn . "&sortdirection=" . $this->sortDirection . $filter;
385 $link = new htmlLink(null, $linkHref, '../../graphics/go-last.svg');
386 $link->setTitle(_('Jump to last page'));
387 $link->setCSSClasses(['icon']);
388 $navGroup->addElement($link);
389 }
390 }
391 $row->add($navGroup, 12, 6, 6, 'responsiveLabel');
392 parseHtml(null, $row, [], false);
393 }
394
395 /**
396 * Returns the filter as text to be used as URL parameter.
397 *
398 * @return string filter text
399 */
400 protected function getFilterAsTextForURL(): string {
401 $text = '';
402 foreach ($this->filters as $attr => $filter) {
403 $text .= "&filter" . strtolower($attr) . '=' . $filter;
404 }
405 return $text;
406 }
407
408 /**
409 * Prints the entry list
410 *
411 * @param int[] $indexes entry indexes
412 */
413 private function printAccountTable($indexes): void {
414 $titles = $this->descArray;
415 array_unshift($titles, _('Actions'));
416 $data = [];
417 $data[] = $this->getSortingElements();
418 $data[] = $this->getFilterElements();
419 $onClickEvents = [];
420 $onDoubleClickEvents = [];
421 $this->addDataElements($data, $indexes, $onClickEvents, $onDoubleClickEvents);
422
423 $table = new htmlResponsiveTable($titles, $data);
424 $table->setCSSClasses(['accountlist']);
425 $table->setOnClickEvents($onClickEvents);
426 $table->setOnDoubleClickEvents($onDoubleClickEvents);
427
428 parseHtml(null, $table, [], false);
429 }
430
431 /**
432 * Returns the elements to show in sorting row.
433 *
434 * @return htmlElement[] elements
435 */
436 private function getSortingElements() {
437 $filter = $this->getFilterAsTextForURL();
438 $sortElements = [new htmlSpan(new htmlOutputText(_('Sort sequence')), ['nowrap'])];
439 foreach ($this->attrArray as $attributeName) {
440 $link = "list.php?type=" . $this->type->getId() . "&" .
441 "sort=" . strtolower($attributeName) . $filter . "&norefresh=y";
442 $buttons = new htmlGroup();
443 $down = new htmlLink(null, $link . '&sortdirection=1', '../../graphics/pan-down.svg');
444 if (strtolower($attributeName) == $this->sortColumn) {
445 if ($this->sortDirection < 0) {
446 $down->setCSSClasses(['icon noMarginSides']);
447 $down->setTitle(_('Sort ascending'));
448 $buttons->addElement($down);
449 $up = new htmlLink(null, $link . '&sortdirection=-1', '../../graphics/pan-up.svg');
450 $up->setCSSClasses(['icon icon-active noMarginSides']);
451 }
452 else {
453 $down->setCSSClasses(['icon icon-active noMarginSides']);
454 $down->setTitle(_('Sort ascending'));
455 $buttons->addElement($down);
456 $up = new htmlLink(null, $link . '&sortdirection=-1', '../../graphics/pan-up.svg');
457 $up->setCSSClasses(['icon noMarginSides']);
458 }
459 }
460 else {
461 $down->setCSSClasses(['icon noMarginSides']);
462 $down->setTitle(_('Sort ascending'));
463 $buttons->addElement($down);
464 $up = new htmlLink(null, $link . '&sortdirection=-1', '../../graphics/pan-up.svg');
465 $up->setCSSClasses(['icon noMarginSides']);
466 }
467 $up->setTitle(_('Sort descending'));
468 $buttons->addElement($up);
469 $sortElements[] = $buttons;
470 }
471 return $sortElements;
472 }
473
474 /**
475 * Returns the elements to show in filter row.
476 *
477 * @return htmlElement[] elements
478 */
479 private function getFilterElements() {
480 $actionElement = new htmlGroup();
481 $selectAll = new htmlInputCheckbox('tableSelectAll', false);
482 $selectAll->setCSSClasses(['align-middle']);
483 $selectAll->setOnClick('list_switchAccountSelection();');
484 $selectAll->setTitle(_('Select all'));
485 $actionElement->addElement($selectAll);
486 $actionElement->addElement(new htmlSpacer('1rem', null));
487 $actionElement->addElement(new htmlOutputText(_('Filter')));
488 $filterButton = new htmlButton('apply_filter', 'filter.svg', true);
489 $filterButton->setTitle(_("Here you can input simple filter expressions (e.g. 'value' or 'v*'). The filter is case-insensitive."));
490 $actionElement->addElement($filterButton);
491 if (count($this->filters) > 0) {
492 $clearFilterButton = new htmlButton('clear_filter', 'del.svg', true);
493 $clearFilterButton->setTitle(_('Clear filter'));
494 $actionElement->addElement($clearFilterButton);
495 }
496
497 $filterElements = [new htmlDiv(null, $actionElement, ['lam-listtools'])];
498 $clearFilter = isset($_POST['clear_filter']);
499 foreach ($this->attrArray as $attributeName) {
500 $attributeName = strtolower($attributeName);
501 if ($this->canBeFiltered($attributeName)) {
502 $filterElements[] = $this->getFilterArea($attributeName, $clearFilter);
503 }
504 else {
505 $filterElements[] = new htmlOutputText('');
506 }
507 }
508 return $filterElements;
509 }
510
511 /**
512 * Prints the content of a single attribute filter area.
513 *
514 * @param string $attrName attribute name
515 * @param bool $clearFilter true if filter value should be cleared
516 * @return htmlElement element to show
517 */
518 protected function getFilterArea(string $attrName, bool $clearFilter): htmlElement {
519 if ($attrName === self::ATTR_ACCOUNT_STATUS) {
520 return $this->getAccountStatusFilterArea($clearFilter);
521 }
522 $value = "";
523 if (!$clearFilter && isset($this->filters[$attrName])) {
524 $value = $this->filters[$attrName];
525 }
526 $filterInput = new htmlInputField('filter' . $attrName, $value, null);
527 $filterInput->setOnKeyPress("SubmitForm('apply_filter', event);");
528 $filterInput->setFieldSize(null);
529 $filterInput->setTitle(_('Filter'));
530 return $filterInput;
531 }
532
533 /**
534 * Returns the filter for account status.
535 *
536 * @param bool $clearFilter filter should be cleared
537 */
538 protected function getAccountStatusFilterArea(bool $clearFilter): htmlElement {
539 $value = "-";
540 if (!$clearFilter && isset($this->filters[self::ATTR_ACCOUNT_STATUS])) {
541 $value = $this->filters[self::ATTR_ACCOUNT_STATUS];
542 }
543 $filterOptions = [
544 '' => '',
545 _('Unlocked') => self::FILTER_UNLOCKED,
546 _('Partially locked') => self::FILTER_SEMILOCKED,
547 _('Locked') => self::FILTER_LOCKED,
548 _('Expired') => self::FILTER_EXPIRED,
549 ];
550 $filterInput = new htmlSelect('filter' . strtolower(self::ATTR_ACCOUNT_STATUS), $filterOptions, [$value]);
551 $filterInput->setCSSClasses([$this->type->getScope() . '-bright']);
552 $filterInput->setHasDescriptiveElements(true);
553 $filterInput->setOnchangeEvent('document.getElementsByName(\'apply_filter\')[0].click();');
554 $filterInput->setAccessibilityLabel(_('Filter'));
555 return $filterInput;
556 }
557
558 /**
559 * Adds the LDAP data elements to the given array.
560 *
561 * @param mixed[][] $data data for responsible table
562 * @param int[] $entryIndexes entry indexes
563 * @param array<int, string> $onClickEvents row number => code
564 * @param array<int, string> $onDoubleClickEvents row number => code
565 */
566 private function addDataElements(&$data, $entryIndexes, &$onClickEvents, &$onDoubleClickEvents): void {
567 // calculate which rows to show
568 $table_begin = ($this->page - 1) * $this->maxPageEntries;
569 $table_end = ($this->page * $this->maxPageEntries) > count($entryIndexes) ? count($entryIndexes) : $this->page * $this->maxPageEntries;
570 // get sort mapping
571 if (empty($this->sortMapping)) {
572 $this->sortMapping = [];
573 foreach ($entryIndexes as $entryIndex) {
574 $this->sortMapping[$entryIndex] = $entryIndex;
575 }
576 }
577 // get custom render functions
578 $renderFunctions = [];
579 $modules = $this->type->getModules();
580 foreach ($modules as $module) {
581 $moduleObj = moduleCache::getModule($module, $this->type->getScope());
582 foreach ($this->attrArray as $attributeName) {
583 $attributeName = strtolower($attributeName);
584 $renderFunction = $moduleObj->getListRenderFunction($attributeName, $this->type);
585 if ($renderFunction !== null) {
586 $renderFunctions[$attributeName] = $renderFunction;
587 }
588 }
589 }
590 // print account list
591 for ($i = $table_begin; $i < $table_end; $i++) {
592 $row = [];
593 $index = $this->sortMapping[$i];
594 $rowID = base64_encode($this->ldapEntries[$entryIndexes[$index]]['dn']);
595 $actionElement = new htmlGroup();
596 $checkbox = new htmlInputCheckbox($rowID, false);
597 $checkbox->setOnClick("list_click('" . $rowID . "');");
598 $checkbox->setCSSClasses(['accountBoxUnchecked align-middle']);
599 $checkbox->setTitle(_('Select'));
600 $actionElement->addElement($checkbox);
601 $actionElement->addElement(new htmlSpacer('0.5rem', null));
602 $rowNumber = $i - $table_begin + 2;
603 $onClickEvents[$rowNumber] = "list_click('" . $rowID . "');";
604 $onDoubleClickEvents[$rowNumber] = "top.location.href='../account/edit.php?type=" . $this->type->getId() . "&amp;DN=" . rawurlencode($this->ldapEntries[$entryIndexes[$index]]['dn']) . "';";
605 $this->addToolLinks($this->ldapEntries[$entryIndexes[$index]], $rowID, $actionElement);
606 $row[] = new htmlDiv(null, $actionElement, ['lam-listtools']);
607 foreach ($this->attrArray as $attributeName) {
608 $attributeName = strtolower($attributeName);
609 if (!empty($renderFunctions[$attributeName])) {
610 $row[] = $renderFunctions[$attributeName]($this->ldapEntries[$entryIndexes[$index]], $attributeName);
611 }
612 else {
613 $row[] = $this->getTableCellContent($this->ldapEntries[$entryIndexes[$index]], $attributeName);
614 }
615 }
616 $data[] = $row;
617 }
618 }
619
620 /**
621 * Adds the tool image links (e.g. edit and delete) for each account.
622 *
623 * @param array<string, string[]|string> $account LDAP attributes
624 * @param string $id account ID
625 * @param htmlGroup $element location where to add tools
626 */
627 private function addToolLinks($account, $id, $element): void {
628 // edit link
629 $editLink = new htmlLink('', "../account/edit.php?type=" . $this->type->getId() . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/edit.svg');
630 $editLink->setTitle(_("Edit"));
631 $editLink->setCSSClasses(['lam-margin-smaller', 'icon']);
632 $element->addElement($editLink);
633 // delete link
634 if (checkIfWriteAccessIsAllowed($this->type->getId()) && checkIfDeleteEntriesIsAllowed($this->type->getId())) {
635 $deleteLink = new htmlLink('', "deletelink.php?type=" . $this->type->getId() . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/delete.svg');
636 $deleteLink->setTitle(_("Delete"));
637 $deleteLink->setCSSClasses(['lam-margin-smaller', 'icon']);
638 $element->addElement($deleteLink);
639 }
640 // copy link
641 if (checkIfWriteAccessIsAllowed($this->type->getId()) && checkIfNewEntriesAreAllowed($this->type->getId())) {
642 $copyLink = new htmlLink('', "../account/edit.php?type=" . $this->type->getId() . "&copyDn='" . rawurlencode($account['dn']) . "'", '../../graphics/copy.svg');
643 $copyLink->setTitle(_("Copy"));
644 $copyLink->setCSSClasses(['lam-margin-smaller', 'icon']);
645 $element->addElement($copyLink);
646 }
647 // PDF button
648 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
649 $pdfStructures = $pdfStructurePersistenceManager->getPDFStructures($_SESSION['config']->getName(), $this->type->getId());
650 if (!empty($pdfStructures)) {
651 $pdfButton = new htmlButton("createPDF_" . $id, 'pdf.svg', true);
652 $pdfButton->setTitle(_('Create PDF file'));
653 $pdfButton->setCSSClasses(['lam-margin-smaller']);
654 $element->addElement($pdfButton);
655 }
656 // password quick change
657 if (isLAMProVersion() && $this->supportsPasswordQuickChange && checkIfPasswordChangeIsAllowed()) {
658 $pwdChangeButton = new htmlLink('', "changePassword.php?type=" . $this->type->getId() . "&DN=" . rawurlencode($account['dn']), '../../graphics/key.svg');
659 $pwdChangeButton->setTitle(_('Change password'));
660 $pwdChangeButton->setCSSClasses(['lam-margin-smaller', 'icon']);
661 $element->addElement($pwdChangeButton);
662 }
663 // additional tools
664 $tools = $this->getAdditionalTools();
665 for ($i = 0; $i < count($tools); $i++) {
666 $toolLink = new htmlLink('', $tools[$i]->getLinkTarget() . "?type=" . $this->type->getId() . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/' . $tools[$i]->getImage());
667 $toolLink->setTitle($tools[$i]->getName());
668 $toolLink->setCSSClasses(['lam-margin-smaller', 'icon']);
669 $element->addElement($toolLink);
670 }
671 }
672
673 /**
674 * Returns if this account supports the password quick change page.
675 *
676 * @return bool quick change supported
677 */
678 private function isSupportingPasswordQuickChange(): bool {
679 $modules = $this->type->getModules();
680 foreach ($modules as $module) {
681 if (!in_array(passwordService::class, class_implements($module))) {
682 continue;
683 }
684 $moduleObj = new $module($this->type->getScope());
685 if (($moduleObj instanceof passwordService) && $moduleObj->supportsPasswordQuickChangePage()) {
686 return true;
687 }
688 }
689 return false;
690 }
691
692 /**
693 * Returns if this account supports the account status column.
694 *
695 * @return bool quick change supported
696 */
697 private function isSupportingAccountStatus(): bool {
698 $modules = $this->type->getModules();
699 foreach ($modules as $module) {
700 if (!in_array('AccountStatusProvider', class_implements($module))) {
701 continue;
702 }
703 return true;
704 }
705 return false;
706 }
707
708 /**
709 * Returns if the given attribute can be filtered.
710 * If filtering is not possible then no filter box will be displayed.
711 * By default all attributes can be filtered.
712 *
713 * @param String $attr attribute name
714 * @return boolean filtering possible
715 */
716 protected function canBeFiltered($attr) {
717 return true;
718 }
719
720 /**
721 * Returns the content of a cell in the account list for a given LDAP entry and attribute.
722 *
723 * @param array<string, string[]|string> $entry LDAP attributes
724 * @param string $attribute attribute name
725 * @return htmlElement|null content
726 */
727 protected function getTableCellContent(&$entry, &$attribute): ?htmlElement {
728 // account status
729 if ($attribute === self::ATTR_ACCOUNT_STATUS) {
730 return $this->getAccountStatus($entry);
731 }
732 if (($attribute === 'dn') && is_string($entry[$attribute])) {
733 return new htmlOutputText(getAbstractDN($entry[$attribute]));
734 }
735 // print all attribute entries separated by "; "
736 if (isset($entry[$attribute]) && count($entry[$attribute]) > 0) {
737 // sort array
738 natcasesort($entry[$attribute]);
739 return new htmlOutputText(implode("; ", $entry[$attribute]));
740 }
741 return null;
742 }
743
744 /**
745 * Manages all POST actions (e.g. button pressed) for the account lists.
746 *
747 * @return htmlElement|null HTML fragment to insert into beginning of account list
748 */
749 protected function listDoPost(): htmlElement|null {
750 if (!empty($_POST)) {
751 validateSecurityToken();
752 }
753 // check if button was pressed and if we have to add/delete an account or call file upload
754 if (isset($_POST['new']) || isset($_POST['del']) || isset($_POST['fileUpload'])) {
755 if (!checkIfWriteAccessIsAllowed($this->type->getId())) {
756 die();
757 }
758 // add new account
759 if (isset($_POST['new']) && checkIfNewEntriesAreAllowed($this->type->getId())) {
760 metaRefresh("../account/edit.php?type=" . $this->type->getId() . "&suffix=" . $this->suffix);
761 exit;
762 }
763 // delete account(s)
764 elseif (isset($_POST['del']) && checkIfDeleteEntriesIsAllowed($this->type->getId())) {
765 // search for checkboxes
766 $accounts = array_keys($_POST, "on");
767 // build DN list
768 $_SESSION['delete_dn'] = [];
769 for ($i = 0; $i < count($accounts); $i++) {
770 if ($accounts[$i] == 'tableSelectAll') {
771 continue;
772 }
773 $_SESSION['delete_dn'][] = base64_decode($accounts[$i]);
774 }
775 if ($accounts !== []) {
776 metaRefresh("../delete.php?type=" . $this->type->getId());
777 exit;
778 }
779 }
780 // file upload
781 elseif (isset($_POST['fileUpload']) && checkIfNewEntriesAreAllowed($this->type->getId())) {
782 metaRefresh("../upload/masscreate.php?type=" . $this->type->getId());
783 exit;
784 }
785 }
786 // PDF button
787 foreach (array_keys($_POST) as $key) {
788 if (strpos($key, 'createPDF_') > -1) {
789 $parts = explode("_", $key);
790 if (count($parts) === 2) {
791 $this->showPDFPage($parts[1]);
792 exit;
793 }
794 }
795 }
796 // PDF creation Ok
797 if (isset($_POST['createPDFok'])) {
798 try {
799 $pdfStruct = (string) $_POST['pdf_structure'];
800 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
801 $pdfStructures = $pdfStructurePersistenceManager->getPDFStructures($_SESSION['config']->getName(), $this->type->getId());
802 if (!in_array($pdfStruct, $pdfStructures)) {
803 logNewMessage(LOG_ERR, 'Invalid PDF structure: ' . $pdfStruct);
804 die();
805 }
806 $pdfFont = (string) $_POST['pdf_font'];
807 $fonts = getPdfFonts();
808 if (!in_array($pdfFont, $fonts)) {
809 logNewMessage(LOG_ERR, 'Invalid font name: ' . $pdfFont);
810 die();
811 }
812 $option = $_POST['createFor'];
813 $fileName = '';
814 // create for clicked account
815 if ($option == 'DN') {
816 $_SESSION["accountPDF"] = new accountContainer($this->type, "accountPDF");
817 $_SESSION["accountPDF"]->load_account(base64_decode($_POST['clickedAccount']));
818 $fileName = createModulePDF([$_SESSION["accountPDF"]], $pdfStruct, $pdfFont);
819 unset($_SESSION["accountPDF"]);
820 } // create for all selected accounts
821 elseif ($option == 'SELECTED') {
822 // search for checkboxes
823 $accounts = array_keys($_POST, "on");
824 $list = [];
825 // load accounts from LDAP
826 for ($i = 0; $i < count($accounts); $i++) {
827 $_SESSION["accountPDF-$i"] = new accountContainer($this->type, "accountPDF-$i");
828 $_SESSION["accountPDF-$i"]->load_account(base64_decode($accounts[$i]));
829 $list[$i] = $_SESSION["accountPDF-$i"];
830 }
831 if ($list !== []) {
832 $fileName = createModulePDF($list, $pdfStruct, $pdfFont);
833 for ($i = 0; $i < count($accounts); $i++) {
834 unset($_SESSION["accountPDF-$i"]);
835 }
836 }
837 } // create for all accounts
838 elseif ($option == 'ALL') {
839 $list = [];
840 foreach ($this->entries as $entryPos) {
841 $_SESSION["accountPDF-$entryPos"] = new accountContainer($this->type, "accountPDF-$entryPos");
842 $_SESSION["accountPDF-$entryPos"]->load_account($this->ldapEntries[$entryPos]['dn']);
843 $list[$entryPos] = $_SESSION["accountPDF-$entryPos"];
844 }
845 if ($list !== []) {
846 $fileName = createModulePDF($list, $pdfStruct, $pdfFont);
847 foreach ($this->entries as $entryPos) {
848 // clean session
849 unset($_SESSION["accountPDF-$entryPos"]);
850 }
851 }
852 }
853 elseif ($option == 'SESSION') {
854 $fileName = createModulePDF([$_SESSION[$_POST['PDFSessionID']]], $pdfStruct, $pdfFont);
855 unset($_SESSION[$_POST['PDFSessionID']]);
856 }
857 if (!empty($fileName)) {
858 $tempFilesManager = new LamTemporaryFilesManager();
859 return new htmlJavaScript("window.open('" . $tempFilesManager->getDownloadLink($fileName) . "', '_blank');");
860 }
861 }
862 catch (LAMException $e) {
863 return new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
864 }
865 }
866 // check if back from configuration page
867 if ((count($this->configOptions) > 0) && isset($_POST['saveConfigOptions'])) {
868 $cookieValue = '';
869 for ($i = 0; $i < count($this->configOptions); $i++) {
870 $this->configOptions[$i]->fillFromPostData();
871 $cookieValue .= $this->configOptions[$i]->getID() . "=" . $this->configOptions[$i]->getValue() . ';';
872 }
873 // save options as cookie for one year
874 $cookieOptions = lamDefaultCookieOptions();
875 $cookieOptions['expires'] = time() + (60 * 60 * 24 * 365);
876 setcookie("ListOptions_" . $this->type->getId(), $cookieValue, $cookieOptions);
877 // notify subclasses
878 $this->listConfigurationChanged();
879 }
880 return null;
881 }
882
883 /**
884 * Shows the page where the user may select the PDF options.
885 *
886 * @param string|null $id account ID
887 */
888 private function showPDFPage($id): void {
889 $sessionObject = null;
890 $PDFSessionID = null;
891 if (($id == null) && isset($_GET['PDFSessionID'])) {
892 $PDFSessionID = $_GET['PDFSessionID'];
893 $sessionObject = $_SESSION[$PDFSessionID];
894 }
895 // search for checkboxes
896 $selAccounts = array_keys($_POST, "on");
897 if (!in_array($id, $selAccounts) && ($id !== null)) {
898 $selAccounts[] = $id;
899 }
900 if (in_array('tableSelectAll', $selAccounts)) {
901 $selAccounts = array_delete(['tableSelectAll'], $selAccounts);
902 }
903 // get possible PDF structures
904 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
905 $pdf_structures = $pdfStructurePersistenceManager->getPDFStructures($_SESSION['config']->getName(), $this->type->getId());
906
907 $this->printHeader();
908
909 echo "<div class=\"smallPaddingContent\">\n";
910 $refreshParam = '&amp;norefresh=true';
911 if (isset($_GET['refresh']) && ($_GET['refresh'] == 'true')) {
912 $refreshParam = '&amp;refresh=true';
913 }
914 echo "<form action=\"list.php?type=" . $this->type->getId() . $refreshParam . "\" method=\"post\">\n";
915
916 $container = new htmlResponsiveRow();
917 $container->add(new htmlSubTitle(_('Create PDF file')));
918
919 $container->add(new htmlResponsiveSelect('pdf_structure', $pdf_structures, ['default'], _('PDF structure'), '405'));
920 $fonts = getPdfFonts();
921 $fontSelection = new htmlResponsiveSelect('pdf_font', $fonts, [], _('Font'), '411');
922 $fontSelection->setCSSClasses(['lam-save-selection']);
923 $fontSelection->setHasDescriptiveElements(true);
924 $fontSelection->setSortElements(false);
925 $container->add($fontSelection);
926
927 $container->addVerticalSpacer('1rem');
928 $container->addLabel(new htmlOutputText(_('Create for')));
929 // check if account object is already in session
930 if ($sessionObject != null) {
931 $container->addField(new htmlOutputText(getAbstractDN($sessionObject->finalDN)));
932 $container->add(new htmlHiddenInput('createFor', 'SESSION'), 0);
933 $container->add(new htmlHiddenInput('PDFSessionID', $PDFSessionID), 0);
934 }
935 else {
936 $radioOptions = [
937 getAbstractDN(base64_decode($id)) => 'DN',
938 sprintf(_('All selected accounts (%s)'), count($selAccounts)) => 'SELECTED',
939 sprintf(_('All accounts (%s)'), count($this->entries)) => 'ALL'
940 ];
941 $container->addField(new htmlRadio('createFor', $radioOptions, 'DN'));
942 }
943
944 $container->addVerticalSpacer('2rem');
945 $container->addLabel(new htmlOutputText('&nbsp;', false));
946 $buttonContainer = new htmlGroup();
947 $buttonContainer->addElement(new htmlButton('createPDFok', _('Ok')));
948 $buttonContainer->addElement(new htmlSpacer('0.5rem', null));
949 $buttonContainer->addElement(new htmlButton('createPDFCancel', _('Cancel')));
950 $container->addField($buttonContainer);
951 // hidden inputs for selected accounts
952 for ($i = 0; $i < count($selAccounts); $i++) {
953 $container->add(new htmlHiddenInput($selAccounts[$i], 'on'), 0);
954 }
955 $container->add(new htmlHiddenInput('clickedAccount', $id), 0);
956 addSecurityTokenToMetaHTML($container);
957
958 parseHtml(null, $container, [], false);
959
960 $this->printFooter();
961 }
962
963 /**
964 * Prints a combobox with possible sub-DNs.
965 *
966 * @return htmlGroup OU selection (may be empty)
967 */
968 protected function listShowOUSelection() {
969 $group = new htmlGroup();
970 if (count($this->possibleSuffixes) > 1) {
971 $suffixList = [];
972 for ($i = 0; $i < count($this->possibleSuffixes); $i++) {
973 $suffixList[getAbstractDN($this->possibleSuffixes[$i])] = $this->possibleSuffixes[$i];
974 }
975 $suffixSelect = new htmlSelect('suffix', $suffixList, [$this->suffix]);
976 $suffixSelect->setOnchangeEvent("listOUchanged('" . $this->type->getId() . "', this)");
977 $suffixSelect->setRightToLeftTextDirection(true);
978 $suffixSelect->setSortElements(false);
979 $suffixSelect->setHasDescriptiveElements(true);
980 $suffixSelect->setAccessibilityLabel(_('Suffix'));
981 $group->addElement($suffixSelect);
982 }
983 return $group;
984 }
985
986 /**
987 * Prints the create and delete buttons.
988 *
989 * @param boolean $createOnly true if only the create button should be displayed
990 */
991 protected function listPrintButtons($createOnly): void {
992 $row = new htmlResponsiveRow();
993 $row->setCSSClasses(['maxrow lam-list-buttons']);
994 $left = new htmlGroup();
995 // button part
996 if (checkIfWriteAccessIsAllowed($this->type->getId())) {
997 // add button
998 if (checkIfNewEntriesAreAllowed($this->type->getId())) {
999 $newButton = new htmlButton('new', $this->labels['newEntry']);
1000 $newButton->setCSSClasses(['lam-primary fullwidth-mobile-only']);
1001 $left->addElement($newButton);
1002 }
1003 if ($this->type->getBaseType()->supportsFileUpload() && checkIfNewEntriesAreAllowed($this->type->getId())
1004 && $_SESSION['config']->isToolActive('toolFileUpload')) {
1005 $uploadButton = new htmlButton('fileUpload', _('File upload'));
1006 $uploadButton->setCSSClasses(['fullwidth-mobile-only lam-secondary']);
1007 $left->addElement($uploadButton);
1008 }
1009 // delete button
1010 if (!$createOnly && checkIfDeleteEntriesIsAllowed($this->type->getId())) {
1011 $delButton = new htmlButton('del', $this->labels['deleteEntry']);
1012 $delButton->setCSSClasses(['lam-danger fullwidth-mobile-only']);
1013 $left->addElement($delButton);
1014 }
1015 }
1016
1017 // OU selection and settings
1018 $right = new htmlResponsiveRow();
1019 $right->add($this->listShowOUSelection(), 12, 12, 10);
1020 $rightButtonGroup = new htmlGroup();
1021 $refreshButton = new htmlButton('refresh', 'refresh.svg', true);
1022 $refreshButton->setTitle(_("Refresh"));
1023 $rightButtonGroup->addElement($refreshButton);
1024 $settingsLink = new htmlLink('', '#', '../../graphics/configure.svg');
1025 $settingsLink->setOnClick('window.lam.accountLists.listShowSettingsDialog(\'' . _('Change list settings') . '\', \'' . _('Ok') . '\', \'' . _('Cancel') . '\');');
1026 $settingsLink->setTitle(_('Change settings'));
1027 $settingsLink->setCSSClasses(['icon']);
1028 $rightButtonGroup->addElement($settingsLink);
1029 $right->add($rightButtonGroup, 12, 12, 2);
1030
1031 $this->addExtraInputElementsToTopArea($left, $right);
1032 $row->add($left, 12, 6, 6, 'text-left');
1033 $row->add($right, 12, 6, 6, 'text-right');
1034 parseHtml(null, $row, [], false);
1035 }
1036
1037 /**
1038 * Can be used by subclasses to add e.g. additional buttons to the top area.
1039 *
1040 * @param htmlGroup $left left part
1041 * @param htmlResponsiveRow $right right part
1042 */
1043 protected function addExtraInputElementsToTopArea(&$left, &$right): void {
1044 // only used by subclasses
1045 }
1046
1047 /**
1048 * Prints the header part of the page.
1049 */
1050 private function printHeader(): void {
1051 include_once __DIR__ . '/adminHeader.inc';
1052 $row = new htmlResponsiveRow();
1053 $row->setCSSClasses(['maxrow']);
1054 $row->add(new htmlTitle($this->type->getAlias()));
1055 parseHtml(null, $row, [], true);
1056 $this->printHeaderContent();
1057 }
1058
1059 /**
1060 * Prints any extra HTML for the header part.
1061 */
1062 protected function printHeaderContent(): void {
1063 // implemented by child classes if needed
1064 }
1065
1066 /**
1067 * Prints the footer area of the page.
1068 */
1069 private function printFooter(): void {
1070 $this->printFooterContent();
1071 include_once __DIR__ . '/adminFooter.inc';
1072 }
1073
1074 /**
1075 * Prints any extra HTML for the footer part.
1076 */
1077 protected function printFooterContent(): void {
1078 ?>
1079 <input type="hidden" name="<?php echo getSecurityTokenName(); ?>"
1080 value="<?php echo getSecurityTokenValue(); ?>">
1081 </form>
1082 <?php
1083 }
1084
1085 /**
1086 * Returns an hash array containing with all attributes to be shown and their descriptions.
1087 * Format: array(attribute => description)
1088 *
1089 * @return array<string, string> attribute list
1090 */
1091 protected function listGetAttributeDescriptionList(): array {
1092 $attrs = $this->type->getAttributes();
1093 $ret = [];
1094 $predefinedDescriptions = $this->type->getBaseType()->getListAttributeDescriptions();
1095 $predefinedDescriptions = array_change_key_case($predefinedDescriptions);
1096 foreach ($attrs as $attr) {
1097 $ret[$attr->getAttributeName()] = $attr->getAlias($predefinedDescriptions);
1098 }
1099 if ($this->showAccountStatus) {
1100 $ret[self::ATTR_ACCOUNT_STATUS] = _('Account status');
1101 }
1102 return $ret;
1103 }
1104
1105 /**
1106 * Sets some internal parameters.
1107 */
1108 protected function listGetParams(): void {
1109 if (isset($_GET['accountEditBack'])) {
1110 $this->refresh = true;
1111 return;
1112 }
1113 // check if only PDF should be shown
1114 if (isset($_GET['printPDF'])) {
1115 $this->showPDFPage(null);
1116 exit();
1117 }
1118 // get current page
1119 $this->page = empty($_GET["page"]) ? 1 : $_GET["page"];
1120 // generate attribute-description table
1121 $temp_array = $this->listGetAttributeDescriptionList();
1122 $this->attrArray = array_keys($temp_array); // list of LDAP attributes to show
1123 $this->descArray = array_values($temp_array); // list of descriptions for the attributes
1124 // get sorting column
1125 if (isset($_GET["sort"]) && in_array_ignore_case($_GET["sort"], $this->attrArray)) {
1126 if ($_GET["sort"] == $this->sortColumn) {
1127 $this->sortDirection = -$this->sortDirection;
1128 }
1129 else {
1130 $this->sortColumn = $_GET["sort"];
1131 $this->sortDirection = 1;
1132 }
1133 }
1134 else {
1135 $this->sortColumn = strtolower($this->attrArray[0]);
1136 $this->sortDirection = 1;
1137 }
1138 // get sort order
1139 if (isset($_GET['sortdirection'])) {
1140 $this->sortDirection = ($_GET['sortdirection'] === '1') ? 1 : -1;
1141 }
1142 // check search suffix
1143 if (isset($_POST['suffix'])) {
1144 // new suffix selected via combobox
1145 $this->suffix = $_POST['suffix'];
1146 }
1147 elseif (isset($_GET['suffix'])) {
1148 // new suffix selected via combobox
1149 $this->suffix = $_GET['suffix'];
1150 }
1151 elseif (empty($this->suffix)) {
1152 // default suffix
1153 $this->suffix = $this->type->getSuffix();
1154 }
1155 // check if LDAP data should be refreshed
1156 $this->refresh = true;
1157 if (isset($_GET['norefresh'])) {
1158 $this->refresh = false;
1159 }
1160 if (isset($_POST['refresh'])) {
1161 $this->refresh = true;
1162 }
1163 if (isset($_POST['apply_filter']) || isset($_POST['clear_filter'])) {
1164 $noRefresh = '&norefresh=true';
1165 if ($this->serverSideFilterChanged) {
1166 $this->refresh = true;
1167 $noRefresh = '';
1168 }
1169 $filter = $this->getFilterAsTextForURL();
1170 metaRefresh("list.php?type=" . $this->type->getId() . "&page=1" .
1171 "&sort=" . $this->sortColumn . "&sortdirection=" . $this->sortDirection . $filter . $noRefresh);
1172 exit();
1173 }
1174 }
1175
1176 /**
1177 * Rereads the entries from LDAP.
1178 */
1179 protected function listRefreshData(): void {
1180 // check suffix
1181 if (empty($this->suffix)) {
1182 $this->suffix = $this->type->getSuffix(); // default suffix
1183 }
1184 // configure search filter
1185 $module_filter = get_ldap_filter($this->type->getId()); // basic filter is provided by modules
1186 $filter = "(&" . $module_filter . $this->buildLDAPAttributeFilter() . ")";
1187 $attrs = $this->attrArray;
1188 // remove virtual attributes from list
1189 for ($i = 0; $i < count($attrs); $i++) {
1190 if (str_starts_with($attrs[$i], self::VIRTUAL_ATTRIBUTE_PREFIX)) {
1191 unset($attrs[$i]);
1192 }
1193 }
1194 $attrs = array_values($attrs);
1195 // include additional attributes
1196 $additionalAttrs = $this->getAdditionalLDAPAttributesToRead();
1197 for ($i = 0; $i < count($additionalAttrs); $i++) {
1198 if (!in_array_ignore_case($additionalAttrs[$i], $attrs)) {
1199 $attrs[] = $additionalAttrs[$i];
1200 }
1201 }
1202 $this->ldapEntries = searchLDAP($this->suffix, $filter, $attrs);
1203 $this->entries = [];
1204 foreach ($this->ldapEntries as $index) {
1205 $this->entries[] = $index;
1206 }
1207 $lastError = getLastLDAPError();
1208 if ($lastError != null) {
1209 call_user_func_array(StatusMessage(...), $lastError);
1210 }
1211 // generate list of possible suffixes
1212 $this->possibleSuffixes = $this->type->getSuffixList();
1213 // show account status
1214 if ($this->showAccountStatus) {
1215 $this->injectAccountStatusAttribute();
1216 }
1217 }
1218
1219 /**
1220 * Builds the LDAP filter based on the filter entries in the GUI.
1221 *
1222 * @return String LDAP filter
1223 */
1224 protected function buildLDAPAttributeFilter() {
1225 $text = '';
1226 foreach ($this->filters as $attr => $filter) {
1227 if (!$this->isAttributeFilteredByServer($attr)) {
1228 continue;
1229 }
1230 $filterExpression = $filter;
1231 if (str_starts_with($filter, '^')) {
1232 $filterExpression = substr($filterExpression, 1);
1233 }
1234 elseif (!str_starts_with($filter, '*')) {
1235 $filterExpression = '*' . $filterExpression;
1236 }
1237 if (strrpos($filter, '$') === (strlen($filter) - 1)) {
1238 $filterExpression = substr($filterExpression, 0, -1);
1239 }
1240 elseif (strrpos($filter, '*') !== (strlen($filter) - 1)) {
1241 $filterExpression .= '*';
1242 }
1243 $text .= '(' . $attr . '=' . $filterExpression . ')';
1244 }
1245 return $text;
1246 }
1247
1248 /**
1249 * Specifies if the given attribute name is used for server side filtering (LDAP filter string).
1250 *
1251 * @param string $attrName attribute name
1252 * @return bool filter server side
1253 */
1254 protected function isAttributeFilteredByServer($attrName) {
1255 // do not filter status server side
1256 if ($attrName === self::ATTR_ACCOUNT_STATUS) {
1257 return false;
1258 }
1259 return in_array(strtolower($attrName), $this->serverSideFilterAttributes);
1260 }
1261
1262 /**
1263 * Applies any local filters for attributes that cannot be filtered server side.
1264 */
1265 protected function applyLocalFilters(): void {
1266 $this->entries = [];
1267 foreach (array_keys($this->ldapEntries) as $index) {
1268 $this->entries[] = $index;
1269 }
1270 // get custom filter functions
1271 $filterFunctions = [];
1272 $modules = $this->type->getModules();
1273 foreach ($modules as $module) {
1274 $moduleObj = moduleCache::getModule($module, $this->type->getScope());
1275 foreach (array_keys($this->filters) as $filterAttribute) {
1276 $attributeName = strtolower($filterAttribute);
1277 $filterFunction = $moduleObj->getListFilterFunction($attributeName);
1278 if ($filterFunction !== null) {
1279 $filterFunctions[$filterAttribute] = $filterFunction;
1280 }
1281 }
1282 }
1283 $toFilter = [];
1284 foreach ($this->filters as $filterAttribute => $filterValue) {
1285 if ($this->isAttributeFilteredByServer($filterAttribute) || ($filterValue === '')) {
1286 continue;
1287 }
1288 foreach ($this->entries as $index) {
1289 if (in_array($index, $toFilter)) {
1290 continue;
1291 }
1292 $regex = str_replace(['*'], ['.*'], $filterValue);
1293 $regex = '/' . $regex . '/i';
1294 if (!empty($filterFunctions[$filterAttribute])) {
1295 $value = $this->ldapEntries[$index][$filterAttribute] ?? null;
1296 if (!$filterFunctions[$filterAttribute]($value, $filterValue)) {
1297 $toFilter[] = $index;
1298 }
1299 }
1300 elseif (!$this->isFilterMatching($this->ldapEntries[$index], $filterAttribute, $regex)) {
1301 $toFilter[] = $index;
1302 }
1303 }
1304 }
1305 foreach ($toFilter as $index) {
1306 $pos = array_search($index, $this->entries);
1307 if ($pos !== false) {
1308 unset($this->entries[$pos]);
1309 }
1310 }
1311 $this->entries = array_values($this->entries);
1312 }
1313
1314 /**
1315 * Checks if the given LDAP data matches the filter.
1316 *
1317 * @param array<string, string|string[]> $data LDAP attributes
1318 * @param string $filterAttribute filter attribute name
1319 * @param string $regex filter attribute regex
1320 * @return bool filter matches the entry
1321 */
1322 protected function isFilterMatching(&$data, $filterAttribute, $regex): bool {
1323 if ($filterAttribute == self::ATTR_ACCOUNT_STATUS) {
1324 return preg_match($regex, $data[self::ATTR_ACCOUNT_STATUS][0]);
1325 }
1326 if (!isset($data[$filterAttribute])) {
1327 return false;
1328 }
1329 foreach ($data[$filterAttribute] as $value) {
1330 if (preg_match($regex, $value)) {
1331 return true;
1332 }
1333 }
1334 return false;
1335 }
1336
1337 /**
1338 * Forces a refresh of the LDAP data.
1339 * Function must be called before $this->refresh option is checked to load new LDAP data (e.g. in listGetParams).
1340 */
1341 protected function forceRefresh(): void {
1342 $this->refresh = true;
1343 if (isset($_GET['norefresh'])) {
1344 unset($_GET['norefresh']);
1345 }
1346 }
1347
1348 /**
1349 * Returns a list of additional LDAP attributes that should be read.
1350 * This can be used to show additional data even if the user selected other attributes to show in the list.
1351 *
1352 * @return string[] additional attribute names
1353 */
1354 protected function getAdditionalLDAPAttributesToRead(): array {
1355 $attrs = [];
1356 if ($this->showAccountStatus) {
1357 $modules = $_SESSION['config']->get_AccountModules($this->type->getId());
1358 foreach ($modules as $module) {
1359 $moduleObject = moduleCache::getModule($module, $this->type->getScope());
1360 if (!($moduleObject instanceof AccountStatusProvider)) {
1361 continue;
1362 }
1363 $attrs = array_merge($attrs, $moduleObject->getAccountStatusRequiredAttributes($this->type));
1364 }
1365 }
1366 return $attrs;
1367 }
1368
1369 /**
1370 * Returns a list of lamListTool objects to display next to the edit/delete buttons.
1371 *
1372 * @return lamListTool[] tools
1373 */
1374 protected function getAdditionalTools(): array {
1375 return [];
1376 }
1377
1378 /**
1379 * Returns a list of possible configuration options.
1380 *
1381 * @return lamListOption[] list of lamListOption objects
1382 */
1383 protected function listGetAllConfigOptions(): array {
1384 $options = [];
1385 $listSizeOption = new lamSelectListOption(_("Maximum list entries"),
1386 ['10', '20', '30', '50', '75', '100', '500', '1000'], self::LIST_SIZE_OPTION_NAME);
1387 $listSizeOption->setHelpID('208');
1388 $listSizeOption->setValue((string) $this->maxPageEntries);
1389 $options[] = $listSizeOption;
1390 if ($this->isSupportingAccountStatus()) {
1391 $options[] = new lamBooleanListOption(_('Show account status'), self::ACCOUNT_STATUS_OPTION_NAME);
1392 }
1393 return $options;
1394 }
1395
1396 /**
1397 * Prints the list configuration page.
1398 */
1399 protected function listPrintConfigurationPage(): void {
1400 echo "<div id=\"settingsDialog\" class=\"hidden dialog-content\">\n";
1401 echo "<form id=\"settingsDialogForm\" action=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true\" method=\"post\">\n";
1402
1403 $configContainer = new htmlResponsiveRow();
1404 for ($i = 0; $i < count($this->configOptions); $i++) {
1405 $configContainer->add($this->configOptions[$i]->getMetaHTML());
1406 }
1407 $configContainer->add(new htmlHiddenInput('saveConfigOptions', 'ok'));
1408 addSecurityTokenToMetaHTML($configContainer);
1409
1410 parseHtml('', $configContainer, [], false);
1411
1412 echo '</form>';
1413 echo "</div>\n";
1414 }
1415
1416 /**
1417 * Returns the configuration option with the given ID.
1418 *
1419 * @param string $ID ID
1420 * @return ?lamListOption option
1421 */
1422 protected function listGetConfigOptionByID(string $ID): ?lamListOption {
1423 for ($i = 0; $i < count($this->configOptions); $i++) {
1424 if ($this->configOptions[$i]->getID() === $ID) {
1425 return $this->configOptions[$i];
1426 }
1427 }
1428 return null;
1429 }
1430
1431 /**
1432 * Called when the configuration options changed.
1433 */
1434 protected function listConfigurationChanged(): void {
1435 $sizeOption = $this->listGetConfigOptionByID(self::LIST_SIZE_OPTION_NAME);
1436 if ($sizeOption->getValue() != null) {
1437 $this->maxPageEntries = intval($sizeOption->getValue());
1438 }
1439 // if account status was activated, reload LDAP data
1440 if ($this->isSupportingAccountStatus()) {
1441 $asOption = $this->listGetConfigOptionByID(self::ACCOUNT_STATUS_OPTION_NAME);
1442 $asOptionOldValue = $this->showAccountStatus;
1443 $this->showAccountStatus = ($asOption instanceof lamBooleanListOption) && $asOption->isSelected();
1444 if ($this->showAccountStatus && !$asOptionOldValue) {
1445 $this->forceRefresh();
1446 }
1447 }
1448 }
1449
1450 /**
1451 * Prints messages when another page (e.g. delete/upload) redirects to the list view.
1452 */
1453 protected function listPrintRedirectMessages():void {
1454 if (isset($_GET['deleteAllOk'])) {
1455 StatusMessage('INFO', _('Deletion was successful.'));
1456 }
1457 elseif (isset($_GET['uploadAllOk'])) {
1458 StatusMessage('INFO', _("Upload has finished"));
1459 if (isset($_SESSION['mass_pdf']['file'])) {
1460 $tempFilesManager = new LamTemporaryFilesManager();
1461 StatusMessage('INFO',
1462 _('You can download your PDF files %shere%s.'),
1463 '',
1464 [
1465 '<a href="' . $tempFilesManager->getDownloadLink($_SESSION['mass_pdf']['file']) . '">',
1466 '</a>'
1467 ]);
1468 }
1469 }
1470 elseif (isset($_GET['accountEditInvalidID'])) {
1471 StatusMessage('WARN', _('Please do not edit multiple accounts in parallel in multiple browser tabs.'));
1472 }
1473 if (isset($_SESSION['listRedirectMessages'])) {
1474 for ($i = 0; $i < count($_SESSION['listRedirectMessages']); $i++) {
1475 call_user_func_array(StatusMessage(...), $_SESSION['listRedirectMessages'][$i]);
1476 }
1477 unset($_SESSION['listRedirectMessages']);
1478 }
1479 }
1480
1481 /**
1482 * Injects values for the virtual account status attribute to make it sortable.
1483 */
1484 private function injectAccountStatusAttribute(): void {
1485 $entryCount = count($this->ldapEntries);
1486 for ($i = 0; $i < $entryCount; $i++) {
1487 $accountStatus = AccountStatus::fromAttributes($this->type, $this->ldapEntries[$i]);
1488 $status = self::FILTER_UNLOCKED;
1489 if ($accountStatus->isLocked()) {
1490 $status = self::FILTER_LOCKED;
1491 }
1492 elseif ($accountStatus->isPartiallyLocked()) {
1493 $status = self::FILTER_SEMILOCKED;
1494 }
1495 elseif ($accountStatus->isPartiallyExpired() || $accountStatus->isExpired()) {
1496 $status = self::FILTER_EXPIRED;
1497 }
1498 // add virtual attribute
1499 $this->ldapEntries[$i][self::ATTR_ACCOUNT_STATUS][0] = $status;
1500 }
1501 }
1502
1503 /**
1504 * Returns the account status.
1505 *
1506 * @param array<string, string[]|string> $attrs LDAP attributes
1507 * @return htmlElement content
1508 */
1509 private function getAccountStatus($attrs): htmlElement {
1510 $statusContent = new htmlGroup();
1511 $accountStatus = AccountStatus::fromAttributes($this->type, $attrs);
1512 $mainIcon = 'unlocked.svg';
1513 $altText = _('Unlocked');
1514 if ($accountStatus->isLocked()) {
1515 $mainIcon = 'locked.svg';
1516 $altText = _('Locked');
1517 }
1518 elseif ($accountStatus->isPartiallyLocked()) {
1519 $mainIcon = 'partiallyLocked.svg';
1520 $altText = _('Partially locked');
1521 }
1522 elseif ($accountStatus->isExpired()) {
1523 $mainIcon = 'expired.svg';
1524 $altText = _('Expired');
1525 }
1526 elseif ($accountStatus->isPartiallyExpired()) {
1527 $mainIcon = 'expired.svg';
1528 $altText = _('Expired');
1529 }
1530 $statusIcon = new htmlImage('../../graphics/' . $mainIcon, null, null, $altText);
1531 $statusIcon->setCSSClasses(['icon']);
1532 if (!empty($accountStatus->getDetails())) {
1533 $detailsTable = new htmlTable();
1534 foreach ($accountStatus->getDetails() as $detail) {
1535 $label = new htmlOutputText($detail->getDetails());
1536 $label->setNoWrap(true);
1537 $detailsTable->addElement($label);
1538 $statusDetailIcon = new htmlImage('../../graphics/' . $detail->getIcon(), '16px', '16px');
1539 $statusDetailIcon->setCSSClasses(['fixed-size-16']);
1540 $detailsTable->addElement($statusDetailIcon);
1541 $detailsTable->addNewLine();
1542 }
1543 $statusIcon->setHelpData(_('Account status'), $detailsTable);
1544 }
1545 $statusContent->addElement($statusIcon);
1546 return $statusContent;
1547 }
1548
1549 }
1550
1551 /**
1552 * Represents a tool which can be included in the account lists.
1553 *
1554 * @package lists
1555 * @author Roland Gruber
1556 */
1557 class lamListTool {
1558
1559 /** tool name */
1560 private string $name;
1561 /** tool image */
1562 private string $image;
1563 /** link target */
1564 private string $target;
1565
1566 /**
1567 * Constructor
1568 *
1569 * @param string $name tool name
1570 * @param string $image image file
1571 * @param string $target target page
1572 */
1573 public function __construct(string $name, string $image, string $target) {
1574 $this->name = $name;
1575 $this->image = $image;
1576 $this->target = $target;
1577 }
1578
1579 /**
1580 * Returns the name of the tool image.
1581 * The image is returned without path (e.g. mytool.png). All images must reside in the graphics folder.
1582 *
1583 * @return string image name
1584 */
1585 public function getImage(): string {
1586 return $this->image;
1587 }
1588
1589 /**
1590 * Returns the tool name.
1591 * This is used for the tool tip.
1592 *
1593 * @return string name
1594 */
1595 public function getName(): string {
1596 return $this->name;
1597 }
1598
1599 /**
1600 * Returns the PHP file (relative to 'templates/lists') which will be the target for this tool.
1601 * The target page will be opened with two GET parameters: DN and type (e.g. user)
1602 *
1603 * @return string page file (e.g. 'mytool.php')
1604 */
1605 public function getLinkTarget(): string {
1606 return $this->target;
1607 }
1608
1609 }
1610
1611 /**
1612 * Represents a list configuration option.
1613 *
1614 * @package lists
1615 * @author Roland Gruber
1616 */
1617 abstract class lamListOption {
1618
1619 /** unique ID */
1620 private string $ID;
1621 /** option value */
1622 private ?string $value = null;
1623
1624 /**
1625 * Creates a new config option.
1626 *
1627 * @param string $ID unique ID
1628 */
1629 public function __construct(string $ID) {
1630 $this->ID = $ID;
1631 }
1632
1633 /**
1634 * Returns the option ID.
1635 *
1636 * @return string ID
1637 */
1638 public function getID(): string {
1639 return $this->ID;
1640 }
1641
1642 /**
1643 * Fills the config option from POST data.
1644 */
1645 abstract public function fillFromPostData(): void;
1646
1647 /**
1648 * Returns the option value. The value must not contain "=" and ";".
1649 *
1650 * @return string|null value
1651 */
1652 public function getValue(): ?string {
1653 return $this->value;
1654 }
1655
1656 /**
1657 * Sets the config option value. The value must not contain "=" and ";".
1658 *
1659 * @param string $value value
1660 */
1661 public function setValue(string $value): void {
1662 if ((strpos($value, '=') > -1) || (strpos($value, ';') > -1)) {
1663 logNewMessage(LOG_ERR, "Invalid value for list option: " . $value);
1664 die();
1665 }
1666 $this->value = $value;
1667 }
1668
1669 /**
1670 * Returns the meta HTML data to display this option.
1671 *
1672 * @return htmlResponsiveRow meta HTML
1673 */
1674 abstract public function getMetaHTML(): htmlResponsiveRow;
1675
1676 }
1677
1678 /**
1679 * Boolean option for list configuration.
1680 *
1681 * @package lists
1682 * @author Roland Gruber
1683 */
1684 class lamBooleanListOption extends lamListOption {
1685
1686 /** option name */
1687 private string $name;
1688
1689 /**
1690 * Creates a new boolean option.
1691 *
1692 * @param string $name name to show on config page
1693 * @param string $ID unique ID
1694 */
1695 public function __construct(string $name, string $ID) {
1696 parent::__construct($ID);
1697 $this->name = $name;
1698 }
1699
1700 /**
1701 * Returns if this option is selected.
1702 *
1703 * @return bool true, if selected
1704 */
1705 public function isSelected(): bool {
1706 return ($this->getValue() === "1");
1707 }
1708
1709 /**
1710 * {@inheritDoc}
1711 */
1712 public function fillFromPostData(): void {
1713 if (isset($_POST[$this->getID()])) {
1714 $this->setValue("1");
1715 }
1716 else {
1717 $this->setValue("0");
1718 }
1719 }
1720
1721 /**
1722 * {@inheritDoc}
1723 * @see lamListOption::getMetaHTML()
1724 */
1725 public function getMetaHTML(): htmlResponsiveRow {
1726 $return = new htmlResponsiveRow();
1727 $return->add(new htmlResponsiveInputCheckbox($this->getID(), $this->isSelected(), $this->name));
1728 return $return;
1729 }
1730
1731 }
1732
1733 /**
1734 * Boolean option for list configuration.
1735 *
1736 * @package lists
1737 * @author Roland Gruber
1738 */
1739 class lamSelectListOption extends lamListOption {
1740
1741 /** option name */
1742 private string $name;
1743 /** @var string[] possible select options */
1744 private array $options;
1745 /** help ID */
1746 private ?string $helpID = null;
1747
1748 /**
1749 * Creates a new selection list option.
1750 *
1751 * @param string $name name to show on config page
1752 * @param string[] $options list of possible values
1753 * @param string $ID unique ID
1754 */
1755 public function __construct(string $name, array $options, string $ID) {
1756 parent::__construct($ID);
1757 $this->name = $name;
1758 $this->options = $options;
1759 }
1760
1761 /**
1762 * Sets the help ID.
1763 *
1764 * @param string $id help ID
1765 */
1766 public function setHelpID($id): void {
1767 $this->helpID = $id;
1768 }
1769
1770 /**
1771 * {@inheritDoc}
1772 */
1773 public function fillFromPostData(): void {
1774 if (isset($_POST[$this->getID()])) {
1775 $this->setValue($_POST[$this->getID()]);
1776 }
1777 else {
1778 $this->setValue('');
1779 }
1780 }
1781
1782 /**
1783 * {@inheritDoc}
1784 * @see lamListOption::getMetaHTML()
1785 */
1786 public function getMetaHTML(): htmlResponsiveRow {
1787 $return = new htmlResponsiveRow();
1788 $return->add(new htmlResponsiveSelect($this->getID(), $this->options, [$this->getValue()], $this->name, $this->helpID));
1789 return $return;
1790 }
1791
1792 }