]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/netscape/NetscapeBookmarkUtils.php
namespacing: \Shaarli\Netscape\NetscapeBookmarkUtils
[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;
48417aed 8use Psr\Log\LogLevel;
f24896b2 9use Shaarli\Bookmark\LinkDB;
87e9631e 10use Shaarli\Config\ConfigManager;
bdc5152d 11use Shaarli\History;
48417aed
A
12use Shaarli\NetscapeBookmarkParser\NetscapeBookmarkParser;
13use Katzgrau\KLogger\Logger;
14
cd5327be
V
15/**
16 * Utilities to import and export bookmarks using the Netscape format
48417aed 17 * TODO: Not static, use a container.
cd5327be
V
18 */
19class NetscapeBookmarkUtils
20{
21
22 /**
23 * Filters links and adds Netscape-formatted fields
24 *
25 * Added fields:
26 * - timestamp link addition date, using the Unix epoch format
27 * - taglist comma-separated tag list
28 *
bb4a23aa
V
29 * @param LinkDB $linkDb Link datastore
30 * @param string $selection Which links to export: (all|private|public)
31 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
32 * @param string $indexUrl Absolute URL of the Shaarli index page
cd5327be
V
33 *
34 * @throws Exception Invalid export selection
35 *
36 * @return array The links to be exported, with additional fields
37 */
bb4a23aa 38 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
cd5327be
V
39 {
40 // see tpl/export.html for possible values
349b0144
V
41 if (!in_array($selection, array('all', 'public', 'private'))) {
42 throw new Exception(t('Invalid export selection:') . ' "' . $selection . '"');
cd5327be
V
43 }
44
45 $bookmarkLinks = array();
cd5327be
V
46 foreach ($linkDb as $link) {
47 if ($link['private'] != 0 && $selection == 'public') {
48 continue;
49 }
50 if ($link['private'] == 0 && $selection == 'private') {
51 continue;
52 }
01878a75 53 $date = $link['created'];
cd5327be
V
54 $link['timestamp'] = $date->getTimestamp();
55 $link['taglist'] = str_replace(' ', ',', $link['tags']);
bb4a23aa
V
56
57 if (startsWith($link['url'], '?') && $prependNoteUrl) {
58 $link['url'] = $indexUrl . $link['url'];
59 }
60
cd5327be
V
61 $bookmarkLinks[] = $link;
62 }
63
64 return $bookmarkLinks;
65 }
a973afea
V
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 links were imported
73 * @param int $overwriteCount how many links were overwritten
74 * @param int $skipCount how many links were skipped
66e74d50 75 * @param int $duration how many seconds did the import take
a973afea
V
76 *
77 * @return string Summary of the bookmark import status
78 */
79 private static function importStatus(
80 $filename,
81 $filesize,
f211e417
V
82 $importCount = 0,
83 $overwriteCount = 0,
84 $skipCount = 0,
85 $duration = 0
86 ) {
12266213 87 $status = sprintf(t('File %s (%d bytes) '), $filename, $filesize);
a973afea 88 if ($importCount == 0 && $overwriteCount == 0 && $skipCount == 0) {
12266213 89 $status .= t('has an unknown file format. Nothing was imported.');
a973afea 90 } else {
12266213 91 $status .= vsprintf(
9d9f6d75
V
92 t(
93 'was successfully processed in %d seconds: '
349b0144 94 . '%d links imported, %d links overwritten, %d links skipped.'
9d9f6d75 95 ),
12266213
A
96 [$duration, $importCount, $overwriteCount, $skipCount]
97 );
a973afea
V
98 }
99 return $status;
100 }
101
102 /**
103 * Imports Web bookmarks from an uploaded Netscape bookmark dump
104 *
349b0144
V
105 * @param array $post Server $_POST parameters
106 * @param array $files Server $_FILES parameters
107 * @param LinkDB $linkDb Loaded LinkDB instance
108 * @param ConfigManager $conf instance
109 * @param History $history History instance
a973afea
V
110 *
111 * @return string Summary of the bookmark import status
112 */
4306b184 113 public static function import($post, $files, $linkDb, $conf, $history)
a973afea 114 {
66e74d50 115 $start = time();
a973afea
V
116 $filename = $files['filetoupload']['name'];
117 $filesize = $files['filetoupload']['size'];
118 $data = file_get_contents($files['filetoupload']['tmp_name']);
119
3ff1ce47 120 if (preg_match('/<!DOCTYPE NETSCAPE-Bookmark-file-1>/i', $data) === 0) {
a973afea
V
121 return self::importStatus($filename, $filesize);
122 }
123
124 // Overwrite existing links?
349b0144 125 $overwrite = !empty($post['overwrite']);
a973afea
V
126
127 // Add tags to all imported links?
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 // links are imported as public by default
138 $defaultPrivacy = 0;
139
140 $parser = new NetscapeBookmarkParser(
48417aed
A
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'),
349b0144 148 !$conf->get('dev.debug') ? LogLevel::INFO : LogLevel::DEBUG,
48417aed
A
149 [
150 'prefix' => 'import.',
151 'extension' => 'log',
152 ]
a973afea 153 );
48417aed 154 $parser->setLogger($logger);
a973afea
V
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;
d2d4f993 166 } elseif ($post['privacy'] == 'private') {
a973afea
V
167 // all imported links are private
168 $private = 1;
d2d4f993 169 } elseif ($post['privacy'] == 'public') {
a973afea
V
170 // all imported links are public
171 $private = 0;
3ff1ce47 172 }
a973afea
V
173
174 $newLink = array(
175 'title' => $bkm['title'],
176 'url' => $bkm['uri'],
177 'description' => $bkm['note'],
178 'private' => $private,
a973afea
V
179 'tags' => $bkm['tags']
180 );
181
182 $existingLink = $linkDb->getLinkFromUrl($bkm['uri']);
183
184 if ($existingLink !== false) {
185 if ($overwrite === false) {
186 // Do not overwrite an existing link
187 $skipCount++;
188 continue;
189 }
190
191 // Overwrite an existing link, keep its date
01878a75
A
192 $newLink['id'] = $existingLink['id'];
193 $newLink['created'] = $existingLink['created'];
194 $newLink['updated'] = new DateTime();
28794b69 195 $newLink['shorturl'] = $existingLink['shorturl'];
01878a75 196 $linkDb[$existingLink['id']] = $newLink;
a973afea
V
197 $importCount++;
198 $overwriteCount++;
199 continue;
200 }
201
01878a75 202 // Add a new link - @ used for UNIX timestamps
349b0144 203 $newLinkDate = new DateTime('@' . strval($bkm['time']));
01878a75
A
204 $newLinkDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
205 $newLink['created'] = $newLinkDate;
206 $newLink['id'] = $linkDb->getNextId();
d592daea 207 $newLink['shorturl'] = link_small_hash($newLink['created'], $newLink['id']);
01878a75 208 $linkDb[$newLink['id']] = $newLink;
a973afea
V
209 $importCount++;
210 }
211
48417aed 212 $linkDb->save($conf->get('resource.page_cache'));
66e74d50
A
213 $history->importLinks();
214
215 $duration = time() - $start;
a973afea
V
216 return self::importStatus(
217 $filename,
218 $filesize,
219 $importCount,
220 $overwriteCount,
66e74d50
A
221 $skipCount,
222 $duration
a973afea
V
223 );
224 }
cd5327be 225}