Cli.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. <?php
  2. namespace Sabre\VObject;
  3. use InvalidArgumentException;
  4. /**
  5. * This is the CLI interface for sabre-vobject.
  6. *
  7. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  8. * @author Evert Pot (http://evertpot.com/)
  9. * @license http://sabre.io/license/ Modified BSD License
  10. */
  11. class Cli
  12. {
  13. /**
  14. * No output.
  15. *
  16. * @var bool
  17. */
  18. protected $quiet = false;
  19. /**
  20. * Help display.
  21. *
  22. * @var bool
  23. */
  24. protected $showHelp = false;
  25. /**
  26. * Whether to spit out 'mimedir' or 'json' format.
  27. *
  28. * @var string
  29. */
  30. protected $format;
  31. /**
  32. * JSON pretty print.
  33. *
  34. * @var bool
  35. */
  36. protected $pretty;
  37. /**
  38. * Source file.
  39. *
  40. * @var string
  41. */
  42. protected $inputPath;
  43. /**
  44. * Destination file.
  45. *
  46. * @var string
  47. */
  48. protected $outputPath;
  49. /**
  50. * output stream.
  51. *
  52. * @var resource
  53. */
  54. protected $stdout;
  55. /**
  56. * stdin.
  57. *
  58. * @var resource
  59. */
  60. protected $stdin;
  61. /**
  62. * stderr.
  63. *
  64. * @var resource
  65. */
  66. protected $stderr;
  67. /**
  68. * Input format (one of json or mimedir).
  69. *
  70. * @var string
  71. */
  72. protected $inputFormat;
  73. /**
  74. * Makes the parser less strict.
  75. *
  76. * @var bool
  77. */
  78. protected $forgiving = false;
  79. /**
  80. * Main function.
  81. *
  82. * @return int
  83. */
  84. public function main(array $argv)
  85. {
  86. // @codeCoverageIgnoreStart
  87. // We cannot easily test this, so we'll skip it. Pretty basic anyway.
  88. if (!$this->stderr) {
  89. $this->stderr = fopen('php://stderr', 'w');
  90. }
  91. if (!$this->stdout) {
  92. $this->stdout = fopen('php://stdout', 'w');
  93. }
  94. if (!$this->stdin) {
  95. $this->stdin = fopen('php://stdin', 'r');
  96. }
  97. // @codeCoverageIgnoreEnd
  98. try {
  99. list($options, $positional) = $this->parseArguments($argv);
  100. if (isset($options['q'])) {
  101. $this->quiet = true;
  102. }
  103. $this->log($this->colorize('green', 'sabre/vobject ').$this->colorize('yellow', Version::VERSION));
  104. foreach ($options as $name => $value) {
  105. switch ($name) {
  106. case 'q':
  107. // Already handled earlier.
  108. break;
  109. case 'h':
  110. case 'help':
  111. $this->showHelp();
  112. return 0;
  113. break;
  114. case 'format':
  115. switch ($value) {
  116. // jcard/jcal documents
  117. case 'jcard':
  118. case 'jcal':
  119. // specific document versions
  120. case 'vcard21':
  121. case 'vcard30':
  122. case 'vcard40':
  123. case 'icalendar20':
  124. // specific formats
  125. case 'json':
  126. case 'mimedir':
  127. // icalendar/vcad
  128. case 'icalendar':
  129. case 'vcard':
  130. $this->format = $value;
  131. break;
  132. default:
  133. throw new InvalidArgumentException('Unknown format: '.$value);
  134. }
  135. break;
  136. case 'pretty':
  137. if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
  138. $this->pretty = true;
  139. }
  140. break;
  141. case 'forgiving':
  142. $this->forgiving = true;
  143. break;
  144. case 'inputformat':
  145. switch ($value) {
  146. // json formats
  147. case 'jcard':
  148. case 'jcal':
  149. case 'json':
  150. $this->inputFormat = 'json';
  151. break;
  152. // mimedir formats
  153. case 'mimedir':
  154. case 'icalendar':
  155. case 'vcard':
  156. case 'vcard21':
  157. case 'vcard30':
  158. case 'vcard40':
  159. case 'icalendar20':
  160. $this->inputFormat = 'mimedir';
  161. break;
  162. default:
  163. throw new InvalidArgumentException('Unknown format: '.$value);
  164. }
  165. break;
  166. default:
  167. throw new InvalidArgumentException('Unknown option: '.$name);
  168. }
  169. }
  170. if (0 === count($positional)) {
  171. $this->showHelp();
  172. return 1;
  173. }
  174. if (1 === count($positional)) {
  175. throw new InvalidArgumentException('Inputfile is a required argument');
  176. }
  177. if (count($positional) > 3) {
  178. throw new InvalidArgumentException('Too many arguments');
  179. }
  180. if (!in_array($positional[0], ['validate', 'repair', 'convert', 'color'])) {
  181. throw new InvalidArgumentException('Unknown command: '.$positional[0]);
  182. }
  183. } catch (InvalidArgumentException $e) {
  184. $this->showHelp();
  185. $this->log('Error: '.$e->getMessage(), 'red');
  186. return 1;
  187. }
  188. $command = $positional[0];
  189. $this->inputPath = $positional[1];
  190. $this->outputPath = isset($positional[2]) ? $positional[2] : '-';
  191. if ('-' !== $this->outputPath) {
  192. $this->stdout = fopen($this->outputPath, 'w');
  193. }
  194. if (!$this->inputFormat) {
  195. if ('.json' === substr($this->inputPath, -5)) {
  196. $this->inputFormat = 'json';
  197. } else {
  198. $this->inputFormat = 'mimedir';
  199. }
  200. }
  201. if (!$this->format) {
  202. if ('.json' === substr($this->outputPath, -5)) {
  203. $this->format = 'json';
  204. } else {
  205. $this->format = 'mimedir';
  206. }
  207. }
  208. $realCode = 0;
  209. try {
  210. while ($input = $this->readInput()) {
  211. $returnCode = $this->$command($input);
  212. if (0 !== $returnCode) {
  213. $realCode = $returnCode;
  214. }
  215. }
  216. } catch (EofException $e) {
  217. // end of file
  218. } catch (\Exception $e) {
  219. $this->log('Error: '.$e->getMessage(), 'red');
  220. return 2;
  221. }
  222. return $realCode;
  223. }
  224. /**
  225. * Shows the help message.
  226. */
  227. protected function showHelp()
  228. {
  229. $this->log('Usage:', 'yellow');
  230. $this->log(' vobject [options] command [arguments]');
  231. $this->log('');
  232. $this->log('Options:', 'yellow');
  233. $this->log($this->colorize('green', ' -q ')."Don't output anything.");
  234. $this->log($this->colorize('green', ' -help -h ').'Display this help message.');
  235. $this->log($this->colorize('green', ' --format ').'Convert to a specific format. Must be one of: vcard, vcard21,');
  236. $this->log($this->colorize('green', ' --forgiving ').'Makes the parser less strict.');
  237. $this->log(' vcard30, vcard40, icalendar20, jcal, jcard, json, mimedir.');
  238. $this->log($this->colorize('green', ' --inputformat ').'If the input format cannot be guessed from the extension, it');
  239. $this->log(' must be specified here.');
  240. // Only PHP 5.4 and up
  241. if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
  242. $this->log($this->colorize('green', ' --pretty ').'json pretty-print.');
  243. }
  244. $this->log('');
  245. $this->log('Commands:', 'yellow');
  246. $this->log($this->colorize('green', ' validate').' source_file Validates a file for correctness.');
  247. $this->log($this->colorize('green', ' repair').' source_file [output_file] Repairs a file.');
  248. $this->log($this->colorize('green', ' convert').' source_file [output_file] Converts a file.');
  249. $this->log($this->colorize('green', ' color').' source_file Colorize a file, useful for debugging.');
  250. $this->log(
  251. <<<HELP
  252. If source_file is set as '-', STDIN will be used.
  253. If output_file is omitted, STDOUT will be used.
  254. All other output is sent to STDERR.
  255. HELP
  256. );
  257. $this->log('Examples:', 'yellow');
  258. $this->log(' vobject convert contact.vcf contact.json');
  259. $this->log(' vobject convert --format=vcard40 old.vcf new.vcf');
  260. $this->log(' vobject convert --inputformat=json --format=mimedir - -');
  261. $this->log(' vobject color calendar.ics');
  262. $this->log('');
  263. $this->log('https://github.com/fruux/sabre-vobject', 'purple');
  264. }
  265. /**
  266. * Validates a VObject file.
  267. *
  268. * @return int
  269. */
  270. protected function validate(Component $vObj)
  271. {
  272. $returnCode = 0;
  273. switch ($vObj->name) {
  274. case 'VCALENDAR':
  275. $this->log('iCalendar: '.(string) $vObj->VERSION);
  276. break;
  277. case 'VCARD':
  278. $this->log('vCard: '.(string) $vObj->VERSION);
  279. break;
  280. }
  281. $warnings = $vObj->validate();
  282. if (!count($warnings)) {
  283. $this->log(' No warnings!');
  284. } else {
  285. $levels = [
  286. 1 => 'REPAIRED',
  287. 2 => 'WARNING',
  288. 3 => 'ERROR',
  289. ];
  290. $returnCode = 2;
  291. foreach ($warnings as $warn) {
  292. $extra = '';
  293. if ($warn['node'] instanceof Property) {
  294. $extra = ' (property: "'.$warn['node']->name.'")';
  295. }
  296. $this->log(' ['.$levels[$warn['level']].'] '.$warn['message'].$extra);
  297. }
  298. }
  299. return $returnCode;
  300. }
  301. /**
  302. * Repairs a VObject file.
  303. *
  304. * @return int
  305. */
  306. protected function repair(Component $vObj)
  307. {
  308. $returnCode = 0;
  309. switch ($vObj->name) {
  310. case 'VCALENDAR':
  311. $this->log('iCalendar: '.(string) $vObj->VERSION);
  312. break;
  313. case 'VCARD':
  314. $this->log('vCard: '.(string) $vObj->VERSION);
  315. break;
  316. }
  317. $warnings = $vObj->validate(Node::REPAIR);
  318. if (!count($warnings)) {
  319. $this->log(' No warnings!');
  320. } else {
  321. $levels = [
  322. 1 => 'REPAIRED',
  323. 2 => 'WARNING',
  324. 3 => 'ERROR',
  325. ];
  326. $returnCode = 2;
  327. foreach ($warnings as $warn) {
  328. $extra = '';
  329. if ($warn['node'] instanceof Property) {
  330. $extra = ' (property: "'.$warn['node']->name.'")';
  331. }
  332. $this->log(' ['.$levels[$warn['level']].'] '.$warn['message'].$extra);
  333. }
  334. }
  335. fwrite($this->stdout, $vObj->serialize());
  336. return $returnCode;
  337. }
  338. /**
  339. * Converts a vObject file to a new format.
  340. *
  341. * @param Component $vObj
  342. *
  343. * @return int
  344. */
  345. protected function convert($vObj)
  346. {
  347. $json = false;
  348. $convertVersion = null;
  349. $forceInput = null;
  350. switch ($this->format) {
  351. case 'json':
  352. $json = true;
  353. if ('VCARD' === $vObj->name) {
  354. $convertVersion = Document::VCARD40;
  355. }
  356. break;
  357. case 'jcard':
  358. $json = true;
  359. $forceInput = 'VCARD';
  360. $convertVersion = Document::VCARD40;
  361. break;
  362. case 'jcal':
  363. $json = true;
  364. $forceInput = 'VCALENDAR';
  365. break;
  366. case 'mimedir':
  367. case 'icalendar':
  368. case 'icalendar20':
  369. case 'vcard':
  370. break;
  371. case 'vcard21':
  372. $convertVersion = Document::VCARD21;
  373. break;
  374. case 'vcard30':
  375. $convertVersion = Document::VCARD30;
  376. break;
  377. case 'vcard40':
  378. $convertVersion = Document::VCARD40;
  379. break;
  380. }
  381. if ($forceInput && $vObj->name !== $forceInput) {
  382. throw new \Exception('You cannot convert a '.strtolower($vObj->name).' to '.$this->format);
  383. }
  384. if ($convertVersion) {
  385. $vObj = $vObj->convert($convertVersion);
  386. }
  387. if ($json) {
  388. $jsonOptions = 0;
  389. if ($this->pretty) {
  390. $jsonOptions = JSON_PRETTY_PRINT;
  391. }
  392. fwrite($this->stdout, json_encode($vObj->jsonSerialize(), $jsonOptions));
  393. } else {
  394. fwrite($this->stdout, $vObj->serialize());
  395. }
  396. return 0;
  397. }
  398. /**
  399. * Colorizes a file.
  400. *
  401. * @param Component $vObj
  402. */
  403. protected function color($vObj)
  404. {
  405. $this->serializeComponent($vObj);
  406. }
  407. /**
  408. * Returns an ansi color string for a color name.
  409. *
  410. * @param string $color
  411. *
  412. * @return string
  413. */
  414. protected function colorize($color, $str, $resetTo = 'default')
  415. {
  416. $colors = [
  417. 'cyan' => '1;36',
  418. 'red' => '1;31',
  419. 'yellow' => '1;33',
  420. 'blue' => '0;34',
  421. 'green' => '0;32',
  422. 'default' => '0',
  423. 'purple' => '0;35',
  424. ];
  425. return "\033[".$colors[$color].'m'.$str."\033[".$colors[$resetTo].'m';
  426. }
  427. /**
  428. * Writes out a string in specific color.
  429. *
  430. * @param string $color
  431. * @param string $str
  432. */
  433. protected function cWrite($color, $str)
  434. {
  435. fwrite($this->stdout, $this->colorize($color, $str));
  436. }
  437. protected function serializeComponent(Component $vObj)
  438. {
  439. $this->cWrite('cyan', 'BEGIN');
  440. $this->cWrite('red', ':');
  441. $this->cWrite('yellow', $vObj->name."\n");
  442. /**
  443. * Gives a component a 'score' for sorting purposes.
  444. *
  445. * This is solely used by the childrenSort method.
  446. *
  447. * A higher score means the item will be lower in the list.
  448. * To avoid score collisions, each "score category" has a reasonable
  449. * space to accommodate elements. The $key is added to the $score to
  450. * preserve the original relative order of elements.
  451. *
  452. * @param int $key
  453. * @param array $array
  454. *
  455. * @return int
  456. */
  457. $sortScore = function ($key, $array) {
  458. if ($array[$key] instanceof Component) {
  459. // We want to encode VTIMEZONE first, this is a personal
  460. // preference.
  461. if ('VTIMEZONE' === $array[$key]->name) {
  462. $score = 300000000;
  463. return $score + $key;
  464. } else {
  465. $score = 400000000;
  466. return $score + $key;
  467. }
  468. } else {
  469. // Properties get encoded first
  470. // VCARD version 4.0 wants the VERSION property to appear first
  471. if ($array[$key] instanceof Property) {
  472. if ('VERSION' === $array[$key]->name) {
  473. $score = 100000000;
  474. return $score + $key;
  475. } else {
  476. // All other properties
  477. $score = 200000000;
  478. return $score + $key;
  479. }
  480. }
  481. }
  482. };
  483. $children = $vObj->children();
  484. $tmp = $children;
  485. uksort(
  486. $children,
  487. function ($a, $b) use ($sortScore, $tmp) {
  488. $sA = $sortScore($a, $tmp);
  489. $sB = $sortScore($b, $tmp);
  490. return $sA - $sB;
  491. }
  492. );
  493. foreach ($children as $child) {
  494. if ($child instanceof Component) {
  495. $this->serializeComponent($child);
  496. } else {
  497. $this->serializeProperty($child);
  498. }
  499. }
  500. $this->cWrite('cyan', 'END');
  501. $this->cWrite('red', ':');
  502. $this->cWrite('yellow', $vObj->name."\n");
  503. }
  504. /**
  505. * Colorizes a property.
  506. */
  507. protected function serializeProperty(Property $property)
  508. {
  509. if ($property->group) {
  510. $this->cWrite('default', $property->group);
  511. $this->cWrite('red', '.');
  512. }
  513. $this->cWrite('yellow', $property->name);
  514. foreach ($property->parameters as $param) {
  515. $this->cWrite('red', ';');
  516. $this->cWrite('blue', $param->serialize());
  517. }
  518. $this->cWrite('red', ':');
  519. if ($property instanceof Property\Binary) {
  520. $this->cWrite('default', 'embedded binary stripped. ('.strlen($property->getValue()).' bytes)');
  521. } else {
  522. $parts = $property->getParts();
  523. $first1 = true;
  524. // Looping through property values
  525. foreach ($parts as $part) {
  526. if ($first1) {
  527. $first1 = false;
  528. } else {
  529. $this->cWrite('red', $property->delimiter);
  530. }
  531. $first2 = true;
  532. // Looping through property sub-values
  533. foreach ((array) $part as $subPart) {
  534. if ($first2) {
  535. $first2 = false;
  536. } else {
  537. // The sub-value delimiter is always comma
  538. $this->cWrite('red', ',');
  539. }
  540. $subPart = strtr(
  541. $subPart,
  542. [
  543. '\\' => $this->colorize('purple', '\\\\', 'green'),
  544. ';' => $this->colorize('purple', '\;', 'green'),
  545. ',' => $this->colorize('purple', '\,', 'green'),
  546. "\n" => $this->colorize('purple', "\\n\n\t", 'green'),
  547. "\r" => '',
  548. ]
  549. );
  550. $this->cWrite('green', $subPart);
  551. }
  552. }
  553. }
  554. $this->cWrite('default', "\n");
  555. }
  556. /**
  557. * Parses the list of arguments.
  558. */
  559. protected function parseArguments(array $argv)
  560. {
  561. $positional = [];
  562. $options = [];
  563. for ($ii = 0; $ii < count($argv); ++$ii) {
  564. // Skipping the first argument.
  565. if (0 === $ii) {
  566. continue;
  567. }
  568. $v = $argv[$ii];
  569. if ('--' === substr($v, 0, 2)) {
  570. // This is a long-form option.
  571. $optionName = substr($v, 2);
  572. $optionValue = true;
  573. if (strpos($optionName, '=')) {
  574. list($optionName, $optionValue) = explode('=', $optionName);
  575. }
  576. $options[$optionName] = $optionValue;
  577. } elseif ('-' === substr($v, 0, 1) && strlen($v) > 1) {
  578. // This is a short-form option.
  579. foreach (str_split(substr($v, 1)) as $option) {
  580. $options[$option] = true;
  581. }
  582. } else {
  583. $positional[] = $v;
  584. }
  585. }
  586. return [$options, $positional];
  587. }
  588. protected $parser;
  589. /**
  590. * Reads the input file.
  591. *
  592. * @return Component
  593. */
  594. protected function readInput()
  595. {
  596. if (!$this->parser) {
  597. if ('-' !== $this->inputPath) {
  598. $this->stdin = fopen($this->inputPath, 'r');
  599. }
  600. if ('mimedir' === $this->inputFormat) {
  601. $this->parser = new Parser\MimeDir($this->stdin, ($this->forgiving ? Reader::OPTION_FORGIVING : 0));
  602. } else {
  603. $this->parser = new Parser\Json($this->stdin, ($this->forgiving ? Reader::OPTION_FORGIVING : 0));
  604. }
  605. }
  606. return $this->parser->parse();
  607. }
  608. /**
  609. * Sends a message to STDERR.
  610. *
  611. * @param string $msg
  612. */
  613. protected function log($msg, $color = 'default')
  614. {
  615. if (!$this->quiet) {
  616. if ('default' !== $color) {
  617. $msg = $this->colorize($color, $msg);
  618. }
  619. fwrite($this->stderr, $msg."\n");
  620. }
  621. }
  622. }