xref: /webtrees/app/Date.php (revision cd1ec0d0efaac433e873afc688050c81d1b4ad02)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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 <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use DomainException;
23use Fisharebest\ExtCalendar\GregorianCalendar;
24use Fisharebest\Webtrees\Date\AbstractCalendarDate;
25use Fisharebest\Webtrees\Date\FrenchDate;
26use Fisharebest\Webtrees\Date\GregorianDate;
27use Fisharebest\Webtrees\Date\HijriDate;
28use Fisharebest\Webtrees\Date\JalaliDate;
29use Fisharebest\Webtrees\Date\JewishDate;
30use Fisharebest\Webtrees\Date\JulianDate;
31use Fisharebest\Webtrees\Date\RomanDate;
32
33use function app;
34
35/**
36 * A representation of GEDCOM dates and date ranges.
37 *
38 * Since different calendars start their days at different times, (civil
39 * midnight, solar midnight, sunset, sunrise, etc.), we convert on the basis of
40 * midday.
41 *
42 * We assume that years start on the first day of the first month. Where
43 * this is not the case (e.g. England prior to 1752), we need to use modified
44 * years or the OS/NS notation "4 FEB 1750/51".
45 */
46class Date
47{
48    // Optional qualifier, such as BEF, FROM, ABT
49    public string $qual1 = '';
50
51    // The first (or only) date
52    private AbstractCalendarDate $date1;
53
54    // Optional qualifier, such as TO, AND
55    public string $qual2 = '';
56
57    // Optional second date
58    private ?AbstractCalendarDate $date2 = null;
59
60    // Optional text, as included with an INTerpreted date
61    private string $text = '';
62
63    /**
64     * Create a date, from GEDCOM data.
65     *
66     * @param string $date A date in GEDCOM format
67     */
68    public function __construct(string $date)
69    {
70        // Extract any explanatory text
71        if (preg_match('/^(.*) ?[(](.*)[)]/', $date, $match)) {
72            $date       = $match[1];
73            $this->text = $match[2];
74        }
75        if (preg_match('/^(FROM|BET) (.+) (AND|TO) (.+)/', $date, $match)) {
76            $this->qual1 = $match[1];
77            $this->date1 = $this->parseDate($match[2]);
78            $this->qual2 = $match[3];
79            $this->date2 = $this->parseDate($match[4]);
80        } elseif (preg_match('/^(TO|FROM|BEF|AFT|CAL|EST|INT|ABT) (.+)/', $date, $match)) {
81            $this->qual1 = $match[1];
82            $this->date1 = $this->parseDate($match[2]);
83        } else {
84            $this->date1 = $this->parseDate($date);
85        }
86    }
87
88    /**
89     * When we copy a date object, we need to create copies of
90     * its child objects.
91     */
92    public function __clone()
93    {
94        $this->date1 = clone $this->date1;
95        if ($this->date2 !== null) {
96            $this->date2 = clone $this->date2;
97        }
98    }
99
100    /**
101     * Convert a calendar date, such as "12 JUN 1943" into calendar date object.
102     * A GEDCOM date range may have two calendar dates.
103     *
104     * @param string $date
105     *
106     * @return AbstractCalendarDate
107     * @throws DomainException
108     */
109    private function parseDate(string $date): AbstractCalendarDate
110    {
111        // Valid calendar escape specified? - use it
112        if (preg_match('/^(@#D(?:GREGORIAN|JULIAN|HEBREW|HIJRI|JALALI|FRENCH R|ROMAN)+@) ?(.*)/', $date, $match)) {
113            $cal  = $match[1];
114            $date = $match[2];
115        } else {
116            $cal = '';
117        }
118        // A date with a month: DM, M, MY or DMY
119        if (preg_match('/^(\d?\d?) ?(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC|TSH|CSH|KSL|TVT|SHV|ADR|ADS|NSN|IYR|SVN|TMZ|AAV|ELL|VEND|BRUM|FRIM|NIVO|PLUV|VENT|GERM|FLOR|PRAI|MESS|THER|FRUC|COMP|MUHAR|SAFAR|RABI[AT]|JUMA[AT]|RAJAB|SHAAB|RAMAD|SHAWW|DHUAQ|DHUAH|FARVA|ORDIB|KHORD|TIR|MORDA|SHAHR|MEHR|ABAN|AZAR|DEY|BAHMA|ESFAN) ?((?:\d{1,4}(?: B\.C\.)?|\d\d\d\d\/\d\d)?)$/', $date, $match)) {
120            $d = $match[1];
121            $m = $match[2];
122            $y = $match[3];
123        } elseif (preg_match('/^(\d{1,4}(?: B\.C\.)?|\d\d\d\d\/\d\d)$/', $date, $match)) {
124            // A date with just a year
125            $d = '';
126            $m = '';
127            $y = $match[1];
128        } else {
129            // An invalid date - do the best we can.
130            $d = '';
131            $m = '';
132            $y = '';
133            // Look for a 3/4 digit year anywhere in the date
134            if (preg_match('/\b(\d{3,4})\b/', $date, $match)) {
135                $y = $match[1];
136            }
137            // Look for a month anywhere in the date
138            if (preg_match('/(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC|TSH|CSH|KSL|TVT|SHV|ADR|ADS|NSN|IYR|SVN|TMZ|AAV|ELL|VEND|BRUM|FRIM|NIVO|PLUV|VENT|GERM|FLOR|PRAI|MESS|THER|FRUC|COMP|MUHAR|SAFAR|RABI[AT]|JUMA[AT]|RAJAB|SHAAB|RAMAD|SHAWW|DHUAQ|DHUAH|FARVA|ORDIB|KHORD|TIR|MORDA|SHAHR|MEHR|ABAN|AZAR|DEY|BAHMA|ESFAN)/', $date, $match)) {
139                $m = $match[1];
140                // Look for a day number anywhere in the date
141                if (preg_match('/\b(\d\d?)\b/', $date, $match)) {
142                    $d = $match[1];
143                }
144            }
145        }
146
147        // Unambiguous dates - override calendar escape
148        if (preg_match('/^(TSH|CSH|KSL|TVT|SHV|ADR|ADS|NSN|IYR|SVN|TMZ|AAV|ELL)$/', $m)) {
149            $cal = JewishDate::ESCAPE;
150        } elseif (preg_match('/^(VEND|BRUM|FRIM|NIVO|PLUV|VENT|GERM|FLOR|PRAI|MESS|THER|FRUC|COMP)$/', $m)) {
151            $cal = FrenchDate::ESCAPE;
152        } elseif (preg_match('/^(MUHAR|SAFAR|RABI[AT]|JUMA[AT]|RAJAB|SHAAB|RAMAD|SHAWW|DHUAQ|DHUAH)$/', $m)) {
153            $cal = HijriDate::ESCAPE; // This is a WT extension
154        } elseif (preg_match('/^(FARVA|ORDIB|KHORD|TIR|MORDA|SHAHR|MEHR|ABAN|AZAR|DEY|BAHMA|ESFAN)$/', $m)) {
155            $cal = JalaliDate::ESCAPE; // This is a WT extension
156        } elseif (preg_match('/^\d{1,4}( B\.C\.)|\d\d\d\d\/\d\d$/', $y)) {
157            $cal = JulianDate::ESCAPE;
158        }
159
160        // Ambiguous dates - don't override calendar escape
161        if ($cal === '') {
162            if (preg_match('/^(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)$/', $m)) {
163                $cal = GregorianDate::ESCAPE;
164            } elseif (preg_match('/^[345]\d\d\d$/', $y)) {
165                // Year 3000-5999
166                $cal = JewishDate::ESCAPE;
167            } else {
168                $cal = GregorianDate::ESCAPE;
169            }
170        }
171        // Now construct an object of the correct type
172        switch ($cal) {
173            case GregorianDate::ESCAPE:
174                return new GregorianDate([
175                    $y,
176                    $m,
177                    $d,
178                ]);
179            case JulianDate::ESCAPE:
180                return new JulianDate([
181                    $y,
182                    $m,
183                    $d,
184                ]);
185            case JewishDate::ESCAPE:
186                return new JewishDate([
187                    $y,
188                    $m,
189                    $d,
190                ]);
191            case HijriDate::ESCAPE:
192                return new HijriDate([
193                    $y,
194                    $m,
195                    $d,
196                ]);
197            case FrenchDate::ESCAPE:
198                return new FrenchDate([
199                    $y,
200                    $m,
201                    $d,
202                ]);
203            case JalaliDate::ESCAPE:
204                return new JalaliDate([
205                    $y,
206                    $m,
207                    $d,
208                ]);
209            case RomanDate::ESCAPE:
210                return new RomanDate([
211                    $y,
212                    $m,
213                    $d,
214                ]);
215            default:
216                throw new DomainException('Invalid calendar');
217        }
218    }
219
220    /**
221     * A list of supported calendars and their names.
222     *
223     * @return array<string>
224     */
225    public static function calendarNames(): array
226    {
227        return [
228            /* I18N: The gregorian calendar */
229            'gregorian' => I18N::translate('Gregorian'),
230            /* I18N: The julian calendar */
231            'julian'    => I18N::translate('Julian'),
232            /* I18N: The French calendar */
233            'french'    => I18N::translate('French'),
234            /* I18N: The Hebrew/Jewish calendar */
235            'jewish'    => I18N::translate('Jewish'),
236            /* I18N: The Arabic/Hijri calendar */
237            'hijri'     => I18N::translate('Hijri'),
238            /* I18N: The Persian/Jalali calendar */
239            'jalali'    => I18N::translate('Jalali'),
240        ];
241    }
242
243    /**
244     * Convert a date to the preferred format and calendar(s) display.
245     *
246     * @param bool        $url               Wrap the date in a link to calendar.php
247     * @param string|null $date_format       Override the default date format
248     * @param bool        $convert_calendars Convert the date into other calendars
249     *
250     * @return string
251     */
252    public function display(bool $url = false, string $date_format = null, bool $convert_calendars = true): string
253    {
254        // Do we need a new DateFormatterService class?
255        if (app()->has(Tree::class)) {
256            $tree            = app(Tree::class);
257            $CALENDAR_FORMAT = $tree->getPreference('CALENDAR_FORMAT');
258        } else {
259            $tree            = null;
260            $CALENDAR_FORMAT = '';
261        }
262
263        $date_format = $date_format ?? I18N::dateFormat();
264
265        if ($convert_calendars) {
266            $calendar_format = explode('_and_', $CALENDAR_FORMAT);
267        } else {
268            $calendar_format = [];
269        }
270
271        // Two dates with text before, between and after
272        $q1 = $this->qual1;
273        $d1 = $this->date1->format($date_format, $this->qual1);
274        $q2 = $this->qual2;
275        if ($this->date2 === null) {
276            $d2 = '';
277        } else {
278            $d2 = $this->date2->format($date_format, $this->qual2);
279        }
280        // Con vert to other calendars, if requested
281        $conv1 = '';
282        $conv2 = '';
283        foreach ($calendar_format as $cal_fmt) {
284            if ($cal_fmt !== 'none') {
285                $d1conv = $this->date1->convertToCalendar($cal_fmt);
286                if ($d1conv->inValidRange()) {
287                    $d1tmp = $d1conv->format($date_format, $this->qual1);
288                } else {
289                    $d1tmp = '';
290                }
291                if ($this->date2 === null) {
292                    $d2conv = null;
293                    $d2tmp  = '';
294                } else {
295                    $d2conv = $this->date2->convertToCalendar($cal_fmt);
296                    if ($d2conv->inValidRange()) {
297                        $d2tmp = $d2conv->format($date_format, $this->qual2);
298                    } else {
299                        $d2tmp = '';
300                    }
301                }
302                // If the date is different from the unconverted date, add it to the date string.
303                if ($d1 != $d1tmp && $d1tmp !== '') {
304                    if ($url) {
305                        if ($CALENDAR_FORMAT !== 'none') {
306                            $conv1 .= ' <span dir="' . I18N::direction() . '">(<a href="' . e($d1conv->calendarUrl($date_format, $tree)) . '" rel="nofollow">' . $d1tmp . '</a>)</span>';
307                        } else {
308                            $conv1 .= ' <span dir="' . I18N::direction() . '"><br><a href="' . e($d1conv->calendarUrl($date_format, $tree)) . '" rel="nofollow">' . $d1tmp . '</a></span>';
309                        }
310                    } else {
311                        $conv1 .= ' <span dir="' . I18N::direction() . '">(' . $d1tmp . ')</span>';
312                    }
313                }
314                if ($this->date2 !== null && $d2 != $d2tmp && $d1tmp != '') {
315                    if ($url) {
316                        $conv2 .= ' <span dir="' . I18N::direction() . '">(<a href="' . e($d2conv->calendarUrl($date_format, $tree)) . '" rel="nofollow">' . $d2tmp . '</a>)</span>';
317                    } else {
318                        $conv2 .= ' <span dir="' . I18N::direction() . '">(' . $d2tmp . ')</span>';
319                    }
320                }
321            }
322        }
323
324        // Add URLs, if requested
325        if ($url) {
326            $d1 = '<a href="' . e($this->date1->calendarUrl($date_format, $tree)) . '" rel="nofollow">' . $d1 . '</a>';
327            if ($this->date2 instanceof AbstractCalendarDate) {
328                $d2 = '<a href="' . e($this->date2->calendarUrl($date_format, $tree)) . '" rel="nofollow">' . $d2 . '</a>';
329            }
330        }
331
332        // Localise the date
333        switch ($q1 . $q2) {
334            case '':
335                $tmp = $d1 . $conv1;
336                break;
337            case 'ABT':
338                /* I18N: Gedcom ABT dates */
339                $tmp = I18N::translate('about %s', $d1 . $conv1);
340                break;
341            case 'CAL':
342                /* I18N: Gedcom CAL dates */
343                $tmp = I18N::translate('calculated %s', $d1 . $conv1);
344                break;
345            case 'EST':
346                /* I18N: Gedcom EST dates */
347                $tmp = I18N::translate('estimated %s', $d1 . $conv1);
348                break;
349            case 'INT':
350                /* I18N: Gedcom INT dates */
351                $tmp = I18N::translate('interpreted %s (%s)', $d1 . $conv1, e($this->text));
352                break;
353            case 'BEF':
354                /* I18N: Gedcom BEF dates */
355                $tmp = I18N::translate('before %s', $d1 . $conv1);
356                break;
357            case 'AFT':
358                /* I18N: Gedcom AFT dates */
359                $tmp = I18N::translate('after %s', $d1 . $conv1);
360                break;
361            case 'FROM':
362                /* I18N: Gedcom FROM dates */
363                $tmp = I18N::translate('from %s', $d1 . $conv1);
364                break;
365            case 'TO':
366                /* I18N: Gedcom TO dates */
367                $tmp = I18N::translate('to %s', $d1 . $conv1);
368                break;
369            case 'BETAND':
370                /* I18N: Gedcom BET-AND dates */
371                $tmp = I18N::translate('between %s and %s', $d1 . $conv1, $d2 . $conv2);
372                break;
373            case 'FROMTO':
374                /* I18N: Gedcom FROM-TO dates */
375                $tmp = I18N::translate('from %s to %s', $d1 . $conv1, $d2 . $conv2);
376                break;
377            default:
378                $tmp = I18N::translate('Invalid date');
379                break;
380        }
381
382        if (strip_tags($tmp) === '') {
383            return '';
384        }
385
386        return '<span class="date">' . $tmp . '</span>';
387    }
388
389    /**
390     * Get the earliest calendar date from this GEDCOM date.
391     *
392     * In the date “FROM 1900 TO 1910”, this would be 1900.
393     *
394     * @return AbstractCalendarDate
395     */
396    public function minimumDate(): AbstractCalendarDate
397    {
398        return $this->date1;
399    }
400
401    /**
402     * Get the latest calendar date from this GEDCOM date.
403     *
404     * In the date “FROM 1900 TO 1910”, this would be 1910.
405     *
406     * @return AbstractCalendarDate
407     */
408    public function maximumDate(): AbstractCalendarDate
409    {
410        return $this->date2 ?? $this->date1;
411    }
412
413    /**
414     * Get the earliest Julian day number from this GEDCOM date.
415     *
416     * @return int
417     */
418    public function minimumJulianDay(): int
419    {
420        return $this->minimumDate()->minimumJulianDay();
421    }
422
423    /**
424     * Get the latest Julian day number from this GEDCOM date.
425     *
426     * @return int
427     */
428    public function maximumJulianDay(): int
429    {
430        return $this->maximumDate()->maximumJulianDay();
431    }
432
433    /**
434     * Get the middle Julian day number from the GEDCOM date.
435     *
436     * For a month-only date, this would be somewhere around the 16th day.
437     * For a year-only date, this would be somewhere around 1st July.
438     *
439     * @return int
440     */
441    public function julianDay(): int
442    {
443        return intdiv($this->minimumJulianDay() + $this->maximumJulianDay(), 2);
444    }
445
446    /**
447     * Offset this date by N years, and round to the whole year.
448     *
449     * This is typically used to create an estimated death date,
450     * which is before a certain number of years after the birth date.
451     *
452     * @param int    $years     a number of years, positive or negative
453     * @param string $qualifier typically “BEF” or “AFT”
454     *
455     * @return Date
456     */
457    public function addYears(int $years, string $qualifier = ''): Date
458    {
459        $tmp               = clone $this;
460        $tmp->date1->year  += $years;
461        $tmp->date1->month = 0;
462        $tmp->date1->day   = 0;
463        $tmp->date1->setJdFromYmd();
464        $tmp->qual1 = $qualifier;
465        $tmp->qual2 = '';
466        $tmp->date2 = null;
467
468        return $tmp;
469    }
470
471    /**
472     * Compare two dates, so they can be sorted.
473     *
474     * return -1 if $a<$b
475     * return +1 if $b>$a
476     * return  0 if dates same/overlap
477     * BEF/AFT sort as the day before/after
478     *
479     * @param Date $a
480     * @param Date $b
481     *
482     * @return int
483     */
484    public static function compare(Date $a, Date $b): int
485    {
486        // Get min/max JD for each date.
487        switch ($a->qual1) {
488            case 'BEF':
489                $amin = $a->minimumJulianDay() - 1;
490                $amax = $amin;
491                break;
492            case 'AFT':
493                $amax = $a->maximumJulianDay() + 1;
494                $amin = $amax;
495                break;
496            default:
497                $amin = $a->minimumJulianDay();
498                $amax = $a->maximumJulianDay();
499                break;
500        }
501        switch ($b->qual1) {
502            case 'BEF':
503                $bmin = $b->minimumJulianDay() - 1;
504                $bmax = $bmin;
505                break;
506            case 'AFT':
507                $bmax = $b->maximumJulianDay() + 1;
508                $bmin = $bmax;
509                break;
510            default:
511                $bmin = $b->minimumJulianDay();
512                $bmax = $b->maximumJulianDay();
513                break;
514        }
515        if ($amax < $bmin) {
516            return -1;
517        }
518
519        if ($amin > $bmax && $bmax > 0) {
520            return 1;
521        }
522
523        if ($amin < $bmin && $amax <= $bmax) {
524            return -1;
525        }
526
527        if ($amin > $bmin && $amax >= $bmax && $bmax > 0) {
528            return 1;
529        }
530
531        return 0;
532    }
533
534    /**
535     * Check whether a gedcom date contains usable calendar date(s).
536     *
537     * An incomplete date such as "12 AUG" would be invalid, as
538     * we cannot sort it.
539     *
540     * @return bool
541     */
542    public function isOK(): bool
543    {
544        return $this->minimumJulianDay() && $this->maximumJulianDay();
545    }
546
547    /**
548     * Calculate the gregorian year for a date. This should NOT be used internally
549     * within WT - we should keep the code "calendar neutral" to allow support for
550     * jewish/arabic users. This is only for interfacing with external entities,
551     * such as the ancestry.com search interface or the dated fact icons.
552     *
553     * @return int
554     */
555    public function gregorianYear(): int
556    {
557        if ($this->isOK()) {
558            $gregorian_calendar = new GregorianCalendar();
559            [$year] = $gregorian_calendar->jdToYmd($this->julianDay());
560
561            return $year;
562        }
563
564        return 0;
565    }
566}
567