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