xref: /webtrees/app/Services/CalendarService.php (revision 9f0d6dbf6a7dc021fda5f95a2659a003c0707732)
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                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
213                    return $x->jd <=> $y->jd;
214                });
215                break;
216
217            case 'alpha':
218                $facts = $facts->sort(static function (Fact $x, Fact $y): int {
219                    return GedcomRecord::nameComparator()($x->record(), $y->record());
220                });
221                break;
222        }
223
224        return $facts->values();
225    }
226
227    /**
228     * Get a list of events whose anniversary occured on a given julian day.
229     * Used on the on-this-day/upcoming blocks and the day/month calendar views.
230     *
231     * @param int    $jd    the julian day
232     * @param string $facts restrict the search to just these facts or leave blank for all
233     * @param Tree   $tree  the tree to search
234     *
235     * @return Fact[]
236     */
237    public function getAnniversaryEvents($jd, string $facts, Tree $tree): array
238    {
239        $found_facts = [];
240
241        $anniversaries = [
242            new GregorianDate($jd),
243            new JulianDate($jd),
244            new FrenchDate($jd),
245            new JewishDate($jd),
246            new HijriDate($jd),
247        ];
248
249        // There is a bug in the Persian Calendar that gives zero months for invalid dates
250        if ($jd > (new PersianCalendar())->jdStart()) {
251            $anniversaries[] = new JalaliDate($jd);
252        }
253
254        foreach ($anniversaries as $anniv) {
255            // Build a query to match anniversaries in the appropriate calendar.
256            $query = DB::table('dates')
257                ->distinct()
258                ->where('d_file', '=', $tree->id())
259                ->where('d_type', '=', $anniv->format('%@'));
260
261            // SIMPLE CASES:
262            // a) Non-hebrew anniversaries
263            // b) Hebrew months TVT, SHV, IYR, SVN, TMZ, AAV, ELL
264            if (!$anniv instanceof JewishDate || in_array($anniv->month, [1, 5, 6, 9, 10, 11, 12, 13], true)) {
265                $this->defaultAnniversaries($query, $anniv);
266            } else {
267                // SPECIAL CASES:
268                switch ($anniv->month) {
269                    case 2:
270                        $this->cheshvanAnniversaries($query, $anniv);
271                        break;
272                    case 3:
273                        $this->kislevAnniversaries($query, $anniv);
274                        break;
275                    case 4:
276                        $this->tevetAnniversaries($query, $anniv);
277                        break;
278                    case 7:
279                        $this->adarIIAnniversaries($query, $anniv);
280                        break;
281                    case 8:
282                        $this->nisanAnniversaries($query, $anniv);
283                        break;
284                }
285            }
286            // Only events in the past (includes dates without a year)
287            $query->where('d_year', '<=', $anniv->year());
288
289            if ($facts === '') {
290                // If no facts specified, get all except these
291                $query->whereNotIn('d_fact', self::SKIP_FACTS);
292            } else {
293                // Restrict to certain types of fact
294                preg_match_all('/([_A-Z]+)/', $facts, $matches);
295
296                $query->whereIn('d_fact', $matches[1]);
297            }
298
299            $query
300                ->orderBy('d_day')
301                ->orderBy('d_year', 'DESC');
302
303            $ind_query = (clone $query)
304                ->join('individuals', static function (JoinClause $join): void {
305                    $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
306                })
307                ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
308
309            $fam_query = (clone $query)
310                ->join('families', static function (JoinClause $join): void {
311                    $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
312                })
313                ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
314
315            // Now fetch these anniversaries
316            foreach (['INDI' => $ind_query, 'FAM' => $fam_query] as $type => $record_query) {
317                foreach ($record_query->get() as $row) {
318                    if ($type === 'INDI') {
319                        $record = Factory::individual()->make($row->xref, $tree, $row->gedcom);
320                    } else {
321                        $record = Factory::family()->make($row->xref, $tree, $row->gedcom);
322                    }
323
324                    $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
325
326                    // The record may have multiple facts of this type.
327                    // Find the ones that match the date.
328                    foreach ($record->facts([$row->d_fact]) as $fact) {
329                        $min_date = $fact->date()->minimumDate();
330                        $max_date = $fact->date()->maximumDate();
331
332                        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) {
333                            $fact->anniv   = $row->d_year === '0' ? 0 : $anniv->year - $row->d_year;
334                            $fact->jd      = $jd;
335                            $found_facts[] = $fact;
336                        }
337                    }
338                }
339            }
340        }
341
342        return $found_facts;
343    }
344
345    /**
346     * By default, missing days have anniversaries on the first of the month,
347     * and invalid days have anniversaries on the last day of the month.
348     *
349     * @param Builder              $query
350     * @param AbstractCalendarDate $anniv
351     */
352    private function defaultAnniversaries(Builder $query, AbstractCalendarDate $anniv): void
353    {
354        if ($anniv->day() === 1) {
355            $query->where('d_day', '<=', 1);
356        } elseif ($anniv->day() === $anniv->daysInMonth()) {
357            $query->where('d_day', '>=', $anniv->daysInMonth());
358        } else {
359            $query->where('d_day', '=', $anniv->day());
360        }
361
362        $query->where('d_mon', '=', $anniv->month());
363    }
364
365    /**
366     * 29 CSH does not include 30 CSH (but would include an invalid 31 CSH if there were no 30 CSH).
367     *
368     * @param Builder    $query
369     * @param JewishDate $anniv
370     */
371    private function cheshvanAnniversaries(Builder $query, JewishDate $anniv): void
372    {
373        if ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
374            $query
375                ->where('d_mon', '=', 2)
376                ->where('d_day', '>=', 29)
377                ->where('d_day', '<>', 30);
378        } else {
379            $this->defaultAnniversaries($query, $anniv);
380        }
381    }
382
383    /**
384     * 1 KSL includes 30 CSH (if this year didn’t have 30 CSH).
385     * 29 KSL does not include 30 KSL (but would include an invalid 31 KSL if there were no 30 KSL).
386     *
387     * @param Builder    $query
388     * @param JewishDate $anniv
389     */
390    private function kislevAnniversaries(Builder $query, JewishDate $anniv): void
391    {
392        $tmp = new JewishDate([(string) $anniv->year, 'CSH', '1']);
393
394        if ($anniv->day() === 1 && $tmp->daysInMonth() === 29) {
395            $query->where(static function (Builder $query): void {
396                $query->where(static function (Builder $query): void {
397                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 3);
398                })->orWhere(static function (Builder $query): void {
399                    $query->where('d_day', '=', 30)->where('d_mon', '=', 2);
400                });
401            });
402        } elseif ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
403            $query
404                ->where('d_mon', '=', 3)
405                ->where('d_day', '>=', 29)
406                ->where('d_day', '<>', 30);
407        } else {
408            $this->defaultAnniversaries($query, $anniv);
409        }
410    }
411
412    /**
413     * 1 TVT includes 30 KSL (if this year didn’t have 30 KSL).
414     *
415     * @param Builder    $query
416     * @param JewishDate $anniv
417     */
418    private function tevetAnniversaries(Builder $query, JewishDate $anniv): void
419    {
420        $tmp = new JewishDate([(string) $anniv->year, 'KSL', '1']);
421
422        if ($anniv->day === 1 && $tmp->daysInMonth() === 29) {
423            $query->where(static function (Builder $query): void {
424                $query->where(static function (Builder $query): void {
425                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 4);
426                })->orWhere(static function (Builder $query): void {
427                    $query->where('d_day', '=', 30)->where('d_mon', '=', 3);
428                });
429            });
430        } else {
431            $this->defaultAnniversaries($query, $anniv);
432        }
433    }
434
435    /**
436     * ADS includes non-leap ADR.
437     *
438     * @param Builder    $query
439     * @param JewishDate $anniv
440     */
441    private function adarIIAnniversaries(Builder $query, JewishDate $anniv): void
442    {
443        if ($anniv->day() === 1) {
444            $query->where('d_day', '<=', 1);
445        } elseif ($anniv->day() === $anniv->daysInMonth()) {
446            $query->where('d_day', '>=', $anniv->daysInMonth());
447        } else {
448            $query->where('d_day', '<=', 1);
449        }
450
451        $query->where(static function (Builder $query): void {
452            $query
453                ->where('d_mon', '=', 7)
454                ->orWhere(static function (Builder $query): void {
455                    $query
456                        ->where('d_mon', '=', 6)
457                        ->where(new Expression('(7 * d_year + 1 % 19)'), '>=', 7);
458                });
459        });
460    }
461
462    /**
463     * 1 NSN includes 30 ADR, if this year is non-leap.
464     *
465     * @param Builder    $query
466     * @param JewishDate $anniv
467     */
468    private function nisanAnniversaries(Builder $query, JewishDate $anniv): void
469    {
470        if ($anniv->day === 1 && !$anniv->isLeapYear()) {
471            $query->where(static function (Builder $query): void {
472                $query->where(static function (Builder $query): void {
473                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 8);
474                })->orWhere(static function (Builder $query): void {
475                    $query->where('d_day', '=', 30)->where('d_mon', '=', 6);
476                });
477            });
478        } else {
479            $this->defaultAnniversaries($query, $anniv);
480        }
481    }
482}
483