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