Cli.php 21 KB

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