4 use Shaarli\Config\ConfigManager
;
5 use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser
;
6 use Katzgrau\KLogger\Logger
;
9 * Utilities to import and export bookmarks using the Netscape format
10 * TODO: Not static, use a container.
12 class NetscapeBookmarkUtils
16 * Filters links and adds Netscape-formatted fields
19 * - timestamp link addition date, using the Unix epoch format
20 * - taglist comma-separated tag list
22 * @param LinkDB $linkDb Link datastore
23 * @param string $selection Which links to export: (all|private|public)
24 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
25 * @param string $indexUrl Absolute URL of the Shaarli index page
27 * @throws Exception Invalid export selection
29 * @return array The links to be exported, with additional fields
31 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
33 // see tpl/export.html for possible values
34 if (! in_array($selection, array('all', 'public', 'private'))) {
35 throw new Exception(t('Invalid export selection:') .' "'.$selection.'"');
38 $bookmarkLinks = array();
39 foreach ($linkDb as $link) {
40 if ($link['private'] != 0 && $selection == 'public') {
43 if ($link['private'] == 0 && $selection == 'private') {
46 $date = $link['created'];
47 $link['timestamp'] = $date->getTimestamp();
48 $link['taglist'] = str_replace(' ', ',', $link['tags']);
50 if (startsWith($link['url'], '?') && $prependNoteUrl) {
51 $link['url'] = $indexUrl . $link['url'];
54 $bookmarkLinks[] = $link;
57 return $bookmarkLinks;
61 * Generates an import status summary
63 * @param string $filename name of the file to import
64 * @param int $filesize size of the file to import
65 * @param int $importCount how many links were imported
66 * @param int $overwriteCount how many links were overwritten
67 * @param int $skipCount how many links were skipped
68 * @param int $duration how many seconds did the import take
70 * @return string Summary of the bookmark import status
72 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.');
86 t('was successfully processed in %d seconds: %d links imported, %d links overwritten, %d links skipped.'),
87 [$duration, $importCount, $overwriteCount, $skipCount]
94 * Imports Web bookmarks from an uploaded Netscape bookmark dump
96 * @param array $post Server $_POST parameters
97 * @param array $files Server $_FILES parameters
98 * @param LinkDB $linkDb Loaded LinkDB instance
99 * @param ConfigManager $conf instance
100 * @param History $history History instance
102 * @return string Summary of the bookmark import status
104 public static function import($post, $files, $linkDb, $conf, $history)
107 $filename = $files['filetoupload']['name'];
108 $filesize = $files['filetoupload']['size'];
109 $data = file_get_contents($files['filetoupload']['tmp_name']);
111 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
112 return self
::importStatus($filename, $filesize);
115 // Overwrite existing links?
116 $overwrite = ! empty($post['overwrite']);
118 // Add tags to all imported links?
119 if (empty($post['default_tags'])) {
120 $defaultTags = array();
122 $defaultTags = preg_split(
124 escape($post['default_tags'])
128 // links are imported as public by default
131 $parser = new NetscapeBookmarkParser(
132 true, // nested tag support
133 $defaultTags, // additional user-specified tags
134 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
135 $conf->get('resource.data_dir') // log path, will be overridden
137 $logger = new Logger(
138 $conf->get('resource.data_dir'),
139 ! $conf->get('dev.debug') ? LogLevel
::INFO
: LogLevel
::DEBUG
,
141 'prefix' => 'import.',
142 'extension' => 'log',
145 $parser->setLogger($logger);
146 $bookmarks = $parser->parseString($data);
152 foreach ($bookmarks as $bkm) {
153 $private = $defaultPrivacy;
154 if (empty($post['privacy']) || $post['privacy'] == 'default') {
155 // use value from the imported file
156 $private = $bkm['pub'] == '1' ? 0 : 1;
157 } elseif ($post['privacy'] == 'private') {
158 // all imported links are private
160 } elseif ($post['privacy'] == 'public') {
161 // all imported links are public
166 'title' => $bkm['title'],
167 'url' => $bkm['uri'],
168 'description' => $bkm['note'],
169 'private' => $private,
170 'tags' => $bkm['tags']
173 $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
175 if ($existingLink !== false) {
176 if ($overwrite === false) {
177 // Do not overwrite an existing link
182 // Overwrite an existing link, keep its date
183 $newLink['id'] = $existingLink['id'];
184 $newLink['created'] = $existingLink['created'];
185 $newLink['updated'] = new DateTime();
186 $newLink['shorturl'] = $existingLink['shorturl'];
187 $linkDb[$existingLink['id']] = $newLink;
193 // Add a new link - @ used for UNIX timestamps
194 $newLinkDate = new DateTime('@'.strval($bkm['time']));
195 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
196 $newLink['created'] = $newLinkDate;
197 $newLink['id'] = $linkDb->getNextId();
198 $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
199 $linkDb[$newLink['id']] = $newLink;
203 $linkDb->save($conf->get('resource.page_cache'));
204 $history->importLinks();
206 $duration = time() - $start;
207 return self
::importStatus(