xref: /webtrees/app/Services/CalendarService.php (revision ac71572d8462e396ed5a307f05b29381e49f9e6e)
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\Services;
21
22use Fisharebest\ExtCalendar\PersianCalendar;
23use Fisharebest\Webtrees\Date;
24use Fisharebest\Webtrees\Date\AbstractCalendarDate;
25use Fisharebest\Webtrees\Date\FrenchDate;
26use Fisharebest\Webtrees\Date\GregorianDate;
27use Fisharebest\Webtrees\Date\HijriDate;
28use Fisharebest\Webtrees\Date\JalaliDate;
29use Fisharebest\Webtrees\Date\JewishDate;
30use Fisharebest\Webtrees\Date\JulianDate;
31use Fisharebest\Webtrees\Fact;
32use Fisharebest\Webtrees\Family;
33use Fisharebest\Webtrees\GedcomRecord;
34use Fisharebest\Webtrees\Individual;
35use Fisharebest\Webtrees\Registry;
36use Fisharebest\Webtrees\Tree;
37use Illuminate\Database\Capsule\Manager as DB;
38use Illuminate\Database\Query\Builder;
39use Illuminate\Database\Query\JoinClause;
40use Illuminate\Support\Collection;
41
42use function array_merge;
43use function assert;
44use function in_array;
45use function preg_match_all;
46use function range;
47
48/**
49 * Calculate anniversaries, etc.
50 */
51class CalendarService
52{
53    // If no facts specified, get all except these
54    protected const SKIP_FACTS = ['CHAN', 'BAPL', 'SLGC', 'SLGS', 'ENDL', 'CENS', 'RESI', 'NOTE', 'ADDR', 'OBJE', 'SOUR', '_TODO'];
55
56    /**
57     * List all the months in a given year.
58     *
59     * @param string $calendar
60     * @param int    $year
61     *
62     * @return array<string>
63     */
64    public function calendarMonthsInYear(string $calendar, int $year): array
65    {
66        $date          = new Date($calendar . ' ' . $year);
67        $calendar_date = $date->minimumDate();
68        $month_numbers = range(1, $calendar_date->monthsInYear());
69        $month_names   = [];
70
71        foreach ($month_numbers as $month_number) {
72            $calendar_date->day   = 1;
73            $calendar_date->month = $month_number;
74            $calendar_date->setJdFromYmd();
75
76            if ($month_number === 6 && $calendar_date instanceof JewishDate && !$calendar_date->isLeapYear()) {
77                // No month 6 in Jewish non-leap years.
78                continue;
79            }
80
81            if ($month_number === 7 && $calendar_date instanceof JewishDate && !$calendar_date->isLeapYear()) {
82                // Month 7 is ADR in Jewish non-leap years (and ADS in others).
83                $mon = 'ADR';
84            } else {
85                $mon = $calendar_date->format('%O');
86            }
87
88            $month_names[$mon] = $calendar_date->format('%F');
89        }
90
91        return $month_names;
92    }
93
94    /**
95     * Get a list of events which occurred during a given date range.
96     *
97     * @param int    $jd1      the start range of julian day
98     * @param int    $jd2      the end range of julian day
99     * @param string $facts    restrict the search to just these facts or leave blank for all
100     * @param Tree   $tree     the tree to search
101     * @param string $filterof filter by living/recent
102     * @param string $filtersx filter by sex
103     *
104     * @return array<Fact>
105     */
106    public function getCalendarEvents(int $jd1, int $jd2, string $facts, Tree $tree, string $filterof = '', string $filtersx = ''): array
107    {
108        // Events that start or end during the period
109        $query = DB::table('dates')
110            ->where('d_file', '=', $tree->id())
111            ->where(static function (Builder $query) use ($jd1, $jd2): void {
112                $query->where(static function (Builder $query) use ($jd1, $jd2): void {
113                    $query
114                        ->where('d_julianday1', '>=', $jd1)
115                        ->where('d_julianday1', '<=', $jd2);
116                })->orWhere(static function (Builder $query) use ($jd1, $jd2): void {
117                    $query
118                        ->where('d_julianday2', '>=', $jd1)
119                        ->where('d_julianday2', '<=', $jd2);
120                });
121            });
122
123        // Restrict to certain types of fact
124        if ($facts === '') {
125            $query->whereNotIn('d_fact', self::SKIP_FACTS);
126        } else {
127            preg_match_all('/([_A-Z]+)/', $facts, $matches);
128
129            $query->whereIn('d_fact', $matches[1]);
130        }
131
132        if ($filterof === 'recent') {
133            $query->where('d_julianday1', '>=', Registry::timestampFactory()->now()->subtractYears(100)->julianDay());
134        }
135
136        $ind_query = (clone $query)
137            ->join('individuals', static function (JoinClause $join): void {
138                $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
139            })
140            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
141
142        $queries = ['INDI' => $ind_query];
143
144        if ($filtersx === '') {
145            $fam_query = (clone $query)
146                ->join('families', static function (JoinClause $join): void {
147                    $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
148                })
149                ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
150
151            $queries['FAM'] = $fam_query;
152        } else {
153            $queries['INDI']->where('i_sex', '=', $filtersx);
154        }
155
156        // Now fetch these events
157        $found_facts = [];
158
159        foreach ($queries as $type => $record_query) {
160            foreach ($record_query->get() as $row) {
161                if ($type === 'INDI') {
162                    $record = Registry::individualFactory()->make($row->xref, $tree, $row->gedcom);
163                    assert($record instanceof Individual);
164
165                    if ($filterof === 'living' && $record->isDead()) {
166                        continue;
167                    }
168                } else {
169                    $record = Registry::familyFactory()->make($row->xref, $tree, $row->gedcom);
170                    assert($record instanceof Family);
171                    $husb = $record->husband();
172                    $wife = $record->wife();
173
174                    if ($filterof === 'living' && ($husb && $husb->isDead() || $wife && $wife->isDead())) {
175                        continue;
176                    }
177                }
178
179                $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
180
181                foreach ($record->facts([$row->d_fact]) as $fact) {
182                    // For date ranges, we need a match on either the start/end.
183                    if ($fact->date()->minimumJulianDay() === $anniv_date->minimumJulianDay() || $fact->date()->maximumJulianDay() === $anniv_date->maximumJulianDay()) {
184                        $fact->anniv   = 0;
185                        $found_facts[] = $fact;
186                    }
187                }
188            }
189        }
190
191        return $found_facts;
192    }
193
194    /**
195     * Get the list of current and upcoming events, sorted by anniversary date
196     *
197     * @param int    $jd1
198     * @param int    $jd2
199     * @param string $events
200     * @param bool   $only_living
201     * @param string $sort_by
202     * @param Tree   $tree
203     *
204     * @return Collection<int,Fact>
205     */
206    public function getEventsList(int $jd1, int $jd2, string $events, bool $only_living, string $sort_by, Tree $tree): Collection
207    {
208        $found_facts = [];
209        $facts       = new Collection();
210
211        foreach (range($jd1, $jd2) as $jd) {
212            $found_facts = array_merge($found_facts, $this->getAnniversaryEvents($jd, $events, $tree));
213        }
214
215        foreach ($found_facts as $fact) {
216            $record = $fact->record();
217            // only living people ?
218            if ($only_living) {
219                if ($record instanceof Individual && $record->isDead()) {
220                    continue;
221                }
222                if ($record instanceof Family) {
223                    $husb = $record->husband();
224                    if ($husb === null || $husb->isDead()) {
225                        continue;
226                    }
227                    $wife = $record->wife();
228                    if ($wife === null || $wife->isDead()) {
229                        continue;
230                    }
231                }
232            }
233            $facts->push($fact);
234        }
235
236        switch ($sort_by) {
237            case 'anniv':
238            case 'anniv_asc':
239                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
240                    return $x->jd <=> $y->jd ?: $x->date()->minimumJulianDay() <=> $y->date()->minimumJulianDay();
241                });
242                break;
243
244            case 'anniv_desc':
245                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
246                    return $x->jd <=> $y->jd ?: $y->date()->minimumJulianDay() <=> $x->date()->minimumJulianDay();
247                });
248                break;
249
250            case 'alpha':
251                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
252                    return GedcomRecord::nameComparator()($x->record(), $y->record());
253                });
254                break;
255        }
256
257        return $facts->values();
258    }
259
260    /**
261     * Get a list of events whose anniversary occurred on a given julian day.
262     * Used on the on-this-day/upcoming blocks and the day/month calendar views.
263     *
264     * @param int    $jd       the julian day
265     * @param string $facts    restrict the search to just these facts or leave blank for all
266     * @param Tree   $tree     the tree to search
267     * @param string $filterof filter by living/recent
268     * @param string $filtersx filter by sex
269     *
270     * @return array<Fact>
271     */
272    public function getAnniversaryEvents(int $jd, string $facts, Tree $tree, string $filterof = '', string $filtersx = ''): array
273    {
274        $found_facts = [];
275
276        $anniversaries = [
277            new GregorianDate($jd),
278            new JulianDate($jd),
279            new FrenchDate($jd),
280            new JewishDate($jd),
281            new HijriDate($jd),
282        ];
283
284        // There is a bug in the Persian Calendar that gives zero months for invalid dates
285        if ($jd > (new PersianCalendar())->jdStart()) {
286            $anniversaries[] = new JalaliDate($jd);
287        }
288
289        foreach ($anniversaries as $anniv) {
290            // Build a query to match anniversaries in the appropriate calendar.
291            $query = DB::table('dates')
292                ->distinct()
293                ->where('d_file', '=', $tree->id())
294                ->where('d_type', '=', $anniv->format('%@'));
295
296            // SIMPLE CASES:
297            // a) Non-hebrew anniversaries
298            // b) Hebrew months TVT, SHV, IYR, SVN, TMZ, AAV, ELL
299            if (!$anniv instanceof JewishDate || in_array($anniv->month, [1, 5, 6, 9, 10, 11, 12, 13], true)) {
300                $this->defaultAnniversaries($query, $anniv);
301            } else {
302                // SPECIAL CASES:
303                switch ($anniv->month) {
304                    case 2:
305                        $this->cheshvanAnniversaries($query, $anniv);
306                        break;
307                    case 3:
308                        $this->kislevAnniversaries($query, $anniv);
309                        break;
310                    case 4:
311                        $this->tevetAnniversaries($query, $anniv);
312                        break;
313                    case 7:
314                        $this->adarIIAnniversaries($query, $anniv);
315                        break;
316                    case 8:
317                        $this->nisanAnniversaries($query, $anniv);
318                        break;
319                }
320            }
321            // Only events in the past (includes dates without a year)
322            $query->where('d_year', '<=', $anniv->year());
323
324            if ($facts === '') {
325                // If no facts specified, get all except these
326                $query->whereNotIn('d_fact', self::SKIP_FACTS);
327            } else {
328                // Restrict to certain types of fact
329                preg_match_all('/([_A-Z]+)/', $facts, $matches);
330
331                $query->whereIn('d_fact', $matches[1]);
332            }
333
334            if ($filterof === 'recent') {
335                $query->where('d_julianday1', '>=', Registry::timestampFactory()->now()->subtractYears(100)->julianDay());
336            }
337
338            $query
339                ->orderBy('d_day')
340                ->orderBy('d_year', 'DESC');
341
342            $ind_query = (clone $query)
343                ->join('individuals', static function (JoinClause $join): void {
344                    $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
345                })
346                ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
347
348            $queries = ['INDI' => $ind_query];
349
350            if ($filtersx === '') {
351                $fam_query = (clone $query)
352                    ->join('families', static function (JoinClause $join): void {
353                        $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
354                    })
355                    ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
356
357                $queries['FAM'] = $fam_query;
358            } else {
359                $queries['INDI']->where('i_sex', '=', $filtersx);
360            }
361
362            // Now fetch these anniversaries
363            foreach ($queries as $type => $record_query) {
364                foreach ($record_query->get() as $row) {
365                    if ($type === 'INDI') {
366                        $record = Registry::individualFactory()->make($row->xref, $tree, $row->gedcom);
367                        assert($record instanceof Individual);
368
369                        if ($filterof === 'living' && $record->isDead()) {
370                            continue;
371                        }
372                    } else {
373                        $record = Registry::familyFactory()->make($row->xref, $tree, $row->gedcom);
374                        assert($record instanceof Family);
375                        $husb = $record->husband();
376                        $wife = $record->wife();
377
378                        if ($filterof === 'living' && ($husb && $husb->isDead() || $wife && $wife->isDead())) {
379                            continue;
380                        }
381                    }
382
383                    $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
384
385                    // The record may have multiple facts of this type.
386                    // Find the ones that match the date.
387                    foreach ($record->facts([$row->d_fact]) as $fact) {
388                        $min_date = $fact->date()->minimumDate();
389                        $max_date = $fact->date()->maximumDate();
390
391                        if ($min_date->minimumJulianDay() === $anniv_date->minimumJulianDay() && $min_date::ESCAPE === $row->d_type || $max_date->maximumJulianDay() === $anniv_date->maximumJulianDay() && $max_date::ESCAPE === $row->d_type) {
392                            $fact->anniv   = $row->d_year === '0' ? 0 : $anniv->year - $row->d_year;
393                            $fact->jd      = $jd;
394                            $found_facts[] = $fact;
395                        }
396                    }
397                }
398            }
399        }
400
401        return $found_facts;
402    }
403
404    /**
405     * By default, missing days have anniversaries on the first of the month,
406     * and invalid days have anniversaries on the last day of the month.
407     *
408     * @param Builder              $query
409     * @param AbstractCalendarDate $anniv
410     */
411    private function defaultAnniversaries(Builder $query, AbstractCalendarDate $anniv): void
412    {
413        if ($anniv->day() === 1) {
414            $query->where('d_day', '<=', 1);
415        } elseif ($anniv->day() === $anniv->daysInMonth()) {
416            $query->where('d_day', '>=', $anniv->daysInMonth());
417        } else {
418            $query->where('d_day', '=', $anniv->day());
419        }
420
421        $query->where('d_mon', '=', $anniv->month());
422    }
423
424    /**
425     * 29 CSH does not include 30 CSH (but would include an invalid 31 CSH if there were no 30 CSH).
426     *
427     * @param Builder    $query
428     * @param JewishDate $anniv
429     */
430    private function cheshvanAnniversaries(Builder $query, JewishDate $anniv): void
431    {
432        if ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
433            $query
434                ->where('d_mon', '=', 2)
435                ->where('d_day', '>=', 29)
436                ->where('d_day', '<>', 30);
437        } else {
438            $this->defaultAnniversaries($query, $anniv);
439        }
440    }
441
442    /**
443     * 1 KSL includes 30 CSH (if this year didn’t have 30 CSH).
444     * 29 KSL does not include 30 KSL (but would include an invalid 31 KSL if there were no 30 KSL).
445     *
446     * @param Builder    $query
447     * @param JewishDate $anniv
448     */
449    private function kislevAnniversaries(Builder $query, JewishDate $anniv): void
450    {
451        $tmp = new JewishDate([(string) $anniv->year, 'CSH', '1']);
452
453        if ($anniv->day() === 1 && $tmp->daysInMonth() === 29) {
454            $query->where(static function (Builder $query): void {
455                $query->where(static function (Builder $query): void {
456                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 3);
457                })->orWhere(static function (Builder $query): void {
458                    $query->where('d_day', '=', 30)->where('d_mon', '=', 2);
459                });
460            });
461        } elseif ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
462            $query
463                ->where('d_mon', '=', 3)
464                ->where('d_day', '>=', 29)
465                ->where('d_day', '<>', 30);
466        } else {
467            $this->defaultAnniversaries($query, $anniv);
468        }
469    }
470
471    /**
472     * 1 TVT includes 30 KSL (if this year didn’t have 30 KSL).
473     *
474     * @param Builder    $query
475     * @param JewishDate $anniv
476     */
477    private function tevetAnniversaries(Builder $query, JewishDate $anniv): void
478    {
479        $tmp = new JewishDate([(string) $anniv->year, 'KSL', '1']);
480
481        if ($anniv->day === 1 && $tmp->daysInMonth() === 29) {
482            $query->where(static function (Builder $query): void {
483                $query->where(static function (Builder $query): void {
484                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 4);
485                })->orWhere(static function (Builder $query): void {
486                    $query->where('d_day', '=', 30)->where('d_mon', '=', 3);
487                });
488            });
489        } else {
490            $this->defaultAnniversaries($query, $anniv);
491        }
492    }
493
494    /**
495     * ADS includes non-leap ADR.
496     *
497     * @param Builder    $query
498     * @param JewishDate $anniv
499     */
500    private function adarIIAnniversaries(Builder $query, JewishDate $anniv): void
501    {
502        if ($anniv->day() === 1) {
503            $query->where('d_day', '<=', 1);
504        } elseif ($anniv->day() === $anniv->daysInMonth()) {
505            $query->where('d_day', '>=', $anniv->daysInMonth());
506            if ($anniv->daysInMonth() === 29) {
507                // On short months, 30th Adar shown on 1st Nissan
508                $query->where('d_day', '<>', 30);
509            }
510        } else {
511            $query->where('d_day', '=', $anniv->day());
512        }
513
514        if ($anniv->isLeapYear()) {
515            $query->where('d_mon', '=', 7);
516        } else {
517            $query->whereIn('d_mon', [6, 7]);
518        }
519    }
520
521    /**
522     * 1 NSN includes 30 ADR, if this year is non-leap.
523     *
524     * @param Builder    $query
525     * @param JewishDate $anniv
526     */
527    private function nisanAnniversaries(Builder $query, JewishDate $anniv): void
528    {
529        if ($anniv->day === 1 && !$anniv->isLeapYear()) {
530            $query->where(static function (Builder $query): void {
531                $query->where(static function (Builder $query): void {
532                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 8);
533                })->orWhere(static function (Builder $query): void {
534                    $query->where('d_day', '=', 30)->where('d_mon', '=', 6);
535                });
536            });
537        } else {
538            $this->defaultAnniversaries($query, $anniv);
539        }
540    }
541}
542