]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/netscape/NetscapeBookmarkUtils.php
Handle pagination through BookmarkService
[github/shaarli/Shaarli.git] / application / netscape / NetscapeBookmarkUtils.php
CommitLineData
cd5327be
V
1<?php
2
349b0144
V
3namespace Shaarli\Netscape;
4
5use DateTime;
6use DateTimeZone;
7use Exception;
dea72c71 8use Katzgrau\KLogger\Logger;
78657347 9use Psr\Http\Message\UploadedFileInterface;
48417aed 10use Psr\Log\LogLevel;
cf92b4dd
A
11use Shaarli\Bookmark\Bookmark;
12use Shaarli\Bookmark\BookmarkServiceInterface;
87e9631e 13use Shaarli\Config\ConfigManager;
cf92b4dd 14use Shaarli\Formatter\BookmarkFormatter;
bdc5152d 15use Shaarli\History;
48417aed 16use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser;
48417aed 17
cd5327be
V
18/**
19 * Utilities to import and export bookmarks using the Netscape format
20 */
21class NetscapeBookmarkUtils
22{
e8a10f31
A
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 }
cd5327be
V
38
39 /**
cf92b4dd 40 * Filters bookmarks and adds Netscape-formatted fields
cd5327be
V
41 *
42 * Added fields:
43 * - timestamp link addition date, using the Unix epoch format
44 * - taglist comma-separated tag list
45 *
cf92b4dd
A
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
cd5327be 50 *
cf92b4dd 51 * @return array The bookmarks to be exported, with additional fields
cd5327be 52 *
e8a10f31 53 * @throws Exception Invalid export selection
cd5327be 54 */
e8a10f31 55 public function filterAndFormat(
cf92b4dd
A
56 $formatter,
57 $selection,
58 $prependNoteUrl,
59 $indexUrl
60 ) {
cd5327be 61 // see tpl/export.html for possible values
53054b2b 62 if (!in_array($selection, ['all', 'public', 'private'])) {
349b0144 63 throw new Exception(t('Invalid export selection:') . ' "' . $selection . '"');
cd5327be
V
64 }
65
53054b2b 66 $bookmarkLinks = [];
9b8c0a45 67 foreach ($this->bookmarkService->search([], $selection)->getBookmarks() as $bookmark) {
cf92b4dd
A
68 $link = $formatter->format($bookmark);
69 $link['taglist'] = implode(',', $bookmark->getTags());
70 if ($bookmark->isNote() && $prependNoteUrl) {
301c7ab1 71 $link['url'] = rtrim($indexUrl, '/') . '/' . ltrim($link['url'], '/');
bb4a23aa
V
72 }
73
cd5327be
V
74 $bookmarkLinks[] = $link;
75 }
76
77 return $bookmarkLinks;
78 }
a973afea 79
a973afea
V
80 /**
81 * Imports Web bookmarks from an uploaded Netscape bookmark dump
82 *
78657347
A
83 * @param array $post Server $_POST parameters
84 * @param UploadedFileInterface $file File in PSR-7 object format
a973afea
V
85 *
86 * @return string Summary of the bookmark import status
87 */
78657347 88 public function import($post, UploadedFileInterface $file)
a973afea 89 {
66e74d50 90 $start = time();
78657347
A
91 $filename = $file->getClientFilename();
92 $filesize = $file->getSize();
93 $data = (string) $file->getStream();
a973afea 94
3ff1ce47 95 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
78657347 96 return $this->importStatus($filename, $filesize);
a973afea
V
97 }
98
cf92b4dd 99 // Overwrite existing bookmarks?
349b0144 100 $overwrite = !empty($post['overwrite']);
a973afea 101
cf92b4dd 102 // Add tags to all imported bookmarks?
a973afea 103 if (empty($post['default_tags'])) {
b3bd8c3e 104 $defaultTags = [];
a973afea 105 } else {
b3bd8c3e
A
106 $defaultTags = tags_str2array(
107 escape($post['default_tags']),
108 $this->conf->get('general.tags_separator', ' ')
a973afea
V
109 );
110 }
111
cf92b4dd 112 // bookmarks are imported as public by default
a973afea
V
113 $defaultPrivacy = 0;
114
115 $parser = new NetscapeBookmarkParser(
48417aed
A
116 true, // nested tag support
117 $defaultTags, // additional user-specified tags
118 strval(1 - $defaultPrivacy), // defaultPub = 1 - defaultPrivacy
e8a10f31 119 $this->conf->get('resource.data_dir') // log path, will be overridden
48417aed
A
120 );
121 $logger = new Logger(
e8a10f31
A
122 $this->conf->get('resource.data_dir'),
123 !$this->conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
48417aed
A
124 [
125 'prefix' => 'import.',
126 'extension' => 'log',
127 ]
a973afea 128 );
48417aed 129 $parser->setLogger($logger);
a973afea
V
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;
d2d4f993 141 } elseif ($post['privacy'] == 'private') {
cf92b4dd 142 // all imported bookmarks are private
a973afea 143 $private = 1;
d2d4f993 144 } elseif ($post['privacy'] == 'public') {
cf92b4dd 145 // all imported bookmarks are public
a973afea 146 $private = 0;
3ff1ce47 147 }
a973afea 148
e8a10f31 149 $link = $this->bookmarkService->findByUrl($bkm['uri']);
cf92b4dd
A
150 $existingLink = $link !== null;
151 if (! $existingLink) {
152 $link = new Bookmark();
153 }
a973afea
V
154
155 if ($existingLink !== false) {
156 if ($overwrite === false) {
157 // Do not overwrite an existing link
158 $skipCount++;
159 continue;
160 }
161
cf92b4dd 162 $link->setUpdated(new DateTime());
a973afea 163 $overwriteCount++;
cf92b4dd
A
164 } else {
165 $newLinkDate = new DateTime('@' . strval($bkm['time']));
166 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
167 $link->setCreated($newLinkDate);
a973afea
V
168 }
169
cf92b4dd 170 $link->setTitle($bkm['title']);
e8a10f31 171 $link->setUrl($bkm['uri'], $this->conf->get('security.allowed_protocols'));
cf92b4dd
A
172 $link->setDescription($bkm['note']);
173 $link->setPrivate($private);
b3bd8c3e 174 $link->setTags($bkm['tags']);
cf92b4dd 175
e8a10f31 176 $this->bookmarkService->addOrSet($link, false);
a973afea
V
177 $importCount++;
178 }
179
e8a10f31
A
180 $this->bookmarkService->save();
181 $this->history->importLinks();
66e74d50
A
182
183 $duration = time() - $start;
e8a10f31
A
184
185 return $this->importStatus(
a973afea
V
186 $filename,
187 $filesize,
188 $importCount,
189 $overwriteCount,
66e74d50
A
190 $skipCount,
191 $duration
a973afea
V
192 );
193 }
e8a10f31
A
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 }
cd5327be 229}