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