MimeDir.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <?php
  2. namespace Sabre\VObject\Parser;
  3. use
  4. Sabre\VObject\ParseException,
  5. Sabre\VObject\EofException,
  6. Sabre\VObject\Component,
  7. Sabre\VObject\Property,
  8. Sabre\VObject\Component\VCalendar,
  9. Sabre\VObject\Component\VCard;
  10. /**
  11. * MimeDir parser.
  12. *
  13. * This class parses iCalendar 2.0 and vCard 2.1, 3.0 and 4.0 files. This
  14. * parser will return one of the following two objects from the parse method:
  15. *
  16. * Sabre\VObject\Component\VCalendar
  17. * Sabre\VObject\Component\VCard
  18. *
  19. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  20. * @author Evert Pot (http://evertpot.com/)
  21. * @license http://sabre.io/license/ Modified BSD License
  22. */
  23. class MimeDir extends Parser {
  24. /**
  25. * The input stream.
  26. *
  27. * @var resource
  28. */
  29. protected $input;
  30. /**
  31. * Root component
  32. *
  33. * @var Component
  34. */
  35. protected $root;
  36. /**
  37. * Parses an iCalendar or vCard file
  38. *
  39. * Pass a stream or a string. If null is parsed, the existing buffer is
  40. * used.
  41. *
  42. * @param string|resource|null $input
  43. * @param int|null $options
  44. * @return array
  45. */
  46. public function parse($input = null, $options = null) {
  47. $this->root = null;
  48. if (!is_null($input)) {
  49. $this->setInput($input);
  50. }
  51. if (!is_null($options)) $this->options = $options;
  52. $this->parseDocument();
  53. return $this->root;
  54. }
  55. /**
  56. * Sets the input buffer. Must be a string or stream.
  57. *
  58. * @param resource|string $input
  59. * @return void
  60. */
  61. public function setInput($input) {
  62. // Resetting the parser
  63. $this->lineIndex = 0;
  64. $this->startLine = 0;
  65. if (is_string($input)) {
  66. // Convering to a stream.
  67. $stream = fopen('php://temp', 'r+');
  68. fwrite($stream, $input);
  69. rewind($stream);
  70. $this->input = $stream;
  71. } elseif (is_resource($input)) {
  72. $this->input = $input;
  73. } else {
  74. throw new \InvalidArgumentException('This parser can only read from strings or streams.');
  75. }
  76. }
  77. /**
  78. * Parses an entire document.
  79. *
  80. * @return void
  81. */
  82. protected function parseDocument() {
  83. $line = $this->readLine();
  84. // BOM is ZERO WIDTH NO-BREAK SPACE (U+FEFF).
  85. // It's 0xEF 0xBB 0xBF in UTF-8 hex.
  86. if ( 3 <= strlen($line)
  87. && ord($line[0]) === 0xef
  88. && ord($line[1]) === 0xbb
  89. && ord($line[2]) === 0xbf) {
  90. $line = substr($line, 3);
  91. }
  92. switch(strtoupper($line)) {
  93. case 'BEGIN:VCALENDAR' :
  94. $class = isset(VCalendar::$componentMap['VCALENDAR'])
  95. ? VCalendar::$componentMap[$name]
  96. : 'Sabre\\VObject\\Component\\VCalendar';
  97. break;
  98. case 'BEGIN:VCARD' :
  99. $class = isset(VCard::$componentMap['VCARD'])
  100. ? VCard::$componentMap['VCARD']
  101. : 'Sabre\\VObject\\Component\\VCard';
  102. break;
  103. default :
  104. throw new ParseException('This parser only supports VCARD and VCALENDAR files');
  105. }
  106. $this->root = new $class(array(), false);
  107. while(true) {
  108. // Reading until we hit END:
  109. $line = $this->readLine();
  110. if (strtoupper(substr($line,0,4)) === 'END:') {
  111. break;
  112. }
  113. $result = $this->parseLine($line);
  114. if ($result) {
  115. $this->root->add($result);
  116. }
  117. }
  118. $name = strtoupper(substr($line, 4));
  119. if ($name!==$this->root->name) {
  120. throw new ParseException('Invalid MimeDir file. expected: "END:' . $this->root->name . '" got: "END:' . $name . '"');
  121. }
  122. }
  123. /**
  124. * Parses a line, and if it hits a component, it will also attempt to parse
  125. * the entire component
  126. *
  127. * @param string $line Unfolded line
  128. * @return Node
  129. */
  130. protected function parseLine($line) {
  131. // Start of a new component
  132. if (strtoupper(substr($line, 0, 6)) === 'BEGIN:') {
  133. $component = $this->root->createComponent(substr($line,6), array(), false);
  134. while(true) {
  135. // Reading until we hit END:
  136. $line = $this->readLine();
  137. if (strtoupper(substr($line,0,4)) === 'END:') {
  138. break;
  139. }
  140. $result = $this->parseLine($line);
  141. if ($result) {
  142. $component->add($result);
  143. }
  144. }
  145. $name = strtoupper(substr($line, 4));
  146. if ($name!==$component->name) {
  147. throw new ParseException('Invalid MimeDir file. expected: "END:' . $component->name . '" got: "END:' . $name . '"');
  148. }
  149. return $component;
  150. } else {
  151. // Property reader
  152. $property = $this->readProperty($line);
  153. if (!$property) {
  154. // Ignored line
  155. return false;
  156. }
  157. return $property;
  158. }
  159. }
  160. /**
  161. * We need to look ahead 1 line every time to see if we need to 'unfold'
  162. * the next line.
  163. *
  164. * If that was not the case, we store it here.
  165. *
  166. * @var null|string
  167. */
  168. protected $lineBuffer;
  169. /**
  170. * The real current line number.
  171. */
  172. protected $lineIndex = 0;
  173. /**
  174. * In the case of unfolded lines, this property holds the line number for
  175. * the start of the line.
  176. *
  177. * @var int
  178. */
  179. protected $startLine = 0;
  180. /**
  181. * Contains a 'raw' representation of the current line.
  182. *
  183. * @var string
  184. */
  185. protected $rawLine;
  186. /**
  187. * Reads a single line from the buffer.
  188. *
  189. * This method strips any newlines and also takes care of unfolding.
  190. *
  191. * @throws \Sabre\VObject\EofException
  192. * @return string
  193. */
  194. protected function readLine() {
  195. if (!is_null($this->lineBuffer)) {
  196. $rawLine = $this->lineBuffer;
  197. $this->lineBuffer = null;
  198. } else {
  199. do {
  200. $eof = feof($this->input);
  201. $rawLine = fgets($this->input);
  202. if ($eof || (feof($this->input) && $rawLine===false)) {
  203. throw new EofException('End of document reached prematurely');
  204. }
  205. if ($rawLine === false) {
  206. throw new ParseException('Error reading from input stream');
  207. }
  208. $rawLine = rtrim($rawLine, "\r\n");
  209. } while ($rawLine === ''); // Skipping empty lines
  210. $this->lineIndex++;
  211. }
  212. $line = $rawLine;
  213. $this->startLine = $this->lineIndex;
  214. // Looking ahead for folded lines.
  215. while (true) {
  216. $nextLine = rtrim(fgets($this->input), "\r\n");
  217. $this->lineIndex++;
  218. if (!$nextLine) {
  219. break;
  220. }
  221. if ($nextLine[0] === "\t" || $nextLine[0] === " ") {
  222. $line .= substr($nextLine, 1);
  223. $rawLine .= "\n " . substr($nextLine, 1);
  224. } else {
  225. $this->lineBuffer = $nextLine;
  226. break;
  227. }
  228. }
  229. $this->rawLine = $rawLine;
  230. return $line;
  231. }
  232. /**
  233. * Reads a property or component from a line.
  234. *
  235. * @return void
  236. */
  237. protected function readProperty($line) {
  238. if ($this->options & self::OPTION_FORGIVING) {
  239. $propNameToken = 'A-Z0-9\-\._\\/';
  240. } else {
  241. $propNameToken = 'A-Z0-9\-\.';
  242. }
  243. $paramNameToken = 'A-Z0-9\-';
  244. $safeChar = '^";:,';
  245. $qSafeChar = '^"';
  246. $regex = "/
  247. ^(?P<name> [$propNameToken]+ ) (?=[;:]) # property name
  248. |
  249. (?<=:)(?P<propValue> .+)$ # property value
  250. |
  251. ;(?P<paramName> [$paramNameToken]+) (?=[=;:]) # parameter name
  252. |
  253. (=|,)(?P<paramValue> # parameter value
  254. (?: [$safeChar]*) |
  255. \"(?: [$qSafeChar]+)\"
  256. ) (?=[;:,])
  257. /xi";
  258. //echo $regex, "\n"; die();
  259. preg_match_all($regex, $line, $matches, PREG_SET_ORDER);
  260. $property = array(
  261. 'name' => null,
  262. 'parameters' => array(),
  263. 'value' => null
  264. );
  265. $lastParam = null;
  266. /**
  267. * Looping through all the tokens.
  268. *
  269. * Note that we are looping through them in reverse order, because if a
  270. * sub-pattern matched, the subsequent named patterns will not show up
  271. * in the result.
  272. */
  273. foreach($matches as $match) {
  274. if (isset($match['paramValue'])) {
  275. if ($match['paramValue'] && $match['paramValue'][0] === '"') {
  276. $value = substr($match['paramValue'], 1, -1);
  277. } else {
  278. $value = $match['paramValue'];
  279. }
  280. $value = $this->unescapeParam($value);
  281. if (is_null($property['parameters'][$lastParam])) {
  282. $property['parameters'][$lastParam] = $value;
  283. } elseif (is_array($property['parameters'][$lastParam])) {
  284. $property['parameters'][$lastParam][] = $value;
  285. } else {
  286. $property['parameters'][$lastParam] = array(
  287. $property['parameters'][$lastParam],
  288. $value
  289. );
  290. }
  291. continue;
  292. }
  293. if (isset($match['paramName'])) {
  294. $lastParam = strtoupper($match['paramName']);
  295. if (!isset($property['parameters'][$lastParam])) {
  296. $property['parameters'][$lastParam] = null;
  297. }
  298. continue;
  299. }
  300. if (isset($match['propValue'])) {
  301. $property['value'] = $match['propValue'];
  302. continue;
  303. }
  304. if (isset($match['name']) && $match['name']) {
  305. $property['name'] = strtoupper($match['name']);
  306. continue;
  307. }
  308. // @codeCoverageIgnoreStart
  309. throw new \LogicException('This code should not be reachable');
  310. // @codeCoverageIgnoreEnd
  311. }
  312. if (is_null($property['value'])) {
  313. $property['value'] = '';
  314. }
  315. if (!$property['name']) {
  316. if ($this->options & self::OPTION_IGNORE_INVALID_LINES) {
  317. return false;
  318. }
  319. throw new ParseException('Invalid Mimedir file. Line starting at ' . $this->startLine . ' did not follow iCalendar/vCard conventions');
  320. }
  321. // vCard 2.1 states that parameters may appear without a name, and only
  322. // a value. We can deduce the value based on it's name.
  323. //
  324. // Our parser will get those as parameters without a value instead, so
  325. // we're filtering these parameters out first.
  326. $namedParameters = array();
  327. $namelessParameters = array();
  328. foreach($property['parameters'] as $name=>$value) {
  329. if (!is_null($value)) {
  330. $namedParameters[$name] = $value;
  331. } else {
  332. $namelessParameters[] = $name;
  333. }
  334. }
  335. $propObj = $this->root->createProperty($property['name'], null, $namedParameters);
  336. foreach($namelessParameters as $namelessParameter) {
  337. $propObj->add(null, $namelessParameter);
  338. }
  339. if (strtoupper($propObj['ENCODING']) === 'QUOTED-PRINTABLE') {
  340. $propObj->setQuotedPrintableValue($this->extractQuotedPrintableValue());
  341. } else {
  342. $propObj->setRawMimeDirValue($property['value']);
  343. }
  344. return $propObj;
  345. }
  346. /**
  347. * Unescapes a property value.
  348. *
  349. * vCard 2.1 says:
  350. * * Semi-colons must be escaped in some property values, specifically
  351. * ADR, ORG and N.
  352. * * Semi-colons must be escaped in parameter values, because semi-colons
  353. * are also use to separate values.
  354. * * No mention of escaping backslashes with another backslash.
  355. * * newlines are not escaped either, instead QUOTED-PRINTABLE is used to
  356. * span values over more than 1 line.
  357. *
  358. * vCard 3.0 says:
  359. * * (rfc2425) Backslashes, newlines (\n or \N) and comma's must be
  360. * escaped, all time time.
  361. * * Comma's are used for delimeters in multiple values
  362. * * (rfc2426) Adds to to this that the semi-colon MUST also be escaped,
  363. * as in some properties semi-colon is used for separators.
  364. * * Properties using semi-colons: N, ADR, GEO, ORG
  365. * * Both ADR and N's individual parts may be broken up further with a
  366. * comma.
  367. * * Properties using commas: NICKNAME, CATEGORIES
  368. *
  369. * vCard 4.0 (rfc6350) says:
  370. * * Commas must be escaped.
  371. * * Semi-colons may be escaped, an unescaped semi-colon _may_ be a
  372. * delimiter, depending on the property.
  373. * * Backslashes must be escaped
  374. * * Newlines must be escaped as either \N or \n.
  375. * * Some compound properties may contain multiple parts themselves, so a
  376. * comma within a semi-colon delimited property may also be unescaped
  377. * to denote multiple parts _within_ the compound property.
  378. * * Text-properties using semi-colons: N, ADR, ORG, CLIENTPIDMAP.
  379. * * Text-properties using commas: NICKNAME, RELATED, CATEGORIES, PID.
  380. *
  381. * Even though the spec says that commas must always be escaped, the
  382. * example for GEO in Section 6.5.2 seems to violate this.
  383. *
  384. * iCalendar 2.0 (rfc5545) says:
  385. * * Commas or semi-colons may be used as delimiters, depending on the
  386. * property.
  387. * * Commas, semi-colons, backslashes, newline (\N or \n) are always
  388. * escaped, unless they are delimiters.
  389. * * Colons shall not be escaped.
  390. * * Commas can be considered the 'default delimiter' and is described as
  391. * the delimiter in cases where the order of the multiple values is
  392. * insignificant.
  393. * * Semi-colons are described as the delimiter for 'structured values'.
  394. * They are specifically used in Semi-colons are used as a delimiter in
  395. * REQUEST-STATUS, RRULE, GEO and EXRULE. EXRULE is deprecated however.
  396. *
  397. * Now for the parameters
  398. *
  399. * If delimiter is not set (null) this method will just return a string.
  400. * If it's a comma or a semi-colon the string will be split on those
  401. * characters, and always return an array.
  402. *
  403. * @param string $input
  404. * @param string $delimiter
  405. * @return string|string[]
  406. */
  407. static public function unescapeValue($input, $delimiter = ';') {
  408. $regex = '# (?: (\\\\ (?: \\\\ | N | n | ; | , ) )';
  409. if ($delimiter) {
  410. $regex .= ' | (' . $delimiter . ')';
  411. }
  412. $regex .= ') #x';
  413. $matches = preg_split($regex, $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  414. $resultArray = array();
  415. $result = '';
  416. foreach($matches as $match) {
  417. switch ($match) {
  418. case '\\\\' :
  419. $result .='\\';
  420. break;
  421. case '\N' :
  422. case '\n' :
  423. $result .="\n";
  424. break;
  425. case '\;' :
  426. $result .=';';
  427. break;
  428. case '\,' :
  429. $result .=',';
  430. break;
  431. case $delimiter :
  432. $resultArray[] = $result;
  433. $result = '';
  434. break;
  435. default :
  436. $result .= $match;
  437. break;
  438. }
  439. }
  440. $resultArray[] = $result;
  441. return $delimiter ? $resultArray : $result;
  442. }
  443. /**
  444. * Unescapes a parameter value.
  445. *
  446. * vCard 2.1:
  447. * * Does not mention a mechanism for this. In addition, double quotes
  448. * are never used to wrap values.
  449. * * This means that parameters can simply not contain colons or
  450. * semi-colons.
  451. *
  452. * vCard 3.0 (rfc2425, rfc2426):
  453. * * Parameters _may_ be surrounded by double quotes.
  454. * * If this is not the case, semi-colon, colon and comma may simply not
  455. * occur (the comma used for multiple parameter values though).
  456. * * If it is surrounded by double-quotes, it may simply not contain
  457. * double-quotes.
  458. * * This means that a parameter can in no case encode double-quotes, or
  459. * newlines.
  460. *
  461. * vCard 4.0 (rfc6350)
  462. * * Behavior seems to be identical to vCard 3.0
  463. *
  464. * iCalendar 2.0 (rfc5545)
  465. * * Behavior seems to be identical to vCard 3.0
  466. *
  467. * Parameter escaping mechanism (rfc6868) :
  468. * * This rfc describes a new way to escape parameter values.
  469. * * New-line is encoded as ^n
  470. * * ^ is encoded as ^^.
  471. * * " is encoded as ^'
  472. *
  473. * @param string $input
  474. * @return void
  475. */
  476. private function unescapeParam($input) {
  477. return
  478. preg_replace_callback(
  479. '#(\^(\^|n|\'))#',
  480. function($matches) {
  481. switch($matches[2]) {
  482. case 'n' :
  483. return "\n";
  484. case '^' :
  485. return '^';
  486. case '\'' :
  487. return '"';
  488. // @codeCoverageIgnoreStart
  489. }
  490. // @codeCoverageIgnoreEnd
  491. },
  492. $input
  493. );
  494. }
  495. /**
  496. * Gets the full quoted printable value.
  497. *
  498. * We need a special method for this, because newlines have both a meaning
  499. * in vCards, and in QuotedPrintable.
  500. *
  501. * This method does not do any decoding.
  502. *
  503. * @return string
  504. */
  505. private function extractQuotedPrintableValue() {
  506. // We need to parse the raw line again to get the start of the value.
  507. //
  508. // We are basically looking for the first colon (:), but we need to
  509. // skip over the parameters first, as they may contain one.
  510. $regex = '/^
  511. (?: [^:])+ # Anything but a colon
  512. (?: "[^"]")* # A parameter in double quotes
  513. : # start of the value we really care about
  514. (.*)$
  515. /xs';
  516. preg_match($regex, $this->rawLine, $matches);
  517. $value = $matches[1];
  518. // Removing the first whitespace character from every line. Kind of
  519. // like unfolding, but we keep the newline.
  520. $value = str_replace("\n ", "\n", $value);
  521. // Microsoft products don't always correctly fold lines, they may be
  522. // missing a whitespace. So if 'forgiving' is turned on, we will take
  523. // those as well.
  524. if ($this->options & self::OPTION_FORGIVING) {
  525. while(substr($value,-1) === '=') {
  526. // Reading the line
  527. $this->readLine();
  528. // Grabbing the raw form
  529. $value.="\n" . $this->rawLine;
  530. }
  531. }
  532. return $value;
  533. }
  534. }