Passed
Push — master ( a91af2...e218f3 )
by Greg
06:06
created

FrequentlyAskedQuestionsModule::postAdminAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
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
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Module;
21
22
use Fisharebest\Webtrees\Http\RequestHandlers\ControlPanel;
23
use Fisharebest\Webtrees\I18N;
24
use Fisharebest\Webtrees\Menu;
25
use Fisharebest\Webtrees\Services\HtmlService;
26
use Fisharebest\Webtrees\Services\TreeService;
27
use Fisharebest\Webtrees\Tree;
28
use Illuminate\Database\Capsule\Manager as DB;
29
use Illuminate\Database\Query\Builder;
30
use Illuminate\Support\Collection;
31
use InvalidArgumentException;
32
use Psr\Http\Message\ResponseInterface;
33
use Psr\Http\Message\ServerRequestInterface;
34
use stdClass;
35
36
use function assert;
37
use function redirect;
38
use function route;
39
40
/**
41
 * Class FrequentlyAskedQuestionsModule
42
 */
43
class 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'      => Tree::getNameList(),
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
        $tree     = $request->getAttribute('tree');
290
        $block_id = (int) ($request->getQueryParams()['block_id'] ?? 0);
291
292
        if ($block_id === 0) {
293
            // Creating a new faq
294
            $header  = '';
295
            $faqbody = '';
296
297
            $block_order = 1 + (int) DB::table('block')
298
                    ->where('module_name', '=', $this->name())
299
                    ->max('block_order');
300
301
            $languages = [];
302
303
            $title = I18N::translate('Add an FAQ');
304
        } else {
305
            // Editing an existing faq
306
            $header  = $this->getBlockSetting($block_id, 'header');
307
            $faqbody = $this->getBlockSetting($block_id, 'faqbody');
308
309
            $block_order = DB::table('block')
310
                ->where('block_id', '=', $block_id)
311
                ->value('block_order');
312
313
            $languages = explode(',', $this->getBlockSetting($block_id, 'languages'));
314
315
            $title = I18N::translate('Edit the FAQ');
316
        }
317
318
        $tree_names = ['' => I18N::translate('All')] + Tree::getIdList();
319
320
        return $this->viewResponse('modules/faq/edit', [
321
            'block_id'    => $block_id,
322
            'block_order' => $block_order,
323
            'header'      => $header,
324
            'faqbody'     => $faqbody,
325
            'languages'   => $languages,
326
            'title'       => $title,
327
            'tree'        => $tree,
328
            'tree_names'  => $tree_names,
329
        ]);
330
    }
331
332
    /**
333
     * @param ServerRequestInterface $request
334
     *
335
     * @return ResponseInterface
336
     */
337
    public function postAdminEditAction(ServerRequestInterface $request): ResponseInterface
338
    {
339
        $tree     = $request->getAttribute('tree');
340
        $block_id = (int) ($request->getQueryParams()['block_id'] ?? 0);
341
342
        $params = $request->getParsedBody();
343
344
        $faqbody     = $params['faqbody'];
345
        $header      = $params['header'];
346
        $languages   = $params['languages'] ?? [];
347
        $gedcom_id   = (int) $params['gedcom_id'] ?: null;
348
        $block_order = (int) $params['block_order'];
349
350
        $faqbody = $this->html_service->sanitize($faqbody);
351
        $header  = $this->html_service->sanitize($header);
352
353
        if ($block_id !== 0) {
354
            DB::table('block')
355
                ->where('block_id', '=', $block_id)
356
                ->update([
357
                    'gedcom_id'   => $gedcom_id,
358
                    'block_order' => $block_order,
359
                ]);
360
        } else {
361
            DB::table('block')->insert([
362
                'gedcom_id'   => $gedcom_id,
363
                'module_name' => $this->name(),
364
                'block_order' => $block_order,
365
            ]);
366
367
            $block_id = (int) DB::connection()->getPdo()->lastInsertId();
368
        }
369
370
        $this->setBlockSetting($block_id, 'faqbody', $faqbody);
371
        $this->setBlockSetting($block_id, 'header', $header);
372
        $this->setBlockSetting($block_id, 'languages', implode(',', $languages));
373
374
        $url = route('module', [
375
            'module' => $this->name(),
376
            'action' => 'Admin',
377
            'tree'   => $tree->name(),
378
        ]);
379
380
        return redirect($url);
381
    }
382
383
    /**
384
     * @param ServerRequestInterface $request
385
     *
386
     * @return ResponseInterface
387
     */
388
    public function getShowAction(ServerRequestInterface $request): ResponseInterface
389
    {
390
        $tree = $request->getAttribute('tree');
391
        assert($tree instanceof Tree, new InvalidArgumentException());
392
393
        // Filter foreign languages.
394
        $faqs = $this->faqsForTree($tree)
395
            ->filter(static function (stdClass $faq): bool {
396
                return $faq->languages === '' || in_array(WT_LOCALE, explode(',', $faq->languages), true);
397
            });
398
399
        return $this->viewResponse('modules/faq/show', [
400
            'faqs'  => $faqs,
401
            'title' => I18N::translate('Frequently asked questions'),
402
            'tree'  => $tree,
403
        ]);
404
    }
405
406
    /**
407
     * @param Tree $tree
408
     *
409
     * @return Collection
410
     */
411
    private function faqsForTree(Tree $tree): Collection
412
    {
413
        return DB::table('block')
414
            ->join('block_setting AS bs1', 'bs1.block_id', '=', 'block.block_id')
415
            ->join('block_setting AS bs2', 'bs2.block_id', '=', 'block.block_id')
416
            ->join('block_setting AS bs3', 'bs3.block_id', '=', 'block.block_id')
417
            ->where('module_name', '=', $this->name())
418
            ->where('bs1.setting_name', '=', 'header')
419
            ->where('bs2.setting_name', '=', 'faqbody')
420
            ->where('bs3.setting_name', '=', 'languages')
421
            ->where(static function (Builder $query) use ($tree): void {
422
                $query
423
                    ->whereNull('gedcom_id')
424
                    ->orWhere('gedcom_id', '=', $tree->id());
425
            })
426
            ->orderBy('block_order')
427
            ->select(['block.block_id', 'block_order', 'gedcom_id', 'bs1.setting_value AS header', 'bs2.setting_value AS faqbody', 'bs3.setting_value AS languages'])
428
            ->get();
429
    }
430
431
    /**
432
     * @param Tree   $tree
433
     * @param string $language
434
     *
435
     * @return bool
436
     */
437
    private function faqsExist(Tree $tree, string $language): bool
438
    {
439
        return DB::table('block')
440
            ->join('block_setting', 'block_setting.block_id', '=', 'block.block_id')
441
            ->where('module_name', '=', $this->name())
442
            ->where('setting_name', '=', 'languages')
443
            ->where(static function (Builder $query) use ($tree): void {
444
                $query
445
                    ->whereNull('gedcom_id')
446
                    ->orWhere('gedcom_id', '=', $tree->id());
447
            })
448
            ->select(['setting_value AS languages'])
449
            ->get()
450
            ->filter(static function (stdClass $faq) use ($language): bool {
451
                return $faq->languages === '' || in_array($language, explode(',', $faq->languages), true);
452
            })
453
            ->isNotEmpty();
454
    }
455
}
456