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