Debian Codegraph @

lib/persistence.inc

raw
1 <?php
2
3 namespace LAM\PERSISTENCE;
4
5 use LAM\DB\CronDatabase;
6 use LAM\LOGIN\WEBAUTHN\WebauthnManager;
7 use LAM\PDF\PDFStructure;
8 use LAM\PDF\PdfStructurePersistenceManager;
9 use LAM\PROFILES\AccountProfilePersistenceManager;
10 use LAM\WHITE_PAGES\WhitePagesPersistence;
11 use LAM\WHITE_PAGES\WhitePagesProfile;
12 use LAMCfgMain;
13 use LAMConfig;
14 use LAMException;
15 use PDO;
16 use PDOException;
17 use SelfServicePersistence;
18 use selfServiceProfile;
19 use ServerProfilePersistenceManager;
20
21 /*
22
23 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
24 Copyright (C) 2020 - 2026 Roland Gruber
25
26 This program is free software; you can redistribute it and/or modify
27 it under the terms of the GNU General Public License as published by
28 the Free Software Foundation; either version 2 of the License, or
29 (at your option) any later version.
30
31 This program is distributed in the hope that it will be useful,
32 but WITHOUT ANY WARRANTY; without even the implied warranty of
33 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 GNU General Public License for more details.
35
36 You should have received a copy of the GNU General Public License
37 along with this program; if not, write to the Free Software
38 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
39
40 */
41
42 /**
43 * This file includes functions to manage the persistence of LAM's configuration files.
44 *
45 * @package configuration
46 * @author Roland Gruber
47 */
48
49 include_once __DIR__ . '/config.inc';
50 include_once __DIR__ . '/profiles.inc';
51 include_once __DIR__ . '/whitePages.inc';
52
53 /**
54 * Exporter for LAM's configuration data.
55 */
56 class ConfigDataExporter {
57
58 /**
59 * Exports LAM's configuration data in JSON format.
60 *
61 * @return string JSON
62 * @throws LAMException error during export
63 */
64 public function exportAsJson(): string {
65 $mainCfg = $this->_getMainConfiguration();
66 $jsonData = [];
67 $jsonData['mainConfig'] = $this->_getMainConfigData($mainCfg);
68 $jsonData['certificates'] = $this->_getCertificates($mainCfg);
69 $serverProfilesPersistenceManager = new ServerProfilePersistenceManager();
70 $serverProfileNames = $serverProfilesPersistenceManager->getProfiles();
71 $serverProfiles = [];
72 foreach ($serverProfileNames as $serverProfileName) {
73 $serverProfiles[$serverProfileName] = $serverProfilesPersistenceManager->loadProfile($serverProfileName);
74 }
75 $jsonData['serverProfiles'] = $this->_getServerProfiles($serverProfiles);
76 $jsonData['accountProfiles'] = $this->_getAccountProfiles($serverProfiles);
77 $jsonData['accountProfileTemplates'] = $this->_getAccountProfileTemplates();
78 $jsonData['pdfProfiles'] = $this->_getPdfProfiles($serverProfiles);
79 $jsonData['pdfProfileTemplates'] = $this->_getPdfProfileTemplates();
80 $jsonData['selfServiceProfiles'] = $this->_getSelfServiceProfiles();
81 $jsonData['whitePagesProfiles'] = $this->_getWhitePagesProfiles();
82 $jsonData['webauthn'] = $this->_getWebauthn();
83 $jsonData['cronJobs'] = $this->_getCronJobData($serverProfiles);
84 $jsonData['requestAccess'] = $this->_getRequestAccessData();
85 return json_encode($jsonData);
86 }
87
88 /**
89 * Returns the main configuration.
90 *
91 * @return LAMCfgMain main config
92 */
93 public function _getMainConfiguration(): LAMCfgMain {
94 return new LAMCfgMain();
95 }
96
97 /**
98 * Internal function to read master configuration.
99 *
100 * @param LAMCfgMain $mainCfg main config
101 * @return array<string, string|string[]|int|bool|null> data
102 */
103 public function _getMainConfigData(LAMCfgMain $mainCfg): array {
104 return $mainCfg->exportData(true);
105 }
106
107 /**
108 * Returns the certificate file content.
109 *
110 * @param LAMCfgMain $mainCfg main config
111 * @return string|null data
112 */
113 public function _getCertificates(LAMCfgMain $mainCfg): ?string {
114 return $mainCfg->exportCertificates();
115 }
116
117 /**
118 * Returns the content of the server profiles.
119 *
120 * @param array<string, LAMConfig> $serverProfiles list of server profiles (name => object)
121 * @return array<string, array<string, string|int|bool|null|object|array<string, string|string[]>>> data
122 */
123 public function _getServerProfiles(array $serverProfiles): array {
124 return array_map(fn($serverProfile) => $serverProfile->exportData(), $serverProfiles);
125 }
126
127 /**
128 * Returns the content of the account profiles.
129 *
130 * @param array<string, LAMConfig> $serverProfiles list of server profiles (name => object)
131 * @return array<string, array<string, array<string, array<string, string[]>>>> $data export data
132 * @throws LAMException error reading profiles
133 */
134 public function _getAccountProfiles(array $serverProfiles): array {
135 $data = [];
136 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
137 foreach ($serverProfiles as $profileName => $serverProfile) {
138 foreach ($serverProfile->get_ActiveTypes() as $typeId) {
139 $accountProfileNames = $accountProfilePersistenceManager->getAccountProfileNames($typeId, $profileName);
140 foreach ($accountProfileNames as $accountProfileName) {
141 $accountProfile = $accountProfilePersistenceManager->loadAccountProfile($typeId, $accountProfileName, $profileName);
142 $data[$profileName][$typeId][$accountProfileName] = $accountProfile;
143 }
144 }
145 }
146 return $data;
147 }
148
149 /**
150 * Returns the content of the account profile templates.
151 *
152 * @return array<string, array<string, array<string, string[]>>> $data export data
153 * @throws LAMException error reading template
154 */
155 public function _getAccountProfileTemplates(): array {
156 $data = [];
157 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
158 $accountProfileTemplateNames = $accountProfilePersistenceManager->getAccountProfileTemplateNames();
159 foreach ($accountProfileTemplateNames as $scope => $templateNames) {
160 foreach ($templateNames as $templateName) {
161 $accountProfileTemplate = $accountProfilePersistenceManager->loadAccountProfileTemplate($scope, $templateName);
162 $data[$scope][$templateName] = $accountProfileTemplate;
163 }
164 }
165 return $data;
166 }
167
168 /**
169 * Returns the content of the PDF profiles.
170 *
171 * @param array<string, LAMConfig> $serverProfiles list of server profiles (name => object)
172 * @return array<string, mixed> $data
173 * @throws LAMException error reading logo
174 */
175 public function _getPdfProfiles(array $serverProfiles): array {
176 $data = [];
177 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
178 foreach ($serverProfiles as $profileName => $serverProfile) {
179 foreach ($serverProfile->get_ActiveTypes() as $typeId) {
180 $pdfProfileNames = $pdfStructurePersistenceManager->getPDFStructures($profileName, $typeId);
181 foreach ($pdfProfileNames as $pdfProfileName) {
182 $pdfStructure = $pdfStructurePersistenceManager->readPdfStructure($profileName, $typeId, $pdfProfileName);
183 $data[$profileName]['structures'][$typeId][$pdfProfileName] = $pdfStructure->export();
184 }
185 }
186 $logoData = $pdfStructurePersistenceManager->getPdfLogos($profileName);
187 foreach ($logoData as $logo) {
188 $logoName = $logo->getName();
189 $logoBinary = $pdfStructurePersistenceManager->getPdfLogoBinary($profileName, $logoName);
190 $data[$profileName]['logos'][$logoName] = base64_encode($logoBinary);
191 }
192 }
193 return $data;
194 }
195
196 /**
197 * Returns the content of the account profile templates.
198 *
199 * @return array<string, mixed> $data
200 * @throws LAMException error reading template
201 */
202 public function _getPdfProfileTemplates(): array {
203 $data = [];
204 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
205 $pdfTemplateNames = $pdfStructurePersistenceManager->getPdfStructureTemplateNames();
206 foreach ($pdfTemplateNames as $scope => $templateNames) {
207 foreach ($templateNames as $templateName) {
208 $pdfStructure = $pdfStructurePersistenceManager->readPdfStructureTemplate($scope, $templateName);
209 $data['structures'][$scope][$templateName] = $pdfStructure->export();
210 }
211 }
212 $logoNames = $pdfStructurePersistenceManager->getPdfTemplateLogoNames();
213 foreach ($logoNames as $logoName) {
214 $data['logos'][$logoName] = base64_encode($pdfStructurePersistenceManager->getPdfTemplateLogoBinary($logoName));
215 }
216 return $data;
217 }
218
219 /**
220 * Returns the content of the self-service profiles.
221 *
222 * @return array<string, array<string, array<string, string|int>>> data
223 */
224 public function _getSelfServiceProfiles(): array {
225 $data = [];
226 $selfServicePersistence = new SelfServicePersistence();
227 $profileTypes = $selfServicePersistence->getProfiles();
228 foreach ($profileTypes as $profileType => $profileNames) {
229 foreach ($profileNames as $profileName) {
230 try {
231 $profile = $selfServicePersistence->load($profileName, $profileType);
232 }
233 catch (LAMException $e) {
234 logNewMessage(LOG_ERR, $e->getTitle() . ' ' . $profileName);
235 continue;
236 }
237 $data[$profileType][$profileName] = $profile->export();
238 }
239 }
240 return $data;
241 }
242
243 /**
244 * Returns the content of the white pages profiles.
245 *
246 * @return array<string, array<string, int|string|array<string, string|string[]|array<string, string>[]>[]>> data
247 */
248 public function _getWhitePagesProfiles(): array {
249 $data = [];
250 $whitePagesPersistence = new WhitePagesPersistence();
251 $profiles = $whitePagesPersistence->getProfiles();
252 foreach ($profiles as $profileName) {
253 try {
254 $profile = $whitePagesPersistence->load($profileName);
255 }
256 catch (LAMException $e) {
257 logNewMessage(LOG_ERR, $e->getTitle() . ' ' . $profileName);
258 continue;
259 }
260 $data[$profileName] = $profile->export();
261 }
262 return $data;
263 }
264
265 /**
266 * Returns the content of the webauthn database.
267 *
268 * @return array<array<string, mixed>> data
269 */
270 public function _getWebauthn(): array {
271 $data = [];
272 if (extension_loaded('PDO')
273 && in_array('sqlite', PDO::getAvailableDrivers())) {
274 include_once __DIR__ . '/webauthn.inc';
275 $webauthnManager = new WebauthnManager();
276 $webauthnDatabase = $webauthnManager->getDatabase();
277 $data = $webauthnDatabase->export();
278 }
279 return $data;
280 }
281
282 /**
283 * Returns the content of the cron jobs.
284 *
285 * @param array<string, LAMConfig> $serverProfiles list of server profiles (name => object)
286 * @return mixed[] data
287 * @throws LAMException error reading cron jobs
288 */
289 public function _getCronJobData(array $serverProfiles): array {
290 $data = [];
291 if (!isLAMProVersion()) {
292 return $data;
293 }
294 include_once __DIR__ . '/database.inc';
295 foreach ($serverProfiles as $serverProfileName => $serverProfile) {
296 try {
297 $cronDatabase = new CronDatabase($serverProfile);
298 if (empty($cronDatabase->getJobs())) {
299 continue;
300 }
301 $cronDatabase->connect();
302 foreach ($cronDatabase->getJobRuns() as $jobRun) {
303 $data[$serverProfileName]['jobRuns'][] = [
304 'runId' => $jobRun->getRunId(),
305 'name' => $jobRun->getName(),
306 'jobId' => $jobRun->getJobId(),
307 'time' => $jobRun->getTime()->format('Y-m-d H:i:s'),
308 'isOk' => $jobRun->isOk(),
309 'message' => $jobRun->getMessages()
310 ];
311 }
312 $jobs = $cronDatabase->getJobs();
313 foreach ($jobs as $jobId => $job) {
314 $exportData = $job->export($cronDatabase->getPdo(), $jobId);
315 if (!empty($exportData)) {
316 $data[$serverProfileName]['jobData'][$jobId] = $exportData;
317 }
318 }
319 }
320 catch (LAMException $e) {
321 logNewMessage(LOG_ERR, $e->getTitle());
322 }
323 }
324 return $data;
325 }
326
327 /**
328 * Returns the content for request access requests.
329 *
330 * @return array<string, array<string, string>[]> data
331 * @throws LAMException error reading data
332 */
333 public function _getRequestAccessData(): array {
334 $data = [];
335 if (!isLAMProVersion()) {
336 return $data;
337 }
338 $database = \requestAccess::getDatabase();
339 return $database->exportData();
340 }
341
342 }
343
344 /**
345 * Importer for LAM's configuration data.
346 */
347 class ConfigDataImporter {
348
349 /**
350 * Returns a list of possible import objects.
351 *
352 * @param string $json JSON data
353 * @return ImporterStep[] steps
354 * @throws LAMException if invalid format
355 */
356 public function getPossibleImportSteps(string $json): array {
357 $data = json_decode($json, true);
358 if ($data === null) {
359 throw new LAMException(_('Unable to read import file.'));
360 }
361 $steps = [];
362 foreach ($data as $key => $value) {
363 switch ($key) {
364 case 'mainConfig':
365 $steps[] = new ImporterStep(_('General settings'), 'mainConfig', $value);
366 break;
367 case 'certificates':
368 $steps[] = new ImporterStep(_('SSL certificates'), 'certificates', [$value]);
369 break;
370 case 'serverProfiles':
371 $mainStep = new ImporterStep(_('Server profiles'), 'serverProfiles', $value);
372 foreach ($value as $profileName => $profileData) {
373 $mainStep->addSubStep(new ImporterStep($profileName, 'serverProfile_' . $profileName, $profileData));
374 }
375 $steps[] = $mainStep;
376 break;
377 case 'accountProfiles':
378 $mainStep = new ImporterStep(_('Account profiles'), 'accountProfiles', $value);
379 foreach ($value as $profileName => $profileData) {
380 $mainStep->addSubStep(new ImporterStep($profileName, 'accountProfile_' . $profileName, $profileData));
381 }
382 $steps[] = $mainStep;
383 break;
384 case 'accountProfileTemplates':
385 $steps[] = new ImporterStep(_('Account profiles') . ' - ' . _('Global templates'), 'accountProfileTemplates', $value);
386 break;
387 case 'pdfProfiles':
388 $mainStep = new ImporterStep(_('PDF structures'), 'pdfProfiles', $value);
389 foreach ($value as $profileName => $profileData) {
390 $mainStep->addSubStep(new ImporterStep($profileName, 'pdfProfile_' . $profileName, $profileData));
391 }
392 $steps[] = $mainStep;
393 break;
394 case 'pdfProfileTemplates':
395 $steps[] = new ImporterStep(_('PDF structures') . ' - ' . _('Global templates'), 'pdfProfileTemplates', $value);
396 break;
397 case 'selfServiceProfiles':
398 $mainStep = new ImporterStep(_('Self-service profiles'), 'selfServiceProfiles', $value);
399 foreach ($value as $scope => $profiles) {
400 foreach ($profiles as $profileName => $profileData) {
401 $mainStep->addSubStep(new ImporterStep($profileName, 'selfServiceProfile_' . $scope . '__' . $profileName, $profileData));
402 }
403 }
404 $steps[] = $mainStep;
405 break;
406 case 'whitePagesProfiles':
407 $mainStep = new ImporterStep(_('White pages profiles'), 'whitePagesProfiles', $value);
408 foreach ($value as $profileName => $profileData) {
409 $mainStep->addSubStep(new ImporterStep($profileName, 'whitePagesProfile__' . $profileName, $profileData));
410 }
411 $steps[] = $mainStep;
412 break;
413 case 'webauthn':
414 if (extension_loaded('PDO')
415 && in_array('sqlite', PDO::getAvailableDrivers())) {
416 $steps[] = new ImporterStep(_('WebAuthn devices'), 'webauthn', $value);
417 }
418 break;
419 case 'cronJobs':
420 if (isLAMProVersion()) {
421 $mainStep = new ImporterStep(_('Cron jobs'), 'cronJobs', $value);
422 foreach ($value as $profileName => $profileData) {
423 $mainStep->addSubStep(new ImporterStep($profileName, 'cronJob_' . $profileName, $profileData));
424 }
425 $steps[] = $mainStep;
426 }
427 break;
428 case 'requestAccess':
429 if (isLAMProVersion()) {
430 $mainStep = new ImporterStep(_('Request access'), 'requestAccess', $value);
431 if (isset($value['openRequests'])) {
432 $mainStep->addSubStep(new ImporterStep(_('Open requests'), 'requestAccess_openRequests', $value['openRequests']));
433 }
434 if (isset($value['historicRequests'])) {
435 $mainStep->addSubStep(new ImporterStep(_('Request history'), 'requestAccess_historicRequests', $value['historicRequests']));
436 }
437 if (isset($value['expirations'])) {
438 $mainStep->addSubStep(new ImporterStep(_('Revocation information'), 'requestAccess_expirations', $value['expirations']));
439 }
440 $steps[] = $mainStep;
441 }
442 break;
443 default:
444 logNewMessage(LOG_WARNING, 'Unknown import type: ' . $key);
445 }
446 }
447 if (empty($steps)) {
448 throw new LAMException(_('Unable to read import file.'));
449 }
450 return $steps;
451 }
452
453 /**
454 * Runs the actual import.
455 *
456 * @param ImporterStep[] $steps import steps
457 * @throws LAMException if an error occurred
458 */
459 public function runImport(array $steps): void {
460 foreach ($steps as $step) {
461 if (!$step->isActive()) {
462 continue;
463 }
464 $key = $step->getKey();
465 match ($key) {
466 'mainConfig' => $this->importMainConfig($step->getValue()),
467 'certificates' => $this->importCertificates($step->getValue()[0]),
468 'serverProfiles' => $this->importServerProfiles($step),
469 'accountProfiles' => $this->importAccountProfiles($step),
470 'accountProfileTemplates' => $this->importAccountProfileTemplates($step),
471 'pdfProfiles' => $this->importPdfProfiles($step),
472 'pdfProfileTemplates' => $this->importPdfProfileTemplates($step),
473 'selfServiceProfiles' => $this->importSelfServiceProfiles($step),
474 'whitePagesProfiles' => $this->importWhitePagesProfiles($step),
475 'webauthn' => $this->importWebauthn($step),
476 'cronJobs' => $this->importCronJobs($step),
477 'requestAccess' => $this->importRequestAccess($step),
478 default => logNewMessage(LOG_WARNING, 'Unknown import type: ' . $key),
479 };
480 }
481 }
482
483 /**
484 * Imports the main configuration.
485 *
486 * @param array<string, string|string[]|int|bool|null|object> $data main config data
487 * @throws LAMException error during import
488 */
489 private function importMainConfig(array $data): void {
490 $cfgMain = new LAMCfgMain();
491 $cfgMain->importData($data);
492 $cfgMain->save();
493 }
494
495 /**
496 * Imports the SSL certificates.
497 *
498 * @param string|null $data file content
499 * @throws LAMException error during import
500 */
501 private function importCertificates(?string $data): void {
502 $cfgMain = new LAMCfgMain();
503 $cfgMain->importCertificates($data);
504 }
505
506 /**
507 * Imports the server profiles.
508 *
509 * @param ImporterStep $step step
510 * @throws LAMException error during import
511 */
512 private function importServerProfiles(ImporterStep $step): void {
513 $failedProfiles = [];
514 $serverProfilePersistenceManager = new ServerProfilePersistenceManager();
515 foreach ($step->getSubSteps() as $profileStep) {
516 if (!$profileStep->isActive()) {
517 continue;
518 }
519 $data = $profileStep->getValue();
520 $profileName = str_replace('serverProfile_', '', $profileStep->getKey());
521 try {
522 $serverProfile = new LAMConfig();
523 $serverProfile->setName($profileName);
524 $serverProfile->importData($data);
525 $serverProfilePersistenceManager->saveProfile($serverProfile, $profileName);
526 }
527 catch (LAMException $e) {
528 logNewMessage(LOG_ERR, $e->getTitle());
529 $failedProfiles[] = $profileName;
530 }
531 }
532 if (!empty($failedProfiles)) {
533 throw new LAMException(_('Unable to save server profile.'), implode(', ', $failedProfiles));
534 }
535 }
536
537 /**
538 * Imports the account profiles.
539 *
540 * @param ImporterStep $step step
541 * @throws LAMException error during import
542 */
543 private function importAccountProfiles(ImporterStep $step): void {
544 $failedProfiles = [];
545 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
546 foreach ($step->getSubSteps() as $profileStep) {
547 if (!$profileStep->isActive()) {
548 continue;
549 }
550 $data = $profileStep->getValue();
551 $serverProfileName = str_replace('accountProfile_', '', $profileStep->getKey());
552 foreach ($data as $typeId => $accountProfiles) {
553 foreach ($accountProfiles as $accountProfileName => $accountProfileData) {
554 try {
555 $accountProfilePersistenceManager->writeAccountProfile($typeId, $accountProfileName, $serverProfileName, $accountProfileData);
556 }
557 catch (LAMException) {
558 $failedProfiles[] = $serverProfileName . ':' . $typeId . ':' . $accountProfileName;
559 }
560 }
561 }
562 }
563 if (!empty($failedProfiles)) {
564 throw new LAMException(_('Unable to save account profile.'), implode(', ', $failedProfiles));
565 }
566 }
567
568 /**
569 * Imports the account profile templates.
570 *
571 * @param ImporterStep $step step
572 * @throws LAMException error during import
573 */
574 private function importAccountProfileTemplates(ImporterStep $step): void {
575 $data = $step->getValue();
576 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
577 foreach ($data as $scope => $accountProfileTemplates) {
578 foreach ($accountProfileTemplates as $accountProfileTemplateName => $accountProfileData) {
579 $accountProfilePersistenceManager->writeAccountProfileTemplate($scope, $accountProfileTemplateName, $accountProfileData);
580 }
581 }
582 }
583
584 /**
585 * Imports the PDF profiles.
586 *
587 * @param ImporterStep $step step
588 * @throws LAMException error during import
589 */
590 private function importPdfProfiles(ImporterStep $step): void {
591 $failedProfiles = [];
592 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
593 foreach ($step->getSubSteps() as $profileStep) {
594 if (!$profileStep->isActive()) {
595 continue;
596 }
597 $data = $profileStep->getValue();
598 $serverProfileName = str_replace('pdfProfile_', '', $profileStep->getKey());
599 if (isset($data['structures'])) {
600 foreach ($data['structures'] as $typeId => $pdfProfiles) {
601 foreach ($pdfProfiles as $pdfProfileName => $pdfProfileData) {
602 $structure = new PDFStructure();
603 $structure->import($pdfProfileData);
604 try {
605 $pdfStructurePersistenceManager->savePdfStructure($serverProfileName, $typeId, $pdfProfileName, $structure);
606 }
607 catch (LAMException $e) {
608 logNewMessage(LOG_ERR, $e->getTitle() . ' ' . $e->getMessage());
609 $failedProfiles[] = $serverProfileName . ':' . $typeId . ':' . $pdfProfileName;
610 }
611 }
612 }
613 }
614 if (isset($data['logos'])) {
615 foreach ($data['logos'] as $logoFileName => $logoData) {
616 $logoBinary = base64_decode($logoData);
617 $pdfStructurePersistenceManager->savePdfLogo($serverProfileName, trim($logoFileName), $logoBinary);
618 }
619 }
620 }
621 if (!empty($failedProfiles)) {
622 throw new LAMException(_('Could not save PDF structure, access denied.'), implode(', ', $failedProfiles));
623 }
624 }
625
626 /**
627 * Imports the PDF profile templates.
628 *
629 * @param ImporterStep $step step
630 * @throws LAMException error during import
631 */
632 private function importPdfProfileTemplates(ImporterStep $step): void {
633 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
634 $failedNames = [];
635 $data = $step->getValue();
636 if (isset($data['structures'])) {
637 foreach ($data['structures'] as $scope => $pdfProfiles) {
638 foreach ($pdfProfiles as $pdfProfileName => $pdfProfileData) {
639 $structure = new PDFStructure();
640 $structure->import($pdfProfileData);
641 try {
642 $pdfStructurePersistenceManager->savePdfStructureTemplate($scope, $pdfProfileName, $structure);
643 }
644 catch (LAMException $e) {
645 $failedNames[] = $scope . ':' . $pdfProfileName;
646 logNewMessage(LOG_ERR, $e->getTitle() . ' ' . $e->getMessage());
647 }
648 }
649 }
650 }
651 $failedLogos = [];
652 if (isset($data['logos'])) {
653 foreach ($data['logos'] as $logoFileName => $logoData) {
654 $logoBinary = base64_decode($logoData);
655 try {
656 $pdfStructurePersistenceManager->savePdfTemplateLogo($logoFileName, $logoBinary);
657 }
658 catch (LAMException $e) {
659 logNewMessage(LOG_ERR, $e->getTitle());
660 $failedLogos[] = $logoFileName;
661 }
662 }
663 }
664 if (!empty($failedNames)) {
665 throw new LAMException(_('Could not save PDF structure, access denied.'), implode(', ', $failedNames));
666 }
667 if (!empty($failedLogos)) {
668 throw new LAMException(_('Unable to upload logo file.'), implode(', ', $failedLogos));
669 }
670 }
671
672 /**
673 * Imports the self-service profiles.
674 *
675 * @param ImporterStep $step importer step
676 * @throws LAMException error saving profiles
677 */
678 private function importSelfServiceProfiles(ImporterStep $step): void {
679 $failedProfiles = [];
680 $selfServicePersistence = new SelfServicePersistence();
681 foreach ($step->getSubSteps() as $profileStep) {
682 if (!$profileStep->isActive()) {
683 continue;
684 }
685 $data = $profileStep->getValue();
686 $profileKey = str_replace('selfServiceProfile_', '', $profileStep->getKey());
687 $profileKeyParts = explode('__', $profileKey);
688 $profileScope = $profileKeyParts[0];
689 $profileName = substr($profileKey, strlen($profileScope) + 2);
690 try {
691 $profile = selfServiceProfile::import($data);
692 $selfServicePersistence->save($profileName, $profileScope, $profile);
693 }
694 catch (LAMException $e) {
695 logNewMessage(LOG_ERR, $e->getTitle());
696 $failedProfiles[] = $profileName . '.' . $profileScope;
697 }
698 }
699 if (!empty($failedProfiles)) {
700 throw new LAMException(_('Unable to save self-service profile.'), implode(', ', $failedProfiles));
701 }
702 }
703
704 /**
705 * Imports the white pages profiles.
706 *
707 * @param ImporterStep $step importer step
708 * @throws LAMException error saving profiles
709 */
710 private function importWhitePagesProfiles(ImporterStep $step): void {
711 $failedProfiles = [];
712 $whitePagesPersistence = new WhitePagesPersistence();
713 foreach ($step->getSubSteps() as $profileStep) {
714 if (!$profileStep->isActive()) {
715 continue;
716 }
717 $data = $profileStep->getValue();
718 $profileName = str_replace('whitePagesProfile__', '', $profileStep->getKey());
719 try {
720 $profile = WhitePagesProfile::import($data);
721 $whitePagesPersistence->save($profileName, $profile);
722 }
723 catch (LAMException $e) {
724 logNewMessage(LOG_ERR, $e->getTitle());
725 $failedProfiles[] = $profileName;
726 }
727 }
728 if (!empty($failedProfiles)) {
729 throw new LAMException(_('Unable to save white pages profile.'), implode(', ', $failedProfiles));
730 }
731 }
732
733 /**
734 * Imports the webauthn data.
735 *
736 * @param ImporterStep $step importer step
737 * @throws LAMException error saving profiles
738 */
739 private function importWebauthn(ImporterStep $step): void {
740 $data = $step->getValue();
741 include_once __DIR__ . '/webauthn.inc';
742 $webauthnManager = new WebauthnManager();
743 $webauthnDatabase = $webauthnManager->getDatabase();
744 $webauthnDatabase->import($data);
745 }
746
747 /**
748 * Imports the cron jobs.
749 *
750 * @param ImporterStep $step step
751 * @throws LAMException error during import
752 */
753 private function importCronJobs(ImporterStep $step): void {
754 if (!isLAMProVersion()) {
755 return;
756 }
757 include_once __DIR__ . '/database.inc';
758 $serverProfilePersistenceManager = new ServerProfilePersistenceManager();
759 foreach ($step->getSubSteps() as $profileStep) {
760 if (!$profileStep->isActive()) {
761 continue;
762 }
763 $data = $profileStep->getValue();
764 $serverProfileName = str_replace('cronJob_', '', $profileStep->getKey());
765 $serverProfile = $serverProfilePersistenceManager->loadProfile($serverProfileName);
766 $cronDatabase = new CronDatabase($serverProfile);
767 $cronDatabase->connect();
768 if (isset($data['jobRuns'])) {
769 logNewMessage(LOG_DEBUG, 'Import ' . count($data['jobRuns']) . ' cron job runs for ' . $serverProfileName);
770 $cronDatabase->clearJobRuns();
771 foreach ($data['jobRuns'] as $jobRun) {
772 $cronDatabase->importJobRun($jobRun['runId'], $jobRun['name'], $jobRun['jobId'], $jobRun['time'], $jobRun['isOk'], $jobRun['message']);
773 }
774 }
775 if (isset($data['jobData'])) {
776 $jobs = $cronDatabase->getJobs();
777 foreach ($data['jobData'] as $jobId => $jobData) {
778 if (!isset($jobs[$jobId])) {
779 continue;
780 }
781 $job = $jobs[$jobId];
782 logNewMessage(LOG_DEBUG, 'Import ' . count($jobData) . ' cron data entries for ' . $job->getName() . ' - ' . $jobId);
783 $job->import($cronDatabase->getPdo(), $jobData, $jobId);
784 }
785 }
786 }
787 }
788
789 /**
790 * Imports request access data.
791 *
792 * @param ImporterStep $step step
793 * @throws LAMException error accessing database
794 */
795 private function importRequestAccess(ImporterStep $step): void {
796 if (!isLAMProVersion()) {
797 return;
798 }
799 $database = \requestAccess::getDatabase();
800 foreach ($step->getSubSteps() as $subStep) {
801 if (!$subStep->isActive()) {
802 continue;
803 }
804 $data = $subStep->getValue();
805 $stepName = str_replace('requestAccess_', '', $subStep->getKey());
806 switch ($stepName) {
807 case 'openRequests':
808 $database->importOpenRequests($data);
809 break;
810 case 'historicRequests':
811 $database->importRequestHistory($data);
812 break;
813 case 'expirations':
814 $database->importExpirations($data);
815 break;
816 }
817 }
818 }
819
820 }
821
822 /**
823 * Step of the import process.
824 */
825 class ImporterStep {
826
827 private string $label;
828 private string $key;
829 /** @var mixed[] $value value */
830 private array $value;
831 private bool $active = false;
832 /** @var ImporterStep[] $subSteps substeps */
833 private array $subSteps = [];
834
835 /**
836 * Constructor.
837 *
838 * @param string $label label
839 * @param string $key key
840 * @param mixed[] $value value
841 */
842 public function __construct(string $label, string $key, array $value) {
843 $this->label = $label;
844 $this->key = $key;
845 $this->value = $value;
846 }
847
848 /**
849 * Returns the label.
850 *
851 * @return string label
852 */
853 public function getLabel(): string {
854 return $this->label;
855 }
856
857 /**
858 * Returns the key.
859 *
860 * @return string key
861 */
862 public function getKey(): string {
863 return $this->key;
864 }
865
866 /**
867 * Returns if this step should be executed.
868 *
869 * @return bool active
870 */
871 public function isActive(): bool {
872 return $this->active;
873 }
874
875 /**
876 * Sets if this step should be executed.
877 *
878 * @param bool $active active
879 */
880 public function setActive(bool $active): void {
881 $this->active = $active;
882 }
883
884 /**
885 * Returns the value.
886 *
887 * @return mixed[] value
888 */
889 public function getValue(): array {
890 return $this->value;
891 }
892
893 /**
894 * Adds a sub-step.
895 *
896 * @param ImporterStep $subStep sub-step
897 */
898 public function addSubStep(ImporterStep $subStep): void {
899 $this->subSteps[] = $subStep;
900 }
901
902 /**
903 * Returns the sub-steps.
904 *
905 * @return ImporterStep[] sub-steps
906 */
907 public function getSubSteps(): array {
908 return $this->subSteps;
909 }
910
911 }
912
913 /**
914 * Manages the configuration persistence.
915 *
916 * @package LAM\PERSISTENCE
917 */
918 class ConfigurationDatabase {
919
920 /** table for schema versions */
921 public const TABLE_SCHEMA_VERSIONS = 'schema_versions';
922 /** row name for system schema version */
923 private const ROW_VERSION_SYSTEM = 'system';
924 /** table for main configuration */
925 public const TABLE_MAIN_CONFIG = 'main_configuration';
926 /** row name for main config schema version */
927 private const ROW_VERSION_MAIN_CONFIG = 'main_configuration';
928
929 private LAMCfgMain $cfgMain;
930
931 /**
932 * @var PDO|null PDO
933 */
934 private ?PDO $pdo = null;
935
936 /**
937 * Constructor
938 *
939 * @param LAMCfgMain $cfgMain main configuration
940 */
941 public function __construct(LAMCfgMain $cfgMain) {
942 $this->cfgMain = $cfgMain;
943 }
944
945 /**
946 * Returns if a remote database is to be used.
947 *
948 * @return bool use remote database
949 */
950 public function useRemoteDb(): bool {
951 return (!empty($this->cfgMain->configDatabaseType) && ($this->cfgMain->configDatabaseType === LAMCfgMain::DATABASE_MYSQL));
952 }
953
954 /**
955 * Checks if the database connection is ok.
956 *
957 * @throws PDOException error opening connection to database
958 */
959 public function checkConnection(): void {
960 if (!$this->useRemoteDb()) {
961 return;
962 }
963 $pdo = $this->getPdo();
964 $this->updateSchema($pdo);
965 }
966
967 /**
968 * Returns the PDO to read and write data.
969 *
970 * @return PDO PDO
971 * @throws PDOException error opening connection to database
972 */
973 public function getPdo(): PDO {
974 if ($this->pdo !== null) {
975 return $this->pdo;
976 }
977 $url = $this->getPdoUrl();
978 $pdoAttr = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
979 if (!empty($this->cfgMain->configDatabaseSSLCA)) {
980 if (version_compare(phpversion(), '8.5.0') < 0) {
981 $pdoAttr[PDO::MYSQL_ATTR_SSL_CA] = $this->cfgMain->configDatabaseSSLCA;
982 }
983 else {
984 $pdoAttr[Pdo\Mysql::ATTR_SSL_CA] = $this->cfgMain->configDatabaseSSLCA;
985 }
986 }
987 $this->pdo = new PDO($url, $this->cfgMain->configDatabaseUser, $this->cfgMain->configDatabasePassword, $pdoAttr);
988 return $this->pdo;
989 }
990
991 /**
992 * Builds the PDO URL.
993 *
994 * @return string PDO URL
995 */
996 private function getPdoUrl(): string {
997 $portConf = empty($this->cfgMain->configDatabasePort) ? '' : ';port=' . $this->cfgMain->configDatabasePort;
998 return 'mysql:host=' . $this->cfgMain->configDatabaseServer . $portConf . ';dbname=' . $this->cfgMain->configDatabaseName;
999 }
1000
1001 /**
1002 * Updates the schema to latest version.
1003 *
1004 * @param PDO $pdo PDO
1005 */
1006 private function updateSchema(PDO $pdo): void {
1007 // initial system schema
1008 if (!dbTableExists($pdo, self::TABLE_SCHEMA_VERSIONS)) {
1009 $this->createInitialSchema($pdo);
1010 }
1011
1012 }
1013
1014 /**
1015 * Creates the initial schema.
1016 *
1017 * @param PDO $pdo PDO
1018 */
1019 private function createInitialSchema(PDO $pdo): void {
1020 logNewMessage(LOG_NOTICE, 'Create initial config database...');
1021 // schema versions
1022 $sql = 'create table ' . self::TABLE_SCHEMA_VERSIONS . '('
1023 . 'name VARCHAR(250) PRIMARY KEY,'
1024 . 'version INT(3) NOT NULL'
1025 . ');';
1026 $pdo->exec($sql);
1027 $sql = 'insert into ' . self::TABLE_SCHEMA_VERSIONS . ' (name, version) VALUES ("' . self::ROW_VERSION_SYSTEM . '", 1);';
1028 $pdo->exec($sql);
1029 // main configuration
1030 $sql = 'create table ' . self::TABLE_MAIN_CONFIG . '('
1031 . 'name VARCHAR(250) PRIMARY KEY,'
1032 . 'value LONGTEXT NOT NULL'
1033 . ');';
1034 $pdo->exec($sql);
1035 $sql = 'insert into ' . self::TABLE_SCHEMA_VERSIONS . ' (name, version) VALUES ("' . self::ROW_VERSION_MAIN_CONFIG . '", 1);';
1036 $pdo->exec($sql);
1037 logNewMessage(LOG_NOTICE, 'Created initial config database.');
1038 }
1039
1040 }
1041
1042 /**
1043 * Returns if the given table name exists
1044 *
1045 * @param PDO $pdo PDO
1046 * @param string $tableName table name
1047 * @return bool true if existing
1048 */
1049 function dbTableExists(PDO $pdo, string $tableName): bool {
1050 try {
1051 $result = $pdo->query("SELECT 1 FROM $tableName LIMIT 1");
1052 return ($result !== false);
1053 }
1054 catch (PDOException) {
1055 return false;
1056 }
1057 }