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