NetscapeBookmarkUtils.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. foreach ($linkDb as $link) {
  36. if ($link['private'] != 0 && $selection == 'public') {
  37. continue;
  38. }
  39. if ($link['private'] == 0 && $selection == 'private') {
  40. continue;
  41. }
  42. $date = $link['created'];
  43. $link['timestamp'] = $date->getTimestamp();
  44. $link['taglist'] = str_replace(' ', ',', $link['tags']);
  45. if (startsWith($link['url'], '?') && $prependNoteUrl) {
  46. $link['url'] = $indexUrl . $link['url'];
  47. }
  48. $bookmarkLinks[] = $link;
  49. }
  50. return $bookmarkLinks;
  51. }
  52. /**
  53. * Generates an import status summary
  54. *
  55. * @param string $filename name of the file to import
  56. * @param int $filesize size of the file to import
  57. * @param int $importCount how many links were imported
  58. * @param int $overwriteCount how many links were overwritten
  59. * @param int $skipCount how many links were skipped
  60. * @param int $duration how many seconds did the import take
  61. *
  62. * @return string Summary of the bookmark import status
  63. */
  64. private static function importStatus(
  65. $filename,
  66. $filesize,
  67. $importCount=0,
  68. $overwriteCount=0,
  69. $skipCount=0,
  70. $duration=0
  71. )
  72. {
  73. $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
  74. if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
  75. $status .= t('has an unknown file format. Nothing was imported.');
  76. } else {
  77. $status .= vsprintf(
  78. t('was successfully processed in %d seconds: %d links imported, %d links overwritten, %d links skipped.'),
  79. [$duration, $importCount, $overwriteCount, $skipCount]
  80. );
  81. }
  82. return $status;
  83. }
  84. /**
  85. * Imports Web bookmarks from an uploaded Netscape bookmark dump
  86. *
  87. * @param array $post Server $_POST parameters
  88. * @param array $files Server $_FILES parameters
  89. * @param LinkDB $linkDb Loaded LinkDB instance
  90. * @param ConfigManager $conf instance
  91. * @param History $history History instance
  92. *
  93. * @return string Summary of the bookmark import status
  94. */
  95. public static function import($post, $files, $linkDb, $conf, $history)
  96. {
  97. $start = time();
  98. $filename = $files['filetoupload']['name'];
  99. $filesize = $files['filetoupload']['size'];
  100. $data = file_get_contents($files['filetoupload']['tmp_name']);
  101. if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
  102. return self::importStatus($filename, $filesize);
  103. }
  104. // Overwrite existing links?
  105. $overwrite = ! empty($post['overwrite']);
  106. // Add tags to all imported links?
  107. if (empty($post['default_tags'])) {
  108. $defaultTags = array();
  109. } else {
  110. $defaultTags = preg_split(
  111. '/[\s,]+/',
  112. escape($post['default_tags'])
  113. );
  114. }
  115. // links are imported as public by default
  116. $defaultPrivacy = 0;
  117. $parser = new NetscapeBookmarkParser(
  118. true, // nested tag support
  119. $defaultTags, // additional user-specified tags
  120. strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
  121. $conf->get('resource.data_dir') // log path, will be overridden
  122. );
  123. $logger = new Logger(
  124. $conf->get('resource.data_dir'),
  125. ! $conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
  126. [
  127. 'prefix' => 'import.',
  128. 'extension' => 'log',
  129. ]
  130. );
  131. $parser->setLogger($logger);
  132. $bookmarks = $parser->parseString($data);
  133. $importCount = 0;
  134. $overwriteCount = 0;
  135. $skipCount = 0;
  136. foreach ($bookmarks as $bkm) {
  137. $private = $defaultPrivacy;
  138. if (empty($post['privacy']) || $post['privacy'] == 'default') {
  139. // use value from the imported file
  140. $private = $bkm['pub'] == '1' ? 0 : 1;
  141. } elseif ($post['privacy'] == 'private') {
  142. // all imported links are private
  143. $private = 1;
  144. } elseif ($post['privacy'] == 'public') {
  145. // all imported links are public
  146. $private = 0;
  147. }
  148. $newLink = array(
  149. 'title' => $bkm['title'],
  150. 'url' => $bkm['uri'],
  151. 'description' => $bkm['note'],
  152. 'private' => $private,
  153. 'tags' => $bkm['tags']
  154. );
  155. $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
  156. if ($existingLink !== false) {
  157. if ($overwrite === false) {
  158. // Do not overwrite an existing link
  159. $skipCount++;
  160. continue;
  161. }
  162. // Overwrite an existing link, keep its date
  163. $newLink['id'] = $existingLink['id'];
  164. $newLink['created'] = $existingLink['created'];
  165. $newLink['updated'] = new DateTime();
  166. $newLink['shorturl'] = $existingLink['shorturl'];
  167. $linkDb[$existingLink['id']] = $newLink;
  168. $importCount++;
  169. $overwriteCount++;
  170. continue;
  171. }
  172. // Add a new link - @ used for UNIX timestamps
  173. $newLinkDate = new DateTime('@'.strval($bkm['time']));
  174. $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
  175. $newLink['created'] = $newLinkDate;
  176. $newLink['id'] = $linkDb->getNextId();
  177. $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
  178. $linkDb[$newLink['id']] = $newLink;
  179. $importCount++;
  180. }
  181. $linkDb->save($conf->get('resource.page_cache'));
  182. $history->importLinks();
  183. $duration = time() - $start;
  184. return self::importStatus(
  185. $filename,
  186. $filesize,
  187. $importCount,
  188. $overwriteCount,
  189. $skipCount,
  190. $duration
  191. );
  192. }
  193. }