Passed
Pull Request — master (#3652)
by
unknown
17:21
created

LocationController::mapDataEdit()   C

Complexity

Conditions 11
Paths 100

Size

Total Lines 83
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 59
c 1
b 0
f 0
nc 100
nop 1
dl 0
loc 83
rs 6.7478

How to fix   Long Method    Complexity   

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