4 use Shaarli\Config\ConfigManager
;
6 use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser
;
7 use Katzgrau\KLogger\Logger
;
10 * Utilities to import and export bookmarks using the Netscape format
11 * TODO: Not static, use a container.
13 class NetscapeBookmarkUtils
17 * Filters links and adds Netscape-formatted fields
20 * - timestamp link addition date, using the Unix epoch format
21 * - taglist comma-separated tag list
23 * @param LinkDB $linkDb Link datastore
24 * @param string $selection Which links to export: (all|private|public)
25 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
26 * @param string $indexUrl Absolute URL of the Shaarli index page
28 * @throws Exception Invalid export selection
30 * @return array The links to be exported, with additional fields
32 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
34 // see tpl/export.html for possible values
35 if (! in_array($selection, array('all', 'public', 'private'))) {
36 throw new Exception(t('Invalid export selection:') .' "'.$selection.'"');
39 $bookmarkLinks = array();
40 foreach ($linkDb as $link) {
41 if ($link['private'] != 0 && $selection == 'public') {
44 if ($link['private'] == 0 && $selection == 'private') {
47 $date = $link['created'];
48 $link['timestamp'] = $date->getTimestamp();
49 $link['taglist'] = str_replace(' ', ',', $link['tags']);
51 if (startsWith($link['url'], '?') && $prependNoteUrl) {
52 $link['url'] = $indexUrl . $link['url'];
55 $bookmarkLinks[] = $link;
58 return $bookmarkLinks;
62 * Generates an import status summary
64 * @param string $filename name of the file to import
65 * @param int $filesize size of the file to import
66 * @param int $importCount how many links were imported
67 * @param int $overwriteCount how many links were overwritten
68 * @param int $skipCount how many links were skipped
69 * @param int $duration how many seconds did the import take
71 * @return string Summary of the bookmark import status
73 private static function importStatus(
81 $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
82 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
83 $status .= t('has an unknown file format. Nothing was imported.');
87 'was successfully processed in %d seconds: '
88 .'%d links imported, %d links overwritten, %d links skipped.'
90 [$duration, $importCount, $overwriteCount, $skipCount]
97 * Imports Web bookmarks from an uploaded Netscape bookmark dump
99 * @param array $post Server $_POST parameters
100 * @param array $files Server $_FILES parameters
101 * @param LinkDB $linkDb Loaded LinkDB instance
102 * @param ConfigManager $conf instance
103 * @param History $history History instance
105 * @return string Summary of the bookmark import status
107 public static function import($post, $files, $linkDb, $conf, $history)
110 $filename = $files['filetoupload']['name'];
111 $filesize = $files['filetoupload']['size'];
112 $data = file_get_contents($files['filetoupload']['tmp_name']);
114 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
115 return self
::importStatus($filename, $filesize);
118 // Overwrite existing links?
119 $overwrite = ! empty($post['overwrite']);
121 // Add tags to all imported links?
122 if (empty($post['default_tags'])) {
123 $defaultTags = array();
125 $defaultTags = preg_split(
127 escape($post['default_tags'])
131 // links are imported as public by default
134 $parser = new NetscapeBookmarkParser(
135 true, // nested tag support
136 $defaultTags, // additional user-specified tags
137 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
138 $conf->get('resource.data_dir') // log path, will be overridden
140 $logger = new Logger(
141 $conf->get('resource.data_dir'),
142 ! $conf->get('dev.debug') ? LogLevel
::INFO
: LogLevel
::DEBUG
,
144 'prefix' => 'import.',
145 'extension' => 'log',
148 $parser->setLogger($logger);
149 $bookmarks = $parser->parseString($data);
155 foreach ($bookmarks as $bkm) {
156 $private = $defaultPrivacy;
157 if (empty($post['privacy']) || $post['privacy'] == 'default') {
158 // use value from the imported file
159 $private = $bkm['pub'] == '1' ? 0 : 1;
160 } elseif ($post['privacy'] == 'private') {
161 // all imported links are private
163 } elseif ($post['privacy'] == 'public') {
164 // all imported links are public
169 'title' => $bkm['title'],
170 'url' => $bkm['uri'],
171 'description' => $bkm['note'],
172 'private' => $private,
173 'tags' => $bkm['tags']
176 $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
178 if ($existingLink !== false) {
179 if ($overwrite === false) {
180 // Do not overwrite an existing link
185 // Overwrite an existing link, keep its date
186 $newLink['id'] = $existingLink['id'];
187 $newLink['created'] = $existingLink['created'];
188 $newLink['updated'] = new DateTime();
189 $newLink['shorturl'] = $existingLink['shorturl'];
190 $linkDb[$existingLink['id']] = $newLink;
196 // Add a new link - @ used for UNIX timestamps
197 $newLinkDate = new DateTime('@'.strval($bkm['time']));
198 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
199 $newLink['created'] = $newLinkDate;
200 $newLink['id'] = $linkDb->getNextId();
201 $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
202 $linkDb[$newLink['id']] = $newLink;
206 $linkDb->save($conf->get('resource.page_cache'));
207 $history->importLinks();
209 $duration = time() - $start;
210 return self
::importStatus(