xref: /webtrees/app/Services/CalendarService.php (revision 379e735bf03b2ef02d2bf328828aaefcfc3d572a)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Services;
19
20use Fisharebest\ExtCalendar\PersianCalendar;
21use Fisharebest\Webtrees\Date;
22use Fisharebest\Webtrees\Date\AbstractCalendarDate;
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\GedcomRecord;
32use Fisharebest\Webtrees\Individual;
33use Fisharebest\Webtrees\Tree;
34use Illuminate\Database\Capsule\Manager as DB;
35use Illuminate\Database\Query\Builder;
36use Illuminate\Database\Query\Expression;
37use Illuminate\Database\Query\JoinClause;
38use Illuminate\Support\Collection;
39use function preg_match_all;
40use function range;
41
42/**
43 * Calculate anniversaries, etc.
44 */
45class CalendarService
46{
47    // If no facts specified, get all except these
48    protected const SKIP_FACTS = ['CHAN', 'BAPL', 'SLGC', 'SLGS', 'ENDL', 'CENS', 'RESI', 'NOTE', 'ADDR', 'OBJE', 'SOUR', '_TODO'];
49
50    /**
51     * List all the months in a given year.
52     *
53     * @param string $calendar
54     * @param int    $year
55     *
56     * @return string[]
57     */
58    public function calendarMonthsInYear(string $calendar, int $year): array
59    {
60        $date          = new Date($calendar . ' ' . $year);
61        $calendar_date = $date->minimumDate();
62        $month_numbers = range(1, $calendar_date->monthsInYear());
63        $month_names   = [];
64
65        foreach ($month_numbers as $month_number) {
66            $calendar_date->day   = 1;
67            $calendar_date->month = $month_number;
68            $calendar_date->setJdFromYmd();
69
70            if ($month_number === 6 && $calendar_date instanceof JewishDate && !$calendar_date->isLeapYear()) {
71                // No month 6 in Jewish non-leap years.
72                continue;
73            }
74
75            if ($month_number === 7 && $calendar_date instanceof JewishDate && !$calendar_date->isLeapYear()) {
76                // Month 7 is ADR in Jewish non-leap years (and ADS in others).
77                $mon = 'ADR';
78            } else {
79                $mon = $calendar_date->format('%O');
80            }
81
82            $month_names[$mon] = $calendar_date->format('%F');
83        }
84
85        return $month_names;
86    }
87
88    /**
89     * Get a list of events which occured during a given date range.
90     *
91     * @param int    $jd1   the start range of julian day
92     * @param int    $jd2   the end range of julian day
93     * @param string $facts restrict the search to just these facts or leave blank for all
94     * @param Tree   $tree  the tree to search
95     *
96     * @return Fact[]
97     */
98    public function getCalendarEvents(int $jd1, int $jd2, string $facts, Tree $tree): array
99    {
100        // Events that start or end during the period
101        $query = DB::table('dates')
102            ->where('d_file', '=', $tree->id())
103            ->where(static function (Builder $query) use ($jd1, $jd2): void {
104                $query->where(static function (Builder $query) use ($jd1, $jd2): void {
105                    $query
106                        ->where('d_julianday1', '>=', $jd1)
107                        ->where('d_julianday1', '<=', $jd2);
108                })->orWhere(static function (Builder $query) use ($jd1, $jd2): void {
109                    $query
110                        ->where('d_julianday2', '>=', $jd1)
111                        ->where('d_julianday2', '<=', $jd2);
112                });
113            });
114
115        // Restrict to certain types of fact
116        if ($facts === '') {
117            $query->whereNotIn('d_fact', self::SKIP_FACTS);
118        } else {
119            preg_match_all('/([_A-Z]+)/', $facts, $matches);
120
121            $query->whereIn('d_fact', $matches[1]);
122        }
123
124        $ind_query = (clone $query)
125            ->join('individuals', static function (JoinClause $join): void {
126                $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
127            })
128            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
129
130        $fam_query = (clone $query)
131            ->join('families', static function (JoinClause $join): void {
132                $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
133            })
134            ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
135
136        // Now fetch these events
137        $found_facts = [];
138
139        foreach (['INDI' => $ind_query, 'FAM' => $fam_query] as $type => $query) {
140            foreach ($query->get() as $row) {
141                if ($type === 'INDI') {
142                    $record = Individual::getInstance($row->xref, $tree, $row->gedcom);
143                } else {
144                    $record = Family::getInstance($row->xref, $tree, $row->gedcom);
145                }
146
147                $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
148
149                foreach ($record->facts() as $fact) {
150                    // For date ranges, we need a match on either the start/end.
151                    if (($fact->date()->minimumJulianDay() === $anniv_date->minimumJulianDay() || $fact->date()->maximumJulianDay() === $anniv_date->maximumJulianDay()) && $fact->getTag() === $row->d_fact) {
152                        $fact->anniv   = 0;
153                        $found_facts[] = $fact;
154                    }
155                }
156            }
157        }
158
159        return $found_facts;
160    }
161
162    /**
163     * Get the list of current and upcoming events, sorted by anniversary date
164     *
165     * @param int    $jd1
166     * @param int    $jd2
167     * @param string $events
168     * @param bool   $only_living
169     * @param string $sort_by
170     * @param Tree   $tree
171     *
172     * @return Fact[]
173     */
174    public function getEventsList(int $jd1, int $jd2, string $events, bool $only_living, string $sort_by, Tree $tree): array
175    {
176        $found_facts = [];
177        $facts       = [];
178
179        foreach (range($jd1, $jd2) as $jd) {
180            $found_facts = array_merge($found_facts, $this->getAnniversaryEvents($jd, $events, $tree));
181        }
182
183        foreach ($found_facts as $fact) {
184            $record = $fact->record();
185            // only living people ?
186            if ($only_living) {
187                if ($record instanceof Individual && $record->isDead()) {
188                    continue;
189                }
190                if ($record instanceof Family) {
191                    $husb = $record->husband();
192                    if ($husb === null || $husb->isDead()) {
193                        continue;
194                    }
195                    $wife = $record->wife();
196                    if ($wife === null || $wife->isDead()) {
197                        continue;
198                    }
199                }
200            }
201            $facts[] = $fact;
202        }
203
204        switch ($sort_by) {
205            case 'anniv':
206                $facts = Fact::sortFacts(Collection::make($facts))->all();
207                break;
208
209            case 'alpha':
210                uasort($facts, static function (Fact $x, Fact $y): int {
211                    return GedcomRecord::nameComparator()($x->record(), $y->record());
212                });
213                break;
214        }
215
216        return $facts;
217    }
218
219    /**
220     * Get a list of events whose anniversary occured on a given julian day.
221     * Used on the on-this-day/upcoming blocks and the day/month calendar views.
222     *
223     * @param int    $jd    the julian day
224     * @param string $facts restrict the search to just these facts or leave blank for all
225     * @param Tree   $tree  the tree to search
226     *
227     * @return Fact[]
228     */
229    public function getAnniversaryEvents($jd, string $facts, Tree $tree): array
230    {
231        $found_facts = [];
232
233        $anniversaries = [
234            new GregorianDate($jd),
235            new JulianDate($jd),
236            new FrenchDate($jd),
237            new JewishDate($jd),
238            new HijriDate($jd),
239        ];
240
241        // @TODO - there is a bug in the Persian Calendar that gives zero months for invalid dates
242        if ($jd > (new PersianCalendar())->jdStart()) {
243            $anniversaries[] = new JalaliDate($jd);
244        }
245
246        foreach ($anniversaries as $anniv) {
247            // Build a query to match anniversaries in the appropriate calendar.
248            $query = DB::table('dates')
249                ->distinct()
250                ->where('d_file', '=', $tree->id())
251                ->where('d_type', '=', $anniv->format('%@'));
252
253            // SIMPLE CASES:
254            // a) Non-hebrew anniversaries
255            // b) Hebrew months TVT, SHV, IYR, SVN, TMZ, AAV, ELL
256            if (!$anniv instanceof JewishDate || in_array($anniv->month, [1, 5, 6, 9, 10, 11, 12, 13], true)) {
257                $this->defaultAnniversaries($query, $anniv);
258            } else {
259                // SPECIAL CASES:
260                switch ($anniv->month) {
261                    case 2:
262                        $this->cheshvanAnniversaries($query, $anniv);
263                        break;
264                    case 3:
265                        $this->kislevAnniversaries($query, $anniv);
266                        break;
267                    case 4:
268                        $this->tevetAnniversaries($query, $anniv);
269                        break;
270                    case 7:
271                        $this->adarIIAnniversaries($query, $anniv);
272                        break;
273                    case 8:
274                        $this->nisanAnniversaries($query, $anniv);
275                        break;
276                }
277            }
278            // Only events in the past (includes dates without a year)
279            $query->where('d_year', '<=', $anniv->year());
280
281            if ($facts === '') {
282                // If no facts specified, get all except these
283                $query->whereNotIn('d_fact', self::SKIP_FACTS);
284            } else {
285                // Restrict to certain types of fact
286                preg_match_all('/([_A-Z]+)/', $facts, $matches);
287
288                $query->whereIn('d_fact', $matches[1]);
289            }
290
291            $query
292                ->orderBy('d_day')
293                ->orderByDesc('d_year');
294
295            $ind_query = (clone $query)
296                ->join('individuals', static function (JoinClause $join): void {
297                    $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
298                })
299                ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
300
301            $fam_query = (clone $query)
302                ->join('families', static function (JoinClause $join): void {
303                    $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
304                })
305                ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact']);
306
307            // Now fetch these anniversaries
308            foreach (['INDI' => $ind_query, 'FAM' => $fam_query] as $type => $query) {
309                foreach ($query->get() as $row) {
310                    if ($type === 'INDI') {
311                        $record = Individual::getInstance($row->xref, $tree, $row->gedcom);
312                    } else {
313                        $record = Family::getInstance($row->xref, $tree, $row->gedcom);
314                    }
315
316                    $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
317
318                    foreach ($record->facts() as $fact) {
319                        if (($fact->date()->minimumJulianDay() === $anniv_date->minimumJulianDay() || $fact->date()->maximumJulianDay() === $anniv_date->maximumJulianDay()) && $fact->getTag() === $row->d_fact) {
320                            $fact->anniv   = $row->d_year === '0' ? 0 : $anniv->year - $row->d_year;
321                            $fact->jd      = $jd;
322                            $found_facts[] = $fact;
323                        }
324                    }
325                }
326            }
327        }
328
329        return $found_facts;
330    }
331
332    /**
333     * By default, missing days have anniversaries on the first of the month,
334     * and invalid days have anniversaries on the last day of the month.
335     *
336     * @param Builder              $query
337     * @param AbstractCalendarDate $anniv
338     */
339    private function defaultAnniversaries(Builder $query, AbstractCalendarDate $anniv): void
340    {
341        if ($anniv->day() === 1) {
342            $query->where('d_day', '<=', 1);
343        } elseif ($anniv->day() === $anniv->daysInMonth()) {
344            $query->where('d_day', '>=', $anniv->daysInMonth());
345        } else {
346            $query->where('d_day', '=', $anniv->day());
347        }
348
349        $query->where('d_mon', '=', $anniv->month());
350    }
351
352    /**
353     * 29 CSH does not include 30 CSH (but would include an invalid 31 CSH if there were no 30 CSH).
354     *
355     * @param Builder    $query
356     * @param JewishDate $anniv
357     */
358    private function cheshvanAnniversaries(Builder $query, JewishDate $anniv): void
359    {
360        if ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
361            $query
362                ->where('d_mon', '=', 2)
363                ->where('d_day', '>=', 29)
364                ->where('d_day', '<>', 30);
365        } else {
366            $this->defaultAnniversaries($query, $anniv);
367        }
368    }
369
370    /**
371     * 1 KSL includes 30 CSH (if this year didn’t have 30 CSH).
372     * 29 KSL does not include 30 KSL (but would include an invalid 31 KSL if there were no 30 KSL).
373     *
374     * @param Builder    $query
375     * @param JewishDate $anniv
376     */
377    private function kislevAnniversaries(Builder $query, JewishDate $anniv): void
378    {
379        $tmp = new JewishDate([(string) $anniv->year, 'CSH', '1']);
380
381        if ($anniv->day() === 1 && $tmp->daysInMonth() === 29) {
382            $query->where(static function (Builder $query): void {
383                $query->where(static function (Builder $query): void {
384                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 3);
385                })->orWhere(static function (Builder $query): void {
386                    $query->where('d_day', '=', 30)->where('d_mon', '=', 2);
387                });
388            });
389        } elseif ($anniv->day === 29 && $anniv->daysInMonth() === 29) {
390            $query
391                ->where('d_mon', '=', 3)
392                ->where('d_day', '>=', 29)
393                ->where('d_day', '<>', 30);
394        } else {
395            $this->defaultAnniversaries($query, $anniv);
396        }
397    }
398
399    /**
400     * 1 TVT includes 30 KSL (if this year didn’t have 30 KSL).
401     *
402     * @param Builder    $query
403     * @param JewishDate $anniv
404     */
405    private function tevetAnniversaries(Builder $query, JewishDate $anniv): void
406    {
407        $tmp = new JewishDate([(string) $anniv->year, 'KSL', '1']);
408
409        if ($anniv->day === 1 && $tmp->daysInMonth() === 29) {
410            $query->where(static function (Builder $query): void {
411                $query->where(static function (Builder $query): void {
412                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 4);
413                })->orWhere(static function (Builder $query): void {
414                    $query->where('d_day', '=', 30)->where('d_mon', '=', 3);
415                });
416            });
417        } else {
418            $this->defaultAnniversaries($query, $anniv);
419        }
420    }
421
422    /**
423     * ADS includes non-leap ADR.
424     *
425     * @param Builder    $query
426     * @param JewishDate $anniv
427     */
428    private function adarIIAnniversaries(Builder $query, JewishDate $anniv): void
429    {
430        if ($anniv->day() === 1) {
431            $query->where('d_day', '<=', 1);
432        } elseif ($anniv->day() === $anniv->daysInMonth()) {
433            $query->where('d_day', '>=', $anniv->daysInMonth());
434        } else {
435            $query->where('d_day', '<=', 1);
436        }
437
438        $query->where(static function (Builder $query): void {
439            $query
440                ->where('d_mon', '=', 7)
441                ->orWhere(static function (Builder $query): void {
442                    $query
443                        ->where('d_mon', '=', 6)
444                        ->where(new Expression('(7 * d_year + 1 % 19)'), '>=', 7);
445                });
446        });
447    }
448
449    /**
450     * 1 NSN includes 30 ADR, if this year is non-leap.
451     *
452     * @param Builder    $query
453     * @param JewishDate $anniv
454     */
455    private function nisanAnniversaries(Builder $query, JewishDate $anniv): void
456    {
457        if ($anniv->day === 1 && !$anniv->isLeapYear()) {
458            $query->where(static function (Builder $query): void {
459                $query->where(static function (Builder $query): void {
460                    $query->where('d_day', '<=', 1)->where('d_mon', '=', 8);
461                })->orWhere(static function (Builder $query): void {
462                    $query->where('d_day', '=', 30)->where('d_mon', '=', 6);
463                });
464            });
465        } else {
466            $this->defaultAnniversaries($query, $anniv);
467        }
468    }
469}
470