]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/netscape/NetscapeBookmarkUtils.php
Store bookmarks as PHP objects and add a service layer to retriā€¦ (#1307)
[github/shaarli/Shaarli.git] / application / netscape / NetscapeBookmarkUtils.php
1 <?php
2
3 namespace Shaarli\Netscape;
4
5 use DateTime;
6 use DateTimeZone;
7 use Exception;
8 use Katzgrau\KLogger\Logger;
9 use Psr\Log\LogLevel;
10 use Shaarli\Bookmark\Bookmark;
11 use Shaarli\Bookmark\BookmarkServiceInterface;
12 use Shaarli\Config\ConfigManager;
13 use Shaarli\Formatter\BookmarkFormatter;
14 use Shaarli\History;
15 use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser;
16
17 /**
18 * Utilities to import and export bookmarks using the Netscape format
19 * TODO: Not static, use a container.
20 */
21 class NetscapeBookmarkUtils
22 {
23
24 /**
25 * Filters bookmarks and adds Netscape-formatted fields
26 *
27 * Added fields:
28 * - timestamp link addition date, using the Unix epoch format
29 * - taglist comma-separated tag list
30 *
31 * @param BookmarkServiceInterface $bookmarkService Link datastore
32 * @param BookmarkFormatter $formatter instance
33 * @param string $selection Which bookmarks to export: (all|private|public)
34 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
35 * @param string $indexUrl Absolute URL of the Shaarli index page
36 *
37 * @return array The bookmarks to be exported, with additional fields
38 *@throws Exception Invalid export selection
39 *
40 */
41 public static function filterAndFormat(
42 $bookmarkService,
43 $formatter,
44 $selection,
45 $prependNoteUrl,
46 $indexUrl
47 ) {
48 // see tpl/export.html for possible values
49 if (!in_array($selection, array('all', 'public', 'private'))) {
50 throw new Exception(t('Invalid export selection:') . ' "' . $selection . '"');
51 }
52
53 $bookmarkLinks = array();
54 foreach ($bookmarkService->search([], $selection) as $bookmark) {
55 $link = $formatter->format($bookmark);
56 $link['taglist'] = implode(',', $bookmark->getTags());
57 if ($bookmark->isNote() && $prependNoteUrl) {
58 $link['url'] = $indexUrl . $link['url'];
59 }
60
61 $bookmarkLinks[] = $link;
62 }
63
64 return $bookmarkLinks;
65 }
66
67 /**
68 * Generates an import status summary
69 *
70 * @param string $filename name of the file to import
71 * @param int $filesize size of the file to import
72 * @param int $importCount how many bookmarks were imported
73 * @param int $overwriteCount how many bookmarks were overwritten
74 * @param int $skipCount how many bookmarks were skipped
75 * @param int $duration how many seconds did the import take
76 *
77 * @return string Summary of the bookmark import status
78 */
79 private static function importStatus(
80 $filename,
81 $filesize,
82 $importCount = 0,
83 $overwriteCount = 0,
84 $skipCount = 0,
85 $duration = 0
86 ) {
87 $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
88 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
89 $status .= t('has an unknown file format. Nothing was imported.');
90 } else {
91 $status .= vsprintf(
92 t(
93 'was successfully processed in %d seconds: '
94 . '%d bookmarks imported, %d bookmarks overwritten, %d bookmarks skipped.'
95 ),
96 [$duration, $importCount, $overwriteCount, $skipCount]
97 );
98 }
99 return $status;
100 }
101
102 /**
103 * Imports Web bookmarks from an uploaded Netscape bookmark dump
104 *
105 * @param array $post Server $_POST parameters
106 * @param array $files Server $_FILES parameters
107 * @param BookmarkServiceInterface $bookmarkService Loaded LinkDB instance
108 * @param ConfigManager $conf instance
109 * @param History $history History instance
110 *
111 * @return string Summary of the bookmark import status
112 */
113 public static function import($post, $files, $bookmarkService, $conf, $history)
114 {
115 $start = time();
116 $filename = $files['filetoupload']['name'];
117 $filesize = $files['filetoupload']['size'];
118 $data = file_get_contents($files['filetoupload']['tmp_name']);
119
120 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
121 return self::importStatus($filename, $filesize);
122 }
123
124 // Overwrite existing bookmarks?
125 $overwrite = !empty($post['overwrite']);
126
127 // Add tags to all imported bookmarks?
128 if (empty($post['default_tags'])) {
129 $defaultTags = array();
130 } else {
131 $defaultTags = preg_split(
132 '/[\s,]+/',
133 escape($post['default_tags'])
134 );
135 }
136
137 // bookmarks are imported as public by default
138 $defaultPrivacy = 0;
139
140 $parser = new NetscapeBookmarkParser(
141 true, // nested tag support
142 $defaultTags, // additional user-specified tags
143 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
144 $conf->get('resource.data_dir') // log path, will be overridden
145 );
146 $logger = new Logger(
147 $conf->get('resource.data_dir'),
148 !$conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
149 [
150 'prefix' => 'import.',
151 'extension' => 'log',
152 ]
153 );
154 $parser->setLogger($logger);
155 $bookmarks = $parser->parseString($data);
156
157 $importCount = 0;
158 $overwriteCount = 0;
159 $skipCount = 0;
160
161 foreach ($bookmarks as $bkm) {
162 $private = $defaultPrivacy;
163 if (empty($post['privacy']) || $post['privacy'] == 'default') {
164 // use value from the imported file
165 $private = $bkm['pub'] == '1' ? 0 : 1;
166 } elseif ($post['privacy'] == 'private') {
167 // all imported bookmarks are private
168 $private = 1;
169 } elseif ($post['privacy'] == 'public') {
170 // all imported bookmarks are public
171 $private = 0;
172 }
173
174 $link = $bookmarkService->findByUrl($bkm['uri']);
175 $existingLink = $link !== null;
176 if (! $existingLink) {
177 $link = new Bookmark();
178 }
179
180 if ($existingLink !== false) {
181 if ($overwrite === false) {
182 // Do not overwrite an existing link
183 $skipCount++;
184 continue;
185 }
186
187 $link->setUpdated(new DateTime());
188 $overwriteCount++;
189 } else {
190 $newLinkDate = new DateTime('@' . strval($bkm['time']));
191 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
192 $link->setCreated($newLinkDate);
193 }
194
195 $link->setTitle($bkm['title']);
196 $link->setUrl($bkm['uri'], $conf->get('security.allowed_protocols'));
197 $link->setDescription($bkm['note']);
198 $link->setPrivate($private);
199 $link->setTagsString($bkm['tags']);
200
201 $bookmarkService->addOrSet($link, false);
202 $importCount++;
203 }
204
205 $bookmarkService->save();
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 }