xref: /webtrees/app/Http/RequestHandlers/MapDataImportAction.php (revision 10e0649788c8d7d4974d81c048ca2b225df8f22e)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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\Exceptions\FileUploadException;
24use Fisharebest\Webtrees\FlashMessages;
25use Fisharebest\Webtrees\Gedcom;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\PlaceLocation;
28use Fisharebest\Webtrees\Registry;
29use Fisharebest\Webtrees\Services\MapDataService;
30use Illuminate\Database\Capsule\Manager as DB;
31use League\Flysystem\FilesystemException;
32use League\Flysystem\UnableToCheckFileExistence;
33use League\Flysystem\UnableToReadFile;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Message\UploadedFileInterface;
37use Psr\Http\Server\RequestHandlerInterface;
38
39use function array_filter;
40use function array_reverse;
41use function array_slice;
42use function count;
43use function fclose;
44use function fgetcsv;
45use function implode;
46use function is_numeric;
47use function json_decode;
48use function redirect;
49use function rewind;
50use function route;
51use function str_contains;
52use function stream_get_contents;
53
54use const JSON_THROW_ON_ERROR;
55use const UPLOAD_ERR_OK;
56
57/**
58 * Import geographic data.
59 */
60class MapDataImportAction implements RequestHandlerInterface
61{
62    /**
63     * This function assumes the input file layout is
64     * level followed by a variable number of placename fields
65     * followed by Longitude, Latitude, Zoom & Icon
66     *
67     * @param ServerRequestInterface $request
68     *
69     * @return ResponseInterface
70     * @throws Exception
71     */
72    public function handle(ServerRequestInterface $request): ResponseInterface
73    {
74        $data_filesystem = Registry::filesystem()->data();
75
76        $params = (array) $request->getParsedBody();
77
78        $serverfile     = $params['serverfile'] ?? '';
79        $options        = $params['import-options'] ?? '';
80        $local_file     = $request->getUploadedFiles()['localfile'] ?? null;
81
82        $places = [];
83
84        $url = route(MapDataList::class, ['parent_id' => 0]);
85
86        try {
87            $file_exists = $data_filesystem->fileExists(MapDataService::PLACES_FOLDER . $serverfile);
88        } catch (FilesystemException | UnableToCheckFileExistence $ex) {
89            $file_exists = false;
90        }
91
92
93        if ($serverfile !== '' && $file_exists) {
94            // first choice is file on server
95            try {
96                $fp = $data_filesystem->readStream(MapDataService::PLACES_FOLDER . $serverfile);
97            } catch (FilesystemException | UnableToReadFile $ex) {
98                $fp = false;
99            }
100        } elseif ($local_file instanceof UploadedFileInterface && $local_file->getError() === UPLOAD_ERR_OK) {
101            // 2nd choice is local file
102            $fp = $local_file->getStream()->detach();
103        } else {
104            throw new FileUploadException($local_file);
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        $added   = 0;
147        $updated = 0;
148
149        // Remove places with 0,0 coordinates at lower levels.
150        $callback = static fn (array $place): bool => !str_contains($place['name'], ',') || $place['longitude'] !== 0.0 || $place['latitude'] !== 0.0;
151
152        $places = array_filter($places, $callback);
153
154        foreach ($places as $place) {
155            $location = new PlaceLocation($place['name']);
156            $exists   = $location->exists();
157
158            // Only update existing records
159            if ($options === 'update' && !$exists) {
160                continue;
161            }
162
163            // Only add new records
164            if ($options === 'add' && $exists) {
165                continue;
166            }
167
168            if (!$exists) {
169                $added++;
170            }
171
172            $updated += DB::table('place_location')
173                ->where('id', '=', $location->id())
174                ->update([
175                    'latitude'  => $place['latitude'],
176                    'longitude' => $place['longitude'],
177                ]);
178        }
179
180        FlashMessages::addMessage(
181            I18N::translate('locations updated: %s, locations added: %s', I18N::number($updated), I18N::number($added)),
182            'info'
183        );
184
185        return redirect($url);
186    }
187}
188