xref: /webtrees/app/Module/UserFavoritesModule.php (revision 50d6f48c66bf0bac3eabb9bdf84f878e4cc97d4a)
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   $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'    => true,
80            'favorites'   => $this->getFavorites($tree, Auth::user()),
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 true;
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 false;
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 user
156     *
157     * @param Tree          $tree
158     * @param UserInterface $user
159     *
160     * @return stdClass[]
161     */
162    public function getFavorites(Tree $tree, UserInterface $user): array
163    {
164        return DB::table('favorite')
165            ->where('gedcom_id', '=', $tree->id())
166            ->where('user_id', '=', $user->id())
167            ->get()
168            ->map(static function (stdClass $row) use ($tree): stdClass {
169                if ($row->xref !== null) {
170                    $row->record = GedcomRecord::getInstance($row->xref, $tree);
171                } else {
172                    $row->record = null;
173                }
174
175                return $row;
176            })
177            ->all();
178    }
179
180    /**
181     * @param ServerRequestInterface $request
182     * @param Tree                   $tree
183     * @param UserInterface          $user
184     *
185     * @return ResponseInterface
186     */
187    public function postAddFavoriteAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
188    {
189        $params = $request->getParsedBody();
190
191        $note  = $params['note'];
192        $title = $params['title'];
193        $url   = $params['url'];
194        $type  = $params['type'];
195        $xref  = $params[$type . '-xref'] ?? '';
196
197        $record = $this->getRecordForType($type, $xref, $tree);
198
199        if (Auth::check()) {
200            if ($type === 'url' && $url !== '') {
201                $this->addUrlFavorite($tree, $user, $url, $title ?: $url, $note);
202            }
203
204            if ($record instanceof GedcomRecord && $record->canShow()) {
205                $this->addRecordFavorite($tree, $user, $record, $note);
206            }
207        }
208
209        $url = route('user-page', ['ged' => $tree->name()]);
210
211        return redirect($url);
212    }
213
214    /**
215     * @param ServerRequestInterface $request
216     * @param Tree                   $tree
217     * @param UserInterface          $user
218     *
219     * @return ResponseInterface
220     */
221    public function postDeleteFavoriteAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
222    {
223        $favorite_id = $request->getQueryParams()['favorite_id'];
224
225        if (Auth::check()) {
226            DB::table('favorite')
227                ->where('favorite_id', '=', $favorite_id)
228                ->where('user_id', '=', $user->id())
229                ->delete();
230        }
231
232        $url = route('user-page', ['ged' => $tree->name()]);
233
234        return redirect($url);
235    }
236
237    /**
238     * @param Tree          $tree
239     * @param UserInterface $user
240     * @param string        $url
241     * @param string        $title
242     * @param string        $note
243     *
244     * @return void
245     */
246    private function addUrlFavorite(Tree $tree, UserInterface $user, string $url, string $title, string $note): void
247    {
248        DB::table('favorite')->updateOrInsert([
249            'gedcom_id' => $tree->id(),
250            'user_id'   => $user->id(),
251            'url'       => $url,
252        ], [
253            'favorite_type' => 'URL',
254            'note'          => $note,
255            'title'         => $title,
256        ]);
257    }
258
259    /**
260     * @param Tree          $tree
261     * @param UserInterface $user
262     * @param GedcomRecord  $record
263     * @param string        $note
264     *
265     * @return void
266     */
267    private function addRecordFavorite(Tree $tree, UserInterface $user, GedcomRecord $record, string $note): void
268    {
269        DB::table('favorite')->updateOrInsert([
270            'gedcom_id' => $tree->id(),
271            'user_id'   => $user->id(),
272            'xref'      => $record->xref(),
273        ], [
274            'favorite_type' => $record::RECORD_TYPE,
275            'note'          => $note,
276        ]);
277    }
278
279    /**
280     * @param string $type
281     * @param string $xref
282     * @param Tree   $tree
283     *
284     * @return GedcomRecord|null
285     */
286    private function getRecordForType(string $type, string $xref, Tree $tree): ?GedcomRecord
287    {
288        switch ($type) {
289            case 'indi':
290                return Individual::getInstance($xref, $tree);
291
292            case 'fam':
293                return Family::getInstance($xref, $tree);
294
295            case 'sour':
296                return Source::getInstance($xref, $tree);
297
298            case 'repo':
299                return Repository::getInstance($xref, $tree);
300
301            case 'obje':
302                return Media::getInstance($xref, $tree);
303
304            default:
305                return null;
306        }
307    }
308}
309