4 use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser
;
5 use Katzgrau\KLogger\Logger
;
8 * Utilities to import and export bookmarks using the Netscape format
9 * TODO: Not static, use a container.
11 class NetscapeBookmarkUtils
15 * Filters links and adds Netscape-formatted fields
18 * - timestamp link addition date, using the Unix epoch format
19 * - taglist comma-separated tag list
21 * @param LinkDB $linkDb Link datastore
22 * @param string $selection Which links to export: (all|private|public)
23 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
24 * @param string $indexUrl Absolute URL of the Shaarli index page
26 * @throws Exception Invalid export selection
28 * @return array The links to be exported, with additional fields
30 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
32 // see tpl/export.html for possible values
33 if (! in_array($selection, array('all', 'public', 'private'))) {
34 throw new Exception('Invalid export selection: "'.$selection.'"');
37 $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
69 * @return string Summary of the bookmark import status
71 private static function importStatus(
79 $status = 'File '.$filename.' ('.$filesize.' bytes) ';
80 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
81 $status .= 'has an unknown file format. Nothing was imported.';
83 $status .= 'was successfully processed: '.$importCount.' links imported, ';
84 $status .= $overwriteCount.' links overwritten, ';
85 $status .= $skipCount.' links skipped.';
91 * Imports Web bookmarks from an uploaded Netscape bookmark dump
93 * @param array $post Server $_POST parameters
94 * @param array $files Server $_FILES parameters
95 * @param LinkDB $linkDb Loaded LinkDB instance
96 * @param ConfigManager $conf instance
98 * @return string Summary of the bookmark import status
100 public static function import($post, $files, $linkDb, $conf)
102 $filename = $files['filetoupload']['name'];
103 $filesize = $files['filetoupload']['size'];
104 $data = file_get_contents($files['filetoupload']['tmp_name']);
106 if (strpos($data, '<!DOCTYPE NETSCAPE-Bookmark-file-1>') === false) {
107 return self
::importStatus($filename, $filesize);
110 // Overwrite existing links?
111 $overwrite = ! empty($post['overwrite']);
113 // Add tags to all imported links?
114 if (empty($post['default_tags'])) {
115 $defaultTags = array();
117 $defaultTags = preg_split(
119 escape($post['default_tags'])
123 // links are imported as public by default
126 $parser = new NetscapeBookmarkParser(
127 true, // nested tag support
128 $defaultTags, // additional user-specified tags
129 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
130 $conf->get('resource.data_dir') // log path, will be overridden
132 $logger = new Logger(
133 $conf->get('resource.data_dir'),
134 ! $conf->get('dev.debug') ? LogLevel
::INFO
: LogLevel
::DEBUG
,
136 'prefix' => 'import.',
137 'extension' => 'log',
140 $parser->setLogger($logger);
141 $bookmarks = $parser->parseString($data);
147 foreach ($bookmarks as $bkm) {
148 $private = $defaultPrivacy;
149 if (empty($post['privacy']) || $post['privacy'] == 'default') {
150 // use value from the imported file
151 $private = $bkm['pub'] == '1' ? 0 : 1;
152 } else if ($post['privacy'] == 'private') {
153 // all imported links are private
155 } else if ($post['privacy'] == 'public') {
156 // all imported links are public
161 'title' => $bkm['title'],
162 'url' => $bkm['uri'],
163 'description' => $bkm['note'],
164 'private' => $private,
165 'tags' => $bkm['tags']
168 $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
170 if ($existingLink !== false) {
171 if ($overwrite === false) {
172 // Do not overwrite an existing link
177 // Overwrite an existing link, keep its date
178 $newLink['id'] = $existingLink['id'];
179 $newLink['created'] = $existingLink['created'];
180 $newLink['updated'] = new DateTime();
181 $linkDb[$existingLink['id']] = $newLink;
187 // Add a new link - @ used for UNIX timestamps
188 $newLinkDate = new DateTime('@'.strval($bkm['time']));
189 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
190 $newLink['created'] = $newLinkDate;
191 $newLink['id'] = $linkDb->getNextId();
192 $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
193 $linkDb[$newLink['id']] = $newLink;
197 $linkDb->save($conf->get('resource.page_cache'));
198 return self
::importStatus(