]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/NetscapeBookmarkUtils.php
documentation: update 3rd-party resources
[github/shaarli/Shaarli.git] / application / NetscapeBookmarkUtils.php
1 <?php
2
3 use Psr\Log\LogLevel;
4 use Shaarli\Config\ConfigManager;
5 use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser;
6 use Katzgrau\KLogger\Logger;
7
8 /**
9 * Utilities to import and export bookmarks using the Netscape format
10 * TODO: Not static, use a container.
11 */
12 class NetscapeBookmarkUtils
13 {
14
15 /**
16 * Filters links and adds Netscape-formatted fields
17 *
18 * Added fields:
19 * - timestamp link addition date, using the Unix epoch format
20 * - taglist comma-separated tag list
21 *
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
26 *
27 * @throws Exception Invalid export selection
28 *
29 * @return array The links to be exported, with additional fields
30 */
31 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
32 {
33 // see tpl/export.html for possible values
34 if (! in_array($selection, array('all', 'public', 'private'))) {
35 throw new Exception('Invalid export selection: "'.$selection.'"');
36 }
37
38 $bookmarkLinks = array();
39
40 foreach ($linkDb as $link) {
41 if ($link['private'] != 0 && $selection == 'public') {
42 continue;
43 }
44 if ($link['private'] == 0 && $selection == 'private') {
45 continue;
46 }
47 $date = $link['created'];
48 $link['timestamp'] = $date->getTimestamp();
49 $link['taglist'] = str_replace(' ', ',', $link['tags']);
50
51 if (startsWith($link['url'], '?') && $prependNoteUrl) {
52 $link['url'] = $indexUrl . $link['url'];
53 }
54
55 $bookmarkLinks[] = $link;
56 }
57
58 return $bookmarkLinks;
59 }
60
61 /**
62 * Generates an import status summary
63 *
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 *
70 * @return string Summary of the bookmark import status
71 */
72 private static function importStatus(
73 $filename,
74 $filesize,
75 $importCount=0,
76 $overwriteCount=0,
77 $skipCount=0
78 )
79 {
80 $status = 'File '.$filename.' ('.$filesize.' bytes) ';
81 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
82 $status .= 'has an unknown file format. Nothing was imported.';
83 } else {
84 $status .= 'was successfully processed: '.$importCount.' links imported, ';
85 $status .= $overwriteCount.' links overwritten, ';
86 $status .= $skipCount.' links skipped.';
87 }
88 return $status;
89 }
90
91 /**
92 * Imports Web bookmarks from an uploaded Netscape bookmark dump
93 *
94 * @param array $post Server $_POST parameters
95 * @param array $files Server $_FILES parameters
96 * @param LinkDB $linkDb Loaded LinkDB instance
97 * @param ConfigManager $conf instance
98 * @param History $history History instance
99 *
100 * @return string Summary of the bookmark import status
101 */
102 public static function import($post, $files, $linkDb, $conf, $history)
103 {
104 $filename = $files['filetoupload']['name'];
105 $filesize = $files['filetoupload']['size'];
106 $data = file_get_contents($files['filetoupload']['tmp_name']);
107
108 if (strpos($data, '<!DOCTYPE NETSCAPE-Bookmark-file-1>') === false) {
109 return self::importStatus($filename, $filesize);
110 }
111
112 // Overwrite existing links?
113 $overwrite = ! empty($post['overwrite']);
114
115 // Add tags to all imported links?
116 if (empty($post['default_tags'])) {
117 $defaultTags = array();
118 } else {
119 $defaultTags = preg_split(
120 '/[\s,]+/',
121 escape($post['default_tags'])
122 );
123 }
124
125 // links are imported as public by default
126 $defaultPrivacy = 0;
127
128 $parser = new NetscapeBookmarkParser(
129 true, // nested tag support
130 $defaultTags, // additional user-specified tags
131 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
132 $conf->get('resource.data_dir') // log path, will be overridden
133 );
134 $logger = new Logger(
135 $conf->get('resource.data_dir'),
136 ! $conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
137 [
138 'prefix' => 'import.',
139 'extension' => 'log',
140 ]
141 );
142 $parser->setLogger($logger);
143 $bookmarks = $parser->parseString($data);
144
145 $importCount = 0;
146 $overwriteCount = 0;
147 $skipCount = 0;
148
149 foreach ($bookmarks as $bkm) {
150 $private = $defaultPrivacy;
151 if (empty($post['privacy']) || $post['privacy'] == 'default') {
152 // use value from the imported file
153 $private = $bkm['pub'] == '1' ? 0 : 1;
154 } else if ($post['privacy'] == 'private') {
155 // all imported links are private
156 $private = 1;
157 } else if ($post['privacy'] == 'public') {
158 // all imported links are public
159 $private = 0;
160 }
161
162 $newLink = array(
163 'title' => $bkm['title'],
164 'url' => $bkm['uri'],
165 'description' => $bkm['note'],
166 'private' => $private,
167 'tags' => $bkm['tags']
168 );
169
170 $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
171
172 if ($existingLink !== false) {
173 if ($overwrite === false) {
174 // Do not overwrite an existing link
175 $skipCount++;
176 continue;
177 }
178
179 // Overwrite an existing link, keep its date
180 $newLink['id'] = $existingLink['id'];
181 $newLink['created'] = $existingLink['created'];
182 $newLink['updated'] = new DateTime();
183 $newLink['shorturl'] = $existingLink['shorturl'];
184 $linkDb[$existingLink['id']] = $newLink;
185 $importCount++;
186 $overwriteCount++;
187 $history->updateLink($newLink);
188 continue;
189 }
190
191 // Add a new link - @ used for UNIX timestamps
192 $newLinkDate = new DateTime('@'.strval($bkm['time']));
193 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
194 $newLink['created'] = $newLinkDate;
195 $newLink['id'] = $linkDb->getNextId();
196 $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
197 $linkDb[$newLink['id']] = $newLink;
198 $importCount++;
199 $history->addLink($newLink);
200 }
201
202 $linkDb->save($conf->get('resource.page_cache'));
203 return self::importStatus(
204 $filename,
205 $filesize,
206 $importCount,
207 $overwriteCount,
208 $skipCount
209 );
210 }
211 }