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