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