]>
Commit | Line | Data |
---|---|---|
ca74886f V |
1 | <?php |
2 | /** | |
3 | * Data storage for links. | |
4 | * | |
5 | * This object behaves like an associative array. | |
6 | * | |
7 | * Example: | |
8 | * $myLinks = new LinkDB(); | |
9 | * echo $myLinks['20110826_161819']['title']; | |
10 | * foreach ($myLinks as $link) | |
11 | * echo $link['title'].' at url '.$link['url'].'; description:'.$link['description']; | |
12 | * | |
13 | * Available keys: | |
14 | * - description: description of the entry | |
15 | * - linkdate: date of the creation of this entry, in the form YYYYMMDD_HHMMSS | |
16 | * (e.g.'20110914_192317') | |
17 | * - private: Is this link private? 0=no, other value=yes | |
18 | * - tags: tags attached to this entry (separated by spaces) | |
19 | * - title Title of the link | |
49e62f22 A |
20 | * - url URL of the link. Used for displayable links (no redirector, relative, etc.). |
21 | * Can be absolute or relative. | |
ca74886f | 22 | * Relative URLs are permalinks (e.g.'?m-ukcw') |
49e62f22 | 23 | * - real_url Absolute processed URL. |
ca74886f V |
24 | * |
25 | * Implements 3 interfaces: | |
26 | * - ArrayAccess: behaves like an associative array; | |
27 | * - Countable: there is a count() method; | |
28 | * - Iterator: usable in foreach () loops. | |
29 | */ | |
30 | class LinkDB implements Iterator, Countable, ArrayAccess | |
31 | { | |
9c8752a2 | 32 | // Links are stored as a PHP serialized string |
07b6fa75 | 33 | private $_datastore; |
9c8752a2 V |
34 | |
35 | // Datastore PHP prefix | |
36 | protected static $phpPrefix = '<?php /* '; | |
37 | ||
38 | // Datastore PHP suffix | |
39 | protected static $phpSuffix = ' */ ?>'; | |
40 | ||
ca74886f V |
41 | // List of links (associative array) |
42 | // - key: link date (e.g. "20110823_124546"), | |
43 | // - value: associative array (keys: title, description...) | |
07b6fa75 | 44 | private $_links; |
ca74886f V |
45 | |
46 | // List of all recorded URLs (key=url, value=linkdate) | |
47 | // for fast reserve search (url-->linkdate) | |
07b6fa75 | 48 | private $_urls; |
ca74886f V |
49 | |
50 | // List of linkdate keys (for the Iterator interface implementation) | |
07b6fa75 | 51 | private $_keys; |
ca74886f | 52 | |
07b6fa75 V |
53 | // Position in the $this->_keys array (for the Iterator interface) |
54 | private $_position; | |
ca74886f V |
55 | |
56 | // Is the user logged in? (used to filter private links) | |
07b6fa75 | 57 | private $_loggedIn; |
ca74886f | 58 | |
9f15ca9e | 59 | // Hide public links |
07b6fa75 | 60 | private $_hidePublicLinks; |
9f15ca9e | 61 | |
90e5bd65 A |
62 | // link redirector set in user settings. |
63 | private $_redirector; | |
64 | ||
ca74886f V |
65 | /** |
66 | * Creates a new LinkDB | |
67 | * | |
68 | * Checks if the datastore exists; else, attempts to create a dummy one. | |
69 | * | |
90e5bd65 A |
70 | * @param string $datastore datastore file path. |
71 | * @param boolean $isLoggedIn is the user logged in? | |
72 | * @param boolean $hidePublicLinks if true all links are private. | |
73 | * @param string $redirector link redirector set in user settings. | |
ca74886f | 74 | */ |
90e5bd65 | 75 | function __construct($datastore, $isLoggedIn, $hidePublicLinks, $redirector = '') |
ca74886f | 76 | { |
07b6fa75 V |
77 | $this->_datastore = $datastore; |
78 | $this->_loggedIn = $isLoggedIn; | |
79 | $this->_hidePublicLinks = $hidePublicLinks; | |
90e5bd65 | 80 | $this->_redirector = $redirector; |
07b6fa75 V |
81 | $this->_checkDB(); |
82 | $this->_readDB(); | |
ca74886f V |
83 | } |
84 | ||
85 | /** | |
86 | * Countable - Counts elements of an object | |
87 | */ | |
88 | public function count() | |
89 | { | |
07b6fa75 | 90 | return count($this->_links); |
ca74886f V |
91 | } |
92 | ||
93 | /** | |
94 | * ArrayAccess - Assigns a value to the specified offset | |
95 | */ | |
96 | public function offsetSet($offset, $value) | |
97 | { | |
98 | // TODO: use exceptions instead of "die" | |
07b6fa75 | 99 | if (!$this->_loggedIn) { |
ca74886f V |
100 | die('You are not authorized to add a link.'); |
101 | } | |
102 | if (empty($value['linkdate']) || empty($value['url'])) { | |
103 | die('Internal Error: A link should always have a linkdate and URL.'); | |
104 | } | |
105 | if (empty($offset)) { | |
106 | die('You must specify a key.'); | |
107 | } | |
07b6fa75 V |
108 | $this->_links[$offset] = $value; |
109 | $this->_urls[$value['url']]=$offset; | |
ca74886f V |
110 | } |
111 | ||
112 | /** | |
113 | * ArrayAccess - Whether or not an offset exists | |
114 | */ | |
115 | public function offsetExists($offset) | |
116 | { | |
07b6fa75 | 117 | return array_key_exists($offset, $this->_links); |
ca74886f V |
118 | } |
119 | ||
120 | /** | |
121 | * ArrayAccess - Unsets an offset | |
122 | */ | |
123 | public function offsetUnset($offset) | |
124 | { | |
07b6fa75 | 125 | if (!$this->_loggedIn) { |
ca74886f V |
126 | // TODO: raise an exception |
127 | die('You are not authorized to delete a link.'); | |
128 | } | |
07b6fa75 V |
129 | $url = $this->_links[$offset]['url']; |
130 | unset($this->_urls[$url]); | |
131 | unset($this->_links[$offset]); | |
ca74886f V |
132 | } |
133 | ||
134 | /** | |
135 | * ArrayAccess - Returns the value at specified offset | |
136 | */ | |
137 | public function offsetGet($offset) | |
138 | { | |
07b6fa75 | 139 | return isset($this->_links[$offset]) ? $this->_links[$offset] : null; |
ca74886f V |
140 | } |
141 | ||
142 | /** | |
143 | * Iterator - Returns the current element | |
144 | */ | |
145 | function current() | |
146 | { | |
07b6fa75 | 147 | return $this->_links[$this->_keys[$this->_position]]; |
ca74886f V |
148 | } |
149 | ||
150 | /** | |
151 | * Iterator - Returns the key of the current element | |
152 | */ | |
153 | function key() | |
154 | { | |
07b6fa75 | 155 | return $this->_keys[$this->_position]; |
ca74886f V |
156 | } |
157 | ||
158 | /** | |
159 | * Iterator - Moves forward to next element | |
160 | */ | |
161 | function next() | |
162 | { | |
07b6fa75 | 163 | ++$this->_position; |
ca74886f V |
164 | } |
165 | ||
166 | /** | |
167 | * Iterator - Rewinds the Iterator to the first element | |
168 | * | |
169 | * Entries are sorted by date (latest first) | |
170 | */ | |
171 | function rewind() | |
172 | { | |
07b6fa75 V |
173 | $this->_keys = array_keys($this->_links); |
174 | rsort($this->_keys); | |
175 | $this->_position = 0; | |
ca74886f V |
176 | } |
177 | ||
178 | /** | |
179 | * Iterator - Checks if current position is valid | |
180 | */ | |
181 | function valid() | |
182 | { | |
07b6fa75 | 183 | return isset($this->_keys[$this->_position]); |
ca74886f V |
184 | } |
185 | ||
186 | /** | |
187 | * Checks if the DB directory and file exist | |
188 | * | |
189 | * If no DB file is found, creates a dummy DB. | |
190 | */ | |
07b6fa75 | 191 | private function _checkDB() |
ca74886f | 192 | { |
07b6fa75 | 193 | if (file_exists($this->_datastore)) { |
ca74886f V |
194 | return; |
195 | } | |
196 | ||
197 | // Create a dummy database for example | |
07b6fa75 | 198 | $this->_links = array(); |
ca74886f | 199 | $link = array( |
598376d4 A |
200 | 'title'=>' Shaarli: the personal, minimalist, super-fast, no-database delicious clone', |
201 | 'url'=>'https://github.com/shaarli/Shaarli/wiki', | |
202 | 'description'=>'Welcome to Shaarli! This is your first public bookmark. To edit or delete me, you must first login. | |
203 | ||
204 | To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page. | |
205 | ||
206 | You use the community supported version of the original Shaarli project, by Sebastien Sauvage.', | |
ca74886f | 207 | 'private'=>0, |
598376d4 | 208 | 'linkdate'=> date('Ymd_His'), |
ca74886f V |
209 | 'tags'=>'opensource software' |
210 | ); | |
07b6fa75 | 211 | $this->_links[$link['linkdate']] = $link; |
ca74886f V |
212 | |
213 | $link = array( | |
214 | 'title'=>'My secret stuff... - Pastebin.com', | |
215 | 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=', | |
598376d4 | 216 | 'description'=>'Shhhh! I\'m a private link only YOU can see. You can delete me too.', |
ca74886f | 217 | 'private'=>1, |
598376d4 | 218 | 'linkdate'=> date('Ymd_His', strtotime('-1 minute')), |
ca74886f V |
219 | 'tags'=>'secretstuff' |
220 | ); | |
07b6fa75 | 221 | $this->_links[$link['linkdate']] = $link; |
ca74886f V |
222 | |
223 | // Write database to disk | |
2e28269b | 224 | $this->writeDB(); |
ca74886f V |
225 | } |
226 | ||
227 | /** | |
228 | * Reads database from disk to memory | |
229 | */ | |
07b6fa75 | 230 | private function _readDB() |
ca74886f | 231 | { |
578a84bd | 232 | |
233 | // Public links are hidden and user not logged in => nothing to show | |
07b6fa75 V |
234 | if ($this->_hidePublicLinks && !$this->_loggedIn) { |
235 | $this->_links = array(); | |
578a84bd | 236 | return; |
237 | } | |
238 | ||
ca74886f V |
239 | // Read data |
240 | // Note that gzinflate is faster than gzuncompress. | |
241 | // See: http://www.php.net/manual/en/function.gzdeflate.php#96439 | |
07b6fa75 | 242 | $this->_links = array(); |
ca74886f | 243 | |
07b6fa75 V |
244 | if (file_exists($this->_datastore)) { |
245 | $this->_links = unserialize(gzinflate(base64_decode( | |
246 | substr(file_get_contents($this->_datastore), | |
9c8752a2 | 247 | strlen(self::$phpPrefix), -strlen(self::$phpSuffix))))); |
ca74886f V |
248 | } |
249 | ||
250 | // If user is not logged in, filter private links. | |
07b6fa75 | 251 | if (!$this->_loggedIn) { |
ca74886f | 252 | $toremove = array(); |
07b6fa75 | 253 | foreach ($this->_links as $link) { |
ca74886f V |
254 | if ($link['private'] != 0) { |
255 | $toremove[] = $link['linkdate']; | |
256 | } | |
257 | } | |
258 | foreach ($toremove as $linkdate) { | |
07b6fa75 | 259 | unset($this->_links[$linkdate]); |
ca74886f V |
260 | } |
261 | } | |
262 | ||
263 | // Keep the list of the mapping URLs-->linkdate up-to-date. | |
07b6fa75 V |
264 | $this->_urls = array(); |
265 | foreach ($this->_links as $link) { | |
266 | $this->_urls[$link['url']] = $link['linkdate']; | |
ca74886f | 267 | } |
5f85fcd8 A |
268 | |
269 | // Escape links data | |
07b6fa75 | 270 | foreach($this->_links as &$link) { |
90e5bd65 A |
271 | sanitizeLink($link); |
272 | // Do not use the redirector for internal links (Shaarli note URL starting with a '?'). | |
273 | if (!empty($this->_redirector) && !startsWith($link['url'], '?')) { | |
274 | $link['real_url'] = $this->_redirector . urlencode($link['url']); | |
275 | } | |
276 | else { | |
277 | $link['real_url'] = $link['url']; | |
278 | } | |
5f85fcd8 | 279 | } |
ca74886f V |
280 | } |
281 | ||
2e28269b V |
282 | /** |
283 | * Saves the database from memory to disk | |
284 | * | |
285 | * @throws IOException the datastore is not writable | |
286 | */ | |
287 | private function writeDB() | |
288 | { | |
289 | if (is_file($this->_datastore) && !is_writeable($this->_datastore)) { | |
290 | // The datastore exists but is not writeable | |
291 | throw new IOException($this->_datastore); | |
292 | } else if (!is_file($this->_datastore) && !is_writeable(dirname($this->_datastore))) { | |
293 | // The datastore does not exist and its parent directory is not writeable | |
294 | throw new IOException(dirname($this->_datastore)); | |
295 | } | |
296 | ||
297 | file_put_contents( | |
298 | $this->_datastore, | |
299 | self::$phpPrefix.base64_encode(gzdeflate(serialize($this->_links))).self::$phpSuffix | |
300 | ); | |
301 | ||
302 | } | |
303 | ||
ca74886f V |
304 | /** |
305 | * Saves the database from memory to disk | |
01e48f26 V |
306 | * |
307 | * @param string $pageCacheDir page cache directory | |
ca74886f | 308 | */ |
01e48f26 | 309 | public function savedb($pageCacheDir) |
ca74886f | 310 | { |
07b6fa75 | 311 | if (!$this->_loggedIn) { |
ca74886f V |
312 | // TODO: raise an Exception instead |
313 | die('You are not authorized to change the database.'); | |
314 | } | |
2e28269b V |
315 | |
316 | $this->writeDB(); | |
317 | ||
01e48f26 | 318 | invalidateCaches($pageCacheDir); |
ca74886f V |
319 | } |
320 | ||
321 | /** | |
322 | * Returns the link for a given URL, or False if it does not exist. | |
ef591e7e GV |
323 | * |
324 | * @param string $url URL to search for | |
325 | * | |
326 | * @return mixed the existing link if it exists, else 'false' | |
ca74886f V |
327 | */ |
328 | public function getLinkFromUrl($url) | |
329 | { | |
07b6fa75 V |
330 | if (isset($this->_urls[$url])) { |
331 | return $this->_links[$this->_urls[$url]]; | |
ca74886f V |
332 | } |
333 | return false; | |
334 | } | |
335 | ||
336 | /** | |
337 | * Returns the list of links corresponding to a full-text search | |
338 | * | |
339 | * Searches: | |
340 | * - in the URLs, title and description; | |
341 | * - are case-insensitive. | |
342 | * | |
343 | * Example: | |
344 | * print_r($mydb->filterFulltext('hollandais')); | |
345 | * | |
346 | * mb_convert_case($val, MB_CASE_LOWER, 'UTF-8') | |
347 | * - allows to perform searches on Unicode text | |
348 | * - see https://github.com/shaarli/Shaarli/issues/75 for examples | |
349 | */ | |
350 | public function filterFulltext($searchterms) | |
351 | { | |
352 | // FIXME: explode(' ',$searchterms) and perform a AND search. | |
353 | // FIXME: accept double-quotes to search for a string "as is"? | |
354 | $filtered = array(); | |
355 | $search = mb_convert_case($searchterms, MB_CASE_LOWER, 'UTF-8'); | |
ddfc4004 | 356 | $keys = array('title', 'description', 'url', 'tags'); |
ca74886f | 357 | |
07b6fa75 | 358 | foreach ($this->_links as $link) { |
ca74886f V |
359 | $found = false; |
360 | ||
361 | foreach ($keys as $key) { | |
362 | if (strpos(mb_convert_case($link[$key], MB_CASE_LOWER, 'UTF-8'), | |
363 | $search) !== false) { | |
364 | $found = true; | |
365 | } | |
366 | } | |
367 | ||
368 | if ($found) { | |
369 | $filtered[$link['linkdate']] = $link; | |
370 | } | |
371 | } | |
372 | krsort($filtered); | |
373 | return $filtered; | |
374 | } | |
375 | ||
376 | /** | |
377 | * Returns the list of links associated with a given list of tags | |
378 | * | |
379 | * You can specify one or more tags, separated by space or a comma, e.g. | |
380 | * print_r($mydb->filterTags('linux programming')); | |
381 | */ | |
382 | public function filterTags($tags, $casesensitive=false) | |
383 | { | |
384 | // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek) | |
385 | // FIXME: is $casesensitive ever true? | |
386 | $t = str_replace( | |
387 | ',', ' ', | |
388 | ($casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8')) | |
389 | ); | |
390 | ||
391 | $searchtags = explode(' ', $t); | |
392 | $filtered = array(); | |
393 | ||
07b6fa75 | 394 | foreach ($this->_links as $l) { |
ca74886f V |
395 | $linktags = explode( |
396 | ' ', | |
397 | ($casesensitive ? $l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER, 'UTF-8')) | |
398 | ); | |
399 | ||
400 | if (count(array_intersect($linktags, $searchtags)) == count($searchtags)) { | |
401 | $filtered[$l['linkdate']] = $l; | |
402 | } | |
403 | } | |
404 | krsort($filtered); | |
405 | return $filtered; | |
406 | } | |
407 | ||
408 | ||
409 | /** | |
410 | * Returns the list of articles for a given day, chronologically sorted | |
411 | * | |
412 | * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g. | |
413 | * print_r($mydb->filterDay('20120125')); | |
414 | */ | |
415 | public function filterDay($day) | |
416 | { | |
9186ab95 V |
417 | if (! checkDateFormat('Ymd', $day)) { |
418 | throw new Exception('Invalid date format'); | |
419 | } | |
420 | ||
ca74886f | 421 | $filtered = array(); |
07b6fa75 | 422 | foreach ($this->_links as $l) { |
ca74886f V |
423 | if (startsWith($l['linkdate'], $day)) { |
424 | $filtered[$l['linkdate']] = $l; | |
425 | } | |
426 | } | |
427 | ksort($filtered); | |
428 | return $filtered; | |
429 | } | |
430 | ||
431 | /** | |
432 | * Returns the article corresponding to a smallHash | |
433 | */ | |
434 | public function filterSmallHash($smallHash) | |
435 | { | |
436 | $filtered = array(); | |
07b6fa75 | 437 | foreach ($this->_links as $l) { |
ca74886f V |
438 | if ($smallHash == smallHash($l['linkdate'])) { |
439 | // Yes, this is ugly and slow | |
440 | $filtered[$l['linkdate']] = $l; | |
441 | return $filtered; | |
442 | } | |
443 | } | |
444 | return $filtered; | |
445 | } | |
446 | ||
447 | /** | |
448 | * Returns the list of all tags | |
449 | * Output: associative array key=tags, value=0 | |
450 | */ | |
451 | public function allTags() | |
452 | { | |
453 | $tags = array(); | |
07b6fa75 | 454 | foreach ($this->_links as $link) { |
ca74886f V |
455 | foreach (explode(' ', $link['tags']) as $tag) { |
456 | if (!empty($tag)) { | |
457 | $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] + 1); | |
458 | } | |
459 | } | |
460 | } | |
461 | // Sort tags by usage (most used tag first) | |
462 | arsort($tags); | |
463 | return $tags; | |
464 | } | |
465 | ||
466 | /** | |
467 | * Returns the list of days containing articles (oldest first) | |
468 | * Output: An array containing days (in format YYYYMMDD). | |
469 | */ | |
470 | public function days() | |
471 | { | |
472 | $linkDays = array(); | |
07b6fa75 | 473 | foreach (array_keys($this->_links) as $day) { |
ca74886f V |
474 | $linkDays[substr($day, 0, 8)] = 0; |
475 | } | |
476 | $linkDays = array_keys($linkDays); | |
477 | sort($linkDays); | |
478 | return $linkDays; | |
479 | } | |
480 | } |