NetscapeBookmarkUtils.php 7.3 KB

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