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