]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkDB.php
Working on shaarli/Shaarli#224
[github/shaarli/Shaarli.git] / application / LinkDB.php
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
20 * - url URL of the link. Can be absolute or relative.
21 * Relative URLs are permalinks (e.g.'?m-ukcw')
22 *
23 * Implements 3 interfaces:
24 * - ArrayAccess: behaves like an associative array;
25 * - Countable: there is a count() method;
26 * - Iterator: usable in foreach () loops.
27 */
28 class LinkDB implements Iterator, Countable, ArrayAccess
29 {
30 // List of links (associative array)
31 // - key: link date (e.g. "20110823_124546"),
32 // - value: associative array (keys: title, description...)
33 private $links;
34
35 // List of all recorded URLs (key=url, value=linkdate)
36 // for fast reserve search (url-->linkdate)
37 private $urls;
38
39 // List of linkdate keys (for the Iterator interface implementation)
40 private $keys;
41
42 // Position in the $this->keys array (for the Iterator interface)
43 private $position;
44
45 // Is the user logged in? (used to filter private links)
46 private $loggedIn;
47
48 /**
49 * Creates a new LinkDB
50 *
51 * Checks if the datastore exists; else, attempts to create a dummy one.
52 *
53 * @param $isLoggedIn is the user logged in?
54 */
55 function __construct($isLoggedIn)
56 {
57 // FIXME: do not access $GLOBALS, pass the datastore instead
58 $this->loggedIn = $isLoggedIn;
59 $this->checkDB();
60 $this->readdb();
61 }
62
63 /**
64 * Countable - Counts elements of an object
65 */
66 public function count()
67 {
68 return count($this->links);
69 }
70
71 /**
72 * ArrayAccess - Assigns a value to the specified offset
73 */
74 public function offsetSet($offset, $value)
75 {
76 // TODO: use exceptions instead of "die"
77 if (!$this->loggedIn) {
78 die('You are not authorized to add a link.');
79 }
80 if (empty($value['linkdate']) || empty($value['url'])) {
81 die('Internal Error: A link should always have a linkdate and URL.');
82 }
83 if (empty($offset)) {
84 die('You must specify a key.');
85 }
86 $this->links[$offset] = $value;
87 $this->urls[$value['url']]=$offset;
88 }
89
90 /**
91 * ArrayAccess - Whether or not an offset exists
92 */
93 public function offsetExists($offset)
94 {
95 return array_key_exists($offset, $this->links);
96 }
97
98 /**
99 * ArrayAccess - Unsets an offset
100 */
101 public function offsetUnset($offset)
102 {
103 if (!$this->loggedIn) {
104 // TODO: raise an exception
105 die('You are not authorized to delete a link.');
106 }
107 $url = $this->links[$offset]['url'];
108 unset($this->urls[$url]);
109 unset($this->links[$offset]);
110 }
111
112 /**
113 * ArrayAccess - Returns the value at specified offset
114 */
115 public function offsetGet($offset)
116 {
117 return isset($this->links[$offset]) ? $this->links[$offset] : null;
118 }
119
120 /**
121 * Iterator - Returns the current element
122 */
123 function current()
124 {
125 return $this->links[$this->keys[$this->position]];
126 }
127
128 /**
129 * Iterator - Returns the key of the current element
130 */
131 function key()
132 {
133 return $this->keys[$this->position];
134 }
135
136 /**
137 * Iterator - Moves forward to next element
138 */
139 function next()
140 {
141 ++$this->position;
142 }
143
144 /**
145 * Iterator - Rewinds the Iterator to the first element
146 *
147 * Entries are sorted by date (latest first)
148 */
149 function rewind()
150 {
151 $this->keys = array_keys($this->links);
152 rsort($this->keys);
153 $this->position = 0;
154 }
155
156 /**
157 * Iterator - Checks if current position is valid
158 */
159 function valid()
160 {
161 return isset($this->keys[$this->position]);
162 }
163
164 /**
165 * Checks if the DB directory and file exist
166 *
167 * If no DB file is found, creates a dummy DB.
168 */
169 private function checkDB()
170 {
171 if (file_exists($GLOBALS['config']['DATASTORE'])) {
172 return;
173 }
174
175 // Create a dummy database for example
176 $this->links = array();
177 $link = array(
178 'title'=>'Shaarli - sebsauvage.net',
179 'url'=>'http://sebsauvage.net/wiki/doku.php?id=php:shaarli',
180 'description'=>'Welcome to Shaarli! This is a bookmark. To edit or delete me, you must first login.',
181 'private'=>0,
182 'linkdate'=>'20110914_190000',
183 'tags'=>'opensource software'
184 );
185 $this->links[$link['linkdate']] = $link;
186
187 $link = array(
188 'title'=>'My secret stuff... - Pastebin.com',
189 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
190 'description'=>'SShhhh!! I\'m a private link only YOU can see. You can delete me too.',
191 'private'=>1,
192 'linkdate'=>'20110914_074522',
193 'tags'=>'secretstuff'
194 );
195 $this->links[$link['linkdate']] = $link;
196
197 // Write database to disk
198 // TODO: raise an exception if the file is not write-able
199 file_put_contents(
200 // FIXME: do not use $GLOBALS
201 $GLOBALS['config']['DATASTORE'],
202 PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX
203 );
204 }
205
206 /**
207 * Reads database from disk to memory
208 */
209 private function readdb()
210 {
211
212 // Public links are hidden and user not logged in => nothing to show
213 if ($GLOBALS['config']['HIDE_PUBLIC_LINKS'] && !isLoggedIn()) {
214 $this->links = array();
215 return;
216 }
217
218 // Read data
219 // Note that gzinflate is faster than gzuncompress.
220 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
221 // FIXME: do not use $GLOBALS
222 $this->links = array();
223
224 if (file_exists($GLOBALS['config']['DATASTORE'])) {
225 $this->links = unserialize(gzinflate(base64_decode(
226 substr(file_get_contents($GLOBALS['config']['DATASTORE']),
227 strlen(PHPPREFIX), -strlen(PHPSUFFIX)))));
228 }
229
230 // If user is not logged in, filter private links.
231 if (!$this->loggedIn) {
232 $toremove = array();
233 foreach ($this->links as $link) {
234 if ($link['private'] != 0) {
235 $toremove[] = $link['linkdate'];
236 }
237 }
238 foreach ($toremove as $linkdate) {
239 unset($this->links[$linkdate]);
240 }
241 }
242
243 // Keep the list of the mapping URLs-->linkdate up-to-date.
244 $this->urls = array();
245 foreach ($this->links as $link) {
246 $this->urls[$link['url']] = $link['linkdate'];
247 }
248
249 // Escape links data
250 foreach($this->links as &$link) {
251 sanitizeLink($link);
252 }
253 }
254
255 /**
256 * Saves the database from memory to disk
257 */
258 public function savedb()
259 {
260 if (!$this->loggedIn) {
261 // TODO: raise an Exception instead
262 die('You are not authorized to change the database.');
263 }
264 file_put_contents(
265 $GLOBALS['config']['DATASTORE'],
266 PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX
267 );
268 invalidateCaches();
269 }
270
271 /**
272 * Returns the link for a given URL, or False if it does not exist.
273 */
274 public function getLinkFromUrl($url)
275 {
276 if (isset($this->urls[$url])) {
277 return $this->links[$this->urls[$url]];
278 }
279 return false;
280 }
281
282 /**
283 * Returns the list of links corresponding to a full-text search
284 *
285 * Searches:
286 * - in the URLs, title and description;
287 * - are case-insensitive.
288 *
289 * Example:
290 * print_r($mydb->filterFulltext('hollandais'));
291 *
292 * mb_convert_case($val, MB_CASE_LOWER, 'UTF-8')
293 * - allows to perform searches on Unicode text
294 * - see https://github.com/shaarli/Shaarli/issues/75 for examples
295 */
296 public function filterFulltext($searchterms)
297 {
298 // FIXME: explode(' ',$searchterms) and perform a AND search.
299 // FIXME: accept double-quotes to search for a string "as is"?
300 $filtered = array();
301 $search = mb_convert_case($searchterms, MB_CASE_LOWER, 'UTF-8');
302 $keys = ['title', 'description', 'url', 'tags'];
303
304 foreach ($this->links as $link) {
305 $found = false;
306
307 foreach ($keys as $key) {
308 if (strpos(mb_convert_case($link[$key], MB_CASE_LOWER, 'UTF-8'),
309 $search) !== false) {
310 $found = true;
311 }
312 }
313
314 if ($found) {
315 $filtered[$link['linkdate']] = $link;
316 }
317 }
318 krsort($filtered);
319 return $filtered;
320 }
321
322 /**
323 * Returns the list of links associated with a given list of tags
324 *
325 * You can specify one or more tags, separated by space or a comma, e.g.
326 * print_r($mydb->filterTags('linux programming'));
327 */
328 public function filterTags($tags, $casesensitive=false)
329 {
330 // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
331 // FIXME: is $casesensitive ever true?
332 $t = str_replace(
333 ',', ' ',
334 ($casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8'))
335 );
336
337 $searchtags = explode(' ', $t);
338 $filtered = array();
339
340 foreach ($this->links as $l) {
341 $linktags = explode(
342 ' ',
343 ($casesensitive ? $l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER, 'UTF-8'))
344 );
345
346 if (count(array_intersect($linktags, $searchtags)) == count($searchtags)) {
347 $filtered[$l['linkdate']] = $l;
348 }
349 }
350 krsort($filtered);
351 return $filtered;
352 }
353
354
355 /**
356 * Returns the list of articles for a given day, chronologically sorted
357 *
358 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
359 * print_r($mydb->filterDay('20120125'));
360 */
361 public function filterDay($day)
362 {
363 // TODO: check input format
364 $filtered = array();
365 foreach ($this->links as $l) {
366 if (startsWith($l['linkdate'], $day)) {
367 $filtered[$l['linkdate']] = $l;
368 }
369 }
370 ksort($filtered);
371 return $filtered;
372 }
373
374 /**
375 * Returns the article corresponding to a smallHash
376 */
377 public function filterSmallHash($smallHash)
378 {
379 $filtered = array();
380 foreach ($this->links as $l) {
381 if ($smallHash == smallHash($l['linkdate'])) {
382 // Yes, this is ugly and slow
383 $filtered[$l['linkdate']] = $l;
384 return $filtered;
385 }
386 }
387 return $filtered;
388 }
389
390 /**
391 * Returns the list of all tags
392 * Output: associative array key=tags, value=0
393 */
394 public function allTags()
395 {
396 $tags = array();
397 foreach ($this->links as $link) {
398 foreach (explode(' ', $link['tags']) as $tag) {
399 if (!empty($tag)) {
400 $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] + 1);
401 }
402 }
403 }
404 // Sort tags by usage (most used tag first)
405 arsort($tags);
406 return $tags;
407 }
408
409 /**
410 * Returns the list of days containing articles (oldest first)
411 * Output: An array containing days (in format YYYYMMDD).
412 */
413 public function days()
414 {
415 $linkDays = array();
416 foreach (array_keys($this->links) as $day) {
417 $linkDays[substr($day, 0, 8)] = 0;
418 }
419 $linkDays = array_keys($linkDays);
420 sort($linkDays);
421 return $linkDays;
422 }
423 }
424 ?>