xref: /webtrees/app/Module/UpcomingAnniversariesModule.php (revision 05cb977553b96deb344ffd980d716e418e5c79a1)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Gedcom;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Registry;
26use Fisharebest\Webtrees\Services\CalendarService;
27use Fisharebest\Webtrees\Tree;
28use Fisharebest\Webtrees\Validator;
29use Illuminate\Support\Str;
30use Psr\Http\Message\ServerRequestInterface;
31
32/**
33 * Class UpcomingAnniversariesModule
34 */
35class UpcomingAnniversariesModule extends AbstractModule implements ModuleBlockInterface
36{
37    use ModuleBlockTrait;
38
39    private const SORT_STYLE_DATE = 'anniv';
40    private const SORT_STYLE_NAME = 'alpha';
41
42    private const LAYOUT_STYLE_LIST  = 'list';
43    private const LAYOUT_STYLE_TABLE = 'table';
44
45    // Default values for new blocks.
46    private const DEFAULT_DAYS   = '7';
47    private const DEFAULT_FILTER = '1';
48    private const DEFAULT_SORT   = self::SORT_STYLE_NAME;
49    private const DEFAULT_STYLE  = self::LAYOUT_STYLE_TABLE;
50
51    // Initial sorting for datatables
52    private const DATATABLES_ORDER = [
53        self::SORT_STYLE_NAME => [[0, 'asc']],
54        self::SORT_STYLE_DATE => [[1, 'asc']],
55    ];
56
57    // Can show this number of days into the future.
58    private const MAX_DAYS = 30;
59
60    // Pagination
61    private const LIMIT_LOW  = 10;
62    private const LIMIT_HIGH = 20;
63
64    // All standard GEDCOM 5.5.1 events except CENS, RESI and EVEN
65    private const ALL_EVENTS = [
66        'ADOP' => 'INDI:ADOP',
67        'ANUL' => 'FAM:ANUL',
68        'BAPM' => 'INDI:BAPM',
69        'BARM' => 'INDI:BARM',
70        'BASM' => 'INDI:BASM',
71        'BIRT' => 'INDI:BIRT',
72        'BLES' => 'INDI:BLES',
73        'BURI' => 'INDI:BURI',
74        'CHR'  => 'INDI:CHR',
75        'CHRA' => 'INDI:CHRA',
76        'CONF' => 'INDI:CONF',
77        'CREM' => 'INDI:CREM',
78        'DEAT' => 'INDI:DEAT',
79        'DIV'  => 'FAM:DIV',
80        'DIVF' => 'FAM:DIVF',
81        'EMIG' => 'INDI:EMIG',
82        'ENGA' => 'FAM:ENGA',
83        'FCOM' => 'INDI:FCOM',
84        'GRAD' => 'INDI:GRAD',
85        'IMMI' => 'INDI:IMMI',
86        'MARB' => 'FAM:MARB',
87        'MARC' => 'FAM:MARC',
88        'MARL' => 'FAM:MARL',
89        'MARR' => 'FAM:MARR',
90        'MARS' => 'FAM:MARS',
91        'NATU' => 'INDI:NATU',
92        'ORDN' => 'INDI:ORDN',
93        'PROB' => 'INDI:PROB',
94        'RETI' => 'INDI:RETI',
95        'WILL' => 'INDI:WILL',
96    ];
97
98    private const DEFAULT_EVENTS = [
99        'BIRT',
100        'MARR',
101        'DEAT',
102    ];
103
104    private CalendarService $calendar_service;
105
106    /**
107     * @param CalendarService $calendar_service
108     */
109    public function __construct(CalendarService $calendar_service)
110    {
111        $this->calendar_service = $calendar_service;
112    }
113
114    /**
115     * How should this module be identified in the control panel, etc.?
116     *
117     * @return string
118     */
119    public function title(): string
120    {
121        /* I18N: Name of a module */
122        return I18N::translate('Upcoming events');
123    }
124
125    /**
126     * A sentence describing what this module does.
127     *
128     * @return string
129     */
130    public function description(): string
131    {
132        /* I18N: Description of the “Upcoming events” module */
133        return I18N::translate('A list of the anniversaries that will occur in the near future.');
134    }
135
136    /**
137     * Generate the HTML content of this block.
138     *
139     * @param Tree                 $tree
140     * @param int                  $block_id
141     * @param string               $context
142     * @param array<string,string> $config
143     *
144     * @return string
145     */
146    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
147    {
148        $default_events = implode(',', self::DEFAULT_EVENTS);
149
150        $days      = (int)$this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
151        $filter    = (bool)$this->getBlockSetting($block_id, 'filter', self::DEFAULT_FILTER);
152        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
153        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT);
154        $events    = $this->getBlockSetting($block_id, 'events', $default_events);
155
156        extract($config, EXTR_OVERWRITE);
157
158        $event_array = explode(',', $events);
159
160        // If we are only showing living individuals, then we don't need to search for DEAT events.
161        if ($filter) {
162            $event_array = array_diff($event_array, Gedcom::DEATH_EVENTS);
163        }
164
165        $events_filter = implode('|', $event_array);
166
167        $startjd = Registry::timestampFactory()->now()->addDays(1)->julianDay();
168        $endjd   = Registry::timestampFactory()->now()->addDays($days)->julianDay();
169
170        $facts = $this->calendar_service->getEventsList($startjd, $endjd, $events_filter, $filter, $sortStyle, $tree);
171
172        if ($facts->isEmpty()) {
173            if ($endjd === $startjd) {
174                if ($filter && Auth::check()) {
175                    $message = I18N::translate('No events for living individuals exist for tomorrow.');
176                } else {
177                    $message = I18N::translate('No events exist for tomorrow.');
178                }
179
180                $content = view('modules/upcoming_events/empty', ['message' => $message]);
181            } else {
182                if ($filter && Auth::check()) {
183                    /* I18N: translation for %s==1 is unused; it is translated separately as “tomorrow” */
184                    $message = I18N::plural('No events for living people exist for the next %s day.', 'No events for living people exist for the next %s days.', $endjd - $startjd + 1, I18N::number($endjd - $startjd + 1));
185                } else {
186                    /* I18N: translation for %s==1 is unused; it is translated separately as “tomorrow” */
187                    $message = I18N::plural('No events exist for the next %s day.', 'No events exist for the next %s days.', $endjd - $startjd + 1, I18N::number($endjd - $startjd + 1));
188                }
189                $content = view('modules/upcoming_events/empty', ['message' => $message]);
190            }
191        } elseif ($infoStyle === 'list') {
192            $content = view('lists/anniversaries-list', [
193                'id'         => $block_id,
194                'facts'      => $facts,
195                'limit_low'  => self::LIMIT_LOW,
196                'limit_high' => self::LIMIT_HIGH,
197            ]);
198        } else {
199            $content = view('lists/anniversaries-table', [
200                'facts'      => $facts,
201                'limit_low'  => self::LIMIT_LOW,
202                'limit_high' => self::LIMIT_HIGH,
203                'order'      => self::DATATABLES_ORDER[$sortStyle],
204            ]);
205        }
206
207        if ($context !== self::CONTEXT_EMBED) {
208            return view('modules/block-template', [
209                'block'      => Str::kebab($this->name()),
210                'id'         => $block_id,
211                'config_url' => $this->configUrl($tree, $context, $block_id),
212                'title'      => $this->title(),
213                'content'    => $content,
214            ]);
215        }
216
217        return $content;
218    }
219
220    /**
221     * Should this block load asynchronously using AJAX?
222     *
223     * Simple blocks are faster in-line, more complex ones can be loaded later.
224     *
225     * @return bool
226     */
227    public function loadAjax(): bool
228    {
229        return true;
230    }
231
232    /**
233     * Can this block be shown on the user’s home page?
234     *
235     * @return bool
236     */
237    public function isUserBlock(): bool
238    {
239        return true;
240    }
241
242    /**
243     * Can this block be shown on the tree’s home page?
244     *
245     * @return bool
246     */
247    public function isTreeBlock(): bool
248    {
249        return true;
250    }
251
252    /**
253     * Update the configuration for a block.
254     *
255     * @param ServerRequestInterface $request
256     * @param int                    $block_id
257     *
258     * @return void
259     */
260    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
261    {
262        $days       = Validator::parsedBody($request)->isBetween(1, self::MAX_DAYS)->integer('days');
263        $filter     = Validator::parsedBody($request)->boolean('filter');
264        $info_style = Validator::parsedBody($request)->isInArrayKeys($this->infoStyles())->string('infoStyle');
265        $sort_style = Validator::parsedBody($request)->isInArrayKeys($this->sortStyles())->string('sortStyle');
266        $events     = Validator::parsedBody($request)->array('events');
267
268        $this->setBlockSetting($block_id, 'days', (string)$days);
269        $this->setBlockSetting($block_id, 'filter', (string)$filter);
270        $this->setBlockSetting($block_id, 'infoStyle', $info_style);
271        $this->setBlockSetting($block_id, 'sortStyle', $sort_style);
272        $this->setBlockSetting($block_id, 'events', implode(',', $events));
273    }
274
275    /**
276     * An HTML form to edit block settings
277     *
278     * @param Tree $tree
279     * @param int  $block_id
280     *
281     * @return string
282     */
283    public function editBlockConfiguration(Tree $tree, int $block_id): string
284    {
285        $default_events = implode(',', self::DEFAULT_EVENTS);
286
287        $days       = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
288        $filter     = $this->getBlockSetting($block_id, 'filter', self::DEFAULT_FILTER);
289        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
290        $sort_style = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT);
291        $events     = $this->getBlockSetting($block_id, 'events', $default_events);
292
293        $event_array = explode(',', $events);
294
295        $all_events = [];
296        foreach (self::ALL_EVENTS as $event => $tag) {
297            $all_events[$event] = Registry::elementFactory()->make($tag)->label();
298        }
299
300        return view('modules/upcoming_events/config', [
301            'all_events'  => $all_events,
302            'days'        => $days,
303            'event_array' => $event_array,
304            'filter'      => $filter,
305            'info_style'  => $info_style,
306            'info_styles' => $this->infoStyles(),
307            'max_days'    => self::MAX_DAYS,
308            'sort_style'  => $sort_style,
309            'sort_styles' => $this->sortStyles(),
310        ]);
311    }
312
313    /**
314     * @return array<string,string>
315     */
316    private function infoStyles(): array
317    {
318        return [
319            self::LAYOUT_STYLE_LIST  => /* I18N: An option in a list-box */ I18N::translate('list'),
320            self::LAYOUT_STYLE_TABLE => /* I18N: An option in a list-box */ I18N::translate('table'),
321        ];
322    }
323
324    /**
325     * @return array<string,string>
326     */
327    private function sortStyles(): array
328    {
329        return [
330            self::SORT_STYLE_NAME => /* I18N: An option in a list-box */ I18N::translate('sort by name'),
331            self::SORT_STYLE_DATE => /* I18N: An option in a list-box */ I18N::translate('sort by date'),
332        ];
333    }
334}
335