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