xref: /webtrees/app/Module/PedigreeMapModule.php (revision 578877948456c73e8f5f48fcfab0a2814b7653ff)
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;
32
33/**
34 * Class PedigreeMapModule
35 */
36class PedigreeMapModule extends AbstractModule implements ModuleChartInterface
37{
38    const LINE_COLORS  = [
39        '#FF0000',
40        // Red
41        '#00FF00',
42        // Green
43        '#0000FF',
44        // Blue
45        '#FFB300',
46        // Gold
47        '#00FFFF',
48        // Cyan
49        '#FF00FF',
50        // Purple
51        '#7777FF',
52        // Light blue
53        '#80FF80'
54        // Light green
55    ];
56
57    private static $map_providers  = null;
58    private static $map_selections = null;
59
60    /** {@inheritdoc} */
61    public function getTitle()
62    {
63        return /* I18N: Name of a module */
64            I18N::translate('Pedigree map');
65    }
66
67    /** {@inheritdoc} */
68    public function getDescription()
69    {
70        return /* I18N: Description of the “OSM” module */
71            I18N::translate('Show the birthplace of ancestors on a map.');
72    }
73
74    /** {@inheritdoc} */
75    public function defaultAccessLevel()
76    {
77        return Auth::PRIV_PRIVATE;
78    }
79
80    /**
81     * Return a menu item for this chart.
82     *
83     * @param Individual $individual
84     *
85     * @return Menu
86     */
87    public function getChartMenu(Individual $individual)
88    {
89        return new Menu(
90            I18N::translate('Pedigree map'),
91            route('module', [
92                'module' => $this->getName(),
93                'action' => 'PedigreeMap',
94                'xref'   => $individual->getXref(),
95            ]),
96            'menu-chart-pedigreemap',
97            ['rel' => 'nofollow']
98        );
99    }
100
101    /**
102     * Return a menu item for this chart - for use in individual boxes.
103     *
104     * @param Individual $individual
105     *
106     * @return Menu
107     */
108    public function getBoxChartMenu(Individual $individual)
109    {
110        return $this->getChartMenu($individual);
111    }
112
113    /**
114     * @param Request $request
115     *
116     * @return JsonResponse
117     * @throws Exception
118     */
119    public function getMapDataAction(Request $request): JsonResponse
120    {
121        $xref        = $request->get('reference');
122        $tree        = $request->attributes->get('tree');
123        $indi        = Individual::getInstance($xref, $tree);
124        $color_count = count(self::LINE_COLORS);
125
126        $facts = $this->getPedigreeMapFacts($request);
127
128        $geojson = [
129            'type'     => 'FeatureCollection',
130            'features' => [],
131        ];
132        if (empty($facts)) {
133            $code = 204;
134        } else {
135            $code = 200;
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      = (int)floor($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
179        return new JsonResponse($geojson, $code);
180    }
181
182    /**
183     * @param Request $request
184     *
185     * @return array
186     * @throws Exception
187     */
188    private function getPedigreeMapFacts(Request $request)
189    {
190        $xref        = $request->get('reference');
191        $tree        = $request->attributes->get('tree');
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 ($item) {
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     *
307     * @return object
308     * @throws Exception
309     */
310    public function getPedigreeMapAction(Request $request)
311    {
312        /** @var Tree $tree */
313        $tree           = $request->attributes->get('tree');
314        $xref           = $request->get('xref');
315        $individual     = Individual::getInstance($xref, $tree);
316        $maxgenerations = $tree->getPreference('MAX_PEDIGREE_GENERATIONS');
317        $generations    = $request->get('generations', $tree->getPreference('DEFAULT_PEDIGREE_GENERATIONS'));
318
319        if ($individual === null) {
320            throw new IndividualNotFoundException;
321        } elseif (!$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                'title'          => /* I18N: %s is an individual’s name */
330                    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