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