xref: /webtrees/app/Module/ShareAnniversaryModule.php (revision b55cbc6b43247e8b2ad14af6f6d24dc6747195ff)
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\Module;
21
22use Aura\Router\RouterContainer;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Date\GregorianDate;
25use Fisharebest\Webtrees\Fact;
26use Fisharebest\Webtrees\Family;
27use Fisharebest\Webtrees\GedcomRecord;
28use Fisharebest\Webtrees\Http\Exceptions\HttpNotFoundException;
29use Fisharebest\Webtrees\I18N;
30use Fisharebest\Webtrees\Individual;
31use Fisharebest\Webtrees\Registry;
32use Fisharebest\Webtrees\Validator;
33use Illuminate\Support\Collection;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Server\RequestHandlerInterface;
37use Sabre\VObject\Component\VCalendar;
38
39use function app;
40use function assert;
41use function response;
42use function route;
43use function strip_tags;
44use function view;
45
46/**
47 * Class ShareAnniversaryModule
48 */
49class ShareAnniversaryModule extends AbstractModule implements ModuleShareInterface, RequestHandlerInterface
50{
51    use ModuleShareTrait;
52
53    protected const INDIVIDUAL_EVENTS = ['BIRT', 'DEAT'];
54    protected const FAMILY_EVENTS     = ['MARR'];
55
56    protected const ROUTE_URL = '/tree/{tree}/anniversary-ics/{xref}/{fact_id}';
57
58    /**
59     * Initialization.
60     *
61     * @return void
62     */
63    public function boot(): void
64    {
65        $router_container = app(RouterContainer::class);
66        assert($router_container instanceof RouterContainer);
67
68        $router_container->getMap()
69            ->get(static::class, static::ROUTE_URL, $this);
70    }
71
72    /**
73     * How should this module be identified in the control panel, etc.?
74     *
75     * @return string
76     */
77    public function title(): string
78    {
79        return I18N::translate('Share the anniversary of an event');
80    }
81
82    /**
83     * A sentence describing what this module does.
84     *
85     * @return string
86     */
87    public function description(): string
88    {
89        return I18N::translate('Download a .ICS file containing an anniversary');
90    }
91
92    /**
93     * HTML to include in the share links page.
94     *
95     * @param GedcomRecord $record
96     *
97     * @return string
98     */
99    public function share(GedcomRecord $record): string
100    {
101        if ($record instanceof Individual) {
102            $facts = $record->facts(static::INDIVIDUAL_EVENTS, true)
103                ->merge($record->spouseFamilies()->map(fn (Family $family): Collection => $family->facts(static::FAMILY_EVENTS, true)));
104        } elseif ($record instanceof Family) {
105            $facts = $record->facts(static::FAMILY_EVENTS, true);
106        } else {
107            return '';
108        }
109
110        // iCalendar only supports exact Gregorian dates.
111        $facts = $facts
112            ->flatten()
113            ->filter(fn (Fact $fact): bool => $fact->date()->isOK())
114            ->filter(fn (Fact $fact): bool => $fact->date()->qual1 === '')
115            ->filter(fn (Fact $fact): bool => $fact->date()->minimumDate() instanceof GregorianDate)
116            ->filter(fn (Fact $fact): bool => $fact->date()->minimumJulianDay() === $fact->date()->maximumJulianDay())
117            ->mapWithKeys(fn (Fact $fact): array => [
118                route(static::class, ['tree' => $record->tree()->name(), 'xref' => $fact->record()->xref(), 'fact_id' => $fact->id()]) =>
119                    $fact->label() . ' — ' . $fact->date()->display(),
120            ]);
121
122        if ($facts->isNotEmpty()) {
123            $url = route(static::class, ['tree' => $record->tree()->name(), 'xref' => $record->xref()]);
124
125            return view('modules/share-anniversary/share', [
126                'facts'  => $facts,
127                'record' => $record,
128                'url'    => $url,
129            ]);
130        }
131
132        return '';
133    }
134
135    /**
136     * @param ServerRequestInterface $request
137     *
138     * @return ResponseInterface
139     */
140    public function handle(ServerRequestInterface $request): ResponseInterface
141    {
142        $tree    = Validator::attributes($request)->tree();
143        $xref    = Validator::attributes($request)->isXref()->string('xref');
144        $fact_id = Validator::attributes($request)->string('fact_id');
145        $record  = Registry::gedcomRecordFactory()->make($xref, $tree);
146        $record  = Auth::checkRecordAccess($record);
147
148        $fact = $record->facts()
149            ->filter(fn (Fact $fact): bool => $fact->id() === $fact_id)
150            ->first();
151
152        if ($fact instanceof Fact) {
153            $date             = $fact->date()->minimumDate()->format('%Y%m%d');
154            $vcalendar        = new VCalendar();
155            $vevent           = $vcalendar->add('VEVENT');
156            $dtstart          = $vevent->add('DTSTART', $date);
157            $dtstart['VALUE'] = 'DATE';
158            $vevent->add('RRULE', 'FREQ=YEARLY');
159            $vevent->add('SUMMARY', strip_tags($record->fullName()) . ' — ' . $fact->label());
160
161            return response($vcalendar->serialize())
162                ->withHeader('Content-Type', 'text/calendar')
163                ->withHeader('Content-Disposition', 'attachment; filename="' . $fact->id() . '.ics');
164        }
165
166        throw new HttpNotFoundException();
167    }
168}
169