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