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