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