xref: /webtrees/app/Date.php (revision 309092efc56540a95d8117fad7180fe470aadff6)
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('/^(TO|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	/**
204	 * A list of supported calendars and their names.
205	 *
206	 * @return string[]
207	 */
208	public static function calendarNames() {
209		return array(
210			'gregorian' => /* I18N: The gregorian calendar */ I18N::translate('Gregorian'),
211			'julian'    => /* I18N: The julian calendar */ I18N::translate('Julian'),
212			'french'    => /* I18N: The French calendar */ I18N::translate('French'),
213			'jewish'    => /* I18N: The Hebrew/Jewish calendar */ I18N::translate('Jewish'),
214			'hijri'     => /* I18N: The Arabic/Hijri calendar */ I18N::translate('Hijri'),
215			'jalali'    => /* I18N: The Persian/Jalali calendar */ I18N::translate('Jalali'),
216		);
217	}
218
219	/**
220	 * Convert a date to the preferred format and calendar(s) display.
221	 *
222	 * @param boolean|null $url               Wrap the date in a link to calendar.php
223	 * @param string|null  $date_format       Override the default date format
224	 * @param boolean|null $convert_calendars Convert the date into other calendars
225	 *
226	 * @return string
227	 */
228	public function display($url = false, $date_format = null, $convert_calendars = true) {
229		global $WT_TREE;
230
231		// Search engines do not get links to the calendar pages
232		if (Auth::isSearchEngine()) {
233			$url = false;
234		}
235
236		$CALENDAR_FORMAT = $WT_TREE->getPreference('CALENDAR_FORMAT');
237
238		if ($date_format === null) {
239			$date_format = I18N::dateFormat();
240		}
241
242		if ($convert_calendars) {
243			$calendar_format = explode('_and_', $CALENDAR_FORMAT);
244		} else {
245			$calendar_format = array();
246		}
247
248		// Two dates with text before, between and after
249		$q1 = $this->qual1;
250		$d1 = $this->date1->format($date_format, $this->qual1);
251		$q2 = $this->qual2;
252		if (is_null($this->date2)) {
253			$d2 = '';
254		} else {
255			$d2 = $this->date2->format($date_format, $this->qual2);
256		}
257		// Con vert to other calendars, if requested
258		$conv1 = '';
259		$conv2 = '';
260		foreach ($calendar_format as $cal_fmt) {
261			if ($cal_fmt != 'none') {
262				$d1conv = $this->date1->convertToCalendar($cal_fmt);
263				if ($d1conv->inValidRange()) {
264					$d1tmp = $d1conv->format($date_format, $this->qual1);
265				} else {
266					$d1tmp = '';
267				}
268				if (is_null($this->date2)) {
269					$d2conv = null;
270					$d2tmp  = '';
271				} else {
272					$d2conv = $this->date2->convertToCalendar($cal_fmt);
273					if ($d2conv->inValidRange()) {
274						$d2tmp = $d2conv->format($date_format, $this->qual2);
275					} else {
276						$d2tmp = '';
277					}
278				}
279				// If the date is different from the unconverted date, add it to the date string.
280				if ($d1 != $d1tmp && $d1tmp !== '') {
281					if ($url) {
282						if ($CALENDAR_FORMAT !== 'none') {
283							$conv1 .= ' <span dir="' . I18N::direction() . '">(<a href="' . $d1conv->calendarUrl($date_format) . '">' . $d1tmp . '</a>)</span>';
284						} else {
285							$conv1 .= ' <span dir="' . I18N::direction() . '"><br><a href="' . $d1conv->calendarUrl($date_format) . '">' . $d1tmp . '</a></span>';
286						}
287					} else {
288						$conv1 .= ' <span dir="' . I18N::direction() . '">(' . $d1tmp . ')</span>';
289					}
290				}
291				if (!is_null($this->date2) && $d2 != $d2tmp && $d1tmp != '') {
292					if ($url) {
293						$conv2 .= ' <span dir="' . I18N::direction() . '">(<a href="' . $d2conv->calendarUrl($date_format) . '">' . $d2tmp . '</a>)</span>';
294					} else {
295						$conv2 .= ' <span dir="' . I18N::direction() . '">(' . $d2tmp . ')</span>';
296					}
297				}
298			}
299		}
300
301		// Add URLs, if requested
302		if ($url) {
303			$d1 = '<a href="' . $this->date1->calendarUrl($date_format) . '">' . $d1 . '</a>';
304			if (!is_null($this->date2)) {
305				$d2 = '<a href="' . $this->date2->calendarUrl($date_format) . '">' . $d2 . '</a>';
306			}
307		}
308
309		// Localise the date
310		switch ($q1 . $q2) {
311		case '':
312			$tmp = $d1 . $conv1;
313			break;
314		case 'ABT':
315			$tmp = /* I18N: Gedcom ABT dates */ I18N::translate('about %s', $d1 . $conv1);
316			break;
317		case 'CAL':
318			$tmp = /* I18N: Gedcom CAL dates */ I18N::translate('calculated %s', $d1 . $conv1);
319			break;
320		case 'EST':
321			$tmp = /* I18N: Gedcom EST dates */ I18N::translate('estimated %s', $d1 . $conv1);
322			break;
323		case 'INT':
324			$tmp = /* I18N: Gedcom INT dates */ I18N::translate('interpreted %s (%s)', $d1 . $conv1, $this->text);
325			break;
326		case 'BEF':
327			$tmp = /* I18N: Gedcom BEF dates */ I18N::translate('before %s', $d1 . $conv1);
328			break;
329		case 'AFT':
330			$tmp = /* I18N: Gedcom AFT dates */ I18N::translate('after %s', $d1 . $conv1);
331			break;
332		case 'FROM':
333			$tmp = /* I18N: Gedcom FROM dates */ I18N::translate('from %s', $d1 . $conv1);
334			break;
335		case 'TO':
336			$tmp = /* I18N: Gedcom TO dates */ I18N::translate('to %s', $d1 . $conv1);
337			break;
338		case 'BETAND':
339			$tmp = /* I18N: Gedcom BET-AND dates */ I18N::translate('between %s and %s', $d1 . $conv1, $d2 . $conv2);
340			break;
341		case 'FROMTO':
342			$tmp = /* I18N: Gedcom FROM-TO dates */ I18N::translate('from %s to %s', $d1 . $conv1, $d2 . $conv2);
343			break;
344		default:
345			$tmp = I18N::translate('Invalid date');
346			break; // e.g. BET without AND
347		}
348		if ($this->text && !$q1) {
349			$tmp = I18N::translate('%1$s (%2$s)', $tmp, $this->text);
350		}
351
352		if (strip_tags($tmp) === '') {
353			return '';
354		} else {
355			return '<span class="date">' . $tmp . '</span>';
356		}
357	}
358
359	/**
360	 * Get the earliest calendar date from this GEDCOM date.
361	 *
362	 * In the date “FROM 1900 TO 1910”, this would be 1900.
363	 *
364	 * @return CalendarDate
365	 */
366	public function minimumDate() {
367		return $this->date1;
368	}
369
370	/**
371	 * Get the latest calendar date from this GEDCOM date.
372	 *
373	 * In the date “FROM 1900 TO 1910”, this would be 1910.
374	 *
375	 * @return CalendarDate
376	 */
377	public function maximumDate() {
378		if (is_null($this->date2)) {
379			return $this->date1;
380		} else {
381			return $this->date2;
382		}
383	}
384
385	/**
386	 * Get the earliest Julian day number from this GEDCOM date.
387	 *
388	 * @return integer
389	 */
390	public function minimumJulianDay() {
391		return $this->minimumDate()->minJD;
392	}
393
394	/**
395	 * Get the latest Julian day number from this GEDCOM date.
396	 *
397	 * @return integer
398	 */
399	public function maximumJulianDay() {
400		return $this->maximumDate()->maxJD;
401	}
402
403	/**
404	 * Get the middle Julian day number from the GEDCOM date.
405	 *
406	 * For a month-only date, this would be somewhere around the 16th day.
407	 * For a year-only date, this would be somewhere around 1st July.
408	 *
409	 * @return integer
410	 */
411	public function julianDay() {
412		return (int) (($this->minimumJulianDay() + $this->maximumJulianDay()) / 2);
413	}
414
415	/**
416	 * Offset this date by N years, and round to the whole year.
417	 *
418	 * This is typically used to create an estimated death date,
419	 * which is before a certain number of years after the birth date.
420	 *
421	 * @param integer $years     - a number of years, positive or negative
422	 * @param string  $qualifier - typically “BEF” or “AFT”
423	 *
424	 * @return Date
425	 */
426	public function addYears($years, $qualifier = '') {
427		$tmp = clone $this;
428		$tmp->date1->y += $years;
429		$tmp->date1->m = 0;
430		$tmp->date1->d = 0;
431		$tmp->date1->setJdFromYmd();
432		$tmp->qual1 = $qualifier;
433		$tmp->qual2 = '';
434		$tmp->date2 = null;
435
436		return $tmp;
437	}
438
439	/**
440	 * Calculate the the age of a person, on a date.
441	 *
442	 * @param Date    $d1
443	 * @param Date    $d2
444	 * @param integer $format
445	 *
446	 * @return int|string
447	 * @throws \InvalidArgumentException
448	 */
449	public static function getAge(Date $d1, Date $d2 = null, $format = 0) {
450		if ($d2) {
451			if ($d2->maximumJulianDay() >= $d1->minimumJulianDay() && $d2->minimumJulianDay() <= $d1->minimumJulianDay()) {
452				// Overlapping dates
453				$jd = $d1->minimumJulianDay();
454			} else {
455				// Non-overlapping dates
456				$jd = $d2->minimumJulianDay();
457			}
458		} else {
459			// If second date not specified, use today’s date
460			$jd = WT_CLIENT_JD;
461		}
462
463		switch ($format) {
464		case 0:
465			// Years - integer only (for statistics, rather than for display)
466			if ($jd && $d1->minimumJulianDay() && $d1->minimumJulianDay() <= $jd) {
467				return $d1->minimumDate()->getAge(false, $jd, false);
468			} else {
469				return -1;
470			}
471		case 1:
472			// Days - integer only (for sorting, rather than for display)
473			if ($jd && $d1->minimumJulianDay()) {
474				return $jd - $d1->minimumJulianDay();
475			} else {
476				return -1;
477			}
478		case 2:
479			// Just years, in local digits, with warning for negative/
480			if ($jd && $d1->minimumJulianDay()) {
481				if ($d1->minimumJulianDay() > $jd) {
482					return '<i class="icon-warning"></i>';
483				} else {
484					return I18N::number($d1->minimumDate()->getAge(false, $jd));
485				}
486			} else {
487				return '&nbsp;';
488			}
489		default:
490			throw new \InvalidArgumentException('format: ' . $format);
491		}
492	}
493
494	/**
495	 * Calculate the years/months/days between two events
496	 * Return a gedcom style age string: "1y 2m 3d" (for fact details)
497	 *
498	 * @param Date      $d1
499	 * @param Date|null $d2
500	 * @param boolean      $warn_on_negative
501	 *
502	 * @return string
503	 */
504	public static function getAgeGedcom(Date $d1, Date $d2 = null, $warn_on_negative = true) {
505		if (is_null($d2)) {
506			return $d1->date1->getAge(true, WT_CLIENT_JD, $warn_on_negative);
507		} else {
508			// If dates overlap, then can’t calculate age.
509			if (self::compare($d1, $d2)) {
510				return $d1->date1->getAge(true, $d2->minimumJulianDay(), $warn_on_negative);
511			} elseif (self::compare($d1, $d2) == 0 && $d1->date1->minJD == $d2->minimumJulianDay()) {
512				return '0d';
513			} else {
514				return '';
515			}
516		}
517	}
518
519	/**
520	 * Compare two dates, so they can be sorted.
521	 *
522	 * return <0 if $a<$b
523	 * return >0 if $b>$a
524	 * return  0 if dates same/overlap
525	 * BEF/AFT sort as the day before/after
526	 *
527	 * @param Date $a
528	 * @param Date $b
529	 *
530	 * @return integer
531	 */
532	public static function compare(Date $a, Date $b) {
533		// Get min/max JD for each date.
534		switch ($a->qual1) {
535		case 'BEF':
536			$amin = $a->minimumJulianDay() - 1;
537			$amax = $amin;
538			break;
539		case 'AFT':
540			$amax = $a->maximumJulianDay() + 1;
541			$amin = $amax;
542			break;
543		default:
544			$amin = $a->minimumJulianDay();
545			$amax = $a->maximumJulianDay();
546			break;
547		}
548		switch ($b->qual1) {
549		case 'BEF':
550			$bmin = $b->minimumJulianDay() - 1;
551			$bmax = $bmin;
552			break;
553		case 'AFT':
554			$bmax = $b->maximumJulianDay() + 1;
555			$bmin = $bmax;
556			break;
557		default:
558			$bmin = $b->minimumJulianDay();
559			$bmax = $b->maximumJulianDay();
560			break;
561		}
562		if ($amax < $bmin) {
563			return -1;
564		} elseif ($amin > $bmax && $bmax > 0) {
565			return 1;
566		} elseif ($amin < $bmin && $amax <= $bmax) {
567			return -1;
568		} elseif ($amin > $bmin && $amax >= $bmax && $bmax > 0) {
569			return 1;
570		} else {
571			return 0;
572		}
573	}
574
575	/**
576	 * Check whether a gedcom date contains usable calendar date(s).
577	 *
578	 * An incomplete date such as "12 AUG" would be invalid, as
579	 * we cannot sort it.
580	 *
581	 * @return boolean
582	 */
583	public function isOK() {
584		return $this->minimumJulianDay() && $this->maximumJulianDay();
585	}
586
587	/**
588	 * Calculate the gregorian year for a date.  This should NOT be used internally
589	 * within WT - we should keep the code "calendar neutral" to allow support for
590	 * jewish/arabic users.  This is only for interfacing with external entities,
591	 * such as the ancestry.com search interface or the dated fact icons.
592	 *
593	 * @return integer
594	 */
595	public function gregorianYear() {
596		if ($this->isOK()) {
597			$gregorian_calendar = new GregorianCalendar;
598			list($year) = $gregorian_calendar->jdToYmd($this->julianDay());
599
600			return $year;
601		} else {
602			return 0;
603		}
604	}
605}
606