Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.84% covered (success)
87.84%
224 / 255
65.00% covered (warning)
65.00%
13 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
ConfigurationTabController
87.84% covered (success)
87.84%
224 / 255
65.00% covered (warning)
65.00%
13 / 20
77.55
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 list
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
2.00
 uploadTheme
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
6.01
 save
82.86% covered (success)
82.86%
58 / 70
0.00% covered (danger)
0.00%
0 / 1
30.67
 logSecurityConfigChanges
93.15% covered (success)
93.15%
68 / 73
0.00% covered (danger)
0.00%
0 / 1
11.04
 translations
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
2.00
 templates
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 faqsSortingKey
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 faqsSortingOrder
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 faqsSortingPopular
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 permLevel
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 releaseEnvironment
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 searchRelevance
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 seoMetaTags
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 translationProvider
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 mailProvider
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 cacheAdapter
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 layoutMode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 convertToString
33.33% covered (danger)
33.33%
3 / 9
0.00% covered (danger)
0.00%
0 / 1
12.41
 hasValidThemeCsrfToken
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * The Admin Configuration Tab Controller
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public License,
7 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
8 * obtain one at https://mozilla.org/MPL/2.0/.
9 *
10 * @package   phpMyFAQ
11 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
12 * @copyright 2023-2026 phpMyFAQ Team
13 * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
14 * @link      https://www.phpmyfaq.de
15 * @since     2023-10-30
16 */
17
18declare(strict_types=1);
19
20namespace phpMyFAQ\Controller\Administration\Api;
21
22use phpMyFAQ\Administration\AdminMenuBuilder;
23use phpMyFAQ\Core\Exception;
24use phpMyFAQ\Enums\AdminLogType;
25use phpMyFAQ\Enums\PermissionType;
26use phpMyFAQ\Filter;
27use phpMyFAQ\Helper\LanguageHelper;
28use phpMyFAQ\Helper\PermissionHelper;
29use phpMyFAQ\Language;
30use phpMyFAQ\Session\Token;
31use phpMyFAQ\Strings;
32use phpMyFAQ\System;
33use phpMyFAQ\Template\ThemeManager;
34use phpMyFAQ\Translation;
35use phpMyFAQ\Twig\TemplateException;
36use Symfony\Component\HttpFoundation\Exception\BadRequestException;
37use Symfony\Component\HttpFoundation\File\UploadedFile;
38use Symfony\Component\HttpFoundation\JsonResponse;
39use Symfony\Component\HttpFoundation\Request;
40use Symfony\Component\HttpFoundation\Response;
41use Symfony\Component\Routing\Attribute\Route;
42use Twig\Error\LoaderError;
43
44final class ConfigurationTabController extends AbstractAdministrationApiController
45{
46    public function __construct(
47        private readonly Language $language,
48        private readonly System $faqSystem,
49        private readonly ThemeManager $themeManager,
50    ) {
51        parent::__construct();
52    }
53
54    /**
55     * @throws TemplateException
56     * @throws Exception
57     * @throws LoaderError
58     * @throws \Exception
59     */
60    #[Route(path: 'configuration/list/{mode}', name: 'admin.api.configuration.list', methods: ['GET'])]
61    public function list(Request $request): Response
62    {
63        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
64
65        $currentLanguage = $this->language->setLanguageByAcceptLanguage();
66
67        try {
68            Translation::create()
69                ->setTranslationsDir(PMF_LANGUAGE_DIR)
70                ->setDefaultLanguage(defaultLanguage: 'en')
71                ->setCurrentLanguage($currentLanguage)
72                ->setMultiByteLanguage();
73        } catch (Exception $exception) {
74            throw new BadRequestException($exception->getMessage());
75        }
76
77        $mode = (string) $request->attributes->get(key: 'mode');
78        $configurationList = Translation::getConfigurationItems($mode);
79
80        return $this->render(file: '@admin/configuration/tab-list.twig', context: [
81            'mode' => $mode,
82            'configurationList' => $configurationList,
83            'configurationData' => $this->configuration->getAll(),
84            'specialCases' => [
85                'ldapSupport' => extension_loaded(extension: 'ldap'),
86                'useSslForLogins' => Request::createFromGlobals()->isSecure(),
87                'useSslOnly' => Request::createFromGlobals()->isSecure(),
88                'ssoSupport' => Request::createFromGlobals()->server->get(key: 'REMOTE_USER'),
89                'buttonTes',
90            ],
91            'themeCsrfToken' => Token::getInstance($this->session)->getTokenString('theme-manager'),
92            'activeTheme' => (string) $this->configuration->get('layout.templateSet'),
93        ]);
94    }
95
96    /**
97     * @throws \Exception
98     */
99    #[Route(path: 'configuration/themes/upload', name: 'admin.api.configuration.themes.upload', methods: ['POST'])]
100    public function uploadTheme(Request $request): JsonResponse
101    {
102        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
103
104        if (!$this->hasValidThemeCsrfToken($request)) {
105            return $this->json(['error' => Translation::get(key: 'msgNoPermission')], Response::HTTP_UNAUTHORIZED);
106        }
107
108        $file = $request->files->get('themeArchive');
109        if (!$file instanceof UploadedFile || !$file->isValid()) {
110            return $this->json(['error' => 'No valid ZIP file uploaded.'], Response::HTTP_BAD_REQUEST);
111        }
112
113        $themeName = trim((string) $request->request->get('themeName', ''));
114        if ($themeName === '') {
115            $themeName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
116        }
117
118        try {
119            $uploadedFiles = $this->themeManager->uploadTheme($themeName, $file->getPathname());
120
121            return $this->json([
122                'success' => sprintf('Theme "%s" uploaded (%d files).', $themeName, $uploadedFiles),
123            ], Response::HTTP_OK);
124        } catch (\RuntimeException $runtimeException) {
125            return $this->json(['error' => $runtimeException->getMessage()], Response::HTTP_BAD_REQUEST);
126        }
127    }
128
129    /**
130     * @throws \Exception
131     */
132    #[Route(path: 'configuration', name: 'admin.api.configuration.save', methods: ['POST'])]
133    public function save(Request $request): JsonResponse
134    {
135        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
136
137        $csrfToken = (string) $request->request->get(key: 'pmf-csrf-token');
138        $configurationData = $request->getPayload()->all(key: 'edit');
139        $availableFieldsJson = (string) $request->request->get(key: 'availableFields');
140
141        $oldConfigurationData = $this->configuration->getAll();
142
143        if (!Token::getInstance($this->session)->verifyToken(page: 'configuration', requestToken: $csrfToken)) {
144            return $this->json(['error' => Translation::get(key: 'msgNoPermission')], Response::HTTP_UNAUTHORIZED);
145        }
146
147        // Parse the list of available fields from the form
148        $availableFields = [];
149        if ($availableFieldsJson !== '') {
150            $decodedFields = json_decode($availableFieldsJson, associative: true);
151            if (is_array($decodedFields)) {
152                $availableFields = array_map(
153                    static fn(mixed $fieldName): string => (string) $fieldName,
154                    $decodedFields,
155                );
156            }
157        }
158
159        // Set the new values
160        $newConfigValues = [];
161        $escapeValues = [
162            'main.contactInformation',
163            'main.customPdfHeader',
164            'main.customPdfFooter',
165            'main.titleFAQ',
166        ];
167
168        // Special checks
169        if (array_key_exists('main.enableMarkdownEditor', $configurationData)) {
170            $configurationData['main.enableWysiwygEditor'] = false; // Disable WYSIWYG editor if Markdown is enabled
171        }
172
173        if (array_key_exists('main.currentVersion', $configurationData)) {
174            unset($configurationData['main.currentVersion']); // don't update the version number
175        }
176
177        if (array_key_exists('records.attachmentsPath', $configurationData)) {
178            $realPath = realpath((string) $configurationData['records.attachmentsPath']);
179
180            if (false === $realPath) {
181                unset($configurationData['records.attachmentsPath']);
182            }
183
184            if (false !== $realPath) {
185                $configurationData['records.attachmentsPath'] = str_replace(
186                    search: (string) Request::createFromGlobals()->server->get(key: 'DOCUMENT_ROOT')
187                    . DIRECTORY_SEPARATOR,
188                    replace: '',
189                    subject: $realPath,
190                );
191            }
192        }
193
194        if (
195            array_key_exists('main.referenceURL', $configurationData)
196            && is_null(Filter::filterVar($configurationData['main.referenceURL'], FILTER_VALIDATE_URL))
197        ) {
198            unset($configurationData['main.referenceURL']);
199        }
200
201        foreach ($configurationData as $key => $value) {
202            $stringValue = is_scalar($value) || $value === null ? (string) $value : '';
203            $newConfigValues[(string) $key] = $stringValue;
204            // Escape some values
205            if (in_array($key, $escapeValues, strict: true)) {
206                $newConfigValues[(string) $key] = Strings::htmlspecialchars($stringValue, ENT_QUOTES);
207            }
208        }
209
210        // Only process fields that were available in the current form
211        // For checkboxes: if the field is available but not in configurationData, set to false
212        // For other fields: keep original value if not in configurationData
213        if ($availableFields !== []) {
214            foreach ($availableFields as $availableField) {
215                if (array_key_exists($availableField, $newConfigValues)) {
216                    continue;
217                }
218
219                if (
220                    array_key_exists($availableField, $oldConfigurationData)
221                    && $oldConfigurationData[$availableField] === 'true'
222                ) {
223                    $newConfigValues[$availableField] = 'false';
224                }
225            }
226        }
227
228        // Keep all values that were not in the available fields (from other tabs);
229        // runtime objects under core.* keys are never part of the form payload.
230        foreach ($oldConfigurationData as $key => $value) {
231            if (array_key_exists($key, $newConfigValues)) {
232                continue;
233            }
234
235            if (is_scalar($value) || $value === null) {
236                $newConfigValues[(string) $key] = $value === null ? null : (string) $value;
237            }
238        }
239
240        // Replace "main.referenceUrl" in FAQs
241        $oldReferenceUrl = (string) ($oldConfigurationData['main.referenceURL'] ?? '');
242        $newReferenceUrl = (string) ($newConfigValues['main.referenceURL'] ?? '');
243        if ($oldReferenceUrl !== $newReferenceUrl) {
244            $this->configuration->replaceMainReferenceUrl($oldReferenceUrl, $newReferenceUrl);
245        }
246
247        $this->configuration->update($newConfigValues);
248
249        // Filter out non-scalar values from old config before comparison
250        $oldConfigComparable = array_filter(
251            $oldConfigurationData,
252            static fn($value) => is_scalar($value) || $value === null,
253        );
254
255        $changedKeys = array_keys(array_diff_assoc($newConfigValues, $oldConfigComparable));
256
257        // General configuration change log
258        $this->adminLog->log($this->currentUser, AdminLogType::CONFIG_CHANGE->value . ':' . implode(',', $changedKeys));
259
260        // Specific security-related configuration change logs
261        $this->logSecurityConfigChanges($changedKeys, $oldConfigurationData, $newConfigValues);
262
263        return $this->json(['success' => Translation::get(key: 'ad_config_saved')], Response::HTTP_OK);
264    }
265
266    /**
267     * Log specific security-related configuration changes
268     */
269    /**
270     * @param list<string> $changedKeys
271     * @param array<array-key, mixed> $oldConfig
272     * @param array<array-key, mixed> $newConfig
273     */
274    private function logSecurityConfigChanges(array $changedKeys, array $oldConfig, array $newConfig): void
275    {
276        // Maintenance mode changes
277        if (in_array('main.maintenanceMode', $changedKeys, strict: true)) {
278            if ($newConfig['main.maintenanceMode'] === 'false' && $oldConfig['main.maintenanceMode'] === 'true') {
279                $this->adminLog->log($this->currentUser, AdminLogType::SYSTEM_MAINTENANCE_MODE_DISABLED->value);
280            }
281
282            if ($newConfig['main.maintenanceMode'] === 'true' && $oldConfig['main.maintenanceMode'] === 'false') {
283                $this->adminLog->log($this->currentUser, AdminLogType::SYSTEM_MAINTENANCE_MODE_ENABLED->value);
284            }
285        }
286
287        // Security configuration keys
288        $securityKeys = [
289            'security.permLevel',
290            'security.enableLoginOnly',
291            'security.enableRegistration',
292            'security.useSslForLogins',
293            'security.useSslOnly',
294            'security.forcePasswordUpdate',
295            'security.enableWebAuthnSupport',
296            'security.bannedIPs',
297            'security.loginWithEmailAddress',
298            'security.enableSignInWithMicrosoft',
299            'security.domainWhiteListForRegistrations',
300        ];
301
302        $securityChanges = array_intersect($changedKeys, $securityKeys);
303        if ($securityChanges !== []) {
304            $details = [];
305            foreach ($securityChanges as $key) {
306                $oldValue = $this->convertToString($oldConfig[$key] ?? null);
307                $newValue = $this->convertToString($newConfig[$key] ?? null);
308                $details[] = (string) $key . ':' . $oldValue . '->' . $newValue;
309            }
310            $this->adminLog->log(
311                $this->currentUser,
312                AdminLogType::CONFIG_SECURITY_CHANGED->value . ':' . implode(';', $details),
313            );
314        }
315
316        // LDAP configuration keys
317        $ldapKeys = [
318            'ldap.ldapSupport',
319            'ldap.ldap_server',
320            'ldap.ldap_port',
321            'ldap.ldap_base',
322            'ldap.ldap_groupSupport',
323        ];
324
325        $ldapChanges = array_intersect($changedKeys, $ldapKeys);
326        if ($ldapChanges !== []) {
327            $this->adminLog->log(
328                $this->currentUser,
329                AdminLogType::CONFIG_LDAP_CHANGED->value . ':' . implode(',', $ldapChanges),
330            );
331        }
332
333        // SSO configuration keys
334        $ssoKeys = [
335            'security.ssoSupport',
336            'security.ssoLogoutRedirect',
337            'keycloak.enable',
338            'keycloak.baseUrl',
339            'keycloak.realm',
340            'keycloak.clientId',
341            'keycloak.clientSecret',
342            'keycloak.redirectUri',
343            'keycloak.scopes',
344            'keycloak.autoProvision',
345            'keycloak.groupAutoAssign',
346            'keycloak.groupSyncOnLogin',
347            'keycloak.groupMapping',
348            'keycloak.logoutRedirectUrl',
349        ];
350
351        $ssoChanges = array_intersect($changedKeys, $ssoKeys);
352        if ($ssoChanges !== []) {
353            $this->adminLog->log(
354                $this->currentUser,
355                AdminLogType::CONFIG_SSO_CHANGED->value . ':' . implode(',', $ssoChanges),
356            );
357        }
358
359        // Encryption configuration keys
360        $encryptionKeys = [
361            'security.encryptionType',
362        ];
363
364        $encryptionChanges = array_intersect($changedKeys, $encryptionKeys);
365        if ($encryptionChanges !== []) {
366            $this->adminLog->log(
367                $this->currentUser,
368                AdminLogType::CONFIG_ENCRYPTION_CHANGED->value . ':' . implode(',', $encryptionChanges),
369            );
370        }
371    }
372
373    /**
374     * @throws \Exception
375     */
376    #[Route(path: 'configuration/translations', name: 'admin.api.configuration.translations', methods: ['GET'])]
377    public function translations(): Response
378    {
379        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
380
381        $response = new Response();
382
383        $languages = LanguageHelper::getAvailableLanguages();
384        if ($languages !== []) {
385            return $response->setContent(LanguageHelper::renderLanguageOptions(
386                str_replace(
387                    ['language_', '.php'],
388                    replace: '',
389                    subject: (string) $this->configuration->get(item: 'main.language'),
390                ),
391                onlyThisLang: false,
392                fileLanguageValue: true,
393            ));
394        }
395
396        return $response->setContent(content: '<option value="language_en.php">English</option>');
397    }
398
399    /**
400     * @throws \Exception
401     */
402    #[Route(path: 'configuration/templates', name: 'admin.api.configuration.templates', methods: ['GET'])]
403    public function templates(): Response
404    {
405        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
406
407        $response = new Response();
408        $templates = $this->faqSystem->getAvailableTemplates();
409        $htmlString = '';
410
411        foreach ($templates as $template => $selected) {
412            $selectedAttribute = $selected === true ? ' selected' : '';
413            $htmlString .= sprintf('<option%s>%s</option>', $selectedAttribute, $template);
414        }
415
416        return $response->setContent($htmlString);
417    }
418
419    #[Route(
420        path: 'configuration/faqs-sorting-key/{current}',
421        name: 'admin.api.configuration.faqs-sorting-key',
422        methods: ['GET'],
423    )]
424    public function faqsSortingKey(Request $request): Response
425    {
426        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
427
428        return new Response(AdminMenuBuilder::sortingKeyOptions((string) $request->attributes->get(key: 'current')));
429    }
430
431    #[Route(
432        path: 'configuration/faqs-sorting-order/{current}',
433        name: 'admin.api.configuration.faqs-sorting-order',
434        methods: ['GET'],
435    )]
436    public function faqsSortingOrder(Request $request): Response
437    {
438        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
439
440        return new Response(AdminMenuBuilder::sortingOrderOptions((string) $request->attributes->get(key: 'current')));
441    }
442
443    #[Route(
444        path: 'configuration/faqs-sorting-popular/{current}',
445        name: 'admin.api.configuration.faqs-sorting-popular',
446        methods: ['GET'],
447    )]
448    public function faqsSortingPopular(Request $request): Response
449    {
450        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
451
452        return new Response(AdminMenuBuilder::sortingPopularFaqsOptions((string) $request->attributes->get(
453            key: 'current',
454        )));
455    }
456
457    #[Route(path: 'configuration/perm-level/{current}', name: 'admin.api.configuration.permLevel', methods: ['GET'])]
458    public function permLevel(Request $request): Response
459    {
460        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
461
462        return new Response(PermissionHelper::permOptions((string) $request->attributes->get(key: 'current')));
463    }
464
465    #[Route(
466        path: 'configuration/release-environment/{current}',
467        name: 'admin.api.configuration.release-environment',
468        methods: ['GET'],
469    )]
470    public function releaseEnvironment(Request $request): Response
471    {
472        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
473
474        return new Response(AdminMenuBuilder::renderReleaseTypeOptions((string) $request->attributes->get(
475            key: 'current',
476        )));
477    }
478
479    #[Route(
480        path: 'configuration/search-relevance/{current}',
481        name: 'admin.api.configuration.search-relevance',
482        methods: ['GET'],
483    )]
484    public function searchRelevance(Request $request): Response
485    {
486        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
487
488        return new Response(AdminMenuBuilder::searchRelevanceOptions((string) $request->attributes->get(
489            key: 'current',
490        )));
491    }
492
493    #[Route(
494        path: 'configuration/seo-metatags/{current}',
495        name: 'admin.api.configuration.seo-metatags',
496        methods: ['GET'],
497    )]
498    public function seoMetaTags(Request $request): Response
499    {
500        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
501
502        return new Response(AdminMenuBuilder::renderMetaRobotsDropdown((string) $request->attributes->get(
503            key: 'current',
504        )));
505    }
506
507    #[Route(
508        path: 'configuration/translation-provider/{current}',
509        name: 'admin.api.configuration.translation-provider',
510        methods: ['GET'],
511    )]
512    public function translationProvider(Request $request): Response
513    {
514        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
515
516        return new Response(AdminMenuBuilder::renderTranslationProviderOptions((string) $request->attributes->get(
517            key: 'current',
518        )));
519    }
520
521    #[Route(
522        path: 'configuration/mail-provider/{current}',
523        name: 'admin.api.configuration.mail-provider',
524        methods: ['GET'],
525    )]
526    public function mailProvider(Request $request): Response
527    {
528        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
529
530        return new Response(AdminMenuBuilder::renderMailProviderOptions((string) $request->attributes->get(
531            key: 'current',
532        )));
533    }
534
535    #[Route(
536        path: 'configuration/cache-adapter/{current}',
537        name: 'admin.api.configuration.cache-adapter',
538        methods: ['GET'],
539    )]
540    public function cacheAdapter(Request $request): Response
541    {
542        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
543
544        return new Response(AdminMenuBuilder::renderCacheAdapterOptions((string) $request->attributes->get(
545            key: 'current',
546        )));
547    }
548
549    #[Route(path: 'configuration/layout-mode/{current}', name: 'admin.api.configuration.layout-mode', methods: ['GET'])]
550    public function layoutMode(Request $request): Response
551    {
552        $this->userHasPermission(PermissionType::CONFIGURATION_EDIT);
553
554        return new Response(AdminMenuBuilder::renderLayoutModeOptions((string) $request->attributes->get(
555            key: 'current',
556        )));
557    }
558
559    /**
560     * Converts a value to string safely, handling objects and null values
561     */
562    private function convertToString(mixed $value): string
563    {
564        if ($value === null) {
565            return 'null';
566        }
567
568        if (is_scalar($value)) {
569            return (string) $value;
570        }
571
572        if (is_object($value)) {
573            return get_class($value);
574        }
575
576        if (is_array($value)) {
577            return 'array';
578        }
579
580        return 'unknown';
581    }
582
583    private function hasValidThemeCsrfToken(Request $request): bool
584    {
585        $csrfToken = (string) $request->request->get('theme-csrf-token', '');
586        return Token::getInstance($this->session)->verifyToken('theme-manager', $csrfToken);
587    }
588}