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