xref: /webtrees/app/Module/FamilyTreeFavoritesModule.php (revision 76a5e7c78a07f5736a3cd5b7437c8f18dc196a5e)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2017 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 = []) {
82		global $ctype, $controller, $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		$id    = $this->getName() . $block_id;
131		$class = $this->getName() . '_block';
132		$title = $this->getTitle();
133
134		$content = '';
135		if ($userfavs) {
136			foreach ($userfavs as $key => $favorite) {
137				if (isset($favorite['id'])) {
138					$key = $favorite['id'];
139				}
140				$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> ';
141				if ($favorite['type'] == 'URL') {
142					$content .= '<div id="boxurl' . $key . '.0" class="person_box">';
143					if ($ctype == 'user' || Auth::isManager($WT_TREE)) {
144						$content .= $removeFavourite;
145					}
146					$content .= '<a href="' . $favorite['url'] . '"><b>' . $favorite['title'] . '</b></a>';
147					$content .= '<br>' . $favorite['note'];
148					$content .= '</div>';
149				} else {
150					$record = GedcomRecord::getInstance($favorite['gid'], $WT_TREE);
151					if ($record && $record->canShow()) {
152						if ($record instanceof Individual) {
153							$content .= '<div id="box' . $favorite['gid'] . '.0" class="person_box action_header';
154							switch ($record->getSex()) {
155							case 'M':
156								break;
157							case 'F':
158								$content .= 'F';
159								break;
160							default:
161								$content .= 'NN';
162								break;
163							}
164							$content .= '">';
165							if ($ctype == 'user' || Auth::isManager($WT_TREE)) {
166								$content .= $removeFavourite;
167							}
168							$content .= Theme::theme()->individualBoxLarge($record);
169							$content .= $favorite['note'];
170							$content .= '</div>';
171						} else {
172							$content .= '<div id="box' . $favorite['gid'] . '.0" class="person_box">';
173							if ($ctype == 'user' || Auth::isManager($WT_TREE)) {
174								$content .= $removeFavourite;
175							}
176							$content .= $record->formatList('span');
177							$content .= '<br>' . $favorite['note'];
178							$content .= '</div>';
179						}
180					}
181				}
182			}
183		}
184		if ($ctype == 'user' || Auth::isManager($WT_TREE)) {
185			$uniqueID = Uuid::uuid4(); // This block can theoretically appear multiple times, so use a unique ID.
186			$content .= '<div class="add_fav_head">';
187			$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>';
188			$content .= '</div>';
189			$content .= '<div id="add_fav' . $uniqueID . '" style="display: none;">';
190			$content .= '<form name="addfavform" action="index.php">';
191			$content .= '<input type="hidden" name="action" value="addfav">';
192			$content .= '<input type="hidden" name="ctype" value="' . $ctype . '">';
193			$content .= '<input type="hidden" name="ged" value="' . $WT_TREE->getNameHtml() . '">';
194			$content .= '<div class="add_fav_ref">';
195			$content .= '<input type="radio" name="fav_category" value="record" checked onclick="$(\'#gid' . $uniqueID . '\').removeAttr(\'disabled\'); $(\'#url, #favtitle\').attr(\'disabled\',\'disabled\').val(\'\');">';
196			$content .= '<label for="gid' . $uniqueID . '">' . I18N::translate('Enter an individual, family, or source ID') . '</label>';
197			$content .= '<input class="pedigree_form" data-autocomplete-type="IFSRO" type="text" name="gid" id="gid' . $uniqueID . '" size="5" value="">';
198			$content .= '</div>';
199			$content .= '<div class="add_fav_url">';
200			$content .= '<input type="radio" name="fav_category" value="url" onclick="$(\'#url, #favtitle\').removeAttr(\'disabled\'); $(\'#gid' . $uniqueID . '\').attr(\'disabled\',\'disabled\').val(\'\');">';
201			$content .= '<input type="text" name="url" id="url" size="20" value="" placeholder="' . GedcomTag::getLabel('URL') . '" disabled> ';
202			$content .= '<input type="text" name="favtitle" id="favtitle" size="20" value="" placeholder="' . I18N::translate('Title') . '" disabled>';
203			$content .= '<p>' . I18N::translate('Enter an optional note about this favorite') . '</p>';
204			$content .= '<textarea name="favnote" rows="6" cols="50"></textarea>';
205			$content .= '</div>';
206			$content .= '<input type="submit" value="' . /* I18N: A button label. */ I18N::translate('add') . '">';
207			$content .= '</form></div>';
208		}
209
210		if ($template) {
211			return Theme::theme()->formatBlock($id, $title, $class, $content);
212		} else {
213			return $content;
214		}
215	}
216
217	/**
218	 * Should this block load asynchronously using AJAX?
219	 *
220	 * Simple blocks are faster in-line, more comples ones
221	 * can be loaded later.
222	 *
223	 * @return bool
224	 */
225	public function loadAjax() {
226		return false;
227	}
228
229	/**
230	 * Can this block be shown on the user’s home page?
231	 *
232	 * @return bool
233	 */
234	public function isUserBlock() {
235		return false;
236	}
237
238	/**
239	 * Can this block be shown on the tree’s home page?
240	 *
241	 * @return bool
242	 */
243	public function isGedcomBlock() {
244		return true;
245	}
246
247	/**
248	 * An HTML form to edit block settings
249	 *
250	 * @param int $block_id
251	 */
252	public function configureBlock($block_id) {}
253
254	/**
255	 * Delete a favorite from the database
256	 *
257	 * @param int $favorite_id
258	 *
259	 * @return bool
260	 */
261	public static function deleteFavorite($favorite_id) {
262		return (bool)
263			Database::prepare("DELETE FROM `##favorite` WHERE favorite_id=?")
264			->execute([$favorite_id]);
265	}
266
267	/**
268	 * Store a new favorite in the database
269	 *
270	 * @param $favorite
271	 *
272	 * @return bool
273	 */
274	public static function addFavorite($favorite) {
275		// -- make sure a favorite is added
276		if (empty($favorite['gid']) && empty($favorite['url'])) {
277			return false;
278		}
279
280		//-- make sure this is not a duplicate entry
281		$sql = "SELECT SQL_NO_CACHE 1 FROM `##favorite` WHERE";
282		if (!empty($favorite['gid'])) {
283			$sql .= " xref=?";
284			$vars = [$favorite['gid']];
285		} else {
286			$sql .= " url=?";
287			$vars = [$favorite['url']];
288		}
289		$sql .= " AND gedcom_id=?";
290		$vars[] = $favorite['gedcom_id'];
291		if ($favorite['user_id']) {
292			$sql .= " AND user_id=?";
293			$vars[] = $favorite['user_id'];
294		} else {
295			$sql .= " AND user_id IS NULL";
296		}
297
298		if (Database::prepare($sql)->execute($vars)->fetchOne()) {
299			return false;
300		}
301
302		//-- add the favorite to the database
303		return (bool)
304			Database::prepare("INSERT INTO `##favorite` (user_id, gedcom_id, xref, favorite_type, url, title, note) VALUES (? ,? ,? ,? ,? ,? ,?)")
305				->execute([$favorite['user_id'], $favorite['gedcom_id'], $favorite['gid'], $favorite['type'], $favorite['url'], $favorite['title'], $favorite['note']]);
306	}
307
308	/**
309	 * Get favorites for a user or family tree
310	 *
311	 * @param int $gedcom_id
312	 *
313	 * @return string[][]
314	 */
315	public static function getFavorites($gedcom_id) {
316		return
317			Database::prepare(
318				"SELECT SQL_CACHE favorite_id AS id, user_id, gedcom_id, xref AS gid, favorite_type AS type, title, note, url" .
319				" FROM `##favorite` WHERE gedcom_id=? AND user_id IS NULL")
320			->execute([$gedcom_id])
321			->fetchAll(PDO::FETCH_ASSOC);
322	}
323}
324