xref: /webtrees/app/Http/RequestHandlers/MapDataImportAction.php (revision 33c746f164b5e3569fa2f04ddf7d547bd89852ee)
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        $local_file     = $request->getUploadedFiles()['localfile'] ?? null;
80
81        $places = [];
82
83        $url = route(MapDataList::class, ['parent_id' => 0]);
84
85        $fp = false;
86
87        try {
88            $file_exists = $data_filesystem->fileExists(MapDataService::PLACES_FOLDER . $serverfile);
89        } catch (FilesystemException | UnableToCheckFileExistence $ex) {
90            $file_exists = false;
91        }
92
93
94        if ($serverfile !== '' && $file_exists) {
95            // first choice is file on server
96            try {
97                $fp = $data_filesystem->readStream(MapDataService::PLACES_FOLDER . $serverfile);
98            } catch (FilesystemException | UnableToReadFile $ex) {
99                $fp = false;
100            }
101        } elseif ($local_file instanceof UploadedFileInterface && $local_file->getError() === UPLOAD_ERR_OK) {
102            // 2nd choice is local file
103            $fp = $local_file->getStream()->detach();
104        }
105
106        if ($fp === false || $fp === null) {
107            return redirect($url);
108        }
109
110        $string = stream_get_contents($fp);
111
112        // Check the file type
113        if (str_contains($string, 'FeatureCollection')) {
114            $input_array = json_decode($string, false, 512, JSON_THROW_ON_ERROR);
115
116            foreach ($input_array->features as $feature) {
117                $places[] = [
118                    'latitude'  => $feature->geometry->coordinates[1],
119                    'longitude' => $feature->geometry->coordinates[0],
120                    'name'      => $feature->properties->name,
121                ];
122            }
123        } else {
124            rewind($fp);
125            while (($row = fgetcsv($fp, 0, MapDataService::CSV_SEPARATOR)) !== false) {
126                // Skip the header
127                if (!is_numeric($row[0])) {
128                    continue;
129                }
130
131                $level = (int) $row[0];
132                $count = count($row);
133                $name  = implode(Gedcom::PLACE_SEPARATOR, array_reverse(array_slice($row, 1, 1 + $level)));
134
135                $places[] = [
136                    'latitude'  => (float) strtr($row[$count - 3], ['N' => '', 'S' => '-', ',' => '.']),
137                    'longitude' => (float) strtr($row[$count - 4], ['E' => '', 'W' => '-', ',' => '.']),
138                    'name'      => $name
139                ];
140            }
141        }
142
143        fclose($fp);
144
145        $added   = 0;
146        $updated = 0;
147
148        // Remove places with 0,0 coordinates at lower levels.
149        $callback = static fn (array $place): bool => !str_contains($place['name'], ',') || $place['longitude'] !== 0.0 || $place['latitude'] !== 0.0;
150
151        $places = array_filter($places, $callback);
152
153        foreach ($places as $place) {
154            $location = new PlaceLocation($place['name']);
155            $exists   = $location->exists();
156
157            // Only update existing records
158            if ($options === 'update' && !$exists) {
159                continue;
160            }
161
162            // Only add new records
163            if ($options === 'add' && $exists) {
164                continue;
165            }
166
167            if (!$exists) {
168                $added++;
169            }
170
171            $updated += DB::table('place_location')
172                ->where('id', '=', $location->id())
173                ->update([
174                    'latitude'  => $place['latitude'],
175                    'longitude' => $place['longitude'],
176                ]);
177        }
178
179        FlashMessages::addMessage(
180            I18N::translate('locations updated: %s, locations added: %s', I18N::number($updated), I18N::number($added)),
181            'info'
182        );
183
184        return redirect($url);
185    }
186}
187