]>
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 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: 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.
186 To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page.
188 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.',
190 'linkdate'=> date('Ymd_His'),
191 'tags'=>'opensource software'
193 $this->links
[$link['linkdate']] = $link;
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.',
200 'linkdate'=> date('Ymd_His', strtotime('-1 minute')),
201 'tags'=>'secretstuff'
203 $this->links
[$link['linkdate']] = $link;
205 // Write database to disk
206 // TODO: raise an exception if the file is not write-able
208 // FIXME: do not use $GLOBALS
209 $GLOBALS['config']['DATASTORE'],
210 PHPPREFIX
.base64_encode(gzdeflate(serialize($this->links
))).PHPSUFFIX
215 * Reads database from disk to memory
217 private function readdb()
220 // Public links are hidden and user not logged in => nothing to show
221 if ($this->hidePublicLinks
&& !$this->loggedIn
) {
222 $this->links
= array();
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();
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
)))));
238 // If user is not logged in, filter private links.
239 if (!$this->loggedIn
) {
241 foreach ($this->links
as $link) {
242 if ($link['private'] != 0) {
243 $toremove[] = $link['linkdate'];
246 foreach ($toremove as $linkdate) {
247 unset($this->links
[$linkdate]);
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'];
258 foreach($this->links
as &$link) {
264 * Saves the database from memory to disk
266 public function savedb()
268 if (!$this->loggedIn
) {
269 // TODO: raise an Exception instead
270 die('You are not authorized to change the database.');
273 $GLOBALS['config']['DATASTORE'],
274 PHPPREFIX
.base64_encode(gzdeflate(serialize($this->links
))).PHPSUFFIX
280 * Returns the link for a given URL, or False if it does not exist.
282 public function getLinkFromUrl($url)
284 if (isset($this->urls
[$url])) {
285 return $this->links
[$this->urls
[$url]];
291 * Returns the list of links corresponding to a full-text search
294 * - in the URLs, title and description;
295 * - are case-insensitive.
298 * print_r($mydb->filterFulltext('hollandais'));
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
304 public function filterFulltext($searchterms)
306 // FIXME: explode(' ',$searchterms) and perform a AND search.
307 // FIXME: accept double-quotes to search for a string "as is"?
309 $search = mb_convert_case($searchterms, MB_CASE_LOWER
, 'UTF-8');
310 $keys = ['title', 'description', 'url', 'tags'];
312 foreach ($this->links
as $link) {
315 foreach ($keys as $key) {
316 if (strpos(mb_convert_case($link[$key], MB_CASE_LOWER
, 'UTF-8'),
317 $search) !== false) {
323 $filtered[$link['linkdate']] = $link;
331 * Returns the list of links associated with a given list of tags
333 * You can specify one or more tags, separated by space or a comma, e.g.
334 * print_r($mydb->filterTags('linux programming'));
336 public function filterTags($tags, $casesensitive=false)
338 // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
339 // FIXME: is $casesensitive ever true?
342 ($casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER
, 'UTF-8'))
345 $searchtags = explode(' ', $t);
348 foreach ($this->links
as $l) {
351 ($casesensitive ? $l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER
, 'UTF-8'))
354 if (count(array_intersect($linktags, $searchtags)) == count($searchtags)) {
355 $filtered[$l['linkdate']] = $l;
364 * Returns the list of articles for a given day, chronologically sorted
366 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
367 * print_r($mydb->filterDay('20120125'));
369 public function filterDay($day)
371 // TODO: check input format
373 foreach ($this->links
as $l) {
374 if (startsWith($l['linkdate'], $day)) {
375 $filtered[$l['linkdate']] = $l;
383 * Returns the article corresponding to a smallHash
385 public function filterSmallHash($smallHash)
388 foreach ($this->links
as $l) {
389 if ($smallHash == smallHash($l['linkdate'])) {
390 // Yes, this is ugly and slow
391 $filtered[$l['linkdate']] = $l;
399 * Returns the list of all tags
400 * Output: associative array key=tags, value=0
402 public function allTags()
405 foreach ($this->links
as $link) {
406 foreach (explode(' ', $link['tags']) as $tag) {
408 $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] +
1);
412 // Sort tags by usage (most used tag first)
418 * Returns the list of days containing articles (oldest first)
419 * Output: An array containing days (in format YYYYMMDD).
421 public function days()
424 foreach (array_keys($this->links
) as $day) {
425 $linkDays[substr($day, 0, 8)] = 0;
427 $linkDays = array_keys($linkDays);