xref: /webtrees/app/Module/FamilyTreeFavoritesModule.php (revision 17e8e7bab41cc8e2b71cec9aefd1c4d09f352901)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 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 */
16namespace Fisharebest\Webtrees\Module;
17
18use Fisharebest\Webtrees\Auth;
19use Fisharebest\Webtrees\Database;
20use Fisharebest\Webtrees\Filter;
21use Fisharebest\Webtrees\GedcomRecord;
22use Fisharebest\Webtrees\GedcomTag;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Individual;
25use Fisharebest\Webtrees\Theme;
26use Fisharebest\Webtrees\Tree;
27use Fisharebest\Webtrees\User;
28use Ramsey\Uuid\Uuid;
29use stdClass;
30
31/**
32 * Class FamilyTreeFavoritesModule
33 *
34 * Note that the user favorites module simply extends this module, so ensure that the
35 * logic works for both.
36 */
37class FamilyTreeFavoritesModule extends AbstractModule implements ModuleBlockInterface {
38	// How to update the database schema for this module
39	const SCHEMA_TARGET_VERSION   = 4;
40	const SCHEMA_SETTING_NAME     = 'FV_SCHEMA_VERSION';
41	const SCHEMA_MIGRATION_PREFIX = '\Fisharebest\Webtrees\Module\FamilyTreeFavorites\Schema';
42
43	/**
44	 * Create a new module.
45	 *
46	 * @param string $directory Where is this module installed
47	 */
48	public function __construct($directory) {
49		parent::__construct($directory);
50
51		// Create/update the database tables.
52		// NOTE: if we want to set any module-settings, we'll need to move this.
53		Database::updateSchema(self::SCHEMA_MIGRATION_PREFIX, self::SCHEMA_SETTING_NAME, self::SCHEMA_TARGET_VERSION);
54	}
55
56	/**
57	 * How should this module be labelled on tabs, menus, etc.?
58	 *
59	 * @return string
60	 */
61	public function getTitle() {
62		return /* I18N: Name of a module */ I18N::translate('Favorites');
63	}
64
65	/**
66	 * A sentence describing what this module does.
67	 *
68	 * @return string
69	 */
70	public function getDescription() {
71		return /* I18N: Description of the “Favorites” module */ I18N::translate('Display and manage a family tree’s favorite pages.');
72	}
73
74	/**
75	 * Generate the HTML content of this block.
76	 *
77	 * @param Tree     $tree
78	 * @param int      $block_id
79	 * @param bool     $template
80	 * @param string[] $cfg
81	 *
82	 * @return string
83	 */
84	public function getBlock(Tree $tree, int $block_id, bool $template = true, array $cfg = []): string {
85		global $ctype;
86
87		$action = Filter::get('action');
88		switch ($action) {
89			case 'deletefav':
90				$favorite_id = Filter::getInteger('favorite_id');
91				if ($favorite_id) {
92					self::deleteFavorite($favorite_id);
93				}
94				break;
95			case 'addfav':
96				$gid      = Filter::get('gid', WT_REGEX_XREF, '');
97				$favnote  = Filter::get('favnote');
98				$url      = Filter::getUrl('url');
99				$favtitle = Filter::get('favtitle');
100
101				if ($gid !== '') {
102					$record = GedcomRecord::getInstance($gid, $tree);
103					if ($record && $record->canShow()) {
104						self::addFavorite([
105							'user_id'   => $ctype === 'user' ? Auth::id() : null,
106							'gedcom_id' => $tree->getTreeId(),
107							'gid'       => $record->getXref(),
108							'type'      => $record::RECORD_TYPE,
109							'url'       => null,
110							'note'      => $favnote,
111							'title'     => $favtitle,
112						]);
113					}
114				} elseif ($url !== null) {
115					self::addFavorite([
116						'user_id'   => $ctype === 'user' ? Auth::id() : null,
117						'gedcom_id' => $tree->getTreeId(),
118						'gid'       => null,
119						'type'      => 'URL',
120						'url'       => $url,
121						'note'      => $favnote,
122						'title'     => $favtitle ? $favtitle : $url,
123					]);
124				}
125				break;
126		}
127
128		$userfavs = $this->getFavorites($tree, Auth::user());
129
130		$content = '';
131		if ($userfavs) {
132			foreach ($userfavs as $favorite) {
133				$removeFavourite = '<a class="font9" href="index.php?ctype=' . $ctype . '&amp;ged=' . e($tree->getName()) . '&amp;action=deletefav&amp;favorite_id=' . $favorite->favorite_id . '" data-confirm="' . I18N::translate('Are you sure you want to remove this item from your list of favorites?') . '" onclick="return confirm(this.dataset.confirm);">' . I18N::translate('Remove') . '</a> ';
134				if ($favorite->favorite_type === 'URL') {
135					$content .= '<div id="boxurl' . e($favorite->favorite_id) . '.0" class="person_box">';
136					if ($ctype == 'user' || Auth::isManager($tree)) {
137						$content .= $removeFavourite;
138					}
139					$content .= '<a href="' . e($favorite->url) . '"><b>' . e($favorite->title) . '</b></a>';
140					$content .= '<br>' . e((string) $favorite->note);
141					$content .= '</div>';
142				} else {
143					$record = GedcomRecord::getInstance($favorite->xref, $tree);
144					if ($record && $record->canShow()) {
145						if ($record instanceof Individual) {
146							$content .= '<div id="box' . e($favorite->xref) . '.0" class="person_box action_header';
147							switch ($record->getSex()) {
148								case 'M':
149									break;
150								case 'F':
151									$content .= 'F';
152									break;
153								default:
154									$content .= 'NN';
155									break;
156							}
157							$content .= '">';
158							if ($ctype == 'user' || Auth::isManager($tree)) {
159								$content .= $removeFavourite;
160							}
161							$content .= Theme::theme()->individualBoxLarge($record);
162							$content .= e((string) $favorite->note);
163							$content .= '</div>';
164						} else {
165							$content .= '<div id="box' . e($favorite->xref) . '.0" class="person_box">';
166							if ($ctype == 'user' || Auth::isManager($tree)) {
167								$content .= $removeFavourite;
168							}
169							$content .= $record->formatList();
170							$content .= '<br>' . e((string) $favorite->note);
171							$content .= '</div>';
172						}
173					}
174				}
175			}
176		}
177		if ($ctype == 'user' || Auth::isManager($tree)) {
178			$uniqueID = Uuid::uuid4()->toString(); // This block can theoretically appear multiple times, so use a unique ID.
179			$content .= '<div class="add_fav_head">';
180			$content .= '<a href="#" onclick="return expand_layer(\'add_fav' . $uniqueID . '\');">' . I18N::translate('Add a favorite') . '<i id="add_fav' . $uniqueID . '_img" class="icon-plus"></i></a>';
181			$content .= '</div>';
182			$content .= '<div id="add_fav' . $uniqueID . '" style="display: none;">';
183			$content .= '<form name="addfavform" action="index.php">';
184			$content .= '<input type="hidden" name="action" value="addfav">';
185			$content .= '<input type="hidden" name="ctype" value="' . $ctype . '">';
186			$content .= '<input type="hidden" name="ged" value="' . e($tree->getName()) . '">';
187			$content .= '<div class="add_fav_ref">';
188			$content .= '<input type="radio" name="fav_category" value="record" checked onclick="$(\'#gid' . $uniqueID . '\').removeAttr(\'disabled\'); $(\'#url, #favtitle\').attr(\'disabled\',\'disabled\').val(\'\');">';
189			$content .= '<label for="gid' . $uniqueID . '">' . I18N::translate('Enter an individual, family, or source ID') . '</label>';
190			$content .= '<input class="pedigree_form" data-autocomplete-type="IFSRO" type="text" name="gid" id="gid' . $uniqueID . '" size="5" value="">';
191			$content .= '</div>';
192			$content .= '<div class="add_fav_url">';
193			$content .= '<input type="radio" name="fav_category" value="url" onclick="$(\'#url, #favtitle\').removeAttr(\'disabled\'); $(\'#gid' . $uniqueID . '\').attr(\'disabled\',\'disabled\').val(\'\');">';
194			$content .= '<input type="text" name="url" id="url" size="20" value="" placeholder="' . GedcomTag::getLabel('URL') . '" disabled> ';
195			$content .= '<input type="text" name="favtitle" id="favtitle" size="20" value="" placeholder="' . I18N::translate('Title') . '" disabled>';
196			$content .= '<p>' . I18N::translate('Enter an optional note about this favorite') . '</p>';
197			$content .= '<textarea name="favnote" rows="6" cols="50"></textarea>';
198			$content .= '</div>';
199			$content .= '<input type="submit" value="' . /* I18N: A button label. */ I18N::translate('add') . '">';
200			$content .= '</form></div>';
201		}
202
203		$content = view('blocks/favorites', [
204			'ctype'      => $ctype,
205			'favorites'  => $userfavs,
206			'is_manager' => Auth::isManager($tree),
207			'tree'       => $tree,
208		]);
209
210		if ($template) {
211			return view('blocks/template', [
212				'block'      => str_replace('_', '-', $this->getName()),
213				'id'         => $block_id,
214				'config_url' => '',
215				'title'      => $this->getTitle(),
216				'content'    => $content,
217			]);
218		} else {
219			return $content;
220		}
221	}
222
223	/**
224	 * Should this block load asynchronously using AJAX?
225	 *
226	 * Simple blocks are faster in-line, more comples ones
227	 * can be loaded later.
228	 *
229	 * @return bool
230	 */
231	public function loadAjax(): bool {
232		return false;
233	}
234
235	/**
236	 * Can this block be shown on the user’s home page?
237	 *
238	 * @return bool
239	 */
240	public function isUserBlock(): bool {
241		return false;
242	}
243
244	/**
245	 * Can this block be shown on the tree’s home page?
246	 *
247	 * @return bool
248	 */
249	public function isGedcomBlock(): bool {
250		return true;
251	}
252
253	/**
254	 * An HTML form to edit block settings
255	 *
256	 * @param Tree $tree
257	 * @param int  $block_id
258	 *
259	 * @return void
260	 */
261	public function configureBlock(Tree $tree, int $block_id) {
262	}
263
264	/**
265	 * Delete a favorite from the database
266	 *
267	 * @param int $favorite_id
268	 *
269	 * @return bool
270	 */
271	public static function deleteFavorite($favorite_id) {
272		return (bool)
273			Database::prepare("DELETE FROM `##favorite` WHERE favorite_id=?")
274			->execute([$favorite_id]);
275	}
276
277	/**
278	 * Store a new favorite in the database
279	 *
280	 * @param $favorite
281	 *
282	 * @return bool
283	 */
284	public static function addFavorite($favorite) {
285		// -- make sure a favorite is added
286		if (empty($favorite['gid']) && empty($favorite['url'])) {
287			return false;
288		}
289
290		//-- make sure this is not a duplicate entry
291		$sql = "SELECT 1 FROM `##favorite` WHERE";
292		if (!empty($favorite['gid'])) {
293			$sql .= " xref=?";
294			$vars = [$favorite['gid']];
295		} else {
296			$sql .= " url=?";
297			$vars = [$favorite['url']];
298		}
299		$sql .= " AND gedcom_id=?";
300		$vars[] = $favorite['gedcom_id'];
301		if ($favorite['user_id']) {
302			$sql .= " AND user_id=?";
303			$vars[] = $favorite['user_id'];
304		} else {
305			$sql .= " AND user_id IS NULL";
306		}
307
308		if (Database::prepare($sql)->execute($vars)->fetchOne()) {
309			return false;
310		}
311
312		//-- add the favorite to the database
313		return (bool)
314			Database::prepare("INSERT INTO `##favorite` (user_id, gedcom_id, xref, favorite_type, url, title, note) VALUES (? ,? ,? ,? ,? ,? ,?)")
315				->execute([$favorite['user_id'], $favorite['gedcom_id'], $favorite['gid'], $favorite['type'], $favorite['url'], $favorite['title'], $favorite['note']]);
316	}
317
318	/**
319	 * Get favorites for a user or family tree
320	 *
321	 * @param Tree $tree
322	 * @param User $user
323	 *
324	 * @return stdClass[]
325	 */
326	public static function getFavorites(Tree $tree, User $user) {
327		$favorites =
328			Database::prepare(
329				"SELECT favorite_id, user_id, gedcom_id, xref, favorite_type, title, note, url" .
330				" FROM `##favorite` WHERE gedcom_id = :tree_id AND user_id IS NULL")
331			->execute([
332				'tree_id' => $tree->getTreeId(),
333			])
334			->fetchAll();
335
336		foreach ($favorites as $favorite) {
337			$favorite->record = GedcomRecord::getInstance($favorite->xref, $tree);
338		}
339
340		return $favorites;
341	}
342}
343