]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkDB.php
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 * Creates a new LinkDB
51 * Checks if the datastore exists; else, attempts to create a dummy one.
53 * @param $isLoggedIn is the user logged in?
55 function __construct($isLoggedIn)
57 // FIXME: do not access $GLOBALS, pass the datastore instead
58 $this->loggedIn
= $isLoggedIn;
64 * Countable - Counts elements of an object
66 public function count()
68 return count($this->links
);
72 * ArrayAccess - Assigns a value to the specified offset
74 public function offsetSet($offset, $value)
76 // TODO: use exceptions instead of "die"
77 if (!$this->loggedIn
) {
78 die('You are not authorized to add a link.');
80 if (empty($value['linkdate']) || empty($value['url'])) {
81 die('Internal Error: A link should always have a linkdate and URL.');
84 die('You must specify a key.');
86 $this->links
[$offset] = $value;
87 $this->urls
[$value['url']]=$offset;
91 * ArrayAccess - Whether or not an offset exists
93 public function offsetExists($offset)
95 return array_key_exists($offset, $this->links
);
99 * ArrayAccess - Unsets an offset
101 public function offsetUnset($offset)
103 if (!$this->loggedIn
) {
104 // TODO: raise an exception
105 die('You are not authorized to delete a link.');
107 $url = $this->links
[$offset]['url'];
108 unset($this->urls
[$url]);
109 unset($this->links
[$offset]);
113 * ArrayAccess - Returns the value at specified offset
115 public function offsetGet($offset)
117 return isset($this->links
[$offset]) ? $this->links
[$offset] : null;
121 * Iterator - Returns the current element
125 return $this->links
[$this->keys
[$this->position
]];
129 * Iterator - Returns the key of the current element
133 return $this->keys
[$this->position
];
137 * Iterator - Moves forward to next element
145 * Iterator - Rewinds the Iterator to the first element
147 * Entries are sorted by date (latest first)
151 $this->keys
= array_keys($this->links
);
157 * Iterator - Checks if current position is valid
161 return isset($this->keys
[$this->position
]);
165 * Checks if the DB directory and file exist
167 * If no DB file is found, creates a dummy DB.
169 private function checkDB()
171 if (file_exists($GLOBALS['config']['DATASTORE'])) {
175 // Create a dummy database for example
176 $this->links
= 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.',
182 'linkdate'=>'20110914_190000',
183 'tags'=>'opensource software'
185 $this->links
[$link['linkdate']] = $link;
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.',
192 'linkdate'=>'20110914_074522',
193 'tags'=>'secretstuff'
195 $this->links
[$link['linkdate']] = $link;
197 // Write database to disk
198 // TODO: raise an exception if the file is not write-able
200 // FIXME: do not use $GLOBALS
201 $GLOBALS['config']['DATASTORE'],
202 PHPPREFIX
.base64_encode(gzdeflate(serialize($this->links
))).PHPSUFFIX
207 * Reads database from disk to memory
209 private function readdb()
212 // Note that gzinflate is faster than gzuncompress.
213 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
214 // FIXME: do not use $GLOBALS
215 $this->links
= array();
217 if (file_exists($GLOBALS['config']['DATASTORE'])) {
218 $this->links
= unserialize(gzinflate(base64_decode(
219 substr(file_get_contents($GLOBALS['config']['DATASTORE']),
220 strlen(PHPPREFIX
), -strlen(PHPSUFFIX
)))));
223 // If user is not logged in, filter private links.
224 if (!$this->loggedIn
) {
226 foreach ($this->links
as $link) {
227 if ($link['private'] != 0) {
228 $toremove[] = $link['linkdate'];
231 foreach ($toremove as $linkdate) {
232 unset($this->links
[$linkdate]);
236 // Keep the list of the mapping URLs-->linkdate up-to-date.
237 $this->urls
= array();
238 foreach ($this->links
as $link) {
239 $this->urls
[$link['url']] = $link['linkdate'];
244 * Saves the database from memory to disk
246 public function savedb()
248 if (!$this->loggedIn
) {
249 // TODO: raise an Exception instead
250 die('You are not authorized to change the database.');
253 $GLOBALS['config']['DATASTORE'],
254 PHPPREFIX
.base64_encode(gzdeflate(serialize($this->links
))).PHPSUFFIX
260 * Returns the link for a given URL, or False if it does not exist.
262 public function getLinkFromUrl($url)
264 if (isset($this->urls
[$url])) {
265 return $this->links
[$this->urls
[$url]];
271 * Returns the list of links corresponding to a full-text search
274 * - in the URLs, title and description;
275 * - are case-insensitive.
278 * print_r($mydb->filterFulltext('hollandais'));
280 * mb_convert_case($val, MB_CASE_LOWER, 'UTF-8')
281 * - allows to perform searches on Unicode text
282 * - see https://github.com/shaarli/Shaarli/issues/75 for examples
284 public function filterFulltext($searchterms)
286 // FIXME: explode(' ',$searchterms) and perform a AND search.
287 // FIXME: accept double-quotes to search for a string "as is"?
289 $search = mb_convert_case($searchterms, MB_CASE_LOWER
, 'UTF-8');
290 $keys = ['title', 'description', 'url', 'tags'];
292 foreach ($this->links
as $link) {
295 foreach ($keys as $key) {
296 if (strpos(mb_convert_case($link[$key], MB_CASE_LOWER
, 'UTF-8'),
297 $search) !== false) {
303 $filtered[$link['linkdate']] = $link;
311 * Returns the list of links associated with a given list of tags
313 * You can specify one or more tags, separated by space or a comma, e.g.
314 * print_r($mydb->filterTags('linux programming'));
316 public function filterTags($tags, $casesensitive=false)
318 // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
319 // FIXME: is $casesensitive ever true?
322 ($casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER
, 'UTF-8'))
325 $searchtags = explode(' ', $t);
328 foreach ($this->links
as $l) {
331 ($casesensitive ? $l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER
, 'UTF-8'))
334 if (count(array_intersect($linktags, $searchtags)) == count($searchtags)) {
335 $filtered[$l['linkdate']] = $l;
344 * Returns the list of articles for a given day, chronologically sorted
346 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
347 * print_r($mydb->filterDay('20120125'));
349 public function filterDay($day)
351 // TODO: check input format
353 foreach ($this->links
as $l) {
354 if (startsWith($l['linkdate'], $day)) {
355 $filtered[$l['linkdate']] = $l;
363 * Returns the article corresponding to a smallHash
365 public function filterSmallHash($smallHash)
368 foreach ($this->links
as $l) {
369 if ($smallHash == smallHash($l['linkdate'])) {
370 // Yes, this is ugly and slow
371 $filtered[$l['linkdate']] = $l;
379 * Returns the list of all tags
380 * Output: associative array key=tags, value=0
382 public function allTags()
385 foreach ($this->links
as $link) {
386 foreach (explode(' ', $link['tags']) as $tag) {
388 $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] +
1);
392 // Sort tags by usage (most used tag first)
398 * Returns the list of days containing articles (oldest first)
399 * Output: An array containing days (in format YYYYMMDD).
401 public function days()
404 foreach (array_keys($this->links
) as $day) {
405 $linkDays[substr($day, 0, 8)] = 0;
407 $linkDays = array_keys($linkDays);