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