xref: /webtrees/app/Module/PedigreeMapModule.php (revision 29eb5762de63c94d5fbdadc63af16f6ac11bd664)
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);
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                'name'    => "OpenStreetMap.Mapnik",
226                'options' => []
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 Location($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'   => strip_tags($fact->place()->fullName()),
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
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  = Individual::getInstance($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                    ->filter(static function (Fact $fact): bool {
341                        return $fact->place()->gedcomName() !== '';
342                    })
343                    ->first();
344
345                if ($birth instanceof Fact) {
346                    $facts[$sosa] = $birth;
347                }
348            }
349        }
350
351        return $facts;
352    }
353
354    /**
355     * builds and returns sosa relationship name in the active language
356     *
357     * @param int $sosa Sosa number
358     *
359     * @return string
360     */
361    private function getSosaName(int $sosa): string
362    {
363        $path = '';
364
365        while ($sosa > 1) {
366            if ($sosa % 2 === 1) {
367                $path = 'mot' . $path;
368            } else {
369                $path = 'fat' . $path;
370            }
371            $sosa = intdiv($sosa, 2);
372        }
373
374        return Functions::getRelationshipNameFromPath($path);
375    }
376}
377