xref: /webtrees/app/Module/PedigreeMapModule.php (revision facade402cb57d53631f2fb96d98b1a0b2ba9815)
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    private const ROUTE_NAME = 'pedigree-map';
56    private const ROUTE_URL  = '/tree/{tree}/pedigree-map-{generations}/{xref}';
57
58    // Defaults
59    public const DEFAULT_GENERATIONS = '4';
60    public const DEFAULT_PARAMETERS  = [
61        'generations' => self::DEFAULT_GENERATIONS,
62    ];
63
64    // Limits
65    public const MAXIMUM_GENERATIONS = 10;
66
67    private const COLORS = [
68        ['red'],
69        ['green'],
70        ['blue'],
71        ['gold'],
72        ['cyan'],
73        ['orange'],
74        ['blue-dark'],
75        ['green-light']
76    ];
77
78    /** @var ChartService */
79    private $chart_service;
80
81    /**
82     * PedigreeMapModule constructor.
83     *
84     * @param ChartService $chart_service
85     */
86    public function __construct(ChartService $chart_service)
87    {
88        $this->chart_service = $chart_service;
89    }
90
91    /**
92     * Initialization.
93     *
94     * @return void
95     */
96    public function boot(): void
97    {
98        $router_container = app(RouterContainer::class);
99        assert($router_container instanceof RouterContainer);
100
101        $router_container->getMap()
102            ->get(self::ROUTE_NAME, self::ROUTE_URL, $this)
103            ->allows(RequestMethodInterface::METHOD_POST)
104            ->tokens([
105                'generations' => '\d+',
106            ]);
107    }
108
109    /**
110     * How should this module be identified in the control panel, etc.?
111     *
112     * @return string
113     */
114    public function title(): string
115    {
116        /* I18N: Name of a module */
117        return I18N::translate('Pedigree map');
118    }
119
120    /**
121     * A sentence describing what this module does.
122     *
123     * @return string
124     */
125    public function description(): string
126    {
127        /* I18N: Description of the “Pedigree map” module */
128        return I18N::translate('Show the birthplace of ancestors on a map.');
129    }
130
131    /**
132     * CSS class for the URL.
133     *
134     * @return string
135     */
136    public function chartMenuClass(): string
137    {
138        return 'menu-chart-pedigreemap';
139    }
140
141    /**
142     * Return a menu item for this chart - for use in individual boxes.
143     *
144     * @param Individual $individual
145     *
146     * @return Menu|null
147     */
148    public function chartBoxMenu(Individual $individual): ?Menu
149    {
150        return $this->chartMenu($individual);
151    }
152
153    /**
154     * The title for a specific instance of this chart.
155     *
156     * @param Individual $individual
157     *
158     * @return string
159     */
160    public function chartTitle(Individual $individual): string
161    {
162        /* I18N: %s is an individual’s name */
163        return I18N::translate('Pedigree map of %s', $individual->fullName());
164    }
165
166    /**
167     * The URL for a page showing chart options.
168     *
169     * @param Individual $individual
170     * @param mixed[]    $parameters
171     *
172     * @return string
173     */
174    public function chartUrl(Individual $individual, array $parameters = []): string
175    {
176        return route(self::ROUTE_NAME, [
177                'tree' => $individual->tree()->name(),
178                'xref' => $individual->xref(),
179            ] + $parameters + self::DEFAULT_PARAMETERS);
180    }
181
182    /**
183     * @param ServerRequestInterface $request
184     *
185     * @return ResponseInterface
186     */
187    public function getMapDataAction(ServerRequestInterface $request): ResponseInterface
188    {
189        $tree = $request->getAttribute('tree');
190        assert($tree instanceof Tree);
191
192        $xref        = $request->getQueryParams()['xref'];
193        $individual  = Individual::getInstance($xref, $tree);
194        $color_count = count(self::COLORS);
195
196        $facts = $this->getPedigreeMapFacts($request, $this->chart_service);
197
198        $geojson = [
199            'type'     => 'FeatureCollection',
200            'features' => [],
201        ];
202
203        $sosa_points = [];
204
205        foreach ($facts as $id => $fact) {
206            $location = new Location($fact->place()->gedcomName());
207
208            // Use the co-ordinates from the fact (if they exist).
209            $latitude  = $fact->latitude();
210            $longitude = $fact->longitude();
211
212            // Use the co-ordinates from the location otherwise.
213            if ($latitude === 0.0 && $longitude === 0.0) {
214                $latitude  = $location->latitude();
215                $longitude = $location->longitude();
216            }
217
218            if ($latitude !== 0.0 || $longitude !== 0.0) {
219                $polyline         = null;
220
221                $color_index      = log($id, 2) % $color_count;
222                $color            = self::COLORS[$color_index];
223                $sosa_points[$id] = [$latitude, $longitude];
224                $sosa_parent      = intdiv($id, 2);
225                if (array_key_exists($sosa_parent, $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_parent],
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            return redirect(route(self::ROUTE_NAME, [
285                'tree'        => $tree->name(),
286                'xref'        => $request->getParsedBody()['xref'],
287                'generations' => $request->getParsedBody()['generations'],
288            ]));
289        }
290
291        $map = view('modules/pedigree-map/chart', [
292            'individual'  => $individual,
293            'generations' => $generations,
294        ]);
295
296        return $this->viewResponse('modules/pedigree-map/page', [
297            'module'         => $this->name(),
298            /* I18N: %s is an individual’s name */
299            'title'          => I18N::translate('Pedigree map of %s', $individual->fullName()),
300            'tree'           => $tree,
301            'individual'     => $individual,
302            'generations'    => $generations,
303            'maxgenerations' => self::MAXIMUM_GENERATIONS,
304            'map'            => $map,
305        ]);
306    }
307
308    /**
309     * @param ServerRequestInterface $request
310     * @param ChartService           $chart_service
311     *
312     * @return array
313     */
314    private function getPedigreeMapFacts(ServerRequestInterface $request, ChartService $chart_service): array
315    {
316        $tree = $request->getAttribute('tree');
317        assert($tree instanceof Tree);
318
319        $generations = (int) $request->getQueryParams()['generations'];
320        $xref        = $request->getQueryParams()['xref'];
321        $individual  = Individual::getInstance($xref, $tree);
322        $ancestors   = $chart_service->sosaStradonitzAncestors($individual, $generations);
323        $facts       = [];
324        foreach ($ancestors as $sosa => $person) {
325            if ($person->canShow()) {
326                $birth = $person->facts(['BIRT'])->first();
327                if ($birth instanceof Fact && $birth->place()->gedcomName() !== '') {
328                    $facts[$sosa] = $birth;
329                }
330            }
331        }
332
333        return $facts;
334    }
335
336    /**
337     * @param Individual $individual
338     * @param Fact       $fact
339     * @param int        $sosa
340     *
341     * @return array
342     */
343    private function summaryData(Individual $individual, Fact $fact, int $sosa): array
344    {
345        $record      = $fact->record();
346        $name        = '';
347        $url         = '';
348        $tag         = $fact->label();
349        $addbirthtag = false;
350
351        if ($record instanceof Family) {
352            // Marriage
353            $spouse = $record->spouse($individual);
354            if ($spouse) {
355                $url  = $spouse->url();
356                $name = $spouse->fullName();
357            }
358        } elseif ($record !== $individual) {
359            // Birth of a child
360            $url  = $record->url();
361            $name = $record->fullName();
362            $tag  = GedcomTag::getLabel('_BIRT_CHIL', $record);
363        }
364
365        if ($sosa > 1) {
366            $addbirthtag = true;
367            $tag         = ucfirst($this->getSosaName($sosa));
368        }
369
370        return [
371            'tag'    => $tag,
372            'url'    => $url,
373            'name'   => $name,
374            'value'  => $fact->value(),
375            'date'   => $fact->date()->display(true),
376            'place'  => $fact->place(),
377            'addtag' => $addbirthtag,
378        ];
379    }
380
381    /**
382     * builds and returns sosa relationship name in the active language
383     *
384     * @param int $sosa Sosa number
385     *
386     * @return string
387     */
388    private function getSosaName(int $sosa): string
389    {
390        $path = '';
391
392        while ($sosa > 1) {
393            if ($sosa % 2 === 1) {
394                $path = 'mot' . $path;
395            } else {
396                $path = 'fat' . $path;
397            }
398            $sosa = intdiv($sosa, 2);
399        }
400
401        return Functions::getRelationshipNameFromPath($path);
402    }
403}
404