CalendarEvents::calendarListText()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2025 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
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22
use Fisharebest\Webtrees\Date;
23
use Fisharebest\Webtrees\Date\FrenchDate;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Date\FrenchDate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
use Fisharebest\Webtrees\Date\GregorianDate;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Date\GregorianDate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
25
use Fisharebest\Webtrees\Date\HijriDate;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Date\HijriDate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use Fisharebest\Webtrees\Date\JalaliDate;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Date\JalaliDate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use Fisharebest\Webtrees\Date\JewishDate;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Date\JewishDate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
use Fisharebest\Webtrees\Date\JulianDate;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Date\JulianDate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
use Fisharebest\Webtrees\Fact;
30
use Fisharebest\Webtrees\Family;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Family was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
use Fisharebest\Webtrees\I18N;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\I18N was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
use Fisharebest\Webtrees\Individual;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Individual was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
33
use Fisharebest\Webtrees\Registry;
34
use Fisharebest\Webtrees\Services\CalendarService;
0 ignored issues
show
Bug introduced by
The type Fisharebest\Webtrees\Services\CalendarService was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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