]>
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 * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched.
72 * anonym.to needs clean URL while dereferer.org needs urlencoded URL.
74 * @var boolean $redirectorEncode parameter: true or false
76 private $redirectorEncode;
79 * Creates a new LinkDB
81 * Checks if the datastore exists; else, attempts to create a dummy one.
83 * @param string $datastore datastore file path.
84 * @param boolean $isLoggedIn is the user logged in?
85 * @param boolean $hidePublicLinks if true all links are private.
86 * @param string $redirector link redirector set in user settings.
87 * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true).
94 $redirectorEncode = true
97 $this->_datastore
= $datastore;
98 $this->_loggedIn
= $isLoggedIn;
99 $this->_hidePublicLinks
= $hidePublicLinks;
100 $this->_redirector
= $redirector;
101 $this->redirectorEncode
= $redirectorEncode === true;
107 * Countable - Counts elements of an object
109 public function count()
111 return count($this->_links
);
115 * ArrayAccess - Assigns a value to the specified offset
117 public function offsetSet($offset, $value)
119 // TODO: use exceptions instead of "die"
120 if (!$this->_loggedIn
) {
121 die('You are not authorized to add a link.');
123 if (empty($value['linkdate']) || empty($value['url'])) {
124 die('Internal Error: A link should always have a linkdate and URL.');
126 if (empty($offset)) {
127 die('You must specify a key.');
129 $this->_links
[$offset] = $value;
130 $this->_urls
[$value['url']]=$offset;
134 * ArrayAccess - Whether or not an offset exists
136 public function offsetExists($offset)
138 return array_key_exists($offset, $this->_links
);
142 * ArrayAccess - Unsets an offset
144 public function offsetUnset($offset)
146 if (!$this->_loggedIn
) {
147 // TODO: raise an exception
148 die('You are not authorized to delete a link.');
150 $url = $this->_links
[$offset]['url'];
151 unset($this->_urls
[$url]);
152 unset($this->_links
[$offset]);
156 * ArrayAccess - Returns the value at specified offset
158 public function offsetGet($offset)
160 return isset($this->_links
[$offset]) ? $this->_links
[$offset] : null;
164 * Iterator - Returns the current element
168 return $this->_links
[$this->_keys
[$this->_position
]];
172 * Iterator - Returns the key of the current element
176 return $this->_keys
[$this->_position
];
180 * Iterator - Moves forward to next element
188 * Iterator - Rewinds the Iterator to the first element
190 * Entries are sorted by date (latest first)
194 $this->_keys
= array_keys($this->_links
);
196 $this->_position
= 0;
200 * Iterator - Checks if current position is valid
204 return isset($this->_keys
[$this->_position
]);
208 * Checks if the DB directory and file exist
210 * If no DB file is found, creates a dummy DB.
212 private function _checkDB()
214 if (file_exists($this->_datastore
)) {
218 // Create a dummy database for example
219 $this->_links
= array();
221 'title'=>' Shaarli: the personal, minimalist, super-fast, no-database delicious clone',
222 'url'=>'https://github.com/shaarli/Shaarli/wiki',
223 'description'=>'Welcome to Shaarli! This is your first public bookmark. To edit or delete me, you must first login.
225 To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page.
227 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.',
229 'linkdate'=> date('Ymd_His'),
230 'tags'=>'opensource software'
232 $this->_links
[$link['linkdate']] = $link;
235 'title'=>'My secret stuff... - Pastebin.com',
236 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
237 'description'=>'Shhhh! I\'m a private link only YOU can see. You can delete me too.',
239 'linkdate'=> date('Ymd_His', strtotime('-1 minute')),
240 'tags'=>'secretstuff'
242 $this->_links
[$link['linkdate']] = $link;
244 // Write database to disk
249 * Reads database from disk to memory
251 private function _readDB()
254 // Public links are hidden and user not logged in => nothing to show
255 if ($this->_hidePublicLinks
&& !$this->_loggedIn
) {
256 $this->_links
= array();
261 // Note that gzinflate is faster than gzuncompress.
262 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
263 $this->_links
= array();
265 if (file_exists($this->_datastore
)) {
266 $this->_links
= unserialize(gzinflate(base64_decode(
267 substr(file_get_contents($this->_datastore
),
268 strlen(self
::$phpPrefix), -strlen(self
::$phpSuffix)))));
271 // If user is not logged in, filter private links.
272 if (!$this->_loggedIn
) {
274 foreach ($this->_links
as $link) {
275 if ($link['private'] != 0) {
276 $toremove[] = $link['linkdate'];
279 foreach ($toremove as $linkdate) {
280 unset($this->_links
[$linkdate]);
284 $this->_urls
= array();
285 foreach ($this->_links
as &$link) {
286 // Keep the list of the mapping URLs-->linkdate up-to-date.
287 $this->_urls
[$link['url']] = $link['linkdate'];
289 // Sanitize data fields.
292 // Remove private tags if the user is not logged in.
293 if (! $this->_loggedIn
) {
294 $link['tags'] = preg_replace('/(^| )\.[^($| )]+/', '', $link['tags']);
297 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
298 if (!empty($this->_redirector
) && !startsWith($link['url'], '?')) {
299 $link['real_url'] = $this->_redirector
;
300 if ($this->redirectorEncode
) {
301 $link['real_url'] .= urlencode(unescape($link['url']));
303 $link['real_url'] .= $link['url'];
307 $link['real_url'] = $link['url'];
313 * Saves the database from memory to disk
315 * @throws IOException the datastore is not writable
317 private function writeDB()
319 if (is_file($this->_datastore
) && !is_writeable($this->_datastore
)) {
320 // The datastore exists but is not writeable
321 throw new IOException($this->_datastore
);
322 } else if (!is_file($this->_datastore
) && !is_writeable(dirname($this->_datastore
))) {
323 // The datastore does not exist and its parent directory is not writeable
324 throw new IOException(dirname($this->_datastore
));
329 self
::$phpPrefix.base64_encode(gzdeflate(serialize($this->_links
))).self
::$phpSuffix
335 * Saves the database from memory to disk
337 * @param string $pageCacheDir page cache directory
339 public function savedb($pageCacheDir)
341 if (!$this->_loggedIn
) {
342 // TODO: raise an Exception instead
343 die('You are not authorized to change the database.');
348 invalidateCaches($pageCacheDir);
352 * Returns the link for a given URL, or False if it does not exist.
354 * @param string $url URL to search for
356 * @return mixed the existing link if it exists, else 'false'
358 public function getLinkFromUrl($url)
360 if (isset($this->_urls
[$url])) {
361 return $this->_links
[$this->_urls
[$url]];
367 * Returns the shaare corresponding to a smallHash.
369 * @param string $request QUERY_STRING server parameter.
371 * @return array $filtered array containing permalink data.
373 * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link.
375 public function filterHash($request)
377 $request = substr($request, 0, 6);
378 $linkFilter = new LinkFilter($this->_links
);
379 return $linkFilter->filter(LinkFilter
::$FILTER_HASH, $request);
383 * Returns the list of articles for a given day.
385 * @param string $request day to filter. Format: YYYYMMDD.
387 * @return array list of shaare found.
389 public function filterDay($request) {
390 $linkFilter = new LinkFilter($this->_links
);
391 return $linkFilter->filter(LinkFilter
::$FILTER_DAY, $request);
395 * Filter links according to search parameters.
397 * @param array $filterRequest Search request content. Supported keys:
398 * - searchtags: list of tags
399 * - searchterm: term search
400 * @param bool $casesensitive Optional: Perform case sensitive filter
401 * @param bool $privateonly Optional: Returns private links only if true.
403 * @return array filtered links, all links if no suitable filter was provided.
405 public function filterSearch($filterRequest = array(), $casesensitive = false, $privateonly = false)
407 // Filter link database according to parameters.
408 $searchtags = !empty($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
409 $searchterm = !empty($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
411 // Search tags + fullsearch.
412 if (empty($type) && ! empty($searchtags) && ! empty($searchterm)) {
413 $type = LinkFilter
::$FILTER_TAG | LinkFilter
::$FILTER_TEXT;
414 $request = array($searchtags, $searchterm);
417 elseif (! empty($searchtags)) {
418 $type = LinkFilter
::$FILTER_TAG;
419 $request = $searchtags;
422 elseif (! empty($searchterm)) {
423 $type = LinkFilter
::$FILTER_TEXT;
424 $request = $searchterm;
426 // Otherwise, display without filtering.
432 $linkFilter = new LinkFilter($this->_links
);
433 return $linkFilter->filter($type, $request, $casesensitive, $privateonly);
437 * Returns the list of all tags
438 * Output: associative array key=tags, value=0
440 public function allTags()
443 $caseMapping = array();
444 foreach ($this->_links
as $link) {
445 foreach (explode(' ', $link['tags']) as $tag) {
449 // The first case found will be displayed.
450 if (!isset($caseMapping[strtolower($tag)])) {
451 $caseMapping[strtolower($tag)] = $tag;
452 $tags[$caseMapping[strtolower($tag)]] = 0;
454 $tags[$caseMapping[strtolower($tag)]]++
;
457 // Sort tags by usage (most used tag first)
463 * Returns the list of days containing articles (oldest first)
464 * Output: An array containing days (in format YYYYMMDD).
466 public function days()
469 foreach (array_keys($this->_links
) as $day) {
470 $linkDays[substr($day, 0, 8)] = 0;
472 $linkDays = array_keys($linkDays);