3 declare(strict_types
=1);
5 namespace Shaarli\Bookmark
;
9 use malkusch\lock\mutex\Mutex
;
10 use Shaarli\Bookmark\Exception\BookmarkNotFoundException
;
11 use Shaarli\Bookmark\Exception\DatastoreNotInitializedException
;
12 use Shaarli\Bookmark\Exception\EmptyDataStoreException
;
13 use Shaarli\Config\ConfigManager
;
14 use Shaarli\Formatter\BookmarkMarkdownFormatter
;
16 use Shaarli\Legacy\LegacyLinkDB
;
17 use Shaarli\Legacy\LegacyUpdater
;
18 use Shaarli\Render\PageCacheManager
;
19 use Shaarli\Updater\UpdaterUtils
;
22 * Class BookmarksService
24 * This is the entry point to manipulate the bookmark DB.
25 * It manipulates loads links from a file data store containing all bookmarks.
27 * It also triggers the legacy format (bookmarks as arrays) migration.
29 class BookmarkFileService
implements BookmarkServiceInterface
31 /** @var Bookmark[] instance */
34 /** @var BookmarkIO instance */
35 protected $bookmarksIO;
37 /** @var BookmarkFilter */
38 protected $bookmarkFilter;
40 /** @var ConfigManager instance */
43 /** @var History instance */
46 /** @var PageCacheManager instance */
47 protected $pageCacheManager;
49 /** @var bool true for logged in users. Default value to retrieve private bookmarks. */
50 protected $isLoggedIn;
58 public function __construct(ConfigManager
$conf, History
$history, Mutex
$mutex, bool $isLoggedIn)
61 $this->history
= $history;
62 $this->mutex
= $mutex;
63 $this->pageCacheManager
= new PageCacheManager($this->conf
->get('resource.page_cache'), $isLoggedIn);
64 $this->bookmarksIO
= new BookmarkIO($this->conf
, $this->mutex
);
65 $this->isLoggedIn
= $isLoggedIn;
67 if (!$this->isLoggedIn
&& $this->conf
->get('privacy.hide_public_links', false)) {
68 $this->bookmarks
= [];
71 $this->bookmarks
= $this->bookmarksIO
->read();
72 } catch (EmptyDataStoreException
| DatastoreNotInitializedException
$e) {
73 $this->bookmarks
= new BookmarkArray();
75 if ($this->isLoggedIn
) {
76 // Datastore file does not exists, we initialize it with default bookmarks.
77 if ($e instanceof DatastoreNotInitializedException
) {
85 if (! $this->bookmarks
instanceof BookmarkArray
) {
88 'Your data store has been migrated, please reload the page.' . PHP_EOL
.
89 'If this message keeps showing up, please delete data/updates.txt file.'
94 $this->bookmarkFilter
= new BookmarkFilter($this->bookmarks
, $this->conf
);
100 public function findByHash(string $hash, string $privateKey = null): Bookmark
102 $bookmark = $this->bookmarkFilter
->filter(BookmarkFilter
::$FILTER_HASH, $hash);
103 // PHP 7.3 introduced array_key_first() to avoid this hack
104 $first = reset($bookmark);
107 && $first->isPrivate()
108 && (empty($privateKey) || $privateKey !== $first->getAdditionalContentEntry('private_key'))
110 throw new BookmarkNotFoundException();
119 public function findByUrl(string $url): ?Bookmark
121 return $this->bookmarks
->getByUrl($url);
127 public function search(
129 string $visibility = null,
130 bool $caseSensitive = false,
131 bool $untaggedOnly = false,
132 bool $ignoreSticky = false
134 if ($visibility === null) {
135 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
138 // Filter bookmark database according to parameters.
139 $searchTags = isset($request['searchtags']) ? $request['searchtags'] : '';
140 $searchTerm = isset($request['searchterm']) ? $request['searchterm'] : '';
143 $this->bookmarks
->reorder('DESC', true);
146 return $this->bookmarkFilter
->filter(
147 BookmarkFilter
::$FILTER_TAG | BookmarkFilter
::$FILTER_TEXT,
148 [$searchTags, $searchTerm],
158 public function get(int $id, string $visibility = null): Bookmark
160 if (! isset($this->bookmarks
[$id])) {
161 throw new BookmarkNotFoundException();
164 if ($visibility === null) {
165 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
168 $bookmark = $this->bookmarks
[$id];
170 ($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
171 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
173 throw new Exception('Unauthorized');
182 public function set(Bookmark
$bookmark, bool $save = true): Bookmark
184 if (true !== $this->isLoggedIn
) {
185 throw new Exception(t('You\'re not authorized to alter the datastore'));
187 if (! isset($this->bookmarks
[$bookmark->getId()])) {
188 throw new BookmarkNotFoundException();
190 $bookmark->validate();
192 $bookmark->setUpdated(new DateTime());
193 $this->bookmarks
[$bookmark->getId()] = $bookmark;
194 if ($save === true) {
196 $this->history
->updateLink($bookmark);
198 return $this->bookmarks
[$bookmark->getId()];
204 public function add(Bookmark
$bookmark, bool $save = true): Bookmark
206 if (true !== $this->isLoggedIn
) {
207 throw new Exception(t('You\'re not authorized to alter the datastore'));
209 if (!empty($bookmark->getId())) {
210 throw new Exception(t('This bookmarks already exists'));
212 $bookmark->setId($this->bookmarks
->getNextId());
213 $bookmark->validate();
215 $this->bookmarks
[$bookmark->getId()] = $bookmark;
216 if ($save === true) {
218 $this->history
->addLink($bookmark);
220 return $this->bookmarks
[$bookmark->getId()];
226 public function addOrSet(Bookmark
$bookmark, bool $save = true): Bookmark
228 if (true !== $this->isLoggedIn
) {
229 throw new Exception(t('You\'re not authorized to alter the datastore'));
231 if ($bookmark->getId() === null) {
232 return $this->add($bookmark, $save);
234 return $this->set($bookmark, $save);
240 public function remove(Bookmark
$bookmark, bool $save = true): void
242 if (true !== $this->isLoggedIn
) {
243 throw new Exception(t('You\'re not authorized to alter the datastore'));
245 if (! isset($this->bookmarks
[$bookmark->getId()])) {
246 throw new BookmarkNotFoundException();
249 unset($this->bookmarks
[$bookmark->getId()]);
250 if ($save === true) {
252 $this->history
->deleteLink($bookmark);
259 public function exists(int $id, string $visibility = null): bool
261 if (! isset($this->bookmarks
[$id])) {
265 if ($visibility === null) {
266 $visibility = $this->isLoggedIn
? 'all' : 'public';
269 $bookmark = $this->bookmarks
[$id];
271 ($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
272 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
283 public function count(string $visibility = null): int
285 return count($this->search([], $visibility));
291 public function save(): void
293 if (true !== $this->isLoggedIn
) {
294 // TODO: raise an Exception instead
295 die('You are not authorized to change the database.');
298 $this->bookmarks
->reorder();
299 $this->bookmarksIO
->write($this->bookmarks
);
300 $this->pageCacheManager
->invalidateCaches();
306 public function bookmarksCountPerTag(array $filteringTags = [], string $visibility = null): array
308 $bookmarks = $this->search(['searchtags' => $filteringTags], $visibility);
311 foreach ($bookmarks as $bookmark) {
312 foreach ($bookmark->getTags() as $tag) {
315 || (! $this->isLoggedIn
&& startsWith($tag, '.'))
316 || $tag === BookmarkMarkdownFormatter
::NO_MD_TAG
317 || in_array($tag, $filteringTags, true)
322 // The first case found will be displayed.
323 if (!isset($caseMapping[strtolower($tag)])) {
324 $caseMapping[strtolower($tag)] = $tag;
325 $tags[$caseMapping[strtolower($tag)]] = 0;
327 $tags[$caseMapping[strtolower($tag)]]++
;
332 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
333 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
335 * So we now use array_multisort() to sort tags by DESC occurrences,
336 * then ASC alphabetically for equal values.
338 * @see https://github.com/shaarli/Shaarli/issues/1142
340 $keys = array_keys($tags);
341 $tmpTags = array_combine($keys, $keys);
342 array_multisort($tags, SORT_DESC
, $tmpTags, SORT_ASC
, $tags);
350 public function findByDate(
351 \DateTimeInterface
$from,
352 \DateTimeInterface
$to,
353 ?\DateTimeInterface
&$previous,
354 ?\DateTimeInterface
&$next
360 foreach ($this->search([], null, false, false, true) as $bookmark) {
361 if ($to < $bookmark->getCreated()) {
362 $next = $bookmark->getCreated();
363 } elseif ($from < $bookmark->getCreated() && $to > $bookmark->getCreated()) {
366 if ($previous !== null) {
369 $previous = $bookmark->getCreated();
379 public function getLatest(): ?Bookmark
381 foreach ($this->search([], null, false, false, true) as $bookmark) {
391 public function initialize(): void
393 $initializer = new BookmarkInitializer($this);
394 $initializer->initialize();
396 if (true === $this->isLoggedIn
) {
402 * Handles migration to the new database format (BookmarksArray).
404 protected function migrate(): void
406 $bookmarkDb = new LegacyLinkDB(
407 $this->conf
->get('resource.datastore'),
411 $updater = new LegacyUpdater(
412 UpdaterUtils
::readUpdatesFile($this->conf
->get('resource.updates')),
417 $newUpdates = $updater->update();
418 if (! empty($newUpdates)) {
419 UpdaterUtils
::writeUpdatesFile(
420 $this->conf
->get('resource.updates'),
421 $updater->getDoneUpdates()