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