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