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