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