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