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