xref: /webtrees/app/Module/PedigreeChartModule.php (revision b8fc901f205cd6af65496b916bf63547a3065a2f)
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 is_string;
38use function max;
39use function min;
40use function route;
41use function view;
42
43/**
44 * Class PedigreeChartModule
45 */
46class PedigreeChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
47{
48    use ModuleChartTrait;
49
50    private const ROUTE_NAME = 'pedigree-chart';
51    private 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(self::ROUTE_NAME, self::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(self::ROUTE_NAME, [
179                'xref' => $individual->xref(),
180                'tree' => $individual->tree()->name(),
181            ] + $parameters + self::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 = Individual::getInstance($xref, $tree);
198        $individual = Auth::checkIndividualAccess($individual);
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            return redirect(route(self::ROUTE_NAME, [
208                'tree'        => $request->getAttribute('tree')->name(),
209                'xref'        => $request->getParsedBody()['xref'],
210                'style'       => $request->getParsedBody()['style'],
211                'generations' => $request->getParsedBody()['generations'],
212            ]));
213        }
214
215        Auth::checkComponentAccess($this, 'chart', $tree, $user);
216
217        $generations = min($generations, self::MAXIMUM_GENERATIONS);
218        $generations = max($generations, self::MINIMUM_GENERATIONS);
219
220        if ($ajax === '1') {
221            $this->layout = 'layouts/ajax';
222
223            $ancestors = $this->chart_service->sosaStradonitzAncestors($individual, $generations);
224
225            // Father’s ancestors link to the father’s pedigree
226            // Mother’s ancestors link to the mother’s pedigree..
227            $links = $ancestors->map(function (?Individual $individual, $sosa) use ($ancestors, $style, $generations): string {
228                if ($individual instanceof Individual && $sosa >= 2 ** $generations / 2 && $individual->childFamilies()->isNotEmpty()) {
229                    // The last row/column, and there are more generations.
230                    if ($sosa >= 2 ** $generations * 3 / 4) {
231                        return $this->nextLink($ancestors->get(3), $style, $generations);
232                    }
233
234                    return $this->nextLink($ancestors->get(2), $style, $generations);
235                }
236
237                // A spacer to fix the "Left" layout.
238                return '<span class="invisible px-2">' . view('icons/arrow-' . $style) . '</span>';
239            });
240
241            // Root individual links to their children.
242            $links->put(1, $this->previousLink($individual, $style, $generations));
243
244            return $this->viewResponse('modules/pedigree-chart/chart', [
245                'ancestors'   => $ancestors,
246                'generations' => $generations,
247                'style'       => $style,
248                'layout'      => 'right',
249                'links'       => $links,
250            ]);
251        }
252
253        $ajax_url = $this->chartUrl($individual, [
254            'ajax'        => true,
255            'generations' => $generations,
256            'style'       => $style,
257            'xref'        => $xref,
258        ]);
259
260        return $this->viewResponse('modules/pedigree-chart/page', [
261            'ajax_url'           => $ajax_url,
262            'generations'        => $generations,
263            'generation_options' => $this->generationOptions(),
264            'individual'         => $individual,
265            'module'             => $this->name(),
266            'style'              => $style,
267            'styles'             => $this->styles(),
268            'title'              => $this->chartTitle($individual),
269            'tree'               => $tree,
270        ]);
271    }
272
273    /**
274     * Build a menu for the chart root individual
275     *
276     * @param Individual $individual
277     * @param string     $style
278     * @param int        $generations
279     *
280     * @return string
281     */
282    public function nextLink(Individual $individual, string $style, int $generations): string
283    {
284        $icon  = view('icons/arrow-' . $style);
285        $title = $this->chartTitle($individual);
286        $url   = $this->chartUrl($individual, [
287            'style'       => $style,
288            'generations' => $generations,
289        ]);
290
291        return '<a class="px-2" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $icon . '<span class="sr-only">' . $title . '</span></a>';
292    }
293
294    /**
295     * Build a menu for the chart root individual
296     *
297     * @param Individual $individual
298     * @param string     $style
299     * @param int        $generations
300     *
301     * @return string
302     */
303    public function previousLink(Individual $individual, string $style, int $generations): string
304    {
305        $icon = view('icons/arrow-' . self::MIRROR_STYLE[$style]);
306
307        $siblings = [];
308        $spouses  = [];
309        $children = [];
310
311        foreach ($individual->childFamilies() as $family) {
312            foreach ($family->children() as $child) {
313                if ($child !== $individual) {
314                    $siblings[] = $this->individualLink($child, $style, $generations);
315                }
316            }
317        }
318
319        foreach ($individual->spouseFamilies() as $family) {
320            foreach ($family->spouses() as $spouse) {
321                if ($spouse !== $individual) {
322                    $spouses[] = $this->individualLink($spouse, $style, $generations);
323                }
324            }
325
326            foreach ($family->children() as $child) {
327                $children[] = $this->individualLink($child, $style, $generations);
328            }
329        }
330
331        return view('modules/pedigree-chart/previous', [
332            'icon'        => $icon,
333            'individual'  => $individual,
334            'generations' => $generations,
335            'style'       => $style,
336            'chart'       => $this,
337            'siblings'    => $siblings,
338            'spouses'     => $spouses,
339            'children'    => $children,
340        ]);
341    }
342
343    /**
344     * @param Individual $individual
345     * @param string     $style
346     * @param int        $generations
347     *
348     * @return string
349     */
350    protected function individualLink(Individual $individual, string $style, int $generations): string
351    {
352        $text  = $individual->fullName();
353        $title = $this->chartTitle($individual);
354        $url   = $this->chartUrl($individual, [
355            'style'       => $style,
356            'generations' => $generations,
357        ]);
358
359        return '<a class="dropdown-item" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $text . '</a>';
360    }
361
362    /**
363     * @return string[]
364     */
365    protected function generationOptions(): array
366    {
367        return FunctionsEdit::numericOptions(range(self::MINIMUM_GENERATIONS, self::MAXIMUM_GENERATIONS));
368    }
369
370    /**
371     * This chart can display its output in a number of styles
372     *
373     * @return string[]
374     */
375    protected function styles(): array
376    {
377        return [
378            self::STYLE_LEFT  => I18N::translate('Left'),
379            self::STYLE_RIGHT => I18N::translate('Right'),
380            self::STYLE_UP    => I18N::translate('Up'),
381            self::STYLE_DOWN  => I18N::translate('Down'),
382        ];
383    }
384}
385