aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/NetscapeBookmarkUtils.php
diff options
context:
space:
mode:
authorVirtualTam <virtualtam@flibidi.net>2018-12-04 00:13:42 +0100
committerVirtualTam <virtualtam@flibidi.net>2019-01-12 23:11:19 +0100
commit349b0144011e25f2b1a727b1d28d49d55b3b2ebb (patch)
tree99cf1746e597672389afc1b9231afa16df65de5a /application/NetscapeBookmarkUtils.php
parenta932f486f20f3daf8ad657d8d39a6d6c316e66eb (diff)
downloadShaarli-349b0144011e25f2b1a727b1d28d49d55b3b2ebb.tar.gz
Shaarli-349b0144011e25f2b1a727b1d28d49d55b3b2ebb.tar.zst
Shaarli-349b0144011e25f2b1a727b1d28d49d55b3b2ebb.zip
namespacing: \Shaarli\Netscape\NetscapeBookmarkUtils
Signed-off-by: VirtualTam <virtualtam@flibidi.net>
Diffstat (limited to 'application/NetscapeBookmarkUtils.php')
-rw-r--r--application/NetscapeBookmarkUtils.php220
1 files changed, 0 insertions, 220 deletions
diff --git a/application/NetscapeBookmarkUtils.php b/application/NetscapeBookmarkUtils.php
deleted file mode 100644
index e0022fe1..00000000
--- a/application/NetscapeBookmarkUtils.php
+++ /dev/null
@@ -1,220 +0,0 @@
1<?php
2
3use Psr\Log\LogLevel;
4use Shaarli\Bookmark\LinkDB;
5use Shaarli\Config\ConfigManager;
6use Shaarli\History;
7use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser;
8use Katzgrau\KLogger\Logger;
9
10/**
11 * Utilities to import and export bookmarks using the Netscape format
12 * TODO: Not static, use a container.
13 */
14class NetscapeBookmarkUtils
15{
16
17 /**
18 * Filters links and adds Netscape-formatted fields
19 *
20 * Added fields:
21 * - timestamp link addition date, using the Unix epoch format
22 * - taglist comma-separated tag list
23 *
24 * @param LinkDB $linkDb Link datastore
25 * @param string $selection Which links to export: (all|private|public)
26 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
27 * @param string $indexUrl Absolute URL of the Shaarli index page
28 *
29 * @throws Exception Invalid export selection
30 *
31 * @return array The links to be exported, with additional fields
32 */
33 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
34 {
35 // see tpl/export.html for possible values
36 if (! in_array($selection, array('all', 'public', 'private'))) {
37 throw new Exception(t('Invalid export selection:') .' "'.$selection.'"');
38 }
39
40 $bookmarkLinks = array();
41 foreach ($linkDb as $link) {
42 if ($link['private'] != 0 && $selection == 'public') {
43 continue;
44 }
45 if ($link['private'] == 0 && $selection == 'private') {
46 continue;
47 }
48 $date = $link['created'];
49 $link['timestamp'] = $date->getTimestamp();
50 $link['taglist'] = str_replace(' ', ',', $link['tags']);
51
52 if (startsWith($link['url'], '?') && $prependNoteUrl) {
53 $link['url'] = $indexUrl . $link['url'];
54 }
55
56 $bookmarkLinks[] = $link;
57 }
58
59 return $bookmarkLinks;
60 }
61
62 /**
63 * Generates an import status summary
64 *
65 * @param string $filename name of the file to import
66 * @param int $filesize size of the file to import
67 * @param int $importCount how many links were imported
68 * @param int $overwriteCount how many links were overwritten
69 * @param int $skipCount how many links were skipped
70 * @param int $duration how many seconds did the import take
71 *
72 * @return string Summary of the bookmark import status
73 */
74 private static function importStatus(
75 $filename,
76 $filesize,
77 $importCount = 0,
78 $overwriteCount = 0,
79 $skipCount = 0,
80 $duration = 0
81 ) {
82 $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
83 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
84 $status .= t('has an unknown file format. Nothing was imported.');
85 } else {
86 $status .= vsprintf(
87 t(
88 'was successfully processed in %d seconds: '
89 .'%d links imported, %d links overwritten, %d links skipped.'
90 ),
91 [$duration, $importCount, $overwriteCount, $skipCount]
92 );
93 }
94 return $status;
95 }
96
97 /**
98 * Imports Web bookmarks from an uploaded Netscape bookmark dump
99 *
100 * @param array $post Server $_POST parameters
101 * @param array $files Server $_FILES parameters
102 * @param LinkDB $linkDb Loaded LinkDB instance
103 * @param ConfigManager $conf instance
104 * @param History $history History instance
105 *
106 * @return string Summary of the bookmark import status
107 */
108 public static function import($post, $files, $linkDb, $conf, $history)
109 {
110 $start = time();
111 $filename = $files['filetoupload']['name'];
112 $filesize = $files['filetoupload']['size'];
113 $data = file_get_contents($files['filetoupload']['tmp_name']);
114
115 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
116 return self::importStatus($filename, $filesize);
117 }
118
119 // Overwrite existing links?
120 $overwrite = ! empty($post['overwrite']);
121
122 // Add tags to all imported links?
123 if (empty($post['default_tags'])) {
124 $defaultTags = array();
125 } else {
126 $defaultTags = preg_split(
127 '/[\s,]+/',
128 escape($post['default_tags'])
129 );
130 }
131
132 // links are imported as public by default
133 $defaultPrivacy = 0;
134
135 $parser = new NetscapeBookmarkParser(
136 true, // nested tag support
137 $defaultTags, // additional user-specified tags
138 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
139 $conf->get('resource.data_dir') // log path, will be overridden
140 );
141 $logger = new Logger(
142 $conf->get('resource.data_dir'),
143 ! $conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
144 [
145 'prefix' => 'import.',
146 'extension' => 'log',
147 ]
148 );
149 $parser->setLogger($logger);
150 $bookmarks = $parser->parseString($data);
151
152 $importCount = 0;
153 $overwriteCount = 0;
154 $skipCount = 0;
155
156 foreach ($bookmarks as $bkm) {
157 $private = $defaultPrivacy;
158 if (empty($post['privacy']) || $post['privacy'] == 'default') {
159 // use value from the imported file
160 $private = $bkm['pub'] == '1' ? 0 : 1;
161 } elseif ($post['privacy'] == 'private') {
162 // all imported links are private
163 $private = 1;
164 } elseif ($post['privacy'] == 'public') {
165 // all imported links are public
166 $private = 0;
167 }
168
169 $newLink = array(
170 'title' => $bkm['title'],
171 'url' => $bkm['uri'],
172 'description' => $bkm['note'],
173 'private' => $private,
174 'tags' => $bkm['tags']
175 );
176
177 $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
178
179 if ($existingLink !== false) {
180 if ($overwrite === false) {
181 // Do not overwrite an existing link
182 $skipCount++;
183 continue;
184 }
185
186 // Overwrite an existing link, keep its date
187 $newLink['id'] = $existingLink['id'];
188 $newLink['created'] = $existingLink['created'];
189 $newLink['updated'] = new DateTime();
190 $newLink['shorturl'] = $existingLink['shorturl'];
191 $linkDb[$existingLink['id']] = $newLink;
192 $importCount++;
193 $overwriteCount++;
194 continue;
195 }
196
197 // Add a new link - @ used for UNIX timestamps
198 $newLinkDate = new DateTime('@'.strval($bkm['time']));
199 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
200 $newLink['created'] = $newLinkDate;
201 $newLink['id'] = $linkDb->getNextId();
202 $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
203 $linkDb[$newLink['id']] = $newLink;
204 $importCount++;
205 }
206
207 $linkDb->save($conf->get('resource.page_cache'));
208 $history->importLinks();
209
210 $duration = time() - $start;
211 return self::importStatus(
212 $filename,
213 $filesize,
214 $importCount,
215 $overwriteCount,
216 $skipCount,
217 $duration
218 );
219 }
220}