xref: /webtrees/app/Module/UserFavoritesModule.php (revision 3eae54c8a20b98985facfcff8d58c982338bbf85)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Module;
19
20use Fisharebest\Webtrees\Auth;
21use Fisharebest\Webtrees\Contracts\UserInterface;
22use Fisharebest\Webtrees\Family;
23use Fisharebest\Webtrees\GedcomRecord;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Individual;
26use Fisharebest\Webtrees\Media;
27use Fisharebest\Webtrees\Repository;
28use Fisharebest\Webtrees\Source;
29use Fisharebest\Webtrees\Tree;
30use Illuminate\Database\Capsule\Manager as DB;
31use Illuminate\Support\Str;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use stdClass;
35
36/**
37 * Class UserFavoritesModule
38 */
39class UserFavoritesModule 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 user’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'    => true,
80            'favorites'   => $this->getFavorites($tree, Auth::user()),
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 true;
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 false;
127    }
128
129    /**
130     * Get the favorites for a user
131     *
132     * @param Tree          $tree
133     * @param UserInterface $user
134     *
135     * @return stdClass[]
136     */
137    public function getFavorites(Tree $tree, UserInterface $user): array
138    {
139        return DB::table('favorite')
140            ->where('gedcom_id', '=', $tree->id())
141            ->where('user_id', '=', $user->id())
142            ->get()
143            ->map(static function (stdClass $row) use ($tree): stdClass {
144                if ($row->xref !== null) {
145                    $row->record = GedcomRecord::getInstance($row->xref, $tree);
146                } else {
147                    $row->record = null;
148                }
149
150                return $row;
151            })
152            ->all();
153    }
154
155    /**
156     * @param ServerRequestInterface $request
157     * @param Tree                   $tree
158     * @param UserInterface          $user
159     *
160     * @return ResponseInterface
161     */
162    public function postAddFavoriteAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
163    {
164        $params = $request->getParsedBody();
165
166        $note  = $params['note'];
167        $title = $params['title'];
168        $url   = $params['url'];
169        $type  = $params['type'];
170        $xref  = $params[$type . '-xref'] ?? '';
171
172        $record = $this->getRecordForType($type, $xref, $tree);
173
174        if (Auth::check()) {
175            if ($type === 'url' && $url !== '') {
176                $this->addUrlFavorite($tree, $user, $url, $title ?: $url, $note);
177            }
178
179            if ($record instanceof GedcomRecord && $record->canShow()) {
180                $this->addRecordFavorite($tree, $user, $record, $note);
181            }
182        }
183
184        $url = route('user-page', ['ged' => $tree->name()]);
185
186        return redirect($url);
187    }
188
189    /**
190     * @param ServerRequestInterface $request
191     * @param Tree                   $tree
192     * @param UserInterface          $user
193     *
194     * @return ResponseInterface
195     */
196    public function postDeleteFavoriteAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
197    {
198        $favorite_id = $request->getQueryParams()['favorite_id'];
199
200        if (Auth::check()) {
201            DB::table('favorite')
202                ->where('favorite_id', '=', $favorite_id)
203                ->where('user_id', '=', $user->id())
204                ->delete();
205        }
206
207        $url = route('user-page', ['ged' => $tree->name()]);
208
209        return redirect($url);
210    }
211
212    /**
213     * @param Tree          $tree
214     * @param UserInterface $user
215     * @param string        $url
216     * @param string        $title
217     * @param string        $note
218     *
219     * @return void
220     */
221    private function addUrlFavorite(Tree $tree, UserInterface $user, string $url, string $title, string $note): void
222    {
223        DB::table('favorite')->updateOrInsert([
224            'gedcom_id' => $tree->id(),
225            'user_id'   => $user->id(),
226            'url'       => $url,
227        ], [
228            'favorite_type' => 'URL',
229            'note'          => $note,
230            'title'         => $title,
231        ]);
232    }
233
234    /**
235     * @param Tree          $tree
236     * @param UserInterface $user
237     * @param GedcomRecord  $record
238     * @param string        $note
239     *
240     * @return void
241     */
242    private function addRecordFavorite(Tree $tree, UserInterface $user, GedcomRecord $record, string $note): void
243    {
244        DB::table('favorite')->updateOrInsert([
245            'gedcom_id' => $tree->id(),
246            'user_id'   => $user->id(),
247            'xref'      => $record->xref(),
248        ], [
249            'favorite_type' => $record::RECORD_TYPE,
250            'note'          => $note,
251        ]);
252    }
253
254    /**
255     * @param string $type
256     * @param string $xref
257     * @param Tree   $tree
258     *
259     * @return GedcomRecord|null
260     */
261    private function getRecordForType(string $type, string $xref, Tree $tree): ?GedcomRecord
262    {
263        switch ($type) {
264            case 'indi':
265                return Individual::getInstance($xref, $tree);
266
267            case 'fam':
268                return Family::getInstance($xref, $tree);
269
270            case 'sour':
271                return Source::getInstance($xref, $tree);
272
273            case 'repo':
274                return Repository::getInstance($xref, $tree);
275
276            case 'obje':
277                return Media::getInstance($xref, $tree);
278
279            default:
280                return null;
281        }
282    }
283}
284