xref: /webtrees/app/Http/RequestHandlers/IndividualPage.php (revision 0f5fd22fb1857ad87285e5357592434d47b1f3bf)
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\Http\RequestHandlers;
21
22use Fig\Http\Message\StatusCodeInterface;
23use Fisharebest\Webtrees\Age;
24use Fisharebest\Webtrees\Auth;
25use Fisharebest\Webtrees\Date;
26use Fisharebest\Webtrees\Fact;
27use Fisharebest\Webtrees\Http\ViewResponseTrait;
28use Fisharebest\Webtrees\I18N;
29use Fisharebest\Webtrees\Individual;
30use Fisharebest\Webtrees\Media;
31use Fisharebest\Webtrees\MediaFile;
32use Fisharebest\Webtrees\Module\ModuleShareInterface;
33use Fisharebest\Webtrees\Module\ModuleSidebarInterface;
34use Fisharebest\Webtrees\Module\ModuleTabInterface;
35use Fisharebest\Webtrees\Registry;
36use Fisharebest\Webtrees\Services\ClipboardService;
37use Fisharebest\Webtrees\Services\ModuleService;
38use Fisharebest\Webtrees\Services\UserService;
39use Fisharebest\Webtrees\Tree;
40use Illuminate\Support\Collection;
41use Psr\Http\Message\ResponseInterface;
42use Psr\Http\Message\ServerRequestInterface;
43use Psr\Http\Server\RequestHandlerInterface;
44use stdClass;
45
46use function array_map;
47use function assert;
48use function date;
49use function e;
50use function explode;
51use function implode;
52use function is_string;
53use function redirect;
54use function route;
55use function strtoupper;
56use function view;
57
58/**
59 * Show an individual's page.
60 */
61class IndividualPage implements RequestHandlerInterface
62{
63    use ViewResponseTrait;
64
65    private ClipboardService $clipboard_service;
66
67    private ModuleService $module_service;
68
69    private UserService $user_service;
70
71    /**
72     * IndividualPage constructor.
73     *
74     * @param ClipboardService $clipboard_service
75     * @param ModuleService    $module_service
76     * @param UserService      $user_service
77     */
78    public function __construct(ClipboardService $clipboard_service, ModuleService $module_service, UserService $user_service)
79    {
80        $this->clipboard_service = $clipboard_service;
81        $this->module_service    = $module_service;
82        $this->user_service      = $user_service;
83    }
84
85    /**
86     * @param ServerRequestInterface $request
87     *
88     * @return ResponseInterface
89     */
90    public function handle(ServerRequestInterface $request): ResponseInterface
91    {
92        $tree = $request->getAttribute('tree');
93        assert($tree instanceof Tree);
94
95        $xref = $request->getAttribute('xref');
96        assert(is_string($xref));
97
98        $individual = Registry::individualFactory()->make($xref, $tree);
99        $individual = Auth::checkIndividualAccess($individual);
100
101        // Redirect to correct xref/slug
102        $slug = Registry::slugFactory()->make($individual);
103
104        if ($individual->xref() !== $xref || $request->getAttribute('slug') !== $slug) {
105            return redirect($individual->url(), StatusCodeInterface::STATUS_MOVED_PERMANENTLY);
106        }
107
108        // What images are linked to this individual
109        $individual_media = new Collection();
110        foreach ($individual->facts(['OBJE']) as $fact) {
111            $media_object = $fact->target();
112            if ($media_object instanceof Media) {
113                $media_file = $media_object->firstImageFile();
114                if ($media_file instanceof MediaFile) {
115                    $individual_media->add($media_file);
116                }
117            }
118        }
119
120        $name_records = $individual->facts(['NAME'])->map(static function (Fact $fact): string {
121            return view('individual-name', ['fact' => $fact]);
122        });
123
124        $sex_records = $individual->facts(['SEX'])->map(static function (Fact $fact): string {
125            return view('individual-sex', ['fact' => $fact]);
126        });
127
128        // If this individual is linked to a user account, show the link
129        $user_link = '';
130        if (Auth::isAdmin()) {
131            $users = $this->user_service->findByIndividual($individual);
132            foreach ($users as $user) {
133                $user_link = ' —  <a href="' . e(route(UserListPage::class, ['filter' => $user->email()])) . '">' . e($user->userName()) . '</a>';
134            }
135        }
136
137        $shares = $this->module_service->findByInterface(ModuleShareInterface::class)
138            ->map(fn (ModuleShareInterface $module) => $module->share($individual))
139            ->filter();
140
141        return $this->viewResponse('individual-page', [
142            'age'              => $this->ageString($individual),
143            'clipboard_facts'  => $this->clipboard_service->pastableFacts($individual),
144            'individual_media' => $individual_media,
145            'meta_description' => $this->metaDescription($individual),
146            'meta_robots'      => 'index,follow',
147            'name_records'     => $name_records,
148            'record'           => $individual,
149            'sex_records'      => $sex_records,
150            'shares'           => $shares,
151            'sidebars'         => $this->getSidebars($individual),
152            'tabs'             => $this->getTabs($individual),
153            'significant'      => $this->significant($individual),
154            'title'            => $individual->fullName() . ' ' . $individual->lifespan(),
155            'tree'             => $tree,
156            'user_link'        => $user_link,
157        ]);
158    }
159
160    /**
161     * @param Individual $individual
162     *
163     * @return string
164     */
165    private function ageString(Individual $individual): string
166    {
167        if ($individual->isDead()) {
168            // If dead, show age at death
169            $age = (string) new Age($individual->getBirthDate(), $individual->getDeathDate());
170
171            if ($age === '') {
172                return '';
173            }
174
175            switch ($individual->sex()) {
176                case 'M':
177                    /* I18N: The age of an individual at a given date */
178                    return I18N::translateContext('Male', '(aged %s)', $age);
179                case 'F':
180                    /* I18N: The age of an individual at a given date */
181                    return I18N::translateContext('Female', '(aged %s)', $age);
182                default:
183                    /* I18N: The age of an individual at a given date */
184                    return I18N::translate('(aged %s)', $age);
185            }
186        }
187
188        // If living, show age today
189        $today = new Date(strtoupper(date('d M Y')));
190        $age   = (string) new Age($individual->getBirthDate(), $today);
191
192        if ($age === '') {
193            return '';
194        }
195
196        /* I18N: The current age of a living individual */
197        return I18N::translate('(age %s)', $age);
198    }
199
200    /**
201     * @param Individual $individual
202     *
203     * @return string
204     */
205    private function metaDescription(Individual $individual): string
206    {
207        $meta_facts = [];
208
209        $birth_date  = $individual->getBirthDate();
210        $birth_place = $individual->getBirthPlace();
211
212        if ($birth_date->isOK() || $birth_place->id() !== 0) {
213            $meta_facts[] = I18N::translate('Birth') . ' ' .
214                $birth_date->display(false, null, false) . ' ' .
215                $birth_place->placeName();
216        }
217
218        $death_date  = $individual->getDeathDate();
219        $death_place = $individual->getDeathPlace();
220
221        if ($death_date->isOK() || $death_place->id() !== 0) {
222            $meta_facts[] = I18N::translate('Death') . ' ' .
223                $death_date->display(false, null, false) . ' ' .
224                $death_place->placeName();
225        }
226
227        foreach ($individual->childFamilies() as $family) {
228            $meta_facts[] = I18N::translate('Parents') . ' ' . $family->fullName();
229        }
230
231        foreach ($individual->spouseFamilies() as $family) {
232            $spouse = $family->spouse($individual);
233            if ($spouse instanceof Individual) {
234                $meta_facts[] = I18N::translate('Spouse') . ' ' . $spouse->fullName();
235            }
236
237            $child_names = $family->children()->map(static function (Individual $individual): string {
238                return e($individual->getAllNames()[0]['givn']);
239            })->implode(', ');
240
241
242            if ($child_names !== '') {
243                $meta_facts[] = I18N::translate('Children') . ' ' . $child_names;
244            }
245        }
246
247        $meta_facts = array_map('strip_tags', $meta_facts);
248        $meta_facts = array_map('trim', $meta_facts);
249
250        return implode(', ', $meta_facts);
251    }
252
253    /**
254     * Which tabs should we show on this individual's page.
255     * We don't show empty tabs.
256     *
257     * @param Individual $individual
258     *
259     * @return Collection<ModuleSidebarInterface>
260     */
261    public function getSidebars(Individual $individual): Collection
262    {
263        return $this->module_service->findByComponent(ModuleSidebarInterface::class, $individual->tree(), Auth::user())
264            ->filter(static function (ModuleSidebarInterface $sidebar) use ($individual): bool {
265                return $sidebar->hasSidebarContent($individual);
266            });
267    }
268
269    /**
270     * Which tabs should we show on this individual's page.
271     * We don't show empty tabs.
272     *
273     * @param Individual $individual
274     *
275     * @return Collection<ModuleTabInterface>
276     */
277    public function getTabs(Individual $individual): Collection
278    {
279        return $this->module_service->findByComponent(ModuleTabInterface::class, $individual->tree(), Auth::user())
280            ->filter(static function (ModuleTabInterface $tab) use ($individual): bool {
281                return $tab->hasTabContent($individual);
282            });
283    }
284
285    /**
286     * What are the significant elements of this page?
287     * The layout will need them to generate URLs for charts and reports.
288     *
289     * @param Individual $individual
290     *
291     * @return stdClass
292     */
293    private function significant(Individual $individual): stdClass
294    {
295        [$surname] = explode(',', $individual->sortName());
296
297        $family = $individual->childFamilies()->merge($individual->spouseFamilies())->first();
298
299        return (object) [
300            'family'     => $family,
301            'individual' => $individual,
302            'surname'    => $surname,
303        ];
304    }
305}
306