xref: /webtrees/app/Services/CalendarService.php (revision 1293b98145ba478ac4640f77adba7cf9246f91dd)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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 <http://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\Factory;
33use Fisharebest\Webtrees\Family;
34use Fisharebest\Webtrees\GedcomRecord;
35use Fisharebest\Webtrees\Individual;
36use Fisharebest\Webtrees\Tree;
37use Illuminate\Database\Capsule\Manager as DB;
38use Illuminate\Database\Query\Builder;
39use Illuminate\Database\Query\Expression;
40use Illuminate\Database\Query\JoinClause;
41use Illuminate\Support\Collection;
42
43use function array_merge;
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 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 occured 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     *
102     * @return Fact[]
103     */
104    public function getCalendarEvents(int $jd1, int $jd2, string $facts, Tree $tree): array
105    {
106        // Events that start or end during the period
107        $query = DB::table('dates')
108            ->where('d_file', '=', $tree->id())
109            ->where(static function (Builder $query) use ($jd1, $jd2): void {
110                $query->where(static function (Builder $query) use ($jd1, $jd2): void {
111                    $query
112                        ->where('d_julianday1', '>=', $jd1)
113                        ->where('d_julianday1', '<=', $jd2);
114                })->orWhere(static function (Builder $query) use ($jd1, $jd2): void {
115                    $query
116                        ->where('d_julianday2', '>=', $jd1)
117                        ->where('d_julianday2', '<=', $jd2);
118                });
119            });
120
121        // Restrict to certain types of fact
122        if ($facts === '') {
123            $query->whereNotIn('d_fact', self::SKIP_FACTS);
124        } else {
125            preg_match_all('/([_A-Z]+)/', $facts, $matches);
126
127            $query->whereIn('d_fact', $matches[1]);
128        }
129
130        $ind_query = (clone $query)
131            ->join('individuals', static function (JoinClause $join): void {
132                $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
133            })
134            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
135
136        $fam_query = (clone $query)
137            ->join('families', static function (JoinClause $join): void {
138                $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
139            })
140            ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
141
142        // Now fetch these events
143        $found_facts = [];
144
145        foreach (['INDI' => $ind_query, 'FAM' => $fam_query] as $type => $record_query) {
146            foreach ($record_query->get() as $row) {
147                if ($type === 'INDI') {
148                    $record = Factory::individual()->make($row->xref, $tree, $row->gedcom);
149                } else {
150                    $record = Factory::family()->make($row->xref, $tree, $row->gedcom);
151                }
152
153                $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
154
155                foreach ($record->facts() as $fact) {
156                    // For date ranges, we need a match on either the start/end.
157                    if (($fact->date()->minimumJulianDay() === $anniv_date->minimumJulianDay() || $fact->date()->maximumJulianDay() === $anniv_date->maximumJulianDay()) && $fact->getTag() === $row->d_fact) {
158                        $fact->anniv   = 0;
159                        $found_facts[] = $fact;
160                    }
161                }
162            }
163        }
164
165        return $found_facts;
166    }
167
168    /**
169     * Get the list of current and upcoming events, sorted by anniversary date
170     *
171     * @param int    $jd1
172     * @param int    $jd2
173     * @param string $events
174     * @param bool   $only_living
175     * @param string $sort_by
176     * @param Tree   $tree
177     *
178     * @return Collection<Fact>
179     */
180    public function getEventsList(int $jd1, int $jd2, string $events, bool $only_living, string $sort_by, Tree $tree): Collection
181    {
182        $found_facts = [];
183        $facts       = new Collection();
184
185        foreach (range($jd1, $jd2) as $jd) {
186            $found_facts = array_merge($found_facts, $this->getAnniversaryEvents($jd, $events, $tree));
187        }
188
189        foreach ($found_facts as $fact) {
190            $record = $fact->record();
191            // only living people ?
192            if ($only_living) {
193                if ($record instanceof Individual && $record->isDead()) {
194                    continue;
195                }
196                if ($record instanceof Family) {
197                    $husb = $record->husband();
198                    if ($husb === null || $husb->isDead()) {
199                        continue;
200                    }
201                    $wife = $record->wife();
202                    if ($wife === null || $wife->isDead()) {
203                        continue;
204                    }
205                }
206            }
207            $facts->push($fact);
208        }
209
210        switch ($sort_by) {
211            case 'anniv':
212            case 'anniv_asc':
213                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
214                    return $x->jd <=> $y->jd ?: $x->date()->minimumJulianDay() <=> $y->date()->minimumJulianDay();
215                });
216                break;
217
218            case 'anniv_desc':
219                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
220                    return $x->jd <=> $y->jd ?: $y->date()->minimumJulianDay() <=> $x->date()->minimumJulianDay();
221                });
222                break;
223
224            case 'alpha':
225                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
226                    return GedcomRecord::nameComparator()($x->record(), $y->record());
227                });
228                break;
229        }
230
231        return $facts->values();
232    }
233
234    /**
235     * Get a list of events whose anniversary occured on a given julian day.
236     * Used on the on-this-day/upcoming blocks and the day/month calendar views.
237     *
238     * @param int    $jd    the julian day
239     * @param string $facts restrict the search to just these facts or leave blank for all
240     * @param Tree   $tree  the tree to search
241     *
242     * @return Fact[]
243     */
244    public function getAnniversaryEvents($jd, string $facts, Tree $tree): array
245    {
246        $found_facts = [];
247
248        $anniversaries = [
249            new GregorianDate($jd),
250            new JulianDate($jd),
251            new FrenchDate($jd),
252            new JewishDate($jd),
253            new HijriDate($jd),
254        ];
255
256        // There is a bug in the Persian Calendar that gives zero months for invalid dates
257        if ($jd > (new PersianCalendar())->jdStart()) {
258            $anniversaries[] = new JalaliDate($jd);
259        }
260
261        foreach ($anniversaries as $anniv) {
262            // Build a query to match anniversaries in the appropriate calendar.
263            $query = DB::table('dates')
264                ->distinct()
265                ->where('d_file', '=', $tree->id())
266                ->where('d_type', '=', $anniv->format('%@'));
267
268            // SIMPLE CASES:
269            // a) Non-hebrew anniversaries
270            // b) Hebrew months TVT, SHV, IYR, SVN, TMZ, AAV, ELL
271            if (!$anniv instanceof JewishDate || in_array($anniv->month, [1, 5, 6, 9, 10, 11, 12, 13], true)) {
272                $this->defaultAnniversaries($query, $anniv);
273            } else {
274                // SPECIAL CASES:
275                switch ($anniv->month) {
276                    case 2:
277                        $this->cheshvanAnniversaries($query, $anniv);
278                        break;
279                    case 3:
280                        $this->kislevAnniversaries($query, $anniv);
281                        break;
282                    case 4:
283                        $this->tevetAnniversaries($query, $anniv);
284                        break;
285                    case 7:
286                        $this->adarIIAnniversaries($query, $anniv);
287                        break;
288                    case 8:
289                        $this->nisanAnniversaries($query, $anniv);
290                        break;
291                }
292            }
293            // Only events in the past (includes dates without a year)
294            $query->where('d_year', '<=', $anniv->year());
295
296            if ($facts === '') {
297                // If no facts specified, get all except these
298                $query->whereNotIn('d_fact', self::SKIP_FACTS);
299            } else {
300                // Restrict to certain types of fact
301                preg_match_all('/([_A-Z]+)/', $facts, $matches);
302
303                $query->whereIn('d_fact', $matches[1]);
304            }
305
306            $query
307                ->orderBy('d_day')
308                ->orderBy('d_year', 'DESC');
309
310            $ind_query = (clone $query)
311                ->join('individuals', static function (JoinClause $join): void {
312                    $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
313                })
314                ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
315
316            $fam_query = (clone $query)
317                ->join('families', static function (JoinClause $join): void {
318                    $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
319                })
320                ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
321
322            // Now fetch these anniversaries
323            foreach (['INDI' => $ind_query, 'FAM' => $fam_query] as $type => $record_query) {
324                foreach ($record_query->get() as $row) {
325                    if ($type === 'INDI') {
326                        $record = Factory::individual()->make($row->xref, $tree, $row->gedcom);
327                    } else {
328                        $record = Factory::family()->make($row->xref, $tree, $row->gedcom);
329                    }
330
331                    $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
332
333                    // The record may have multiple facts of this type.
334                    // Find the ones that match the date.
335                    foreach ($record->facts([$row->d_fact]) as $fact) {
336                        $min_date = $fact->date()->minimumDate();
337                        $max_date = $fact->date()->maximumDate();
338
339                        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) {
340                            $fact->anniv   = $row->d_year === '0' ? 0 : $anniv->year - $row->d_year;
341                            $fact->jd      = $jd;
342                            $found_facts[] = $fact;
343                        }
344                    }
345                }
346            }
347        }
348
349        return $found_facts;
350    }
351
352    /**
353     * By default, missing days have anniversaries on the first of the month,
354     * and invalid days have anniversaries on the last day of the month.
355     *
356     * @param Builder              $query
357     * @param AbstractCalendarDate $anniv
358     */
359    private function defaultAnniversaries(Builder $query, AbstractCalendarDate $anniv): void
360    {
361        if ($anniv->day() === 1) {
362            $query->where('d_day', '<=', 1);
363        } elseif ($anniv->day() === $anniv->daysInMonth()) {
364            $query->where('d_day', '>=', $anniv->daysInMonth());
365        } else {
366            $query->where('d_day', '=', $anniv->day());
367        }
368
369        $query->where('d_mon', '=', $anniv->month());
370    }
371
372    /**
373     * 29 CSH does not include 30 CSH (but would include an invalid 31 CSH if there were no 30 CSH).
374     *
375     * @param Builder    $query
376     * @param JewishDate $anniv
377     */
378    private function cheshvanAnniversaries(Builder $query, JewishDate $anniv): void
379    {
380        if ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
381            $query
382                ->where('d_mon', '=', 2)
383                ->where('d_day', '>=', 29)
384                ->where('d_day', '<>', 30);
385        } else {
386            $this->defaultAnniversaries($query, $anniv);
387        }
388    }
389
390    /**
391     * 1 KSL includes 30 CSH (if this year didn’t have 30 CSH).
392     * 29 KSL does not include 30 KSL (but would include an invalid 31 KSL if there were no 30 KSL).
393     *
394     * @param Builder    $query
395     * @param JewishDate $anniv
396     */
397    private function kislevAnniversaries(Builder $query, JewishDate $anniv): void
398    {
399        $tmp = new JewishDate([(string) $anniv->year, 'CSH', '1']);
400
401        if ($anniv->day() === 1 && $tmp->daysInMonth() === 29) {
402            $query->where(static function (Builder $query): void {
403                $query->where(static function (Builder $query): void {
404                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 3);
405                })->orWhere(static function (Builder $query): void {
406                    $query->where('d_day', '=', 30)->where('d_mon', '=', 2);
407                });
408            });
409        } elseif ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
410            $query
411                ->where('d_mon', '=', 3)
412                ->where('d_day', '>=', 29)
413                ->where('d_day', '<>', 30);
414        } else {
415            $this->defaultAnniversaries($query, $anniv);
416        }
417    }
418
419    /**
420     * 1 TVT includes 30 KSL (if this year didn’t have 30 KSL).
421     *
422     * @param Builder    $query
423     * @param JewishDate $anniv
424     */
425    private function tevetAnniversaries(Builder $query, JewishDate $anniv): void
426    {
427        $tmp = new JewishDate([(string) $anniv->year, 'KSL', '1']);
428
429        if ($anniv->day === 1 && $tmp->daysInMonth() === 29) {
430            $query->where(static function (Builder $query): void {
431                $query->where(static function (Builder $query): void {
432                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 4);
433                })->orWhere(static function (Builder $query): void {
434                    $query->where('d_day', '=', 30)->where('d_mon', '=', 3);
435                });
436            });
437        } else {
438            $this->defaultAnniversaries($query, $anniv);
439        }
440    }
441
442    /**
443     * ADS includes non-leap ADR.
444     *
445     * @param Builder    $query
446     * @param JewishDate $anniv
447     */
448    private function adarIIAnniversaries(Builder $query, JewishDate $anniv): void
449    {
450        if ($anniv->day() === 1) {
451            $query->where('d_day', '<=', 1);
452        } elseif ($anniv->day() === $anniv->daysInMonth()) {
453            $query->where('d_day', '>=', $anniv->daysInMonth());
454        } else {
455            $query->where('d_day', '=', $anniv->day());
456        }
457
458        $query->where(static function (Builder $query): void {
459            $query
460                ->where('d_mon', '=', 7)
461                ->orWhere(static function (Builder $query): void {
462                    $query
463                        ->where('d_mon', '=', 6)
464                        ->where(new Expression('(7 * d_year + 1 % 19)'), '<', 7);
465                });
466        });
467    }
468
469    /**
470     * 1 NSN includes 30 ADR, if this year is non-leap.
471     *
472     * @param Builder    $query
473     * @param JewishDate $anniv
474     */
475    private function nisanAnniversaries(Builder $query, JewishDate $anniv): void
476    {
477        if ($anniv->day === 1 && !$anniv->isLeapYear()) {
478            $query->where(static function (Builder $query): void {
479                $query->where(static function (Builder $query): void {
480                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 8);
481                })->orWhere(static function (Builder $query): void {
482                    $query->where('d_day', '=', 30)->where('d_mon', '=', 6);
483                });
484            });
485        } else {
486            $this->defaultAnniversaries($query, $anniv);
487        }
488    }
489}
490