xref: /webtrees/app/Module/PedigreeMapModule.php (revision 752e4449401bd895764f08f44c6c370bce5f7669)
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
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 getMapDataAction(ServerRequestInterface $request): ResponseInterface
196    {
197        $tree = $request->getAttribute('tree');
198        assert($tree instanceof Tree);
199
200        $color_count = count(self::COLORS);
201
202        $facts = $this->getPedigreeMapFacts($request, $this->chart_service);
203
204        $geojson = [
205            'type'     => 'FeatureCollection',
206            'features' => [],
207        ];
208
209        $sosa_points = [];
210
211        foreach ($facts as $sosa => $fact) {
212            $location = new Location($fact->place()->gedcomName());
213
214            // Use the co-ordinates from the fact (if they exist).
215            $latitude  = $fact->latitude();
216            $longitude = $fact->longitude();
217
218            // Use the co-ordinates from the location otherwise.
219            if ($latitude === 0.0 && $longitude === 0.0) {
220                $latitude  = $location->latitude();
221                $longitude = $location->longitude();
222            }
223
224            if ($latitude !== 0.0 || $longitude !== 0.0) {
225                $polyline           = null;
226                $sosa_points[$sosa] = [$latitude, $longitude];
227                $sosa_child         = intdiv($sosa, 2);
228                $color              = self::COLORS[$sosa_child % $color_count];
229
230                if (array_key_exists($sosa_child, $sosa_points)) {
231                    // Would like to use a GeometryCollection to hold LineStrings
232                    // rather than generate polylines but the MarkerCluster library
233                    // doesn't seem to like them
234                    $polyline = [
235                        'points'  => [
236                            $sosa_points[$sosa_child],
237                            [$latitude, $longitude],
238                        ],
239                        'options' => [
240                            'color' => $color,
241                        ],
242                    ];
243                }
244                $geojson['features'][] = [
245                    'type'       => 'Feature',
246                    'id'         => $sosa,
247                    'geometry'   => [
248                        'type'        => 'Point',
249                        'coordinates' => [$longitude, $latitude],
250                    ],
251                    'properties' => [
252                        'polyline'  => $polyline,
253                        'iconcolor' => $color,
254                        'tooltip'   => strip_tags($fact->place()->fullName()),
255                        'summary'   => view('modules/pedigree-map/events', [
256                            'fact'         => $fact,
257                            'relationship' => ucfirst($this->getSosaName($sosa)),
258                            'sosa'         => $sosa,
259                        ]),
260                        'zoom'      => $location->zoom() ?: self::DEFAULT_ZOOM,
261                    ],
262                ];
263            }
264        }
265
266        $code = $facts === [] ? StatusCodeInterface::STATUS_NO_CONTENT : StatusCodeInterface::STATUS_OK;
267
268        return response($geojson, $code);
269    }
270
271    /**
272     * @param ServerRequestInterface $request
273     *
274     * @return ResponseInterface
275     */
276    public function handle(ServerRequestInterface $request): ResponseInterface
277    {
278        $tree = $request->getAttribute('tree');
279        assert($tree instanceof Tree);
280
281        $xref = $request->getAttribute('xref');
282        assert(is_string($xref));
283
284        $individual  = Individual::getInstance($xref, $tree);
285        $individual  = Auth::checkIndividualAccess($individual);
286
287        $user        = $request->getAttribute('user');
288        $generations = (int) $request->getAttribute('generations');
289        Auth::checkComponentAccess($this, 'chart', $tree, $user);
290
291        // Convert POST requests into GET requests for pretty URLs.
292        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
293            $params = (array) $request->getParsedBody();
294
295            return redirect(route(static::class, [
296                'tree'        => $tree->name(),
297                'xref'        => $params['xref'],
298                'generations' => $params['generations'],
299            ]));
300        }
301
302        $map = view('modules/pedigree-map/chart', [
303            'individual'  => $individual,
304            'generations' => $generations,
305        ]);
306
307        return $this->viewResponse('modules/pedigree-map/page', [
308            'module'         => $this->name(),
309            /* I18N: %s is an individual’s name */
310            'title'          => I18N::translate('Pedigree map of %s', $individual->fullName()),
311            'tree'           => $tree,
312            'individual'     => $individual,
313            'generations'    => $generations,
314            'maxgenerations' => self::MAXIMUM_GENERATIONS,
315            'map'            => $map,
316        ]);
317    }
318
319    /**
320     * @param ServerRequestInterface $request
321     * @param ChartService           $chart_service
322     *
323     * @return array
324     */
325    private function getPedigreeMapFacts(ServerRequestInterface $request, ChartService $chart_service): array
326    {
327        $tree = $request->getAttribute('tree');
328        assert($tree instanceof Tree);
329
330        $generations = (int) $request->getQueryParams()['generations'];
331        $xref        = $request->getQueryParams()['xref'];
332        $individual  = Individual::getInstance($xref, $tree);
333        $ancestors   = $chart_service->sosaStradonitzAncestors($individual, $generations);
334        $facts       = [];
335        foreach ($ancestors as $sosa => $person) {
336            if ($person->canShow()) {
337                $birth = $person->facts(Gedcom::BIRTH_EVENTS, true)
338                    ->filter(static function (Fact $fact): bool {
339                        return $fact->place()->gedcomName() !== '';
340                    })
341                    ->first();
342
343                if ($birth instanceof Fact) {
344                    $facts[$sosa] = $birth;
345                }
346            }
347        }
348
349        return $facts;
350    }
351
352    /**
353     * builds and returns sosa relationship name in the active language
354     *
355     * @param int $sosa Sosa number
356     *
357     * @return string
358     */
359    private function getSosaName(int $sosa): string
360    {
361        $path = '';
362
363        while ($sosa > 1) {
364            if ($sosa % 2 === 1) {
365                $path = 'mot' . $path;
366            } else {
367                $path = 'fat' . $path;
368            }
369            $sosa = intdiv($sosa, 2);
370        }
371
372        return Functions::getRelationshipNameFromPath($path);
373    }
374}
375