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