xref: /webtrees/app/Module/UserFavoritesModule.php (revision 5bfc689774bb9a6401271c4ed15a6d50652c991b)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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\GedcomRecord;
25use Fisharebest\Webtrees\Http\RequestHandlers\UserPage;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Registry;
28use Fisharebest\Webtrees\Tree;
29use Fisharebest\Webtrees\Validator;
30use Illuminate\Database\Capsule\Manager as DB;
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    /**
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 user’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,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'    => true,
79            'favorites'   => $this->getFavorites($tree, Auth::user()),
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 true;
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 false;
126    }
127
128    /**
129     * Get the favorites for a user
130     *
131     * @param Tree          $tree
132     * @param UserInterface $user
133     *
134     * @return array<object>
135     */
136    public function getFavorites(Tree $tree, UserInterface $user): array
137    {
138        return DB::table('favorite')
139            ->where('gedcom_id', '=', $tree->id())
140            ->where('user_id', '=', $user->id())
141            ->get()
142            ->map(static function (object $row) use ($tree): object {
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   = Validator::attributes($request)->tree();
167        $user   = Validator::attributes($request)->user();
168        $params = (array) $request->getParsedBody();
169
170        $note  = $params['note'];
171        $title = $params['title'];
172        $url   = $params['url'];
173        $type  = $params['type'];
174        $xref  = $params[$type . '-xref'] ?? '';
175
176        $record = $this->getRecordForType($type, $xref, $tree);
177
178        if (Auth::check()) {
179            if ($type === 'url' && $url !== '') {
180                $this->addUrlFavorite($tree, $user, $url, $title ?: $url, $note);
181            }
182
183            if ($record instanceof GedcomRecord && $record->canShow()) {
184                $this->addRecordFavorite($tree, $user, $record, $note);
185            }
186        }
187
188        $url = route(UserPage::class, ['tree' => $tree->name()]);
189
190        return redirect($url);
191    }
192
193    /**
194     * @param ServerRequestInterface $request
195     *
196     * @return ResponseInterface
197     */
198    public function postDeleteFavoriteAction(ServerRequestInterface $request): ResponseInterface
199    {
200        $tree        = Validator::attributes($request)->tree();
201        $user        = Validator::attributes($request)->user();
202        $favorite_id = Validator::queryParams($request)->integer('favorite_id');
203
204        if (Auth::check()) {
205            DB::table('favorite')
206                ->where('favorite_id', '=', $favorite_id)
207                ->where('user_id', '=', $user->id())
208                ->delete();
209        }
210
211        $url = route(UserPage::class, ['tree' => $tree->name()]);
212
213        return redirect($url);
214    }
215
216    /**
217     * @param Tree          $tree
218     * @param UserInterface $user
219     * @param string        $url
220     * @param string        $title
221     * @param string        $note
222     *
223     * @return void
224     */
225    private function addUrlFavorite(Tree $tree, UserInterface $user, string $url, string $title, string $note): void
226    {
227        DB::table('favorite')->updateOrInsert([
228            'gedcom_id' => $tree->id(),
229            'user_id'   => $user->id(),
230            'url'       => $url,
231        ], [
232            'favorite_type' => 'URL',
233            'note'          => $note,
234            'title'         => $title,
235        ]);
236    }
237
238    /**
239     * @param Tree          $tree
240     * @param UserInterface $user
241     * @param GedcomRecord  $record
242     * @param string        $note
243     *
244     * @return void
245     */
246    private function addRecordFavorite(Tree $tree, UserInterface $user, GedcomRecord $record, string $note): void
247    {
248        DB::table('favorite')->updateOrInsert([
249            'gedcom_id' => $tree->id(),
250            'user_id'   => $user->id(),
251            'xref'      => $record->xref(),
252        ], [
253            'favorite_type' => $record->tag(),
254            'note'          => $note,
255        ]);
256    }
257
258    /**
259     * @param string $type
260     * @param string $xref
261     * @param Tree   $tree
262     *
263     * @return GedcomRecord|null
264     */
265    private function getRecordForType(string $type, string $xref, Tree $tree): ?GedcomRecord
266    {
267        switch ($type) {
268            case 'indi':
269                return Registry::individualFactory()->make($xref, $tree);
270
271            case 'fam':
272                return Registry::familyFactory()->make($xref, $tree);
273
274            case 'sour':
275                return Registry::sourceFactory()->make($xref, $tree);
276
277            case 'repo':
278                return Registry::repositoryFactory()->make($xref, $tree);
279
280            case 'obje':
281                return Registry::mediaFactory()->make($xref, $tree);
282
283            default:
284                return null;
285        }
286    }
287}
288