3 namespace Shaarli\Legacy
;
9 use Shaarli\Bookmark\Exception\BookmarkNotFoundException
;
10 use Shaarli\Exceptions\IOException
;
11 use Shaarli\Helper\FileUtils
;
12 use Shaarli\Render\PageCacheManager
;
15 * Data storage for bookmarks.
17 * This object behaves like an associative array.
20 * $myLinks = new LinkDB();
21 * echo $myLinks[350]['title'];
22 * foreach ($myLinks as $link)
23 * echo $link['title'].' at url '.$link['url'].'; description:'.$link['description'];
26 * - id: primary key, incremental integer identifier (persistent)
27 * - description: description of the entry
28 * - created: creation date of this entry, DateTime object.
29 * - updated: last modification date of this entry, DateTime object.
30 * - private: Is this link private? 0=no, other value=yes
31 * - tags: tags attached to this entry (separated by spaces)
32 * - title Title of the link
33 * - url URL of the link. Used for displayable bookmarks.
34 * Can be absolute or relative in the database but the relative bookmarks
35 * will be converted to absolute ones in templates.
36 * - real_url Raw URL in stored in the DB (absolute or relative).
37 * - shorturl Permalink smallhash
39 * Implements 3 interfaces:
40 * - ArrayAccess: behaves like an associative array;
41 * - Countable: there is a count() method;
42 * - Iterator: usable in foreach () loops.
45 * ArrayAccess is implemented in a way that will allow to access a link
46 * with the unique identifier ID directly with $link[ID].
47 * Note that it's not the real key of the link array attribute.
48 * This mechanism is in place to have persistent link IDs,
49 * even though the internal array is reordered by date.
51 * - DB: link #1 (2010-01-01) link #2 (2016-01-01)
53 * - Import bookmarks containing: link #3 (2013-01-01)
54 * - New DB: link #1 (2010-01-01) link #2 (2016-01-01) link #3 (2013-01-01)
55 * - Real order: #2 #3 #1
59 class LegacyLinkDB
implements Iterator
, Countable
, ArrayAccess
61 // Links are stored as a PHP serialized string
64 // Link date storage format
65 public const LINK_DATE_FORMAT
= 'Ymd_His';
67 // List of bookmarks (associative array)
68 // - key: link date (e.g. "20110823_124546"),
69 // - value: associative array (keys: title, description...)
72 // List of all recorded URLs (key=url, value=link offset)
73 // for fast reserve search (url-->link offset)
77 * @var array List of all bookmarks IDS mapped with their array offset.
82 // List of offset keys (for the Iterator interface implementation)
85 // Position in the $this->keys array (for the Iterator interface)
88 // Is the user logged in? (used to filter private bookmarks)
91 // Hide public bookmarks
92 private $hidePublicLinks;
95 * Creates a new LinkDB
97 * Checks if the datastore exists; else, attempts to create a dummy one.
99 * @param string $datastore datastore file path.
100 * @param boolean $isLoggedIn is the user logged in?
101 * @param boolean $hidePublicLinks if true all bookmarks are private.
103 public function __construct(
109 $this->datastore
= $datastore;
110 $this->loggedIn
= $isLoggedIn;
111 $this->hidePublicLinks
= $hidePublicLinks;
117 * Countable - Counts elements of an object
119 public function count()
121 return count($this->links
);
125 * ArrayAccess - Assigns a value to the specified offset
127 public function offsetSet($offset, $value)
129 // TODO: use exceptions instead of "die"
130 if (!$this->loggedIn
) {
131 die(t('You are not authorized to add a link.'));
133 if (!isset($value['id']) || empty($value['url'])) {
134 die(t('Internal Error: A link should always have an id and URL.'));
136 if (($offset !== null && !is_int($offset)) || !is_int($value['id'])) {
137 die(t('You must specify an integer as a key.'));
139 if ($offset !== null && $offset !== $value['id']) {
140 die(t('Array offset and link ID must be equal.'));
143 // If the link exists, we reuse the real offset, otherwise new entry
144 $existing = $this->getLinkOffset($offset);
145 if ($existing !== null) {
148 $offset = count($this->links
);
150 $this->links
[$offset] = $value;
151 $this->urls
[$value['url']] = $offset;
152 $this->ids
[$value['id']] = $offset;
156 * ArrayAccess - Whether or not an offset exists
158 public function offsetExists($offset)
160 return array_key_exists($this->getLinkOffset($offset), $this->links
);
164 * ArrayAccess - Unsets an offset
166 public function offsetUnset($offset)
168 if (!$this->loggedIn
) {
169 // TODO: raise an exception
170 die('You are not authorized to delete a link.');
172 $realOffset = $this->getLinkOffset($offset);
173 $url = $this->links
[$realOffset]['url'];
174 unset($this->urls
[$url]);
175 unset($this->ids
[$realOffset]);
176 unset($this->links
[$realOffset]);
180 * ArrayAccess - Returns the value at specified offset
182 public function offsetGet($offset)
184 $realOffset = $this->getLinkOffset($offset);
185 return isset($this->links
[$realOffset]) ? $this->links
[$realOffset] : null;
189 * Iterator - Returns the current element
191 public function current()
193 return $this[$this->keys
[$this->position
]];
197 * Iterator - Returns the key of the current element
199 public function key()
201 return $this->keys
[$this->position
];
205 * Iterator - Moves forward to next element
207 public function next()
213 * Iterator - Rewinds the Iterator to the first element
215 * Entries are sorted by date (latest first)
217 public function rewind()
219 $this->keys
= array_keys($this->ids
);
224 * Iterator - Checks if current position is valid
226 public function valid()
228 return isset($this->keys
[$this->position
]);
232 * Checks if the DB directory and file exist
234 * If no DB file is found, creates a dummy DB.
236 private function check()
238 if (file_exists($this->datastore
)) {
242 // Create a dummy database for example
246 'title' => t('The personal, minimalist, super-fast, database free, bookmarking service'),
247 'url' => 'https://shaarli.readthedocs.io',
249 'Welcome to Shaarli! This is your first public bookmark. '
250 . 'To edit or delete me, you must first login.
252 To learn how to use Shaarli, consult the link "Documentation" at the bottom of this page.
254 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.'
257 'created' => new DateTime(),
258 'tags' => 'opensource software',
261 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
262 $this->links
[1] = $link;
266 'title' => t('My secret stuff... - Pastebin.com'),
267 'url' => 'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
268 'description' => t('Shhhh! I\'m a private link only YOU can see. You can delete me too.'),
270 'created' => new DateTime('1 minute ago'),
271 'tags' => 'secretstuff',
274 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
275 $this->links
[0] = $link;
277 // Write database to disk
282 * Reads database from disk to memory
284 private function read()
286 // Public bookmarks are hidden and user not logged in => nothing to show
287 if ($this->hidePublicLinks
&& !$this->loggedIn
) {
294 $this->links
= FileUtils
::readFlatDB($this->datastore
, []);
297 foreach ($this->links
as $key => &$link) {
298 if (!$this->loggedIn
&& $link['private'] != 0) {
299 // Transition for not upgraded databases.
300 unset($this->links
[$key]);
304 // Sanitize data fields.
307 // Remove private tags if the user is not logged in.
308 if (!$this->loggedIn
) {
309 $link['tags'] = preg_replace('/(^|\s+)\.[^($|\s)]+\s*/', ' ', $link['tags']);
312 $link['real_url'] = $link['url'];
314 $link['sticky'] = isset($link['sticky']) ? $link['sticky'] : false;
316 // To be able to load bookmarks before running the update, and prepare the update
317 if (!isset($link['created'])) {
318 $link['id'] = $link['linkdate'];
319 $link['created'] = DateTime
::createFromFormat(self
::LINK_DATE_FORMAT
, $link['linkdate']);
320 if (!empty($link['updated'])) {
321 $link['updated'] = DateTime
::createFromFormat(self
::LINK_DATE_FORMAT
, $link['updated']);
323 $link['shorturl'] = smallHash($link['linkdate']);
326 $this->urls
[$link['url']] = $key;
327 $this->ids
[$link['id']] = $key;
332 * Saves the database from memory to disk
334 * @throws IOException the datastore is not writable
336 private function write()
339 FileUtils
::writeFlatDB($this->datastore
, $this->links
);
343 * Saves the database from memory to disk
345 * @param string $pageCacheDir page cache directory
347 public function save($pageCacheDir)
349 if (!$this->loggedIn
) {
350 // TODO: raise an Exception instead
351 die('You are not authorized to change the database.');
356 $pageCacheManager = new PageCacheManager($pageCacheDir, $this->loggedIn
);
357 $pageCacheManager->invalidateCaches();
361 * Returns the link for a given URL, or False if it does not exist.
363 * @param string $url URL to search for
365 * @return mixed the existing link if it exists, else 'false'
367 public function getLinkFromUrl($url)
369 if (isset($this->urls
[$url])) {
370 return $this->links
[$this->urls
[$url]];
376 * Returns the shaare corresponding to a smallHash.
378 * @param string $request QUERY_STRING server parameter.
380 * @return array $filtered array containing permalink data.
382 * @throws BookmarkNotFoundException if the smallhash is malformed or doesn't match any link.
384 public function filterHash($request)
386 $request = substr($request, 0, 6);
387 $linkFilter = new LegacyLinkFilter($this->links
);
388 return $linkFilter->filter(LegacyLinkFilter
::$FILTER_HASH, $request);
392 * Returns the list of articles for a given day.
394 * @param string $request day to filter. Format: YYYYMMDD.
396 * @return array list of shaare found.
398 public function filterDay($request)
400 $linkFilter = new LegacyLinkFilter($this->links
);
401 return $linkFilter->filter(LegacyLinkFilter
::$FILTER_DAY, $request);
405 * Filter bookmarks according to search parameters.
407 * @param array $filterRequest Search request content. Supported keys:
408 * - searchtags: list of tags
409 * - searchterm: term search
410 * @param bool $casesensitive Optional: Perform case sensitive filter
411 * @param string $visibility return only all/private/public bookmarks
412 * @param bool $untaggedonly return only untagged bookmarks
414 * @return array filtered bookmarks, all bookmarks if no suitable filter was provided.
416 public function filterSearch(
418 $casesensitive = false,
420 $untaggedonly = false
423 // Filter link database according to parameters.
424 $searchtags = isset($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
425 $searchterm = isset($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
427 // Search tags + fullsearch - blank string parameter will return all bookmarks.
428 $type = LegacyLinkFilter
::$FILTER_TAG | LegacyLinkFilter
::$FILTER_TEXT; // == "vuotext"
429 $request = [$searchtags, $searchterm];
431 $linkFilter = new LegacyLinkFilter($this);
432 return $linkFilter->filter($type, $request, $casesensitive, $visibility, $untaggedonly);
436 * Returns the list tags appearing in the bookmarks with the given tags
438 * @param array $filteringTags tags selecting the bookmarks to consider
439 * @param string $visibility process only all/private/public bookmarks
441 * @return array tag => linksCount
443 public function linksCountPerTag($filteringTags = [], $visibility = 'all')
445 $links = $this->filterSearch(['searchtags' => $filteringTags], false, $visibility);
448 foreach ($links as $link) {
449 foreach (preg_split('/\s+/', $link['tags'], 0, PREG_SPLIT_NO_EMPTY
) as $tag) {
453 // The first case found will be displayed.
454 if (!isset($caseMapping[strtolower($tag)])) {
455 $caseMapping[strtolower($tag)] = $tag;
456 $tags[$caseMapping[strtolower($tag)]] = 0;
458 $tags[$caseMapping[strtolower($tag)]]++
;
463 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
464 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
466 * So we now use array_multisort() to sort tags by DESC occurrences,
467 * then ASC alphabetically for equal values.
469 * @see https://github.com/shaarli/Shaarli/issues/1142
471 $keys = array_keys($tags);
472 $tmpTags = array_combine($keys, $keys);
473 array_multisort($tags, SORT_DESC
, $tmpTags, SORT_ASC
, $tags);
478 * Rename or delete a tag across all bookmarks.
480 * @param string $from Tag to rename
481 * @param string $to New tag. If none is provided, the from tag will be deleted
483 * @return array|bool List of altered bookmarks or false on error
485 public function renameTag($from, $to)
490 $delete = empty($to);
491 // True for case-sensitive tag search.
492 $linksToAlter = $this->filterSearch(['searchtags' => $from], true);
493 foreach ($linksToAlter as $key => &$value) {
494 $tags = preg_split('/\s+/', trim($value['tags']));
495 if (($pos = array_search($from, $tags)) !== false) {
497 unset($tags[$pos]); // Remove tag.
499 $tags[$pos] = trim($to);
501 $value['tags'] = trim(implode(' ', array_unique($tags)));
502 $this[$value['id']] = $value;
506 return $linksToAlter;
510 * Returns the list of days containing articles (oldest first)
511 * Output: An array containing days (in format YYYYMMDD).
513 public function days()
516 foreach ($this->links
as $link) {
517 $linkDays[$link['created']->format('Ymd')] = 0;
519 $linkDays = array_keys($linkDays);
526 * Reorder bookmarks by creation date (newest first).
528 * Also update the urls and ids mapping arrays.
530 * @param string $order ASC|DESC
532 public function reorder($order = 'DESC')
534 $order = $order === 'ASC' ? -1 : 1;
535 // Reorder array by dates.
536 usort($this->links
, function ($a, $b) use ($order) {
537 if (isset($a['sticky']) && isset($b['sticky']) && $a['sticky'] !== $b['sticky']) {
538 return $a['sticky'] ? -1 : 1;
540 if ($a['created'] == $b['created']) {
541 return $a['id'] < $b['id'] ? 1 * $order : -1 * $order;
543 return $a['created'] < $b['created'] ? 1 * $order : -1 * $order;
548 foreach ($this->links
as $key => $link) {
549 $this->urls
[$link['url']] = $key;
550 $this->ids
[$link['id']] = $key;
555 * Return the next key for link creation.
556 * E.g. If the last ID is 597, the next will be 598.
558 * @return int next ID.
560 public function getNextId()
562 if (!empty($this->ids
)) {
563 return max(array_keys($this->ids
)) +
1;
569 * Returns a link offset in bookmarks array from its unique ID.
571 * @param int $id Persistent ID of a link.
573 * @return int Real offset in local array, or null if doesn't exist.
575 protected function getLinkOffset($id)
577 if (isset($this->ids
[$id])) {
578 return $this->ids
[$id];