xref: /webtrees/app/Module/PlacesModule.php (revision 4fbeb707df82fa5025e6110f443695700edd846c)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 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\Fact;
22use Fisharebest\Webtrees\Family;
23use Fisharebest\Webtrees\Functions\Functions;
24use Fisharebest\Webtrees\GedcomTag;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Individual;
27use Fisharebest\Webtrees\Location;
28use Fisharebest\Webtrees\Webtrees;
29use Illuminate\Support\Collection;
30use stdClass;
31use Symfony\Component\HttpFoundation\JsonResponse;
32use Symfony\Component\HttpFoundation\Request;
33
34/**
35 * Class PlacesMapModule
36 */
37class PlacesModule extends AbstractModule implements ModuleTabInterface
38{
39    use ModuleTabTrait;
40
41    private static $map_providers  = null;
42    private static $map_selections = null;
43
44    public const ICONS = [
45        'BIRT' => ['color' => 'Crimson', 'name' => 'birthday-cake'],
46        'MARR' => ['color' => 'Green', 'name' => 'venus-mars'],
47        'DEAT' => ['color' => 'Black', 'name' => 'plus'],
48        'CENS' => ['color' => 'MediumBlue', 'name' => 'users'],
49        'RESI' => ['color' => 'MediumBlue', 'name' => 'home'],
50        'OCCU' => ['color' => 'MediumBlue', 'name' => 'briefcase'],
51        'GRAD' => ['color' => 'MediumBlue', 'name' => 'graduation-cap'],
52        'EDUC' => ['color' => 'MediumBlue', 'name' => 'university'],
53    ];
54
55    public const DEFAULT_ICON = ['color' => 'Gold', 'name' => 'bullseye '];
56
57    /**
58     * How should this module be labelled on tabs, menus, etc.?
59     *
60     * @return string
61     */
62    public function title(): string
63    {
64        /* I18N: Name of a module */
65        return I18N::translate('Places');
66    }
67
68    /**
69     * A sentence describing what this module does.
70     *
71     * @return string
72     */
73    public function description(): string
74    {
75        /* I18N: Description of the “OSM” module */
76        return I18N::translate('Show the location of events on a map.');
77    }
78
79    /**
80     * The default position for this tab.  It can be changed in the control panel.
81     *
82     * @return int
83     */
84    public function defaultTabOrder(): int
85    {
86        return 1;
87    }
88
89    /** {@inheritdoc} */
90    public function hasTabContent(Individual $individual): bool
91    {
92        return true;
93    }
94
95    /** {@inheritdoc} */
96    public function isGrayedOut(Individual $individual): bool
97    {
98        return false;
99    }
100
101    /** {@inheritdoc} */
102    public function canLoadAjax(): bool
103    {
104        return true;
105    }
106
107    /** {@inheritdoc} */
108    public function getTabContent(Individual $individual): string
109    {
110        return view('modules/places/tab', [
111            'data' => $this->getMapData($individual),
112        ]);
113    }
114
115    /**
116     * @param Individual $indi
117     *
118     * @return stdClass
119     */
120    private function getMapData(Individual $indi): stdClass
121    {
122        $facts = $this->getPersonalFacts($indi);
123
124        $geojson = [
125            'type'     => 'FeatureCollection',
126            'features' => [],
127        ];
128
129        foreach ($facts as $id => $fact) {
130            $location = new Location($fact->place()->gedcomName());
131
132            // Use the co-ordinates from the fact (if they exist).
133            $latitude  = $fact->latitude();
134            $longitude = $fact->longitude();
135
136            // Use the co-ordinates from the location otherwise.
137            if ($latitude === 0.0 && $longitude === 0.0) {
138                $latitude  = $location->latitude();
139                $longitude = $location->longitude();
140            }
141
142            $icon = self::ICONS[$fact->getTag()] ?? self::DEFAULT_ICON;
143
144            if ($latitude !== 0.0 || $longitude !== 0.0) {
145                $geojson['features'][] = [
146                    'type'       => 'Feature',
147                    'id'         => $id,
148                    'valid'      => true,
149                    'geometry'   => [
150                        'type'        => 'Point',
151                        'coordinates' => [$longitude, $latitude],
152                    ],
153                    'properties' => [
154                        'polyline' => null,
155                        'icon'     => $icon,
156                        'tooltip'  => strip_tags($fact->place()->fullName()),
157                        'summary'  => view('modules/places/event-sidebar', $this->summaryData($indi, $fact)),
158                        'zoom'     => $location->zoom(),
159                    ],
160                ];
161            }
162        }
163
164        return (object) $geojson;
165    }
166
167    /**
168     * @param Individual $individual
169     * @param Fact       $fact
170     *
171     * @return mixed[]
172     */
173    private function summaryData(Individual $individual, Fact $fact): array
174    {
175        $record = $fact->record();
176        $name   = '';
177        $url    = '';
178        $tag    = $fact->label();
179
180        if ($record instanceof Family) {
181            // Marriage
182            $spouse = $record->spouse($individual);
183            if ($spouse instanceof Individual) {
184                $url  = $spouse->url();
185                $name = $spouse->fullName();
186            }
187        } elseif ($record !== $individual) {
188            // Birth of a child
189            $url  = $record->url();
190            $name = $record->fullName();
191            $tag  = GedcomTag::getLabel('_BIRT_CHIL', $record);
192        }
193
194        return [
195            'tag'    => $tag,
196            'url'    => $url,
197            'name'   => $name,
198            'value'  => $fact->value(),
199            'date'   => $fact->date()->display(true),
200            'place'  => $fact->place(),
201            'addtag' => false,
202        ];
203    }
204
205    /**
206     * @param Individual $individual
207     *
208     * @return Collection|Fact[]
209     * @throws Exception
210     */
211    private function getPersonalFacts(Individual $individual): Collection
212    {
213        $facts = $individual->facts();
214
215        foreach ($individual->spouseFamilies() as $family) {
216            $facts = $facts->merge($family->facts());
217            // Add birth of children from this family to the facts array
218            foreach ($family->children() as $child) {
219                $childsBirth = $child->facts(['BIRT'])->first();
220                if ($childsBirth && $childsBirth->place()->gedcomName() !== '') {
221                    $facts->push($childsBirth);
222                }
223            }
224        }
225
226        Functions::sortFacts($facts);
227
228        return $facts->filter(function (Fact $item): bool {
229            return $item->place()->gedcomName() !== '';
230        });
231    }
232
233    /**
234     * @param Request $request
235     *
236     * @return JsonResponse
237     */
238    public function getProviderStylesAction(Request $request): JsonResponse
239    {
240        $styles = $this->getMapProviderData($request);
241
242        return new JsonResponse($styles);
243    }
244
245    /**
246     * @param Request $request
247     *
248     * @return array|null
249     */
250    private function getMapProviderData(Request $request)
251    {
252        if (self::$map_providers === null) {
253            $providersFile        = WT_ROOT . Webtrees::MODULES_PATH . 'openstreetmap/providers/providers.xml';
254            self::$map_selections = [
255                'provider' => $this->getPreference('provider', 'openstreetmap'),
256                'style'    => $this->getPreference('provider_style', 'mapnik'),
257            ];
258
259            try {
260                $xml = simplexml_load_file($providersFile);
261                // need to convert xml structure into arrays & strings
262                foreach ($xml as $provider) {
263                    $style_keys = array_map(
264                        function (string $item): string {
265                            return preg_replace('/[^a-z\d]/i', '', strtolower($item));
266                        },
267                        (array) $provider->styles
268                    );
269
270                    $key = preg_replace('/[^a-z\d]/i', '', strtolower((string) $provider->name));
271
272                    self::$map_providers[$key] = [
273                        'name'   => (string) $provider->name,
274                        'styles' => array_combine($style_keys, (array) $provider->styles),
275                    ];
276                }
277            } catch (Exception $ex) {
278                // Default provider is OpenStreetMap
279                self::$map_selections = [
280                    'provider' => 'openstreetmap',
281                    'style'    => 'mapnik',
282                ];
283                self::$map_providers  = [
284                    'openstreetmap' => [
285                        'name'   => 'OpenStreetMap',
286                        'styles' => ['mapnik' => 'Mapnik'],
287                    ],
288                ];
289            };
290        }
291
292        //Ugly!!!
293        switch ($request->get('action')) {
294            case 'BaseData':
295                $varName = (self::$map_selections['style'] === '') ? '' : self::$map_providers[self::$map_selections['provider']]['styles'][self::$map_selections['style']];
296                $payload = [
297                    'selectedProvIndex' => self::$map_selections['provider'],
298                    'selectedProvName'  => self::$map_providers[self::$map_selections['provider']]['name'],
299                    'selectedStyleName' => $varName,
300                ];
301                break;
302            case 'ProviderStyles':
303                $provider = $request->get('provider', 'openstreetmap');
304                $payload  = self::$map_providers[$provider]['styles'];
305                break;
306            case 'AdminConfig':
307                $providers = [];
308                foreach (self::$map_providers as $key => $provider) {
309                    $providers[$key] = $provider['name'];
310                }
311                $payload = [
312                    'providers'     => $providers,
313                    'selectedProv'  => self::$map_selections['provider'],
314                    'styles'        => self::$map_providers[self::$map_selections['provider']]['styles'],
315                    'selectedStyle' => self::$map_selections['style'],
316                ];
317                break;
318            default:
319                $payload = null;
320        }
321
322        return $payload;
323    }
324}
325