xref: /webtrees/app/Module/FamilyTreeFavoritesModule.php (revision d3d68c00895c5db24007b987c2ee5f9f44403bef)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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\Auth;
23use Fisharebest\Webtrees\GedcomRecord;
24use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Database\Capsule\Manager as DB;
29use Illuminate\Support\Str;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32
33use function assert;
34
35/**
36 * Class FamilyTreeFavoritesModule
37 */
38class FamilyTreeFavoritesModule extends AbstractModule implements ModuleBlockInterface
39{
40    use ModuleBlockTrait;
41
42    /**
43     * How should this module be identified in the control panel, etc.?
44     *
45     * @return string
46     */
47    public function title(): string
48    {
49        /* I18N: Name of a module */
50        return I18N::translate('Favorites');
51    }
52
53    /**
54     * A sentence describing what this module does.
55     *
56     * @return string
57     */
58    public function description(): string
59    {
60        /* I18N: Description of the “Favorites” module */
61        return I18N::translate('Display and manage a family tree’s favorite pages.');
62    }
63
64    /**
65     * Generate the HTML content of this block.
66     *
67     * @param Tree          $tree
68     * @param int           $block_id
69     * @param string        $context
70     * @param array<string> $config
71     *
72     * @return string
73     */
74    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
75    {
76        $content = view('modules/favorites/favorites', [
77            'block_id'    => $block_id,
78            'can_edit'    => Auth::isManager($tree),
79            'favorites'   => $this->getFavorites($tree),
80            'module_name' => $this->name(),
81            'tree'        => $tree,
82        ]);
83
84        if ($context !== self::CONTEXT_EMBED) {
85            return view('modules/block-template', [
86                'block'      => Str::kebab($this->name()),
87                'id'         => $block_id,
88                'config_url' => '',
89                'title'      => $this->title(),
90                'content'    => $content,
91            ]);
92        }
93
94        return $content;
95    }
96
97    /**
98     * Should this block load asynchronously using AJAX?
99     * Simple blocks are faster in-line, more complex ones can be loaded later.
100     *
101     * @return bool
102     */
103    public function loadAjax(): bool
104    {
105        return false;
106    }
107
108    /**
109     * Can this block be shown on the user’s home page?
110     *
111     * @return bool
112     */
113    public function isUserBlock(): bool
114    {
115        return false;
116    }
117
118    /**
119     * Can this block be shown on the tree’s home page?
120     *
121     * @return bool
122     */
123    public function isTreeBlock(): bool
124    {
125        return true;
126    }
127
128    /**
129     * Get the favorites for a family tree
130     *
131     * @param Tree $tree
132     *
133     * @return array<object>
134     */
135    public function getFavorites(Tree $tree): array
136    {
137        return DB::table('favorite')
138            ->where('gedcom_id', '=', $tree->id())
139            ->whereNull('user_id')
140            ->get()
141            ->map(static function (object $row) use ($tree): object {
142                if ($row->xref !== null) {
143                    $row->record = Registry::gedcomRecordFactory()->make($row->xref, $tree);
144
145                    if ($row->record instanceof GedcomRecord && !$row->record->canShowName()) {
146                        $row->record = null;
147                        $row->note   = null;
148                    }
149                } else {
150                    $row->record = null;
151                }
152
153                return $row;
154            })
155            ->all();
156    }
157
158    /**
159     * @param ServerRequestInterface $request
160     *
161     * @return ResponseInterface
162     */
163    public function postAddFavoriteAction(ServerRequestInterface $request): ResponseInterface
164    {
165        $tree = $request->getAttribute('tree');
166        assert($tree instanceof Tree);
167
168        $user   = $request->getAttribute('user');
169        $params = (array) $request->getParsedBody();
170
171        $note  = $params['note'];
172        $title = $params['title'];
173        $url   = $params['url'];
174        $type  = $params['type'];
175        $xref  = $params[$type . '-xref'] ?? '';
176
177        $record = $this->getRecordForType($type, $xref, $tree);
178
179        if (Auth::isManager($tree, $user)) {
180            if ($type === 'url' && $url !== '') {
181                $this->addUrlFavorite($tree, $url, $title ?: $url, $note);
182            }
183
184            if ($record instanceof GedcomRecord && $record->canShow()) {
185                $this->addRecordFavorite($tree, $record, $note);
186            }
187        }
188
189        $url = route(TreePage::class, ['tree' => $tree->name()]);
190
191        return redirect($url);
192    }
193
194    /**
195     * @param ServerRequestInterface $request
196     *
197     * @return ResponseInterface
198     */
199    public function postDeleteFavoriteAction(ServerRequestInterface $request): ResponseInterface
200    {
201        $tree = $request->getAttribute('tree');
202        assert($tree instanceof Tree);
203
204        $user        = $request->getAttribute('user');
205        $favorite_id = $request->getQueryParams()['favorite_id'];
206
207        if (Auth::isManager($tree, $user)) {
208            DB::table('favorite')
209                ->where('favorite_id', '=', $favorite_id)
210                ->whereNull('user_id')
211                ->delete();
212        }
213
214        $url = route(TreePage::class, ['tree' => $tree->name()]);
215
216        return redirect($url);
217    }
218
219    /**
220     * @param Tree   $tree
221     * @param string $url
222     * @param string $title
223     * @param string $note
224     *
225     * @return void
226     */
227    private function addUrlFavorite(Tree $tree, string $url, string $title, string $note): void
228    {
229        DB::table('favorite')->updateOrInsert([
230            'gedcom_id' => $tree->id(),
231            'user_id'   => null,
232            'url'       => $url,
233        ], [
234            'favorite_type' => 'URL',
235            'note'          => $note,
236            'title'         => $title,
237        ]);
238    }
239
240    /**
241     * @param Tree         $tree
242     * @param GedcomRecord $record
243     * @param string       $note
244     *
245     * @return void
246     */
247    private function addRecordFavorite(Tree $tree, GedcomRecord $record, string $note): void
248    {
249        DB::table('favorite')->updateOrInsert([
250            'gedcom_id' => $tree->id(),
251            'user_id'   => null,
252            'xref'      => $record->xref(),
253        ], [
254            'favorite_type' => $record->tag(),
255            'note'          => $note,
256        ]);
257    }
258
259    /**
260     * @param string $type
261     * @param string $xref
262     * @param Tree   $tree
263     *
264     * @return GedcomRecord|null
265     */
266    private function getRecordForType(string $type, string $xref, Tree $tree): ?GedcomRecord
267    {
268        switch ($type) {
269            case 'indi':
270                return Registry::individualFactory()->make($xref, $tree);
271
272            case 'fam':
273                return Registry::familyFactory()->make($xref, $tree);
274
275            case 'sour':
276                return Registry::sourceFactory()->make($xref, $tree);
277
278            case 'repo':
279                return Registry::repositoryFactory()->make($xref, $tree);
280
281            case 'obje':
282                return Registry::mediaFactory()->make($xref, $tree);
283
284            default:
285                return null;
286        }
287    }
288}
289