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