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