3 namespace Shaarli\Netscape
;
8 use Katzgrau\KLogger\Logger
;
9 use Psr\Http\Message\UploadedFileInterface
;
11 use Shaarli\Bookmark\Bookmark
;
12 use Shaarli\Bookmark\BookmarkServiceInterface
;
13 use Shaarli\Config\ConfigManager
;
14 use Shaarli\Formatter\BookmarkFormatter
;
16 use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser
;
19 * Utilities to import and export bookmarks using the Netscape format
21 class NetscapeBookmarkUtils
23 /** @var BookmarkServiceInterface */
24 protected $bookmarkService;
26 /** @var ConfigManager */
32 public function __construct(BookmarkServiceInterface
$bookmarkService, ConfigManager
$conf, History
$history)
34 $this->bookmarkService
= $bookmarkService;
36 $this->history
= $history;
40 * Filters bookmarks and adds Netscape-formatted fields
43 * - timestamp link addition date, using the Unix epoch format
44 * - taglist comma-separated tag list
46 * @param BookmarkFormatter $formatter instance
47 * @param string $selection Which bookmarks to export: (all|private|public)
48 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
49 * @param string $indexUrl Absolute URL of the Shaarli index page
51 * @return array The bookmarks to be exported, with additional fields
53 * @throws Exception Invalid export selection
55 public function filterAndFormat(
61 // see tpl/export.html for possible values
62 if (!in_array($selection, array('all', 'public', 'private'))) {
63 throw new Exception(t('Invalid export selection:') . ' "' . $selection . '"');
66 $bookmarkLinks = array();
67 foreach ($this->bookmarkService
->search([], $selection) as $bookmark) {
68 $link = $formatter->format($bookmark);
69 $link['taglist'] = implode(',', $bookmark->getTags());
70 if ($bookmark->isNote() && $prependNoteUrl) {
71 $link['url'] = rtrim($indexUrl, '/') . '/' . ltrim($link['url'], '/');
74 $bookmarkLinks[] = $link;
77 return $bookmarkLinks;
81 * Imports Web bookmarks from an uploaded Netscape bookmark dump
83 * @param array $post Server $_POST parameters
84 * @param UploadedFileInterface $file File in PSR-7 object format
86 * @return string Summary of the bookmark import status
88 public function import($post, UploadedFileInterface
$file)
91 $filename = $file->getClientFilename();
92 $filesize = $file->getSize();
93 $data = (string) $file->getStream();
95 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
96 return $this->importStatus($filename, $filesize);
99 // Overwrite existing bookmarks?
100 $overwrite = !empty($post['overwrite']);
102 // Add tags to all imported bookmarks?
103 if (empty($post['default_tags'])) {
104 $defaultTags = array();
106 $defaultTags = preg_split(
108 escape($post['default_tags'])
112 // bookmarks are imported as public by default
115 $parser = new NetscapeBookmarkParser(
116 true, // nested tag support
117 $defaultTags, // additional user-specified tags
118 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
119 $this->conf
->get('resource.data_dir') // log path, will be overridden
121 $logger = new Logger(
122 $this->conf
->get('resource.data_dir'),
123 !$this->conf
->get('dev.debug') ? LogLevel
::INFO
: LogLevel
::DEBUG
,
125 'prefix' => 'import.',
126 'extension' => 'log',
129 $parser->setLogger($logger);
130 $bookmarks = $parser->parseString($data);
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 bookmarks are private
144 } elseif ($post['privacy'] == 'public') {
145 // all imported bookmarks are public
149 $link = $this->bookmarkService
->findByUrl($bkm['uri']);
150 $existingLink = $link !== null;
151 if (! $existingLink) {
152 $link = new Bookmark();
155 if ($existingLink !== false) {
156 if ($overwrite === false) {
157 // Do not overwrite an existing link
162 $link->setUpdated(new DateTime());
165 $newLinkDate = new DateTime('@' . strval($bkm['time']));
166 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
167 $link->setCreated($newLinkDate);
170 $link->setTitle($bkm['title']);
171 $link->setUrl($bkm['uri'], $this->conf
->get('security.allowed_protocols'));
172 $link->setDescription($bkm['note']);
173 $link->setPrivate($private);
174 $link->setTagsString($bkm['tags']);
176 $this->bookmarkService
->addOrSet($link, false);
180 $this->bookmarkService
->save();
181 $this->history
->importLinks();
183 $duration = time() - $start;
185 return $this->importStatus(
196 * Generates an import status summary
198 * @param string $filename name of the file to import
199 * @param int $filesize size of the file to import
200 * @param int $importCount how many bookmarks were imported
201 * @param int $overwriteCount how many bookmarks were overwritten
202 * @param int $skipCount how many bookmarks were skipped
203 * @param int $duration how many seconds did the import take
205 * @return string Summary of the bookmark import status
207 protected function importStatus(
215 $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
216 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
217 $status .= t('has an unknown file format. Nothing was imported.');
221 'was successfully processed in %d seconds: '
222 . '%d bookmarks imported, %d bookmarks overwritten, %d bookmarks skipped.'
224 [$duration, $importCount, $overwriteCount, $skipCount]