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