]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkDB.php
cf91ad481ddb84db88da8ed312b3c9ba0a7b3858
3 * Data storage for links.
5 * This object behaves like an associative array.
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'];
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')
23 * Implements 3 interfaces:
24 * - ArrayAccess: behaves like an associative array;
25 * - Countable: there is a count() method;
26 * - Iterator: usable in foreach () loops.
28 class LinkDB
implements Iterator
, Countable
, ArrayAccess
30 // List of links (associative array)
31 // - key: link date (e.g. "20110823_124546"),
32 // - value: associative array (keys: title, description...)
35 // List of all recorded URLs (key=url, value=linkdate)
36 // for fast reserve search (url-->linkdate)
39 // List of linkdate keys (for the Iterator interface implementation)
42 // Position in the $this->keys array (for the Iterator interface)
45 // Is the user logged in? (used to filter private links)
49 private $hidePublicLinks;
52 * Creates a new LinkDB
54 * Checks if the datastore exists; else, attempts to create a dummy one.
56 * @param $isLoggedIn is the user logged in?
58 function __construct($isLoggedIn, $hidePublicLinks)
60 // FIXME: do not access $GLOBALS, pass the datastore instead
61 $this->loggedIn
= $isLoggedIn;
62 $this->hidePublicLinks
= $hidePublicLinks;
68 * Countable - Counts elements of an object
70 public function count()
72 return count($this->links
);
76 * ArrayAccess - Assigns a value to the specified offset
78 public function offsetSet($offset, $value)
80 // TODO: use exceptions instead of "die"
81 if (!$this->loggedIn
) {
82 die('You are not authorized to add a link.');
84 if (empty($value['linkdate']) || empty($value['url'])) {
85 die('Internal Error: A link should always have a linkdate and URL.');
88 die('You must specify a key.');
90 $this->links
[$offset] = $value;
91 $this->urls
[$value['url']]=$offset;
95 * ArrayAccess - Whether or not an offset exists
97 public function offsetExists($offset)
99 return array_key_exists($offset, $this->links
);
103 * ArrayAccess - Unsets an offset
105 public function offsetUnset($offset)
107 if (!$this->loggedIn
) {
108 // TODO: raise an exception
109 die('You are not authorized to delete a link.');
111 $url = $this->links
[$offset]['url'];
112 unset($this->urls
[$url]);
113 unset($this->links
[$offset]);
117 * ArrayAccess - Returns the value at specified offset
119 public function offsetGet($offset)
121 return isset($this->links
[$offset]) ? $this->links
[$offset] : null;
125 * Iterator - Returns the current element
129 return $this->links
[$this->keys
[$this->position
]];
133 * Iterator - Returns the key of the current element
137 return $this->keys
[$this->position
];
141 * Iterator - Moves forward to next element
149 * Iterator - Rewinds the Iterator to the first element
151 * Entries are sorted by date (latest first)
155 $this->keys
= array_keys($this->links
);
161 * Iterator - Checks if current position is valid
165 return isset($this->keys
[$this->position
]);
169 * Checks if the DB directory and file exist
171 * If no DB file is found, creates a dummy DB.
173 private function checkDB()
175 if (file_exists($GLOBALS['config']['DATASTORE'])) {
179 // Create a dummy database for example
180 $this->links
= array();
182 'title'=>'Shaarli - sebsauvage.net',
183 'url'=>'http://sebsauvage.net/wiki/doku.php?id=php:shaarli',
184 'description'=>'Welcome to Shaarli! This is a bookmark. To edit or delete me, you must first login.',
186 'linkdate'=>'20110914_190000',
187 'tags'=>'opensource software'
189 $this->links
[$link['linkdate']] = $link;
192 'title'=>'My secret stuff... - Pastebin.com',
193 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
194 'description'=>'SShhhh!! I\'m a private link only YOU can see. You can delete me too.',
196 'linkdate'=>'20110914_074522',
197 'tags'=>'secretstuff'
199 $this->links
[$link['linkdate']] = $link;
201 // Write database to disk
202 // TODO: raise an exception if the file is not write-able
204 // FIXME: do not use $GLOBALS
205 $GLOBALS['config']['DATASTORE'],
206 PHPPREFIX
.base64_encode(gzdeflate(serialize($this->links
))).PHPSUFFIX
211 * Reads database from disk to memory
213 private function readdb()
216 // Public links are hidden and user not logged in => nothing to show
217 if ($this->hidePublicLinks
&& !$this->loggedIn
) {
218 $this->links
= array();
223 // Note that gzinflate is faster than gzuncompress.
224 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
225 // FIXME: do not use $GLOBALS
226 $this->links
= array();
228 if (file_exists($GLOBALS['config']['DATASTORE'])) {
229 $this->links
= unserialize(gzinflate(base64_decode(
230 substr(file_get_contents($GLOBALS['config']['DATASTORE']),
231 strlen(PHPPREFIX
), -strlen(PHPSUFFIX
)))));
234 // If user is not logged in, filter private links.
235 if (!$this->loggedIn
) {
237 foreach ($this->links
as $link) {
238 if ($link['private'] != 0) {
239 $toremove[] = $link['linkdate'];
242 foreach ($toremove as $linkdate) {
243 unset($this->links
[$linkdate]);
247 // Keep the list of the mapping URLs-->linkdate up-to-date.
248 $this->urls
= array();
249 foreach ($this->links
as $link) {
250 $this->urls
[$link['url']] = $link['linkdate'];
254 foreach($this->links
as &$link) {
260 * Saves the database from memory to disk
262 public function savedb()
264 if (!$this->loggedIn
) {
265 // TODO: raise an Exception instead
266 die('You are not authorized to change the database.');
269 $GLOBALS['config']['DATASTORE'],
270 PHPPREFIX
.base64_encode(gzdeflate(serialize($this->links
))).PHPSUFFIX
276 * Returns the link for a given URL, or False if it does not exist.
278 public function getLinkFromUrl($url)
280 if (isset($this->urls
[$url])) {
281 return $this->links
[$this->urls
[$url]];
287 * Returns the list of links corresponding to a full-text search
290 * - in the URLs, title and description;
291 * - are case-insensitive.
294 * print_r($mydb->filterFulltext('hollandais'));
296 * mb_convert_case($val, MB_CASE_LOWER, 'UTF-8')
297 * - allows to perform searches on Unicode text
298 * - see https://github.com/shaarli/Shaarli/issues/75 for examples
300 public function filterFulltext($searchterms)
302 // FIXME: explode(' ',$searchterms) and perform a AND search.
303 // FIXME: accept double-quotes to search for a string "as is"?
305 $search = mb_convert_case($searchterms, MB_CASE_LOWER
, 'UTF-8');
306 $keys = array('title', 'description', 'url', 'tags');
308 foreach ($this->links
as $link) {
311 foreach ($keys as $key) {
312 if (strpos(mb_convert_case($link[$key], MB_CASE_LOWER
, 'UTF-8'),
313 $search) !== false) {
319 $filtered[$link['linkdate']] = $link;
327 * Returns the list of links associated with a given list of tags
329 * You can specify one or more tags, separated by space or a comma, e.g.
330 * print_r($mydb->filterTags('linux programming'));
332 public function filterTags($tags, $casesensitive=false)
334 // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
335 // FIXME: is $casesensitive ever true?
338 ($casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER
, 'UTF-8'))
341 $searchtags = explode(' ', $t);
344 foreach ($this->links
as $l) {
347 ($casesensitive ? $l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER
, 'UTF-8'))
350 if (count(array_intersect($linktags, $searchtags)) == count($searchtags)) {
351 $filtered[$l['linkdate']] = $l;
360 * Returns the list of articles for a given day, chronologically sorted
362 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
363 * print_r($mydb->filterDay('20120125'));
365 public function filterDay($day)
367 // TODO: check input format
369 foreach ($this->links
as $l) {
370 if (startsWith($l['linkdate'], $day)) {
371 $filtered[$l['linkdate']] = $l;
379 * Returns the article corresponding to a smallHash
381 public function filterSmallHash($smallHash)
384 foreach ($this->links
as $l) {
385 if ($smallHash == smallHash($l['linkdate'])) {
386 // Yes, this is ugly and slow
387 $filtered[$l['linkdate']] = $l;
395 * Returns the list of all tags
396 * Output: associative array key=tags, value=0
398 public function allTags()
401 foreach ($this->links
as $link) {
402 foreach (explode(' ', $link['tags']) as $tag) {
404 $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] +
1);
408 // Sort tags by usage (most used tag first)
414 * Returns the list of days containing articles (oldest first)
415 * Output: An array containing days (in format YYYYMMDD).
417 public function days()
420 foreach (array_keys($this->links
) as $day) {
421 $linkDays[substr($day, 0, 8)] = 0;
423 $linkDays = array_keys($linkDays);