xref: /webtrees/app/Place.php (revision f934075922fa819544d437a7c258b0c884f11178)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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;
21
22use Fisharebest\Webtrees\Module\ModuleInterface;
23use Fisharebest\Webtrees\Module\ModuleListInterface;
24use Fisharebest\Webtrees\Module\PlaceHierarchyListModule;
25use Fisharebest\Webtrees\Services\ModuleService;
26use Illuminate\Database\Capsule\Manager as DB;
27use Illuminate\Support\Collection;
28
29use function app;
30use function e;
31use function is_object;
32use function preg_split;
33use function strip_tags;
34use function trim;
35
36use const PREG_SPLIT_NO_EMPTY;
37
38/**
39 * A GEDCOM place (PLAC) object.
40 */
41class Place
42{
43    // "Westminster, London, England"
44    private string $place_name;
45
46    /** @var Collection<int,string> The parts of a place name, e.g. ["Westminster", "London", "England"] */
47    private Collection $parts;
48
49    private Tree $tree;
50
51    /**
52     * Create a place.
53     *
54     * @param string $place_name
55     * @param Tree   $tree
56     */
57    public function __construct(string $place_name, Tree $tree)
58    {
59        // Ignore any empty parts in place names such as "Village, , , Country".
60        $place_name  = trim($place_name);
61        $this->parts = new Collection(preg_split(Gedcom::PLACE_SEPARATOR_REGEX, $place_name, -1, PREG_SPLIT_NO_EMPTY));
62
63        // Rebuild the placename in the correct format.
64        $this->place_name = $this->parts->implode(Gedcom::PLACE_SEPARATOR);
65
66        $this->tree = $tree;
67    }
68
69    /**
70     * Find a place by its ID.
71     *
72     * @param int  $id
73     * @param Tree $tree
74     *
75     * @return Place
76     */
77    public static function find(int $id, Tree $tree): Place
78    {
79        $parts = new Collection();
80
81        while ($id !== 0) {
82            $row = DB::table('places')
83                ->where('p_file', '=', $tree->id())
84                ->where('p_id', '=', $id)
85                ->first();
86
87            if (is_object($row)) {
88                $id = (int) $row->p_parent_id;
89                $parts->add($row->p_place);
90            } else {
91                $id = 0;
92            }
93        }
94
95        $place_name = $parts->implode(Gedcom::PLACE_SEPARATOR);
96
97        return new Place($place_name, $tree);
98    }
99
100    /**
101     * Get the higher level place.
102     *
103     * @return Place
104     */
105    public function parent(): Place
106    {
107        return new self($this->parts->slice(1)->implode(Gedcom::PLACE_SEPARATOR), $this->tree);
108    }
109
110    /**
111     * The database row that contains this place.
112     * Note that due to database collation, both "Quebec" and "Québec" will share the same row.
113     *
114     * @return int
115     */
116    public function id(): int
117    {
118        return Registry::cache()->array()->remember('place-' . $this->place_name, function (): int {
119            // The "top-level" place won't exist in the database.
120            if ($this->parts->isEmpty()) {
121                return 0;
122            }
123
124            $parent_place_id = $this->parent()->id();
125
126            $place_id = (int) DB::table('places')
127                ->where('p_file', '=', $this->tree->id())
128                ->where('p_place', '=', mb_substr($this->parts->first(), 0, 120))
129                ->where('p_parent_id', '=', $parent_place_id)
130                ->value('p_id');
131
132            if ($place_id === 0) {
133                $place = $this->parts->first();
134
135                DB::table('places')->insert([
136                    'p_file'        => $this->tree->id(),
137                    'p_place'       => mb_substr($place, 0, 120),
138                    'p_parent_id'   => $parent_place_id,
139                    'p_std_soundex' => Soundex::russell($place),
140                    'p_dm_soundex'  => Soundex::daitchMokotoff($place),
141                ]);
142
143                $place_id = (int) DB::connection()->getPdo()->lastInsertId();
144            }
145
146            return $place_id;
147        });
148    }
149
150    /**
151     * @return Tree
152     */
153    public function tree(): Tree
154    {
155        return $this->tree;
156    }
157
158    /**
159     * Extract the locality (first parts) of a place name.
160     *
161     * @param int $n
162     *
163     * @return Collection<int,string>
164     */
165    public function firstParts(int $n): Collection
166    {
167        return $this->parts->slice(0, $n);
168    }
169
170    /**
171     * Extract the country (last parts) of a place name.
172     *
173     * @param int $n
174     *
175     * @return Collection<int,string>
176     */
177    public function lastParts(int $n): Collection
178    {
179        return $this->parts->slice(-$n);
180    }
181
182    /**
183     * Get the lower level places.
184     *
185     * @return array<Place>
186     */
187    public function getChildPlaces(): array
188    {
189        if ($this->place_name !== '') {
190            $parent_text = Gedcom::PLACE_SEPARATOR . $this->place_name;
191        } else {
192            $parent_text = '';
193        }
194
195        return DB::table('places')
196            ->where('p_file', '=', $this->tree->id())
197            ->where('p_parent_id', '=', $this->id())
198            ->pluck('p_place')
199            ->sortBy(I18N::comparator())
200            ->map(function (string $place) use ($parent_text): Place {
201                return new self($place . $parent_text, $this->tree);
202            })
203            ->all();
204    }
205
206    /**
207     * Create a URL to the place-hierarchy page.
208     *
209     * @return string
210     */
211    public function url(): string
212    {
213        //find a module providing the place hierarchy
214        $module = app(ModuleService::class)
215            ->findByComponent(ModuleListInterface::class, $this->tree, Auth::user())
216            ->first(static function (ModuleInterface $module): bool {
217                return $module instanceof PlaceHierarchyListModule;
218            });
219
220        if ($module instanceof PlaceHierarchyListModule) {
221            return $module->listUrl($this->tree, [
222                'place_id' => $this->id(),
223                'tree'     => $this->tree->name(),
224            ]);
225        }
226
227        // The place-list module is disabled...
228        return '#';
229    }
230
231    /**
232     * Format this place for GEDCOM data.
233     *
234     * @return string
235     */
236    public function gedcomName(): string
237    {
238        return $this->place_name;
239    }
240
241    /**
242     * Format this place for display on screen.
243     *
244     * @return string
245     */
246    public function placeName(): string
247    {
248        $place_name = $this->parts->first() ?? I18N::translate('unknown');
249
250        return '<bdi>' . e($place_name) . '</bdi>';
251    }
252
253    /**
254     * Generate the place name for display, including the full hierarchy.
255     *
256     * @param bool $link
257     *
258     * @return string
259     */
260    public function fullName(bool $link = false): string
261    {
262        if ($this->parts->isEmpty()) {
263            return '';
264        }
265
266        $full_name = $this->parts->implode(I18N::$list_separator);
267
268        if ($link) {
269            return '<a dir="auto" href="' . e($this->url()) . '">' . e($full_name) . '</a>';
270        }
271
272        return '<bdi>' . e($full_name) . '</bdi>';
273    }
274
275    /**
276     * For lists and charts, where the full name won’t fit.
277     *
278     * @param bool $link
279     *
280     * @return string
281     */
282    public function shortName(bool $link = false): string
283    {
284        $SHOW_PEDIGREE_PLACES = (int) $this->tree->getPreference('SHOW_PEDIGREE_PLACES');
285
286        // Abbreviate the place name, for lists
287        if ($this->tree->getPreference('SHOW_PEDIGREE_PLACES_SUFFIX')) {
288            $parts = $this->lastParts($SHOW_PEDIGREE_PLACES);
289        } else {
290            $parts = $this->firstParts($SHOW_PEDIGREE_PLACES);
291        }
292
293        $short_name = $parts->implode(I18N::$list_separator);
294
295        // Add a tool-tip showing the full name
296        $title = strip_tags($this->fullName());
297
298        if ($link) {
299            return '<a dir="auto" href="' . e($this->url()) . '" title="' . $title . '">' . e($short_name) . '</a>';
300        }
301
302        return '<bdi>' . e($short_name) . '</bdi>';
303    }
304}
305