xref: /webtrees/app/Module/InteractiveTree/TreeView.php (revision 1de810172b2fe9b7cd434f952ee021def759befe)
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 (!empty($pfamily)) {
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        $fop = []; // $fop is fathers of partners
265        if ($partner !== null) {
266            $dashed = '';
267            foreach ($person->getSpouseFamilies() as $family) {
268                $spouse = $family->getSpouse($person);
269                if ($spouse instanceof Individual) {
270                    $spouse_parents = $spouse->getPrimaryChildFamily();
271                    if ($spouse_parents instanceof Family) {
272                        // Prefer the paternal line
273                        $parent = $spouse_parents->getHusband() ?? $spouse_parents->getWife();
274
275                        // The family may have no parents (just children).
276                        if ($parent instanceof Individual) {
277                            $fop[] = [
278                                $parent,
279                                $spouse_parents,
280                            ];
281                        }
282                        $html .= $this->drawPersonName($spouse, $dashed);
283                        $dashed = 'dashed';
284                    }
285                }
286            }
287        }
288        $html .= '</div></td>';
289
290        $primaryChildFamily = $person->getPrimaryChildFamily();
291
292        if ($primaryChildFamily instanceof Family) {
293            // Prefer the paternal line
294            $parent = $primaryChildFamily->getHusband() ?? $primaryChildFamily->getWife();
295        } else {
296            $parent = null;
297        }
298
299        // The family may have no parents (just children).
300        if ($parent instanceof Individual || !empty($fop) || $state < 0) {
301            $html .= $this->drawHorizontalLine();
302        }
303
304        /* draw the parents */
305        if ($primaryChildFamily instanceof Family && $state >= 0 && ($parent instanceof Individual || !empty($fop))) {
306            $unique = $parent === null || empty($fop);
307            $html .= '<td align="left"><table class="tv_tree"><tbody>';
308
309            if (!empty($parent)) {
310                $u = $unique ? 'c' : 't';
311                $html .= '<tr><td ' . ($gen == 0 ? ' abbr="p' . $primaryChildFamily->getXref() . '@' . $u . '"' : '') . '>';
312                $html .= $this->drawPerson($parent, $gen - 1, 1, $primaryChildFamily, $u, false);
313                $html .= '</td></tr>';
314            }
315
316            if (count($fop)) {
317                $n  = 0;
318                $nb = count($fop);
319                foreach ($fop as $p) {
320                    $n++;
321                    $u = $unique ? 'c' : ($n == $nb || empty($p[1]) ? 'b' : 'h');
322                    $html .= '<tr><td ' . ($gen == 0 ? ' abbr="p' . $p[1]->getXref() . '@' . $u . '"' : '') . '>' . $this->drawPerson($p[0], $gen - 1, 1, $p[1], $u, false) . '</td></tr>';
323                }
324            }
325            $html .= '</tbody></table></td>';
326        }
327
328        if ($state < 0) {
329            $html .= $this->drawVerticalLine($line);
330        }
331
332        $html .= '</tr></tbody></table>';
333
334        if ($isRoot) {
335            $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>';
336        }
337
338        return $html;
339    }
340
341    /**
342     * Draw a person name preceded by sex icon, with parents as tooltip
343     *
344     * @param Individual $individual The individual to draw
345     * @param string     $dashed     Either "dashed", to print dashed top border to separate multiple spouses, or ""
346     *
347     * @return string
348     */
349    private function drawPersonName(Individual $individual, string $dashed): string
350    {
351        $family = $individual->getPrimaryChildFamily();
352        if ($family) {
353            $family_name = strip_tags($family->getFullName());
354        } else {
355            $family_name = I18N::translateContext('unknown family', 'unknown');
356        }
357        switch ($individual->getSex()) {
358            case 'M':
359                /* I18N: e.g. “Son of [father name & mother name]” */
360                $title = ' title="' . I18N::translate('Son of %s', $family_name) . '"';
361                break;
362            case 'F':
363                /* I18N: e.g. “Daughter of [father name & mother name]” */
364                $title = ' title="' . I18N::translate('Daughter of %s', $family_name) . '"';
365                break;
366            default:
367                /* I18N: e.g. “Child of [father name & mother name]” */
368                $title = ' title="' . I18N::translate('Child of %s', $family_name) . '"';
369                break;
370        }
371        $sex = $individual->getSex();
372
373        return '<div class="tv' . $sex . ' ' . $dashed . '"' . $title . '><a href="' . e($individual->url()) . '"></a>' . $individual->getFullName() . ' <span class="dates">' . $individual->getLifeSpan() . '</span></div>';
374    }
375
376    /**
377     * Get the thumbnail image for the given person
378     *
379     * @param Individual $individual
380     *
381     * @return string
382     */
383    private function getThumbnail(Individual $individual): string
384    {
385        if ($individual->getTree()->getPreference('SHOW_HIGHLIGHT_IMAGES')) {
386            return $individual->displayImage(40, 50, 'crop', []);
387        }
388
389        return '';
390    }
391
392    /**
393     * Draw a vertical line
394     *
395     * @param string $line A parameter that set how to draw this line with auto-redimensionning capabilities
396     *
397     * @return string
398     * WARNING : some tricky hacks are required in CSS to ensure cross-browser compliance
399     * some browsers shows an image, which imply a size limit in height,
400     * and some other browsers (ex: firefox) shows a <div> tag, which have no size limit in height
401     * Therefore, Firefox is a good choice to print very big trees.
402     */
403    private function drawVerticalLine(string $line): string
404    {
405        return '<td class="tv_vline tv_vline_' . $line . '"><div class="tv_vline tv_vline_' . $line . '"></div></td>';
406    }
407
408    /**
409     * Draw an horizontal line
410     */
411    private function drawHorizontalLine(): string
412    {
413        return '<td class="tv_hline"><div class="tv_hline"></div></td>';
414    }
415}
416