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