xref: /webtrees/app/Place.php (revision d2d9e83c2246f737b4d1e0d342676d64076b9ffc)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees;
19
20use Fisharebest\Webtrees\Module\ModuleInterface;
21use Fisharebest\Webtrees\Module\ModuleListInterface;
22use Fisharebest\Webtrees\Module\PlaceHierarchyListModule;
23use Fisharebest\Webtrees\Services\ModuleService;
24use Illuminate\Database\Capsule\Manager as DB;
25use Illuminate\Database\Query\Expression;
26use Illuminate\Support\Collection;
27
28/**
29 * A GEDCOM place (PLAC) object.
30 */
31class Place
32{
33    /** @var string e.g. "Westminster, London, England" */
34    private $place_name;
35
36    /** @var Collection The parts of a place name, e.g. ["Westminster", "London", "England"] */
37    private $parts;
38
39    /** @var Tree We may have the same place name in different trees. */
40    private $tree;
41
42    /**
43     * Create a place.
44     *
45     * @param string $place_name
46     * @param Tree   $tree
47     */
48    public function __construct(string $place_name, Tree $tree)
49    {
50        // Ignore any empty parts in place names such as "Village, , , Country".
51        $this->parts = Collection::make(preg_split(Gedcom::PLACE_SEPARATOR_REGEX, $place_name))
52            ->filter();
53
54        // Rebuild the placename in the correct format.
55        $this->place_name = $this->parts->implode(Gedcom::PLACE_SEPARATOR);
56
57        $this->tree = $tree;
58    }
59
60    /**
61     * Get the higher level place.
62     *
63     * @return Place
64     */
65    public function parent(): Place
66    {
67        return new self($this->parts->slice(1)->implode(Gedcom::PLACE_SEPARATOR), $this->tree);
68    }
69
70    /**
71     * The database row that contains this place.
72     * Note that due to database collation, both "Quebec" and "Québec" will share the same row.
73     *
74     * @return int
75     */
76    public function id(): int
77    {
78        return app('cache.array')->rememberForever(__CLASS__ . __METHOD__ . $this->place_name, function (): int {
79            // The "top-level" place won't exist in the database.
80            if ($this->parts->isEmpty()) {
81                return 0;
82            }
83
84            $parent_place_id = $this->parent()->id();
85
86            $place_id = (int) DB::table('places')
87                ->where('p_file', '=', $this->tree->id())
88                ->where('p_place', '=', $this->parts->first())
89                ->where('p_parent_id', '=', $parent_place_id)
90                ->value('p_id');
91
92            if ($place_id === 0) {
93                $place = $this->parts->first();
94
95                DB::table('places')->insert([
96                    'p_file'        => $this->tree->id(),
97                    'p_place'       => $place,
98                    'p_parent_id'   => $parent_place_id,
99                    'p_std_soundex' => Soundex::russell($place),
100                    'p_dm_soundex'  => Soundex::daitchMokotoff($place),
101                ]);
102
103                $place_id = (int) DB::connection()->getPdo()->lastInsertId();
104            }
105
106            return $place_id;
107        });
108    }
109
110    /**
111     * Extract the locality (first parts) of a place name.
112     *
113     * @param int $n
114     *
115     * @return Collection
116     */
117    public function firstParts(int $n): Collection
118    {
119        return $this->parts->slice(0, $n);
120    }
121
122    /**
123     * Extract the country (last parts) of a place name.
124     *
125     * @param int $n
126     *
127     * @return Collection
128     */
129    public function lastParts(int $n): Collection
130    {
131        return $this->parts->slice(-$n);
132    }
133
134    /**
135     * Get the lower level places.
136     *
137     * @return Place[]
138     */
139    public function getChildPlaces(): array
140    {
141        if ($this->place_name !== '') {
142            $parent_text = Gedcom::PLACE_SEPARATOR . $this->place_name;
143        } else {
144            $parent_text = '';
145        }
146
147        return DB::table('places')
148            ->where('p_file', '=', $this->tree->id())
149            ->where('p_parent_id', '=', $this->id())
150            ->orderBy(new Expression('p_place /*! COLLATE ' . I18N::collation() . ' */'))
151            ->pluck('p_place')
152            ->map(function (string $place) use ($parent_text): Place {
153                return new self($place . $parent_text, $this->tree);
154            })
155            ->all();
156    }
157
158    /**
159     * Create a URL to the place-hierarchy page.
160     *
161     * @return string
162     */
163    public function url(): string
164    {
165        //find a module providing the place hierarchy
166        $module = app(ModuleService::class)
167            ->findByComponent(ModuleListInterface::class, $this->tree, Auth::user())
168            ->first(static function (ModuleInterface $module): bool {
169                return $module instanceof PlaceHierarchyListModule;
170            });
171
172        if ($module instanceof PlaceHierarchyListModule) {
173            return $module->listUrl($this->tree, [
174                'parent' => $this->parts->reverse()->all(),
175                'ged'    => $this->tree->name(),
176            ]);
177        }
178
179        // The place-list module is disabled...
180        return '#';
181    }
182
183    /**
184     * Format this place for GEDCOM data.
185     *
186     * @return string
187     */
188    public function gedcomName(): string
189    {
190        return $this->place_name;
191    }
192
193    /**
194     * Format this place for display on screen.
195     *
196     * @return string
197     */
198    public function placeName(): string
199    {
200        $place_name = $this->parts->first() ?? I18N::translate('unknown');
201
202        return '<span dir="auto">' . e($place_name) . '</span>';
203    }
204
205    /**
206     * Generate the place name for display, including the full hierarchy.
207     *
208     * @param bool $link
209     *
210     * @return string
211     */
212    public function fullName(bool $link = false): string
213    {
214        if ($this->parts->isEmpty()) {
215            return '';
216        }
217
218        $full_name = $this->parts->implode(I18N::$list_separator);
219
220        if ($link) {
221            return '<a dir="auto" href="' . e($this->url()) . '">' . e($full_name) . '</a>';
222        }
223
224        return '<span dir="auto">' . e($full_name) . '</span>';
225    }
226
227    /**
228     * For lists and charts, where the full name won’t fit.
229     *
230     * @param bool $link
231     *
232     * @return string
233     */
234    public function shortName(bool $link = false): string
235    {
236        $SHOW_PEDIGREE_PLACES = (int) $this->tree->getPreference('SHOW_PEDIGREE_PLACES');
237
238        // Abbreviate the place name, for lists
239        if ($this->tree->getPreference('SHOW_PEDIGREE_PLACES_SUFFIX')) {
240            $parts = $this->lastParts($SHOW_PEDIGREE_PLACES);
241        } else {
242            $parts = $this->firstParts($SHOW_PEDIGREE_PLACES);
243        }
244
245        $short_name = $parts->implode(I18N::$list_separator);
246
247        // Add a tool-tip showing the full name
248        $title = strip_tags($this->fullName());
249
250        if ($link) {
251            return '<a dir="auto" href="' . e($this->url()) . '" title="' . $title . '"">' . e($short_name) . '</a>';
252        }
253
254        return '<span dir="auto">' . e($short_name) . '</span>';
255    }
256}
257