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