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