xref: /webtrees/app/Module/FamilyTreeFavoritesModule.php (revision cf7c85896a54223772c76826381a9151d4a21e10)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Factory;
24use Fisharebest\Webtrees\GedcomRecord;
25use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Database\Capsule\Manager as DB;
29use Illuminate\Support\Str;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use stdClass;
33
34use function assert;
35
36/**
37 * Class FamilyTreeFavoritesModule
38 */
39class FamilyTreeFavoritesModule 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 family tree’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'    => Auth::isManager($tree),
80            'favorites'   => $this->getFavorites($tree),
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 false;
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 true;
127    }
128
129    /**
130     * Get the favorites for a family tree
131     *
132     * @param Tree $tree
133     *
134     * @return stdClass[]
135     */
136    public function getFavorites(Tree $tree): array
137    {
138        return DB::table('favorite')
139            ->where('gedcom_id', '=', $tree->id())
140            ->whereNull('user_id')
141            ->get()
142            ->map(static function (stdClass $row) use ($tree): stdClass {
143                if ($row->xref !== null) {
144                    $row->record = Factory::gedcomRecord()->make($row->xref, $tree);
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 = $request->getAttribute('tree');
162        assert($tree instanceof Tree);
163
164        $user   = $request->getAttribute('user');
165        $params = (array) $request->getParsedBody();
166
167        $note  = $params['note'];
168        $title = $params['title'];
169        $url   = $params['url'];
170        $type  = $params['type'];
171        $xref  = $params[$type . '-xref'] ?? '';
172
173        $record = $this->getRecordForType($type, $xref, $tree);
174
175        if (Auth::isManager($tree, $user)) {
176            if ($type === 'url' && $url !== '') {
177                $this->addUrlFavorite($tree, $url, $title ?: $url, $note);
178            }
179
180            if ($record instanceof GedcomRecord && $record->canShow()) {
181                $this->addRecordFavorite($tree, $record, $note);
182            }
183        }
184
185        $url = route(TreePage::class, ['tree' => $tree->name()]);
186
187        return redirect($url);
188    }
189
190    /**
191     * @param ServerRequestInterface $request
192     *
193     * @return ResponseInterface
194     */
195    public function postDeleteFavoriteAction(ServerRequestInterface $request): ResponseInterface
196    {
197        $tree = $request->getAttribute('tree');
198        assert($tree instanceof Tree);
199
200        $user        = $request->getAttribute('user');
201        $favorite_id = $request->getQueryParams()['favorite_id'];
202
203        if (Auth::isManager($tree, $user)) {
204            DB::table('favorite')
205                ->where('favorite_id', '=', $favorite_id)
206                ->whereNull('user_id')
207                ->delete();
208        }
209
210        $url = route(TreePage::class, ['tree' => $tree->name()]);
211
212        return redirect($url);
213    }
214
215    /**
216     * @param Tree   $tree
217     * @param string $url
218     * @param string $title
219     * @param string $note
220     *
221     * @return void
222     */
223    private function addUrlFavorite(Tree $tree, string $url, string $title, string $note): void
224    {
225        DB::table('favorite')->updateOrInsert([
226            'gedcom_id' => $tree->id(),
227            'user_id'   => null,
228            'url'       => $url,
229        ], [
230            'favorite_type' => 'URL',
231            'note'          => $note,
232            'title'         => $title,
233        ]);
234    }
235
236    /**
237     * @param Tree         $tree
238     * @param GedcomRecord $record
239     * @param string       $note
240     *
241     * @return void
242     */
243    private function addRecordFavorite(Tree $tree, GedcomRecord $record, string $note): void
244    {
245        DB::table('favorite')->updateOrInsert([
246            'gedcom_id' => $tree->id(),
247            'user_id'   => null,
248            'xref'      => $record->xref(),
249        ], [
250            'favorite_type' => $record::RECORD_TYPE,
251            'note'          => $note,
252        ]);
253    }
254
255    /**
256     * @param string $type
257     * @param string $xref
258     * @param Tree   $tree
259     *
260     * @return GedcomRecord|null
261     */
262    private function getRecordForType(string $type, string $xref, Tree $tree): ?GedcomRecord
263    {
264        switch ($type) {
265            case 'indi':
266                return Factory::individual()->make($xref, $tree);
267
268            case 'fam':
269                return Factory::family()->make($xref, $tree);
270
271            case 'sour':
272                return Factory::source()->make($xref, $tree);
273
274            case 'repo':
275                return Factory::repository()->make($xref, $tree);
276
277            case 'obje':
278                return Factory::media()->make($xref, $tree);
279
280            default:
281                return null;
282        }
283    }
284}
285