xref: /webtrees/app/Module/InteractiveTree/TreeView.php (revision 13abd6f3a37322f885d85df150e105d27ad81f8d)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2016 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\InteractiveTree;
17
18use Fisharebest\Webtrees\Family;
19use Fisharebest\Webtrees\Filter;
20use Fisharebest\Webtrees\I18N;
21use Fisharebest\Webtrees\Individual;
22
23/**
24 * Class TreeView
25 */
26class TreeView {
27	/** @var string HTML element name */
28	private $name;
29
30	/** @var string Show all partners */
31	private $all_partners;
32
33	/**
34	 * Treeview Constructor
35	 *
36	 * @param string $name the name of the TreeView object’s instance
37	 */
38	public function __construct($name = 'tree') {
39		$this->name         = $name;
40		$this->all_partners = Filter::cookie('allPartners', 'true|false', 'true');
41	}
42
43	/**
44	 * Draw the viewport which creates the draggable/zoomable framework
45	 * Size is set by the container, as the viewport can scale itself automatically
46	 *
47	 * @param Individual $root_person  the id of the root person
48	 * @param int        $generations number of generations to draw
49	 *
50	 * @return string[]  HTML and Javascript
51	 */
52	public function drawViewport(Individual $root_person, $generations) {
53		$html = '
54			<a name="tv_content"></a>
55			<div id="' . $this->name . '_out" class="tv_out">
56				<div id="tv_tools" class="noprint">
57					<ul>
58						<li id="tvbCompact" class="tv_button">
59							<img src="' . WT_STATIC_URL . WT_MODULES_DIR . 'tree/images/compact.png" alt="' . I18N::translate('Use compact layout') . '" title="' . I18N::translate('Use compact layout') . '">
60						</li>
61						<li id="tvbAllPartners" class="tv_button' . ($this->all_partners === 'true' ? ' tvPressed' : '') . '">
62							<a class="icon-sfamily" href="#" title="' . I18N::translate('Show all spouses and ancestors') . '"></a>
63						</li>
64						<li class="tv_button" id="' . $this->name . '_loading">
65							<i class="icon-loading-small"></i>
66						</li>
67					</ul>
68				</div>
69				<h2 id="tree-title">' . I18N::translate('Interactive tree of %s', $root_person->getFullName()) . '</h2>
70				<div id="' . $this->name . '_in" class="tv_in" dir="ltr">
71					' . $this->drawPerson($root_person, $generations, 0, null, null, true) . '
72				</div>
73			</div>
74		';
75
76		return [$html, 'var ' . $this->name . 'Handler = new TreeViewHandler("' . $this->name . '");'];
77	}
78
79	/**
80	 * Return a JSON structure to a JSON request
81	 *
82	 * @param string $list list of JSON requests
83	 *
84	 * @return string
85	 */
86	public function getPersons($list) {
87		global $WT_TREE;
88
89		$list = explode(';', $list);
90		$r    = [];
91		foreach ($list as $jsonRequest) {
92			$firstLetter = substr($jsonRequest, 0, 1);
93			$jsonRequest = substr($jsonRequest, 1);
94			switch ($firstLetter) {
95			case 'c':
96				$fidlist = explode(',', $jsonRequest);
97				$flist   = [];
98				foreach ($fidlist as $fid) {
99					$flist[] = Family::getInstance($fid, $WT_TREE);
100				}
101				$r[] = $this->drawChildren($flist, 1, true);
102				break;
103			case 'p':
104				$params = explode('@', $jsonRequest);
105				$fid    = $params[0];
106				$order  = $params[1];
107				$f      = Family::getInstance($fid, $WT_TREE);
108				if ($f->getHusband()) {
109					$r[] = $this->drawPerson($f->getHusband(), 0, 1, $f, $order);
110				} elseif ($f->getWife()) {
111					$r[] = $this->drawPerson($f->getWife(), 0, 1, $f, $order);
112				}
113				break;
114			}
115		}
116
117		return json_encode($r);
118	}
119
120	/**
121	 * Get the details for a person and their life partner(s)
122	 *
123	 * @param Individual $individual the individual to return the details for
124	 *
125	 * @return string
126	 */
127	public function getDetails(Individual $individual) {
128		$html = $this->getPersonDetails($individual, null);
129		foreach ($individual->getSpouseFamilies() as $family) {
130			$spouse = $family->getSpouse($individual);
131			if ($spouse) {
132				$html .= $this->getPersonDetails($spouse, $family);
133			}
134		}
135
136		return $html;
137	}
138
139	/**
140	 * Return the details for a person
141	 *
142	 * @param Individual $individual
143	 * @param Family     $family
144	 *
145	 * @return string
146	 */
147	private function getPersonDetails(Individual $individual, Family $family = null) {
148		$hmtl = $this->getThumbnail($individual);
149		$hmtl .= '<a class="tv_link" href="' . $individual->getHtmlUrl() . '">' . $individual->getFullName() . '</a> <a href="module.php?mod=tree&amp;mod_action=treeview&amp;rootid=' . $individual->getXref() . '" title="' . I18N::translate('Interactive tree of %s', strip_tags($individual->getFullName())) . '" class="icon-button_indi tv_link tv_treelink"></a>';
150		foreach ($individual->getFacts(WT_EVENTS_BIRT, true) as $fact) {
151			$hmtl .= $fact->summary();
152		}
153		if ($family) {
154			foreach ($family->getFacts(WT_EVENTS_MARR, true) as $fact) {
155				$hmtl .= $fact->summary();
156			}
157		}
158		foreach ($individual->getFacts(WT_EVENTS_DEAT, true) as $fact) {
159			$hmtl .= $fact->summary();
160		}
161
162		return '<div class="tv' . $individual->getSex() . ' tv_person_expanded">' . $hmtl . '</div>';
163	}
164
165	/**
166	 * Draw the children for some families
167	 *
168	 * @param Family[] $familyList array of families to draw the children for
169	 * @param int      $gen        number of generations to draw
170	 * @param bool     $ajax       setted to true for an ajax call
171	 *
172	 * @return string
173	 */
174	private function drawChildren(array $familyList, $gen = 1, $ajax = false) {
175		$html          = '';
176		$children2draw = [];
177		$f2load        = [];
178
179		foreach ($familyList as $f) {
180			if (empty($f)) {
181				continue;
182			}
183			$children = $f->getChildren();
184			if ($children) {
185				$f2load[] = $f->getXref();
186				foreach ($children as $child) {
187					// Eliminate duplicates - e.g. when adopted by a step-parent
188					$children2draw[$child->getXref()] = $child;
189				}
190			}
191		}
192		$tc = count($children2draw);
193		if ($tc) {
194			$f2load = implode(',', $f2load);
195			$nbc    = 0;
196			foreach ($children2draw as $child) {
197				$nbc++;
198				if ($tc == 1) {
199					$co = 'c'; // unique
200				} elseif ($nbc == 1) {
201					$co = 't'; // first
202				} elseif ($nbc == $tc) {
203					$co = 'b'; //last
204				} else {
205					$co = 'h';
206				}
207				$html .= $this->drawPerson($child, $gen - 1, -1, null, $co);
208			}
209			if (!$ajax) {
210				$html = '<td align="right"' . ($gen == 0 ? ' abbr="c' . $f2load . '"' : '') . '>' . $html . '</td>' . $this->drawHorizontalLine();
211			}
212		}
213
214		return $html;
215	}
216
217	/**
218	 * Draw a person in the tree
219	 *
220	 * @param Individual $person The Person object to draw the box for
221	 * @param int        $gen    The number of generations up or down to print
222	 * @param int        $state  Whether we are going up or down the tree, -1 for descendents +1 for ancestors
223	 * @param Family     $pfamily
224	 * @param string     $order  first (1), last(2), unique(0), or empty. Required for drawing lines between boxes
225	 * @param bool       $isRoot
226	 *
227	 * @return string
228	 *
229	 * Notes : "spouse" means explicitely married partners. Thus, the word "partner"
230	 * (for "life partner") here fits much better than "spouse" or "mate"
231	 * to translate properly the modern french meaning of "conjoint"
232	 */
233	private function drawPerson(Individual $person, $gen, $state, Family $pfamily = null, $order = null, $isRoot = false) {
234		if ($gen < 0) {
235			return '';
236		}
237		if (!empty($pfamily)) {
238			$partner = $pfamily->getSpouse($person);
239		} else {
240			$partner = $person->getCurrentSpouse();
241		}
242		if ($isRoot) {
243			$html = '<table id="tvTreeBorder" class="tv_tree"><tbody><tr><td id="tv_tree_topleft"></td><td id="tv_tree_top"></td><td id="tv_tree_topright"></td></tr><tr><td id="tv_tree_left"></td><td>';
244		} else {
245			$html = '';
246		}
247		/* height 1% : this hack enable the div auto-dimensioning in td for FF & Chrome */
248		$html .= '<table class="tv_tree"' . ($isRoot ? ' id="tv_tree"' : '') . ' style="height: 1%"><tbody><tr>';
249
250		if ($state <= 0) {
251			// draw children
252			$html .= $this->drawChildren($person->getSpouseFamilies(), $gen);
253		} else {
254			// draw the parent’s lines
255			$html .= $this->drawVerticalLine($order) . $this->drawHorizontalLine();
256		}
257
258		/* draw the person. Do NOT add person or family id as an id, since a same person could appear more than once in the tree !!! */
259		// Fixing the width for td to the box initial width when the person is the root person fix a rare bug that happen when a person without child and without known parents is the root person : an unwanted white rectangle appear at the right of the person’s boxes, otherwise.
260		$html .= '<td' . ($isRoot ? ' style="width:1px"' : '') . '><div class="tv_box' . ($isRoot ? ' rootPerson' : '') . '" dir="' . I18N::direction() . '" style="text-align: ' . (I18N::direction() === 'rtl' ? 'right' : 'left') . '; direction: ' . I18N::direction() . '" abbr="' . $person->getXref() . '" onclick="' . $this->name . 'Handler.expandBox(this, event);">';
261		$html .= $this->drawPersonName($person);
262		$fop = []; // $fop is fathers of partners
263		if (!is_null($partner)) {
264			$dashed = '';
265			foreach ($person->getSpouseFamilies() as $family) {
266				$spouse = $family->getSpouse($person);
267				if ($spouse) {
268					if ($spouse === $partner || $this->all_partners === 'true') {
269						$spouse_parents = $spouse->getPrimaryChildFamily();
270						if ($spouse_parents && $spouse_parents->getHusband()) {
271							$fop[] = [$spouse_parents->getHusband(), $spouse_parents];
272						} elseif ($spouse_parents && $spouse_parents->getWife()) {
273							$fop[] = [$spouse_parents->getWife(), $spouse_parents];
274						}
275						$html .= $this->drawPersonName($spouse, $dashed);
276						if ($this->all_partners !== 'true') {
277							break; // we can stop here the foreach loop
278						}
279						$dashed = 'dashed';
280					}
281				}
282			}
283		}
284		$html .= '</div></td>';
285
286		$primaryChildFamily = $person->getPrimaryChildFamily();
287		if (!empty($primaryChildFamily)) {
288			$parent = $primaryChildFamily->getHusband();
289			if (empty($parent)) {
290				$parent = $primaryChildFamily->getWife();
291			}
292		}
293		if (!empty($parent) || count($fop) || ($state < 0)) {
294			$html .= $this->drawHorizontalLine();
295		}
296		/* draw the parents */
297		if ($state >= 0 && (!empty($parent) || count($fop))) {
298			$unique = (empty($parent) || count($fop) == 0);
299			$html .= '<td align="left"><table class="tv_tree"><tbody>';
300			if (!empty($parent)) {
301				$u = $unique ? 'c' : 't';
302				$html .= '<tr><td ' . ($gen == 0 ? ' abbr="p' . $primaryChildFamily->getXref() . '@' . $u . '"' : '') . '>';
303				$html .= $this->drawPerson($parent, $gen - 1, 1, $primaryChildFamily, $u);
304				$html .= '</td></tr>';
305			}
306			if (count($fop)) {
307				$n  = 0;
308				$nb = count($fop);
309				foreach ($fop as $p) {
310					$n++;
311					$u = $unique ? 'c' : ($n == $nb || empty($p[1]) ? 'b' : 'h');
312					$html .= '<tr><td ' . ($gen == 0 ? ' abbr="p' . $p[1]->getXref() . '@' . $u . '"' : '') . '>' . $this->drawPerson($p[0], $gen - 1, 1, $p[1], $u) . '</td></tr>';
313				}
314			}
315			$html .= '</tbody></table></td>';
316		}
317		if ($state < 0) {
318			$html .= $this->drawVerticalLine($order);
319		}
320		$html .= '</tr></tbody></table>';
321		if ($isRoot) {
322			$html .= '</td><td id="tv_tree_right"></td></tr><tr><td id="tv_tree_bottomleft"></td><td id="tv_tree_bottom"></td><td id="tv_tree_bottomright"></td></tr></tbody></table>';
323		}
324
325		return $html;
326	}
327
328	/**
329	 * Draw a person name preceded by sex icon, with parents as tooltip
330	 *
331	 * @param Individual $individual an individual
332	 * @param string        $dashed     if = 'dashed' print dashed top border to separate multiple spuses
333	 *
334	 * @return string
335	 */
336	private function drawPersonName(Individual $individual, $dashed = '') {
337		if ($this->all_partners === 'true') {
338			$family = $individual->getPrimaryChildFamily();
339			if ($family) {
340				$family_name = strip_tags($family->getFullName());
341			} else {
342				$family_name = I18N::translateContext('unknown family', 'unknown');
343			}
344			switch ($individual->getSex()) {
345			case 'M':
346				$title = ' title="' . /* I18N: e.g. “Son of [father name & mother name]” */ I18N::translate('Son of %s', $family_name) . '"';
347				break;
348			case 'F':
349				$title = ' title="' . /* I18N: e.g. “Daughter of [father name & mother name]” */ I18N::translate('Daughter of %s', $family_name) . '"';
350				break;
351			default:
352				$title = ' title="' . /* I18N: e.g. “Child of [father name & mother name]” */ I18N::translate('Child of %s', $family_name) . '"';
353				break;
354			}
355		} else {
356			$title = '';
357		}
358		$sex = $individual->getSex();
359
360		return '<div class="tv' . $sex . ' ' . $dashed . '"' . $title . '><a href="' . $individual->getHtmlUrl() . '"></a>' . $individual->getFullName() . ' <span class="dates">' . $individual->getLifeSpan() . '</span></div>';
361	}
362
363	/**
364	 * Get the thumbnail image for the given person
365	 *
366	 * @param Individual $individual
367	 *
368	 * @return string
369	 */
370	private function getThumbnail(Individual $individual) {
371		if ($individual->getTree()->getPreference('SHOW_HIGHLIGHT_IMAGES')) {
372			return $individual->displayImage();
373		} else {
374			return '';
375		}
376	}
377
378	/**
379	 * Draw a vertical line
380	 *
381	 * @param string $order A parameter that set how to draw this line with auto-redimensionning capabilities
382	 *
383	 * @return string
384	 * WARNING : some tricky hacks are required in CSS to ensure cross-browser compliance
385	 * some browsers shows an image, which imply a size limit in height,
386	 * and some other browsers (ex: firefox) shows a <div> tag, which have no size limit in height
387	 * Therefore, Firefox is a good choice to print very big trees.
388	 */
389	private function drawVerticalLine($order) {
390		return '<td class="tv_vline tv_vline_' . $order . '"><div class="tv_vline tv_vline_' . $order . '"></div></td>';
391	}
392
393	/**
394	 * Draw an horizontal line
395	 */
396	private function drawHorizontalLine() {
397		return '<td class="tv_hline"><div class="tv_hline"></div></td>';
398	}
399}
400