xref: /webtrees/app/Module/PedigreeMapModule.php (revision 6172e7f6cb6d9b42e9feef9b728f7561b0d70dc9)
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 for each generation
69    private const COUNT_CSS_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::COUNT_CSS_COLORS . ')';
249                $class              = 'wt-pedigree-map-gen-' . $sosa_child % self::COUNT_CSS_COLORS;
250
251                if (array_key_exists($sosa_child, $sosa_points)) {
252                    // Would like to use a GeometryCollection to hold LineStrings
253                    // rather than generate polylines but the MarkerCluster library
254                    // doesn't seem to like them
255                    $polyline = [
256                        'points'  => [
257                            $sosa_points[$sosa_child],
258                            [$latitude, $longitude],
259                        ],
260                        'options' => [
261                            'color' => $color,
262                        ],
263                    ];
264                }
265                $geojson['features'][] = [
266                    'type'       => 'Feature',
267                    'id'         => $sosa,
268                    'geometry'   => [
269                        'type'        => 'Point',
270                        'coordinates' => [$longitude, $latitude],
271                    ],
272                    'properties' => [
273                        'polyline'  => $polyline,
274                        'iconcolor' => $color,
275                        'tooltip'   => $fact->place()->gedcomName(),
276                        'summary'   => view('modules/pedigree-map/events', [
277                            'class'        => $class,
278                            'fact'         => $fact,
279                            'relationship' => ucfirst($this->getSosaName($sosa)),
280                            'sosa'         => $sosa,
281                        ]),
282                    ],
283                ];
284            }
285        }
286
287        return $geojson;
288    }
289
290    /**
291     * @param ServerRequestInterface $request
292     * @param ChartService           $chart_service
293     *
294     * @return array<Fact>
295     */
296    private function getPedigreeMapFacts(ServerRequestInterface $request, ChartService $chart_service): array
297    {
298        $tree        = Validator::attributes($request)->tree();
299        $generations = Validator::attributes($request)->isBetween(self::MINIMUM_GENERATIONS, self::MAXIMUM_GENERATIONS)->integer('generations');
300        $xref        = Validator::attributes($request)->isXref()->string('xref');
301        $individual  = Registry::individualFactory()->make($xref, $tree);
302        $individual  = Auth::checkIndividualAccess($individual, false, true);
303        $ancestors   = $chart_service->sosaStradonitzAncestors($individual, $generations);
304        $facts       = [];
305
306        foreach ($ancestors as $sosa => $person) {
307            if ($person->canShow()) {
308                $birth = $person->facts(Gedcom::BIRTH_EVENTS, true)
309                    ->first(static function (Fact $fact): bool {
310                        return $fact->place()->gedcomName() !== '';
311                    });
312
313                if ($birth instanceof Fact) {
314                    $facts[$sosa] = $birth;
315                }
316            }
317        }
318
319        return $facts;
320    }
321
322    /**
323     * builds and returns sosa relationship name in the active language
324     *
325     * @param int $sosa Sosa number
326     *
327     * @return string
328     */
329    private function getSosaName(int $sosa): string
330    {
331        $path = '';
332
333        while ($sosa > 1) {
334            if ($sosa % 2 === 1) {
335                $path = 'mot' . $path;
336            } else {
337                $path = 'fat' . $path;
338            }
339            $sosa = intdiv($sosa, 2);
340        }
341
342        $relationship_service = app(RelationshipService::class);
343        assert($relationship_service instanceof RelationshipService);
344
345        return $relationship_service->legacyNameAlgorithm($path);
346    }
347}
348