xref: /webtrees/app/Module/FamilyTreeFavoritesModule.php (revision 39b00ae97f08f1096ebe5846700f5ed4f140ea3b)
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 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   $ctype
71     * @param string[] $cfg
72     *
73     * @return string
74     */
75    public function getBlock(Tree $tree, int $block_id, string $ctype = '', array $cfg = []): 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 ($ctype !== '') {
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 comples ones
101     * 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 false;
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 true;
128    }
129
130    /**
131     * Update the configuration for a block.
132     *
133     * @param ServerRequestInterface $request
134     * @param int     $block_id
135     *
136     * @return void
137     */
138    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
139    {
140    }
141
142    /**
143     * An HTML form to edit block settings
144     *
145     * @param Tree $tree
146     * @param int  $block_id
147     *
148     * @return void
149     */
150    public function editBlockConfiguration(Tree $tree, int $block_id): void
151    {
152    }
153
154    /**
155     * Get the favorites for a family tree
156     *
157     * @param Tree $tree
158     *
159     * @return stdClass[]
160     */
161    public function getFavorites(Tree $tree): array
162    {
163        return DB::table('favorite')
164            ->where('gedcom_id', '=', $tree->id())
165            ->whereNull('user_id')
166            ->get()
167            ->map(static function (stdClass $row) use ($tree): stdClass {
168                if ($row->xref !== null) {
169                    $row->record = GedcomRecord::getInstance($row->xref, $tree);
170                } else {
171                    $row->record = null;
172                }
173
174                return $row;
175            })
176            ->all();
177    }
178
179    /**
180     * @param ServerRequestInterface $request
181     * @param Tree                   $tree
182     * @param UserInterface          $user
183     *
184     * @return ResponseInterface
185     */
186    public function postAddFavoriteAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
187    {
188        $params = $request->getParsedBody();
189
190        $note  = $params['note'];
191        $title = $params['title'];
192        $url   = $params['url'];
193        $type  = $params['type'];
194        $xref  = $params[$type . '-xref'] ?? '';
195
196        $record = $this->getRecordForType($type, $xref, $tree);
197
198        if (Auth::isManager($tree, $user)) {
199            if ($type === 'url' && $url !== '') {
200                $this->addUrlFavorite($tree, $url, $title ?: $url, $note);
201            }
202
203            if ($record instanceof GedcomRecord && $record->canShow()) {
204                $this->addRecordFavorite($tree, $record, $note);
205            }
206        }
207
208        $url = route('tree-page', ['ged' => $tree->name()]);
209
210        return redirect($url);
211    }
212
213    /**
214     * @param ServerRequestInterface $request
215     * @param Tree                   $tree
216     * @param UserInterface          $user
217     *
218     * @return ResponseInterface
219     */
220    public function postDeleteFavoriteAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
221    {
222        $favorite_id = $request->getQueryParams()['favorite_id'];
223
224        if (Auth::isManager($tree, $user)) {
225            DB::table('favorite')
226                ->where('favorite_id', '=', $favorite_id)
227                ->whereNull('user_id')
228                ->delete();
229        }
230
231        $url = route('tree-page', ['ged' => $tree->name()]);
232
233        return redirect($url);
234    }
235
236    /**
237     * @param Tree   $tree
238     * @param string $url
239     * @param string $title
240     * @param string $note
241     *
242     * @return void
243     */
244    private function addUrlFavorite(Tree $tree, string $url, string $title, string $note): void
245    {
246        DB::table('favorite')->updateOrInsert([
247            'gedcom_id' => $tree->id(),
248            'user_id'   => null,
249            'url'       => $url,
250        ], [
251            'favorite_type' => 'URL',
252            'note'          => $note,
253            'title'         => $title,
254        ]);
255    }
256
257    /**
258     * @param Tree         $tree
259     * @param GedcomRecord $record
260     * @param string       $note
261     *
262     * @return void
263     */
264    private function addRecordFavorite(Tree $tree, GedcomRecord $record, string $note): void
265    {
266        DB::table('favorite')->updateOrInsert([
267            'gedcom_id' => $tree->id(),
268            'user_id'   => null,
269            'xref'      => $record->xref(),
270        ], [
271            'favorite_type' => $record::RECORD_TYPE,
272            'note'          => $note,
273        ]);
274    }
275
276    /**
277     * @param string $type
278     * @param string $xref
279     * @param Tree   $tree
280     *
281     * @return GedcomRecord|null
282     */
283    private function getRecordForType(string $type, string $xref, Tree $tree): ?GedcomRecord
284    {
285        switch ($type) {
286            case 'indi':
287                return Individual::getInstance($xref, $tree);
288
289            case 'fam':
290                return Family::getInstance($xref, $tree);
291
292            case 'sour':
293                return Source::getInstance($xref, $tree);
294
295            case 'repo':
296                return Repository::getInstance($xref, $tree);
297
298            case 'obje':
299                return Media::getInstance($xref, $tree);
300
301            default:
302                return null;
303        }
304    }
305}
306