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