xref: /webtrees/app/Module/FamilyTreeFavoritesModule.php (revision e5588fb099ce26dcdcb7faeb13861818cd9a4306)
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 PDO;
29use Ramsey\Uuid\Uuid;
30use stdClass;
31
32/**
33 * Class FamilyTreeFavoritesModule
34 *
35 * Note that the user favorites module simply extends this module, so ensure that the
36 * logic works for both.
37 */
38class FamilyTreeFavoritesModule extends AbstractModule implements ModuleBlockInterface {
39	// How to update the database schema for this module
40	const SCHEMA_TARGET_VERSION   = 4;
41	const SCHEMA_SETTING_NAME     = 'FV_SCHEMA_VERSION';
42	const SCHEMA_MIGRATION_PREFIX = '\Fisharebest\Webtrees\Module\FamilyTreeFavorites\Schema';
43
44	/**
45	 * Create a new module.
46	 *
47	 * @param string $directory Where is this module installed
48	 */
49	public function __construct($directory) {
50		parent::__construct($directory);
51
52		// Create/update the database tables.
53		// NOTE: if we want to set any module-settings, we'll need to move this.
54		Database::updateSchema(self::SCHEMA_MIGRATION_PREFIX, self::SCHEMA_SETTING_NAME, self::SCHEMA_TARGET_VERSION);
55	}
56
57	/**
58	 * How should this module be labelled on tabs, menus, etc.?
59	 *
60	 * @return string
61	 */
62	public function getTitle() {
63		return /* I18N: Name of a module */ I18N::translate('Favorites');
64	}
65
66	/**
67	 * A sentence describing what this module does.
68	 *
69	 * @return string
70	 */
71	public function getDescription() {
72		return /* I18N: Description of the “Favorites” module */ I18N::translate('Display and manage a family tree’s favorite pages.');
73	}
74
75	/**
76	 * Generate the HTML content of this block.
77	 *
78	 * @param int      $block_id
79	 * @param bool     $template
80	 * @param string[] $cfg
81	 *
82	 * @return string
83	 */
84	public function getBlock($block_id, $template = true, $cfg = []): string {
85		global $ctype, $WT_TREE;
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, $WT_TREE);
103					if ($record && $record->canShow()) {
104						self::addFavorite([
105							'user_id'   => $ctype === 'user' ? Auth::id() : null,
106							'gedcom_id' => $WT_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' => $WT_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($WT_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($WT_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($WT_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, $WT_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($WT_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($WT_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($WT_TREE)) {
178			$uniqueID = Uuid::uuid4(); // 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($WT_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($WT_TREE),
207			'tree'       => $WT_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 int $block_id
257	 *
258	 * @return void
259	 */
260	public function configureBlock($block_id) {
261	}
262
263	/**
264	 * Delete a favorite from the database
265	 *
266	 * @param int $favorite_id
267	 *
268	 * @return bool
269	 */
270	public static function deleteFavorite($favorite_id) {
271		return (bool)
272			Database::prepare("DELETE FROM `##favorite` WHERE favorite_id=?")
273			->execute([$favorite_id]);
274	}
275
276	/**
277	 * Store a new favorite in the database
278	 *
279	 * @param $favorite
280	 *
281	 * @return bool
282	 */
283	public static function addFavorite($favorite) {
284		// -- make sure a favorite is added
285		if (empty($favorite['gid']) && empty($favorite['url'])) {
286			return false;
287		}
288
289		//-- make sure this is not a duplicate entry
290		$sql = "SELECT 1 FROM `##favorite` WHERE";
291		if (!empty($favorite['gid'])) {
292			$sql .= " xref=?";
293			$vars = [$favorite['gid']];
294		} else {
295			$sql .= " url=?";
296			$vars = [$favorite['url']];
297		}
298		$sql .= " AND gedcom_id=?";
299		$vars[] = $favorite['gedcom_id'];
300		if ($favorite['user_id']) {
301			$sql .= " AND user_id=?";
302			$vars[] = $favorite['user_id'];
303		} else {
304			$sql .= " AND user_id IS NULL";
305		}
306
307		if (Database::prepare($sql)->execute($vars)->fetchOne()) {
308			return false;
309		}
310
311		//-- add the favorite to the database
312		return (bool)
313			Database::prepare("INSERT INTO `##favorite` (user_id, gedcom_id, xref, favorite_type, url, title, note) VALUES (? ,? ,? ,? ,? ,? ,?)")
314				->execute([$favorite['user_id'], $favorite['gedcom_id'], $favorite['gid'], $favorite['type'], $favorite['url'], $favorite['title'], $favorite['note']]);
315	}
316
317	/**
318	 * Get favorites for a user or family tree
319	 *
320	 * @param Tree $tree
321	 * @param User $user
322	 *
323	 * @return stdClass[]
324	 */
325	public static function getFavorites(Tree $tree, User $user) {
326		$favorites =
327			Database::prepare(
328				"SELECT favorite_id, user_id, gedcom_id, xref, favorite_type, title, note, url" .
329				" FROM `##favorite` WHERE gedcom_id = :tree_id AND user_id IS NULL")
330			->execute([
331				'tree_id' => $tree->getTreeId(),
332			])
333			->fetchAll();
334
335		foreach ($favorites as $favorite) {
336			$favorite->record = GedcomRecord::getInstance($favorite->xref, $tree);
337		}
338
339		return $favorites;
340	}
341}
342