xref: /webtrees/app/Date.php (revision d5d589847982b4ed47de90592c05d01c42f71920)
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;
19
20use DomainException;
21use Fisharebest\ExtCalendar\GregorianCalendar;
22use Fisharebest\Webtrees\Date\AbstractCalendarDate;
23use Fisharebest\Webtrees\Date\FrenchDate;
24use Fisharebest\Webtrees\Date\GregorianDate;
25use Fisharebest\Webtrees\Date\HijriDate;
26use Fisharebest\Webtrees\Date\JalaliDate;
27use Fisharebest\Webtrees\Date\JewishDate;
28use Fisharebest\Webtrees\Date\JulianDate;
29use Fisharebest\Webtrees\Date\RomanDate;
30
31/**
32 * A representation of GEDCOM dates and date ranges.
33 *
34 * Since different calendars start their days at different times, (civil
35 * midnight, solar midnight, sunset, sunrise, etc.), we convert on the basis of
36 * midday.
37 *
38 * We assume that years start on the first day of the first month. Where
39 * this is not the case (e.g. England prior to 1752), we need to use modified
40 * years or the OS/NS notation "4 FEB 1750/51".
41 */
42class Date
43{
44    /** @var string Optional qualifier, such as BEF, FROM, ABT */
45    public $qual1 = '';
46
47    /** @var AbstractCalendarDate  The first (or only) date */
48    private $date1;
49
50    /** @var string  Optional qualifier, such as TO, AND */
51    public $qual2 = '';
52
53    /** @var AbstractCalendarDate|null Optional second date */
54    private $date2 = null;
55
56    /** @var string ptional text, as included with an INTerpreted date */
57    private $text = '';
58
59    /**
60     * Create a date, from GEDCOM data.
61     *
62     * @param string $date A date in GEDCOM format
63     */
64    public function __construct(string $date)
65    {
66        // Extract any explanatory text
67        if (preg_match('/^(.*) ?[(](.*)[)]/', $date, $match)) {
68            $date       = $match[1];
69            $this->text = $match[2];
70        }
71        if (preg_match('/^(FROM|BET) (.+) (AND|TO) (.+)/', $date, $match)) {
72            $this->qual1 = $match[1];
73            $this->date1 = $this->parseDate($match[2]);
74            $this->qual2 = $match[3];
75            $this->date2 = $this->parseDate($match[4]);
76        } elseif (preg_match('/^(TO|FROM|BEF|AFT|CAL|EST|INT|ABT) (.+)/', $date, $match)) {
77            $this->qual1 = $match[1];
78            $this->date1 = $this->parseDate($match[2]);
79        } else {
80            $this->date1 = $this->parseDate($date);
81        }
82    }
83
84    /**
85     * When we copy a date object, we need to create copies of
86     * its child objects.
87     */
88    public function __clone()
89    {
90        $this->date1 = clone $this->date1;
91        if ($this->date2 !== null) {
92            $this->date2 = clone $this->date2;
93        }
94    }
95
96    /**
97     * Convert a calendar date, such as "12 JUN 1943" into calendar date object.
98     * A GEDCOM date range may have two calendar dates.
99     *
100     * @param string $date
101     *
102     * @throws DomainException
103     * @return AbstractCalendarDate
104     */
105    private function parseDate($date): AbstractCalendarDate
106    {
107        // Valid calendar escape specified? - use it
108        if (preg_match('/^(@#D(?:GREGORIAN|JULIAN|HEBREW|HIJRI|JALALI|FRENCH R|ROMAN)+@) ?(.*)/', $date, $match)) {
109            $cal  = $match[1];
110            $date = $match[2];
111        } else {
112            $cal = '';
113        }
114        // A date with a month: DM, M, MY or DMY
115        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)) {
116            $d = $match[1];
117            $m = $match[2];
118            $y = $match[3];
119        } elseif (preg_match('/^(\d{1,4}(?: B\.C\.)?|\d\d\d\d\/\d\d)$/', $date, $match)) {
120            // A date with just a year
121            $d = '';
122            $m = '';
123            $y = $match[1];
124        } else {
125            // An invalid date - do the best we can.
126            $d = '';
127            $m = '';
128            $y = '';
129            // Look for a 3/4 digit year anywhere in the date
130            if (preg_match('/\b(\d{3,4})\b/', $date, $match)) {
131                $y = $match[1];
132            }
133            // Look for a month anywhere in the date
134            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)) {
135                $m = $match[1];
136                // Look for a day number anywhere in the date
137                if (preg_match('/\b(\d\d?)\b/', $date, $match)) {
138                    $d = $match[1];
139                }
140            }
141        }
142
143        // Unambiguous dates - override calendar escape
144        if (preg_match('/^(TSH|CSH|KSL|TVT|SHV|ADR|ADS|NSN|IYR|SVN|TMZ|AAV|ELL)$/', $m)) {
145            $cal = JewishDate::ESCAPE;
146        } else {
147            if (preg_match('/^(VEND|BRUM|FRIM|NIVO|PLUV|VENT|GERM|FLOR|PRAI|MESS|THER|FRUC|COMP)$/', $m)) {
148                $cal = FrenchDate::ESCAPE;
149            } else {
150                if (preg_match('/^(MUHAR|SAFAR|RABI[AT]|JUMA[AT]|RAJAB|SHAAB|RAMAD|SHAWW|DHUAQ|DHUAH)$/', $m)) {
151                    $cal = HijriDate::ESCAPE; // This is a WT extension
152                } else {
153                    if (preg_match('/^(FARVA|ORDIB|KHORD|TIR|MORDA|SHAHR|MEHR|ABAN|AZAR|DEY|BAHMA|ESFAN)$/', $m)) {
154                        $cal = JalaliDate::ESCAPE; // This is a WT extension
155                    } elseif (preg_match('/^\d{1,4}( B\.C\.)|\d\d\d\d\/\d\d$/', $y)) {
156                        $cal = JulianDate::ESCAPE;
157                    }
158                }
159            }
160        }
161
162        // Ambiguous dates - don't override calendar escape
163        if ($cal == '') {
164            if (preg_match('/^(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)$/', $m)) {
165                $cal =  GregorianDate::ESCAPE;
166            } else {
167                if (preg_match('/^[345]\d\d\d$/', $y)) {
168                    // Year 3000-5999
169                    $cal = JewishDate::ESCAPE;
170                } else {
171                    $cal = GregorianDate::ESCAPE;
172                }
173            }
174        }
175        // Now construct an object of the correct type
176        switch ($cal) {
177            case GregorianDate::ESCAPE:
178                return new GregorianDate([
179                    $y,
180                    $m,
181                    $d,
182                ]);
183            case JulianDate::ESCAPE:
184                return new JulianDate([
185                    $y,
186                    $m,
187                    $d,
188                ]);
189            case JewishDate::ESCAPE:
190                return new JewishDate([
191                    $y,
192                    $m,
193                    $d,
194                ]);
195            case HijriDate::ESCAPE:
196                return new HijriDate([
197                    $y,
198                    $m,
199                    $d,
200                ]);
201            case FrenchDate::ESCAPE:
202                return new FrenchDate([
203                    $y,
204                    $m,
205                    $d,
206                ]);
207            case JalaliDate::ESCAPE:
208                return new JalaliDate([
209                    $y,
210                    $m,
211                    $d,
212                ]);
213            case RomanDate::ESCAPE:
214                return new RomanDate([
215                    $y,
216                    $m,
217                    $d,
218                ]);
219            default:
220                throw new DomainException('Invalid calendar');
221        }
222    }
223
224    /**
225     * A list of supported calendars and their names.
226     *
227     * @return string[]
228     */
229    public static function calendarNames(): array
230    {
231        return [
232            /* I18N: The gregorian calendar */
233            'gregorian' => I18N::translate('Gregorian'),
234            /* I18N: The julian calendar */
235            'julian'    => I18N::translate('Julian'),
236            /* I18N: The French calendar */
237            'french'    => I18N::translate('French'),
238            /* I18N: The Hebrew/Jewish calendar */
239            'jewish'    => I18N::translate('Jewish'),
240            /* I18N: The Arabic/Hijri calendar */
241            'hijri'     => I18N::translate('Hijri'),
242            /* I18N: The Persian/Jalali calendar */
243            'jalali'    => I18N::translate('Jalali'),
244        ];
245    }
246
247    /**
248     * Convert a date to the preferred format and calendar(s) display.
249     *
250     * @param bool|null   $url               Wrap the date in a link to calendar.php
251     * @param string|null $date_format       Override the default date format
252     * @param bool|null   $convert_calendars Convert the date into other calendars
253     *
254     * @return string
255     */
256    public function display($url = false, $date_format = null, $convert_calendars = true)
257    {
258        // Do we need a new DateFormatterService class?
259        $tree = app(Tree::class);
260
261        $CALENDAR_FORMAT = $tree->getPreference('CALENDAR_FORMAT');
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()
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 ($d2->maximumJulianDay() >= $d1->minimumJulianDay() && $d2->minimumJulianDay() <= $d1->minimumJulianDay()) {
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        } else {
494            return -1;
495        }
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->minimumJulianDay()) {
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        } else {
520            return -1;
521        }
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 Date) {
535            if ($d2->maximumJulianDay() >= $d1->minimumJulianDay() && $d2->minimumJulianDay() <= $d1->minimumJulianDay()) {
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            } else {
552                $years = $d1->minimumDate()->getAge($jd);
553
554                return I18N::number($years);
555            }
556        } else {
557            return '';
558        }
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)
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)
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()
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