xref: /webtrees/app/Module/PedigreeChartModule.php (revision 62fa6fd79d2f943d0a6f3e88ffeab601aec582a6)
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, 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::ROUTE_NAME, [
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            ]);
253        }
254
255        $ajax_url = $this->chartUrl($individual, [
256            'ajax'        => true,
257            'generations' => $generations,
258            'style'       => $style,
259            'xref'        => $xref,
260        ]);
261
262        return $this->viewResponse('modules/pedigree-chart/page', [
263            'ajax_url'           => $ajax_url,
264            'generations'        => $generations,
265            'generation_options' => $this->generationOptions(),
266            'individual'         => $individual,
267            'module'             => $this->name(),
268            'style'              => $style,
269            'styles'             => $this->styles(),
270            'title'              => $this->chartTitle($individual),
271            'tree'               => $tree,
272        ]);
273    }
274
275    /**
276     * Build a menu for the chart root individual
277     *
278     * @param Individual $individual
279     * @param string     $style
280     * @param int        $generations
281     *
282     * @return string
283     */
284    public function nextLink(Individual $individual, string $style, int $generations): string
285    {
286        $icon  = view('icons/arrow-' . $style);
287        $title = $this->chartTitle($individual);
288        $url   = $this->chartUrl($individual, [
289            'style'       => $style,
290            'generations' => $generations,
291        ]);
292
293        return '<a class="px-2" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $icon . '<span class="sr-only">' . $title . '</span></a>';
294    }
295
296    /**
297     * Build a menu for the chart root individual
298     *
299     * @param Individual $individual
300     * @param string     $style
301     * @param int        $generations
302     *
303     * @return string
304     */
305    public function previousLink(Individual $individual, string $style, int $generations): string
306    {
307        $icon = view('icons/arrow-' . self::MIRROR_STYLE[$style]);
308
309        $siblings = [];
310        $spouses  = [];
311        $children = [];
312
313        foreach ($individual->childFamilies() as $family) {
314            foreach ($family->children() as $child) {
315                if ($child !== $individual) {
316                    $siblings[] = $this->individualLink($child, $style, $generations);
317                }
318            }
319        }
320
321        foreach ($individual->spouseFamilies() as $family) {
322            foreach ($family->spouses() as $spouse) {
323                if ($spouse !== $individual) {
324                    $spouses[] = $this->individualLink($spouse, $style, $generations);
325                }
326            }
327
328            foreach ($family->children() as $child) {
329                $children[] = $this->individualLink($child, $style, $generations);
330            }
331        }
332
333        return view('modules/pedigree-chart/previous', [
334            'icon'        => $icon,
335            'individual'  => $individual,
336            'generations' => $generations,
337            'style'       => $style,
338            'chart'       => $this,
339            'siblings'    => $siblings,
340            'spouses'     => $spouses,
341            'children'    => $children,
342        ]);
343    }
344
345    /**
346     * @param Individual $individual
347     * @param string     $style
348     * @param int        $generations
349     *
350     * @return string
351     */
352    protected function individualLink(Individual $individual, string $style, int $generations): string
353    {
354        $text  = $individual->fullName();
355        $title = $this->chartTitle($individual);
356        $url   = $this->chartUrl($individual, [
357            'style'       => $style,
358            'generations' => $generations,
359        ]);
360
361        return '<a class="dropdown-item" href="' . e($url) . '" title="' . strip_tags($title) . '">' . $text . '</a>';
362    }
363
364    /**
365     * @return string[]
366     */
367    protected function generationOptions(): array
368    {
369        return FunctionsEdit::numericOptions(range(self::MINIMUM_GENERATIONS, self::MAXIMUM_GENERATIONS));
370    }
371
372    /**
373     * This chart can display its output in a number of styles
374     *
375     * @return string[]
376     */
377    protected function styles(): array
378    {
379        return [
380            self::STYLE_LEFT  => I18N::translate('Left'),
381            self::STYLE_RIGHT => I18N::translate('Right'),
382            self::STYLE_UP    => I18N::translate('Up'),
383            self::STYLE_DOWN  => I18N::translate('Down'),
384        ];
385    }
386}
387