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