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