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