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