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