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