xref: /webtrees/app/Date.php (revision 00b1984e374faddab4698e73088f0c964e529b65)
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 */
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    /** @var string Optional qualifier, such as BEF, FROM, ABT */
49    public $qual1 = '';
50
51    /** @var AbstractCalendarDate  The first (or only) date */
52    private $date1;
53
54    /** @var string  Optional qualifier, such as TO, AND */
55    public $qual2 = '';
56
57    /** @var AbstractCalendarDate|null Optional second date */
58    private $date2 = null;
59
60    /** @var string Optional text, as included with an INTerpreted date */
61    private $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     * @throws DomainException
107     * @return AbstractCalendarDate
108     */
109    private function parseDate($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 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|null   $url               Wrap the date in a link to calendar.php
247     * @param string|null $date_format       Override the default date format
248     * @param bool|null   $convert_calendars Convert the date into other calendars
249     *
250     * @return string
251     */
252    public function display($url = false, $date_format = null, $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        if ($date_format === null) {
264            $date_format = I18N::dateFormat();
265        }
266
267        if ($convert_calendars) {
268            $calendar_format = explode('_and_', $CALENDAR_FORMAT);
269        } else {
270            $calendar_format = [];
271        }
272
273        // Two dates with text before, between and after
274        $q1 = $this->qual1;
275        $d1 = $this->date1->format($date_format, $this->qual1);
276        $q2 = $this->qual2;
277        if ($this->date2 === null) {
278            $d2 = '';
279        } else {
280            $d2 = $this->date2->format($date_format, $this->qual2);
281        }
282        // Con vert to other calendars, if requested
283        $conv1 = '';
284        $conv2 = '';
285        foreach ($calendar_format as $cal_fmt) {
286            if ($cal_fmt !== 'none') {
287                $d1conv = $this->date1->convertToCalendar($cal_fmt);
288                if ($d1conv->inValidRange()) {
289                    $d1tmp = $d1conv->format($date_format, $this->qual1);
290                } else {
291                    $d1tmp = '';
292                }
293                if ($this->date2 === null) {
294                    $d2conv = null;
295                    $d2tmp  = '';
296                } else {
297                    $d2conv = $this->date2->convertToCalendar($cal_fmt);
298                    if ($d2conv->inValidRange()) {
299                        $d2tmp = $d2conv->format($date_format, $this->qual2);
300                    } else {
301                        $d2tmp = '';
302                    }
303                }
304                // If the date is different from the unconverted date, add it to the date string.
305                if ($d1 != $d1tmp && $d1tmp !== '') {
306                    if ($url) {
307                        if ($CALENDAR_FORMAT !== 'none') {
308                            $conv1 .= ' <span dir="' . I18N::direction() . '">(<a href="' . $d1conv->calendarUrl($date_format, $tree) . '" rel="nofollow">' . $d1tmp . '</a>)</span>';
309                        } else {
310                            $conv1 .= ' <span dir="' . I18N::direction() . '"><br><a href="' . $d1conv->calendarUrl($date_format, $tree) . '" rel="nofollow">' . $d1tmp . '</a></span>';
311                        }
312                    } else {
313                        $conv1 .= ' <span dir="' . I18N::direction() . '">(' . $d1tmp . ')</span>';
314                    }
315                }
316                if ($this->date2 !== null && $d2 != $d2tmp && $d1tmp != '') {
317                    if ($url) {
318                        $conv2 .= ' <span dir="' . I18N::direction() . '">(<a href="' . $d2conv->calendarUrl($date_format, $tree) . '" rel="nofollow">' . $d2tmp . '</a>)</span>';
319                    } else {
320                        $conv2 .= ' <span dir="' . I18N::direction() . '">(' . $d2tmp . ')</span>';
321                    }
322                }
323            }
324        }
325
326        // Add URLs, if requested
327        if ($url) {
328            $d1 = '<a href="' . $this->date1->calendarUrl($date_format, $tree) . '" rel="nofollow">' . $d1 . '</a>';
329            if ($this->date2 instanceof AbstractCalendarDate) {
330                $d2 = '<a href="' . $this->date2->calendarUrl($date_format, $tree) . '" rel="nofollow">' . $d2 . '</a>';
331            }
332        }
333
334        // Localise the date
335        switch ($q1 . $q2) {
336            case '':
337                $tmp = $d1 . $conv1;
338                break;
339            case 'ABT':
340                /* I18N: Gedcom ABT dates */
341                $tmp = I18N::translate('about %s', $d1 . $conv1);
342                break;
343            case 'CAL':
344                /* I18N: Gedcom CAL dates */
345                $tmp = I18N::translate('calculated %s', $d1 . $conv1);
346                break;
347            case 'EST':
348                /* I18N: Gedcom EST dates */
349                $tmp = I18N::translate('estimated %s', $d1 . $conv1);
350                break;
351            case 'INT':
352                /* I18N: Gedcom INT dates */
353                $tmp = I18N::translate('interpreted %s (%s)', $d1 . $conv1, e($this->text));
354                break;
355            case 'BEF':
356                /* I18N: Gedcom BEF dates */
357                $tmp = I18N::translate('before %s', $d1 . $conv1);
358                break;
359            case 'AFT':
360                /* I18N: Gedcom AFT dates */
361                $tmp = I18N::translate('after %s', $d1 . $conv1);
362                break;
363            case 'FROM':
364                /* I18N: Gedcom FROM dates */
365                $tmp = I18N::translate('from %s', $d1 . $conv1);
366                break;
367            case 'TO':
368                /* I18N: Gedcom TO dates */
369                $tmp = I18N::translate('to %s', $d1 . $conv1);
370                break;
371            case 'BETAND':
372                /* I18N: Gedcom BET-AND dates */
373                $tmp = I18N::translate('between %s and %s', $d1 . $conv1, $d2 . $conv2);
374                break;
375            case 'FROMTO':
376                /* I18N: Gedcom FROM-TO dates */
377                $tmp = I18N::translate('from %s to %s', $d1 . $conv1, $d2 . $conv2);
378                break;
379            default:
380                $tmp = I18N::translate('Invalid date');
381                break;
382        }
383
384        if (strip_tags($tmp) === '') {
385            return '';
386        }
387
388        return '<span class="date">' . $tmp . '</span>';
389    }
390
391    /**
392     * Get the earliest calendar date from this GEDCOM date.
393     *
394     * In the date “FROM 1900 TO 1910”, this would be 1900.
395     *
396     * @return AbstractCalendarDate
397     */
398    public function minimumDate(): AbstractCalendarDate
399    {
400        return $this->date1;
401    }
402
403    /**
404     * Get the latest calendar date from this GEDCOM date.
405     *
406     * In the date “FROM 1900 TO 1910”, this would be 1910.
407     *
408     * @return AbstractCalendarDate
409     */
410    public function maximumDate(): AbstractCalendarDate
411    {
412        return $this->date2 ?? $this->date1;
413    }
414
415    /**
416     * Get the earliest Julian day number from this GEDCOM date.
417     *
418     * @return int
419     */
420    public function minimumJulianDay(): int
421    {
422        return $this->minimumDate()->minimumJulianDay();
423    }
424
425    /**
426     * Get the latest Julian day number from this GEDCOM date.
427     *
428     * @return int
429     */
430    public function maximumJulianDay(): int
431    {
432        return $this->maximumDate()->maximumJulianDay();
433    }
434
435    /**
436     * Get the middle Julian day number from the GEDCOM date.
437     *
438     * For a month-only date, this would be somewhere around the 16th day.
439     * For a year-only date, this would be somewhere around 1st July.
440     *
441     * @return int
442     */
443    public function julianDay(): int
444    {
445        return intdiv($this->minimumJulianDay() + $this->maximumJulianDay(), 2);
446    }
447
448    /**
449     * Offset this date by N years, and round to the whole year.
450     *
451     * This is typically used to create an estimated death date,
452     * which is before a certain number of years after the birth date.
453     *
454     * @param int    $years     a number of years, positive or negative
455     * @param string $qualifier typically “BEF” or “AFT”
456     *
457     * @return Date
458     */
459    public function addYears(int $years, string $qualifier = ''): Date
460    {
461        $tmp               = clone $this;
462        $tmp->date1->year  += $years;
463        $tmp->date1->month = 0;
464        $tmp->date1->day   = 0;
465        $tmp->date1->setJdFromYmd();
466        $tmp->qual1 = $qualifier;
467        $tmp->qual2 = '';
468        $tmp->date2 = null;
469
470        return $tmp;
471    }
472
473    /**
474     * Calculate the the age of a person (n years), on a given date.
475     *
476     * @param Date $d1
477     * @param Date $d2
478     *
479     * @return int
480     */
481    public static function getAgeYears(Date $d1, Date $d2): int
482    {
483        if (self::compare($d1, $d2) === 0) {
484            // Overlapping dates
485            $jd = $d1->minimumJulianDay();
486        } else {
487            // Non-overlapping dates
488            $jd = $d2->minimumJulianDay();
489        }
490
491        if ($jd && $d1->minimumJulianDay() && $d1->minimumJulianDay() <= $jd) {
492            return $d1->minimumDate()->getAge($jd);
493        }
494
495        return -1;
496    }
497
498    /**
499     * Calculate the the age of a person (n days), on a given date.
500     *
501     * @param Date $d1
502     * @param Date $d2
503     *
504     * @return int
505     */
506    public static function getAgeDays(Date $d1, Date $d2): int
507    {
508        if ($d2->maximumJulianDay() >= $d1->minimumJulianDay() && $d2->minimumJulianDay() <= $d1->maximumJulianDay()) {
509            // Overlapping dates
510            $jd = $d1->minimumJulianDay();
511        } else {
512            // Non-overlapping dates
513            $jd = $d2->minimumJulianDay();
514        }
515
516        // Days - integer only (for sorting, rather than for display)
517        if ($jd && $d1->minimumJulianDay()) {
518            return $jd - $d1->minimumJulianDay();
519        }
520
521        return -1;
522    }
523
524    /**
525     * Calculate the the age of a person, on a date.
526     *
527     * @param Date      $d1
528     * @param Date|null $d2
529     *
530     * @return string
531     */
532    public static function getAge(Date $d1, Date $d2 = null): string
533    {
534        if ($d2 instanceof self) {
535            if ($d2->maximumJulianDay() >= $d1->minimumJulianDay() && $d2->minimumJulianDay() <= $d1->maximumJulianDay()) {
536                // Overlapping dates
537                $jd = $d1->minimumJulianDay();
538            } else {
539                // Non-overlapping dates
540                $jd = $d2->minimumJulianDay();
541            }
542        } else {
543            // If second date not specified, use today’s date
544            $jd = Carbon::now()->julianDay();
545        }
546
547        // Just years, in local digits, with warning for negative/
548        if ($jd && $d1->minimumJulianDay()) {
549            if ($d1->minimumJulianDay() > $jd) {
550                return view('icons/warning');
551            }
552
553            $years = $d1->minimumDate()->getAge($jd);
554
555            return I18N::number($years);
556        }
557
558        return '';
559    }
560
561    /**
562     * Calculate the years/months/days between two events
563     * Return a gedcom style age string: "1y 2m 3d" (for fact details)
564     *
565     * @param Date      $d1
566     * @param Date|null $d2
567     *
568     * @return string
569     */
570    public static function getAgeGedcom(Date $d1, Date $d2 = null): string
571    {
572        if ($d2 === null) {
573            return $d1->date1->getAgeFull(Carbon::now()->julianDay());
574        }
575
576        if (self::compare($d1, $d2) !== 0) {
577            return $d1->date1->getAgeFull($d2->minimumJulianDay());
578        }
579
580        if ($d1->minimumJulianDay() == $d2->minimumJulianDay()) {
581            return '0d';
582        }
583
584        return '';
585    }
586
587    /**
588     * Compare two dates, so they can be sorted.
589     *
590     * return <0 if $a<$b
591     * return >0 if $b>$a
592     * return  0 if dates same/overlap
593     * BEF/AFT sort as the day before/after
594     *
595     * @param Date $a
596     * @param Date $b
597     *
598     * @return int
599     */
600    public static function compare(Date $a, Date $b): int
601    {
602        // Get min/max JD for each date.
603        switch ($a->qual1) {
604            case 'BEF':
605                $amin = $a->minimumJulianDay() - 1;
606                $amax = $amin;
607                break;
608            case 'AFT':
609                $amax = $a->maximumJulianDay() + 1;
610                $amin = $amax;
611                break;
612            default:
613                $amin = $a->minimumJulianDay();
614                $amax = $a->maximumJulianDay();
615                break;
616        }
617        switch ($b->qual1) {
618            case 'BEF':
619                $bmin = $b->minimumJulianDay() - 1;
620                $bmax = $bmin;
621                break;
622            case 'AFT':
623                $bmax = $b->maximumJulianDay() + 1;
624                $bmin = $bmax;
625                break;
626            default:
627                $bmin = $b->minimumJulianDay();
628                $bmax = $b->maximumJulianDay();
629                break;
630        }
631        if ($amax < $bmin) {
632            return -1;
633        }
634
635        if ($amin > $bmax && $bmax > 0) {
636            return 1;
637        }
638
639        if ($amin < $bmin && $amax <= $bmax) {
640            return -1;
641        }
642
643        if ($amin > $bmin && $amax >= $bmax && $bmax > 0) {
644            return 1;
645        }
646
647        return 0;
648    }
649
650    /**
651     * Check whether a gedcom date contains usable calendar date(s).
652     *
653     * An incomplete date such as "12 AUG" would be invalid, as
654     * we cannot sort it.
655     *
656     * @return bool
657     */
658    public function isOK(): bool
659    {
660        return $this->minimumJulianDay() && $this->maximumJulianDay();
661    }
662
663    /**
664     * Calculate the gregorian year for a date. This should NOT be used internally
665     * within WT - we should keep the code "calendar neutral" to allow support for
666     * jewish/arabic users. This is only for interfacing with external entities,
667     * such as the ancestry.com search interface or the dated fact icons.
668     *
669     * @return int
670     */
671    public function gregorianYear(): int
672    {
673        if ($this->isOK()) {
674            $gregorian_calendar = new GregorianCalendar();
675            [$year] = $gregorian_calendar->jdToYmd($this->julianDay());
676
677            return $year;
678        }
679
680        return 0;
681    }
682}
683