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