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