xref: /webtrees/app/Module/PedigreeChartModule.php (revision 3340ecd27b8901a894bff51b7c40bfa2896a552b)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Aura\Router\RouterContainer;
23use Fig\Http\Message\RequestMethodInterface;
24use Fisharebest\Webtrees\Auth;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Individual;
27use Fisharebest\Webtrees\Menu;
28use Fisharebest\Webtrees\Registry;
29use Fisharebest\Webtrees\Services\ChartService;
30use Fisharebest\Webtrees\Tree;
31use Psr\Http\Message\ResponseInterface;
32use Psr\Http\Message\ServerRequestInterface;
33use Psr\Http\Server\RequestHandlerInterface;
34
35use function app;
36use function assert;
37use function is_string;
38use function max;
39use function min;
40use function route;
41use function view;
42
43/**
44 * Class PedigreeChartModule
45 */
46class PedigreeChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
47{
48    use ModuleChartTrait;
49
50    protected const ROUTE_URL = '/tree/{tree}/pedigree-{style}-{generations}/{xref}';
51
52    // Chart styles
53    public const STYLE_LEFT  = 'left';
54    public const STYLE_RIGHT = 'right';
55    public const STYLE_UP    = 'up';
56    public const STYLE_DOWN  = 'down';
57
58    // Defaults
59    protected const DEFAULT_GENERATIONS = '4';
60    protected const DEFAULT_STYLE       = self::STYLE_RIGHT;
61    protected const DEFAULT_PARAMETERS  = [
62        'generations' => self::DEFAULT_GENERATIONS,
63        'style'       => self::DEFAULT_STYLE,
64    ];
65
66    // Limits
67    protected const MINIMUM_GENERATIONS = 2;
68    protected const MAXIMUM_GENERATIONS = 12;
69
70    // For RTL languages
71    protected const MIRROR_STYLE = [
72        self::STYLE_UP    => self::STYLE_DOWN,
73        self::STYLE_DOWN  => self::STYLE_UP,
74        self::STYLE_LEFT  => self::STYLE_RIGHT,
75        self::STYLE_RIGHT => self::STYLE_LEFT,
76    ];
77
78    private ChartService $chart_service;
79
80    /**
81     * PedigreeChartModule constructor.
82     *
83     * @param ChartService $chart_service
84     */
85    public function __construct(ChartService $chart_service)
86    {
87        $this->chart_service = $chart_service;
88    }
89
90    /**
91     * Initialization.
92     *
93     * @return void
94     */
95    public function boot(): void
96    {
97        $router_container = app(RouterContainer::class);
98        assert($router_container instanceof RouterContainer);
99
100        $router_container->getMap()
101            ->get(static::class, static::ROUTE_URL, $this)
102            ->allows(RequestMethodInterface::METHOD_POST)
103            ->tokens([
104                'generations' => '\d+',
105                'style'       => implode('|', array_keys($this->styles('ltr'))),
106            ]);
107    }
108
109    /**
110     * How should this module be identified in the control panel, etc.?
111     *
112     * @return string
113     */
114    public function title(): string
115    {
116        /* I18N: Name of a module/chart */
117        return I18N::translate('Pedigree');
118    }
119
120    /**
121     * A sentence describing what this module does.
122     *
123     * @return string
124     */
125    public function description(): string
126    {
127        /* I18N: Description of the “PedigreeChart” module */
128        return I18N::translate('A chart of an individual’s ancestors, formatted as a tree.');
129    }
130
131    /**
132     * CSS class for the URL.
133     *
134     * @return string
135     */
136    public function chartMenuClass(): string
137    {
138        return 'menu-chart-pedigree';
139    }
140
141    /**
142     * Return a menu item for this chart - for use in individual boxes.
143     *
144     * @param Individual $individual
145     *
146     * @return Menu|null
147     */
148    public function chartBoxMenu(Individual $individual): ?Menu
149    {
150        return $this->chartMenu($individual);
151    }
152
153    /**
154     * The title for a specific instance of this chart.
155     *
156     * @param Individual $individual
157     *
158     * @return string
159     */
160    public function chartTitle(Individual $individual): string
161    {
162        /* I18N: %s is an individual’s name */
163        return I18N::translate('Pedigree tree of %s', $individual->fullName());
164    }
165
166    /**
167     * The URL for a page showing chart options.
168     *
169     * @param Individual                        $individual
170     * @param array<bool|int|string|array|null> $parameters
171     *
172     * @return string
173     */
174    public function chartUrl(Individual $individual, array $parameters = []): string
175    {
176        return route(static::class, [
177                'xref' => $individual->xref(),
178                'tree' => $individual->tree()->name(),
179            ] + $parameters + static::DEFAULT_PARAMETERS);
180    }
181
182    /**
183     * @param ServerRequestInterface $request
184     *
185     * @return ResponseInterface
186     */
187    public function handle(ServerRequestInterface $request): ResponseInterface
188    {
189        $tree = $request->getAttribute('tree');
190        assert($tree instanceof Tree);
191
192        $xref = $request->getAttribute('xref');
193        assert(is_string($xref));
194
195        $individual = Registry::individualFactory()->make($xref, $tree);
196        $individual = Auth::checkIndividualAccess($individual, false, true);
197
198        $ajax        = $request->getQueryParams()['ajax'] ?? '';
199        $generations = (int) $request->getAttribute('generations');
200        $style       = $request->getAttribute('style');
201        $user        = $request->getAttribute('user');
202
203        // Convert POST requests into GET requests for pretty URLs.
204        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
205            $params = (array) $request->getParsedBody();
206
207            return redirect(route(self::class, [
208                'tree'        => $request->getAttribute('tree')->name(),
209                'xref'        => $params['xref'],
210                'style'       => $params['style'],
211                'generations' => $params['generations'],
212            ]));
213        }
214
215        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
216
217        $generations = min($generations, self::MAXIMUM_GENERATIONS);
218        $generations = max($generations, self::MINIMUM_GENERATIONS);
219
220        if ($ajax === '1') {
221            $this->layout = 'layouts/ajax';
222
223            $ancestors = $this->chart_service->sosaStradonitzAncestors($individual, $generations);
224
225            // Father’s ancestors link to the father’s pedigree
226            // Mother’s ancestors link to the mother’s pedigree..
227            $links = $ancestors->map(function (?Individual $individual, $sosa) use ($ancestors, $style, $generations): string {
228                if ($individual instanceof Individual && $sosa >= 2 ** $generations / 2 && $individual->childFamilies()->isNotEmpty()) {
229                    // The last row/column, and there are more generations.
230                    if ($sosa >= 2 ** $generations * 3 / 4) {
231                        return $this->nextLink($ancestors->get(3), $style, $generations);
232                    }
233
234                    return $this->nextLink($ancestors->get(2), $style, $generations);
235                }
236
237                // A spacer to fix the "Left" layout.
238                return '<span class="invisible px-2">' . view('icons/arrow-' . $style) . '</span>';
239            });
240
241            // Root individual links to their children.
242            $links->put(1, $this->previousLink($individual, $style, $generations));
243
244            return $this->viewResponse('modules/pedigree-chart/chart', [
245                'ancestors'   => $ancestors,
246                'generations' => $generations,
247                'style'       => $style,
248                'layout'      => 'right',
249                'links'       => $links,
250                'spacer'      => $this->spacer(),
251            ]);
252        }
253
254        $ajax_url = $this->chartUrl($individual, [
255            'ajax'        => true,
256            'generations' => $generations,
257            'style'       => $style,
258            'xref'        => $xref,
259        ]);
260
261        return $this->viewResponse('modules/pedigree-chart/page', [
262            'ajax_url'           => $ajax_url,
263            'generations'        => $generations,
264            'individual'         => $individual,
265            'module'             => $this->name(),
266            'max_generations'    => self::MAXIMUM_GENERATIONS,
267            'min_generations'    => self::MINIMUM_GENERATIONS,
268            'style'              => $style,
269            'styles'             => $this->styles(I18N::direction()),
270            'title'              => $this->chartTitle($individual),
271            'tree'               => $tree,
272        ]);
273    }
274
275    /**
276     * A link-sized spacer, to maintain the chart layout
277     *
278     * @return string
279     */
280    public function spacer(): string
281    {
282        return '<span class="px-2">' . view('icons/spacer') . '</span>';
283    }
284
285    /**
286     * Build a menu for the chart root individual
287     *
288     * @param Individual $individual
289     * @param string     $style
290     * @param int        $generations
291     *
292     * @return string
293     */
294    public function nextLink(Individual $individual, string $style, int $generations): string
295    {
296        $icon  = view('icons/arrow-' . $style);
297        $title = $this->chartTitle($individual);
298        $url   = $this->chartUrl($individual, [
299            'style'       => $style,
300            'generations' => $generations,
301        ]);
302
303        return '<a class="px-2" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $icon . '<span class="visually-hidden">' . $title . '</span></a>';
304    }
305
306    /**
307     * Build a menu for the chart root individual
308     *
309     * @param Individual $individual
310     * @param string     $style
311     * @param int        $generations
312     *
313     * @return string
314     */
315    public function previousLink(Individual $individual, string $style, int $generations): string
316    {
317        $icon = view('icons/arrow-' . self::MIRROR_STYLE[$style]);
318
319        $siblings = [];
320        $spouses  = [];
321        $children = [];
322
323        foreach ($individual->childFamilies() as $family) {
324            foreach ($family->children() as $child) {
325                if ($child !== $individual) {
326                    $siblings[] = $this->individualLink($child, $style, $generations);
327                }
328            }
329        }
330
331        foreach ($individual->spouseFamilies() as $family) {
332            foreach ($family->spouses() as $spouse) {
333                if ($spouse !== $individual) {
334                    $spouses[] = $this->individualLink($spouse, $style, $generations);
335                }
336            }
337
338            foreach ($family->children() as $child) {
339                $children[] = $this->individualLink($child, $style, $generations);
340            }
341        }
342
343        return view('modules/pedigree-chart/previous', [
344            'icon'        => $icon,
345            'individual'  => $individual,
346            'generations' => $generations,
347            'style'       => $style,
348            'chart'       => $this,
349            'siblings'    => $siblings,
350            'spouses'     => $spouses,
351            'children'    => $children,
352        ]);
353    }
354
355    /**
356     * @param Individual $individual
357     * @param string     $style
358     * @param int        $generations
359     *
360     * @return string
361     */
362    protected function individualLink(Individual $individual, string $style, int $generations): string
363    {
364        $text  = $individual->fullName();
365        $title = $this->chartTitle($individual);
366        $url   = $this->chartUrl($individual, [
367            'style'       => $style,
368            'generations' => $generations,
369        ]);
370
371        return '<a class="dropdown-item" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $text . '</a>';
372    }
373
374    /**
375     * This chart can display its output in a number of styles
376     *
377     * @param string $direction
378     *
379     * @return array<string>
380     */
381    protected function styles(string $direction): array
382    {
383        // On right-to-left pages, the CSS will mirror the chart, so we need to mirror the label.
384        if ($direction === 'rtl') {
385            return [
386                self::STYLE_RIGHT => view('icons/pedigree-left') . I18N::translate('left'),
387                self::STYLE_LEFT  => view('icons/pedigree-right') . I18N::translate('right'),
388                self::STYLE_UP    => view('icons/pedigree-up') . I18N::translate('up'),
389                self::STYLE_DOWN  => view('icons/pedigree-down') . I18N::translate('down'),
390            ];
391        }
392
393        return [
394            self::STYLE_LEFT  => view('icons/pedigree-left') . I18N::translate('left'),
395            self::STYLE_RIGHT => view('icons/pedigree-right') . I18N::translate('right'),
396            self::STYLE_UP    => view('icons/pedigree-up') . I18N::translate('up'),
397            self::STYLE_DOWN  => view('icons/pedigree-down') . I18N::translate('down'),
398        ];
399    }
400}
401