NetscapeBookmarkUtils.php 7.5 KB

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