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