xref: /webtrees/app/Module/FrequentlyAskedQuestionsModule.php (revision e873f434551745f888937263ff89e80db3b0f785)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Webtrees\DB;
23use Fisharebest\Webtrees\Http\RequestHandlers\ControlPanel;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Menu;
26use Fisharebest\Webtrees\Services\HtmlService;
27use Fisharebest\Webtrees\Services\TreeService;
28use Fisharebest\Webtrees\Site;
29use Fisharebest\Webtrees\Tree;
30use Fisharebest\Webtrees\Validator;
31use Illuminate\Database\Query\Builder;
32use Illuminate\Support\Collection;
33use Psr\Http\Message\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35
36use function in_array;
37use function redirect;
38use function route;
39
40/**
41 * Class FrequentlyAskedQuestionsModule
42 */
43class FrequentlyAskedQuestionsModule extends AbstractModule implements ModuleConfigInterface, ModuleMenuInterface
44{
45    use ModuleConfigTrait;
46    use ModuleMenuTrait;
47
48    private HtmlService $html_service;
49
50    private TreeService $tree_service;
51
52    /**
53     * @param HtmlService $html_service
54     * @param TreeService $tree_service
55     */
56    public function __construct(HtmlService $html_service, TreeService $tree_service)
57    {
58        $this->html_service = $html_service;
59        $this->tree_service = $tree_service;
60    }
61
62    /**
63     * How should this module be identified in the control panel, etc.?
64     *
65     * @return string
66     */
67    public function title(): string
68    {
69        /* I18N: Name of a module. Abbreviation for “Frequently Asked Questions” */
70        return I18N::translate('FAQ');
71    }
72
73    public function description(): string
74    {
75        /* I18N: Description of the “FAQ” module */
76        return I18N::translate('A list of frequently asked questions and answers.');
77    }
78
79    /**
80     * The default position for this menu.  It can be changed in the control panel.
81     *
82     * @return int
83     */
84    public function defaultMenuOrder(): int
85    {
86        return 8;
87    }
88
89    /**
90     * A menu, to be added to the main application menu.
91     *
92     * @param Tree $tree
93     *
94     * @return Menu|null
95     */
96    public function getMenu(Tree $tree): Menu|null
97    {
98        if ($this->faqsExist($tree, I18N::languageTag())) {
99            return new Menu($this->title(), route('module', [
100                'module' => $this->name(),
101                'action' => 'Show',
102                'tree'   => $tree->name(),
103            ]), 'menu-faq');
104        }
105
106        return null;
107    }
108
109    /**
110     * @param ServerRequestInterface $request
111     *
112     * @return ResponseInterface
113     */
114    public function getAdminAction(ServerRequestInterface $request): ResponseInterface
115    {
116        $this->layout = 'layouts/administration';
117
118        // This module can't run without a tree
119        $tree = Validator::attributes($request)->treeOptional();
120
121        if (!$tree instanceof Tree) {
122            $trees = $this->tree_service->all();
123
124            $tree = $trees->get(Site::getPreference('DEFAULT_GEDCOM')) ?? $trees->first();
125
126            if ($tree instanceof Tree) {
127                return redirect(route('module', ['module' => $this->name(), 'action' => 'Admin', 'tree' => $tree->name()]));
128            }
129
130            return redirect(route(ControlPanel::class));
131        }
132
133        $faqs = $this->faqsForTree($tree);
134
135        $min_block_order = (int) DB::table('block')
136            ->where('module_name', '=', $this->name())
137            ->where(static function (Builder $query) use ($tree): void {
138                $query
139                    ->whereNull('gedcom_id')
140                    ->orWhere('gedcom_id', '=', $tree->id());
141            })
142            ->min('block_order');
143
144        $max_block_order = (int) DB::table('block')
145            ->where('module_name', '=', $this->name())
146            ->where(static function (Builder $query) use ($tree): void {
147                $query
148                    ->whereNull('gedcom_id')
149                    ->orWhere('gedcom_id', '=', $tree->id());
150            })
151            ->max('block_order');
152
153        $title = I18N::translate('Frequently asked questions') . ' — ' . $tree->title();
154
155        return $this->viewResponse('modules/faq/config', [
156            'action'          => route('module', ['module' => $this->name(), 'action' => 'Admin']),
157            'faqs'            => $faqs,
158            'max_block_order' => $max_block_order,
159            'min_block_order' => $min_block_order,
160            'module'          => $this->name(),
161            'title'           => $title,
162            'tree'            => $tree,
163            'tree_names'      => $this->tree_service->titles(),
164        ]);
165    }
166
167    /**
168     * @param ServerRequestInterface $request
169     *
170     * @return ResponseInterface
171     */
172    public function postAdminAction(ServerRequestInterface $request): ResponseInterface
173    {
174        return redirect(route('module', [
175            'module' => $this->name(),
176            'action' => 'Admin',
177            'tree'   => Validator::parsedBody($request)->string('tree'),
178        ]));
179    }
180
181    /**
182     * @param ServerRequestInterface $request
183     *
184     * @return ResponseInterface
185     */
186    public function postAdminDeleteAction(ServerRequestInterface $request): ResponseInterface
187    {
188        $block_id = Validator::queryParams($request)->integer('block_id');
189
190        DB::table('block_setting')->where('block_id', '=', $block_id)->delete();
191
192        DB::table('block')->where('block_id', '=', $block_id)->delete();
193
194        $url = route('module', [
195            'module' => $this->name(),
196            'action' => 'Admin',
197        ]);
198
199        return redirect($url);
200    }
201
202    /**
203     * @param ServerRequestInterface $request
204     *
205     * @return ResponseInterface
206     */
207    public function postAdminMoveDownAction(ServerRequestInterface $request): ResponseInterface
208    {
209        $block_id = Validator::queryParams($request)->integer('block_id');
210
211        $block_order = DB::table('block')
212            ->where('block_id', '=', $block_id)
213            ->value('block_order');
214
215        $swap_block = DB::table('block')
216            ->where('module_name', '=', $this->name())
217            ->where('block_order', '>', $block_order)
218            ->orderBy('block_order')
219            ->first();
220
221        if ($block_order !== null && $swap_block !== null) {
222            DB::table('block')
223                ->where('block_id', '=', $block_id)
224                ->update([
225                    'block_order' => $swap_block->block_order,
226                ]);
227
228            DB::table('block')
229                ->where('block_id', '=', $swap_block->block_id)
230                ->update([
231                    'block_order' => $block_order,
232                ]);
233        }
234
235        return response();
236    }
237
238    /**
239     * @param ServerRequestInterface $request
240     *
241     * @return ResponseInterface
242     */
243    public function postAdminMoveUpAction(ServerRequestInterface $request): ResponseInterface
244    {
245        $block_id = Validator::queryParams($request)->integer('block_id');
246
247        $block_order = DB::table('block')
248            ->where('block_id', '=', $block_id)
249            ->value('block_order');
250
251        $swap_block = DB::table('block')
252            ->where('module_name', '=', $this->name())
253            ->where('block_order', '<', $block_order)
254            ->orderBy('block_order', 'desc')
255            ->first();
256
257        if ($block_order !== null && $swap_block !== null) {
258            DB::table('block')
259                ->where('block_id', '=', $block_id)
260                ->update([
261                    'block_order' => $swap_block->block_order,
262                ]);
263
264            DB::table('block')
265                ->where('block_id', '=', $swap_block->block_id)
266                ->update([
267                    'block_order' => $block_order,
268                ]);
269        }
270
271        return response();
272    }
273
274    /**
275     * @param ServerRequestInterface $request
276     *
277     * @return ResponseInterface
278     */
279    public function getAdminEditAction(ServerRequestInterface $request): ResponseInterface
280    {
281        $this->layout = 'layouts/administration';
282
283        $block_id = Validator::queryParams($request)->integer('block_id', 0);
284
285        if ($block_id === 0) {
286            // Creating a new faq
287            $header      = '';
288            $body        = '';
289            $gedcom_id   = null;
290            $block_order = 1 + (int) DB::table('block')->where('module_name', '=', $this->name())->max('block_order');
291
292            $languages = [];
293
294            $title = I18N::translate('Add an FAQ');
295        } else {
296            // Editing an existing faq
297            $header      = $this->getBlockSetting($block_id, 'header');
298            $body        = $this->getBlockSetting($block_id, 'faqbody');
299            $gedcom_id   = DB::table('block')->where('block_id', '=', $block_id)->value('gedcom_id');
300            $block_order = DB::table('block')->where('block_id', '=', $block_id)->value('block_order');
301
302            $languages = explode(',', $this->getBlockSetting($block_id, 'languages'));
303
304            $title = I18N::translate('Edit the FAQ');
305        }
306
307        $gedcom_ids = $this->tree_service->all()
308            ->mapWithKeys(static fn (Tree $tree): array => [$tree->id() => $tree->title()])
309            ->all();
310
311        $gedcom_ids = ['' => I18N::translate('All')] + $gedcom_ids;
312
313        return $this->viewResponse('modules/faq/edit', [
314            'block_id'    => $block_id,
315            'block_order' => $block_order,
316            'header'      => $header,
317            'body'        => $body,
318            'languages'   => $languages,
319            'title'       => $title,
320            'gedcom_id'   => $gedcom_id,
321            'gedcom_ids'  => $gedcom_ids,
322        ]);
323    }
324
325    /**
326     * @param ServerRequestInterface $request
327     *
328     * @return ResponseInterface
329     */
330    public function postAdminEditAction(ServerRequestInterface $request): ResponseInterface
331    {
332        $block_id    = Validator::queryParams($request)->integer('block_id', 0);
333        $body        = Validator::parsedBody($request)->string('body');
334        $header      = Validator::parsedBody($request)->string('header');
335        $languages   = Validator::parsedBody($request)->array('languages');
336        $gedcom_id   = Validator::parsedBody($request)->string('gedcom_id');
337        $block_order = Validator::parsedBody($request)->integer('block_order');
338
339        if ($gedcom_id === '') {
340            $gedcom_id = null;
341        }
342
343        $body    = $this->html_service->sanitize($body);
344        $header  = $this->html_service->sanitize($header);
345
346        if ($block_id !== 0) {
347            DB::table('block')
348                ->where('block_id', '=', $block_id)
349                ->update([
350                    'gedcom_id'   => $gedcom_id,
351                    'block_order' => $block_order,
352                ]);
353        } else {
354            DB::table('block')->insert([
355                'gedcom_id'   => $gedcom_id,
356                'module_name' => $this->name(),
357                'block_order' => $block_order,
358            ]);
359
360            $block_id = DB::lastInsertId();
361        }
362
363        $this->setBlockSetting($block_id, 'faqbody', $body);
364        $this->setBlockSetting($block_id, 'header', $header);
365        $this->setBlockSetting($block_id, 'languages', implode(',', $languages));
366
367        $url = route('module', [
368            'module' => $this->name(),
369            'action' => 'Admin',
370        ]);
371
372        return redirect($url);
373    }
374
375    /**
376     * @param ServerRequestInterface $request
377     *
378     * @return ResponseInterface
379     */
380    public function getShowAction(ServerRequestInterface $request): ResponseInterface
381    {
382        $tree = Validator::attributes($request)->tree();
383
384        // Filter foreign languages.
385        $faqs = $this->faqsForTree($tree)
386            ->filter(static fn (object $faq): bool => $faq->languages === '' || in_array(I18N::languageTag(), explode(',', $faq->languages), true));
387
388        return $this->viewResponse('modules/faq/show', [
389            'faqs'  => $faqs,
390            'title' => I18N::translate('Frequently asked questions'),
391            'tree'  => $tree,
392        ]);
393    }
394
395    /**
396     * @param Tree $tree
397     *
398     * @return Collection<int,object>
399     */
400    private function faqsForTree(Tree $tree): Collection
401    {
402        return DB::table('block')
403            ->join('block_setting AS bs1', 'bs1.block_id', '=', 'block.block_id')
404            ->join('block_setting AS bs2', 'bs2.block_id', '=', 'block.block_id')
405            ->join('block_setting AS bs3', 'bs3.block_id', '=', 'block.block_id')
406            ->where('module_name', '=', $this->name())
407            ->where('bs1.setting_name', '=', 'header')
408            ->where('bs2.setting_name', '=', 'faqbody')
409            ->where('bs3.setting_name', '=', 'languages')
410            ->where(static function (Builder $query) use ($tree): void {
411                $query
412                    ->whereNull('gedcom_id')
413                    ->orWhere('gedcom_id', '=', $tree->id());
414            })
415            ->orderBy('block_order')
416            ->select(['block.block_id', 'block_order', 'gedcom_id', 'bs1.setting_value AS header', 'bs2.setting_value AS faqbody', 'bs3.setting_value AS languages'])
417            ->get()
418            ->map(static function (object $row): object {
419                $row->block_id    = (int) $row->block_id;
420                $row->block_order = (int) $row->block_order;
421                $row->gedcom_id   = (int) $row->gedcom_id;
422
423                return $row;
424            });
425    }
426
427    /**
428     * @param Tree   $tree
429     * @param string $language
430     *
431     * @return bool
432     */
433    private function faqsExist(Tree $tree, string $language): bool
434    {
435        return DB::table('block')
436            ->join('block_setting', 'block_setting.block_id', '=', 'block.block_id')
437            ->where('module_name', '=', $this->name())
438            ->where('setting_name', '=', 'languages')
439            ->where(static function (Builder $query) use ($tree): void {
440                $query
441                    ->whereNull('gedcom_id')
442                    ->orWhere('gedcom_id', '=', $tree->id());
443            })
444            ->select(['setting_value AS languages'])
445            ->get()
446            ->filter(static fn (object $faq): bool => $faq->languages === '' || in_array($language, explode(',', $faq->languages), true))
447            ->isNotEmpty();
448    }
449}
450