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