]>
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 // Links are stored as a PHP serialized string
33 // Datastore PHP prefix
34 protected static $phpPrefix = '<?php /* ';
36 // Datastore PHP suffix
37 protected static $phpSuffix = ' */ ?>';
39 // List of links (associative array)
40 // - key: link date (e.g. "20110823_124546"),
41 // - value: associative array (keys: title, description...)
44 // List of all recorded URLs (key=url, value=linkdate)
45 // for fast reserve search (url-->linkdate)
48 // List of linkdate keys (for the Iterator interface implementation)
51 // Position in the $this->_keys array (for the Iterator interface)
54 // Is the user logged in? (used to filter private links)
58 private $_hidePublicLinks;
60 // link redirector set in user settings.
64 * Creates a new LinkDB
66 * Checks if the datastore exists; else, attempts to create a dummy one.
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.
73 function __construct($datastore, $isLoggedIn, $hidePublicLinks, $redirector = '')
75 $this->_datastore
= $datastore;
76 $this->_loggedIn
= $isLoggedIn;
77 $this->_hidePublicLinks
= $hidePublicLinks;
78 $this->_redirector
= $redirector;
84 * Countable - Counts elements of an object
86 public function count()
88 return count($this->_links
);
92 * ArrayAccess - Assigns a value to the specified offset
94 public function offsetSet($offset, $value)
96 // TODO: use exceptions instead of "die"
97 if (!$this->_loggedIn
) {
98 die('You are not authorized to add a link.');
100 if (empty($value['linkdate']) || empty($value['url'])) {
101 die('Internal Error: A link should always have a linkdate and URL.');
103 if (empty($offset)) {
104 die('You must specify a key.');
106 $this->_links
[$offset] = $value;
107 $this->_urls
[$value['url']]=$offset;
111 * ArrayAccess - Whether or not an offset exists
113 public function offsetExists($offset)
115 return array_key_exists($offset, $this->_links
);
119 * ArrayAccess - Unsets an offset
121 public function offsetUnset($offset)
123 if (!$this->_loggedIn
) {
124 // TODO: raise an exception
125 die('You are not authorized to delete a link.');
127 $url = $this->_links
[$offset]['url'];
128 unset($this->_urls
[$url]);
129 unset($this->_links
[$offset]);
133 * ArrayAccess - Returns the value at specified offset
135 public function offsetGet($offset)
137 return isset($this->_links
[$offset]) ? $this->_links
[$offset] : null;
141 * Iterator - Returns the current element
145 return $this->_links
[$this->_keys
[$this->_position
]];
149 * Iterator - Returns the key of the current element
153 return $this->_keys
[$this->_position
];
157 * Iterator - Moves forward to next element
165 * Iterator - Rewinds the Iterator to the first element
167 * Entries are sorted by date (latest first)
171 $this->_keys
= array_keys($this->_links
);
173 $this->_position
= 0;
177 * Iterator - Checks if current position is valid
181 return isset($this->_keys
[$this->_position
]);
185 * Checks if the DB directory and file exist
187 * If no DB file is found, creates a dummy DB.
189 private function _checkDB()
191 if (file_exists($this->_datastore
)) {
195 // Create a dummy database for example
196 $this->_links
= array();
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.
202 To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page.
204 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.',
206 'linkdate'=> date('Ymd_His'),
207 'tags'=>'opensource software'
209 $this->_links
[$link['linkdate']] = $link;
212 'title'=>'My secret stuff... - Pastebin.com',
213 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
214 'description'=>'Shhhh! I\'m a private link only YOU can see. You can delete me too.',
216 'linkdate'=> date('Ymd_His', strtotime('-1 minute')),
217 'tags'=>'secretstuff'
219 $this->_links
[$link['linkdate']] = $link;
221 // Write database to disk
226 * Reads database from disk to memory
228 private function _readDB()
231 // Public links are hidden and user not logged in => nothing to show
232 if ($this->_hidePublicLinks
&& !$this->_loggedIn
) {
233 $this->_links
= array();
238 // Note that gzinflate is faster than gzuncompress.
239 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
240 $this->_links
= array();
242 if (file_exists($this->_datastore
)) {
243 $this->_links
= unserialize(gzinflate(base64_decode(
244 substr(file_get_contents($this->_datastore
),
245 strlen(self
::$phpPrefix), -strlen(self
::$phpSuffix)))));
248 // If user is not logged in, filter private links.
249 if (!$this->_loggedIn
) {
251 foreach ($this->_links
as $link) {
252 if ($link['private'] != 0) {
253 $toremove[] = $link['linkdate'];
256 foreach ($toremove as $linkdate) {
257 unset($this->_links
[$linkdate]);
261 // Keep the list of the mapping URLs-->linkdate up-to-date.
262 $this->_urls
= array();
263 foreach ($this->_links
as $link) {
264 $this->_urls
[$link['url']] = $link['linkdate'];
268 foreach($this->_links
as &$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']);
275 $link['real_url'] = $link['url'];
281 * Saves the database from memory to disk
283 * @throws IOException the datastore is not writable
285 private function writeDB()
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
));
297 self
::$phpPrefix.base64_encode(gzdeflate(serialize($this->_links
))).self
::$phpSuffix
303 * Saves the database from memory to disk
305 * @param string $pageCacheDir page cache directory
307 public function savedb($pageCacheDir)
309 if (!$this->_loggedIn
) {
310 // TODO: raise an Exception instead
311 die('You are not authorized to change the database.');
316 invalidateCaches($pageCacheDir);
320 * Returns the link for a given URL, or False if it does not exist.
322 * @param string $url URL to search for
324 * @return mixed the existing link if it exists, else 'false'
326 public function getLinkFromUrl($url)
328 if (isset($this->_urls
[$url])) {
329 return $this->_links
[$this->_urls
[$url]];
335 * Returns the list of links corresponding to a full-text search
338 * - in the URLs, title and description;
339 * - are case-insensitive.
342 * print_r($mydb->filterFulltext('hollandais'));
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
348 public function filterFulltext($searchterms)
350 // FIXME: explode(' ',$searchterms) and perform a AND search.
351 // FIXME: accept double-quotes to search for a string "as is"?
353 $search = mb_convert_case($searchterms, MB_CASE_LOWER
, 'UTF-8');
354 $keys = array('title', 'description', 'url', 'tags');
356 foreach ($this->_links
as $link) {
359 foreach ($keys as $key) {
360 if (strpos(mb_convert_case($link[$key], MB_CASE_LOWER
, 'UTF-8'),
361 $search) !== false) {
367 $filtered[$link['linkdate']] = $link;
375 * Returns the list of links associated with a given list of tags
377 * You can specify one or more tags, separated by space or a comma, e.g.
378 * print_r($mydb->filterTags('linux programming'));
380 public function filterTags($tags, $casesensitive=false)
382 // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
383 // FIXME: is $casesensitive ever true?
386 ($casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER
, 'UTF-8'))
389 $searchtags = explode(' ', $t);
392 foreach ($this->_links
as $l) {
395 ($casesensitive ? $l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER
, 'UTF-8'))
398 if (count(array_intersect($linktags, $searchtags)) == count($searchtags)) {
399 $filtered[$l['linkdate']] = $l;
408 * Returns the list of articles for a given day, chronologically sorted
410 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
411 * print_r($mydb->filterDay('20120125'));
413 public function filterDay($day)
415 if (! checkDateFormat('Ymd', $day)) {
416 throw new Exception('Invalid date format');
420 foreach ($this->_links
as $l) {
421 if (startsWith($l['linkdate'], $day)) {
422 $filtered[$l['linkdate']] = $l;
430 * Returns the article corresponding to a smallHash
432 public function filterSmallHash($smallHash)
435 foreach ($this->_links
as $l) {
436 if ($smallHash == smallHash($l['linkdate'])) {
437 // Yes, this is ugly and slow
438 $filtered[$l['linkdate']] = $l;
446 * Returns the list of all tags
447 * Output: associative array key=tags, value=0
449 public function allTags()
452 foreach ($this->_links
as $link) {
453 foreach (explode(' ', $link['tags']) as $tag) {
455 $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] +
1);
459 // Sort tags by usage (most used tag first)
465 * Returns the list of days containing articles (oldest first)
466 * Output: An array containing days (in format YYYYMMDD).
468 public function days()
471 foreach (array_keys($this->_links
) as $day) {
472 $linkDays[substr($day, 0, 8)] = 0;
474 $linkDays = array_keys($linkDays);