]>
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 | 34 | |
205a4277 V |
35 | // Link date storage format |
36 | const LINK_DATE_FORMAT = 'Ymd_His'; | |
37 | ||
9c8752a2 V |
38 | // Datastore PHP prefix |
39 | protected static $phpPrefix = '<?php /* '; | |
40 | ||
41 | // Datastore PHP suffix | |
42 | protected static $phpSuffix = ' */ ?>'; | |
43 | ||
ca74886f V |
44 | // List of links (associative array) |
45 | // - key: link date (e.g. "20110823_124546"), | |
46 | // - value: associative array (keys: title, description...) | |
07b6fa75 | 47 | private $_links; |
ca74886f V |
48 | |
49 | // List of all recorded URLs (key=url, value=linkdate) | |
50 | // for fast reserve search (url-->linkdate) | |
07b6fa75 | 51 | private $_urls; |
ca74886f V |
52 | |
53 | // List of linkdate keys (for the Iterator interface implementation) | |
07b6fa75 | 54 | private $_keys; |
ca74886f | 55 | |
07b6fa75 V |
56 | // Position in the $this->_keys array (for the Iterator interface) |
57 | private $_position; | |
ca74886f V |
58 | |
59 | // Is the user logged in? (used to filter private links) | |
07b6fa75 | 60 | private $_loggedIn; |
ca74886f | 61 | |
9f15ca9e | 62 | // Hide public links |
07b6fa75 | 63 | private $_hidePublicLinks; |
9f15ca9e | 64 | |
90e5bd65 A |
65 | // link redirector set in user settings. |
66 | private $_redirector; | |
67 | ||
043eae70 A |
68 | /** |
69 | * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched. | |
70 | * | |
71 | * Example: | |
72 | * anonym.to needs clean URL while dereferer.org needs urlencoded URL. | |
73 | * | |
74 | * @var boolean $redirectorEncode parameter: true or false | |
75 | */ | |
76 | private $redirectorEncode; | |
77 | ||
ca74886f V |
78 | /** |
79 | * Creates a new LinkDB | |
80 | * | |
81 | * Checks if the datastore exists; else, attempts to create a dummy one. | |
82 | * | |
043eae70 A |
83 | * @param string $datastore datastore file path. |
84 | * @param boolean $isLoggedIn is the user logged in? | |
85 | * @param boolean $hidePublicLinks if true all links are private. | |
86 | * @param string $redirector link redirector set in user settings. | |
87 | * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true). | |
ca74886f | 88 | */ |
043eae70 A |
89 | function __construct( |
90 | $datastore, | |
91 | $isLoggedIn, | |
92 | $hidePublicLinks, | |
93 | $redirector = '', | |
94 | $redirectorEncode = true | |
95 | ) | |
ca74886f | 96 | { |
07b6fa75 V |
97 | $this->_datastore = $datastore; |
98 | $this->_loggedIn = $isLoggedIn; | |
99 | $this->_hidePublicLinks = $hidePublicLinks; | |
90e5bd65 | 100 | $this->_redirector = $redirector; |
043eae70 | 101 | $this->redirectorEncode = $redirectorEncode === true; |
07b6fa75 V |
102 | $this->_checkDB(); |
103 | $this->_readDB(); | |
ca74886f V |
104 | } |
105 | ||
106 | /** | |
107 | * Countable - Counts elements of an object | |
108 | */ | |
109 | public function count() | |
110 | { | |
07b6fa75 | 111 | return count($this->_links); |
ca74886f V |
112 | } |
113 | ||
114 | /** | |
115 | * ArrayAccess - Assigns a value to the specified offset | |
116 | */ | |
117 | public function offsetSet($offset, $value) | |
118 | { | |
119 | // TODO: use exceptions instead of "die" | |
07b6fa75 | 120 | if (!$this->_loggedIn) { |
ca74886f V |
121 | die('You are not authorized to add a link.'); |
122 | } | |
123 | if (empty($value['linkdate']) || empty($value['url'])) { | |
124 | die('Internal Error: A link should always have a linkdate and URL.'); | |
125 | } | |
126 | if (empty($offset)) { | |
127 | die('You must specify a key.'); | |
128 | } | |
07b6fa75 V |
129 | $this->_links[$offset] = $value; |
130 | $this->_urls[$value['url']]=$offset; | |
ca74886f V |
131 | } |
132 | ||
133 | /** | |
134 | * ArrayAccess - Whether or not an offset exists | |
135 | */ | |
136 | public function offsetExists($offset) | |
137 | { | |
07b6fa75 | 138 | return array_key_exists($offset, $this->_links); |
ca74886f V |
139 | } |
140 | ||
141 | /** | |
142 | * ArrayAccess - Unsets an offset | |
143 | */ | |
144 | public function offsetUnset($offset) | |
145 | { | |
07b6fa75 | 146 | if (!$this->_loggedIn) { |
ca74886f V |
147 | // TODO: raise an exception |
148 | die('You are not authorized to delete a link.'); | |
149 | } | |
07b6fa75 V |
150 | $url = $this->_links[$offset]['url']; |
151 | unset($this->_urls[$url]); | |
152 | unset($this->_links[$offset]); | |
ca74886f V |
153 | } |
154 | ||
155 | /** | |
156 | * ArrayAccess - Returns the value at specified offset | |
157 | */ | |
158 | public function offsetGet($offset) | |
159 | { | |
07b6fa75 | 160 | return isset($this->_links[$offset]) ? $this->_links[$offset] : null; |
ca74886f V |
161 | } |
162 | ||
163 | /** | |
164 | * Iterator - Returns the current element | |
165 | */ | |
166 | function current() | |
167 | { | |
07b6fa75 | 168 | return $this->_links[$this->_keys[$this->_position]]; |
ca74886f V |
169 | } |
170 | ||
171 | /** | |
172 | * Iterator - Returns the key of the current element | |
173 | */ | |
174 | function key() | |
175 | { | |
07b6fa75 | 176 | return $this->_keys[$this->_position]; |
ca74886f V |
177 | } |
178 | ||
179 | /** | |
180 | * Iterator - Moves forward to next element | |
181 | */ | |
182 | function next() | |
183 | { | |
07b6fa75 | 184 | ++$this->_position; |
ca74886f V |
185 | } |
186 | ||
187 | /** | |
188 | * Iterator - Rewinds the Iterator to the first element | |
189 | * | |
190 | * Entries are sorted by date (latest first) | |
191 | */ | |
192 | function rewind() | |
193 | { | |
07b6fa75 V |
194 | $this->_keys = array_keys($this->_links); |
195 | rsort($this->_keys); | |
196 | $this->_position = 0; | |
ca74886f V |
197 | } |
198 | ||
199 | /** | |
200 | * Iterator - Checks if current position is valid | |
201 | */ | |
202 | function valid() | |
203 | { | |
07b6fa75 | 204 | return isset($this->_keys[$this->_position]); |
ca74886f V |
205 | } |
206 | ||
207 | /** | |
208 | * Checks if the DB directory and file exist | |
209 | * | |
210 | * If no DB file is found, creates a dummy DB. | |
211 | */ | |
07b6fa75 | 212 | private function _checkDB() |
ca74886f | 213 | { |
07b6fa75 | 214 | if (file_exists($this->_datastore)) { |
ca74886f V |
215 | return; |
216 | } | |
217 | ||
218 | // Create a dummy database for example | |
07b6fa75 | 219 | $this->_links = array(); |
ca74886f | 220 | $link = array( |
598376d4 A |
221 | 'title'=>' Shaarli: the personal, minimalist, super-fast, no-database delicious clone', |
222 | 'url'=>'https://github.com/shaarli/Shaarli/wiki', | |
223 | 'description'=>'Welcome to Shaarli! This is your first public bookmark. To edit or delete me, you must first login. | |
224 | ||
225 | To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page. | |
226 | ||
227 | You use the community supported version of the original Shaarli project, by Sebastien Sauvage.', | |
ca74886f | 228 | 'private'=>0, |
598376d4 | 229 | 'linkdate'=> date('Ymd_His'), |
ca74886f V |
230 | 'tags'=>'opensource software' |
231 | ); | |
07b6fa75 | 232 | $this->_links[$link['linkdate']] = $link; |
ca74886f V |
233 | |
234 | $link = array( | |
235 | 'title'=>'My secret stuff... - Pastebin.com', | |
236 | 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=', | |
598376d4 | 237 | 'description'=>'Shhhh! I\'m a private link only YOU can see. You can delete me too.', |
ca74886f | 238 | 'private'=>1, |
598376d4 | 239 | 'linkdate'=> date('Ymd_His', strtotime('-1 minute')), |
ca74886f V |
240 | 'tags'=>'secretstuff' |
241 | ); | |
07b6fa75 | 242 | $this->_links[$link['linkdate']] = $link; |
ca74886f V |
243 | |
244 | // Write database to disk | |
2e28269b | 245 | $this->writeDB(); |
ca74886f V |
246 | } |
247 | ||
248 | /** | |
249 | * Reads database from disk to memory | |
250 | */ | |
07b6fa75 | 251 | private function _readDB() |
ca74886f | 252 | { |
578a84bd | 253 | |
254 | // Public links are hidden and user not logged in => nothing to show | |
07b6fa75 V |
255 | if ($this->_hidePublicLinks && !$this->_loggedIn) { |
256 | $this->_links = array(); | |
578a84bd | 257 | return; |
258 | } | |
259 | ||
ca74886f V |
260 | // Read data |
261 | // Note that gzinflate is faster than gzuncompress. | |
262 | // See: http://www.php.net/manual/en/function.gzdeflate.php#96439 | |
07b6fa75 | 263 | $this->_links = array(); |
ca74886f | 264 | |
07b6fa75 V |
265 | if (file_exists($this->_datastore)) { |
266 | $this->_links = unserialize(gzinflate(base64_decode( | |
267 | substr(file_get_contents($this->_datastore), | |
9c8752a2 | 268 | strlen(self::$phpPrefix), -strlen(self::$phpSuffix))))); |
ca74886f V |
269 | } |
270 | ||
271 | // If user is not logged in, filter private links. | |
07b6fa75 | 272 | if (!$this->_loggedIn) { |
ca74886f | 273 | $toremove = array(); |
07b6fa75 | 274 | foreach ($this->_links as $link) { |
ca74886f V |
275 | if ($link['private'] != 0) { |
276 | $toremove[] = $link['linkdate']; | |
277 | } | |
278 | } | |
279 | foreach ($toremove as $linkdate) { | |
07b6fa75 | 280 | unset($this->_links[$linkdate]); |
ca74886f V |
281 | } |
282 | } | |
283 | ||
07b6fa75 | 284 | $this->_urls = array(); |
510377d2 A |
285 | foreach ($this->_links as &$link) { |
286 | // Keep the list of the mapping URLs-->linkdate up-to-date. | |
07b6fa75 | 287 | $this->_urls[$link['url']] = $link['linkdate']; |
195acf9f | 288 | |
510377d2 | 289 | // Sanitize data fields. |
90e5bd65 | 290 | sanitizeLink($link); |
195acf9f A |
291 | |
292 | // Remove private tags if the user is not logged in. | |
293 | if (! $this->_loggedIn) { | |
9866b408 | 294 | $link['tags'] = preg_replace('/(^|\s+)\.[^($|\s)]+\s*/', ' ', $link['tags']); |
195acf9f A |
295 | } |
296 | ||
90e5bd65 A |
297 | // Do not use the redirector for internal links (Shaarli note URL starting with a '?'). |
298 | if (!empty($this->_redirector) && !startsWith($link['url'], '?')) { | |
043eae70 A |
299 | $link['real_url'] = $this->_redirector; |
300 | if ($this->redirectorEncode) { | |
301 | $link['real_url'] .= urlencode(unescape($link['url'])); | |
302 | } else { | |
303 | $link['real_url'] .= $link['url']; | |
304 | } | |
90e5bd65 A |
305 | } |
306 | else { | |
307 | $link['real_url'] = $link['url']; | |
308 | } | |
5f85fcd8 | 309 | } |
ca74886f V |
310 | } |
311 | ||
2e28269b V |
312 | /** |
313 | * Saves the database from memory to disk | |
314 | * | |
315 | * @throws IOException the datastore is not writable | |
316 | */ | |
317 | private function writeDB() | |
318 | { | |
319 | if (is_file($this->_datastore) && !is_writeable($this->_datastore)) { | |
320 | // The datastore exists but is not writeable | |
321 | throw new IOException($this->_datastore); | |
322 | } else if (!is_file($this->_datastore) && !is_writeable(dirname($this->_datastore))) { | |
323 | // The datastore does not exist and its parent directory is not writeable | |
324 | throw new IOException(dirname($this->_datastore)); | |
325 | } | |
326 | ||
327 | file_put_contents( | |
328 | $this->_datastore, | |
329 | self::$phpPrefix.base64_encode(gzdeflate(serialize($this->_links))).self::$phpSuffix | |
330 | ); | |
331 | ||
332 | } | |
333 | ||
ca74886f V |
334 | /** |
335 | * Saves the database from memory to disk | |
01e48f26 V |
336 | * |
337 | * @param string $pageCacheDir page cache directory | |
ca74886f | 338 | */ |
01e48f26 | 339 | public function savedb($pageCacheDir) |
ca74886f | 340 | { |
07b6fa75 | 341 | if (!$this->_loggedIn) { |
ca74886f V |
342 | // TODO: raise an Exception instead |
343 | die('You are not authorized to change the database.'); | |
344 | } | |
2e28269b V |
345 | |
346 | $this->writeDB(); | |
347 | ||
01e48f26 | 348 | invalidateCaches($pageCacheDir); |
ca74886f V |
349 | } |
350 | ||
351 | /** | |
352 | * Returns the link for a given URL, or False if it does not exist. | |
ef591e7e GV |
353 | * |
354 | * @param string $url URL to search for | |
355 | * | |
356 | * @return mixed the existing link if it exists, else 'false' | |
ca74886f V |
357 | */ |
358 | public function getLinkFromUrl($url) | |
359 | { | |
07b6fa75 V |
360 | if (isset($this->_urls[$url])) { |
361 | return $this->_links[$this->_urls[$url]]; | |
ca74886f V |
362 | } |
363 | return false; | |
364 | } | |
365 | ||
366 | /** | |
528a6f8a | 367 | * Returns the shaare corresponding to a smallHash. |
ca74886f | 368 | * |
528a6f8a A |
369 | * @param string $request QUERY_STRING server parameter. |
370 | * | |
371 | * @return array $filtered array containing permalink data. | |
372 | * | |
373 | * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link. | |
374 | */ | |
375 | public function filterHash($request) | |
376 | { | |
377 | $request = substr($request, 0, 6); | |
378 | $linkFilter = new LinkFilter($this->_links); | |
379 | return $linkFilter->filter(LinkFilter::$FILTER_HASH, $request); | |
380 | } | |
381 | ||
382 | /** | |
383 | * Returns the list of articles for a given day. | |
384 | * | |
385 | * @param string $request day to filter. Format: YYYYMMDD. | |
386 | * | |
387 | * @return array list of shaare found. | |
388 | */ | |
389 | public function filterDay($request) { | |
390 | $linkFilter = new LinkFilter($this->_links); | |
391 | return $linkFilter->filter(LinkFilter::$FILTER_DAY, $request); | |
392 | } | |
393 | ||
394 | /** | |
395 | * Filter links according to search parameters. | |
396 | * | |
397 | * @param array $filterRequest Search request content. Supported keys: | |
398 | * - searchtags: list of tags | |
399 | * - searchterm: term search | |
822bffce A |
400 | * @param bool $casesensitive Optional: Perform case sensitive filter |
401 | * @param bool $privateonly Optional: Returns private links only if true. | |
ca74886f | 402 | * |
528a6f8a | 403 | * @return array filtered links, all links if no suitable filter was provided. |
ca74886f | 404 | */ |
528a6f8a | 405 | public function filterSearch($filterRequest = array(), $casesensitive = false, $privateonly = false) |
55d0a5c4 | 406 | { |
528a6f8a A |
407 | // Filter link database according to parameters. |
408 | $searchtags = !empty($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : ''; | |
409 | $searchterm = !empty($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : ''; | |
410 | ||
411 | // Search tags + fullsearch. | |
9ccca401 | 412 | if (! empty($searchtags) && ! empty($searchterm)) { |
528a6f8a A |
413 | $type = LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT; |
414 | $request = array($searchtags, $searchterm); | |
415 | } | |
416 | // Search by tags. | |
417 | elseif (! empty($searchtags)) { | |
418 | $type = LinkFilter::$FILTER_TAG; | |
419 | $request = $searchtags; | |
420 | } | |
421 | // Fulltext search. | |
422 | elseif (! empty($searchterm)) { | |
423 | $type = LinkFilter::$FILTER_TEXT; | |
424 | $request = $searchterm; | |
425 | } | |
426 | // Otherwise, display without filtering. | |
427 | else { | |
428 | $type = ''; | |
429 | $request = ''; | |
430 | } | |
431 | ||
55d0a5c4 | 432 | $linkFilter = new LinkFilter($this->_links); |
c51fae92 | 433 | return $linkFilter->filter($type, $request, $casesensitive, $privateonly); |
ca74886f V |
434 | } |
435 | ||
436 | /** | |
437 | * Returns the list of all tags | |
438 | * Output: associative array key=tags, value=0 | |
439 | */ | |
440 | public function allTags() | |
441 | { | |
442 | $tags = array(); | |
b1eb5d1d | 443 | $caseMapping = array(); |
07b6fa75 | 444 | foreach ($this->_links as $link) { |
4b35853d | 445 | foreach (preg_split('/\s+/', $link['tags'], 0, PREG_SPLIT_NO_EMPTY) as $tag) { |
b1eb5d1d A |
446 | if (empty($tag)) { |
447 | continue; | |
ca74886f | 448 | } |
b1eb5d1d A |
449 | // The first case found will be displayed. |
450 | if (!isset($caseMapping[strtolower($tag)])) { | |
451 | $caseMapping[strtolower($tag)] = $tag; | |
452 | $tags[$caseMapping[strtolower($tag)]] = 0; | |
453 | } | |
454 | $tags[$caseMapping[strtolower($tag)]]++; | |
ca74886f V |
455 | } |
456 | } | |
457 | // Sort tags by usage (most used tag first) | |
458 | arsort($tags); | |
459 | return $tags; | |
460 | } | |
461 | ||
462 | /** | |
463 | * Returns the list of days containing articles (oldest first) | |
464 | * Output: An array containing days (in format YYYYMMDD). | |
465 | */ | |
466 | public function days() | |
467 | { | |
468 | $linkDays = array(); | |
07b6fa75 | 469 | foreach (array_keys($this->_links) as $day) { |
ca74886f V |
470 | $linkDays[substr($day, 0, 8)] = 0; |
471 | } | |
472 | $linkDays = array_keys($linkDays); | |
473 | sort($linkDays); | |
510377d2 | 474 | |
ca74886f V |
475 | return $linkDays; |
476 | } | |
477 | } |