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