3 namespace Shaarli\Netscape
;
8 use Katzgrau\KLogger\Logger
;
10 use Shaarli\Bookmark\Bookmark
;
11 use Shaarli\Bookmark\BookmarkServiceInterface
;
12 use Shaarli\Config\ConfigManager
;
13 use Shaarli\Formatter\BookmarkFormatter
;
15 use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser
;
18 * Utilities to import and export bookmarks using the Netscape format
20 class NetscapeBookmarkUtils
22 /** @var BookmarkServiceInterface */
23 protected $bookmarkService;
25 /** @var ConfigManager */
31 public function __construct(BookmarkServiceInterface
$bookmarkService, ConfigManager
$conf, History
$history)
33 $this->bookmarkService
= $bookmarkService;
35 $this->history
= $history;
39 * Filters bookmarks and adds Netscape-formatted fields
42 * - timestamp link addition date, using the Unix epoch format
43 * - taglist comma-separated tag list
45 * @param BookmarkFormatter $formatter instance
46 * @param string $selection Which bookmarks to export: (all|private|public)
47 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
48 * @param string $indexUrl Absolute URL of the Shaarli index page
50 * @return array The bookmarks to be exported, with additional fields
52 * @throws Exception Invalid export selection
54 public function filterAndFormat(
60 // see tpl/export.html for possible values
61 if (!in_array($selection, array('all', 'public', 'private'))) {
62 throw new Exception(t('Invalid export selection:') . ' "' . $selection . '"');
65 $bookmarkLinks = array();
66 foreach ($this->bookmarkService
->search([], $selection) as $bookmark) {
67 $link = $formatter->format($bookmark);
68 $link['taglist'] = implode(',', $bookmark->getTags());
69 if ($bookmark->isNote() && $prependNoteUrl) {
70 $link['url'] = $indexUrl . $link['url'];
73 $bookmarkLinks[] = $link;
76 return $bookmarkLinks;
80 * Imports Web bookmarks from an uploaded Netscape bookmark dump
82 * @param array $post Server $_POST parameters
83 * @param array $files Server $_FILES parameters
85 * @return string Summary of the bookmark import status
87 public function import($post, $files)
90 $filename = $files['filetoupload']['name'];
91 $filesize = $files['filetoupload']['size'];
92 $data = file_get_contents($files['filetoupload']['tmp_name']);
94 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
95 return self
::importStatus($filename, $filesize);
98 // Overwrite existing bookmarks?
99 $overwrite = !empty($post['overwrite']);
101 // Add tags to all imported bookmarks?
102 if (empty($post['default_tags'])) {
103 $defaultTags = array();
105 $defaultTags = preg_split(
107 escape($post['default_tags'])
111 // bookmarks are imported as public by default
114 $parser = new NetscapeBookmarkParser(
115 true, // nested tag support
116 $defaultTags, // additional user-specified tags
117 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
118 $this->conf
->get('resource.data_dir') // log path, will be overridden
120 $logger = new Logger(
121 $this->conf
->get('resource.data_dir'),
122 !$this->conf
->get('dev.debug') ? LogLevel
::INFO
: LogLevel
::DEBUG
,
124 'prefix' => 'import.',
125 'extension' => 'log',
128 $parser->setLogger($logger);
129 $bookmarks = $parser->parseString($data);
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 bookmarks are private
143 } elseif ($post['privacy'] == 'public') {
144 // all imported bookmarks are public
148 $link = $this->bookmarkService
->findByUrl($bkm['uri']);
149 $existingLink = $link !== null;
150 if (! $existingLink) {
151 $link = new Bookmark();
154 if ($existingLink !== false) {
155 if ($overwrite === false) {
156 // Do not overwrite an existing link
161 $link->setUpdated(new DateTime());
164 $newLinkDate = new DateTime('@' . strval($bkm['time']));
165 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
166 $link->setCreated($newLinkDate);
169 $link->setTitle($bkm['title']);
170 $link->setUrl($bkm['uri'], $this->conf
->get('security.allowed_protocols'));
171 $link->setDescription($bkm['note']);
172 $link->setPrivate($private);
173 $link->setTagsString($bkm['tags']);
175 $this->bookmarkService
->addOrSet($link, false);
179 $this->bookmarkService
->save();
180 $this->history
->importLinks();
182 $duration = time() - $start;
184 return $this->importStatus(
195 * Generates an import status summary
197 * @param string $filename name of the file to import
198 * @param int $filesize size of the file to import
199 * @param int $importCount how many bookmarks were imported
200 * @param int $overwriteCount how many bookmarks were overwritten
201 * @param int $skipCount how many bookmarks were skipped
202 * @param int $duration how many seconds did the import take
204 * @return string Summary of the bookmark import status
206 protected function importStatus(
214 $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
215 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
216 $status .= t('has an unknown file format. Nothing was imported.');
220 'was successfully processed in %d seconds: '
221 . '%d bookmarks imported, %d bookmarks overwritten, %d bookmarks skipped.'
223 [$duration, $importCount, $overwriteCount, $skipCount]