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