xref: /webtrees/app/Module/PedigreeMapModule.php (revision c8d78f19d0bdf4c0ec4728253bd37250d2e6cec4)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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 <https://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\Fact;
26use Fisharebest\Webtrees\Gedcom;
27use Fisharebest\Webtrees\I18N;
28use Fisharebest\Webtrees\Individual;
29use Fisharebest\Webtrees\Menu;
30use Fisharebest\Webtrees\PlaceLocation;
31use Fisharebest\Webtrees\Registry;
32use Fisharebest\Webtrees\Services\ChartService;
33use Fisharebest\Webtrees\Services\LeafletJsService;
34use Fisharebest\Webtrees\Services\RelationshipService;
35use Fisharebest\Webtrees\Tree;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestInterface;
38use Psr\Http\Server\RequestHandlerInterface;
39
40use function app;
41use function array_key_exists;
42use function assert;
43use function count;
44use function intdiv;
45use function is_string;
46use function redirect;
47use function route;
48use function ucfirst;
49use function view;
50
51/**
52 * Class PedigreeMapModule
53 */
54class PedigreeMapModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
55{
56    use ModuleChartTrait;
57
58    protected const ROUTE_URL = '/tree/{tree}/pedigree-map-{generations}/{xref}';
59
60    // Defaults
61    public const DEFAULT_GENERATIONS = '4';
62    public const DEFAULT_PARAMETERS  = [
63        'generations' => self::DEFAULT_GENERATIONS,
64    ];
65
66    // Limits
67    public const MAXIMUM_GENERATIONS = 10;
68
69    // CSS colors for each generation
70    private const COLORS = [
71        'Red',
72        'Green',
73        'Blue',
74        'Gold',
75        'Cyan',
76        'Orange',
77        'DarkBlue',
78        'LightGreen',
79        'Magenta',
80        'Brown',
81    ];
82
83    private ChartService $chart_service;
84
85    private LeafletJsService $leaflet_js_service;
86
87    /**
88     * PedigreeMapModule constructor.
89     *
90     * @param ChartService     $chart_service
91     * @param LeafletJsService $leaflet_js_service
92     */
93    public function __construct(ChartService $chart_service, LeafletJsService $leaflet_js_service)
94    {
95        $this->chart_service      = $chart_service;
96        $this->leaflet_js_service = $leaflet_js_service;
97    }
98
99    /**
100     * Initialization.
101     *
102     * @return void
103     */
104    public function boot(): void
105    {
106        $router_container = app(RouterContainer::class);
107        assert($router_container instanceof RouterContainer);
108
109        $router_container->getMap()
110            ->get(static::class, static::ROUTE_URL, $this)
111            ->allows(RequestMethodInterface::METHOD_POST)
112            ->tokens([
113                'generations' => '\d+',
114            ]);
115    }
116
117    /**
118     * How should this module be identified in the control panel, etc.?
119     *
120     * @return string
121     */
122    public function title(): string
123    {
124        /* I18N: Name of a module */
125        return I18N::translate('Pedigree map');
126    }
127
128    /**
129     * A sentence describing what this module does.
130     *
131     * @return string
132     */
133    public function description(): string
134    {
135        /* I18N: Description of the “Pedigree map” module */
136        return I18N::translate('Show the birthplace of ancestors on a map.');
137    }
138
139    /**
140     * CSS class for the URL.
141     *
142     * @return string
143     */
144    public function chartMenuClass(): string
145    {
146        return 'menu-chart-pedigreemap';
147    }
148
149    /**
150     * Return a menu item for this chart - for use in individual boxes.
151     *
152     * @param Individual $individual
153     *
154     * @return Menu|null
155     */
156    public function chartBoxMenu(Individual $individual): ?Menu
157    {
158        return $this->chartMenu($individual);
159    }
160
161    /**
162     * The title for a specific instance of this chart.
163     *
164     * @param Individual $individual
165     *
166     * @return string
167     */
168    public function chartTitle(Individual $individual): string
169    {
170        /* I18N: %s is an individual’s name */
171        return I18N::translate('Pedigree map of %s', $individual->fullName());
172    }
173
174    /**
175     * The URL for a page showing chart options.
176     *
177     * @param Individual                        $individual
178     * @param array<bool|int|string|array|null> $parameters
179     *
180     * @return string
181     */
182    public function chartUrl(Individual $individual, array $parameters = []): string
183    {
184        return route(static::class, [
185                'tree' => $individual->tree()->name(),
186                'xref' => $individual->xref(),
187            ] + $parameters + self::DEFAULT_PARAMETERS);
188    }
189
190    /**
191     * @param ServerRequestInterface $request
192     *
193     * @return ResponseInterface
194     */
195    public function handle(ServerRequestInterface $request): ResponseInterface
196    {
197        $tree = $request->getAttribute('tree');
198        assert($tree instanceof Tree);
199
200        $xref = $request->getAttribute('xref');
201        assert(is_string($xref));
202
203        $individual = Registry::individualFactory()->make($xref, $tree);
204        $individual = Auth::checkIndividualAccess($individual, false, true);
205
206        $user        = $request->getAttribute('user');
207        $generations = (int) $request->getAttribute('generations');
208        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
209
210        // Convert POST requests into GET requests for pretty URLs.
211        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
212            $params = (array) $request->getParsedBody();
213
214            return redirect(route(static::class, [
215                'tree'        => $tree->name(),
216                'xref'        => $params['xref'],
217                'generations' => $params['generations'],
218            ]));
219        }
220
221        $map = view('modules/pedigree-map/chart', [
222            'data'           => $this->getMapData($request),
223            'leaflet_config' => $this->leaflet_js_service->config(),
224        ]);
225
226        return $this->viewResponse('modules/pedigree-map/page', [
227            'module'         => $this->name(),
228            /* I18N: %s is an individual’s name */
229            'title'          => I18N::translate('Pedigree map of %s', $individual->fullName()),
230            'tree'           => $tree,
231            'individual'     => $individual,
232            'generations'    => $generations,
233            'maxgenerations' => self::MAXIMUM_GENERATIONS,
234            'map'            => $map,
235        ]);
236    }
237
238    /**
239     * @param ServerRequestInterface $request
240     *
241     * @return array<mixed> $geojson
242     */
243    private function getMapData(ServerRequestInterface $request): array
244    {
245        $tree = $request->getAttribute('tree');
246        assert($tree instanceof Tree);
247
248        $color_count = count(self::COLORS);
249
250        $facts = $this->getPedigreeMapFacts($request, $this->chart_service);
251
252        $geojson = [
253            'type'     => 'FeatureCollection',
254            'features' => [],
255        ];
256
257        $sosa_points = [];
258
259        foreach ($facts as $sosa => $fact) {
260            $location = new PlaceLocation($fact->place()->gedcomName());
261
262            // Use the co-ordinates from the fact (if they exist).
263            $latitude  = $fact->latitude();
264            $longitude = $fact->longitude();
265
266            // Use the co-ordinates from the location otherwise.
267            if ($latitude === null || $longitude === null) {
268                $latitude  = $location->latitude();
269                $longitude = $location->longitude();
270            }
271
272            if ($latitude !== null && $longitude !== null) {
273                $polyline           = null;
274                $sosa_points[$sosa] = [$latitude, $longitude];
275                $sosa_child         = intdiv($sosa, 2);
276                $color              = self::COLORS[$sosa_child % $color_count];
277
278                if (array_key_exists($sosa_child, $sosa_points)) {
279                    // Would like to use a GeometryCollection to hold LineStrings
280                    // rather than generate polylines but the MarkerCluster library
281                    // doesn't seem to like them
282                    $polyline = [
283                        'points'  => [
284                            $sosa_points[$sosa_child],
285                            [$latitude, $longitude],
286                        ],
287                        'options' => [
288                            'color' => $color,
289                        ],
290                    ];
291                }
292                $geojson['features'][] = [
293                    'type'       => 'Feature',
294                    'id'         => $sosa,
295                    'geometry'   => [
296                        'type'        => 'Point',
297                        'coordinates' => [$longitude, $latitude],
298                    ],
299                    'properties' => [
300                        'polyline'  => $polyline,
301                        'iconcolor' => $color,
302                        'tooltip'   => $fact->place()->gedcomName(),
303                        'summary'   => view('modules/pedigree-map/events', [
304                            'fact'         => $fact,
305                            'relationship' => ucfirst($this->getSosaName($sosa)),
306                            'sosa'         => $sosa,
307                        ]),
308                    ],
309                ];
310            }
311        }
312
313        return $geojson;
314    }
315
316    /**
317     * @param ServerRequestInterface $request
318     * @param ChartService           $chart_service
319     *
320     * @return array<Fact>
321     */
322    private function getPedigreeMapFacts(ServerRequestInterface $request, ChartService $chart_service): array
323    {
324        $tree = $request->getAttribute('tree');
325        assert($tree instanceof Tree);
326
327        $generations = (int) $request->getAttribute('generations');
328        $xref        = $request->getAttribute('xref');
329        $individual  = Registry::individualFactory()->make($xref, $tree);
330        $ancestors   = $chart_service->sosaStradonitzAncestors($individual, $generations);
331        $facts       = [];
332        foreach ($ancestors as $sosa => $person) {
333            if ($person->canShow()) {
334                $birth = $person->facts(Gedcom::BIRTH_EVENTS, true)
335                    ->first(static function (Fact $fact): bool {
336                        return $fact->place()->gedcomName() !== '';
337                    });
338
339                if ($birth instanceof Fact) {
340                    $facts[$sosa] = $birth;
341                }
342            }
343        }
344
345        return $facts;
346    }
347
348    /**
349     * builds and returns sosa relationship name in the active language
350     *
351     * @param int $sosa Sosa number
352     *
353     * @return string
354     */
355    private function getSosaName(int $sosa): string
356    {
357        $path = '';
358
359        while ($sosa > 1) {
360            if ($sosa % 2 === 1) {
361                $path = 'mot' . $path;
362            } else {
363                $path = 'fat' . $path;
364            }
365            $sosa = intdiv($sosa, 2);
366        }
367
368        return app(RelationshipService::class)->legacyNameAlgorithm($path);
369    }
370}
371