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