xref: /webtrees/app/Module/StoriesModule.php (revision 81de533683c82a9e5c2bf2de336b47c4103fda6d)
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\Localization\Locale\LocaleInterface;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Http\RequestHandlers\ControlPanel;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Individual;
27use Fisharebest\Webtrees\Menu;
28use Fisharebest\Webtrees\Services\HtmlService;
29use Fisharebest\Webtrees\Services\TreeService;
30use Fisharebest\Webtrees\Tree;
31use Illuminate\Database\Capsule\Manager as DB;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use stdClass;
35
36use function app;
37use function assert;
38use function redirect;
39use function route;
40
41/**
42 * Class StoriesModule
43 */
44class StoriesModule extends AbstractModule implements ModuleConfigInterface, ModuleMenuInterface, ModuleTabInterface
45{
46    use ModuleTabTrait;
47    use ModuleConfigTrait;
48    use ModuleMenuTrait;
49
50    /** @var HtmlService */
51    private $html_service;
52
53    /** @var TreeService */
54    private $tree_service;
55
56    /**
57     * BatchUpdateModule constructor.
58     *
59     * @param HtmlService $html_service
60     * @param TreeService $tree_service
61     */
62    public function __construct(HtmlService $html_service, TreeService $tree_service)
63    {
64        $this->html_service = $html_service;
65        $this->tree_service = $tree_service;
66    }
67
68    /** @var int The default access level for this module.  It can be changed in the control panel. */
69    protected $access_level = Auth::PRIV_HIDE;
70
71    /**
72     * A sentence describing what this module does.
73     *
74     * @return string
75     */
76    public function description(): string
77    {
78        /* I18N: Description of the “Stories” module */
79        return I18N::translate('Add narrative stories to individuals in the family tree.');
80    }
81
82    /**
83     * The default position for this menu.  It can be changed in the control panel.
84     *
85     * @return int
86     */
87    public function defaultMenuOrder(): int
88    {
89        return 7;
90    }
91
92    /**
93     * The default position for this tab.  It can be changed in the control panel.
94     *
95     * @return int
96     */
97    public function defaultTabOrder(): int
98    {
99        return 9;
100    }
101
102    /**
103     * Generate the HTML content of this tab.
104     *
105     * @param Individual $individual
106     *
107     * @return string
108     */
109    public function getTabContent(Individual $individual): string
110    {
111        return view('modules/stories/tab', [
112            'is_admin'   => Auth::isAdmin(),
113            'individual' => $individual,
114            'stories'    => $this->getStoriesForIndividual($individual),
115            'tree'       => $individual->tree(),
116        ]);
117    }
118
119    /**
120     * @param Individual $individual
121     *
122     * @return stdClass[]
123     */
124    private function getStoriesForIndividual(Individual $individual): array
125    {
126        $locale = app(ServerRequestInterface::class)->getAttribute('locale');
127        assert($locale instanceof LocaleInterface);
128
129        $block_ids = DB::table('block')
130            ->where('module_name', '=', $this->name())
131            ->where('xref', '=', $individual->xref())
132            ->where('gedcom_id', '=', $individual->tree()->id())
133            ->pluck('block_id');
134
135        $stories = [];
136        foreach ($block_ids as $block_id) {
137            $block_id = (int) $block_id;
138
139            // Only show this block for certain languages
140            $languages = $this->getBlockSetting($block_id, 'languages');
141            if ($languages === '' || in_array($locale->languageTag(), explode(',', $languages), true)) {
142                $stories[] = (object) [
143                    'block_id'   => $block_id,
144                    'title'      => $this->getBlockSetting($block_id, 'title'),
145                    'story_body' => $this->getBlockSetting($block_id, 'story_body'),
146                ];
147            }
148        }
149
150        return $stories;
151    }
152
153    /**
154     * Is this tab empty? If so, we don't always need to display it.
155     *
156     * @param Individual $individual
157     *
158     * @return bool
159     */
160    public function hasTabContent(Individual $individual): bool
161    {
162        return Auth::isManager($individual->tree()) || $this->getStoriesForIndividual($individual) !== [];
163    }
164
165    /**
166     * A greyed out tab has no actual content, but may perhaps have
167     * options to create content.
168     *
169     * @param Individual $individual
170     *
171     * @return bool
172     */
173    public function isGrayedOut(Individual $individual): bool
174    {
175        return $this->getStoriesForIndividual($individual) !== [];
176    }
177
178    /**
179     * Can this tab load asynchronously?
180     *
181     * @return bool
182     */
183    public function canLoadAjax(): bool
184    {
185        return false;
186    }
187
188    /**
189     * A menu, to be added to the main application menu.
190     *
191     * @param Tree $tree
192     *
193     * @return Menu|null
194     */
195    public function getMenu(Tree $tree): ?Menu
196    {
197        $menu = new Menu($this->title(), route('module', [
198            'module' => $this->name(),
199            'action' => 'ShowList',
200            'tree'    => $tree->name(),
201        ]), 'menu-story');
202
203        return $menu;
204    }
205
206    /**
207     * How should this module be identified in the control panel, etc.?
208     *
209     * @return string
210     */
211    public function title(): string
212    {
213        /* I18N: Name of a module */
214        return I18N::translate('Stories');
215    }
216
217    /**
218     * @param ServerRequestInterface $request
219     *
220     * @return ResponseInterface
221     */
222    public function getAdminAction(ServerRequestInterface $request): ResponseInterface
223    {
224        $this->layout = 'layouts/administration';
225
226        // This module can't run without a tree
227        $tree = $request->getAttribute('tree');
228
229        if (!$tree instanceof Tree) {
230            $tree = $this->tree_service->all()->first();
231            if ($tree instanceof Tree) {
232                return redirect(route('module', ['module' => $this->name(), 'action' => 'Admin', 'tree' => $tree->name()]));
233            }
234
235            return redirect(route(ControlPanel::class));
236        }
237
238        $stories = DB::table('block')
239            ->where('module_name', '=', $this->name())
240            ->where('gedcom_id', '=', $tree->id())
241            ->orderBy('xref')
242            ->get();
243
244        foreach ($stories as $story) {
245            $block_id = (int) $story->block_id;
246
247            $story->individual = Individual::getInstance($story->xref, $tree);
248            $story->title      = $this->getBlockSetting($block_id, 'title');
249            $story->languages  = $this->getBlockSetting($block_id, 'languages');
250        }
251
252        $tree_names = $this->tree_service->all()->map(static function (Tree $tree): string {
253            return $tree->title();
254        });
255
256        return $this->viewResponse('modules/stories/config', [
257            'module'     => $this->name(),
258            'stories'    => $stories,
259            'title'      => $this->title() . ' — ' . $tree->title(),
260            'tree'       => $tree,
261            'tree_names' => $tree_names,
262        ]);
263    }
264
265    /**
266     * @param ServerRequestInterface $request
267     *
268     * @return ResponseInterface
269     */
270    public function postAdminAction(ServerRequestInterface $request): ResponseInterface
271    {
272        return redirect(route('module', [
273            'module' => $this->name(),
274            'action' => 'Admin',
275            'tree'   => $request->getParsedBody()['tree'] ?? '',
276        ]));
277    }
278
279    /**
280     * @param ServerRequestInterface $request
281     *
282     * @return ResponseInterface
283     */
284    public function getAdminEditAction(ServerRequestInterface $request): ResponseInterface
285    {
286        $this->layout = 'layouts/administration';
287
288        $tree = $request->getAttribute('tree');
289        assert($tree instanceof Tree);
290
291        $block_id = (int) ($request->getQueryParams()['block_id'] ?? 0);
292
293        if ($block_id === 0) {
294            // Creating a new story
295            $story_title = '';
296            $story_body  = '';
297            $languages   = [];
298            $xref = $request->getQueryParams()['xref'] ?? '';
299
300            $title = I18N::translate('Add a story') . ' — ' . e($tree->title());
301        } else {
302            // Editing an existing story
303            $xref = (string) DB::table('block')
304                ->where('block_id', '=', $block_id)
305                ->value('xref');
306
307            $story_title = $this->getBlockSetting($block_id, 'title');
308            $story_body  = $this->getBlockSetting($block_id, 'story_body');
309            $languages   = explode(',', $this->getBlockSetting($block_id, 'languages'));
310
311            $title = I18N::translate('Edit the story') . ' — ' . e($tree->title());
312        }
313
314        $individual  = Individual::getInstance($xref, $tree);
315
316        return $this->viewResponse('modules/stories/edit', [
317            'block_id'    => $block_id,
318            'languages'   => $languages,
319            'story_body'  => $story_body,
320            'story_title' => $story_title,
321            'title'       => $title,
322            'tree'        => $tree,
323            'individual'  => $individual,
324        ]);
325    }
326
327    /**
328     * @param ServerRequestInterface $request
329     *
330     * @return ResponseInterface
331     */
332    public function postAdminEditAction(ServerRequestInterface $request): ResponseInterface
333    {
334        $tree = $request->getAttribute('tree');
335        assert($tree instanceof Tree);
336
337        $block_id = (int) ($request->getQueryParams()['block_id'] ?? 0);
338
339        $params = $request->getParsedBody();
340
341        $xref        = $params['xref'];
342        $story_body  = $params['story_body'];
343        $story_title = $params['story_title'];
344        $languages   = $params['languages'] ?? [];
345
346        $story_body  = $this->html_service->sanitize($story_body);
347        $story_title = $this->html_service->sanitize($story_title);
348
349        if ($block_id !== 0) {
350            DB::table('block')
351                ->where('block_id', '=', $block_id)
352                ->update([
353                    'gedcom_id' => $tree->id(),
354                    'xref'      => $xref,
355                ]);
356        } else {
357            DB::table('block')->insert([
358                'gedcom_id'   => $tree->id(),
359                'xref'        => $xref,
360                'module_name' => $this->name(),
361                'block_order' => 0,
362            ]);
363
364            $block_id = (int) DB::connection()->getPdo()->lastInsertId();
365        }
366
367        $this->setBlockSetting($block_id, 'story_body', $story_body);
368        $this->setBlockSetting($block_id, 'title', $story_title);
369        $this->setBlockSetting($block_id, 'languages', implode(',', $languages));
370
371        $url = route('module', [
372            'module' => $this->name(),
373            'action' => 'Admin',
374            'tree'    => $tree->name(),
375        ]);
376
377        return redirect($url);
378    }
379
380    /**
381     * @param ServerRequestInterface $request
382     *
383     * @return ResponseInterface
384     */
385    public function postAdminDeleteAction(ServerRequestInterface $request): ResponseInterface
386    {
387        $tree = $request->getAttribute('tree');
388        assert($tree instanceof Tree);
389
390        $block_id = $request->getQueryParams()['block_id'];
391
392        DB::table('block_setting')
393            ->where('block_id', '=', $block_id)
394            ->delete();
395
396        DB::table('block')
397            ->where('block_id', '=', $block_id)
398            ->delete();
399
400        $url = route('module', [
401            'module' => $this->name(),
402            'action' => 'Admin',
403            'tree'    => $tree->name(),
404        ]);
405
406        return redirect($url);
407    }
408
409    /**
410     * @param ServerRequestInterface $request
411     *
412     * @return ResponseInterface
413     */
414    public function getShowListAction(ServerRequestInterface $request): ResponseInterface
415    {
416        $tree = $request->getAttribute('tree');
417        assert($tree instanceof Tree);
418
419        $locale = $request->getAttribute('locale');
420        assert($locale instanceof LocaleInterface);
421
422        $stories = DB::table('block')
423            ->where('module_name', '=', $this->name())
424            ->where('gedcom_id', '=', $tree->id())
425            ->get()
426            ->map(function (stdClass $story) use ($tree): stdClass {
427                $block_id = (int) $story->block_id;
428
429                $story->individual = Individual::getInstance($story->xref, $tree);
430                $story->title      = $this->getBlockSetting($block_id, 'title');
431                $story->languages  = $this->getBlockSetting($block_id, 'languages');
432
433                return $story;
434            })->filter(static function (stdClass $story): bool {
435                // Filter non-existant and private individuals.
436                return $story->individual instanceof Individual && $story->individual->canShow();
437            })->filter(static function (stdClass $story) use ($locale): bool {
438                // Filter foreign languages.
439                return $story->languages === '' || in_array($locale->languageTag(), explode(',', $story->languages), true);
440            });
441
442        return $this->viewResponse('modules/stories/list', [
443            'stories' => $stories,
444            'title'   => $this->title(),
445            'tree'    => $tree,
446        ]);
447    }
448}
449