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