xref: /webtrees/app/Http/RequestHandlers/MapDataImportAction.php (revision 08b5db2af7b56fafdef6563369bf89966bc0e451)
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 Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use Psr\Http\Message\UploadedFileInterface;
33use Psr\Http\Server\RequestHandlerInterface;
34
35use function array_filter;
36use function array_reverse;
37use function array_slice;
38use function count;
39use function fclose;
40use function fgetcsv;
41use function implode;
42use function is_numeric;
43use function json_decode;
44use function redirect;
45use function rewind;
46use function route;
47use function str_contains;
48use function stream_get_contents;
49
50use const JSON_THROW_ON_ERROR;
51use const UPLOAD_ERR_OK;
52
53/**
54 * Import geographic data.
55 */
56class MapDataImportAction implements RequestHandlerInterface
57{
58    /**
59     * This function assumes the input file layout is
60     * level followed by a variable number of placename fields
61     * followed by Longitude, Latitude, Zoom & Icon
62     *
63     * @param ServerRequestInterface $request
64     *
65     * @return ResponseInterface
66     * @throws Exception
67     */
68    public function handle(ServerRequestInterface $request): ResponseInterface
69    {
70        $data_filesystem = Registry::filesystem()->data();
71
72        $params = (array) $request->getParsedBody();
73
74        $serverfile     = $params['serverfile'] ?? '';
75        $options        = $params['import-options'] ?? '';
76        $clear_database = (bool) ($params['cleardatabase'] ?? false);
77        $local_file     = $request->getUploadedFiles()['localfile'] ?? null;
78
79        $places = [];
80
81        $url = route(MapDataList::class, ['parent_id' => 0]);
82
83        $fp = false;
84
85        if ($serverfile !== '' && $data_filesystem->fileExists(MapDataService::PLACES_FOLDER . $serverfile)) {
86            // first choice is file on server
87            $fp = $data_filesystem->readStream(MapDataService::PLACES_FOLDER . $serverfile);
88        } elseif ($local_file instanceof UploadedFileInterface && $local_file->getError() === UPLOAD_ERR_OK) {
89            // 2nd choice is local file
90            $fp = $local_file->getStream()->detach();
91        }
92
93        if ($fp === false || $fp === null) {
94            return redirect($url);
95        }
96
97        $string = stream_get_contents($fp);
98
99        // Check the file type
100        if (str_contains($string, 'FeatureCollection')) {
101            $input_array = json_decode($string, false, 512, JSON_THROW_ON_ERROR);
102
103            foreach ($input_array->features as $feature) {
104                $places[] = [
105                    'latitude'  => $feature->geometry->coordinates[1],
106                    'longitude' => $feature->geometry->coordinates[0],
107                    'name'      => $feature->properties->name,
108                ];
109            }
110        } else {
111            rewind($fp);
112            while (($row = fgetcsv($fp, 0, MapDataService::CSV_SEPARATOR)) !== false) {
113                // Skip the header
114                if (!is_numeric($row[0])) {
115                    continue;
116                }
117
118                $level = (int) $row[0];
119                $count = count($row);
120                $name  = implode(Gedcom::PLACE_SEPARATOR, array_reverse(array_slice($row, 1, 1 + $level)));
121
122                $places[] = [
123                    'latitude'  => (float) strtr($row[$count - 3], ['N' => '', 'S' => '-', ',' => '.']),
124                    'longitude' => (float) strtr($row[$count - 4], ['E' => '', 'W' => '-', ',' => '.']),
125                    'name'      => $name
126                ];
127            }
128        }
129
130        fclose($fp);
131
132        if ($clear_database) {
133            // Child places are deleted via on-delete-cascade...
134            DB::table('place_location')
135                ->whereNull('parent_id')
136                ->delete();
137        }
138
139        $added   = 0;
140        $updated = 0;
141
142        // Remove places with 0,0 coordinates at lower levels.
143        $places = array_filter($places, static function ($place) {
144            return !str_contains($place['name'], ',') || $place['longitude'] !== 0.0 || $place['latitude'] !== 0.0;
145        });
146
147        foreach ($places as $place) {
148            $location = new PlaceLocation($place['name']);
149            $exists   = $location->exists();
150
151            // Only update existing records
152            if ($options === 'update' && !$exists) {
153                continue;
154            }
155
156            // Only add new records
157            if ($options === 'add' && $exists) {
158                continue;
159            }
160
161            if (!$exists) {
162                $added++;
163            }
164
165            $updated += DB::table('place_location')
166                ->where('id', '=', $location->id())
167                ->update([
168                    'latitude'  => $place['latitude'],
169                    'longitude' => $place['longitude'],
170                ]);
171        }
172
173        FlashMessages::addMessage(
174            I18N::translate('locations updated: %s, locations added: %s', I18N::number($updated), I18N::number($added)),
175            'info'
176        );
177
178        return redirect($url);
179    }
180}
181