xref: /webtrees/app/Http/RequestHandlers/MapDataImportAction.php (revision df93626bb52ff48b14844baf8098f2fc320d4155)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Exception;
23use Fisharebest\Webtrees\FlashMessages;
24use Fisharebest\Webtrees\Gedcom;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\PlaceLocation;
27use Fisharebest\Webtrees\Registry;
28use Fisharebest\Webtrees\Services\MapDataService;
29use Illuminate\Database\Capsule\Manager as DB;
30use League\Flysystem\FilesystemException;
31use League\Flysystem\UnableToCheckFileExistence;
32use League\Flysystem\UnableToReadFile;
33use Psr\Http\Message\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35use Psr\Http\Message\UploadedFileInterface;
36use Psr\Http\Server\RequestHandlerInterface;
37
38use function array_filter;
39use function array_reverse;
40use function array_slice;
41use function count;
42use function fclose;
43use function fgetcsv;
44use function implode;
45use function is_numeric;
46use function json_decode;
47use function redirect;
48use function rewind;
49use function route;
50use function str_contains;
51use function stream_get_contents;
52
53use const JSON_THROW_ON_ERROR;
54use const UPLOAD_ERR_OK;
55
56/**
57 * Import geographic data.
58 */
59class MapDataImportAction implements RequestHandlerInterface
60{
61    /**
62     * This function assumes the input file layout is
63     * level followed by a variable number of placename fields
64     * followed by Longitude, Latitude, Zoom & Icon
65     *
66     * @param ServerRequestInterface $request
67     *
68     * @return ResponseInterface
69     * @throws Exception
70     */
71    public function handle(ServerRequestInterface $request): ResponseInterface
72    {
73        $data_filesystem = Registry::filesystem()->data();
74
75        $params = (array) $request->getParsedBody();
76
77        $serverfile     = $params['serverfile'] ?? '';
78        $options        = $params['import-options'] ?? '';
79        $clear_database = (bool) ($params['cleardatabase'] ?? false);
80        $local_file     = $request->getUploadedFiles()['localfile'] ?? null;
81
82        $places = [];
83
84        $url = route(MapDataList::class, ['parent_id' => 0]);
85
86        $fp = false;
87
88        try {
89            $file_exists = $data_filesystem->fileExists(MapDataService::PLACES_FOLDER . $serverfile);
90        } catch (FilesystemException | UnableToCheckFileExistence $ex) {
91            $file_exists = false;
92        }
93
94
95        if ($serverfile !== '' && $file_exists) {
96            // first choice is file on server
97            try {
98                $fp = $data_filesystem->readStream(MapDataService::PLACES_FOLDER . $serverfile);
99            } catch (FilesystemException | UnableToReadFile $ex) {
100                $fp = false;
101            }
102        } elseif ($local_file instanceof UploadedFileInterface && $local_file->getError() === UPLOAD_ERR_OK) {
103            // 2nd choice is local file
104            $fp = $local_file->getStream()->detach();
105        }
106
107        if ($fp === false || $fp === null) {
108            return redirect($url);
109        }
110
111        $string = stream_get_contents($fp);
112
113        // Check the file type
114        if (str_contains($string, 'FeatureCollection')) {
115            $input_array = json_decode($string, false, 512, JSON_THROW_ON_ERROR);
116
117            foreach ($input_array->features as $feature) {
118                $places[] = [
119                    'latitude'  => $feature->geometry->coordinates[1],
120                    'longitude' => $feature->geometry->coordinates[0],
121                    'name'      => $feature->properties->name,
122                ];
123            }
124        } else {
125            rewind($fp);
126            while (($row = fgetcsv($fp, 0, MapDataService::CSV_SEPARATOR)) !== false) {
127                // Skip the header
128                if (!is_numeric($row[0])) {
129                    continue;
130                }
131
132                $level = (int) $row[0];
133                $count = count($row);
134                $name  = implode(Gedcom::PLACE_SEPARATOR, array_reverse(array_slice($row, 1, 1 + $level)));
135
136                $places[] = [
137                    'latitude'  => (float) strtr($row[$count - 3], ['N' => '', 'S' => '-', ',' => '.']),
138                    'longitude' => (float) strtr($row[$count - 4], ['E' => '', 'W' => '-', ',' => '.']),
139                    'name'      => $name
140                ];
141            }
142        }
143
144        fclose($fp);
145
146        if ($clear_database) {
147            // Child places are deleted via on-delete-cascade...
148            DB::table('place_location')
149                ->whereNull('parent_id')
150                ->delete();
151        }
152
153        $added   = 0;
154        $updated = 0;
155
156        // Remove places with 0,0 coordinates at lower levels.
157        $places = array_filter($places, static function ($place) {
158            return !str_contains($place['name'], ',') || $place['longitude'] !== 0.0 || $place['latitude'] !== 0.0;
159        });
160
161        foreach ($places as $place) {
162            $location = new PlaceLocation($place['name']);
163            $exists   = $location->exists();
164
165            // Only update existing records
166            if ($options === 'update' && !$exists) {
167                continue;
168            }
169
170            // Only add new records
171            if ($options === 'add' && $exists) {
172                continue;
173            }
174
175            if (!$exists) {
176                $added++;
177            }
178
179            $updated += DB::table('place_location')
180                ->where('id', '=', $location->id())
181                ->update([
182                    'latitude'  => $place['latitude'],
183                    'longitude' => $place['longitude'],
184                ]);
185        }
186
187        FlashMessages::addMessage(
188            I18N::translate('locations updated: %s, locations added: %s', I18N::number($updated), I18N::number($added)),
189            'info'
190        );
191
192        return redirect($url);
193    }
194}
195