]>
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. Used for displayable links (no redirector, relative, etc.).
21 * Can be absolute or relative.
22 * Relative URLs are permalinks (e.g.'?m-ukcw')
23 * - real_url Absolute processed URL.
25 * Implements 3 interfaces:
26 * - ArrayAccess: behaves like an associative array;
27 * - Countable: there is a count() method;
28 * - Iterator: usable in foreach () loops.
30 class LinkDB
implements Iterator
, Countable
, ArrayAccess
32 // Links are stored as a PHP serialized string
35 // Link date storage format
36 const LINK_DATE_FORMAT
= 'Ymd_His';
38 // Datastore PHP prefix
39 protected static $phpPrefix = '<?php /* ';
41 // Datastore PHP suffix
42 protected static $phpSuffix = ' */ ?>';
44 // List of links (associative array)
45 // - key: link date (e.g. "20110823_124546"),
46 // - value: associative array (keys: title, description...)
49 // List of all recorded URLs (key=url, value=linkdate)
50 // for fast reserve search (url-->linkdate)
53 // List of linkdate keys (for the Iterator interface implementation)
56 // Position in the $this->_keys array (for the Iterator interface)
59 // Is the user logged in? (used to filter private links)
63 private $_hidePublicLinks;
65 // link redirector set in user settings.
69 * Creates a new LinkDB
71 * Checks if the datastore exists; else, attempts to create a dummy one.
73 * @param string $datastore datastore file path.
74 * @param boolean $isLoggedIn is the user logged in?
75 * @param boolean $hidePublicLinks if true all links are private.
76 * @param string $redirector link redirector set in user settings.
78 function __construct($datastore, $isLoggedIn, $hidePublicLinks, $redirector = '')
80 $this->_datastore
= $datastore;
81 $this->_loggedIn
= $isLoggedIn;
82 $this->_hidePublicLinks
= $hidePublicLinks;
83 $this->_redirector
= $redirector;
89 * Countable - Counts elements of an object
91 public function count()
93 return count($this->_links
);
97 * ArrayAccess - Assigns a value to the specified offset
99 public function offsetSet($offset, $value)
101 // TODO: use exceptions instead of "die"
102 if (!$this->_loggedIn
) {
103 die('You are not authorized to add a link.');
105 if (empty($value['linkdate']) || empty($value['url'])) {
106 die('Internal Error: A link should always have a linkdate and URL.');
108 if (empty($offset)) {
109 die('You must specify a key.');
111 $this->_links
[$offset] = $value;
112 $this->_urls
[$value['url']]=$offset;
116 * ArrayAccess - Whether or not an offset exists
118 public function offsetExists($offset)
120 return array_key_exists($offset, $this->_links
);
124 * ArrayAccess - Unsets an offset
126 public function offsetUnset($offset)
128 if (!$this->_loggedIn
) {
129 // TODO: raise an exception
130 die('You are not authorized to delete a link.');
132 $url = $this->_links
[$offset]['url'];
133 unset($this->_urls
[$url]);
134 unset($this->_links
[$offset]);
138 * ArrayAccess - Returns the value at specified offset
140 public function offsetGet($offset)
142 return isset($this->_links
[$offset]) ? $this->_links
[$offset] : null;
146 * Iterator - Returns the current element
150 return $this->_links
[$this->_keys
[$this->_position
]];
154 * Iterator - Returns the key of the current element
158 return $this->_keys
[$this->_position
];
162 * Iterator - Moves forward to next element
170 * Iterator - Rewinds the Iterator to the first element
172 * Entries are sorted by date (latest first)
176 $this->_keys
= array_keys($this->_links
);
178 $this->_position
= 0;
182 * Iterator - Checks if current position is valid
186 return isset($this->_keys
[$this->_position
]);
190 * Checks if the DB directory and file exist
192 * If no DB file is found, creates a dummy DB.
194 private function _checkDB()
196 if (file_exists($this->_datastore
)) {
200 // Create a dummy database for example
201 $this->_links
= array();
203 'title'=>' Shaarli: the personal, minimalist, super-fast, no-database delicious clone',
204 'url'=>'https://github.com/shaarli/Shaarli/wiki',
205 'description'=>'Welcome to Shaarli! This is your first public bookmark. To edit or delete me, you must first login.
207 To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page.
209 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.',
211 'linkdate'=> date('Ymd_His'),
212 'tags'=>'opensource software'
214 $this->_links
[$link['linkdate']] = $link;
217 'title'=>'My secret stuff... - Pastebin.com',
218 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
219 'description'=>'Shhhh! I\'m a private link only YOU can see. You can delete me too.',
221 'linkdate'=> date('Ymd_His', strtotime('-1 minute')),
222 'tags'=>'secretstuff'
224 $this->_links
[$link['linkdate']] = $link;
226 // Write database to disk
231 * Reads database from disk to memory
233 private function _readDB()
236 // Public links are hidden and user not logged in => nothing to show
237 if ($this->_hidePublicLinks
&& !$this->_loggedIn
) {
238 $this->_links
= array();
243 // Note that gzinflate is faster than gzuncompress.
244 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
245 $this->_links
= array();
247 if (file_exists($this->_datastore
)) {
248 $this->_links
= unserialize(gzinflate(base64_decode(
249 substr(file_get_contents($this->_datastore
),
250 strlen(self
::$phpPrefix), -strlen(self
::$phpSuffix)))));
253 // If user is not logged in, filter private links.
254 if (!$this->_loggedIn
) {
256 foreach ($this->_links
as $link) {
257 if ($link['private'] != 0) {
258 $toremove[] = $link['linkdate'];
261 foreach ($toremove as $linkdate) {
262 unset($this->_links
[$linkdate]);
266 $this->_urls
= array();
267 foreach ($this->_links
as &$link) {
268 // Keep the list of the mapping URLs-->linkdate up-to-date.
269 $this->_urls
[$link['url']] = $link['linkdate'];
271 // Sanitize data fields.
274 // Remove private tags if the user is not logged in.
275 if (! $this->_loggedIn
) {
276 $link['tags'] = preg_replace('/(^| )\.[^($| )]+/', '', $link['tags']);
279 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
280 if (!empty($this->_redirector
) && !startsWith($link['url'], '?')) {
281 $link['real_url'] = $this->_redirector
. urlencode($link['url']);
284 $link['real_url'] = $link['url'];
290 * Saves the database from memory to disk
292 * @throws IOException the datastore is not writable
294 private function writeDB()
296 if (is_file($this->_datastore
) && !is_writeable($this->_datastore
)) {
297 // The datastore exists but is not writeable
298 throw new IOException($this->_datastore
);
299 } else if (!is_file($this->_datastore
) && !is_writeable(dirname($this->_datastore
))) {
300 // The datastore does not exist and its parent directory is not writeable
301 throw new IOException(dirname($this->_datastore
));
306 self
::$phpPrefix.base64_encode(gzdeflate(serialize($this->_links
))).self
::$phpSuffix
312 * Saves the database from memory to disk
314 * @param string $pageCacheDir page cache directory
316 public function savedb($pageCacheDir)
318 if (!$this->_loggedIn
) {
319 // TODO: raise an Exception instead
320 die('You are not authorized to change the database.');
325 invalidateCaches($pageCacheDir);
329 * Returns the link for a given URL, or False if it does not exist.
331 * @param string $url URL to search for
333 * @return mixed the existing link if it exists, else 'false'
335 public function getLinkFromUrl($url)
337 if (isset($this->_urls
[$url])) {
338 return $this->_links
[$this->_urls
[$url]];
346 * @param string $type Type of filter.
347 * @param mixed $request Search request, string or array.
348 * @param bool $casesensitive Optional: Perform case sensitive filter
349 * @param bool $privateonly Optional: Returns private links only if true.
351 * @return array filtered links
353 public function filter($type = '', $request = '', $casesensitive = false, $privateonly = false)
355 $linkFilter = new LinkFilter($this->_links
);
356 $requestFilter = is_array($request) ? implode(' ', $request) : $request;
357 return $linkFilter->filter($type, trim($requestFilter), $casesensitive, $privateonly);
361 * Returns the list of all tags
362 * Output: associative array key=tags, value=0
364 public function allTags()
367 foreach ($this->_links
as $link) {
368 foreach (explode(' ', $link['tags']) as $tag) {
370 $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] +
1);
374 // Sort tags by usage (most used tag first)
380 * Returns the list of days containing articles (oldest first)
381 * Output: An array containing days (in format YYYYMMDD).
383 public function days()
386 foreach (array_keys($this->_links
) as $day) {
387 $linkDays[substr($day, 0, 8)] = 0;
389 $linkDays = array_keys($linkDays);