-
Notifications
You must be signed in to change notification settings - Fork 23
/
NetscapeBookmarkParser.php
257 lines (229 loc) · 8.3 KB
/
NetscapeBookmarkParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
<?php
/**
* Generic Netscape bookmark parser
*/
class NetscapeBookmarkParser
{
protected $keepNestedTags;
protected $defaultTags;
protected $defaultPub;
protected $items;
const TRUE_PATTERN = 'y|yes|on|checked|ok|1|true|array|\+|okay|yes|t|one';
const FALSE_PATTERN = 'n|no|off|empty|null|false|nil|0|-|exit|die|neg|f|zero|void';
/**
* Instantiates a new NetscapeBookmarkParser
*
* @param bool $keepNestedTags Tag links with parent folder names
* @param array $defaultTags Tag all links with these values
* @param mixed $defaultPub Link publication status if missing
* - '1' => public
* - '0' => private)
*/
public function __construct(
$keepNestedTags=true,
$defaultTags=array(),
$defaultPub='0'
)
{
if ($keepNestedTags) {
$this->keepNestedTags = true;
}
if ($defaultTags) {
$this->defaultTags = $defaultTags;
} else {
$this->defaultTags = array();
}
$this->defaultPub = $defaultPub;
}
/**
* Parses a Netscape bookmark file
*
* @param string $filename Bookmark file to parse
*
* @return array An associative array containing parsed links
*/
public function parseFile($filename)
{
return $this->parseString(file_get_contents($filename));
}
/**
* Parses a string containing Netscape-formatted bookmarks
*
* Output format:
*
* Array
* (
* [0] => Array
* (
* [note] => Some comments about this link
* [pub] => 1
* [tags] => a list of tags
* [time] => 1459371397
* [title] => Some page
* [uri] => http://domain.tld:5678/some-page.html
* )
* [1] => Array
* (
* ...
* )
* )
*
* @param string $bookmarkString String containing Netscape bookmarks
*
* @return array An associative array containing parsed links
*/
public function parseString($bookmarkString) {
$i = 0;
$next = false;
$folderTags = array();
$lines = explode("\n", $this->sanitizeString($bookmarkString));
foreach ($lines as $line_no => $line) {
if (preg_match('/^<h\d.*>(.*)<\/h\d>/i', $line, $m1)) {
// a header is matched:
// - links may be grouped in a (sub-)folder
// - append the header's content to the folder tags
$folderTags[] = strtolower($m1[1]);
continue;
} elseif (preg_match('/^<\/DL>/i', $line)) {
// </DL> matched: stop using header value
array_pop($folderTags);
continue;
}
if (preg_match('/<a/i', $line, $m2)) {
if (preg_match('/href="(.*?)"/i', $line, $m3)) {
$this->items[$i]['uri'] = $m3[1];
} else {
$this->items[$i]['uri'] = '';
}
if (preg_match('/<a.*>(.*?)<\/a>/i', $line, $m4)) {
$this->items[$i]['title'] = $m4[1];
} else {
$this->items[$i]['title'] = 'untitled';
}
if (preg_match('/note="(.*?)"<\/a>/i', $line, $m5)) {
$this->items[$i]['note'] = $m5[1];
} elseif (preg_match('/<dd>(.*?)$/i', $line, $m6)) {
$this->items[$i]['note'] = str_replace('<br>', "\n", $m6[1]);
} else {
$this->items[$i]['note'] = '';
}
$tags = array();
if ($this->defaultTags) {
$tags = array_merge($tags, $this->defaultTags);
}
if ($this->keepNestedTags) {
$tags = array_merge($tags, $folderTags);
}
if (preg_match('/(tags?|labels?|folders?)="(.*?)"/i', $line, $m7)) {
$tags = array_merge(
$tags,
explode(' ', strtr($m7[2], ',', ' '))
);
}
$this->items[$i]['tags'] = implode(' ', $tags);
if (preg_match('/add_date="(.*?)"/i', $line, $m8)) {
$this->items[$i]['time'] = $this->parseDate($m8[1]);
} else {
$this->items[$i]['time'] = time();
}
if (preg_match('/(public|published|pub)="(.*?)"/i', $line, $m9)) {
$this->items[$i]['pub'] = $this->parseBoolean($m9[2], false) ? 1 : 0;
} elseif (preg_match('/(private|shared)="(.*?)"/i', $line, $m10)) {
$this->items[$i]['pub'] = $this->parseBoolean($m10[2], true) ? 0 : 1;
} else {
$this->items[$i]['pub'] = $this->defaultPub;
}
$i++;
}
}
ksort($this->items);
return $this->items;
}
/**
* Parses a formatted date
*
* @see http://php.net/manual/en/datetime.formats.compound.php
* @see http://php.net/manual/en/function.strtotime.php
*
* @param string $date formatted date
*
* @return int Unix timestamp corresponding to a successfully parsed date,
* else current date and time
*/
public static function parseDate($date)
{
if (strtotime('@'.$date)) {
// Unix timestamp
return strtotime('@'.$date);
} else if (strtotime($date)) {
// attempt to parse a known compound date/time format
return strtotime($date);
}
// current date & time
return time();
}
/**
* Parses the value of a supposedly boolean attribute
*
* @param string $value Attribute value to evaluate
*
* @return mixed 'true' when the value is evaluated as true
* 'false' when the value is evaluated as false
* $this->defaultPub if the value is not a boolean
*/
public function parseBoolean($value) {
if (! $value) {
return false;
}
if (! is_string($value)) {
return true;
}
if (preg_match("/^(".self::TRUE_PATTERN.")$/i", $value)) {
return true;
}
if (preg_match("/^(".self::FALSE_PATTERN.")$/i", $value)) {
return false;
}
return $this->defaultPub;
}
/**
* Sanitizes the content of a string containing Netscape bookmarks
*
* This removes:
* - comment blocks
* - metadata: DOCTYPE, H1, META, TITLE
* - extra newlines, trailing spaces and tabs
*
* @param string $bookmarkString Original bookmark string
*
* @return string Sanitized bookmark string
*/
public static function sanitizeString($bookmarkString)
{
$sanitized = $bookmarkString;
// trim comments
$sanitized = preg_replace('@<!--.*-->@mis', '', $sanitized);
// trim unused metadata
$sanitized = preg_replace('@(<!DOCTYPE|<META|<TITLE|<H1|<P).*\n@i', '', $sanitized);
// trim whitespace
$sanitized = trim($sanitized);
// trim carriage returns, replace tabs by a single space
$sanitized = str_replace(array("\r", "\t"), array('',' '), $sanitized);
// convert multiline descriptions to one-line descriptions
// line feeds are converted to <br>
$sanitized = preg_replace_callback(
'@<DD>(.*?)<@mis',
function($match) {
return '<DD>'.str_replace("\n", '<br>', trim($match[1])).PHP_EOL.'<';
},
$sanitized
);
// keep one XML element per line to prepare for linear parsing
$sanitized = preg_replace('@>(\s*?)<@mis', ">\n<", $sanitized);
// concatenate all information related to the same entry on the same line
// e.g. <A HREF="...">My Link</A><DD>List<br>- item1<br>- item2
$sanitized = preg_replace('@\n<br>@mis', "<br>", $sanitized);
$sanitized = preg_replace('@\n<DD@i', '<DD', $sanitized);
return $sanitized;
}
}