DateAndOrTime.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <?php
  2. namespace Sabre\VObject\Property\VCard;
  3. use DateTime;
  4. use DateTimeImmutable;
  5. use DateTimeInterface;
  6. use Sabre\VObject\DateTimeParser;
  7. use Sabre\VObject\InvalidDataException;
  8. use Sabre\VObject\Property;
  9. use Sabre\Xml;
  10. /**
  11. * DateAndOrTime property.
  12. *
  13. * This object encodes DATE-AND-OR-TIME values.
  14. *
  15. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  16. * @author Evert Pot (http://evertpot.com/)
  17. * @license http://sabre.io/license/ Modified BSD License
  18. */
  19. class DateAndOrTime extends Property
  20. {
  21. /**
  22. * Field separator.
  23. *
  24. * @var string
  25. */
  26. public $delimiter = '';
  27. /**
  28. * Returns the type of value.
  29. *
  30. * This corresponds to the VALUE= parameter. Every property also has a
  31. * 'default' valueType.
  32. *
  33. * @return string
  34. */
  35. public function getValueType()
  36. {
  37. return 'DATE-AND-OR-TIME';
  38. }
  39. /**
  40. * Sets a multi-valued property.
  41. *
  42. * You may also specify DateTimeInterface objects here.
  43. */
  44. public function setParts(array $parts)
  45. {
  46. if (count($parts) > 1) {
  47. throw new \InvalidArgumentException('Only one value allowed');
  48. }
  49. if (isset($parts[0]) && $parts[0] instanceof DateTimeInterface) {
  50. $this->setDateTime($parts[0]);
  51. } else {
  52. parent::setParts($parts);
  53. }
  54. }
  55. /**
  56. * Updates the current value.
  57. *
  58. * This may be either a single, or multiple strings in an array.
  59. *
  60. * Instead of strings, you may also use DateTimeInterface here.
  61. *
  62. * @param string|array|DateTimeInterface $value
  63. */
  64. public function setValue($value)
  65. {
  66. if ($value instanceof DateTimeInterface) {
  67. $this->setDateTime($value);
  68. } else {
  69. parent::setValue($value);
  70. }
  71. }
  72. /**
  73. * Sets the property as a DateTime object.
  74. */
  75. public function setDateTime(DateTimeInterface $dt)
  76. {
  77. $tz = $dt->getTimeZone();
  78. $isUtc = in_array($tz->getName(), ['UTC', 'GMT', 'Z']);
  79. if ($isUtc) {
  80. $value = $dt->format('Ymd\\THis\\Z');
  81. } else {
  82. // Calculating the offset.
  83. $value = $dt->format('Ymd\\THisO');
  84. }
  85. $this->value = $value;
  86. }
  87. /**
  88. * Returns a date-time value.
  89. *
  90. * Note that if this property contained more than 1 date-time, only the
  91. * first will be returned. To get an array with multiple values, call
  92. * getDateTimes.
  93. *
  94. * If no time was specified, we will always use midnight (in the default
  95. * timezone) as the time.
  96. *
  97. * If parts of the date were omitted, such as the year, we will grab the
  98. * current values for those. So at the time of writing, if the year was
  99. * omitted, we would have filled in 2014.
  100. *
  101. * @return DateTimeImmutable
  102. */
  103. public function getDateTime()
  104. {
  105. $now = new DateTime();
  106. $tzFormat = 0 === $now->getTimezone()->getOffset($now) ? '\\Z' : 'O';
  107. $nowParts = DateTimeParser::parseVCardDateTime($now->format('Ymd\\This'.$tzFormat));
  108. $dateParts = DateTimeParser::parseVCardDateTime($this->getValue());
  109. // This sets all the missing parts to the current date/time.
  110. // So if the year was missing for a birthday, we're making it 'this
  111. // year'.
  112. foreach ($dateParts as $k => $v) {
  113. if (is_null($v)) {
  114. $dateParts[$k] = $nowParts[$k];
  115. }
  116. }
  117. return new DateTimeImmutable("$dateParts[year]-$dateParts[month]-$dateParts[date] $dateParts[hour]:$dateParts[minute]:$dateParts[second] $dateParts[timezone]");
  118. }
  119. /**
  120. * Returns the value, in the format it should be encoded for json.
  121. *
  122. * This method must always return an array.
  123. *
  124. * @return array
  125. */
  126. public function getJsonValue()
  127. {
  128. $parts = DateTimeParser::parseVCardDateTime($this->getValue());
  129. $dateStr = '';
  130. // Year
  131. if (!is_null($parts['year'])) {
  132. $dateStr .= $parts['year'];
  133. if (!is_null($parts['month'])) {
  134. // If a year and a month is set, we need to insert a separator
  135. // dash.
  136. $dateStr .= '-';
  137. }
  138. } else {
  139. if (!is_null($parts['month']) || !is_null($parts['date'])) {
  140. // Inserting two dashes
  141. $dateStr .= '--';
  142. }
  143. }
  144. // Month
  145. if (!is_null($parts['month'])) {
  146. $dateStr .= $parts['month'];
  147. if (isset($parts['date'])) {
  148. // If month and date are set, we need the separator dash.
  149. $dateStr .= '-';
  150. }
  151. } elseif (isset($parts['date'])) {
  152. // If the month is empty, and a date is set, we need a 'empty
  153. // dash'
  154. $dateStr .= '-';
  155. }
  156. // Date
  157. if (!is_null($parts['date'])) {
  158. $dateStr .= $parts['date'];
  159. }
  160. // Early exit if we don't have a time string.
  161. if (is_null($parts['hour']) && is_null($parts['minute']) && is_null($parts['second'])) {
  162. return [$dateStr];
  163. }
  164. $dateStr .= 'T';
  165. // Hour
  166. if (!is_null($parts['hour'])) {
  167. $dateStr .= $parts['hour'];
  168. if (!is_null($parts['minute'])) {
  169. $dateStr .= ':';
  170. }
  171. } else {
  172. // We know either minute or second _must_ be set, so we insert a
  173. // dash for an empty value.
  174. $dateStr .= '-';
  175. }
  176. // Minute
  177. if (!is_null($parts['minute'])) {
  178. $dateStr .= $parts['minute'];
  179. if (!is_null($parts['second'])) {
  180. $dateStr .= ':';
  181. }
  182. } elseif (isset($parts['second'])) {
  183. // Dash for empty minute
  184. $dateStr .= '-';
  185. }
  186. // Second
  187. if (!is_null($parts['second'])) {
  188. $dateStr .= $parts['second'];
  189. }
  190. // Timezone
  191. if (!is_null($parts['timezone'])) {
  192. $dateStr .= $parts['timezone'];
  193. }
  194. return [$dateStr];
  195. }
  196. /**
  197. * This method serializes only the value of a property. This is used to
  198. * create xCard or xCal documents.
  199. *
  200. * @param Xml\Writer $writer XML writer
  201. */
  202. protected function xmlSerializeValue(Xml\Writer $writer)
  203. {
  204. $valueType = strtolower($this->getValueType());
  205. $parts = DateTimeParser::parseVCardDateAndOrTime($this->getValue());
  206. $value = '';
  207. // $d = defined
  208. $d = function ($part) use ($parts) {
  209. return !is_null($parts[$part]);
  210. };
  211. // $r = read
  212. $r = function ($part) use ($parts) {
  213. return $parts[$part];
  214. };
  215. // From the Relax NG Schema.
  216. //
  217. // # 4.3.1
  218. // value-date = element date {
  219. // xsd:string { pattern = "\d{8}|\d{4}-\d\d|--\d\d(\d\d)?|---\d\d" }
  220. // }
  221. if (($d('year') || $d('month') || $d('date'))
  222. && (!$d('hour') && !$d('minute') && !$d('second') && !$d('timezone'))) {
  223. if ($d('year') && $d('month') && $d('date')) {
  224. $value .= $r('year').$r('month').$r('date');
  225. } elseif ($d('year') && $d('month') && !$d('date')) {
  226. $value .= $r('year').'-'.$r('month');
  227. } elseif (!$d('year') && $d('month')) {
  228. $value .= '--'.$r('month').$r('date');
  229. } elseif (!$d('year') && !$d('month') && $d('date')) {
  230. $value .= '---'.$r('date');
  231. }
  232. // # 4.3.2
  233. // value-time = element time {
  234. // xsd:string { pattern = "(\d\d(\d\d(\d\d)?)?|-\d\d(\d\d?)|--\d\d)"
  235. // ~ "(Z|[+\-]\d\d(\d\d)?)?" }
  236. // }
  237. } elseif ((!$d('year') && !$d('month') && !$d('date'))
  238. && ($d('hour') || $d('minute') || $d('second'))) {
  239. if ($d('hour')) {
  240. $value .= $r('hour').$r('minute').$r('second');
  241. } elseif ($d('minute')) {
  242. $value .= '-'.$r('minute').$r('second');
  243. } elseif ($d('second')) {
  244. $value .= '--'.$r('second');
  245. }
  246. $value .= $r('timezone');
  247. // # 4.3.3
  248. // value-date-time = element date-time {
  249. // xsd:string { pattern = "(\d{8}|--\d{4}|---\d\d)T\d\d(\d\d(\d\d)?)?"
  250. // ~ "(Z|[+\-]\d\d(\d\d)?)?" }
  251. // }
  252. } elseif ($d('date') && $d('hour')) {
  253. if ($d('year') && $d('month') && $d('date')) {
  254. $value .= $r('year').$r('month').$r('date');
  255. } elseif (!$d('year') && $d('month') && $d('date')) {
  256. $value .= '--'.$r('month').$r('date');
  257. } elseif (!$d('year') && !$d('month') && $d('date')) {
  258. $value .= '---'.$r('date');
  259. }
  260. $value .= 'T'.$r('hour').$r('minute').$r('second').
  261. $r('timezone');
  262. }
  263. $writer->writeElement($valueType, $value);
  264. }
  265. /**
  266. * Sets a raw value coming from a mimedir (iCalendar/vCard) file.
  267. *
  268. * This has been 'unfolded', so only 1 line will be passed. Unescaping is
  269. * not yet done, but parameters are not included.
  270. *
  271. * @param string $val
  272. */
  273. public function setRawMimeDirValue($val)
  274. {
  275. $this->setValue($val);
  276. }
  277. /**
  278. * Returns a raw mime-dir representation of the value.
  279. *
  280. * @return string
  281. */
  282. public function getRawMimeDirValue()
  283. {
  284. return implode($this->delimiter, $this->getParts());
  285. }
  286. /**
  287. * Validates the node for correctness.
  288. *
  289. * The following options are supported:
  290. * Node::REPAIR - May attempt to automatically repair the problem.
  291. *
  292. * This method returns an array with detected problems.
  293. * Every element has the following properties:
  294. *
  295. * * level - problem level.
  296. * * message - A human-readable string describing the issue.
  297. * * node - A reference to the problematic node.
  298. *
  299. * The level means:
  300. * 1 - The issue was repaired (only happens if REPAIR was turned on)
  301. * 2 - An inconsequential issue
  302. * 3 - A severe issue.
  303. *
  304. * @param int $options
  305. *
  306. * @return array
  307. */
  308. public function validate($options = 0)
  309. {
  310. $messages = parent::validate($options);
  311. $value = $this->getValue();
  312. try {
  313. DateTimeParser::parseVCardDateTime($value);
  314. } catch (InvalidDataException $e) {
  315. $messages[] = [
  316. 'level' => 3,
  317. 'message' => 'The supplied value ('.$value.') is not a correct DATE-AND-OR-TIME property',
  318. 'node' => $this,
  319. ];
  320. }
  321. return $messages;
  322. }
  323. }