NetscapeBookmarkUtils.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php
  2. use Psr\Log\LogLevel;
  3. use Shaarli\Config\ConfigManager;
  4. use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser;
  5. use Katzgrau\KLogger\Logger;
  6. /**
  7. * Utilities to import and export bookmarks using the Netscape format
  8. * TODO: Not static, use a container.
  9. */
  10. class NetscapeBookmarkUtils
  11. {
  12. /**
  13. * Filters links and adds Netscape-formatted fields
  14. *
  15. * Added fields:
  16. * - timestamp link addition date, using the Unix epoch format
  17. * - taglist comma-separated tag list
  18. *
  19. * @param LinkDB $linkDb Link datastore
  20. * @param string $selection Which links to export: (all|private|public)
  21. * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
  22. * @param string $indexUrl Absolute URL of the Shaarli index page
  23. *
  24. * @throws Exception Invalid export selection
  25. *
  26. * @return array The links to be exported, with additional fields
  27. */
  28. public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
  29. {
  30. // see tpl/export.html for possible values
  31. if (! in_array($selection, array('all', 'public', 'private'))) {
  32. throw new Exception(t('Invalid export selection:') .' "'.$selection.'"');
  33. }
  34. $bookmarkLinks = array();
  35. 7
  36. foreach ($linkDb as $link) {
  37. if ($link['private'] != 0 && $selection == 'public') {
  38. continue;
  39. }
  40. if ($link['private'] == 0 && $selection == 'private') {
  41. continue;
  42. }
  43. $date = $link['created'];
  44. $link['timestamp'] = $date->getTimestamp();
  45. $link['taglist'] = str_replace(' ', ',', $link['tags']);
  46. if (startsWith($link['url'], '?') && $prependNoteUrl) {
  47. $link['url'] = $indexUrl . $link['url'];
  48. }
  49. $bookmarkLinks[] = $link;
  50. }
  51. return $bookmarkLinks;
  52. }
  53. /**
  54. * Generates an import status summary
  55. *
  56. * @param string $filename name of the file to import
  57. * @param int $filesize size of the file to import
  58. * @param int $importCount how many links were imported
  59. * @param int $overwriteCount how many links were overwritten
  60. * @param int $skipCount how many links were skipped
  61. * @param int $duration how many seconds did the import take
  62. *
  63. * @return string Summary of the bookmark import status
  64. */
  65. private static function importStatus(
  66. $filename,
  67. $filesize,
  68. $importCount=0,
  69. $overwriteCount=0,
  70. $skipCount=0,
  71. $duration=0
  72. )
  73. {
  74. $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
  75. if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
  76. $status .= t('has an unknown file format. Nothing was imported.');
  77. } else {
  78. $status .= vsprintf(
  79. t('was successfully processed in %d seconds: %d links imported, %d links overwritten, %d links skipped.'),
  80. [$duration, $importCount, $overwriteCount, $skipCount]
  81. );
  82. }
  83. return $status;
  84. }
  85. /**
  86. * Imports Web bookmarks from an uploaded Netscape bookmark dump
  87. *
  88. * @param array $post Server $_POST parameters
  89. * @param array $files Server $_FILES parameters
  90. * @param LinkDB $linkDb Loaded LinkDB instance
  91. * @param ConfigManager $conf instance
  92. * @param History $history History instance
  93. *
  94. * @return string Summary of the bookmark import status
  95. */
  96. public static function import($post, $files, $linkDb, $conf, $history)
  97. {
  98. $start = time();
  99. $filename = $files['filetoupload']['name'];
  100. $filesize = $files['filetoupload']['size'];
  101. $data = file_get_contents($files['filetoupload']['tmp_name']);
  102. if (strpos($data, '<!DOCTYPE NETSCAPE-Bookmark-file-1>') === false) {
  103. return self::importStatus($filename, $filesize);
  104. }
  105. // Overwrite existing links?
  106. $overwrite = ! empty($post['overwrite']);
  107. // Add tags to all imported links?
  108. if (empty($post['default_tags'])) {
  109. $defaultTags = array();
  110. } else {
  111. $defaultTags = preg_split(
  112. '/[\s,]+/',
  113. escape($post['default_tags'])
  114. );
  115. }
  116. // links are imported as public by default
  117. $defaultPrivacy = 0;
  118. $parser = new NetscapeBookmarkParser(
  119. true, // nested tag support
  120. $defaultTags, // additional user-specified tags
  121. strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
  122. $conf->get('resource.data_dir') // log path, will be overridden
  123. );
  124. $logger = new Logger(
  125. $conf->get('resource.data_dir'),
  126. ! $conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
  127. [
  128. 'prefix' => 'import.',
  129. 'extension' => 'log',
  130. ]
  131. );
  132. $parser->setLogger($logger);
  133. $bookmarks = $parser->parseString($data);
  134. $importCount = 0;
  135. $overwriteCount = 0;
  136. $skipCount = 0;
  137. foreach ($bookmarks as $bkm) {
  138. $private = $defaultPrivacy;
  139. if (empty($post['privacy']) || $post['privacy'] == 'default') {
  140. // use value from the imported file
  141. $private = $bkm['pub'] == '1' ? 0 : 1;
  142. } else if ($post['privacy'] == 'private') {
  143. // all imported links are private
  144. $private = 1;
  145. } else if ($post['privacy'] == 'public') {
  146. // all imported links are public
  147. $private = 0;
  148. }
  149. $newLink = array(
  150. 'title' => $bkm['title'],
  151. 'url' => $bkm['uri'],
  152. 'description' => $bkm['note'],
  153. 'private' => $private,
  154. 'tags' => $bkm['tags']
  155. );
  156. $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
  157. if ($existingLink !== false) {
  158. if ($overwrite === false) {
  159. // Do not overwrite an existing link
  160. $skipCount++;
  161. continue;
  162. }
  163. // Overwrite an existing link, keep its date
  164. $newLink['id'] = $existingLink['id'];
  165. $newLink['created'] = $existingLink['created'];
  166. $newLink['updated'] = new DateTime();
  167. $newLink['shorturl'] = $existingLink['shorturl'];
  168. $linkDb[$existingLink['id']] = $newLink;
  169. $importCount++;
  170. $overwriteCount++;
  171. continue;
  172. }
  173. // Add a new link - @ used for UNIX timestamps
  174. $newLinkDate = new DateTime('@'.strval($bkm['time']));
  175. $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
  176. $newLink['created'] = $newLinkDate;
  177. $newLink['id'] = $linkDb->getNextId();
  178. $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
  179. $linkDb[$newLink['id']] = $newLink;
  180. $importCount++;
  181. }
  182. $linkDb->save($conf->get('resource.page_cache'));
  183. $history->importLinks();
  184. $duration = time() - $start;
  185. return self::importStatus(
  186. $filename,
  187. $filesize,
  188. $importCount,
  189. $overwriteCount,
  190. $skipCount,
  191. $duration
  192. );
  193. }
  194. }