xref: /webtrees/app/Module/PedigreeChartModule.php (revision 66c7498f9d559689b159190509749c1997dc5403)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://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\Functions\FunctionsEdit;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Individual;
28use Fisharebest\Webtrees\Menu;
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 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    private const ROUTE_NAME = 'pedigree-chart';
50    private 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    /** @var ChartService */
79    private $chart_service;
80
81    /**
82     * PedigreeChartModule constructor.
83     *
84     * @param ChartService $chart_service
85     */
86    public function __construct(ChartService $chart_service)
87    {
88        $this->chart_service = $chart_service;
89    }
90
91    /**
92     * Initialization.
93     *
94     * @return void
95     */
96    public function boot(): void
97    {
98        $router_container = app(RouterContainer::class);
99        assert($router_container instanceof RouterContainer);
100
101        $router_container->getMap()
102            ->get(self::ROUTE_NAME, self::ROUTE_URL, $this)
103            ->allows(RequestMethodInterface::METHOD_POST)
104            ->tokens([
105                'generations' => '\d+',
106                'style'       => implode('|', array_keys($this->styles())),
107            ]);
108    }
109
110    /**
111     * How should this module be identified in the control panel, etc.?
112     *
113     * @return string
114     */
115    public function title(): string
116    {
117        /* I18N: Name of a module/chart */
118        return I18N::translate('Pedigree');
119    }
120
121    /**
122     * A sentence describing what this module does.
123     *
124     * @return string
125     */
126    public function description(): string
127    {
128        /* I18N: Description of the “PedigreeChart” module */
129        return I18N::translate('A chart of an individual’s ancestors, formatted as a tree.');
130    }
131
132    /**
133     * CSS class for the URL.
134     *
135     * @return string
136     */
137    public function chartMenuClass(): string
138    {
139        return 'menu-chart-pedigree';
140    }
141
142    /**
143     * Return a menu item for this chart - for use in individual boxes.
144     *
145     * @param Individual $individual
146     *
147     * @return Menu|null
148     */
149    public function chartBoxMenu(Individual $individual): ?Menu
150    {
151        return $this->chartMenu($individual);
152    }
153
154    /**
155     * The title for a specific instance of this chart.
156     *
157     * @param Individual $individual
158     *
159     * @return string
160     */
161    public function chartTitle(Individual $individual): string
162    {
163        /* I18N: %s is an individual’s name */
164        return I18N::translate('Pedigree tree of %s', $individual->fullName());
165    }
166
167    /**
168     * The URL for a page showing chart options.
169     *
170     * @param Individual $individual
171     * @param mixed[]    $parameters
172     *
173     * @return string
174     */
175    public function chartUrl(Individual $individual, array $parameters = []): string
176    {
177        return route(self::ROUTE_NAME, [
178                'xref' => $individual->xref(),
179                'tree' => $individual->tree()->name(),
180            ] + $parameters + self::DEFAULT_PARAMETERS);
181    }
182
183    /**
184     * @param ServerRequestInterface $request
185     *
186     * @return ResponseInterface
187     */
188    public function handle(ServerRequestInterface $request): ResponseInterface
189    {
190        $tree = $request->getAttribute('tree');
191        assert($tree instanceof Tree);
192
193        $ajax        = $request->getQueryParams()['ajax'] ?? '';
194        $generations = (int) $request->getAttribute('generations');
195        $style       = $request->getAttribute('style');
196        $user        = $request->getAttribute('user');
197        $xref        = $request->getAttribute('xref');
198        $individual  = Individual::getInstance($xref, $tree);
199
200        // Convert POST requests into GET requests for pretty URLs.
201        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
202            return redirect(route(self::ROUTE_NAME, [
203                'tree'        => $request->getAttribute('tree')->name(),
204                'xref'        => $request->getParsedBody()['xref'],
205                'style'       => $request->getParsedBody()['style'],
206                'generations' => $request->getParsedBody()['generations'],
207            ]));
208        }
209
210        Auth::checkIndividualAccess($individual);
211        Auth::checkComponentAccess($this, 'chart', $tree, $user);
212
213        $generations = min($generations, self::MAXIMUM_GENERATIONS);
214        $generations = max($generations, self::MINIMUM_GENERATIONS);
215
216        if ($ajax === '1') {
217            $this->layout = 'layouts/ajax';
218
219            $ancestors = $this->chart_service->sosaStradonitzAncestors($individual, $generations);
220
221            // Father’s ancestors link to the father’s pedigree
222            // Mother’s ancestors link to the mother’s pedigree..
223            $links = $ancestors->map(function (?Individual $individual, $sosa) use ($ancestors, $style, $generations): string {
224                if ($individual instanceof Individual && $sosa >= 2 ** $generations / 2 && $individual->childFamilies()->isNotEmpty()) {
225                    // The last row/column, and there are more generations.
226                    if ($sosa >= 2 ** $generations * 3 / 4) {
227                        return $this->nextLink($ancestors->get(3), $style, $generations);
228                    }
229
230                    return $this->nextLink($ancestors->get(2), $style, $generations);
231                }
232
233                // A spacer to fix the "Left" layout.
234                return '<span class="invisible px-2">' . view('icons/arrow-' . $style) . '</span>';
235            });
236
237            // Root individual links to their children.
238            $links->put(1, $this->previousLink($individual, $style, $generations));
239
240            return $this->viewResponse('modules/pedigree-chart/chart', [
241                'ancestors'   => $ancestors,
242                'generations' => $generations,
243                'style'       => $style,
244                'layout'      => 'right',
245                'links'       => $links,
246            ]);
247        }
248
249        $ajax_url = $this->chartUrl($individual, [
250            'ajax'        => true,
251            'generations' => $generations,
252            'style'       => $style,
253            'xref'        => $xref,
254        ]);
255
256        return $this->viewResponse('modules/pedigree-chart/page', [
257            'ajax_url'           => $ajax_url,
258            'generations'        => $generations,
259            'generation_options' => $this->generationOptions(),
260            'individual'         => $individual,
261            'module'             => $this->name(),
262            'style'              => $style,
263            'styles'             => $this->styles(),
264            'title'              => $this->chartTitle($individual),
265            'tree'               => $tree,
266        ]);
267    }
268
269    /**
270     * Build a menu for the chart root individual
271     *
272     * @param Individual $individual
273     * @param string     $style
274     * @param int        $generations
275     *
276     * @return string
277     */
278    public function nextLink(Individual $individual, string $style, int $generations): string
279    {
280        $icon  = view('icons/arrow-' . $style);
281        $title = $this->chartTitle($individual);
282        $url   = $this->chartUrl($individual, [
283            'style'       => $style,
284            'generations' => $generations,
285        ]);
286
287        return '<a class="px-2" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $icon . '<span class="sr-only">' . $title . '</span></a>';
288    }
289
290    /**
291     * Build a menu for the chart root individual
292     *
293     * @param Individual $individual
294     * @param string     $style
295     * @param int        $generations
296     *
297     * @return string
298     */
299    public function previousLink(Individual $individual, string $style, int $generations): string
300    {
301        $icon = view('icons/arrow-' . self::MIRROR_STYLE[$style]);
302
303        $siblings = [];
304        $spouses  = [];
305        $children = [];
306
307        foreach ($individual->childFamilies() as $family) {
308            foreach ($family->children() as $child) {
309                if ($child !== $individual) {
310                    $siblings[] = $this->individualLink($child, $style, $generations);
311                }
312            }
313        }
314
315        foreach ($individual->spouseFamilies() as $family) {
316            foreach ($family->spouses() as $spouse) {
317                if ($spouse !== $individual) {
318                    $spouses[] = $this->individualLink($spouse, $style, $generations);
319                }
320            }
321
322            foreach ($family->children() as $child) {
323                $children[] = $this->individualLink($child, $style, $generations);
324            }
325        }
326
327        return view('modules/pedigree-chart/previous', [
328            'icon'        => $icon,
329            'individual'  => $individual,
330            'generations' => $generations,
331            'style'       => $style,
332            'chart'       => $this,
333            'siblings'    => $siblings,
334            'spouses'     => $spouses,
335            'children'    => $children,
336        ]);
337    }
338
339    /**
340     * @param Individual $individual
341     * @param string     $style
342     * @param int        $generations
343     *
344     * @return string
345     */
346    protected function individualLink(Individual $individual, string $style, int $generations): string
347    {
348        $text  = $individual->fullName();
349        $title = $this->chartTitle($individual);
350        $url   = $this->chartUrl($individual, [
351            'style'       => $style,
352            'generations' => $generations,
353        ]);
354
355        return '<a class="dropdown-item" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $text . '</a>';
356    }
357
358    /**
359     * @return string[]
360     */
361    protected function generationOptions(): array
362    {
363        return FunctionsEdit::numericOptions(range(self::MINIMUM_GENERATIONS, self::MAXIMUM_GENERATIONS));
364    }
365
366    /**
367     * This chart can display its output in a number of styles
368     *
369     * @return string[]
370     */
371    protected function styles(): array
372    {
373        return [
374            self::STYLE_LEFT  => I18N::translate('Left'),
375            self::STYLE_RIGHT => I18N::translate('Right'),
376            self::STYLE_UP    => I18N::translate('Up'),
377            self::STYLE_DOWN  => I18N::translate('Down'),
378        ];
379    }
380}
381