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