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