xref: /webtrees/app/Http/RequestHandlers/CalendarEvents.php (revision 1da5dadd02c9f21e0a345e21a19b2c63ae792ed3)
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\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Date;
23use Fisharebest\Webtrees\Date\FrenchDate;
24use Fisharebest\Webtrees\Date\GregorianDate;
25use Fisharebest\Webtrees\Date\HijriDate;
26use Fisharebest\Webtrees\Date\JalaliDate;
27use Fisharebest\Webtrees\Date\JewishDate;
28use Fisharebest\Webtrees\Date\JulianDate;
29use Fisharebest\Webtrees\Fact;
30use Fisharebest\Webtrees\Family;
31use Fisharebest\Webtrees\I18N;
32use Fisharebest\Webtrees\Individual;
33use Fisharebest\Webtrees\Registry;
34use Fisharebest\Webtrees\Services\CalendarService;
35use Fisharebest\Webtrees\Tree;
36use Fisharebest\Webtrees\Validator;
37use Illuminate\Support\Collection;
38use Psr\Http\Message\ResponseInterface;
39use Psr\Http\Message\ServerRequestInterface;
40use Psr\Http\Server\RequestHandlerInterface;
41
42use function count;
43use function e;
44use function explode;
45use function get_class;
46use function ob_get_clean;
47use function ob_start;
48use function range;
49use function response;
50use function view;
51
52/**
53 * Show anniversaries for events in a given day/month/year.
54 */
55class CalendarEvents implements RequestHandlerInterface
56{
57    private CalendarService $calendar_service;
58
59    /**
60     * @param CalendarService $calendar_service
61     */
62    public function __construct(CalendarService $calendar_service)
63    {
64        $this->calendar_service = $calendar_service;
65    }
66
67    /**
68     * Show anniversaries that occurred on a given day/month/year.
69     *
70     * @param ServerRequestInterface $request
71     *
72     * @return ResponseInterface
73     */
74    public function handle(ServerRequestInterface $request): ResponseInterface
75    {
76        $tree     = Validator::attributes($request)->tree();
77        $view     = Validator::attributes($request)->isInArray(['day', 'month', 'year'])->string('view');
78        $cal      = Validator::queryParams($request)->string('cal');
79        $day      = Validator::queryParams($request)->string('day');
80        $month    = Validator::queryParams($request)->string('month');
81        $year     = Validator::queryParams($request)->string('year');
82        $filterev = Validator::queryParams($request)->string('filterev');
83        $filterof = Validator::queryParams($request)->string('filterof');
84        $filtersx = Validator::queryParams($request)->string('filtersx');
85
86        $ged_date = new Date($cal . ' ' . $day . ' ' . $month . ' ' . $year);
87        $cal_date = $ged_date->minimumDate();
88        $today    = $cal_date->today();
89
90        $days_in_month = $cal_date->daysInMonth();
91        $days_in_week  = $cal_date->daysInWeek();
92
93        $CALENDAR_FORMAT = $tree->getPreference('CALENDAR_FORMAT');
94
95        // Day and year share the same layout.
96        if ($view !== 'month') {
97            if ($view === 'day') {
98                $anniversary_facts = $this->calendar_service->getAnniversaryEvents($cal_date->minimumJulianDay(), $filterev, $tree, $filterof, $filtersx);
99            } else {
100                $ged_year          = new Date($cal . ' ' . $year);
101                $anniversary_facts = $this->calendar_service->getCalendarEvents($ged_year->minimumJulianDay(), $ged_year->maximumJulianDay(), $filterev, $tree, $filterof, $filtersx);
102            }
103
104            $anniversaries = Collection::make($anniversary_facts)
105                ->unique()
106                ->sort(static function (Fact $x, Fact $y): int {
107                    return $x->date()->minimumJulianDay() <=> $y->date()->minimumJulianDay();
108                });
109
110            $family_anniversaries = $anniversaries->filter(static function (Fact $f): bool {
111                return $f->record() instanceof Family;
112            });
113
114            $individual_anniversaries = $anniversaries->filter(static function (Fact $f): bool {
115                return $f->record() instanceof Individual;
116            });
117
118            return response(view('calendar-list', [
119                'family_anniversaries'     => $family_anniversaries,
120                'individual_anniversaries' => $individual_anniversaries,
121            ]));
122        }
123
124        $found_facts = [];
125
126        $cal_date->day = 0;
127        $cal_date->setJdFromYmd();
128        // Make a separate list for each day. Unspecified/invalid days go in day 0.
129        for ($d = 0; $d <= $days_in_month; ++$d) {
130            $found_facts[$d] = [];
131        }
132        // Fetch events for each day
133        $jds = range($cal_date->minimumJulianDay(), $cal_date->maximumJulianDay());
134
135        foreach ($jds as $jd) {
136            foreach ($this->calendar_service->getAnniversaryEvents($jd, $filterev, $tree, $filterof, $filtersx) as $fact) {
137                $tmp = $fact->date()->minimumDate();
138                if ($tmp->day >= 1 && $tmp->day <= $tmp->daysInMonth()) {
139                    // If the day is valid (for its own calendar), display it in the
140                    // anniversary day (for the display calendar).
141                    $found_facts[$jd - $cal_date->minimumJulianDay() + 1][] = $fact;
142                } else {
143                    // Otherwise, display it in the "Day not set" box.
144                    $found_facts[0][] = $fact;
145                }
146            }
147        }
148
149        $cal_facts = [];
150
151        foreach ($found_facts as $d => $facts) {
152            $cal_facts[$d] = [];
153            foreach ($facts as $fact) {
154                $xref = $fact->record()->xref();
155                $text = $fact->label() . ' — ' . $fact->date()->display($tree);
156                if ($fact->anniv > 0) {
157                    $text .= ' (' . I18N::translate('%s year anniversary', I18N::number($fact->anniv)) . ')';
158                }
159                if (empty($cal_facts[$d][$xref])) {
160                    $cal_facts[$d][$xref] = $text;
161                } else {
162                    $cal_facts[$d][$xref] .= '<br>' . $text;
163                }
164            }
165        }
166        // We use JD%7 = 0/Mon…6/Sun. Standard definitions use 0/Sun…6/Sat.
167        $week_start    = (I18N::locale()->territory()->firstDay() + 6) % 7;
168        $weekend_start = (I18N::locale()->territory()->weekendStart() + 6) % 7;
169        $weekend_end   = (I18N::locale()->territory()->weekendEnd() + 6) % 7;
170
171        // The French calendar has a 10-day week, which starts on primidi.
172        if ($days_in_week === 10) {
173            $week_start    = 0;
174            $weekend_start = -1;
175            $weekend_end   = -1;
176        }
177
178        ob_start();
179
180        echo '<table class="w-100 wt-calendar-month"><thead><tr>';
181        for ($week_day = 0; $week_day < $days_in_week; ++$week_day) {
182            $day_name = $cal_date->dayNames(($week_day + $week_start) % $days_in_week);
183            if ($week_day === $weekend_start || $week_day === $weekend_end) {
184                echo '<th class="wt-page-options-label weekend" width="', 100 / $days_in_week, '%">', $day_name, '</th>';
185            } else {
186                echo '<th class="wt-page-options-label" width="', 100 / $days_in_week, '%">', $day_name, '</th>';
187            }
188        }
189        echo '</tr>';
190        echo '</thead>';
191        echo '<tbody>';
192        // Print days 1 to n of the month, but extend to cover "empty" days before/after the month to make whole weeks.
193        // e.g. instead of 1 -> 30 (=30 days), we might have -1 -> 33 (=35 days)
194        $start_d = 1 - ($cal_date->minimumJulianDay() - $week_start) % $days_in_week;
195        $end_d   = $days_in_month + ($days_in_week - ($cal_date->maximumJulianDay() - $week_start + 1) % $days_in_week) % $days_in_week;
196        // Make sure that there is an empty box for any leap/missing days
197        if ($start_d === 1 && $end_d === $days_in_month && count($found_facts[0]) > 0) {
198            $end_d += $days_in_week;
199        }
200        for ($d = $start_d; $d <= $end_d; ++$d) {
201            if (($d + $cal_date->minimumJulianDay() - $week_start) % $days_in_week === 1) {
202                echo '<tr>';
203            }
204            echo '<td class="wt-page-options-value">';
205            if ($d < 1 || $d > $days_in_month) {
206                if (count($cal_facts[0]) > 0) {
207                    echo '<div class="cal_day">', I18N::translate('Day not set'), '</div>';
208                    echo '<div class="small" style="height: 180px; overflow: auto;">';
209                    echo $this->calendarListText($cal_facts[0], $tree);
210                    echo '</div>';
211                    $cal_facts[0] = [];
212                }
213            } else {
214                // Format the day number using the calendar
215                $tmp   = new Date($cal_date->format('%@ ' . $d . ' %O %E'));
216                $d_fmt = $tmp->minimumDate()->format('%j');
217                echo '<div class="d-flex d-flex justify-content-between">';
218                if ($d === $today->day && $cal_date->month === $today->month) {
219                    echo '<span class="cal_day current_day">', $d_fmt, '</span>';
220                } else {
221                    echo '<span class="cal_day">', $d_fmt, '</span>';
222                }
223                // Show a converted date
224                foreach (explode('_and_', $CALENDAR_FORMAT) as $convcal) {
225                    switch ($convcal) {
226                        case 'french':
227                            $alt_date = new FrenchDate($cal_date->minimumJulianDay() + $d - 1);
228                            break;
229                        case 'gregorian':
230                            $alt_date = new GregorianDate($cal_date->minimumJulianDay() + $d - 1);
231                            break;
232                        case 'jewish':
233                            $alt_date = new JewishDate($cal_date->minimumJulianDay() + $d - 1);
234                            break;
235                        case 'julian':
236                            $alt_date = new JulianDate($cal_date->minimumJulianDay() + $d - 1);
237                            break;
238                        case 'hijri':
239                            $alt_date = new HijriDate($cal_date->minimumJulianDay() + $d - 1);
240                            break;
241                        case 'jalali':
242                            $alt_date = new JalaliDate($cal_date->minimumJulianDay() + $d - 1);
243                            break;
244                        case 'none':
245                        default:
246                            $alt_date = $cal_date;
247                            break;
248                    }
249                    if (get_class($alt_date) !== get_class($cal_date) && $alt_date->inValidRange()) {
250                        echo '<span class="rtl_cal_day">' . $alt_date->format('%j %M') . '</span>';
251                        // Just show the first conversion
252                        break;
253                    }
254                }
255                echo '</div>';
256                echo '<div class="small" style="height: 180px; overflow: auto;">';
257                echo $this->calendarListText($cal_facts[$d], $tree);
258                echo '</div>';
259            }
260            echo '</td>';
261            if (($d + $cal_date->minimumJulianDay() - $week_start) % $days_in_week === 0) {
262                echo '</tr>';
263            }
264        }
265        echo '</tbody>';
266        echo '</table>';
267
268        return response(ob_get_clean());
269    }
270
271    /**
272     * Format a list of facts for display
273     *
274     * @param array<string> $list
275     * @param Tree          $tree
276     *
277     * @return string
278     */
279    private function calendarListText(array $list, Tree $tree): string
280    {
281        $html = '';
282
283        foreach ($list as $xref => $facts) {
284            $tmp = Registry::gedcomRecordFactory()->make((string) $xref, $tree);
285            $html .= '<a href="' . e($tmp->url()) . '">' . $tmp->fullName() . '</a> ';
286            $html .= '<div class="indent">' . $facts . '</div>';
287        }
288
289        return $html;
290    }
291}
292