Debian Codegraph @

lib/whitePages.inc

raw
1 <?php
2 /*
3
4 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
5 Copyright (C) 2025 - 2026 Roland Gruber
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
21
22 */
23
24 namespace LAM\WHITE_PAGES;
25
26 use htmlResponsiveInputField;
27 use htmlResponsiveRow;
28 use LAM\LIB\TWO_FACTOR\TwoFactorProviderService;
29 use LAM\PERSISTENCE\ConfigurationDatabase;
30 use LAMCfgMain;
31 use LamColorUtil;
32 use LAMException;
33 use LDAP\Connection;
34 use PDO;
35 use PDOException;
36 use function LAM\PERSISTENCE\dbTableExists;
37
38 /**
39 * Supported authentication types.
40 */
41 enum WP_AUTHENTICATION {
42
43 /**
44 * Anonymous authentication
45 */
46 case AUTH_ANONYMOUS;
47
48 /**
49 * User and password authentication.
50 */
51 case AUTH_USER_PASSWORD;
52
53 /**
54 * Trust the 2FA provider for authentication.
55 */
56 case AUTH_2FA_ONLY;
57
58 }
59
60 /**
61 * Display modes for white pages.
62 */
63 enum WP_DISPLAY_MODE: string {
64 case LIST_GALLERY = 'LIST_GALLERY';
65 case LIST_ONLY = 'LIST_ONLY';
66 case GALLERY_ONLY = 'GALLERY_ONLY';
67 }
68
69 /**
70 * Defines the display of a single item.
71 */
72 enum WP_ITEM_TYPE: string {
73
74 case IMAGE_JPG = 'IMAGE_JPG';
75 case TEXT = 'TEXT';
76 case EMAIL = 'EMAIL';
77 case TELEPHONE = 'TELEPHONE';
78 case LINK = 'LINK';
79
80 }
81
82 enum WP_THEMES: string {
83 case OCEAN = 'OCEAN';
84 case STARS = 'STARS';
85 case GRAND_CANYON = 'GRAND_CANYON';
86 case RAIN_FOREST = 'RAIN_FOREST';
87 case COAST = 'COAST';
88 case MOUNTAIN = 'MOUNTAIN';
89 case CITY = 'CITY';
90
91 /**
92 * Returns the image name.
93 *
94 * @return string image name
95 */
96 public function getImage(): string {
97 return match($this) {
98 self::OCEAN => 'background_jellyfish.jpg',
99 self::STARS => 'background_milkyway.jpg',
100 self::GRAND_CANYON => 'background_grandcanyon.jpg',
101 self::RAIN_FOREST => 'background_rainforest.jpg',
102 self::COAST => 'background_skyline.jpg',
103 self::MOUNTAIN => 'background_mountain.jpg',
104 self::CITY => 'background_city.jpg',
105 };
106 }
107
108 /**
109 * Returns the primary color.
110 *
111 * @return string color
112 */
113 public function getPrimaryColor(): string {
114 return match($this) {
115 self::OCEAN => '#1a5fb4',
116 self::STARS => '#2E4053',
117 self::GRAND_CANYON => '#E2786F',
118 self::RAIN_FOREST => '#2d5001',
119 self::COAST => '#03395f',
120 self::MOUNTAIN => '#45B3FA',
121 self::CITY => '#333333',
122 };
123 }
124
125 /**
126 * Returns the background color.
127 *
128 * @return string color
129 */
130 public function getBackgroundColor(): string {
131 return match($this) {
132 self::OCEAN => '#f9fdff',
133 self::STARS => '#DEDEDE',
134 self::GRAND_CANYON => '#F5F5DC',
135 self::RAIN_FOREST => '#EFF2E1',
136 self::COAST => '#f1fafc',
137 self::MOUNTAIN => '#FFFFFF',
138 self::CITY => '#F4F4ED',
139 };
140 }
141
142 }
143
144 /**
145 * White pages profile.
146 */
147 class WhitePagesProfile {
148
149 /**
150 * @var string LDAP server URL
151 */
152 public string $serverUrl = 'ldap://example.com';
153 /**
154 * @var bool activate TLS
155 */
156 public bool $useTLS = false;
157 /**
158 * @var bool follow referrals
159 */
160 public bool $followReferrals = true;
161 /**
162 * @var string LDAP technical user for connection
163 */
164 public string $ldapConnectionUser = '';
165 /**
166 * @var string password of technical user
167 */
168 public string $ldapConnectionPassword = '';
169 /**
170 * @var bool use technical user for all operations
171 */
172 public bool $useForAllOperations = false;
173 /**
174 * @var string language
175 */
176 public string $language = 'en_gb';
177
178 /**
179 * @var string authentication type
180 */
181 public string $authenticationType = 'AUTH_ANONYMOUS';
182 /**
183 * @var string LDAP suffix for users
184 */
185 public string $authenticationLdapSuffix = 'ou=people,dc=example,dc=com';
186 /**
187 * @var string LDAP search attribute to find the user for authentication
188 */
189 public string $authenticationLdapSearchAttribute = 'uid';
190 /**
191 * @var string additional LDAP search filter for user search
192 */
193 public string $authenticationLdapAdditionalSearchFilter = '';
194
195 /**
196 * @var string provider type
197 */
198 public string $twoFactorAuthenticationType = TwoFactorProviderService::TWO_FACTOR_NONE;
199 /**
200 * @var string authentication URL
201 */
202 public string $twoFactorAuthenticationURL = 'https://localhost';
203 /**
204 * @var bool allow insecure connection
205 */
206 public bool $twoFactorAuthenticationInsecure = false;
207 /**
208 * @var string label
209 */
210 public string $twoFactorAuthenticationLabel = '';
211 /**
212 * @var string caption
213 */
214 public string $twoFactorAuthenticationCaption = '';
215 /**
216 * @var string client ID
217 */
218 public string $twoFactorAuthenticationClientId = '';
219 /**
220 * @var string secret key
221 */
222 public string $twoFactorAuthenticationSecretKey = '';
223 /**
224 * @var string attribute that contains 2FA username
225 */
226 public string $twoFactorAuthenticationAttribute = 'uid';
227 /**
228 * @var string 2FA domain
229 */
230 public string $twoFactorAuthenticationDomain = '';
231 /**
232 * @var bool allow remembering the device
233 */
234 public bool $twoFactorAllowToRememberDevice = false;
235 /**
236 * @var int timeout for remembering the device
237 */
238 public int $twoFactorRememberDeviceDuration = 28800;
239 /**
240 * @var string password to reset remembered devices
241 */
242 public string $twoFactorRememberDevicePassword = '';
243
244 /** provider for captcha (-/google/hCaptcha/friendlyCaptcha) */
245 public string $captchaProvider = '-';
246 /** site key */
247 public string $captchaSiteKey = '';
248 /** secret key */
249 public string $captchaSecretKey = '';
250
251 /** describing text for search attribute */
252 public string $loginAttributeText = '';
253 /** label for password input */
254 public string $passwordLabel = '';
255 /** describing text for user login */
256 public string $loginCaption = '<p><strong>Welcome to LAM white pages. Please enter your user name and password.</strong></p>';
257 /** header HTML for login */
258 public string $loginHeader = '<p><a href="https://www.ldap-account-manager.org/" target="new_window"><img alt="help" class="align-middle" src="../../graphics/logo.svg" style="height:24px; width:24px"> <span style="color: rgb(255, 255, 255);">LDAP Account Manager </span></a></p><p>&nbsp;<br></p>';
259 /** describing text for user login */
260 public string $loginFooter = '<p style="text-align: left;"><span style="color: rgb(255, 255, 255);">Powered by LDAP Account Manager</span></p>';
261
262 /**
263 * @var string header HTML
264 */
265 public string $header = '<p><a href="https://www.ldap-account-manager.org/" target="new_window"><img alt="help" class="align-middle" src="../../graphics/logo.svg" style="height:24px; width:24px"> <span style="color: rgb(255, 255, 255);">LDAP Account Manager </span></a></p><p>&nbsp;<br></p>';
266 /**
267 * @var string footer HTML
268 */
269 public string $footer = '<p style="text-align: left;"><span style="color: rgb(255, 255, 255);">Powered by LDAP Account Manager</span></p>';
270 /**
271 * @var string custom CSS
272 */
273 public string $customCss = '';
274 /**
275 * @var string primary color
276 */
277 public string $primaryColor = '';
278 /**
279 * @var string background color
280 */
281 public string $backgroundColor = '';
282 /**
283 * @var string background image
284 */
285 public string $backgroundImage = '';
286 /**
287 * @var string display mode
288 */
289 public string $displayMode = 'LIST_GALLERY';
290
291 /**
292 * @var WhitePagesTab[] tabs for white pages
293 */
294 public array $tabs = [];
295
296 /**
297 * Imports data to a new profile.
298 *
299 * @param array<string, int|string|array<string, string|string[]|array<string, string>[]>[]> $data data as array
300 * @return WhitePagesProfile profile
301 */
302 public static function import(array $data): WhitePagesProfile {
303 $profile = new WhitePagesProfile();
304 $vars = get_class_vars(WhitePagesProfile::class);
305 foreach ($data as $key => $value) {
306 if ($key === 'tabs') {
307 foreach ($value as $tabData) {
308 $profile->tabs[] = WhitePagesTab::import($tabData);
309 }
310 }
311 elseif (array_key_exists($key, $vars)) {
312 $profile->$key = $value;
313 }
314 }
315 return $profile;
316 }
317
318 /**
319 * Exports the profile as an array.
320 *
321 * @return array<string, int|string|array<string, string|string[]|array<string, string>[]>[]> data
322 */
323 public function export(): array {
324 $data = [];
325 foreach (get_object_vars($this) as $key => $value) {
326 if ($key === 'tabs') {
327 $data[$key] = [];
328 foreach ($this->tabs as $tab) {
329 $data[$key][] = $tab->export();
330 }
331 }
332 else {
333 $data[$key] = $value;
334 }
335 }
336 return $data;
337 }
338
339 /**
340 * Returns the login handler.
341 *
342 * @return WhitePagesLoginHandler handler
343 */
344 public function getLoginHandler(): WhitePagesLoginHandler {
345 return match ($this->authenticationType) {
346 WP_AUTHENTICATION::AUTH_ANONYMOUS->name => new WhitePagesAnonymousAuthLoginHandler(),
347 WP_AUTHENTICATION::AUTH_2FA_ONLY->name => new WhitePages2FaLoginHandler($this),
348 default => new WhitePagesUserPasswordLoginHandler($this),
349 };
350 }
351
352 }
353
354 /**
355 * Single tab inside white pages.
356 */
357 class WhitePagesTab {
358
359 /**
360 * @var string LDAP suffix to find the entries to display
361 */
362 public string $ldapSuffix = 'ou=people,dc=example,dc=com';
363 /**
364 * @var string additional LDAP search filter for entry search
365 */
366 public string $additionalSearchFilter = '';
367
368 /**
369 * @var string display label
370 */
371 public string $label = 'Users';
372 /**
373 * @var string[] searchable LDAP attributes
374 */
375 public array $searchableAttributes = ['cn', 'sn', 'givenName', 'mail', 'telephoneNumber'];
376
377 /**
378 * @var string value to use for initial sorting
379 */
380 public string $initialSorting = '';
381
382 /**
383 * @var WhitePagesDisplayItem[] list items
384 */
385 public array $listItems = [];
386
387 /**
388 * @var string title for gallery view
389 */
390 public string $galleryTitle = '$givenName $sn';
391
392 /**
393 * @var WhitePagesDisplayItem[] gallery items
394 */
395 public array $galleryItems = [];
396
397 /**
398 * @var string title for gallery view
399 */
400 public string $detailViewTitle = '$givenName $sn';
401
402 /**
403 * @var WhitePagesDisplayItem[] detail view items
404 */
405 public array $detailViewItems = [];
406
407 /**
408 * Creates a new default tab.
409 *
410 * @return WhitePagesTab tab
411 */
412 public static function createDefault(): WhitePagesTab {
413 $tab = new WhitePagesTab();
414 $tab->listItems = [
415 new WhitePagesDisplayItem('First name', WP_ITEM_TYPE::TEXT, 'givenName'),
416 new WhitePagesDisplayItem('Last name', WP_ITEM_TYPE::TEXT, 'sn'),
417 new WhitePagesDisplayItem('Email', WP_ITEM_TYPE::EMAIL, 'mail'),
418 ];
419 $tab->galleryItems = [
420 new WhitePagesDisplayItem('Photo', WP_ITEM_TYPE::IMAGE_JPG, 'jpegPhoto'),
421 new WhitePagesDisplayItem('Name', WP_ITEM_TYPE::TEXT, '$givenName$ $sn$'),
422 ];
423 $tab->detailViewItems = [
424 new WhitePagesDisplayItem('Photo', WP_ITEM_TYPE::IMAGE_JPG, 'jpegPhoto'),
425 new WhitePagesDisplayItem('Full name', WP_ITEM_TYPE::TEXT, '$givenName$ $sn$'),
426 new WhitePagesDisplayItem('First name', WP_ITEM_TYPE::TEXT, 'givenName'),
427 new WhitePagesDisplayItem('Last name', WP_ITEM_TYPE::TEXT, 'sn'),
428 new WhitePagesDisplayItem('Email', WP_ITEM_TYPE::EMAIL, 'mail'),
429 new WhitePagesDisplayItem('Telephone', WP_ITEM_TYPE::TELEPHONE, 'telephoneNumber'),
430 new WhitePagesDisplayItem('Manager', WP_ITEM_TYPE::LINK, 'manager:cn'),
431 new WhitePagesDisplayItem('Groups', WP_ITEM_TYPE::LINK, 'memberOf:cn'),
432 ];
433 return $tab;
434 }
435
436 /**
437 * Imports data to a new tab.
438 *
439 * @param array<string, string|string[]|array<string, string>[]> $data data as array
440 * @return WhitePagesTab profile
441 */
442 public static function import(array $data): WhitePagesTab {
443 $tab = new WhitePagesTab();
444 $vars = get_class_vars(WhitePagesTab::class);
445 foreach ($data as $key => $value) {
446 if (in_array($key, ['listItems', 'galleryItems', 'detailViewItems'])) {
447 $tab->$key = [];
448 foreach ($value as $item) {
449 $tab->$key[] = WhitePagesDisplayItem::import($item);
450 }
451 }
452 elseif (array_key_exists($key, $vars)) {
453 $tab->$key = $value;
454 }
455 }
456 return $tab;
457 }
458
459 /**
460 * Exports the tab as an array.
461 *
462 * @return array<string, string|string[]|array<string, string>[]> data
463 */
464 public function export(): array {
465 $data = [];
466 foreach (get_object_vars($this) as $key => $value) {
467 if (in_array($key, ['listItems', 'galleryItems', 'detailViewItems'])) {
468 $itemsData = [];
469 foreach ($value as $item) {
470 $itemsData[] = $item->export();
471 }
472 $data[$key] = $itemsData;
473 }
474 else {
475 $data[$key] = $value;
476 }
477 }
478 return $data;
479 }
480
481 }
482
483 /**
484 * Specifies how a line/column should be rendered.
485 */
486 class WhitePagesDisplayItem {
487
488 /**
489 * @var WP_ITEM_TYPE render type of item
490 */
491 public WP_ITEM_TYPE $type;
492
493 /**
494 * @var string label of this item
495 */
496 public string $label;
497
498 /**
499 * @var string syntax of this item
500 */
501 public string $value;
502
503 /**
504 * Constructor
505 *
506 * @param string $label label
507 * @param WP_ITEM_TYPE $type render type
508 * @param string $value value
509 */
510 public function __construct(string $label = 'First name', WP_ITEM_TYPE $type = WP_ITEM_TYPE::TEXT, string $value = 'givenName') {
511 $this->label = $label;
512 $this->type = $type;
513 $this->value = $value;
514 }
515
516 /**
517 * Imports the display item from a string array.
518 *
519 * @param array<string, string> $data data
520 * @return WhitePagesDisplayItem item
521 */
522 public static function import(array $data): WhitePagesDisplayItem {
523 $label = $data['label'] ?? '';
524 $type = isset($data['type']) ? WP_ITEM_TYPE::from($data['type']) : WP_ITEM_TYPE::TEXT;
525 $value = $data['value'] ?? '';
526 return new WhitePagesDisplayItem($label, $type, $value);
527 }
528
529 /**
530 * Exports the item as an array.
531 *
532 * @return array<string, string> data
533 */
534 public function export(): array {
535 return [
536 'label' => $this->label,
537 'type' => $this->type->name,
538 'value' => $this->value
539 ];
540 }
541
542 }
543
544 /**
545 * Manages the reading and writing of white pages profiles.
546 */
547 class WhitePagesPersistence {
548
549 private WhitePagesPersistenceStrategy $strategy;
550
551 /**
552 * Constructor
553 *
554 * @throws LAMException error connecting database
555 */
556 public function __construct() {
557 $configDb = new ConfigurationDatabase(new LAMCfgMain());
558 if ($configDb->useRemoteDb()) {
559 try {
560 $this->strategy = new WhitePagesPersistenceStrategyPdo($configDb->getPdo());
561 }
562 catch (PDOException $e) {
563 logNewMessage(LOG_ERR, _('Unable to connect to configuration database.') . ' ' . $e->getMessage());
564 throw new LAMException(_('Unable to connect to configuration database.'), '', $e);
565 }
566 }
567 else {
568 $this->strategy = new WhitePagesPersistenceStrategyFileSystem();
569 }
570 }
571
572 /**
573 * Returns if the profile with given name can be written.
574 *
575 * @param string $name profile name
576 * @return bool can be written
577 */
578 public function canWrite(string $name): bool {
579 return $this->strategy->canWrite($name);
580 }
581
582 /**
583 * Loads the given white pages profile.
584 *
585 * @param string $name profile name
586 * @return WhitePagesProfile profile
587 * @throws LAMException error during loading
588 */
589 public function load(string $name): WhitePagesProfile {
590 return $this->strategy->load($name);
591 }
592
593 /**
594 * Stores the given profile.
595 *
596 * @param string $name profile name
597 * @param WhitePagesProfile $profile profile
598 * @throws LAMException error during saving
599 */
600 public function save(string $name, WhitePagesProfile $profile): void {
601 $this->strategy->save($name, $profile);
602 }
603
604 /**
605 * Deletes a white pages profile.
606 *
607 * @param string $name profile name
608 * @throws LAMException error deleting profile
609 */
610 public function delete(string $name): void {
611 $profileList = $this->getProfiles();
612 if (!preg_match("/^[a-z0-9_-]+$/i", $name)
613 || !in_array($name, $profileList)) {
614 throw new LAMException(_("Unable to delete profile!"));
615 }
616 $this->strategy->delete($name);
617 }
618
619 /**
620 * Returns a list of available white pages profiles.
621 *
622 * @return string[] profile names
623 */
624 public function getProfiles(): array {
625 $profiles = $this->strategy->getProfiles();
626 natcasesort($profiles);
627 return array_values($profiles);
628 }
629
630 /**
631 * Renames a white pages profile.
632 *
633 * @param string $oldName existing profile name
634 * @param string $newName new profile name
635 * @throws LAMException error renaming profile
636 */
637 public function rename(string $oldName, string $newName): void {
638 $profileList = $this->getProfiles();
639 if (!self::isValidProfileName($newName)
640 || !in_array($oldName, $profileList)) {
641 throw new LAMException(_("Profile name is invalid!"));
642 }
643 $this->strategy->rename($oldName, $newName);
644 }
645
646 /**
647 * Checks if the profile name is valid.
648 *
649 * @param string $name profile name
650 * @return bool is valid
651 */
652 public static function isValidProfileName(string $name): bool {
653 return preg_match("/^[a-z0-9_-]+$/i", $name);
654 }
655
656 }
657
658 /**
659 * Interface for white pages profile persistence.
660 */
661 interface WhitePagesPersistenceStrategy {
662
663 /**
664 * Returns a list of available white pages profiles.
665 *
666 * @return string[] profile names
667 */
668 public function getProfiles(): array;
669
670 /**
671 * Returns if the profile with given name can be written.
672 *
673 * @param string $name profile name
674 * @return bool can be written
675 */
676 public function canWrite(string $name): bool;
677
678 /**
679 * Loads the given white pages profile.
680 *
681 * @param string $name profile name
682 * @return WhitePagesProfile profile
683 * @throws LAMException error during loading
684 */
685 public function load(string $name): WhitePagesProfile;
686
687 /**
688 * Stores the given profile.
689 *
690 * @param string $name profile name
691 * @param WhitePagesProfile $profile profile
692 * @throws LAMException error during saving
693 */
694 public function save(string $name, WhitePagesProfile $profile): void;
695
696 /**
697 * Deletes a white pages profile.
698 *
699 * @param string $name profile name
700 * @throws LAMException error renaming profile
701 */
702 public function delete(string $name): void;
703
704 /**
705 * Renames a white pages profile.
706 *
707 * @param string $oldName existing profile name
708 * @param string $newName new profile name
709 * @throws LAMException error renaming profile
710 */
711 public function rename(string $oldName, string $newName): void;
712
713 }
714
715 /**
716 * Uses the local file system for storing white pages profiles.
717 */
718 class WhitePagesPersistenceStrategyFileSystem implements WhitePagesPersistenceStrategy {
719
720 /**
721 * @inheritDoc
722 */
723 public function getProfiles(): array {
724 $dir = dir(__DIR__ . "/../config/whitePages");
725 $ret = [];
726 if ($dir === false) {
727 logNewMessage(LOG_ERR, 'Unable to read white pages profiles');
728 return $ret;
729 }
730 while ($entry = $dir->read()) {
731 $name = substr($entry, 0, strrpos($entry, '.'));
732 if (str_ends_with($entry, '.json')) {
733 $ret[] = $name;
734 }
735 }
736 return $ret;
737 }
738
739 /**
740 * @inheritDoc
741 */
742 public function canWrite(string $name): bool {
743 // check the profile name
744 if (!WhitePagesPersistence::isValidProfileName($name)) {
745 return false;
746 }
747 $path = __DIR__ . "/../config/whitePages/" . $name . ".json";
748 return is_writable($path);
749 }
750
751 /**
752 * @inheritDoc
753 */
754 public function load(string $name): WhitePagesProfile {
755 if (!WhitePagesPersistence::isValidProfileName($name)) {
756 throw new LAMException(_("Profile name is invalid!"));
757 }
758 $file = __DIR__ . "/../config/whitePages/" . $name . ".json";
759 if (is_file($file)) {
760 $file = @fopen($file, "r");
761 if ($file) {
762 $data = fread($file, 10000000);
763 $profileData = @json_decode($data, true);
764 if ($profileData === null) {
765 logNewMessage(LOG_ERR, "Unable to load profile because not in JSON format: " . $name);
766 throw new LAMException(_("Unable to load profile!"), $name);
767 }
768 $profile = WhitePagesProfile::import($profileData);
769 fclose($file);
770 return $profile;
771 }
772 else {
773 throw new LAMException(_("Unable to load profile!"), $name);
774 }
775 }
776 else {
777 throw new LAMException(_("Unable to load profile!"), $name);
778 }
779 }
780
781 /**
782 * @inheritDoc
783 */
784 public function save(string $name, WhitePagesProfile $profile): void {
785 // check the profile name
786 if (!WhitePagesPersistence::isValidProfileName($name)) {
787 throw new LAMException(_("Profile name is invalid!"));
788 }
789 $path = __DIR__ . "/../config/whitePages/" . $name . ".json";
790 $file = @fopen($path, "w");
791 if ($file) {
792 // write settings to file
793 fwrite($file, json_encode($profile->export(), JSON_PRETTY_PRINT));
794 // close file
795 fclose($file);
796 @chmod($path, 0600);
797 }
798 else {
799 throw new LAMException(_("Unable to save profile!"));
800 }
801 }
802
803 /**
804 * @inheritDoc
805 */
806 public function delete(string $name): void {
807 if (!unlink("../../config/whitePages/" . $name . ".json")) {
808 throw new LAMException(_("Unable to delete profile!"));
809 }
810 }
811
812 /**
813 * @inheritDoc
814 */
815 public function rename(string $oldName, string $newName): void {
816 if (!@rename(__DIR__ . "/../config/whitePages/" . $oldName . ".json",
817 __DIR__ . "/../config/whitePages/" . $newName . ".json")) {
818 throw new LAMException(_("Could not rename file!"));
819 }
820 }
821
822 }
823
824 /**
825 * Uses PDO for storing white pages profiles.
826 */
827 class WhitePagesPersistenceStrategyPdo implements WhitePagesPersistenceStrategy {
828
829 private const TABLE_NAME = 'white_pages_profiles';
830 private PDO $pdo;
831
832 /**
833 * Constructor
834 *
835 * @param PDO $pdo PDO
836 */
837 public function __construct(PDO $pdo) {
838 $this->pdo = $pdo;
839 $this->checkSchema();
840 }
841
842 /**
843 * Checks if the schema has the latest version.
844 */
845 private function checkSchema(): void {
846 if (!dbTableExists($this->pdo, self::TABLE_NAME)) {
847 $this->createInitialSchema();
848 }
849 }
850
851 /**
852 * Creates the initial schema.
853 */
854 public function createInitialSchema(): void {
855 logNewMessage(LOG_DEBUG, 'Creating database table ' . self::TABLE_NAME);
856 $sql = 'create table ' . self::TABLE_NAME . '('
857 . 'name VARCHAR(300) NOT NULL,'
858 . 'data TEXT NOT NULL,'
859 . 'PRIMARY KEY(name)'
860 . ');';
861 $this->pdo->exec($sql);
862 $sql = 'insert into ' . ConfigurationDatabase::TABLE_SCHEMA_VERSIONS . ' (name, version) VALUES ("white_pages", 1);';
863 $this->pdo->exec($sql);
864 }
865
866 /**
867 * @inheritDocm
868 */
869 public function getProfiles(): array {
870 $statement = $this->pdo->prepare("SELECT name FROM " . self::TABLE_NAME);
871 $statement->execute();
872 $results = $statement->fetchAll();
873 $profiles = [];
874 foreach ($results as $result) {
875 $profiles[] = $result['name'];
876 }
877 return $profiles;
878 }
879
880 /**
881 * @inheritDoc
882 */
883 public function canWrite(string $name): bool {
884 return true;
885 }
886
887 /**
888 * @inheritDoc
889 */
890 public function load(string $name): WhitePagesProfile {
891 // check the profile name
892 if (!WhitePagesPersistence::isValidProfileName($name)) {
893 throw new LAMException(_("Profile name is invalid!"));
894 }
895 $statement = $this->pdo->prepare("SELECT data FROM " . self::TABLE_NAME . " WHERE name = ?");
896 $statement->execute([$name]);
897 $results = $statement->fetchAll();
898 if (empty($results)) {
899 logNewMessage(LOG_ERR, 'White pages profile not found');
900 throw new LAMException(_("Unable to load profile!"), $name);
901 }
902 $data = json_decode($results[0]['data'], true);
903 return WhitePagesProfile::import($data);
904 }
905
906 /**
907 * @inheritDoc
908 */
909 public function save(string $name, WhitePagesProfile $profile): void {
910 // check the profile name
911 if (!WhitePagesPersistence::isValidProfileName($name)) {
912 throw new LAMException(_("Profile name is invalid!"));
913 }
914 $data = json_encode($profile->export(), JSON_PRETTY_PRINT);
915 $statement = $this->pdo->prepare("SELECT data FROM " . self::TABLE_NAME . " WHERE name = ?");
916 $statement->execute([$name]);
917 $results = $statement->fetchAll();
918 if (empty($results)) {
919 $statement = $this->pdo->prepare("INSERT INTO " . self::TABLE_NAME . " (name, data) VALUES (?, ?)");
920 $statement->execute([$name, $data]);
921 }
922 else {
923 $statement = $this->pdo->prepare("UPDATE " . self::TABLE_NAME . " SET data = ? WHERE name = ?");
924 $statement->execute([$data, $name]);
925 }
926 }
927
928 /**
929 * @inheritDoc
930 */
931 public function delete(string $name): void {
932 $statement = $this->pdo->prepare("DELETE FROM " . self::TABLE_NAME . " WHERE name = ?");
933 $statement->execute([$name]);
934 }
935
936 /**
937 * @inheritDoc
938 */
939 public function rename(string $oldName, string $newName): void {
940 $statement = $this->pdo->prepare("UPDATE " . self::TABLE_NAME . " SET name = ? WHERE name = ?");
941 $statement->execute([$newName, $oldName]);
942 }
943
944 }
945
946 /**
947 * Login handler for white pages
948 */
949 interface WhitePagesLoginHandler {
950
951 /**
952 * Adds the necessary fields to the login dialog (e.g. user + password).
953 *
954 * @param htmlResponsiveRow $content dialog content
955 */
956 public function addLoginFields(htmlResponsiveRow $content): void;
957
958 /**
959 * Returns the login name.
960 *
961 * @return string login name
962 */
963 public function getLoginName(): string;
964
965 /**
966 * Returns the login password.
967 *
968 * @return string password
969 */
970 public function getLoginPassword(): string;
971
972 /**
973 * Returns if the login handler manages authentication on its own.
974 *
975 * @return bool manages authentication
976 */
977 public function managesAuthentication(): bool;
978
979 /**
980 * Returns if the authentication was successful.
981 * Only valid if managesAuthentication() returns true.
982 *
983 * @return bool authentication successful
984 * @throws LAMException error during authentication
985 */
986 public function isAuthenticationSuccessful(): bool;
987
988 /**
989 * Authorizes a user provided by the 2FA provider.
990 *
991 * @param string $userName user name
992 * @throws LAMException error during authentication
993 */
994 public function authorize2FaUser(string $userName): void;
995
996 }
997
998 /**
999 * Performs login with user and password.
1000 */
1001 class WhitePagesUserPasswordLoginHandler implements WhitePagesLoginHandler {
1002
1003 private WhitePagesProfile $profile;
1004
1005 /**
1006 * Constructor
1007 *
1008 * @param WhitePagesProfile $profile profile
1009 */
1010 public function __construct(WhitePagesProfile $profile) {
1011 $this->profile = $profile;
1012 }
1013
1014 /**
1015 * @inheritDoc
1016 */
1017 public function addLoginFields(htmlResponsiveRow $content): void {
1018 // user name
1019 $userNameVal = empty($_POST['username']) ? '' : $_POST['username'];
1020 $userText = _("User name");
1021 if (!empty($this->profile->loginAttributeText)) {
1022 $userText = $this->profile->loginAttributeText;
1023 }
1024 $userField = new htmlResponsiveInputField($userText, 'username', $userNameVal);
1025 $userField->setCSSClasses(['lam-initial-focus']);
1026 $content->add($userField);
1027 // password field
1028 $passwordText = _("Password");
1029 if (!empty($this->profile->passwordLabel)) {
1030 $passwordText = $this->profile->passwordLabel;
1031 }
1032 $passwordVal = empty($_POST['password']) ? '' : $_POST['password'];
1033 $passwordField = new htmlResponsiveInputField($passwordText, 'password', $passwordVal);
1034 $passwordField->setIsPassword(true);
1035 $content->add($passwordField);
1036 }
1037
1038 /**
1039 * @inheritDoc
1040 */
1041 public function getLoginName(): string {
1042 return $_POST['username'];
1043 }
1044
1045 /**
1046 * @inheritDoc
1047 */
1048 public function getLoginPassword(): string {
1049 return $_POST['password'];
1050 }
1051
1052 /**
1053 * @inheritDoc
1054 */
1055 public function managesAuthentication(): bool {
1056 return false;
1057 }
1058
1059 /**
1060 * @inheritDoc
1061 */
1062 public function isAuthenticationSuccessful(): bool {
1063 throw new LAMException('Not implemented');
1064 }
1065
1066 /**
1067 * @inheritDoc
1068 */
1069 public function authorize2FaUser(string $userName): void {
1070 // no action
1071 }
1072
1073 }
1074
1075 /**
1076 * Performs login with pure 2FA.
1077 */
1078 class WhitePages2FaLoginHandler implements WhitePagesLoginHandler {
1079
1080 private WhitePagesProfile $profile;
1081
1082 /**
1083 * Constructor
1084 *
1085 * @param WhitePagesProfile $profile profile
1086 */
1087 public function __construct(WhitePagesProfile $profile) {
1088 $this->profile = $profile;
1089 }
1090
1091 /**
1092 * @inheritDoc
1093 */
1094 public function addLoginFields(htmlResponsiveRow $content): void {
1095 // no input fields
1096 }
1097
1098 /**
1099 * @inheritDoc
1100 */
1101 public function getLoginName(): string {
1102 return '';
1103 }
1104
1105 /**
1106 * @inheritDoc
1107 */
1108 public function getLoginPassword(): string {
1109 return '';
1110 }
1111
1112 /**
1113 * @inheritDoc
1114 */
1115 public function managesAuthentication(): bool {
1116 return true;
1117 }
1118
1119 /**
1120 * @inheritDoc
1121 */
1122 public function isAuthenticationSuccessful(): bool {
1123 if (($this->profile->twoFactorAuthenticationType !== TwoFactorProviderService::TWO_FACTOR_OKTA)
1124 && ($this->profile->twoFactorAuthenticationType !== TwoFactorProviderService::TWO_FACTOR_OPENID)) {
1125 logNewMessage(LOG_ERR, 'Unsupported 2FA provider: ' . $this->profile->twoFactorAuthenticationType);
1126 return false;
1127 }
1128 if (!$this->profile->useForAllOperations) {
1129 logNewMessage(LOG_ERR, 'Use for all operations must be set');
1130 return false;
1131 }
1132 // authentication will be checked on the 2FA page
1133 return true;
1134 }
1135
1136 /**
1137 * @inheritDoc
1138 */
1139 public function authorize2FaUser(string $userName): void {
1140 $bindUser = $this->profile->ldapConnectionUser;
1141 if (empty($bindUser)) {
1142 throw new LAMException('WhitePages2FaLoginHandler', 'No bind user set');
1143 }
1144 $bindPassword = deobfuscateText($this->profile->ldapConnectionPassword);
1145 $server = connectToLDAP($this->profile->serverUrl, $this->profile->useTLS);
1146 if ($server === null) {
1147 throw new LAMException('WhitePages2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP connect failed');
1148 }
1149 ldap_set_option($server, LDAP_OPT_REFERRALS, $this->profile->followReferrals);
1150 $bind = @ldap_bind($server, $bindUser, $bindPassword);
1151 if (!$bind) {
1152 throw new LAMException('WhitePages2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP bind failed');
1153 }
1154 $filter = '(' . $this->profile->twoFactorAuthenticationAttribute . "=" . ldap_escape($userName, '', LDAP_ESCAPE_FILTER) . ')';
1155 if (!empty($this->profile->additionalLDAPFilter)) {
1156 $filter = '(&' . $filter . $this->profile->additionalLDAPFilter . ')';
1157 }
1158 $result = @ldap_search($server, $this->profile->authenticationLdapSuffix, $filter, ['DN'], 0, 1, 0, LDAP_DEREF_NEVER);
1159 if ($result === false) {
1160 throw new LAMException('WhitePages2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP search failed');
1161 }
1162 $entries = @ldap_get_entries($server, $result);
1163 if ($entries === false) {
1164 throw new LAMException('WhitePages2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP search failed');
1165 }
1166 $info = $entries;
1167 cleanLDAPResult($info);
1168 if (count($info) === 1) {
1169 $userDN = $info[0]['dn'];
1170 $_SESSION['whitePages_clientDN'] = lamEncrypt($userDN, 'WhitePages');
1171 return;
1172 }
1173 throw new LAMException('WhitePages2FaLoginHandler', 'Multiple or no results for ' . $userName . ' ' . print_r($info, true));
1174 }
1175
1176 }
1177
1178 /**
1179 * Performs anonymous access.
1180 */
1181 class WhitePagesAnonymousAuthLoginHandler implements WhitePagesLoginHandler {
1182
1183 /**
1184 * @inheritDoc
1185 */
1186 public function addLoginFields(htmlResponsiveRow $content): void {
1187 // no input fields
1188 }
1189
1190 /**
1191 * @inheritDoc
1192 */
1193 public function getLoginName(): string {
1194 return '';
1195 }
1196
1197 /**
1198 * @inheritDoc
1199 */
1200 public function getLoginPassword(): string {
1201 return '';
1202 }
1203
1204 /**
1205 * @inheritDoc
1206 */
1207 public function managesAuthentication(): bool {
1208 return true;
1209 }
1210
1211 /**
1212 * @inheritDoc
1213 */
1214 public function isAuthenticationSuccessful(): bool {
1215 // authentication is not needed
1216 return true;
1217 }
1218
1219 /**
1220 * @inheritDoc
1221 */
1222 public function authorize2FaUser(string $userName): void {
1223 // not used
1224 }
1225
1226 }
1227
1228 /**
1229 * Creates styles for white pages.
1230 */
1231 class WhitePagesStyling {
1232
1233 /**
1234 * Creates the main style tag for the page header.
1235 *
1236 * @param WhitePagesProfile $profile profile
1237 * @return string style tag
1238 */
1239 public static function getMainStyleTag(WhitePagesProfile $profile): string {
1240 if (empty($profile->backgroundImage)) {
1241 $image = 'background-color: ' . $profile->backgroundColor . ';';
1242 }
1243 elseif (str_starts_with($profile->backgroundImage, 'http') || str_starts_with($profile->backgroundImage, '/')) {
1244 $image = 'background-image: url(' . htmlspecialchars($profile->backgroundImage) . ');';
1245 }
1246 else {
1247 $image = 'background-image: url(../../graphics/' . htmlspecialchars($profile->backgroundImage) . ');';
1248 }
1249 $backGroundColor = LamColorUtil::parseColor($profile->backgroundColor);
1250 return '<style>
1251 :root {
1252 --lam-background-color-primary: ' . htmlspecialchars($profile->primaryColor) . ';
1253 --lam-background-color-default: ' . htmlspecialchars($profile->backgroundColor) . ';
1254 --swal2-background: ' . htmlspecialchars($profile->backgroundColor) . ';
1255 --lam-border-color-primary: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->primaryColor, 0.8)) . ';
1256 --lam-text-color-primary: ' . htmlspecialchars(LamColorUtil::getTextColor($profile->primaryColor)) . ';
1257 --lam-text-color-default: ' . htmlspecialchars(LamColorUtil::getTextColor($profile->backgroundColor)) . ';
1258 --lam-whitepages-color-primary: ' . htmlspecialchars($profile->primaryColor) . ';
1259 --lam-whitepages-color-background: ' . htmlspecialchars($profile->backgroundColor) . ';
1260 --lam-whitepages-color-panel: rgba(' . $backGroundColor->red . ', ' . $backGroundColor->green . ', ' . $backGroundColor->blue . ');
1261 --lam-whitepages-color-border: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->backgroundColor, 0.8)) . ';
1262 --lam-whitepages-color-card: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->backgroundColor, 2)) . ';
1263 --lam-whitepages-blur: 4px;
1264 --lam-table-background-color-bright: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->backgroundColor, 1.5)) . ';
1265 --lam-table-background-color-dark: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->backgroundColor, 0.95)) . ';
1266 --lam-table-background-color-hover: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->backgroundColor, 0.8)) . ';
1267 --lam-table-text-color-hover: ' . htmlspecialchars(LamColorUtil::getTextColor(LamColorUtil::adjustBrightness($profile->backgroundColor, 0.8))) . ';
1268 --lam-table-border-color: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->backgroundColor, 0.8)) . ';
1269 --lam-border-color: ' . htmlspecialchars(LamColorUtil::adjustBrightness($profile->backgroundColor, 0.8)) . ';
1270 }
1271
1272 div.lam-full-size-background {
1273 ' . $image . '
1274 background-size: cover;
1275 background-repeat: no-repeat;
1276 background-position: center top;
1277 width: 100vw;
1278 height: 100vh;
1279 position: absolute;
1280 overflow: hidden;
1281 top: 0;
1282 left: 0;
1283 z-index: -1;
1284 filter: blur(var(--lam-whitepages-blur));
1285 }
1286 </style>';
1287 }
1288
1289 /**
1290 * Returns a list of installed background image names.
1291 *
1292 * @return string[] image file names
1293 */
1294 public static function getBackgroundImageNames(): array {
1295 $dir = dir(__DIR__ . '/../graphics');
1296 if ($dir === false) {
1297 return [];
1298 }
1299 $imageNames = [];
1300 $fileName = $dir->read();
1301 while ($fileName !== false) {
1302 if (str_starts_with($fileName, 'background_')) {
1303 $imageNames[] = $fileName;
1304 }
1305 $fileName = $dir->read();
1306 }
1307 return $imageNames;
1308 }
1309
1310 }
1311
1312 /**
1313 * LDAP connection for white pages.
1314 */
1315 class WhitePagesLdapConnection {
1316
1317 private ?Connection $server = null;
1318
1319 private WhitePagesProfile $profile;
1320
1321 private bool $bindDone = false;
1322
1323 /**
1324 * Constructor
1325 *
1326 * @param WhitePagesProfile $profile profile
1327 */
1328 public function __construct(WhitePagesProfile $profile) {
1329 $this->profile = $profile;
1330 }
1331
1332 /**
1333 * Returns the LDAP handle.
1334 *
1335 * @return Connection|null LDAP handle
1336 */
1337 public function getServer(): ?Connection {
1338 if ($this->server !== null) {
1339 return $this->server;
1340 }
1341 $this->server = $this->openLdapConnection($this->profile);
1342 return $this->server;
1343 }
1344
1345 /**
1346 * Opens the LDAP connection and returns the handle. No bind is done.
1347 *
1348 * @param WhitePagesProfile $profile profile
1349 * @return Connection|null LDAP handle or null if the connection failed
1350 */
1351 private function openLdapConnection(WhitePagesProfile $profile): ?Connection {
1352 $server = connectToLDAP($profile->serverUrl, $profile->useTLS);
1353 if ($server != null) {
1354 // follow referrals
1355 ldap_set_option($server, LDAP_OPT_REFERRALS, $profile->followReferrals);
1356 }
1357 return $server;
1358 }
1359
1360 /**
1361 * Binds with the given credentials.
1362 *
1363 * @param string $userDn user DN
1364 * @param string $password password
1365 * @return bool bind was successful
1366 */
1367 public function bind(string $userDn, string $password): bool {
1368 if ($this->profile->useForAllOperations) {
1369 $userDn = $this->profile->ldapConnectionUser;
1370 $password = deobfuscateText($this->profile->ldapConnectionPassword);
1371 }
1372 logNewMessage(LOG_DEBUG, 'White pages, bind with ' . $userDn);
1373 $result = @ldap_bind($this->getServer(), $userDn, $password);
1374 if ($result) {
1375 $this->bindDone = true;
1376 }
1377 return $result;
1378 }
1379
1380 /**
1381 * Closes connection to the LDAP server before serialization.
1382 *
1383 * @return array<string, WhitePagesProfile> data
1384 */
1385 public function __serialize(): array {
1386 if ($this->server !== null) {
1387 @ldap_close($this->server);
1388 $this->server = null;
1389 }
1390 // define which attributes to save
1391 return ['profile' => $this->profile];
1392 }
1393
1394 /**
1395 * Restores the profile.
1396 *
1397 * @param array<string, WhitePagesProfile> $data data
1398 */
1399 public function __unserialize(array $data): void {
1400 $this->profile = $data['profile'];
1401 }
1402
1403 /**
1404 * Returns if a bind was already done.
1405 *
1406 * @return bool bind was done
1407 */
1408 public function isBinded(): bool {
1409 return $this->bindDone;
1410 }
1411
1412 }
1413
1414 /**
1415 * Utility class for search support.
1416 */
1417 class WhitePagesSearch {
1418
1419 private const SEPARATOR = '|';
1420
1421 /**
1422 * Generates the search data.
1423 *
1424 * @param array<string, string[]|string> $attributes LDAP attributes
1425 * @param string[] $searchAttributes LDAP attributes to add to search (lower-case)
1426 * @return string search string
1427 */
1428 public static function getSearchData(array $attributes, array $searchAttributes): string {
1429 $data = '';
1430 foreach ($searchAttributes as $searchAttribute) {
1431 if (!isset($attributes[$searchAttribute])) {
1432 continue;
1433 }
1434 if (is_array($attributes[$searchAttribute])) {
1435 $data .= self::SEPARATOR . implode(self::SEPARATOR, $attributes[$searchAttribute]);
1436 }
1437 else {
1438 $data .= self::SEPARATOR . $attributes[$searchAttribute];
1439 }
1440 }
1441 return $data;
1442 }
1443
1444 }