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