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