xref: /webtrees/app/Services/CalendarService.php (revision 89d880da80f202b08b9fe837f38a87b48c6d2a97)
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;
36use Illuminate\Support\Collection;
37
38/**
39 * Calculate anniversaries, etc.
40 */
41class CalendarService
42{
43    /**
44     * List all the months in a given year.
45     *
46     * @param string $calendar
47     * @param int    $year
48     *
49     * @return string[]
50     */
51    public function calendarMonthsInYear(string $calendar, int $year): array
52    {
53        $date          = new Date($calendar . ' ' . $year);
54        $calendar_date = $date->minimumDate();
55        $month_numbers = range(1, $calendar_date->monthsInYear());
56        $month_names   = [];
57
58        foreach ($month_numbers as $month_number) {
59            $calendar_date->day   = 1;
60            $calendar_date->month = $month_number;
61            $calendar_date->setJdFromYmd();
62
63            if ($month_number === 6 && $calendar_date instanceof JewishDate && !$calendar_date->isLeapYear()) {
64                // No month 6 in Jewish non-leap years.
65                continue;
66            }
67
68            if ($month_number === 7 && $calendar_date instanceof JewishDate && !$calendar_date->isLeapYear()) {
69                // Month 7 is ADR in Jewish non-leap years (and ADS in others).
70                $mon = 'ADR';
71            } else {
72                $mon = $calendar_date->format('%O');
73            }
74
75            $month_names[$mon] = $calendar_date->format('%F');
76        }
77
78        return $month_names;
79    }
80
81    /**
82     * Get a list of events which occured during a given date range.
83     *
84     * @param int      $jd1   the start range of julian day
85     * @param int      $jd2   the end range of julian day
86     * @param string[] $facts restrict the search to just these facts or leave blank for all
87     * @param Tree     $tree  the tree to search
88     *
89     * @return Fact[]
90     */
91    public function getCalendarEvents(int $jd1, int $jd2, array $facts, Tree $tree): array
92    {
93        // If no facts specified, get all except these
94        $skipfacts = ['CHAN', 'BAPL', 'SLGC', 'SLGS', 'ENDL', 'CENS', 'RESI', 'NOTE', 'ADDR', 'OBJE', 'SOUR'];
95
96        // Events that start or end during the period
97        $query = DB::table('dates')
98            ->where('d_file', '=', $tree->id())
99            ->where(function (Builder $query) use ($jd1, $jd2): void {
100                $query->where(function (Builder $query) use ($jd1, $jd2): void {
101                    $query
102                        ->where('d_julianday1', '>=', $jd1)
103                        ->where('d_julianday1', '<=', $jd2);
104                })->orWhere(function (Builder $query) use ($jd1, $jd2): void {
105                    $query
106                        ->where('d_julianday2', '>=', $jd1)
107                        ->where('d_julianday2', '<=', $jd2);
108                });
109            });
110
111        // Restrict to certain types of fact
112        if (empty($facts)) {
113            $query->whereNotIn('d_fact', $skipfacts);
114        } else {
115            $query->whereIn('d_fact', $facts);
116        }
117
118        $ind_query = (clone $query)
119            ->join('individuals', function (JoinClause $join): void {
120                $join->on('d_gid', '=', 'i_id')->on('d_file', '=', 'i_file');
121            })
122            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
123
124        $fam_query = (clone $query)
125            ->join('families', function (JoinClause $join): void {
126                $join->on('d_gid', '=', 'f_id')->on('d_file', '=', 'f_file');
127            })
128            ->select(['f_id AS xref', 'f_gedcom AS gedcom', 'd_type', 'd_day', 'd_month', 'd_year', 'd_fact', 'd_type']);
129
130        // Now fetch these events
131        $found_facts = [];
132
133        foreach (['INDI' => $ind_query, 'FAM' => $fam_query] as $type => $query) {
134            foreach ($query->get() as $row) {
135                if ($type === 'INDI') {
136                    $record = Individual::getInstance($row->xref, $tree, $row->gedcom);
137                } else {
138                    $record = Family::getInstance($row->xref, $tree, $row->gedcom);
139                }
140
141                $anniv_date = new Date($row->d_type . ' ' . $row->d_day . ' ' . $row->d_month . ' ' . $row->d_year);
142
143                foreach ($record->facts() as $fact) {
144                    // For date ranges, we need a match on either the start/end.
145                    if (($fact->date()->minimumJulianDay() === $anniv_date->minimumJulianDay() || $fact->date()->maximumJulianDay() === $anniv_date->maximumJulianDay()) && $fact->getTag() === $row->d_fact) {
146                        $fact->anniv   = 0;
147                        $found_facts[] = $fact;
148                    }
149                }
150            }
151        }
152
153        return $found_facts;
154    }
155
156    /**
157     * Get the list of current and upcoming events, sorted by anniversary date
158     *
159     * @param int    $jd1
160     * @param int    $jd2
161     * @param string $events
162     * @param bool   $only_living
163     * @param string $sort_by
164     * @param Tree   $tree
165     *
166     * @return Fact[]
167     */
168    public function getEventsList(int $jd1, int $jd2, string $events, bool $only_living, string $sort_by, Tree $tree): array
169    {
170        $found_facts = [];
171        $facts       = [];
172
173        foreach (range($jd1, $jd2) as $jd) {
174            $found_facts = array_merge($found_facts, $this->getAnniversaryEvents($jd, $events, $tree));
175        }
176
177        foreach ($found_facts as $fact) {
178            $record = $fact->record();
179            // only living people ?
180            if ($only_living) {
181                if ($record instanceof Individual && $record->isDead()) {
182                    continue;
183                }
184                if ($record instanceof Family) {
185                    $husb = $record->husband();
186                    if ($husb === null || $husb->isDead()) {
187                        continue;
188                    }
189                    $wife = $record->wife();
190                    if ($wife === null || $wife->isDead()) {
191                        continue;
192                    }
193                }
194            }
195            $facts[] = $fact;
196        }
197
198        switch ($sort_by) {
199            case 'anniv':
200                $facts = Fact::sortFacts(Collection::make($facts))->all();
201                break;
202
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], true)) {
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('(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