xref: /webtrees/app/Module/UpcomingAnniversariesModule.php (revision 7413816e6dd2d50e569034fb804f3dce7471bb94)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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    public function description(): string
126    {
127        /* I18N: Description of the “Upcoming events” module */
128        return I18N::translate('A list of the anniversaries that will occur in the near future.');
129    }
130
131    /**
132     * Generate the HTML content of this block.
133     *
134     * @param Tree                 $tree
135     * @param int                  $block_id
136     * @param string               $context
137     * @param array<string,string> $config
138     *
139     * @return string
140     */
141    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
142    {
143        $default_events = implode(',', self::DEFAULT_EVENTS);
144
145        $days      = (int)$this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
146        $filter    = (bool)$this->getBlockSetting($block_id, 'filter', self::DEFAULT_FILTER);
147        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
148        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT);
149        $events    = $this->getBlockSetting($block_id, 'events', $default_events);
150
151        extract($config, EXTR_OVERWRITE);
152
153        $event_array = explode(',', $events);
154
155        // If we are only showing living individuals, then we don't need to search for DEAT events.
156        if ($filter) {
157            $event_array = array_diff($event_array, Gedcom::DEATH_EVENTS);
158        }
159
160        $events_filter = implode('|', $event_array);
161
162        $startjd = Registry::timestampFactory()->now()->addDays(1)->julianDay();
163        $endjd   = Registry::timestampFactory()->now()->addDays($days)->julianDay();
164
165        $facts = $this->calendar_service->getEventsList($startjd, $endjd, $events_filter, $filter, $sortStyle, $tree);
166
167        if ($facts->isEmpty()) {
168            if ($endjd === $startjd) {
169                if ($filter && Auth::check()) {
170                    $message = I18N::translate('No events for living individuals exist for tomorrow.');
171                } else {
172                    $message = I18N::translate('No events exist for tomorrow.');
173                }
174            } else {
175                if ($filter && Auth::check()) {
176                    $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));
177                } else {
178                    $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));
179                }
180            }
181
182            $content = view('modules/upcoming_events/empty', ['message' => $message]);
183        } elseif ($infoStyle === 'list') {
184            $content = view('lists/anniversaries-list', [
185                'id'         => $block_id,
186                'facts'      => $facts,
187                'limit_low'  => self::LIMIT_LOW,
188                'limit_high' => self::LIMIT_HIGH,
189            ]);
190        } else {
191            $content = view('lists/anniversaries-table', [
192                'facts'      => $facts,
193                'limit_low'  => self::LIMIT_LOW,
194                'limit_high' => self::LIMIT_HIGH,
195                'order'      => self::DATATABLES_ORDER[$sortStyle],
196            ]);
197        }
198
199        if ($context !== self::CONTEXT_EMBED) {
200            return view('modules/block-template', [
201                'block'      => Str::kebab($this->name()),
202                'id'         => $block_id,
203                'config_url' => $this->configUrl($tree, $context, $block_id),
204                'title'      => $this->title(),
205                'content'    => $content,
206            ]);
207        }
208
209        return $content;
210    }
211
212    /**
213     * Should this block load asynchronously using AJAX?
214     *
215     * Simple blocks are faster in-line, more complex ones can be loaded later.
216     *
217     * @return bool
218     */
219    public function loadAjax(): bool
220    {
221        return true;
222    }
223
224    /**
225     * Can this block be shown on the user’s home page?
226     *
227     * @return bool
228     */
229    public function isUserBlock(): bool
230    {
231        return true;
232    }
233
234    /**
235     * Can this block be shown on the tree’s home page?
236     *
237     * @return bool
238     */
239    public function isTreeBlock(): bool
240    {
241        return true;
242    }
243
244    /**
245     * Update the configuration for a block.
246     *
247     * @param ServerRequestInterface $request
248     * @param int                    $block_id
249     *
250     * @return void
251     */
252    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
253    {
254        $days       = Validator::parsedBody($request)->isBetween(1, self::MAX_DAYS)->integer('days');
255        $filter     = Validator::parsedBody($request)->boolean('filter');
256        $info_style = Validator::parsedBody($request)->isInArrayKeys($this->infoStyles())->string('infoStyle');
257        $sort_style = Validator::parsedBody($request)->isInArrayKeys($this->sortStyles())->string('sortStyle');
258        $events     = Validator::parsedBody($request)->array('events');
259
260        $this->setBlockSetting($block_id, 'days', (string)$days);
261        $this->setBlockSetting($block_id, 'filter', (string)$filter);
262        $this->setBlockSetting($block_id, 'infoStyle', $info_style);
263        $this->setBlockSetting($block_id, 'sortStyle', $sort_style);
264        $this->setBlockSetting($block_id, 'events', implode(',', $events));
265    }
266
267    /**
268     * An HTML form to edit block settings
269     *
270     * @param Tree $tree
271     * @param int  $block_id
272     *
273     * @return string
274     */
275    public function editBlockConfiguration(Tree $tree, int $block_id): string
276    {
277        $default_events = implode(',', self::DEFAULT_EVENTS);
278
279        $days       = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
280        $filter     = $this->getBlockSetting($block_id, 'filter', self::DEFAULT_FILTER);
281        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
282        $sort_style = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT);
283        $events     = $this->getBlockSetting($block_id, 'events', $default_events);
284
285        $event_array = explode(',', $events);
286
287        $all_events = [];
288        foreach (self::ALL_EVENTS as $event => $tag) {
289            $all_events[$event] = Registry::elementFactory()->make($tag)->label();
290        }
291
292        return view('modules/upcoming_events/config', [
293            'all_events'  => $all_events,
294            'days'        => $days,
295            'event_array' => $event_array,
296            'filter'      => $filter,
297            'info_style'  => $info_style,
298            'info_styles' => $this->infoStyles(),
299            'max_days'    => self::MAX_DAYS,
300            'sort_style'  => $sort_style,
301            'sort_styles' => $this->sortStyles(),
302        ]);
303    }
304
305    /**
306     * @return array<string,string>
307     */
308    private function infoStyles(): array
309    {
310        return [
311            self::LAYOUT_STYLE_LIST  => /* I18N: An option in a list-box */ I18N::translate('list'),
312            self::LAYOUT_STYLE_TABLE => /* I18N: An option in a list-box */ I18N::translate('table'),
313        ];
314    }
315
316    /**
317     * @return array<string,string>
318     */
319    private function sortStyles(): array
320    {
321        return [
322            self::SORT_STYLE_NAME => /* I18N: An option in a list-box */ I18N::translate('sort by name'),
323            self::SORT_STYLE_DATE => /* I18N: An option in a list-box */ I18N::translate('sort by date'),
324        ];
325    }
326}
327