xref: /webtrees/app/Module/PedigreeMapModule.php (revision 884ee8ff8928019b49207eaa8e65e14df114f7c1)
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 redirect;
44use function route;
45use function view;
46
47/**
48 * Class PedigreeMapModule
49 */
50class PedigreeMapModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
51{
52    use ModuleChartTrait;
53
54    private const ROUTE_NAME = 'pedigree-map';
55    private 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 LINE_COLORS = [
67        '#FF0000',
68        // Red
69        '#00FF00',
70        // Green
71        '#0000FF',
72        // Blue
73        '#FFB300',
74        // Gold
75        '#00FFFF',
76        // Cyan
77        '#FF00FF',
78        // Purple
79        '#7777FF',
80        // Light blue
81        '#80FF80'
82        // Light green
83    ];
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(self::ROUTE_NAME, self::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(self::ROUTE_NAME, [
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::LINE_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            $icon = ['color' => 'Gold', 'name' => 'bullseye '];
226            if ($latitude !== 0.0 || $longitude !== 0.0) {
227                $polyline         = null;
228                $color            = self::LINE_COLORS[log($id, 2) % $color_count];
229                $icon['color']    = $color; //make icon color the same as the line
230                $sosa_points[$id] = [$latitude, $longitude];
231                $sosa_parent      = intdiv($id, 2);
232                if (array_key_exists($sosa_parent, $sosa_points)) {
233                    // Would like to use a GeometryCollection to hold LineStrings
234                    // rather than generate polylines but the MarkerCluster library
235                    // doesn't seem to like them
236                    $polyline = [
237                        'points'  => [
238                            $sosa_points[$sosa_parent],
239                            [$latitude, $longitude],
240                        ],
241                        'options' => [
242                            'color' => $color,
243                        ],
244                    ];
245                }
246                $geojson['features'][] = [
247                    'type'       => 'Feature',
248                    'id'         => $id,
249                    'valid'      => true,
250                    'geometry'   => [
251                        'type'        => 'Point',
252                        'coordinates' => [$longitude, $latitude],
253                    ],
254                    'properties' => [
255                        'polyline' => $polyline,
256                        'icon'     => $icon,
257                        'tooltip'  => strip_tags($fact->place()->fullName()),
258                        'summary'  => view('modules/pedigree-map/events', $this->summaryData($individual, $fact, $id)),
259                        'zoom'     => $location->zoom() ?: 2,
260                    ],
261                ];
262            }
263        }
264
265        $code = empty($facts) ? StatusCodeInterface::STATUS_NO_CONTENT : StatusCodeInterface::STATUS_OK;
266
267        return response($geojson, $code);
268    }
269
270    /**
271     * @param ServerRequestInterface $request
272     *
273     * @return ResponseInterface
274     */
275    public function handle(ServerRequestInterface $request): ResponseInterface
276    {
277        $tree = $request->getAttribute('tree');
278        assert($tree instanceof Tree);
279
280        $tree        = $request->getAttribute('tree');
281        $user        = $request->getAttribute('user');
282        $xref        = $request->getAttribute('xref');
283        $generations = (int) $request->getAttribute('generations');
284        $individual  = Individual::getInstance($xref, $tree);
285
286        // Convert POST requests into GET requests for pretty URLs.
287        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
288            return redirect(route(self::ROUTE_NAME, [
289                'tree'        => $tree->name(),
290                'xref'        => $request->getParsedBody()['xref'],
291                'generations' => $request->getParsedBody()['generations'],
292            ]));
293        }
294
295        Auth::checkIndividualAccess($individual);
296        Auth::checkComponentAccess($this, 'chart', $tree, $user);
297
298        $map = view('modules/pedigree-map/chart', [
299            'module'      => $this->name(),
300            'individual'  => $individual,
301            'type'        => 'pedigree',
302            'generations' => $generations,
303        ]);
304
305        return $this->viewResponse('modules/pedigree-map/page', [
306            'module'         => $this->name(),
307            /* I18N: %s is an individual’s name */
308            'title'          => I18N::translate('Pedigree map of %s', $individual->fullName()),
309            'tree'           => $tree,
310            'individual'     => $individual,
311            'generations'    => $generations,
312            'maxgenerations' => self::MAXIMUM_GENERATIONS,
313            'map'            => $map,
314        ]);
315    }
316
317    /**
318     * @param ServerRequestInterface $request
319     * @param ChartService           $chart_service
320     *
321     * @return array
322     */
323    private function getPedigreeMapFacts(ServerRequestInterface $request, ChartService $chart_service): array
324    {
325        $tree = $request->getAttribute('tree');
326        assert($tree instanceof Tree);
327
328        $generations = (int) $request->getQueryParams()['generations'];
329        $xref        = $request->getQueryParams()['xref'];
330        $individual  = Individual::getInstance($xref, $tree);
331        $ancestors   = $chart_service->sosaStradonitzAncestors($individual, $generations);
332        $facts       = [];
333        foreach ($ancestors as $sosa => $person) {
334            if ($person->canShow()) {
335                $birth = $person->facts(['BIRT'])->first();
336                if ($birth instanceof Fact && $birth->place()->gedcomName() !== '') {
337                    $facts[$sosa] = $birth;
338                }
339            }
340        }
341
342        return $facts;
343    }
344
345    /**
346     * @param Individual $individual
347     * @param Fact       $fact
348     * @param int        $sosa
349     *
350     * @return array
351     */
352    private function summaryData(Individual $individual, Fact $fact, int $sosa): array
353    {
354        $record      = $fact->record();
355        $name        = '';
356        $url         = '';
357        $tag         = $fact->label();
358        $addbirthtag = false;
359
360        if ($record instanceof Family) {
361            // Marriage
362            $spouse = $record->spouse($individual);
363            if ($spouse) {
364                $url  = $spouse->url();
365                $name = $spouse->fullName();
366            }
367        } elseif ($record !== $individual) {
368            // Birth of a child
369            $url  = $record->url();
370            $name = $record->fullName();
371            $tag  = GedcomTag::getLabel('_BIRT_CHIL', $record);
372        }
373
374        if ($sosa > 1) {
375            $addbirthtag = true;
376            $tag         = ucfirst($this->getSosaName($sosa));
377        }
378
379        return [
380            'tag'    => $tag,
381            'url'    => $url,
382            'name'   => $name,
383            'value'  => $fact->value(),
384            'date'   => $fact->date()->display(true),
385            'place'  => $fact->place(),
386            'addtag' => $addbirthtag,
387        ];
388    }
389
390    /**
391     * builds and returns sosa relationship name in the active language
392     *
393     * @param int $sosa Sosa number
394     *
395     * @return string
396     */
397    private function getSosaName(int $sosa): string
398    {
399        $path = '';
400
401        while ($sosa > 1) {
402            if ($sosa % 2 === 1) {
403                $path = 'mot' . $path;
404            } else {
405                $path = 'fat' . $path;
406            }
407            $sosa = intdiv($sosa, 2);
408        }
409
410        return Functions::getRelationshipNameFromPath($path);
411    }
412}
413