]>
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: creation date of this entry, format: YYYYMMDD_HHMMSS
16 * (e.g.'20110914_192317')
17 * - updated: last modification date of this entry, format: YYYYMMDD_HHMMSS
18 * - private: Is this link private? 0=no, other value=yes
19 * - tags: tags attached to this entry (separated by spaces)
20 * - title Title of the link
21 * - url URL of the link. Used for displayable links (no redirector, relative, etc.).
22 * Can be absolute or relative.
23 * Relative URLs are permalinks (e.g.'?m-ukcw')
24 * - real_url Absolute processed URL.
26 * Implements 3 interfaces:
27 * - ArrayAccess: behaves like an associative array;
28 * - Countable: there is a count() method;
29 * - Iterator: usable in foreach () loops.
31 class LinkDB
implements Iterator
, Countable
, ArrayAccess
33 // Links are stored as a PHP serialized string
36 // Link date storage format
37 const LINK_DATE_FORMAT
= 'Ymd_His';
39 // Datastore PHP prefix
40 protected static $phpPrefix = '<?php /* ';
42 // Datastore PHP suffix
43 protected static $phpSuffix = ' */ ?>';
45 // List of links (associative array)
46 // - key: link date (e.g. "20110823_124546"),
47 // - value: associative array (keys: title, description...)
50 // List of all recorded URLs (key=url, value=linkdate)
51 // for fast reserve search (url-->linkdate)
54 // List of linkdate keys (for the Iterator interface implementation)
57 // Position in the $this->_keys array (for the Iterator interface)
60 // Is the user logged in? (used to filter private links)
64 private $_hidePublicLinks;
66 // link redirector set in user settings.
70 * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched.
73 * anonym.to needs clean URL while dereferer.org needs urlencoded URL.
75 * @var boolean $redirectorEncode parameter: true or false
77 private $redirectorEncode;
80 * Creates a new LinkDB
82 * Checks if the datastore exists; else, attempts to create a dummy one.
84 * @param string $datastore datastore file path.
85 * @param boolean $isLoggedIn is the user logged in?
86 * @param boolean $hidePublicLinks if true all links are private.
87 * @param string $redirector link redirector set in user settings.
88 * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true).
95 $redirectorEncode = true
98 $this->_datastore
= $datastore;
99 $this->_loggedIn
= $isLoggedIn;
100 $this->_hidePublicLinks
= $hidePublicLinks;
101 $this->_redirector
= $redirector;
102 $this->redirectorEncode
= $redirectorEncode === true;
108 * Countable - Counts elements of an object
110 public function count()
112 return count($this->_links
);
116 * ArrayAccess - Assigns a value to the specified offset
118 public function offsetSet($offset, $value)
120 // TODO: use exceptions instead of "die"
121 if (!$this->_loggedIn
) {
122 die('You are not authorized to add a link.');
124 if (empty($value['linkdate']) || empty($value['url'])) {
125 die('Internal Error: A link should always have a linkdate and URL.');
127 if (empty($offset)) {
128 die('You must specify a key.');
130 $this->_links
[$offset] = $value;
131 $this->_urls
[$value['url']]=$offset;
135 * ArrayAccess - Whether or not an offset exists
137 public function offsetExists($offset)
139 return array_key_exists($offset, $this->_links
);
143 * ArrayAccess - Unsets an offset
145 public function offsetUnset($offset)
147 if (!$this->_loggedIn
) {
148 // TODO: raise an exception
149 die('You are not authorized to delete a link.');
151 $url = $this->_links
[$offset]['url'];
152 unset($this->_urls
[$url]);
153 unset($this->_links
[$offset]);
157 * ArrayAccess - Returns the value at specified offset
159 public function offsetGet($offset)
161 return isset($this->_links
[$offset]) ? $this->_links
[$offset] : null;
165 * Iterator - Returns the current element
169 return $this->_links
[$this->_keys
[$this->_position
]];
173 * Iterator - Returns the key of the current element
177 return $this->_keys
[$this->_position
];
181 * Iterator - Moves forward to next element
189 * Iterator - Rewinds the Iterator to the first element
191 * Entries are sorted by date (latest first)
195 $this->_keys
= array_keys($this->_links
);
197 $this->_position
= 0;
201 * Iterator - Checks if current position is valid
205 return isset($this->_keys
[$this->_position
]);
209 * Checks if the DB directory and file exist
211 * If no DB file is found, creates a dummy DB.
213 private function _checkDB()
215 if (file_exists($this->_datastore
)) {
219 // Create a dummy database for example
220 $this->_links
= array();
222 'title'=>' Shaarli: the personal, minimalist, super-fast, no-database delicious clone',
223 'url'=>'https://github.com/shaarli/Shaarli/wiki',
224 'description'=>'Welcome to Shaarli! This is your first public bookmark. To edit or delete me, you must first login.
226 To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page.
228 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.',
230 'linkdate'=> date('Ymd_His'),
231 'tags'=>'opensource software'
233 $this->_links
[$link['linkdate']] = $link;
236 'title'=>'My secret stuff... - Pastebin.com',
237 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
238 'description'=>'Shhhh! I\'m a private link only YOU can see. You can delete me too.',
240 'linkdate'=> date('Ymd_His', strtotime('-1 minute')),
241 'tags'=>'secretstuff'
243 $this->_links
[$link['linkdate']] = $link;
245 // Write database to disk
250 * Reads database from disk to memory
252 private function _readDB()
255 // Public links are hidden and user not logged in => nothing to show
256 if ($this->_hidePublicLinks
&& !$this->_loggedIn
) {
257 $this->_links
= array();
262 // Note that gzinflate is faster than gzuncompress.
263 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
264 $this->_links
= array();
266 if (file_exists($this->_datastore
)) {
267 $this->_links
= unserialize(gzinflate(base64_decode(
268 substr(file_get_contents($this->_datastore
),
269 strlen(self
::$phpPrefix), -strlen(self
::$phpSuffix)))));
272 // If user is not logged in, filter private links.
273 if (!$this->_loggedIn
) {
275 foreach ($this->_links
as $link) {
276 if ($link['private'] != 0) {
277 $toremove[] = $link['linkdate'];
280 foreach ($toremove as $linkdate) {
281 unset($this->_links
[$linkdate]);
285 $this->_urls
= array();
286 foreach ($this->_links
as &$link) {
287 // Keep the list of the mapping URLs-->linkdate up-to-date.
288 $this->_urls
[$link['url']] = $link['linkdate'];
290 // Sanitize data fields.
293 // Remove private tags if the user is not logged in.
294 if (! $this->_loggedIn
) {
295 $link['tags'] = preg_replace('/(^|\s+)\.[^($|\s)]+\s*/', ' ', $link['tags']);
298 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
299 if (!empty($this->_redirector
) && !startsWith($link['url'], '?')) {
300 $link['real_url'] = $this->_redirector
;
301 if ($this->redirectorEncode
) {
302 $link['real_url'] .= urlencode(unescape($link['url']));
304 $link['real_url'] .= $link['url'];
308 $link['real_url'] = $link['url'];
314 * Saves the database from memory to disk
316 * @throws IOException the datastore is not writable
318 private function writeDB()
320 if (is_file($this->_datastore
) && !is_writeable($this->_datastore
)) {
321 // The datastore exists but is not writeable
322 throw new IOException($this->_datastore
);
323 } else if (!is_file($this->_datastore
) && !is_writeable(dirname($this->_datastore
))) {
324 // The datastore does not exist and its parent directory is not writeable
325 throw new IOException(dirname($this->_datastore
));
330 self
::$phpPrefix.base64_encode(gzdeflate(serialize($this->_links
))).self
::$phpSuffix
336 * Saves the database from memory to disk
338 * @param string $pageCacheDir page cache directory
340 public function savedb($pageCacheDir)
342 if (!$this->_loggedIn
) {
343 // TODO: raise an Exception instead
344 die('You are not authorized to change the database.');
349 invalidateCaches($pageCacheDir);
353 * Returns the link for a given URL, or False if it does not exist.
355 * @param string $url URL to search for
357 * @return mixed the existing link if it exists, else 'false'
359 public function getLinkFromUrl($url)
361 if (isset($this->_urls
[$url])) {
362 return $this->_links
[$this->_urls
[$url]];
368 * Returns the shaare corresponding to a smallHash.
370 * @param string $request QUERY_STRING server parameter.
372 * @return array $filtered array containing permalink data.
374 * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link.
376 public function filterHash($request)
378 $request = substr($request, 0, 6);
379 $linkFilter = new LinkFilter($this->_links
);
380 return $linkFilter->filter(LinkFilter
::$FILTER_HASH, $request);
384 * Returns the list of articles for a given day.
386 * @param string $request day to filter. Format: YYYYMMDD.
388 * @return array list of shaare found.
390 public function filterDay($request) {
391 $linkFilter = new LinkFilter($this->_links
);
392 return $linkFilter->filter(LinkFilter
::$FILTER_DAY, $request);
396 * Filter links according to search parameters.
398 * @param array $filterRequest Search request content. Supported keys:
399 * - searchtags: list of tags
400 * - searchterm: term search
401 * @param bool $casesensitive Optional: Perform case sensitive filter
402 * @param bool $privateonly Optional: Returns private links only if true.
404 * @return array filtered links, all links if no suitable filter was provided.
406 public function filterSearch($filterRequest = array(), $casesensitive = false, $privateonly = false)
408 // Filter link database according to parameters.
409 $searchtags = !empty($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
410 $searchterm = !empty($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
412 // Search tags + fullsearch.
413 if (! empty($searchtags) && ! empty($searchterm)) {
414 $type = LinkFilter
::$FILTER_TAG | LinkFilter
::$FILTER_TEXT;
415 $request = array($searchtags, $searchterm);
418 elseif (! empty($searchtags)) {
419 $type = LinkFilter
::$FILTER_TAG;
420 $request = $searchtags;
423 elseif (! empty($searchterm)) {
424 $type = LinkFilter
::$FILTER_TEXT;
425 $request = $searchterm;
427 // Otherwise, display without filtering.
433 $linkFilter = new LinkFilter($this->_links
);
434 return $linkFilter->filter($type, $request, $casesensitive, $privateonly);
438 * Returns the list of all tags
439 * Output: associative array key=tags, value=0
441 public function allTags()
444 $caseMapping = array();
445 foreach ($this->_links
as $link) {
446 foreach (preg_split('/\s+/', $link['tags'], 0, PREG_SPLIT_NO_EMPTY
) as $tag) {
450 // The first case found will be displayed.
451 if (!isset($caseMapping[strtolower($tag)])) {
452 $caseMapping[strtolower($tag)] = $tag;
453 $tags[$caseMapping[strtolower($tag)]] = 0;
455 $tags[$caseMapping[strtolower($tag)]]++
;
458 // Sort tags by usage (most used tag first)
464 * Returns the list of days containing articles (oldest first)
465 * Output: An array containing days (in format YYYYMMDD).
467 public function days()
470 foreach (array_keys($this->_links
) as $day) {
471 $linkDays[substr($day, 0, 8)] = 0;
473 $linkDays = array_keys($linkDays);