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