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