3 use Shaarli\Exceptions\IOException
;
6 * Data storage for links.
8 * This object behaves like an associative array.
11 * $myLinks = new LinkDB();
12 * echo $myLinks[350]['title'];
13 * foreach ($myLinks as $link)
14 * echo $link['title'].' at url '.$link['url'].'; description:'.$link['description'];
17 * - id: primary key, incremental integer identifier (persistent)
18 * - description: description of the entry
19 * - created: creation date of this entry, DateTime object.
20 * - updated: last modification date of this entry, DateTime object.
21 * - private: Is this link private? 0=no, other value=yes
22 * - tags: tags attached to this entry (separated by spaces)
23 * - title Title of the link
24 * - url URL of the link. Used for displayable links (no redirector, relative, etc.).
25 * Can be absolute or relative.
26 * Relative URLs are permalinks (e.g.'?m-ukcw')
27 * - real_url Absolute processed URL.
28 * - shorturl Permalink smallhash
30 * Implements 3 interfaces:
31 * - ArrayAccess: behaves like an associative array;
32 * - Countable: there is a count() method;
33 * - Iterator: usable in foreach () loops.
36 * ArrayAccess is implemented in a way that will allow to access a link
37 * with the unique identifier ID directly with $link[ID].
38 * Note that it's not the real key of the link array attribute.
39 * This mechanism is in place to have persistent link IDs,
40 * even though the internal array is reordered by date.
42 * - DB: link #1 (2010-01-01) link #2 (2016-01-01)
44 * - Import links containing: link #3 (2013-01-01)
45 * - New DB: link #1 (2010-01-01) link #2 (2016-01-01) link #3 (2013-01-01)
46 * - Real order: #2 #3 #1
48 class LinkDB
implements Iterator
, Countable
, ArrayAccess
50 // Links are stored as a PHP serialized string
53 // Link date storage format
54 const LINK_DATE_FORMAT
= 'Ymd_His';
56 // List of links (associative array)
57 // - key: link date (e.g. "20110823_124546"),
58 // - value: associative array (keys: title, description...)
61 // List of all recorded URLs (key=url, value=link offset)
62 // for fast reserve search (url-->link offset)
66 * @var array List of all links IDS mapped with their array offset.
71 // List of offset keys (for the Iterator interface implementation)
74 // Position in the $this->keys array (for the Iterator interface)
77 // Is the user logged in? (used to filter private links)
81 private $hidePublicLinks;
83 // link redirector set in user settings.
87 * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched.
90 * anonym.to needs clean URL while dereferer.org needs urlencoded URL.
92 * @var boolean $redirectorEncode parameter: true or false
94 private $redirectorEncode;
97 * Creates a new LinkDB
99 * Checks if the datastore exists; else, attempts to create a dummy one.
101 * @param string $datastore datastore file path.
102 * @param boolean $isLoggedIn is the user logged in?
103 * @param boolean $hidePublicLinks if true all links are private.
104 * @param string $redirector link redirector set in user settings.
105 * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true).
107 public function __construct(
112 $redirectorEncode = true
114 $this->datastore
= $datastore;
115 $this->loggedIn
= $isLoggedIn;
116 $this->hidePublicLinks
= $hidePublicLinks;
117 $this->redirector
= $redirector;
118 $this->redirectorEncode
= $redirectorEncode === true;
124 * Countable - Counts elements of an object
126 public function count()
128 return count($this->links
);
132 * ArrayAccess - Assigns a value to the specified offset
134 public function offsetSet($offset, $value)
136 // TODO: use exceptions instead of "die"
137 if (!$this->loggedIn
) {
138 die(t('You are not authorized to add a link.'));
140 if (!isset($value['id']) || empty($value['url'])) {
141 die(t('Internal Error: A link should always have an id and URL.'));
143 if (($offset !== null && ! is_int($offset)) || ! is_int($value['id'])) {
144 die(t('You must specify an integer as a key.'));
146 if ($offset !== null && $offset !== $value['id']) {
147 die(t('Array offset and link ID must be equal.'));
150 // If the link exists, we reuse the real offset, otherwise new entry
151 $existing = $this->getLinkOffset($offset);
152 if ($existing !== null) {
155 $offset = count($this->links
);
157 $this->links
[$offset] = $value;
158 $this->urls
[$value['url']] = $offset;
159 $this->ids
[$value['id']] = $offset;
163 * ArrayAccess - Whether or not an offset exists
165 public function offsetExists($offset)
167 return array_key_exists($this->getLinkOffset($offset), $this->links
);
171 * ArrayAccess - Unsets an offset
173 public function offsetUnset($offset)
175 if (!$this->loggedIn
) {
176 // TODO: raise an exception
177 die('You are not authorized to delete a link.');
179 $realOffset = $this->getLinkOffset($offset);
180 $url = $this->links
[$realOffset]['url'];
181 unset($this->urls
[$url]);
182 unset($this->ids
[$realOffset]);
183 unset($this->links
[$realOffset]);
187 * ArrayAccess - Returns the value at specified offset
189 public function offsetGet($offset)
191 $realOffset = $this->getLinkOffset($offset);
192 return isset($this->links
[$realOffset]) ? $this->links
[$realOffset] : null;
196 * Iterator - Returns the current element
198 public function current()
200 return $this[$this->keys
[$this->position
]];
204 * Iterator - Returns the key of the current element
206 public function key()
208 return $this->keys
[$this->position
];
212 * Iterator - Moves forward to next element
214 public function next()
220 * Iterator - Rewinds the Iterator to the first element
222 * Entries are sorted by date (latest first)
224 public function rewind()
226 $this->keys
= array_keys($this->ids
);
231 * Iterator - Checks if current position is valid
233 public function valid()
235 return isset($this->keys
[$this->position
]);
239 * Checks if the DB directory and file exist
241 * If no DB file is found, creates a dummy DB.
243 private function check()
245 if (file_exists($this->datastore
)) {
249 // Create a dummy database for example
250 $this->links
= array();
253 'title'=> t('The personal, minimalist, super-fast, database free, bookmarking service'),
254 'url'=>'https://shaarli.readthedocs.io',
256 'Welcome to Shaarli! This is your first public bookmark. '
257 .'To edit or delete me, you must first login.
259 To learn how to use Shaarli, consult the link "Documentation" at the bottom of this page.
261 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.'
264 'created'=> new DateTime(),
265 'tags'=>'opensource software'
267 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
268 $this->links
[1] = $link;
272 'title'=> t('My secret stuff... - Pastebin.com'),
273 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
274 'description'=> t('Shhhh! I\'m a private link only YOU can see. You can delete me too.'),
276 'created'=> new DateTime('1 minute ago'),
277 'tags'=>'secretstuff',
279 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
280 $this->links
[0] = $link;
282 // Write database to disk
287 * Reads database from disk to memory
289 private function read()
291 // Public links are hidden and user not logged in => nothing to show
292 if ($this->hidePublicLinks
&& !$this->loggedIn
) {
293 $this->links
= array();
299 $this->links
= FileUtils
::readFlatDB($this->datastore
, []);
302 foreach ($this->links
as $key => &$link) {
303 if (! $this->loggedIn
&& $link['private'] != 0) {
304 // Transition for not upgraded databases.
305 unset($this->links
[$key]);
309 // Sanitize data fields.
312 // Remove private tags if the user is not logged in.
313 if (! $this->loggedIn
) {
314 $link['tags'] = preg_replace('/(^|\s+)\.[^($|\s)]+\s*/', ' ', $link['tags']);
317 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
318 if (!empty($this->redirector
) && !startsWith($link['url'], '?')) {
319 $link['real_url'] = $this->redirector
;
320 if ($this->redirectorEncode
) {
321 $link['real_url'] .= urlencode(unescape($link['url']));
323 $link['real_url'] .= $link['url'];
326 $link['real_url'] = $link['url'];
329 // To be able to load links before running the update, and prepare the update
330 if (! isset($link['created'])) {
331 $link['id'] = $link['linkdate'];
332 $link['created'] = DateTime
::createFromFormat(self
::LINK_DATE_FORMAT
, $link['linkdate']);
333 if (! empty($link['updated'])) {
334 $link['updated'] = DateTime
::createFromFormat(self
::LINK_DATE_FORMAT
, $link['updated']);
336 $link['shorturl'] = smallHash($link['linkdate']);
339 $this->urls
[$link['url']] = $key;
340 $this->ids
[$link['id']] = $key;
345 * Saves the database from memory to disk
347 * @throws IOException the datastore is not writable
349 private function write()
352 FileUtils
::writeFlatDB($this->datastore
, $this->links
);
356 * Saves the database from memory to disk
358 * @param string $pageCacheDir page cache directory
360 public function save($pageCacheDir)
362 if (!$this->loggedIn
) {
363 // TODO: raise an Exception instead
364 die('You are not authorized to change the database.');
369 invalidateCaches($pageCacheDir);
373 * Returns the link for a given URL, or False if it does not exist.
375 * @param string $url URL to search for
377 * @return mixed the existing link if it exists, else 'false'
379 public function getLinkFromUrl($url)
381 if (isset($this->urls
[$url])) {
382 return $this->links
[$this->urls
[$url]];
388 * Returns the shaare corresponding to a smallHash.
390 * @param string $request QUERY_STRING server parameter.
392 * @return array $filtered array containing permalink data.
394 * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link.
396 public function filterHash($request)
398 $request = substr($request, 0, 6);
399 $linkFilter = new LinkFilter($this->links
);
400 return $linkFilter->filter(LinkFilter
::$FILTER_HASH, $request);
404 * Returns the list of articles for a given day.
406 * @param string $request day to filter. Format: YYYYMMDD.
408 * @return array list of shaare found.
410 public function filterDay($request)
412 $linkFilter = new LinkFilter($this->links
);
413 return $linkFilter->filter(LinkFilter
::$FILTER_DAY, $request);
417 * Filter links according to search parameters.
419 * @param array $filterRequest Search request content. Supported keys:
420 * - searchtags: list of tags
421 * - searchterm: term search
422 * @param bool $casesensitive Optional: Perform case sensitive filter
423 * @param string $visibility return only all/private/public links
424 * @param string $untaggedonly return only untagged links
426 * @return array filtered links, all links if no suitable filter was provided.
428 public function filterSearch(
429 $filterRequest = array(),
430 $casesensitive = false,
432 $untaggedonly = false
434 // Filter link database according to parameters.
435 $searchtags = isset($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
436 $searchterm = isset($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
438 // Search tags + fullsearch - blank string parameter will return all links.
439 $type = LinkFilter
::$FILTER_TAG | LinkFilter
::$FILTER_TEXT; // == "vuotext"
440 $request = [$searchtags, $searchterm];
442 $linkFilter = new LinkFilter($this);
443 return $linkFilter->filter($type, $request, $casesensitive, $visibility, $untaggedonly);
447 * Returns the list tags appearing in the links with the given tags
449 * @param array $filteringTags tags selecting the links to consider
450 * @param string $visibility process only all/private/public links
452 * @return array tag => linksCount
454 public function linksCountPerTag($filteringTags = [], $visibility = 'all')
456 $links = $this->filterSearch(['searchtags' => $filteringTags], false, $visibility);
459 foreach ($links as $link) {
460 foreach (preg_split('/\s+/', $link['tags'], 0, PREG_SPLIT_NO_EMPTY
) as $tag) {
464 // The first case found will be displayed.
465 if (!isset($caseMapping[strtolower($tag)])) {
466 $caseMapping[strtolower($tag)] = $tag;
467 $tags[$caseMapping[strtolower($tag)]] = 0;
469 $tags[$caseMapping[strtolower($tag)]]++
;
474 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
475 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
477 * So we now use array_multisort() to sort tags by DESC occurrences,
478 * then ASC alphabetically for equal values.
480 * @see https://github.com/shaarli/Shaarli/issues/1142
482 $keys = array_keys($tags);
483 $tmpTags = array_combine($keys, $keys);
484 array_multisort($tags, SORT_DESC
, $tmpTags, SORT_ASC
, $tags);
489 * Rename or delete a tag across all links.
491 * @param string $from Tag to rename
492 * @param string $to New tag. If none is provided, the from tag will be deleted
494 * @return array|bool List of altered links or false on error
496 public function renameTag($from, $to)
501 $delete = empty($to);
502 // True for case-sensitive tag search.
503 $linksToAlter = $this->filterSearch(['searchtags' => $from], true);
504 foreach ($linksToAlter as $key => &$value) {
505 $tags = preg_split('/\s+/', trim($value['tags']));
506 if (($pos = array_search($from, $tags)) !== false) {
508 unset($tags[$pos]); // Remove tag.
510 $tags[$pos] = trim($to);
512 $value['tags'] = trim(implode(' ', array_unique($tags)));
513 $this[$value['id']] = $value;
517 return $linksToAlter;
521 * Returns the list of days containing articles (oldest first)
522 * Output: An array containing days (in format YYYYMMDD).
524 public function days()
527 foreach ($this->links
as $link) {
528 $linkDays[$link['created']->format('Ymd')] = 0;
530 $linkDays = array_keys($linkDays);
537 * Reorder links by creation date (newest first).
539 * Also update the urls and ids mapping arrays.
541 * @param string $order ASC|DESC
543 public function reorder($order = 'DESC')
545 $order = $order === 'ASC' ? -1 : 1;
546 // Reorder array by dates.
547 usort($this->links
, function ($a, $b) use ($order) {
548 if (isset($a['sticky']) && isset($b['sticky']) && $a['sticky'] !== $b['sticky']) {
549 return $a['sticky'] ? -1 : 1;
551 return $a['created'] < $b['created'] ? 1 * $order : -1 * $order;
556 foreach ($this->links
as $key => $link) {
557 $this->urls
[$link['url']] = $key;
558 $this->ids
[$link['id']] = $key;
563 * Return the next key for link creation.
564 * E.g. If the last ID is 597, the next will be 598.
566 * @return int next ID.
568 public function getNextId()
570 if (!empty($this->ids
)) {
571 return max(array_keys($this->ids
)) +
1;
577 * Returns a link offset in links array from its unique ID.
579 * @param int $id Persistent ID of a link.
581 * @return int Real offset in local array, or null if doesn't exist.
583 protected function getLinkOffset($id)
585 if (isset($this->ids
[$id])) {
586 return $this->ids
[$id];