Completed
Pull Request — master (#3652)
by
unknown
06:05
created

LocationController::mapDataSave()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 52
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 39
nc 3
nop 1
dl 0
loc 52
rs 8.6737
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Http\Controllers\Admin;
21
22
use Exception;
23
use Fisharebest\Webtrees\FlashMessages;
24
use Fisharebest\Webtrees\Gedcom;
25
use Fisharebest\Webtrees\Http\RequestHandlers\ControlPanel;
26
use Fisharebest\Webtrees\Http\RequestHandlers\MapDataList;
27
use Fisharebest\Webtrees\I18N;
28
use Fisharebest\Webtrees\PlaceLocation;
29
use Fisharebest\Webtrees\Registry;
30
use Fisharebest\Webtrees\Services\GedcomService;
31
use Illuminate\Database\Capsule\Manager as DB;
32
use Illuminate\Database\Eloquent\Collection;
33
use Illuminate\Database\Query\Expression;
34
use Psr\Http\Message\ResponseInterface;
35
use Psr\Http\Message\ServerRequestInterface;
36
use Psr\Http\Message\UploadedFileInterface;
37
use RuntimeException;
38
use stdClass;
39
40
use function addcslashes;
41
use function array_filter;
42
use function array_merge;
43
use function array_pad;
44
use function array_reverse;
45
use function array_slice;
46
use function assert;
47
use function count;
48
use function e;
49
use function fclose;
50
use function fgetcsv;
51
use function fopen;
52
use function fputcsv;
53
use function implode;
54
use function is_numeric;
55
use function json_decode;
56
use function preg_replace;
57
use function redirect;
58
use function response;
59
use function rewind;
60
use function route;
61
use function str_replace;
62
use function stream_get_contents;
63
use function stripos;
64
use function substr_count;
65
66
use const UPLOAD_ERR_OK;
67
68
/**
69
 * Controller for maintaining geographic data.
70
 */
71
class LocationController extends AbstractAdminController
72
{
73
    // Location of files to import
74
    private const PLACES_FOLDER = 'places/';
75
76
    /** @var GedcomService */
77
    private $gedcom_service;
78
79
    /**
80
     * Dependency injection.
81
     *
82
     * @param GedcomService $gedcom_service
83
     */
84
    public function __construct(GedcomService $gedcom_service)
85
    {
86
        $this->gedcom_service = $gedcom_service;
87
    }
88
89
    /**
90
     * @param int $id
91
     *
92
     * @return array<stdClass>
93
     */
94
    private function getHierarchy(int $id): array
95
    {
96
        $arr  = [];
97
        $fqpn = [];
98
99
        while ($id !== 0) {
100
            $row = DB::table('placelocation')
101
                ->where('pl_id', '=', $id)
102
                ->first();
103
104
            // For static analysis tools.
105
            assert($row instanceof stdClass);
106
107
            $fqpn[]    = $row->pl_place;
108
            $row->fqpn = implode(Gedcom::PLACE_SEPARATOR, $fqpn);
109
            $id        = (int) $row->pl_parent_id;
110
            $arr[]     = $row;
111
        }
112
113
        return array_reverse($arr);
114
    }
115
116
    /**
117
     * @param ServerRequestInterface $request
118
     *
119
     * @return ResponseInterface
120
     */
121
    public function mapDataEdit(ServerRequestInterface $request): ResponseInterface
122
    {
123
        $parent_id = (int) $request->getQueryParams()['parent_id'];
124
        $hierarchy = $this->getHierarchy($parent_id);
125
        $fqpn      = $hierarchy === [] ? '' : $hierarchy[0]->fqpn;
126
        $parent    = new PlaceLocation($fqpn);
127
128
        $place_id  = (int) $request->getQueryParams()['place_id'];
129
        $hierarchy = $this->getHierarchy($place_id);
130
        $fqpn      = $hierarchy === [] ? '' : $hierarchy[0]->fqpn;
131
        $location  = new PlaceLocation($fqpn);
132
133
        if ($location->id() !== 0) {
134
            $title = e($location->locationName());
135
        } else {
136
            // Add a place
137
            if ($parent_id === 0) {
138
                // We're at the global level so create a minimal
139
                // place for the page title and breadcrumbs
140
                $title     = I18N::translate('World');
141
                $hierarchy = [];
142
            } else {
143
                $hierarchy = $this->getHierarchy($parent_id);
144
                $tmp       = new PlaceLocation($hierarchy[0]->fqpn);
145
                $title     = e($tmp->locationName());
146
147
                if ($tmp->latitude() === 0.0 && $tmp->longitude() === 0.0) {
0 ignored issues
show
introduced by
The condition $tmp->latitude() === 0.0 is always false.
Loading history...
148
                    FlashMessages::addMessage(I18N::translate('%s (coordinates [0,0]) cannot have a subordinate place', $title), 'warning');
149
150
                    return redirect(route(MapDataList::class, ['parent_id' => 0]));
151
                }
152
            }
153
        }
154
155
        $breadcrumbs = [
156
            route(ControlPanel::class) => I18N::translate('Control panel'),
157
            route(MapDataList::class)  => I18N::translate('Geographic data'),
158
        ];
159
160
        foreach ($hierarchy as $row) {
161
            $breadcrumbs[route(MapDataList::class, ['parent_id' => $row->pl_id])] = e($row->pl_place);
162
        }
163
164
        if ($place_id === 0) {
165
            $title .= ' — ' . I18N::translate('Add');
166
            $breadcrumbs[] = I18N::translate('Add');
167
            $latitude      = null;
168
            $longitude     = null;
169
            $map_bounds    = $parent->boundingRectangle();
170
        } else {
171
            $title .= ' — ' . I18N::translate('Edit');
172
            $breadcrumbs[] = I18N::translate('Edit');
173
            $latitude      = $location->latitude();
174
            $longitude     = $location->longitude();
175
            $map_bounds    = $location->boundingRectangle();
176
        }
177
178
        // If the current co-ordinates are unknown, leave the input fields empty,
179
        // and show a marker in the middle of the map.
180
        if ($latitude === null || $longitude === null) {
181
            $marker_position = [
182
                ($map_bounds[0][0] + $map_bounds[1][0]) / 2.0,
183
                ($map_bounds[0][1] + $map_bounds[1][1]) / 2.0,
184
            ];
185
        } else {
186
            $marker_position = [$latitude, $longitude];
187
        }
188
189
        return $this->viewResponse('admin/location-edit', [
190
            'breadcrumbs'     => $breadcrumbs,
191
            'title'           => $title,
192
            'location'        => $location,
193
            'latitude'        => $latitude,
194
            'longitude'       => $longitude,
195
            'map_bounds'      => $map_bounds,
196
            'marker_position' => $marker_position,
197
            'parent'          => $parent,
198
            'level'           => $parent_id,
199
            'provider'        => [
200
                'url'     => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
201
                'options' => [
202
                    'attribution' => '<a href="https://www.openstreetmap.org/copyright">&copy; OpenStreetMap</a> contributors',
203
                    'max_zoom'    => 19
204
                ]
205
            ],
206
        ]);
207
    }
208
209
    /**
210
     * @param ServerRequestInterface $request
211
     *
212
     * @return ResponseInterface
213
     */
214
    public function mapDataSave(ServerRequestInterface $request): ResponseInterface
215
    {
216
        $params = (array) $request->getParsedBody();
217
218
        $parent_id = (int) $request->getQueryParams()['parent_id'];
219
        $place_id  = (int) $request->getQueryParams()['place_id'];
220
        $lat       = $this->gedcom_service->writeLatitude((float) $params['new_place_lati']);
221
        $lng       = $this->gedcom_service->writeLongitude((float) $params['new_place_long']);
222
        $hierarchy = $this->getHierarchy($parent_id);
223
        $level     = count($hierarchy);
224
        $icon      = $params['icon'] ?: null;
225
        $zoom      = (int) $params['new_zoom_factor'];
226
227
        if ($parent_id > 0 && $lat === 'N0' && $lng === 'E0') {
228
            FlashMessages::addMessage(I18N::translate('Location [0,0] cannot be subordinate to another place'), 'warning');
229
        } else {
230
            if ($place_id === 0) {
231
                $place_id = 1 + (int) DB::table('placelocation')->max('pl_id');
232
233
                DB::table('placelocation')->insert([
234
                    'pl_id'        => $place_id,
235
                    'pl_parent_id' => $parent_id,
236
                    'pl_level'     => $level,
237
                    'pl_place'     => mb_substr($params['new_place_name'], 0, 120),
238
                    'pl_lati'      => $lat,
239
                    'pl_long'      => $lng,
240
                    'pl_zoom'      => $zoom,
241
                    'pl_icon'      => $icon,
242
                ]);
243
            } else {
244
                DB::table('placelocation')
245
                ->where('pl_id', '=', $place_id)
246
                    ->update([
247
                        'pl_place' => mb_substr($params['new_place_name'], 0, 120),
248
                        'pl_lati'  => $lat,
249
                        'pl_long'  => $lng,
250
                        'pl_zoom'  => $zoom,
251
                        'pl_icon'  => $icon,
252
                    ]);
253
            }
254
255
            FlashMessages::addMessage(
256
                I18N::translate(
257
                    'The details for “%s” have been updated.',
258
                    e($params['new_place_name'])
259
                ),
260
                'success'
261
            );
262
        }
263
        $url = route(MapDataList::class, ['parent_id' => $parent_id]);
264
265
        return redirect($url);
266
    }
267
268
    /**
269
     * @param ServerRequestInterface $request
270
     *
271
     * @return ResponseInterface
272
     */
273
    public function exportLocations(ServerRequestInterface $request): ResponseInterface
274
    {
275
        $parent_id = (int) $request->getQueryParams()['parent_id'];
276
        $format    = $request->getQueryParams()['format'];
277
        $hierarchy = $this->getHierarchy($parent_id);
278
279
        // Create the file name
280
        // $hierarchy[0] always holds the full placename
281
        $place_name = $hierarchy === [] ? 'Global' : $hierarchy[0]->fqpn;
282
        $place_name = str_replace(Gedcom::PLACE_SEPARATOR, '-', $place_name);
283
        $filename   = addcslashes('Places-' . preg_replace('/[^a-zA-Z0-9.-]/', '', $place_name), '"');
284
285
        // Fill in the place names for the starting conditions
286
        $startfqpn = [];
287
        foreach ($hierarchy as $record) {
288
            $startfqpn[] = $record->pl_place;
289
        }
290
291
        // Generate an array containing the data to output.
292
        $places = [];
293
        $this->buildExport($parent_id, $startfqpn, $places);
294
295
        // Pad all locations to the length of the longest.
296
        $max_level = 0;
297
        foreach ($places as $place) {
298
            $max_level = max($max_level, count($place->fqpn));
299
        }
300
301
        $places = array_map(static function (stdClass $place) use ($max_level): array {
302
            return array_merge(
303
                [count($place->fqpn) - 1],
304
                array_pad($place->fqpn, $max_level, ''),
305
                [$place->pl_long],
306
                [$place->pl_lati],
307
                [$place->pl_zoom],
308
                [$place->pl_icon]
309
            );
310
        }, $places);
311
312
        if ($format === 'csv') {
313
            // Create the header line for the output file (always English)
314
            $header = [
315
                'Level',
316
            ];
317
318
            for ($i = 0; $i < $max_level; $i++) {
319
                $header[] = 'Place' . $i;
320
            }
321
322
            $header[] = 'Longitude';
323
            $header[] = 'Latitude';
324
            $header[] = 'Zoom';
325
            $header[] = 'Icon';
326
327
            return $this->exportCSV($filename . '.csv', $header, $places);
328
        }
329
330
        return $this->exportGeoJSON($filename . '.geojson', $places, $max_level);
331
    }
332
333
    /**
334
     * @param int             $parent_id
335
     * @param array<string>   $fqpn
336
     * @param array<stdClass> $places
337
     *
338
     * @return void
339
     * @throws Exception
340
     */
341
    private function buildExport(int $parent_id, array $fqpn, array &$places): void
342
    {
343
        // Current number of levels.
344
        $level = count($fqpn);
345
346
        // Data for the next level.
347
        $rows = DB::table('placelocation')
348
            ->where('pl_parent_id', '=', $parent_id)
349
            ->whereNotNull('pl_lati')
350
            ->whereNotNull('pl_long')
351
            ->orderBy(new Expression('pl_place /*! COLLATE ' . I18N::collation() . ' */'))
352
            ->get();
353
354
        foreach ($rows as $row) {
355
            $fqpn[$level] = $row->pl_place;
356
357
            $row->fqpn    = $fqpn;
358
            $row->pl_zoom = (int) $row->pl_zoom;
359
            $row->pl_icon = (string) $row->pl_icon;
360
361
            $places[] = $row;
362
363
            $this->buildExport((int) $row->pl_id, $fqpn, $places);
364
        }
365
    }
366
367
    /**
368
     * @param string     $filename
369
     * @param string[]   $columns
370
     * @param string[][] $places
371
     *
372
     * @return ResponseInterface
373
     */
374
    private function exportCSV(string $filename, array $columns, array $places): ResponseInterface
375
    {
376
        $resource = fopen('php://temp', 'wb+');
377
378
        if ($resource === false) {
379
            throw new RuntimeException('Failed to create temporary stream');
380
        }
381
382
        fputcsv($resource, $columns, ';');
383
384
        foreach ($places as $place) {
385
            fputcsv($resource, $place, ';');
386
        }
387
388
        rewind($resource);
389
390
        return response(stream_get_contents($resource))
391
            ->withHeader('Content-Type', 'text/csv; charset=utf-8')
392
            ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
393
    }
394
395
    /**
396
     * @param string $filename
397
     * @param array  $rows
398
     * @param int    $maxlevel
399
     *
400
     * @return ResponseInterface
401
     */
402
    private function exportGeoJSON(string $filename, array $rows, int $maxlevel): ResponseInterface
403
    {
404
        $geojson = [
405
            'type'     => 'FeatureCollection',
406
            'features' => [],
407
        ];
408
        foreach ($rows as $place) {
409
            $fqpn = implode(
410
                Gedcom::PLACE_SEPARATOR,
411
                array_reverse(
412
                    array_filter(
413
                        array_slice($place, 1, $maxlevel)
414
                    )
415
                )
416
            );
417
418
            $geojson['features'][] = [
419
                'type'       => 'Feature',
420
                'geometry'   => [
421
                    'type'        => 'Point',
422
                    'coordinates' => [
423
                        $this->gedcom_service->readLongitude($place[$maxlevel + 1]),
424
                        $this->gedcom_service->readLatitude($place[$maxlevel + 2]),
425
                    ],
426
                ],
427
                'properties' => [
428
                    'name' => $fqpn,
429
                ],
430
            ];
431
        }
432
433
        return response($geojson)
434
            ->withHeader('Content-Type', 'application/vnd.geo+json')
435
            ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
436
    }
437
438
    /**
439
     * @param ServerRequestInterface $request
440
     *
441
     * @return ResponseInterface
442
     */
443
    public function importLocations(ServerRequestInterface $request): ResponseInterface
444
    {
445
        $data_filesystem      = Registry::filesystem()->data();
446
        $data_filesystem_name = Registry::filesystem()->dataName();
447
448
        $parent_id = (int) $request->getQueryParams()['parent_id'];
449
450
        $files = Collection::make($data_filesystem->listContents('places'))
451
            ->filter(static function (array $metadata): bool {
452
                $extension = strtolower($metadata['extension'] ?? '');
453
454
                return $extension === 'csv' || $extension === 'geojson';
455
            })
456
            ->map(static function (array $metadata): string {
457
                return $metadata['basename'];
458
            })
459
            ->sort();
460
461
        return $this->viewResponse('admin/map-import-form', [
462
            'place_folder' => $data_filesystem_name . self::PLACES_FOLDER,
463
            'title'        => I18N::translate('Import geographic data'),
464
            'parent_id'    => $parent_id,
465
            'files'        => $files,
466
        ]);
467
    }
468
469
    /**
470
     * This function assumes the input file layout is
471
     * level followed by a variable number of placename fields
472
     * followed by Longitude, Latitude, Zoom & Icon
473
     *
474
     * @param ServerRequestInterface $request
475
     *
476
     * @return ResponseInterface
477
     * @throws Exception
478
     */
479
    public function importLocationsAction(ServerRequestInterface $request): ResponseInterface
480
    {
481
        $data_filesystem = Registry::filesystem()->data();
482
483
        $params = (array) $request->getParsedBody();
484
        $url    = route(MapDataList::class, ['parent_id' => 0]);
485
486
        $serverfile     = $params['serverfile'] ?? '';
487
        $options        = $params['import-options'] ?? '';
488
        $clear_database = (bool) ($params['cleardatabase'] ?? false);
489
        $local_file     = $request->getUploadedFiles()['localfile'] ?? null;
490
491
        $fp = false;
492
493
        if ($serverfile !== '' && $data_filesystem->has(self::PLACES_FOLDER . $serverfile)) {
494
            // first choice is file on server
495
            $fp = $data_filesystem->readStream(self::PLACES_FOLDER . $serverfile);
496
        } elseif ($local_file instanceof UploadedFileInterface && $local_file->getError() === UPLOAD_ERR_OK) {
497
            // 2nd choice is local file
498
            $fp = $local_file->getStream()->detach();
499
        }
500
501
        if ($fp === false) {
502
            return redirect($url);
503
        }
504
505
        $string = stream_get_contents($fp);
506
507
        $places = [];
508
509
        // Check the file type
510
        if (stripos($string, 'FeatureCollection') !== false) {
511
            $input_array = json_decode($string, false);
512
513
            foreach ($input_array->features as $feature) {
514
                $places[] = [
515
                    'pl_level' => $feature->properties->level ?? substr_count($feature->properties->name, ','),
516
                    'pl_long'  => $feature->geometry->coordinates[0],
517
                    'pl_lati'  => $feature->geometry->coordinates[1],
518
                    'pl_zoom'  => $feature->properties->zoom ?? null,
519
                    'pl_icon'  => $feature->properties->icon ?? null,
520
                    'fqpn'     => $feature->properties->name,
521
                ];
522
            }
523
        } else {
524
            rewind($fp);
525
            while (($row = fgetcsv($fp, 0, ';')) !== false) {
526
                // Skip the header
527
                if (!is_numeric($row[0])) {
528
                    continue;
529
                }
530
531
                $level = (int) $row[0];
532
                $count = count($row);
533
534
                // convert separate place fields into a comma separated placename
535
                $fqdn = implode(Gedcom::PLACE_SEPARATOR, array_reverse(array_slice($row, 1, 1 + $level)));
536
537
                $places[] = [
538
                    'pl_level' => $level,
539
                    'pl_long'  => (float) strtr($row[$count - 4], ['E' => '', 'W' => '-', ',' => '.']),
540
                    'pl_lati'  => (float) strtr($row[$count - 3], ['N' => '', 'S' => '-', ',' => '.']),
541
                    'pl_zoom'  => $row[$count - 2],
542
                    'pl_icon'  => $row[$count - 1],
543
                    'fqpn'     => $fqdn,
544
                ];
545
            }
546
        }
547
548
        fclose($fp);
549
550
        if ($clear_database) {
551
            DB::table('placelocation')->delete();
552
        }
553
554
        $added   = 0;
555
        $updated = 0;
556
557
        // Remove places with invalid coordinates
558
        $places = array_filter($places, function ($item) {
559
            return $item['pl_level'] === 0 || $item['pl_long'] !== 0.0 || $item['pl_lati'] !== 0.0;
560
        });
561
562
        foreach ($places as $place) {
563
            $location = new PlaceLocation($place['fqpn']);
564
            $exists   = $location->exists();
565
566
            // Only update existing records
567
            if ($options === 'update' && !$exists) {
568
                continue;
569
            }
570
571
            // Only add new records
572
            if ($options === 'add' && $exists) {
573
                continue;
574
            }
575
576
            if (!$exists) {
577
                $added++;
578
            }
579
580
            $updated += DB::table('placelocation')
581
                ->where('pl_id', '=', $location->id())
582
                ->update([
583
                    'pl_lati' => $this->gedcom_service->writeLatitude($place['pl_lati']),
584
                    'pl_long' => $this->gedcom_service->writeLongitude($place['pl_long']),
585
                    'pl_zoom' => $place['pl_zoom'] ?: null,
586
                    'pl_icon' => $place['pl_icon'] ?: null,
587
                ]);
588
        }
589
        FlashMessages::addMessage(
590
            I18N::translate('locations updated: %s, locations added: %s', I18N::number($updated), I18N::number($added)),
591
            'info'
592
        );
593
594
        return redirect($url);
595
    }
596
}
597