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