xref: /webtrees/app/Http/RequestHandlers/IndividualPage.php (revision d087306a423a21f415379a268c361cb15f96c514)
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\Http\RequestHandlers;
21
22use Fig\Http\Message\StatusCodeInterface;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Date;
25use Fisharebest\Webtrees\Fact;
26use Fisharebest\Webtrees\Functions\FunctionsDate;
27use Fisharebest\Webtrees\Functions\FunctionsPrint;
28use Fisharebest\Webtrees\Functions\FunctionsPrintFacts;
29use Fisharebest\Webtrees\GedcomCode\GedcomCodeName;
30use Fisharebest\Webtrees\GedcomTag;
31use Fisharebest\Webtrees\Http\ViewResponseTrait;
32use Fisharebest\Webtrees\I18N;
33use Fisharebest\Webtrees\Individual;
34use Fisharebest\Webtrees\Media;
35use Fisharebest\Webtrees\MediaFile;
36use Fisharebest\Webtrees\Module\ModuleSidebarInterface;
37use Fisharebest\Webtrees\Module\ModuleTabInterface;
38use Fisharebest\Webtrees\Services\ClipboardService;
39use Fisharebest\Webtrees\Services\ModuleService;
40use Fisharebest\Webtrees\Services\UserService;
41use Fisharebest\Webtrees\Tree;
42use Illuminate\Support\Collection;
43use Psr\Http\Message\ResponseInterface;
44use Psr\Http\Message\ServerRequestInterface;
45use Psr\Http\Server\RequestHandlerInterface;
46use stdClass;
47
48use function assert;
49use function e;
50use function explode;
51use function is_string;
52use function ob_get_clean;
53use function ob_start;
54use function preg_match_all;
55use function preg_replace;
56use function redirect;
57use function route;
58use function str_replace;
59use function strpos;
60
61/**
62 * Show an individual's page.
63 */
64class IndividualPage implements RequestHandlerInterface
65{
66    use ViewResponseTrait;
67
68    /** @var ClipboardService */
69    private $clipboard_service;
70
71    /** @var ModuleService */
72    private $module_service;
73
74    /** @var UserService */
75    private $user_service;
76
77    /**
78     * IndividualPage constructor.
79     *
80     * @param ClipboardService $clipboard_service
81     * @param ModuleService    $module_service
82     * @param UserService      $user_service
83     */
84    public function __construct(ClipboardService $clipboard_service, ModuleService $module_service, UserService $user_service)
85    {
86        $this->clipboard_service = $clipboard_service;
87        $this->module_service    = $module_service;
88        $this->user_service      = $user_service;
89    }
90
91    /**
92     * @param ServerRequestInterface $request
93     *
94     * @return ResponseInterface
95     */
96    public function handle(ServerRequestInterface $request): ResponseInterface
97    {
98        $tree = $request->getAttribute('tree');
99        assert($tree instanceof Tree);
100
101        $xref = $request->getAttribute('xref');
102        assert(is_string($xref));
103
104        $individual = Individual::getInstance($xref, $tree);
105        $individual = Auth::checkIndividualAccess($individual);
106
107        // Redirect to correct xref/slug
108        if ($individual->xref() !== $xref || $request->getAttribute('slug') !== $individual->slug()) {
109            return redirect($individual->url(), StatusCodeInterface::STATUS_MOVED_PERMANENTLY);
110        }
111
112        // What is (was) the age of the individual
113        $bdate = $individual->getBirthDate();
114        $ddate = $individual->getDeathDate();
115        if ($bdate->isOK() && !$individual->isDead()) {
116            // If living display age
117            $age = ' (' . I18N::translate('age') . ' ' . FunctionsDate::getAgeAtEvent(Date::getAgeGedcom($bdate, new Date(strtoupper(date('d M Y'))))) . ')';
118        } elseif ($bdate->isOK() && $ddate->isOK()) {
119            // If dead, show age at death
120            $age = ' (' . I18N::translate('age') . ' ' . FunctionsDate::getAgeAtEvent(Date::getAgeGedcom($bdate, $ddate)) . ')';
121        } else {
122            $age = '';
123        }
124
125        // What images are linked to this individual
126        $individual_media = new Collection();
127        foreach ($individual->facts(['OBJE']) as $fact) {
128            $media_object = $fact->target();
129            if ($media_object instanceof Media) {
130                $media_file = $media_object->firstImageFile();
131                if ($media_file instanceof MediaFile) {
132                    $individual_media->add($media_file);
133                }
134            }
135        }
136
137        $name_records = new Collection();
138        foreach ($individual->facts(['NAME']) as $n => $name_fact) {
139            $name_records->add($this->formatNameRecord($tree, $n, $name_fact));
140        }
141
142        $sex_records = new Collection();
143        foreach ($individual->facts(['SEX']) as $n => $sex_fact) {
144            $sex_records->add($this->formatSexRecord($sex_fact));
145        }
146
147        // If this individual is linked to a user account, show the link
148        $user_link = '';
149        if (Auth::isAdmin()) {
150            $users = $this->user_service->findByIndividual($individual);
151            foreach ($users as $user) {
152                $user_link = ' —  <a href="' . e(route('admin-users', ['filter' => $user->email()])) . '">' . e($user->userName()) . '</a>';
153            }
154        }
155
156        return $this->viewResponse('individual-page', [
157            'age'              => $age,
158            'clipboard_facts'  => $this->clipboard_service->pastableFacts($individual, new Collection()),
159            'count_media'      => $this->countFacts($individual, ['OBJE']),
160            'count_names'      => $this->countFacts($individual, ['NAME']),
161            'count_sex'        => $this->countFacts($individual, ['SEX']),
162            'individual'       => $individual,
163            'individual_media' => $individual_media,
164            'meta_robots'      => 'index,follow',
165            'name_records'     => $name_records,
166            'sex_records'      => $sex_records,
167            'sidebars'         => $this->getSidebars($individual),
168            'tabs'             => $this->getTabs($individual),
169            'significant'      => $this->significant($individual),
170            'title'            => $individual->fullName() . ' ' . $individual->lifespan(),
171            'tree'             => $tree,
172            'user_link'        => $user_link,
173        ]);
174    }
175
176    /**
177     * Count the (non-pending-delete) name records for an individual.
178     *
179     * @param Individual $individual
180     * @param string[]   $tags
181     *
182     * @return int
183     */
184    private function countFacts(Individual $individual, array $tags): int
185    {
186        $count = 0;
187
188        foreach ($individual->facts($tags) as $fact) {
189            if (!$fact->isPendingDeletion()) {
190                $count++;
191            }
192        }
193
194        return $count;
195    }
196
197    /**
198     * Format a name record
199     *
200     * @param Tree $tree
201     * @param int  $n
202     * @param Fact $fact
203     *
204     * @return string
205     */
206    private function formatNameRecord(Tree $tree, $n, Fact $fact): string
207    {
208        $individual = $fact->record();
209
210        // Create a dummy record, so we can extract the formatted NAME value from it.
211        $dummy = new Individual(
212            'xref',
213            "0 @xref@ INDI\n1 DEAT Y\n" . $fact->gedcom(),
214            null,
215            $individual->tree()
216        );
217        $dummy->setPrimaryName(0); // Make sure we use the name from "1 NAME"
218
219        $container_class = 'card';
220        $content_class   = 'collapse';
221        $aria            = 'false';
222
223        if ($n === 0) {
224            $content_class = 'collapse show';
225            $aria          = 'true';
226        }
227        if ($fact->isPendingDeletion()) {
228            $container_class .= ' wt-old';
229        } elseif ($fact->isPendingAddition()) {
230            $container_class .= ' wt-new';
231        }
232
233        ob_start();
234        echo '<dl><dt class="label">', I18N::translate('Name'), '</dt>';
235        echo '<dd class="field">', $dummy->fullName(), '</dd>';
236        $ct = preg_match_all('/\n2 (\w+) (.*)/', $fact->gedcom(), $nmatch, PREG_SET_ORDER);
237        for ($i = 0; $i < $ct; $i++) {
238            $tag = $nmatch[$i][1];
239            if ($tag !== 'SOUR' && $tag !== 'NOTE' && $tag !== 'SPFX') {
240                echo '<dt class="label">', GedcomTag::getLabel($tag, $individual), '</dt>';
241                echo '<dd class="field">'; // Before using dir="auto" on this field, note that Gecko treats this as an inline element but WebKit treats it as a block element
242                if (isset($nmatch[$i][2])) {
243                    $name = e($nmatch[$i][2]);
244                    $name = str_replace('/', '', $name);
245                    $name = preg_replace('/(\S*)\*/', '<span class="starredname">\\1</span>', $name);
246                    switch ($tag) {
247                        case 'TYPE':
248                            echo GedcomCodeName::getValue($name, $individual);
249                            break;
250                        case 'SURN':
251                            // The SURN field is not necessarily the surname.
252                            // Where it is not a substring of the real surname, show it after the real surname.
253                            $surname = e($dummy->getAllNames()[0]['surname']);
254                            $surns   = preg_replace('/, */', ' ', $nmatch[$i][2]);
255                            if (strpos($dummy->getAllNames()[0]['surname'], $surns) !== false) {
256                                echo '<span dir="auto">' . $surname . '</span>';
257                            } else {
258                                echo I18N::translate('%1$s (%2$s)', '<span dir="auto">' . $surname . '</span>', '<span dir="auto">' . $name . '</span>');
259                            }
260                            break;
261                        default:
262                            echo '<span dir="auto">' . $name . '</span>';
263                            break;
264                    }
265                }
266                echo '</dd>';
267            }
268        }
269        echo '</dl>';
270        if (strpos($fact->gedcom(), "\n2 SOUR") !== false) {
271            echo '<div id="indi_sour" class="clearfix">', FunctionsPrintFacts::printFactSources($tree, $fact->gedcom(), 2), '</div>';
272        }
273        if (strpos($fact->gedcom(), "\n2 NOTE") !== false) {
274            echo '<div id="indi_note" class="clearfix">', FunctionsPrint::printFactNotes($tree, $fact->gedcom(), 2), '</div>';
275        }
276        $content = ob_get_clean();
277
278        if ($fact->canEdit()) {
279            $edit_links =
280                '<a class="btn btn-link" href="#" data-confirm="' . I18N::translate('Are you sure you want to delete this fact?') . '" data-post-url="' . e(route(DeleteFact::class, ['tree' => $individual->tree()->name(), 'xref' => $individual->xref(), 'fact_id' => $fact->id()])) . '" title="' . I18N::translate('Delete this name') . '">' . view('icons/delete') . '<span class="sr-only">' . I18N::translate('Delete this name') . '</span></a>' .
281                '<a class="btn btn-link" href="' . e(route('edit-name', ['xref' => $individual->xref(), 'fact_id' => $fact->id(), 'tree' => $individual->tree()->name()])) . '" title="' . I18N::translate('Edit the name') . '">' . view('icons/edit') . '<span class="sr-only">' . I18N::translate('Edit the name') . '</span></a>';
282        } else {
283            $edit_links = '';
284        }
285
286        return '
287			<div class="' . $container_class . '">
288        <div class="card-header" role="tab" id="name-header-' . $n . '">
289		        <a data-toggle="collapse" data-parent="#individual-names" href="#name-content-' . $n . '" aria-expanded="' . $aria . '" aria-controls="name-content-' . $n . '">' . $dummy->fullName() . '</a>
290		      ' . $edit_links . '
291        </div>
292		    <div id="name-content-' . $n . '" class="' . $content_class . '" role="tabpanel" aria-labelledby="name-header-' . $n . '">
293		      <div class="card-body">' . $content . '</div>
294        </div>
295      </div>';
296    }
297
298    /**
299     * print information for a sex record
300     *
301     * @param Fact $fact
302     *
303     * @return string
304     */
305    private function formatSexRecord(Fact $fact): string
306    {
307        $individual = $fact->record();
308
309        switch ($fact->value()) {
310            case 'M':
311                $sex = I18N::translate('Male');
312                break;
313            case 'F':
314                $sex = I18N::translate('Female');
315                break;
316            default:
317                $sex = I18N::translateContext('unknown gender', 'Unknown');
318                break;
319        }
320
321        $container_class = 'card';
322        if ($fact->isPendingDeletion()) {
323            $container_class .= ' wt-old';
324        } elseif ($fact->isPendingAddition()) {
325            $container_class .= ' wt-new';
326        }
327
328        if ($individual->canEdit()) {
329            $edit_links = '<a class="btn btn-link" href="' . e(route(EditFact::class, ['xref' => $individual->xref(), 'fact_id' => $fact->id(), 'tree' => $individual->tree()->name()])) . '" title="' . I18N::translate('Edit the gender') . '">' . view('icons/edit') . '<span class="sr-only">' . I18N::translate('Edit the gender') . '</span></a>';
330        } else {
331            $edit_links = '';
332        }
333
334        return '
335		<div class="' . $container_class . '">
336			<div class="card-header" role="tab" id="name-header-add">
337				<div class="card-title mb-0">
338					<b>' . I18N::translate('Gender') . '</b> ' . $sex . $edit_links . '
339				</div>
340			</div>
341		</div>';
342    }
343
344    /**
345     * Which tabs should we show on this individual's page.
346     * We don't show empty tabs.
347     *
348     * @param Individual $individual
349     *
350     * @return Collection
351     */
352    public function getSidebars(Individual $individual): Collection
353    {
354        return $this->module_service->findByComponent(ModuleSidebarInterface::class, $individual->tree(), Auth::user())
355            ->filter(static function (ModuleSidebarInterface $sidebar) use ($individual): bool {
356                return $sidebar->hasSidebarContent($individual);
357            });
358    }
359
360    /**
361     * Which tabs should we show on this individual's page.
362     * We don't show empty tabs.
363     *
364     * @param Individual $individual
365     *
366     * @return Collection
367     */
368    public function getTabs(Individual $individual): Collection
369    {
370        return $this->module_service->findByComponent(ModuleTabInterface::class, $individual->tree(), Auth::user())
371            ->filter(static function (ModuleTabInterface $tab) use ($individual): bool {
372                return $tab->hasTabContent($individual);
373            });
374    }
375
376    /**
377     * What are the significant elements of this page?
378     * The layout will need them to generate URLs for charts and reports.
379     *
380     * @param Individual $individual
381     *
382     * @return stdClass
383     */
384    private function significant(Individual $individual): stdClass
385    {
386        [$surname] = explode(',', $individual->sortName());
387
388        $family = $individual->childFamilies()->merge($individual->spouseFamilies())->first();
389
390        return (object) [
391            'family'     => $family,
392            'individual' => $individual,
393            'surname'    => $surname,
394        ];
395    }
396}
397