xref: /webtrees/app/Module/PedigreeMapModule.php (revision 299ca8d22e0b70bd405b788311c6116987f1ba96)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Module;
19
20use Exception;
21use Fisharebest\Webtrees\Auth;
22use Fisharebest\Webtrees\Exceptions\IndividualAccessDeniedException;
23use Fisharebest\Webtrees\Exceptions\IndividualNotFoundException;
24use Fisharebest\Webtrees\Fact;
25use Fisharebest\Webtrees\FactLocation;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Individual;
28use Fisharebest\Webtrees\Menu;
29use Fisharebest\Webtrees\Tree;
30use Symfony\Component\HttpFoundation\JsonResponse;
31use Symfony\Component\HttpFoundation\Request;
32use Symfony\Component\HttpFoundation\Response;
33
34/**
35 * Class PedigreeMapModule
36 */
37class PedigreeMapModule extends AbstractModule implements ModuleChartInterface
38{
39    const LINE_COLORS = [
40        '#FF0000',
41        // Red
42        '#00FF00',
43        // Green
44        '#0000FF',
45        // Blue
46        '#FFB300',
47        // Gold
48        '#00FFFF',
49        // Cyan
50        '#FF00FF',
51        // Purple
52        '#7777FF',
53        // Light blue
54        '#80FF80'
55        // Light green
56    ];
57
58    private static $map_providers  = null;
59    private static $map_selections = null;
60
61    /** {@inheritdoc} */
62    public function getTitle(): string
63    {
64        /* I18N: Name of a module */
65        return I18N::translate('Pedigree map');
66    }
67
68    /** {@inheritdoc} */
69    public function getDescription(): string
70    {
71        /* I18N: Description of the “OSM” module */
72        return I18N::translate('Show the birthplace of ancestors on a map.');
73    }
74
75    /** {@inheritdoc} */
76    public function defaultAccessLevel(): int
77    {
78        return Auth::PRIV_PRIVATE;
79    }
80
81    /**
82     * Return a menu item for this chart.
83     *
84     * @param Individual $individual
85     *
86     * @return Menu
87     */
88    public function getChartMenu(Individual $individual): Menu
89    {
90        return new Menu(
91            I18N::translate('Pedigree map'),
92            route('module', [
93                'module' => $this->getName(),
94                'action' => 'PedigreeMap',
95                'xref'   => $individual->getXref(),
96                'ged'    => $individual->getTree()->getName(),
97            ]),
98            'menu-chart-pedigreemap',
99            ['rel' => 'nofollow']
100        );
101    }
102
103    /**
104     * Return a menu item for this chart - for use in individual boxes.
105     *
106     * @param Individual $individual
107     *
108     * @return Menu
109     */
110    public function getBoxChartMenu(Individual $individual): Menu
111    {
112        return $this->getChartMenu($individual);
113    }
114
115    /**
116     * @param Request $request
117     * @param Tree    $tree
118     *
119     * @return JsonResponse
120     */
121    public function getMapDataAction(Request $request, Tree $tree): JsonResponse
122    {
123        $xref        = $request->get('reference');
124        $indi        = Individual::getInstance($xref, $tree);
125        $color_count = count(self::LINE_COLORS);
126
127        $facts = $this->getPedigreeMapFacts($request, $tree);
128
129        $geojson = [
130            'type'     => 'FeatureCollection',
131            'features' => [],
132        ];
133
134        $sosa_points = [];
135
136        foreach ($facts as $id => $fact) {
137            $event = new FactLocation($fact, $indi);
138            $icon  = $event->getIconDetails();
139            if ($event->knownLatLon()) {
140                $polyline         = null;
141                $color            = self::LINE_COLORS[log($id, 2) % $color_count];
142                $icon['color']    = $color; //make icon color the same as the line
143                $sosa_points[$id] = $event->getLatLonJSArray();
144                $sosa_parent      = intdiv($id, 2);
145                if (array_key_exists($sosa_parent, $sosa_points)) {
146                    // Would like to use a GeometryCollection to hold LineStrings
147                    // rather than generate polylines but the MarkerCluster library
148                    // doesn't seem to like them
149                    $polyline = [
150                        'points'  => [
151                            $sosa_points[$sosa_parent],
152                            $event->getLatLonJSArray(),
153                        ],
154                        'options' => [
155                            'color' => $color,
156                        ],
157                    ];
158                }
159                $geojson['features'][] = [
160                    'type'       => 'Feature',
161                    'id'         => $id,
162                    'valid'      => true,
163                    'geometry'   => [
164                        'type'        => 'Point',
165                        'coordinates' => $event->getGeoJsonCoords(),
166                    ],
167                    'properties' => [
168                        'polyline' => $polyline,
169                        'icon'     => $icon,
170                        'tooltip'  => $event->toolTip(),
171                        'summary'  => view('modules/pedigree-map/event-sidebar', $event->shortSummary('pedigree', $id)),
172                        'zoom'     => (int) $event->getZoom(),
173                    ],
174                ];
175            }
176        }
177
178        $code = empty($facts) ? Response::HTTP_NO_CONTENT : Response::HTTP_OK;
179
180        return new JsonResponse($geojson, $code);
181    }
182
183    /**
184     * @param Request $request
185     * @param Tree    $tree
186     *
187     * @return array
188     */
189    private function getPedigreeMapFacts(Request $request, Tree $tree): array
190    {
191        $xref        = $request->get('reference');
192        $individual  = Individual::getInstance($xref, $tree);
193        $generations = (int) $request->get(
194            'generations',
195            $tree->getPreference('DEFAULT_PEDIGREE_GENERATIONS')
196        );
197        $ancestors   = $this->sosaStradonitzAncestors($individual, $generations);
198        $facts       = [];
199        foreach ($ancestors as $sosa => $person) {
200            if ($person !== null && $person->canShow()) {
201                /** @var Fact $birth */
202                $birth = $person->getFirstFact('BIRT');
203                if ($birth && !$birth->getPlace()->isEmpty()) {
204                    $facts[$sosa] = $birth;
205                }
206            }
207        }
208
209        return $facts;
210    }
211
212    /**
213     * @param Request $request
214     *
215     * @return JsonResponse
216     */
217    public function getProviderStylesAction(Request $request): JsonResponse
218    {
219        $styles = $this->getMapProviderData($request);
220
221        return new JsonResponse($styles);
222    }
223
224    /**
225     * @param Request $request
226     *
227     * @return array|null
228     */
229    private function getMapProviderData(Request $request)
230    {
231        if (self::$map_providers === null) {
232            $providersFile        = WT_ROOT . WT_MODULES_DIR . 'openstreetmap/providers/providers.xml';
233            self::$map_selections = [
234                'provider' => $this->getPreference('provider', 'openstreetmap'),
235                'style'    => $this->getPreference('provider_style', 'mapnik'),
236            ];
237
238            try {
239                $xml = simplexml_load_file($providersFile);
240                // need to convert xml structure into arrays & strings
241                foreach ($xml as $provider) {
242                    $style_keys = array_map(
243                        function (string $item): string {
244                            return preg_replace('/[^a-z\d]/i', '', strtolower($item));
245                        },
246                        (array) $provider->styles
247                    );
248
249                    $key = preg_replace('/[^a-z\d]/i', '', strtolower((string) $provider->name));
250
251                    self::$map_providers[$key] = [
252                        'name'   => (string) $provider->name,
253                        'styles' => array_combine($style_keys, (array) $provider->styles),
254                    ];
255                }
256            } catch (Exception $ex) {
257                // Default provider is OpenStreetMap
258                self::$map_selections = [
259                    'provider' => 'openstreetmap',
260                    'style'    => 'mapnik',
261                ];
262                self::$map_providers = [
263                    'openstreetmap' => [
264                        'name'   => 'OpenStreetMap',
265                        'styles' => ['mapnik' => 'Mapnik'],
266                    ],
267                ];
268            };
269        }
270
271        //Ugly!!!
272        switch ($request->get('action')) {
273            case 'BaseData':
274                $varName = (self::$map_selections['style'] === '') ? '' : self::$map_providers[self::$map_selections['provider']]['styles'][self::$map_selections['style']];
275                $payload = [
276                    'selectedProvIndex' => self::$map_selections['provider'],
277                    'selectedProvName'  => self::$map_providers[self::$map_selections['provider']]['name'],
278                    'selectedStyleName' => $varName,
279                ];
280                break;
281            case 'ProviderStyles':
282                $provider = $request->get('provider', 'openstreetmap');
283                $payload  = self::$map_providers[$provider]['styles'];
284                break;
285            case 'AdminConfig':
286                $providers = [];
287                foreach (self::$map_providers as $key => $provider) {
288                    $providers[$key] = $provider['name'];
289                }
290                $payload = [
291                    'providers'     => $providers,
292                    'selectedProv'  => self::$map_selections['provider'],
293                    'styles'        => self::$map_providers[self::$map_selections['provider']]['styles'],
294                    'selectedStyle' => self::$map_selections['style'],
295                ];
296                break;
297            default:
298                $payload = null;
299        }
300
301        return $payload;
302    }
303
304    /**
305     * @param Request $request
306     * @param Tree    $tree
307     *
308     * @return object
309     */
310    public function getPedigreeMapAction(Request $request, Tree $tree)
311    {
312        $xref           = $request->get('xref');
313        $individual     = Individual::getInstance($xref, $tree);
314        $maxgenerations = $tree->getPreference('MAX_PEDIGREE_GENERATIONS');
315        $generations    = $request->get('generations', $tree->getPreference('DEFAULT_PEDIGREE_GENERATIONS'));
316
317        if ($individual === null) {
318            throw new IndividualNotFoundException();
319        }
320
321        if (!$individual->canShow()) {
322            throw new IndividualAccessDeniedException();
323        }
324
325        return (object) [
326            'name' => 'modules/pedigree-map/pedigree-map-page',
327            'data' => [
328                'module'         => $this->getName(),
329                /* I18N: %s is an individual’s name */
330                'title'          => I18N::translate('Pedigree map of %s', $individual->getFullName()),
331                'tree'           => $tree,
332                'individual'     => $individual,
333                'generations'    => $generations,
334                'maxgenerations' => $maxgenerations,
335                'map'            => view(
336                    'modules/pedigree-map/pedigree-map',
337                    [
338                        'module'      => $this->getName(),
339                        'ref'         => $individual->getXref(),
340                        'type'        => 'pedigree',
341                        'generations' => $generations,
342                    ]
343                ),
344            ],
345        ];
346    }
347
348    // @TODO shift the following function to somewhere more appropriate during restructure
349
350    /**
351     * Copied from AbstractChartController.php
352     *
353     * Find the ancestors of an individual, and generate an array indexed by
354     * Sosa-Stradonitz number.
355     *
356     * @param Individual $individual  Start with this individual
357     * @param int        $generations Fetch this number of generations
358     *
359     * @return Individual[]
360     */
361    private function sosaStradonitzAncestors(Individual $individual, int $generations): array
362    {
363        /** @var Individual[] $ancestors */
364        $ancestors = [
365            1 => $individual,
366        ];
367
368        for ($i = 1, $max = 2 ** ($generations - 1); $i < $max; $i++) {
369            $ancestors[$i * 2]     = null;
370            $ancestors[$i * 2 + 1] = null;
371
372            $individual = $ancestors[$i];
373
374            if ($individual !== null) {
375                $family = $individual->getPrimaryChildFamily();
376                if ($family !== null) {
377                    if ($family->getHusband() !== null) {
378                        $ancestors[$i * 2] = $family->getHusband();
379                    }
380                    if ($family->getWife() !== null) {
381                        $ancestors[$i * 2 + 1] = $family->getWife();
382                    }
383                }
384            }
385        }
386
387        return $ancestors;
388    }
389}
390