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