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