]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/NetscapeBookmarkUtils.php
lint: fix line-length warnings
[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(t('Invalid export selection:') .' "'.$selection.'"');
36 }
37
38 $bookmarkLinks = array();
39 foreach ($linkDb as $link) {
40 if ($link['private'] != 0 && $selection == 'public') {
41 continue;
42 }
43 if ($link['private'] == 0 && $selection == 'private') {
44 continue;
45 }
46 $date = $link['created'];
47 $link['timestamp'] = $date->getTimestamp();
48 $link['taglist'] = str_replace(' ', ',', $link['tags']);
49
50 if (startsWith($link['url'], '?') && $prependNoteUrl) {
51 $link['url'] = $indexUrl . $link['url'];
52 }
53
54 $bookmarkLinks[] = $link;
55 }
56
57 return $bookmarkLinks;
58 }
59
60 /**
61 * Generates an import status summary
62 *
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
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 $duration = 0
79 ) {
80 $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
81 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
82 $status .= t('has an unknown file format. Nothing was imported.');
83 } else {
84 $status .= vsprintf(
85 t(
86 'was successfully processed in %d seconds: '
87 .'%d links imported, %d links overwritten, %d links skipped.'
88 ),
89 [$duration, $importCount, $overwriteCount, $skipCount]
90 );
91 }
92 return $status;
93 }
94
95 /**
96 * Imports Web bookmarks from an uploaded Netscape bookmark dump
97 *
98 * @param array $post Server $_POST parameters
99 * @param array $files Server $_FILES parameters
100 * @param LinkDB $linkDb Loaded LinkDB instance
101 * @param ConfigManager $conf instance
102 * @param History $history History instance
103 *
104 * @return string Summary of the bookmark import status
105 */
106 public static function import($post, $files, $linkDb, $conf, $history)
107 {
108 $start = time();
109 $filename = $files['filetoupload']['name'];
110 $filesize = $files['filetoupload']['size'];
111 $data = file_get_contents($files['filetoupload']['tmp_name']);
112
113 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
114 return self::importStatus($filename, $filesize);
115 }
116
117 // Overwrite existing links?
118 $overwrite = ! empty($post['overwrite']);
119
120 // Add tags to all imported links?
121 if (empty($post['default_tags'])) {
122 $defaultTags = array();
123 } else {
124 $defaultTags = preg_split(
125 '/[\s,]+/',
126 escape($post['default_tags'])
127 );
128 }
129
130 // links are imported as public by default
131 $defaultPrivacy = 0;
132
133 $parser = new NetscapeBookmarkParser(
134 true, // nested tag support
135 $defaultTags, // additional user-specified tags
136 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
137 $conf->get('resource.data_dir') // log path, will be overridden
138 );
139 $logger = new Logger(
140 $conf->get('resource.data_dir'),
141 ! $conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
142 [
143 'prefix' => 'import.',
144 'extension' => 'log',
145 ]
146 );
147 $parser->setLogger($logger);
148 $bookmarks = $parser->parseString($data);
149
150 $importCount = 0;
151 $overwriteCount = 0;
152 $skipCount = 0;
153
154 foreach ($bookmarks as $bkm) {
155 $private = $defaultPrivacy;
156 if (empty($post['privacy']) || $post['privacy'] == 'default') {
157 // use value from the imported file
158 $private = $bkm['pub'] == '1' ? 0 : 1;
159 } elseif ($post['privacy'] == 'private') {
160 // all imported links are private
161 $private = 1;
162 } elseif ($post['privacy'] == 'public') {
163 // all imported links are public
164 $private = 0;
165 }
166
167 $newLink = array(
168 'title' => $bkm['title'],
169 'url' => $bkm['uri'],
170 'description' => $bkm['note'],
171 'private' => $private,
172 'tags' => $bkm['tags']
173 );
174
175 $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
176
177 if ($existingLink !== false) {
178 if ($overwrite === false) {
179 // Do not overwrite an existing link
180 $skipCount++;
181 continue;
182 }
183
184 // Overwrite an existing link, keep its date
185 $newLink['id'] = $existingLink['id'];
186 $newLink['created'] = $existingLink['created'];
187 $newLink['updated'] = new DateTime();
188 $newLink['shorturl'] = $existingLink['shorturl'];
189 $linkDb[$existingLink['id']] = $newLink;
190 $importCount++;
191 $overwriteCount++;
192 continue;
193 }
194
195 // Add a new link - @ used for UNIX timestamps
196 $newLinkDate = new DateTime('@'.strval($bkm['time']));
197 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
198 $newLink['created'] = $newLinkDate;
199 $newLink['id'] = $linkDb->getNextId();
200 $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
201 $linkDb[$newLink['id']] = $newLink;
202 $importCount++;
203 }
204
205 $linkDb->save($conf->get('resource.page_cache'));
206 $history->importLinks();
207
208 $duration = time() - $start;
209 return self::importStatus(
210 $filename,
211 $filesize,
212 $importCount,
213 $overwriteCount,
214 $skipCount,
215 $duration
216 );
217 }
218 }