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