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