xref: /webtrees/app/Module/PlaceHierarchyListModule.php (revision 73b8c04073f4aae42af235f4485847d0a07c8f8c)
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
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Aura\Router\RouterContainer;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Place;
27use Fisharebest\Webtrees\PlaceLocation;
28use Fisharebest\Webtrees\Services\ModuleService;
29use Fisharebest\Webtrees\Services\SearchService;
30use Fisharebest\Webtrees\Services\UserService;
31use Fisharebest\Webtrees\Site;
32use Fisharebest\Webtrees\Statistics;
33use Fisharebest\Webtrees\Tree;
34use Fisharebest\Webtrees\Webtrees;
35use Illuminate\Database\Capsule\Manager as DB;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestInterface;
38use Psr\Http\Server\RequestHandlerInterface;
39
40use function array_chunk;
41use function array_pop;
42use function array_reverse;
43use function assert;
44use function ceil;
45use function count;
46use function is_file;
47use function redirect;
48use function route;
49use function view;
50
51/**
52 * Class IndividualListModule
53 */
54class PlaceHierarchyListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
55{
56    use ModuleListTrait;
57
58    protected const ROUTE_URL = '/tree/{tree}/place-list';
59
60    /** @var int The default access level for this module.  It can be changed in the control panel. */
61    protected $access_level = Auth::PRIV_USER;
62
63    /** @var SearchService */
64    private $search_service;
65
66    /**
67     * PlaceHierarchy constructor.
68     *
69     * @param SearchService $search_service
70     */
71    public function __construct(SearchService $search_service)
72    {
73        $this->search_service = $search_service;
74    }
75
76    /**
77     * Initialization.
78     *
79     * @return void
80     */
81    public function boot(): void
82    {
83        $router_container = app(RouterContainer::class);
84        assert($router_container instanceof RouterContainer);
85
86        $router_container->getMap()
87            ->get(static::class, static::ROUTE_URL, $this);
88    }
89
90    /**
91     * How should this module be identified in the control panel, etc.?
92     *
93     * @return string
94     */
95    public function title(): string
96    {
97        /* I18N: Name of a module/list */
98        return I18N::translate('Place hierarchy');
99    }
100
101    /**
102     * A sentence describing what this module does.
103     *
104     * @return string
105     */
106    public function description(): string
107    {
108        /* I18N: Description of the “Place hierarchy” module */
109        return I18N::translate('The place hierarchy.');
110    }
111
112    /**
113     * CSS class for the URL.
114     *
115     * @return string
116     */
117    public function listMenuClass(): string
118    {
119        return 'menu-list-plac';
120    }
121
122    /**
123     * @param Tree    $tree
124     * @param mixed[] $parameters
125     *
126     * @return string
127     */
128    public function listUrl(Tree $tree, array $parameters = []): string
129    {
130        $parameters['tree'] = $tree->name();
131
132        return route(static::class, $parameters);
133    }
134
135    /**
136     * @return string[]
137     */
138    public function listUrlAttributes(): array
139    {
140        return [];
141    }
142
143    /**
144     * @param Tree $tree
145     *
146     * @return bool
147     */
148    public function listIsEmpty(Tree $tree): bool
149    {
150        return !DB::table('places')
151            ->where('p_file', '=', $tree->id())
152            ->exists();
153    }
154
155    /**
156     * Handle URLs generated by older versions of webtrees
157     *
158     * @param ServerRequestInterface $request
159     *
160     * @return ResponseInterface
161     */
162    public function getListAction(ServerRequestInterface $request): ResponseInterface
163    {
164        return redirect($this->listUrl($request->getAttribute('tree'), $request->getQueryParams()));
165    }
166
167    /**
168     * @param ServerRequestInterface $request
169     *
170     * @return ResponseInterface
171     */
172    public function handle(ServerRequestInterface $request): ResponseInterface
173    {
174        $tree = $request->getAttribute('tree');
175        assert($tree instanceof Tree);
176
177        $user = $request->getAttribute('user');
178        assert($user instanceof UserInterface);
179
180        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
181
182        $action2  = $request->getQueryParams()['action2'] ?? 'hierarchy';
183        $place_id = (int) ($request->getQueryParams()['place_id'] ?? 0);
184        $place    = Place::find($place_id, $tree);
185
186        // Request for a non-existent place?
187        if ($place_id !== $place->id()) {
188            return redirect($place->url());
189        }
190
191        $content = '';
192        $showmap = Site::getPreference('map-provider') !== '';
193        $data    = null;
194
195        if ($showmap) {
196            $content .= view('modules/place-hierarchy/map', [
197                'data'     => $this->mapData($tree, $place),
198                'provider' => [
199                    'url'    => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
200                    'options' => [
201                        'attribution' => '<a href="https://www.openstreetmap.org/copyright">&copy; OpenStreetMap</a> contributors',
202                        'max_zoom'    => 19
203                    ]
204                ]
205            ]);
206        }
207
208        switch ($action2) {
209            case 'list':
210            default:
211                $alt_link = I18N::translate('Show place hierarchy');
212                $alt_url  = $this->listUrl($tree, ['action2' => 'hierarchy', 'place_id' => $place_id]);
213                $content .= view('modules/place-hierarchy/list', ['columns' => $this->getList($tree)]);
214                break;
215            case 'hierarchy':
216            case 'hierarchy-e':
217                $alt_link = I18N::translate('Show all places in a list');
218                $alt_url  = $this->listUrl($tree, ['action2' => 'list', 'place_id' => 0]);
219                $data     = $this->getHierarchy($place);
220                $content .= (null === $data || $showmap) ? '' : view('place-hierarchy', $data);
221                if (null === $data || $action2 === 'hierarchy-e') {
222                    $content .= view('modules/place-hierarchy/events', [
223                        'indilist' => $this->search_service->searchIndividualsInPlace($place),
224                        'famlist'  => $this->search_service->searchFamiliesInPlace($place),
225                        'tree'     => $place->tree(),
226                    ]);
227                }
228        }
229
230        if ($data !== null && $action2 !== 'hierarchy-e' && $place->gedcomName() !== '') {
231            $events_link = $this->listUrl($tree, ['action2' => 'hierarchy-e', 'place_id' => $place_id]);
232        } else {
233            $events_link = '';
234        }
235
236        $breadcrumbs = $this->breadcrumbs($place);
237
238        return $this->viewResponse('modules/place-hierarchy/page', [
239            'alt_link'    => $alt_link,
240            'alt_url'     => $alt_url,
241            'breadcrumbs' => $breadcrumbs['breadcrumbs'],
242            'content'     => $content,
243            'current'     => $breadcrumbs['current'],
244            'events_link' => $events_link,
245            'place'       => $place,
246            'title'       => I18N::translate('Place hierarchy'),
247            'tree'        => $tree,
248            'world_url'   => $this->listUrl($tree)
249        ]);
250    }
251
252    /**
253     * @param Tree $tree
254     *
255     * @return array<array<Place>>
256     */
257    private function getList(Tree $tree): array
258    {
259        $places = $this->search_service->searchPlaces($tree, '')
260            ->sort(static function (Place $x, Place $y): int {
261                return $x->gedcomName() <=> $y->gedcomName();
262            })
263            ->all();
264
265        $count = count($places);
266
267        if ($places === []) {
268            return [];
269        }
270
271        $columns = $count > 20 ? 3 : 2;
272
273        return array_chunk($places, (int) ceil($count / $columns));
274    }
275
276
277    /**
278     * @param Place $place
279     *
280     * @return array{'tree':Tree,'col_class':string,'columns':array<array<Place>>,'place':Place}|null
281     */
282    private function getHierarchy(Place $place): ?array
283    {
284        $child_places = $place->getChildPlaces();
285        $numfound     = count($child_places);
286
287        if ($numfound > 0) {
288            $divisor = $numfound > 20 ? 3 : 2;
289
290            return [
291                'tree'      => $place->tree(),
292                'col_class' => 'w-' . ($divisor === 2 ? '25' : '50'),
293                'columns'   => array_chunk($child_places, (int) ceil($numfound / $divisor)),
294                'place'     => $place,
295            ];
296        }
297
298        return null;
299    }
300
301    /**
302     * @param Place $place
303     *
304     * @return array{'breadcrumbs':array<Place>,'current':Place|null}
305     */
306    private function breadcrumbs(Place $place): array
307    {
308        $breadcrumbs = [];
309        if ($place->gedcomName() !== '') {
310            $breadcrumbs[] = $place;
311            $parent_place  = $place->parent();
312            while ($parent_place->gedcomName() !== '') {
313                $breadcrumbs[] = $parent_place;
314                $parent_place  = $parent_place->parent();
315            }
316            $breadcrumbs = array_reverse($breadcrumbs);
317            $current     = array_pop($breadcrumbs);
318        } else {
319            $current = null;
320        }
321
322        return [
323            'breadcrumbs' => $breadcrumbs,
324            'current'     => $current,
325        ];
326    }
327
328    /**
329     * @param Tree  $tree
330     * @param Place $placeObj
331     *
332     * @return array<mixed>
333     */
334    protected function mapData(Tree $tree, Place $placeObj): array
335    {
336        $places    = $placeObj->getChildPlaces();
337        $features  = [];
338        $sidebar   = '';
339        $flag_path = Webtrees::MODULES_DIR . 'openstreetmap/';
340        $show_link = true;
341
342        if ($places === []) {
343            $places[] = $placeObj;
344            $show_link = false;
345        }
346
347        foreach ($places as $id => $place) {
348            $location = new PlaceLocation($place->gedcomName());
349
350            if ($location->icon() !== '' && is_file($flag_path . $location->icon())) {
351                $flag = $flag_path . $location->icon();
352            } else {
353                $flag = '';
354            }
355
356            if ($location->latitude() === 0.0 && $location->longitude() === 0.0) {
357                $sidebar_class = 'unmapped';
358            } else {
359                $sidebar_class = 'mapped';
360                $features[]    = [
361                    'type'       => 'Feature',
362                    'id'         => $id,
363                    'geometry'   => [
364                        'type'        => 'Point',
365                        'coordinates' => [$location->longitude(), $location->latitude()],
366                    ],
367                    'properties' => [
368                        'tooltip' => $place->gedcomName(),
369                        'popup'   => view('modules/place-hierarchy/popup', [
370                            'showlink'  => $show_link,
371                            'flag'      => $flag,
372                            'place'     => $place,
373                            'latitude'  => $location->latitude(),
374                            'longitude' => $location->longitude(),
375                        ]),
376                    ],
377                ];
378            }
379
380            $statistics = new Statistics(app(ModuleService::class), $tree, app(UserService::class));
381
382            //Stats
383            $placeStats = [];
384            foreach (['INDI', 'FAM'] as $type) {
385                $tmp               = $statistics->statsPlaces($type, '', $place->id());
386                $placeStats[$type] = $tmp === [] ? 0 : $tmp[0]->tot;
387            }
388            $sidebar .= view('modules/place-hierarchy/sidebar', [
389                'showlink'      => $show_link,
390                'flag'          => $flag,
391                'id'            => $id,
392                'place'         => $place,
393                'sidebar_class' => $sidebar_class,
394                'stats'         => $placeStats,
395            ]);
396        }
397
398        return [
399            'bounds'  => (new PlaceLocation($placeObj->gedcomName()))->boundingRectangle(),
400            'sidebar' => $sidebar,
401            'markers' => [
402                'type'     => 'FeatureCollection',
403                'features' => $features,
404            ]
405        ];
406    }
407}
408