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