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(
65 $this->history
= $history;
66 $this->mutex
= $mutex;
67 $this->pageCacheManager
= new PageCacheManager($this->conf
->get('resource.page_cache'), $isLoggedIn);
68 $this->bookmarksIO
= new BookmarkIO($this->conf
, $this->mutex
);
69 $this->isLoggedIn
= $isLoggedIn;
71 if (!$this->isLoggedIn
&& $this->conf
->get('privacy.hide_public_links', false)) {
72 $this->bookmarks
= [];
75 $this->bookmarks
= $this->bookmarksIO
->read();
76 } catch (EmptyDataStoreException
| DatastoreNotInitializedException
$e) {
77 $this->bookmarks
= new BookmarkArray();
79 if ($this->isLoggedIn
) {
80 // Datastore file does not exists, we initialize it with default bookmarks.
81 if ($e instanceof DatastoreNotInitializedException
) {
89 if (! $this->bookmarks
instanceof BookmarkArray
) {
92 'Your data store has been migrated, please reload the page.' . PHP_EOL
.
93 'If this message keeps showing up, please delete data/updates.txt file.'
98 $this->bookmarkFilter
= new BookmarkFilter($this->bookmarks
, $this->conf
);
104 public function findByHash(string $hash, string $privateKey = null): Bookmark
106 $bookmark = $this->bookmarkFilter
->filter(BookmarkFilter
::$FILTER_HASH, $hash);
107 // PHP 7.3 introduced array_key_first() to avoid this hack
108 $first = reset($bookmark);
111 && $first->isPrivate()
112 && (empty($privateKey) || $privateKey !== $first->getAdditionalContentEntry('private_key'))
114 throw new BookmarkNotFoundException();
123 public function findByUrl(string $url): ?Bookmark
125 return $this->bookmarks
->getByUrl($url);
131 public function search(
133 string $visibility = null,
134 bool $caseSensitive = false,
135 bool $untaggedOnly = false,
136 bool $ignoreSticky = false,
137 array $pagination = []
139 if ($visibility === null) {
140 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
143 // Filter bookmark database according to parameters.
144 $searchTags = isset($request['searchtags']) ? $request['searchtags'] : '';
145 $searchTerm = isset($request['searchterm']) ? $request['searchterm'] : '';
148 $this->bookmarks
->reorder('DESC', true);
151 $bookmarks = $this->bookmarkFilter
->filter(
152 BookmarkFilter
::$FILTER_TAG | BookmarkFilter
::$FILTER_TEXT,
153 [$searchTags, $searchTerm],
159 return SearchResult
::getSearchResult(
161 $pagination['offset'] ?? 0,
162 $pagination['limit'] ?? null,
163 $pagination['allowOutOfBounds'] ?? false
170 public function get(int $id, string $visibility = null): Bookmark
172 if (! isset($this->bookmarks
[$id])) {
173 throw new BookmarkNotFoundException();
176 if ($visibility === null) {
177 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
180 $bookmark = $this->bookmarks
[$id];
182 ($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
183 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
185 throw new Exception('Unauthorized');
194 public function set(Bookmark
$bookmark, bool $save = true): Bookmark
196 if (true !== $this->isLoggedIn
) {
197 throw new Exception(t('You\'re not authorized to alter the datastore'));
199 if (! isset($this->bookmarks
[$bookmark->getId()])) {
200 throw new BookmarkNotFoundException();
202 $bookmark->validate();
204 $bookmark->setUpdated(new DateTime());
205 $this->bookmarks
[$bookmark->getId()] = $bookmark;
206 if ($save === true) {
208 $this->history
->updateLink($bookmark);
210 return $this->bookmarks
[$bookmark->getId()];
216 public function add(Bookmark
$bookmark, bool $save = true): Bookmark
218 if (true !== $this->isLoggedIn
) {
219 throw new Exception(t('You\'re not authorized to alter the datastore'));
221 if (!empty($bookmark->getId())) {
222 throw new Exception(t('This bookmarks already exists'));
224 $bookmark->setId($this->bookmarks
->getNextId());
225 $bookmark->validate();
227 $this->bookmarks
[$bookmark->getId()] = $bookmark;
228 if ($save === true) {
230 $this->history
->addLink($bookmark);
232 return $this->bookmarks
[$bookmark->getId()];
238 public function addOrSet(Bookmark
$bookmark, bool $save = true): Bookmark
240 if (true !== $this->isLoggedIn
) {
241 throw new Exception(t('You\'re not authorized to alter the datastore'));
243 if ($bookmark->getId() === null) {
244 return $this->add($bookmark, $save);
246 return $this->set($bookmark, $save);
252 public function remove(Bookmark
$bookmark, bool $save = true): void
254 if (true !== $this->isLoggedIn
) {
255 throw new Exception(t('You\'re not authorized to alter the datastore'));
257 if (! isset($this->bookmarks
[$bookmark->getId()])) {
258 throw new BookmarkNotFoundException();
261 unset($this->bookmarks
[$bookmark->getId()]);
262 if ($save === true) {
264 $this->history
->deleteLink($bookmark);
271 public function exists(int $id, string $visibility = null): bool
273 if (! isset($this->bookmarks
[$id])) {
277 if ($visibility === null) {
278 $visibility = $this->isLoggedIn
? 'all' : 'public';
281 $bookmark = $this->bookmarks
[$id];
283 ($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
284 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
295 public function count(string $visibility = null): int
297 return $this->search([], $visibility)->getResultCount();
303 public function save(): void
305 if (true !== $this->isLoggedIn
) {
306 // TODO: raise an Exception instead
307 die('You are not authorized to change the database.');
310 $this->bookmarks
->reorder();
311 $this->bookmarksIO
->write($this->bookmarks
);
312 $this->pageCacheManager
->invalidateCaches();
318 public function bookmarksCountPerTag(array $filteringTags = [], string $visibility = null): array
320 $searchResult = $this->search(['searchtags' => $filteringTags], $visibility);
323 foreach ($searchResult->getBookmarks() as $bookmark) {
324 foreach ($bookmark->getTags() as $tag) {
327 || (! $this->isLoggedIn
&& startsWith($tag, '.'))
328 || $tag === BookmarkMarkdownFormatter
::NO_MD_TAG
329 || in_array($tag, $filteringTags, true)
334 // The first case found will be displayed.
335 if (!isset($caseMapping[strtolower($tag)])) {
336 $caseMapping[strtolower($tag)] = $tag;
337 $tags[$caseMapping[strtolower($tag)]] = 0;
339 $tags[$caseMapping[strtolower($tag)]]++
;
344 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
345 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
347 * So we now use array_multisort() to sort tags by DESC occurrences,
348 * then ASC alphabetically for equal values.
350 * @see https://github.com/shaarli/Shaarli/issues/1142
352 $keys = array_keys($tags);
353 $tmpTags = array_combine($keys, $keys);
354 array_multisort($tags, SORT_DESC
, $tmpTags, SORT_ASC
, $tags);
362 public function findByDate(
363 \DateTimeInterface
$from,
364 \DateTimeInterface
$to,
365 ?\DateTimeInterface
&$previous,
366 ?\DateTimeInterface
&$next
372 foreach ($this->search([], null, false, false, true)->getBookmarks() as $bookmark) {
373 if ($to < $bookmark->getCreated()) {
374 $next = $bookmark->getCreated();
375 } elseif ($from < $bookmark->getCreated() && $to > $bookmark->getCreated()) {
378 if ($previous !== null) {
381 $previous = $bookmark->getCreated();
391 public function getLatest(): ?Bookmark
393 foreach ($this->search([], null, false, false, true)->getBookmarks() as $bookmark) {
403 public function initialize(): void
405 $initializer = new BookmarkInitializer($this);
406 $initializer->initialize();
408 if (true === $this->isLoggedIn
) {
414 * Handles migration to the new database format (BookmarksArray).
416 protected function migrate(): void
418 $bookmarkDb = new LegacyLinkDB(
419 $this->conf
->get('resource.datastore'),
423 $updater = new LegacyUpdater(
424 UpdaterUtils
::readUpdatesFile($this->conf
->get('resource.updates')),
429 $newUpdates = $updater->update();
430 if (! empty($newUpdates)) {
431 UpdaterUtils
::writeUpdatesFile(
432 $this->conf
->get('resource.updates'),
433 $updater->getDoneUpdates()