xref: /webtrees/app/Module/PlacesModule.php (revision f397d0fdeebb0d5a9590d5ba2d4d2aae8df09df1)
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 Psr\Http\Message\ResponseInterface;
30use Psr\Http\Message\ServerRequestInterface;
31use stdClass;
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 identified in the control panel, 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 8;
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
208     * @return 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        $facts = Fact::sortFacts($facts);
227
228        return $facts->filter(static function (Fact $item): bool {
229            return $item->place()->gedcomName() !== '';
230        });
231    }
232
233    /**
234     * @param ServerRequestInterface $request
235     *
236     * @return ResponseInterface
237     */
238    public function getProviderStylesAction(ServerRequestInterface $request): ResponseInterface
239    {
240        $styles = $this->getMapProviderData($request);
241
242        return response($styles);
243    }
244
245    /**
246     * @param ServerRequestInterface $request
247     *
248     * @return array|null
249     */
250    private function getMapProviderData(ServerRequestInterface $request): ?array
251    {
252        if (self::$map_providers === null) {
253            $providersFile        = Webtrees::MODULES_DIR . '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_string(file_get_contents($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