Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.86% covered (success)
95.86%
162 / 169
66.67% covered (warning)
66.67%
4 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
AbstractFrontController
95.86% covered (success)
95.86%
162 / 169
66.67% covered (warning)
66.67%
4 / 6
33
0.00% covered (danger)
0.00%
0 / 1
 initializeFromContainer
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
4.01
 getHeader
100.00% covered (success)
100.00%
78 / 78
100.00% covered (success)
100.00%
1 / 1
9
 getTopNavigation
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
5
 getUserDropdown
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
5
 getFooterNavigation
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
5
 handleStaticPageRedirect
53.85% covered (warning)
53.85%
7 / 13
0.00% covered (danger)
0.00%
0 / 1
7.46
1<?php
2
3/**
4 * The abstract Front 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 2024-2025 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     2024-06-16
16 */
17
18declare(strict_types=1);
19
20namespace phpMyFAQ\Controller\Frontend;
21
22use LogicException;
23use phpMyFAQ\Controller\AbstractController;
24use phpMyFAQ\Core\Exception;
25use phpMyFAQ\CustomPage;
26use phpMyFAQ\Enums\PermissionType;
27use phpMyFAQ\Environment;
28use phpMyFAQ\Helper\LanguageHelper;
29use phpMyFAQ\Seo;
30use phpMyFAQ\Session\Token;
31use phpMyFAQ\System;
32use phpMyFAQ\Translation;
33use phpMyFAQ\Twig\TwigWrapper;
34use Symfony\Component\HttpFoundation\RedirectResponse;
35use Symfony\Component\HttpFoundation\Request;
36use Symfony\Component\HttpFoundation\Response;
37use Twig\Error\LoaderError;
38
39abstract class AbstractFrontController extends AbstractController
40{
41    protected System $faqSystem;
42
43    protected Seo $seo;
44
45    #[\Override]
46    protected function initializeFromContainer(): void
47    {
48        parent::initializeFromContainer();
49
50        /* @mago-expect lint:no-isset - typed property may be uninitialized */
51        if (!isset($this->container)) {
52            throw new LogicException('Container is not initialized.');
53        }
54
55        $faqSystem = $this->container->get(id: 'phpmyfaq.system');
56        if (!$faqSystem instanceof System) {
57            throw new LogicException('System service not found in container.');
58        }
59
60        $this->faqSystem = $faqSystem;
61
62        $seo = $this->container->get(id: 'phpmyfaq.seo');
63        if (!$seo instanceof Seo) {
64            throw new LogicException('Seo service not found in container.');
65        }
66
67        $this->seo = $seo;
68    }
69
70    /**
71     * @return array<string, mixed>
72     * @throws \Exception
73     */
74    protected function getHeader(Request $request): array
75    {
76        $action = $request->query->get(key: 'action', default: 'index');
77
78        $isUserHasAdminRights = $this->currentUser->perm->hasPermission(
79            $this->currentUser->getUserId(),
80            PermissionType::VIEW_ADMIN_LINK->value,
81        );
82
83        // Get flash messages
84        $successMessages = $this->session->getFlashBag()->get('success');
85        $errorMessages = $this->session->getFlashBag()->get('error');
86
87        return [
88            ...$this->getUserDropdown(),
89            'successMessage' => count($successMessages) > 0 ? $successMessages[0] : null,
90            'errorMessage' => count($errorMessages) > 0 ? $errorMessages[0] : null,
91            'isMaintenanceMode' => $this->configuration->get('main.maintenanceMode'),
92            'isCompletelySecured' => $this->configuration->get('security.enableLoginOnly'),
93            'isDebugEnabled' => Environment::isDebugMode(),
94            'richSnippetsEnabled' => $this->configuration->get('seo.enableRichSnippets'),
95            'tplSetName' => TwigWrapper::getTemplateSetName(),
96            'msgLoginUser' => $this->currentUser->isLoggedIn()
97                ? $this->currentUser->getUserData('display_name')
98                : Translation::get(key: 'msgLoginUser'),
99            'isUserLoggedIn' => $this->currentUser->isLoggedIn(),
100            'isUserHasAdminRights' => $isUserHasAdminRights || $this->currentUser->isSuperAdmin(),
101            'baseHref' => $this->faqSystem->getSystemUri($this->configuration),
102            'customCss' => $this->configuration->getCustomCss(),
103            'defaultLayoutMode' => (string) ($this->configuration->get('layout.defaultLayoutMode') ?? 'auto'),
104            'allowUserLayoutMode' =>
105                $this->configuration->get('layout.allowUserLayoutMode') === true
106                    || $this->configuration->get('layout.allowUserLayoutMode') === 'true',
107            'version' => $this->configuration->getVersion(),
108            'header' => str_replace(search: '"', replace: '', subject: $this->configuration->getTitle()),
109            'metaDescription' => $this->configuration->get('seo.description'),
110            'metaPublisher' => $this->configuration->get('main.metaPublisher'),
111            'metaLanguage' => Translation::get(key: 'metaLanguage'),
112            'metaRobots' => $this->seo->getMetaRobots($action),
113            'phpmyfaqVersion' => $this->configuration->getVersion(),
114            'stylesheet' => Translation::get(key: 'direction') === 'rtl' ? 'style.rtl' : 'style',
115            'currentPageUrl' => $request->getSchemeAndHttpHost() . $request->getRequestUri(),
116            'action' => $action,
117            'dir' => Translation::get(key: 'direction'),
118            'formActionUrl' => './search',
119            'searchBox' => Translation::get(key: 'msgSearch'),
120            'languageBox' => Translation::get(key: 'msgLanguageSubmit'),
121            'switchLanguages' => LanguageHelper::renderSelectLanguage(
122                $this->configuration->getLanguage()->getLanguage(),
123                true,
124            ),
125            'copyright' => System::getPoweredByString(),
126            'isUserRegistrationEnabled' => $this->configuration->get('security.enableRegistration'),
127            'pluginStylesheets' => $this->configuration->getPluginManager()->getAllPluginStylesheets(),
128            'pluginScripts' => $this->configuration->getPluginManager()->getAllPluginScripts(),
129            'msgFullName' => Translation::getString(key: 'ad_user_loggedin') . $this->currentUser->getLogin(),
130            'msgLoginName' => $this->currentUser->getUserData('display_name'),
131            'loginHeader' => Translation::get(key: 'msgLoginUser'),
132            'msgAdvancedSearch' => Translation::get(key: 'msgAdvancedSearch'),
133            'currentYear' => date(format: 'Y', timestamp: time()),
134            'cookieConsentEnabled' => $this->configuration->get('layout.enableCookieConsent'),
135            'faqHome' => $this->configuration->getDefaultUrl(),
136            'topNavigation' => $this->getTopNavigation($request),
137            'isAskQuestionsEnabled' => $this->configuration->get('main.enableAskQuestions'),
138            'isOpenQuestionsEnabled' => $this->configuration->get('main.enableAskQuestions'),
139            'footerNavigation' => $this->getFooterNavigation($request),
140            'isPrivacyLinkEnabled' => $this->configuration->get('layout.enablePrivacyLink'),
141            'msgPrivacyNote' => Translation::get(key: 'msgPrivacyNote'),
142            'isTermsLinkEnabled' => (string) $this->configuration->get('main.termsURL') !== '',
143            'msgTermsOfService' => Translation::get(key: 'msgTermsOfService'),
144            'isImprintLinkEnabled' => (string) $this->configuration->get('main.imprintURL') !== '',
145            'msgImprint' => Translation::get(key: 'msgImprint'),
146            'isCookieConsentEnabled' => $this->configuration->get('layout.enableCookieConsent'),
147            'cookiePreferences' => Translation::get(key: 'cookiePreferences'),
148            'isAccessibilityStatementEnabled' =>
149                (string) $this->configuration->get('main.accessibilityStatementURL') !== '',
150            'msgAccessibilityStatement' => Translation::get(key: 'msgAccessibilityStatement'),
151            'pushEnabled' =>
152                (
153                    $this->configuration->get('push.enableWebPush') === 'true'
154                    || $this->configuration->get('push.enableWebPush') === true
155                )
156                    && (string) $this->configuration->get('push.vapidPublicKey') !== '',
157        ];
158    }
159
160    private function getTopNavigation(Request $request): array
161    {
162        $action = $request->query->get(key: 'action', default: 'index');
163
164        return [
165            [
166                'name' => Translation::get(key: 'msgShowAllCategories'),
167                'link' => './show-categories.html',
168                'active' => 'show' === $action ? 'active' : '',
169            ],
170            [
171                'name' => Translation::get(key: 'msgAddContent'),
172                'link' => './add-faq.html',
173                'active' => 'add' === $action ? 'active' : '',
174            ],
175            [
176                'name' => Translation::get(key: 'msgQuestion'),
177                'link' => './add-question.html',
178                'active' => 'ask' === $action ? 'active' : '',
179            ],
180            [
181                'name' => Translation::get(key: 'msgOpenQuestions'),
182                'link' => './open-questions.html',
183                'active' => 'open-questions' === $action ? 'active' : '',
184            ],
185        ];
186    }
187
188    /**
189     * @throws \Exception
190     */
191    private function getUserDropdown(): array
192    {
193        $templateVars = [];
194        if ($this->currentUser->isLoggedIn() && $this->currentUser->getUserId() > 0) {
195            $csrfLogoutToken = Token::getInstance($this->session)->getTokenString('logout');
196
197            if (
198                $this->currentUser->perm->hasPermission(
199                    $this->currentUser->getUserId(),
200                    PermissionType::VIEW_ADMIN_LINK->value,
201                )
202                || $this->currentUser->isSuperAdmin()
203            ) {
204                $templateVars = [
205                    ...$templateVars,
206                    'msgAdmin' => Translation::get(key: 'adminSection'),
207                ];
208            }
209
210            $templateVars = [
211                ...$templateVars,
212                'msgUserControlDropDown' => Translation::get(key: 'headerUserControlPanel'),
213                'msgBookmarks' => Translation::get(key: 'msgBookmarks'),
214                'msgUserRemoval' => Translation::get(key: 'ad_menu_RequestRemove'),
215                'msgLogoutUser' => Translation::get(key: 'ad_menu_logout'),
216                'csrfLogout' => $csrfLogoutToken,
217            ];
218        }
219
220        return $templateVars;
221    }
222
223    private function getFooterNavigation(Request $request): array
224    {
225        $action = $request->query->get(key: 'action', default: 'index');
226
227        return [
228            [
229                'name' => Translation::get(key: 'faqOverview'),
230                'link' => './overview.html',
231                'active' => 'faq-overview' === $action ? 'active' : '',
232            ],
233            [
234                'name' => Translation::get(key: 'msgSitemap'),
235                'link' => './sitemap/A/' . $this->configuration->getLanguage()->getLanguage() . '.html',
236                'active' => 'sitemap' === $action ? 'active' : '',
237            ],
238            [
239                'name' => Translation::get(key: 'ad_menu_glossary'),
240                'link' => './glossary.html',
241                'active' => 'glossary' === $action ? 'active' : '',
242            ],
243            [
244                'name' => Translation::get(key: 'msgContact'),
245                'link' => './contact.html',
246                'active' => 'contact' === $action ? 'active' : '',
247            ],
248        ];
249    }
250
251    /**
252     * Handles static page redirects (cookie policy, imprint, terms, privacy).
253     * Checks if the URL is a reference to a custom page or external URL.
254     *
255     * @param string $configKey Configuration key for the URL (e.g., 'main.cookiePolicyURL')
256     * @return Response RedirectResponse or 404 error page
257     * @throws Exception|LoaderError|\Exception
258     */
259    protected function handleStaticPageRedirect(string $configKey): Response
260    {
261        $url = $this->configuration->get($configKey);
262
263        // Check if this is a reference to a custom page (format: "page:slug")
264        if (str_starts_with((string) $url, 'page:')) {
265            $slug = substr(string: (string) $url, offset: 5);
266            $customPage = new CustomPage($this->configuration);
267            $page = $customPage->getBySlug($slug);
268
269            if ($page && $page->isActive()) {
270                // Redirect to the custom page URL
271                $pageUrl = $this->configuration->getDefaultUrl() . 'page/' . $page->getSlug() . '.html';
272                return new RedirectResponse($pageUrl);
273            }
274        }
275
276        // Default behavior: redirect to external URL
277        if ((string) $url !== '') {
278            return new RedirectResponse((string) $url);
279        }
280
281        // If no URL configured and no fallback, return 404
282        $response = new Response();
283        $response->setStatusCode(Response::HTTP_NOT_FOUND);
284        return $this->render('404.twig', [], $response);
285    }
286}