Property.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. <?php
  2. namespace Sabre\VObject;
  3. use Sabre\Xml;
  4. /**
  5. * Property.
  6. *
  7. * A property is always in a KEY:VALUE structure, and may optionally contain
  8. * parameters.
  9. *
  10. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  11. * @author Evert Pot (http://evertpot.com/)
  12. * @license http://sabre.io/license/ Modified BSD License
  13. */
  14. abstract class Property extends Node
  15. {
  16. /**
  17. * Property name.
  18. *
  19. * This will contain a string such as DTSTART, SUMMARY, FN.
  20. *
  21. * @var string
  22. */
  23. public $name;
  24. /**
  25. * Property group.
  26. *
  27. * This is only used in vcards
  28. *
  29. * @var string|null
  30. */
  31. public $group;
  32. /**
  33. * List of parameters.
  34. *
  35. * @var array
  36. */
  37. public $parameters = [];
  38. /**
  39. * Current value.
  40. *
  41. * @var mixed
  42. */
  43. protected $value;
  44. /**
  45. * In case this is a multi-value property. This string will be used as a
  46. * delimiter.
  47. *
  48. * @var string
  49. */
  50. public $delimiter = ';';
  51. /**
  52. * The line number in the original iCalendar / vCard file
  53. * that corresponds with the current node
  54. * if the node was read from a file.
  55. */
  56. public $lineIndex;
  57. /**
  58. * The line string from the original iCalendar / vCard file
  59. * that corresponds with the current node
  60. * if the node was read from a file.
  61. */
  62. public $lineString;
  63. /**
  64. * Creates the generic property.
  65. *
  66. * Parameters must be specified in key=>value syntax.
  67. *
  68. * @param Component $root The root document
  69. * @param string $name
  70. * @param string|array|null $value
  71. * @param array $parameters List of parameters
  72. * @param string $group The vcard property group
  73. */
  74. public function __construct(Component $root, $name, $value = null, array $parameters = [], $group = null, ?int $lineIndex = null, ?string $lineString = null)
  75. {
  76. $this->name = $name;
  77. $this->group = $group;
  78. $this->root = $root;
  79. foreach ($parameters as $k => $v) {
  80. $this->add($k, $v);
  81. }
  82. if (!is_null($value)) {
  83. $this->setValue($value);
  84. }
  85. if (!is_null($lineIndex)) {
  86. $this->lineIndex = $lineIndex;
  87. }
  88. if (!is_null($lineString)) {
  89. $this->lineString = $lineString;
  90. }
  91. }
  92. /**
  93. * Updates the current value.
  94. *
  95. * This may be either a single, or multiple strings in an array.
  96. *
  97. * @param string|array $value
  98. */
  99. public function setValue($value)
  100. {
  101. $this->value = $value;
  102. }
  103. /**
  104. * Returns the current value.
  105. *
  106. * This method will always return a singular value. If this was a
  107. * multi-value object, some decision will be made first on how to represent
  108. * it as a string.
  109. *
  110. * To get the correct multi-value version, use getParts.
  111. *
  112. * @return string
  113. */
  114. public function getValue()
  115. {
  116. if (is_array($this->value)) {
  117. if (0 == count($this->value)) {
  118. return;
  119. } elseif (1 === count($this->value)) {
  120. return $this->value[0];
  121. } else {
  122. return $this->getRawMimeDirValue();
  123. }
  124. } else {
  125. return $this->value;
  126. }
  127. }
  128. /**
  129. * Sets a multi-valued property.
  130. */
  131. public function setParts(array $parts)
  132. {
  133. $this->value = $parts;
  134. }
  135. /**
  136. * Returns a multi-valued property.
  137. *
  138. * This method always returns an array, if there was only a single value,
  139. * it will still be wrapped in an array.
  140. *
  141. * @return array
  142. */
  143. public function getParts()
  144. {
  145. if (is_null($this->value)) {
  146. return [];
  147. } elseif (is_array($this->value)) {
  148. return $this->value;
  149. } else {
  150. return [$this->value];
  151. }
  152. }
  153. /**
  154. * Adds a new parameter.
  155. *
  156. * If a parameter with same name already existed, the values will be
  157. * combined.
  158. * If nameless parameter is added, we try to guess its name.
  159. *
  160. * @param string $name
  161. * @param string|array|null $value
  162. */
  163. public function add($name, $value = null)
  164. {
  165. $noName = false;
  166. if (null === $name) {
  167. $name = Parameter::guessParameterNameByValue($value);
  168. $noName = true;
  169. }
  170. if (isset($this->parameters[strtoupper($name)])) {
  171. $this->parameters[strtoupper($name)]->addValue($value);
  172. } else {
  173. $param = new Parameter($this->root, $name, $value);
  174. $param->noName = $noName;
  175. $this->parameters[$param->name] = $param;
  176. }
  177. }
  178. /**
  179. * Returns an iterable list of children.
  180. *
  181. * @return array
  182. */
  183. public function parameters()
  184. {
  185. return $this->parameters;
  186. }
  187. /**
  188. * Returns the type of value.
  189. *
  190. * This corresponds to the VALUE= parameter. Every property also has a
  191. * 'default' valueType.
  192. *
  193. * @return string
  194. */
  195. abstract public function getValueType();
  196. /**
  197. * Sets a raw value coming from a mimedir (iCalendar/vCard) file.
  198. *
  199. * This has been 'unfolded', so only 1 line will be passed. Unescaping is
  200. * not yet done, but parameters are not included.
  201. *
  202. * @param string $val
  203. */
  204. abstract public function setRawMimeDirValue($val);
  205. /**
  206. * Returns a raw mime-dir representation of the value.
  207. *
  208. * @return string
  209. */
  210. abstract public function getRawMimeDirValue();
  211. /**
  212. * Turns the object back into a serialized blob.
  213. *
  214. * @return string
  215. */
  216. public function serialize()
  217. {
  218. $str = $this->name;
  219. if ($this->group) {
  220. $str = $this->group.'.'.$this->name;
  221. }
  222. foreach ($this->parameters() as $param) {
  223. $str .= ';'.$param->serialize();
  224. }
  225. $str .= ':'.$this->getRawMimeDirValue();
  226. $str = \preg_replace(
  227. '/(
  228. (?:^.)? # 1 additional byte in first line because of missing single space (see next line)
  229. .{1,74} # max 75 bytes per line (1 byte is used for a single space added after every CRLF)
  230. (?![\x80-\xbf]) # prevent splitting multibyte characters
  231. )/x',
  232. "$1\r\n ",
  233. $str
  234. );
  235. // remove single space after last CRLF
  236. return \substr($str, 0, -1);
  237. }
  238. /**
  239. * Returns the value, in the format it should be encoded for JSON.
  240. *
  241. * This method must always return an array.
  242. *
  243. * @return array
  244. */
  245. public function getJsonValue()
  246. {
  247. return $this->getParts();
  248. }
  249. /**
  250. * Sets the JSON value, as it would appear in a jCard or jCal object.
  251. *
  252. * The value must always be an array.
  253. */
  254. public function setJsonValue(array $value)
  255. {
  256. if (1 === count($value)) {
  257. $this->setValue(reset($value));
  258. } else {
  259. $this->setValue($value);
  260. }
  261. }
  262. /**
  263. * This method returns an array, with the representation as it should be
  264. * encoded in JSON. This is used to create jCard or jCal documents.
  265. *
  266. * @return array
  267. */
  268. #[\ReturnTypeWillChange]
  269. public function jsonSerialize()
  270. {
  271. $parameters = [];
  272. foreach ($this->parameters as $parameter) {
  273. if ('VALUE' === $parameter->name) {
  274. continue;
  275. }
  276. $parameters[strtolower($parameter->name)] = $parameter->jsonSerialize();
  277. }
  278. // In jCard, we need to encode the property-group as a separate 'group'
  279. // parameter.
  280. if ($this->group) {
  281. $parameters['group'] = $this->group;
  282. }
  283. return array_merge(
  284. [
  285. strtolower($this->name),
  286. (object) $parameters,
  287. strtolower($this->getValueType()),
  288. ],
  289. $this->getJsonValue()
  290. );
  291. }
  292. /**
  293. * Hydrate data from a XML subtree, as it would appear in a xCard or xCal
  294. * object.
  295. */
  296. public function setXmlValue(array $value)
  297. {
  298. $this->setJsonValue($value);
  299. }
  300. /**
  301. * This method serializes the data into XML. This is used to create xCard or
  302. * xCal documents.
  303. *
  304. * @param Xml\Writer $writer XML writer
  305. */
  306. public function xmlSerialize(Xml\Writer $writer): void
  307. {
  308. $parameters = [];
  309. foreach ($this->parameters as $parameter) {
  310. if ('VALUE' === $parameter->name) {
  311. continue;
  312. }
  313. $parameters[] = $parameter;
  314. }
  315. $writer->startElement(strtolower($this->name));
  316. if (!empty($parameters)) {
  317. $writer->startElement('parameters');
  318. foreach ($parameters as $parameter) {
  319. $writer->startElement(strtolower($parameter->name));
  320. $writer->write($parameter);
  321. $writer->endElement();
  322. }
  323. $writer->endElement();
  324. }
  325. $this->xmlSerializeValue($writer);
  326. $writer->endElement();
  327. }
  328. /**
  329. * This method serializes only the value of a property. This is used to
  330. * create xCard or xCal documents.
  331. *
  332. * @param Xml\Writer $writer XML writer
  333. */
  334. protected function xmlSerializeValue(Xml\Writer $writer)
  335. {
  336. $valueType = strtolower($this->getValueType());
  337. foreach ($this->getJsonValue() as $values) {
  338. foreach ((array) $values as $value) {
  339. $writer->writeElement($valueType, $value);
  340. }
  341. }
  342. }
  343. /**
  344. * Called when this object is being cast to a string.
  345. *
  346. * If the property only had a single value, you will get just that. In the
  347. * case the property had multiple values, the contents will be escaped and
  348. * combined with ,.
  349. *
  350. * @return string
  351. */
  352. public function __toString()
  353. {
  354. return (string) $this->getValue();
  355. }
  356. /* ArrayAccess interface {{{ */
  357. /**
  358. * Checks if an array element exists.
  359. *
  360. * @param mixed $name
  361. *
  362. * @return bool
  363. */
  364. #[\ReturnTypeWillChange]
  365. public function offsetExists($name)
  366. {
  367. if (is_int($name)) {
  368. return parent::offsetExists($name);
  369. }
  370. $name = strtoupper($name);
  371. foreach ($this->parameters as $parameter) {
  372. if ($parameter->name == $name) {
  373. return true;
  374. }
  375. }
  376. return false;
  377. }
  378. /**
  379. * Returns a parameter.
  380. *
  381. * If the parameter does not exist, null is returned.
  382. *
  383. * @param string $name
  384. *
  385. * @return Node
  386. */
  387. #[\ReturnTypeWillChange]
  388. public function offsetGet($name)
  389. {
  390. if (is_int($name)) {
  391. return parent::offsetGet($name);
  392. }
  393. $name = strtoupper($name);
  394. if (!isset($this->parameters[$name])) {
  395. return;
  396. }
  397. return $this->parameters[$name];
  398. }
  399. /**
  400. * Creates a new parameter.
  401. *
  402. * @param string $name
  403. * @param mixed $value
  404. *
  405. * @return void
  406. */
  407. #[\ReturnTypeWillChange]
  408. public function offsetSet($name, $value)
  409. {
  410. if (is_int($name)) {
  411. parent::offsetSet($name, $value);
  412. // @codeCoverageIgnoreStart
  413. // This will never be reached, because an exception is always
  414. // thrown.
  415. return;
  416. // @codeCoverageIgnoreEnd
  417. }
  418. $param = new Parameter($this->root, $name, $value);
  419. $this->parameters[$param->name] = $param;
  420. }
  421. /**
  422. * Removes one or more parameters with the specified name.
  423. *
  424. * @param string $name
  425. *
  426. * @return void
  427. */
  428. #[\ReturnTypeWillChange]
  429. public function offsetUnset($name)
  430. {
  431. if (is_int($name)) {
  432. parent::offsetUnset($name);
  433. // @codeCoverageIgnoreStart
  434. // This will never be reached, because an exception is always
  435. // thrown.
  436. return;
  437. // @codeCoverageIgnoreEnd
  438. }
  439. unset($this->parameters[strtoupper($name)]);
  440. }
  441. /* }}} */
  442. /**
  443. * This method is automatically called when the object is cloned.
  444. * Specifically, this will ensure all child elements are also cloned.
  445. */
  446. public function __clone()
  447. {
  448. foreach ($this->parameters as $key => $child) {
  449. $this->parameters[$key] = clone $child;
  450. $this->parameters[$key]->parent = $this;
  451. }
  452. }
  453. /**
  454. * Validates the node for correctness.
  455. *
  456. * The following options are supported:
  457. * - Node::REPAIR - If something is broken, and automatic repair may
  458. * be attempted.
  459. *
  460. * An array is returned with warnings.
  461. *
  462. * Every item in the array has the following properties:
  463. * * level - (number between 1 and 3 with severity information)
  464. * * message - (human readable message)
  465. * * node - (reference to the offending node)
  466. *
  467. * @param int $options
  468. *
  469. * @return array
  470. */
  471. public function validate($options = 0)
  472. {
  473. $warnings = [];
  474. // Checking if our value is UTF-8
  475. if (!StringUtil::isUTF8($this->getRawMimeDirValue())) {
  476. $oldValue = $this->getRawMimeDirValue();
  477. $level = 3;
  478. if ($options & self::REPAIR) {
  479. $newValue = StringUtil::convertToUTF8($oldValue);
  480. if (true || StringUtil::isUTF8($newValue)) {
  481. $this->setRawMimeDirValue($newValue);
  482. $level = 1;
  483. }
  484. }
  485. if (preg_match('%([\x00-\x08\x0B-\x0C\x0E-\x1F\x7F])%', $oldValue, $matches)) {
  486. $message = 'Property contained a control character (0x'.bin2hex($matches[1]).')';
  487. } else {
  488. $message = 'Property is not valid UTF-8! '.$oldValue;
  489. }
  490. $warnings[] = [
  491. 'level' => $level,
  492. 'message' => $message,
  493. 'node' => $this,
  494. ];
  495. }
  496. // Checking if the propertyname does not contain any invalid bytes.
  497. if (!preg_match('/^([A-Z0-9-]+)$/', $this->name)) {
  498. $warnings[] = [
  499. 'level' => $options & self::REPAIR ? 1 : 3,
  500. 'message' => 'The propertyname: '.$this->name.' contains invalid characters. Only A-Z, 0-9 and - are allowed',
  501. 'node' => $this,
  502. ];
  503. if ($options & self::REPAIR) {
  504. // Uppercasing and converting underscores to dashes.
  505. $this->name = strtoupper(
  506. str_replace('_', '-', $this->name)
  507. );
  508. // Removing every other invalid character
  509. $this->name = preg_replace('/([^A-Z0-9-])/u', '', $this->name);
  510. }
  511. }
  512. if ($encoding = $this->offsetGet('ENCODING')) {
  513. if (Document::VCARD40 === $this->root->getDocumentType()) {
  514. $warnings[] = [
  515. 'level' => 3,
  516. 'message' => 'ENCODING parameter is not valid in vCard 4.',
  517. 'node' => $this,
  518. ];
  519. } else {
  520. $encoding = (string) $encoding;
  521. $allowedEncoding = [];
  522. switch ($this->root->getDocumentType()) {
  523. case Document::ICALENDAR20:
  524. $allowedEncoding = ['8BIT', 'BASE64'];
  525. break;
  526. case Document::VCARD21:
  527. $allowedEncoding = ['QUOTED-PRINTABLE', 'BASE64', '8BIT'];
  528. break;
  529. case Document::VCARD30:
  530. $allowedEncoding = ['B'];
  531. //Repair vCard30 that use BASE64 encoding
  532. if ($options & self::REPAIR) {
  533. if ('BASE64' === strtoupper($encoding)) {
  534. $encoding = 'B';
  535. $this['ENCODING'] = $encoding;
  536. $warnings[] = [
  537. 'level' => 1,
  538. 'message' => 'ENCODING=BASE64 has been transformed to ENCODING=B.',
  539. 'node' => $this,
  540. ];
  541. }
  542. }
  543. break;
  544. }
  545. if ($allowedEncoding && !in_array(strtoupper($encoding), $allowedEncoding)) {
  546. $warnings[] = [
  547. 'level' => 3,
  548. 'message' => 'ENCODING='.strtoupper($encoding).' is not valid for this document type.',
  549. 'node' => $this,
  550. ];
  551. }
  552. }
  553. }
  554. // Validating inner parameters
  555. foreach ($this->parameters as $param) {
  556. $warnings = array_merge($warnings, $param->validate($options));
  557. }
  558. return $warnings;
  559. }
  560. /**
  561. * Call this method on a document if you're done using it.
  562. *
  563. * It's intended to remove all circular references, so PHP can easily clean
  564. * it up.
  565. */
  566. public function destroy()
  567. {
  568. parent::destroy();
  569. foreach ($this->parameters as $param) {
  570. $param->destroy();
  571. }
  572. $this->parameters = [];
  573. }
  574. }