xref: /webtrees/app/Module/FamilyTreeFavoritesModule.php (revision 1001c3a8c3f3447dd95f8a9481ce18ff581bd6da)
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 Tree     $tree
79	 * @param int      $block_id
80	 * @param bool     $template
81	 * @param string[] $cfg
82	 *
83	 * @return string
84	 */
85	public function getBlock(Tree $tree, int $block_id, bool $template = true, array $cfg = []): string {
86		global $ctype;
87
88		$action = Filter::get('action');
89		switch ($action) {
90			case 'deletefav':
91				$favorite_id = Filter::getInteger('favorite_id');
92				if ($favorite_id) {
93					self::deleteFavorite($favorite_id);
94				}
95				break;
96			case 'addfav':
97				$gid      = Filter::get('gid', WT_REGEX_XREF, '');
98				$favnote  = Filter::get('favnote');
99				$url      = Filter::getUrl('url');
100				$favtitle = Filter::get('favtitle');
101
102				if ($gid !== '') {
103					$record = GedcomRecord::getInstance($gid, $tree);
104					if ($record && $record->canShow()) {
105						self::addFavorite([
106							'user_id'   => $ctype === 'user' ? Auth::id() : null,
107							'gedcom_id' => $tree->getTreeId(),
108							'gid'       => $record->getXref(),
109							'type'      => $record::RECORD_TYPE,
110							'url'       => null,
111							'note'      => $favnote,
112							'title'     => $favtitle,
113						]);
114					}
115				} elseif ($url !== null) {
116					self::addFavorite([
117						'user_id'   => $ctype === 'user' ? Auth::id() : null,
118						'gedcom_id' => $tree->getTreeId(),
119						'gid'       => null,
120						'type'      => 'URL',
121						'url'       => $url,
122						'note'      => $favnote,
123						'title'     => $favtitle ? $favtitle : $url,
124					]);
125				}
126				break;
127		}
128
129		$userfavs = $this->getFavorites($tree, Auth::user());
130
131		$content = '';
132		if ($userfavs) {
133			foreach ($userfavs as $favorite) {
134				$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> ';
135				if ($favorite->favorite_type === 'URL') {
136					$content .= '<div id="boxurl' . e($favorite->favorite_id) . '.0" class="person_box">';
137					if ($ctype == 'user' || Auth::isManager($tree)) {
138						$content .= $removeFavourite;
139					}
140					$content .= '<a href="' . e($favorite->url) . '"><b>' . e($favorite->title) . '</b></a>';
141					$content .= '<br>' . e((string) $favorite->note);
142					$content .= '</div>';
143				} else {
144					$record = GedcomRecord::getInstance($favorite->xref, $tree);
145					if ($record && $record->canShow()) {
146						if ($record instanceof Individual) {
147							$content .= '<div id="box' . e($favorite->xref) . '.0" class="person_box action_header';
148							switch ($record->getSex()) {
149								case 'M':
150									break;
151								case 'F':
152									$content .= 'F';
153									break;
154								default:
155									$content .= 'NN';
156									break;
157							}
158							$content .= '">';
159							if ($ctype == 'user' || Auth::isManager($tree)) {
160								$content .= $removeFavourite;
161							}
162							$content .= Theme::theme()->individualBoxLarge($record);
163							$content .= e((string) $favorite->note);
164							$content .= '</div>';
165						} else {
166							$content .= '<div id="box' . e($favorite->xref) . '.0" class="person_box">';
167							if ($ctype == 'user' || Auth::isManager($tree)) {
168								$content .= $removeFavourite;
169							}
170							$content .= $record->formatList();
171							$content .= '<br>' . e((string) $favorite->note);
172							$content .= '</div>';
173						}
174					}
175				}
176			}
177		}
178		if ($ctype == 'user' || Auth::isManager($tree)) {
179			$uniqueID = Uuid::uuid4(); // This block can theoretically appear multiple times, so use a unique ID.
180			$content .= '<div class="add_fav_head">';
181			$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>';
182			$content .= '</div>';
183			$content .= '<div id="add_fav' . $uniqueID . '" style="display: none;">';
184			$content .= '<form name="addfavform" action="index.php">';
185			$content .= '<input type="hidden" name="action" value="addfav">';
186			$content .= '<input type="hidden" name="ctype" value="' . $ctype . '">';
187			$content .= '<input type="hidden" name="ged" value="' . e($tree->getName()) . '">';
188			$content .= '<div class="add_fav_ref">';
189			$content .= '<input type="radio" name="fav_category" value="record" checked onclick="$(\'#gid' . $uniqueID . '\').removeAttr(\'disabled\'); $(\'#url, #favtitle\').attr(\'disabled\',\'disabled\').val(\'\');">';
190			$content .= '<label for="gid' . $uniqueID . '">' . I18N::translate('Enter an individual, family, or source ID') . '</label>';
191			$content .= '<input class="pedigree_form" data-autocomplete-type="IFSRO" type="text" name="gid" id="gid' . $uniqueID . '" size="5" value="">';
192			$content .= '</div>';
193			$content .= '<div class="add_fav_url">';
194			$content .= '<input type="radio" name="fav_category" value="url" onclick="$(\'#url, #favtitle\').removeAttr(\'disabled\'); $(\'#gid' . $uniqueID . '\').attr(\'disabled\',\'disabled\').val(\'\');">';
195			$content .= '<input type="text" name="url" id="url" size="20" value="" placeholder="' . GedcomTag::getLabel('URL') . '" disabled> ';
196			$content .= '<input type="text" name="favtitle" id="favtitle" size="20" value="" placeholder="' . I18N::translate('Title') . '" disabled>';
197			$content .= '<p>' . I18N::translate('Enter an optional note about this favorite') . '</p>';
198			$content .= '<textarea name="favnote" rows="6" cols="50"></textarea>';
199			$content .= '</div>';
200			$content .= '<input type="submit" value="' . /* I18N: A button label. */ I18N::translate('add') . '">';
201			$content .= '</form></div>';
202		}
203
204		$content = view('blocks/favorites', [
205			'ctype'      => $ctype,
206			'favorites'  => $userfavs,
207			'is_manager' => Auth::isManager($tree),
208			'tree'       => $tree,
209		]);
210
211		if ($template) {
212			return view('blocks/template', [
213				'block'      => str_replace('_', '-', $this->getName()),
214				'id'         => $block_id,
215				'config_url' => '',
216				'title'      => $this->getTitle(),
217				'content'    => $content,
218			]);
219		} else {
220			return $content;
221		}
222	}
223
224	/**
225	 * Should this block load asynchronously using AJAX?
226	 *
227	 * Simple blocks are faster in-line, more comples ones
228	 * can be loaded later.
229	 *
230	 * @return bool
231	 */
232	public function loadAjax(): bool {
233		return false;
234	}
235
236	/**
237	 * Can this block be shown on the user’s home page?
238	 *
239	 * @return bool
240	 */
241	public function isUserBlock(): bool {
242		return false;
243	}
244
245	/**
246	 * Can this block be shown on the tree’s home page?
247	 *
248	 * @return bool
249	 */
250	public function isGedcomBlock(): bool {
251		return true;
252	}
253
254	/**
255	 * An HTML form to edit block settings
256	 *
257	 * @param Tree $tree
258	 * @param int  $block_id
259	 *
260	 * @return void
261	 */
262	public function configureBlock(Tree $tree, int $block_id) {
263	}
264
265	/**
266	 * Delete a favorite from the database
267	 *
268	 * @param int $favorite_id
269	 *
270	 * @return bool
271	 */
272	public static function deleteFavorite($favorite_id) {
273		return (bool)
274			Database::prepare("DELETE FROM `##favorite` WHERE favorite_id=?")
275			->execute([$favorite_id]);
276	}
277
278	/**
279	 * Store a new favorite in the database
280	 *
281	 * @param $favorite
282	 *
283	 * @return bool
284	 */
285	public static function addFavorite($favorite) {
286		// -- make sure a favorite is added
287		if (empty($favorite['gid']) && empty($favorite['url'])) {
288			return false;
289		}
290
291		//-- make sure this is not a duplicate entry
292		$sql = "SELECT 1 FROM `##favorite` WHERE";
293		if (!empty($favorite['gid'])) {
294			$sql .= " xref=?";
295			$vars = [$favorite['gid']];
296		} else {
297			$sql .= " url=?";
298			$vars = [$favorite['url']];
299		}
300		$sql .= " AND gedcom_id=?";
301		$vars[] = $favorite['gedcom_id'];
302		if ($favorite['user_id']) {
303			$sql .= " AND user_id=?";
304			$vars[] = $favorite['user_id'];
305		} else {
306			$sql .= " AND user_id IS NULL";
307		}
308
309		if (Database::prepare($sql)->execute($vars)->fetchOne()) {
310			return false;
311		}
312
313		//-- add the favorite to the database
314		return (bool)
315			Database::prepare("INSERT INTO `##favorite` (user_id, gedcom_id, xref, favorite_type, url, title, note) VALUES (? ,? ,? ,? ,? ,? ,?)")
316				->execute([$favorite['user_id'], $favorite['gedcom_id'], $favorite['gid'], $favorite['type'], $favorite['url'], $favorite['title'], $favorite['note']]);
317	}
318
319	/**
320	 * Get favorites for a user or family tree
321	 *
322	 * @param Tree $tree
323	 * @param User $user
324	 *
325	 * @return stdClass[]
326	 */
327	public static function getFavorites(Tree $tree, User $user) {
328		$favorites =
329			Database::prepare(
330				"SELECT favorite_id, user_id, gedcom_id, xref, favorite_type, title, note, url" .
331				" FROM `##favorite` WHERE gedcom_id = :tree_id AND user_id IS NULL")
332			->execute([
333				'tree_id' => $tree->getTreeId(),
334			])
335			->fetchAll();
336
337		foreach ($favorites as $favorite) {
338			$favorite->record = GedcomRecord::getInstance($favorite->xref, $tree);
339		}
340
341		return $favorites;
342	}
343}
344