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
);
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);
105 if (!$this->isLoggedIn
106 && $first->isPrivate()
107 && (empty($privateKey) || $privateKey !== $first->getAdditionalContentEntry('private_key'))
109 throw new Exception('Not authorized');
118 public function findByUrl(string $url): ?Bookmark
120 return $this->bookmarks
->getByUrl($url);
126 public function search(
128 string $visibility = null,
129 bool $caseSensitive = false,
130 bool $untaggedOnly = false,
131 bool $ignoreSticky = false
133 if ($visibility === null) {
134 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
137 // Filter bookmark database according to parameters.
138 $searchTags = isset($request['searchtags']) ? $request['searchtags'] : '';
139 $searchTerm = isset($request['searchterm']) ? $request['searchterm'] : '';
142 $this->bookmarks
->reorder('DESC', true);
145 return $this->bookmarkFilter
->filter(
146 BookmarkFilter
::$FILTER_TAG | BookmarkFilter
::$FILTER_TEXT,
147 [$searchTags, $searchTerm],
157 public function get(int $id, string $visibility = null): Bookmark
159 if (! isset($this->bookmarks
[$id])) {
160 throw new BookmarkNotFoundException();
163 if ($visibility === null) {
164 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
167 $bookmark = $this->bookmarks
[$id];
168 if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
169 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
171 throw new Exception('Unauthorized');
180 public function set(Bookmark
$bookmark, bool $save = true): Bookmark
182 if (true !== $this->isLoggedIn
) {
183 throw new Exception(t('You\'re not authorized to alter the datastore'));
185 if (! isset($this->bookmarks
[$bookmark->getId()])) {
186 throw new BookmarkNotFoundException();
188 $bookmark->validate();
190 $bookmark->setUpdated(new DateTime());
191 $this->bookmarks
[$bookmark->getId()] = $bookmark;
192 if ($save === true) {
194 $this->history
->updateLink($bookmark);
196 return $this->bookmarks
[$bookmark->getId()];
202 public function add(Bookmark
$bookmark, bool $save = true): Bookmark
204 if (true !== $this->isLoggedIn
) {
205 throw new Exception(t('You\'re not authorized to alter the datastore'));
207 if (!empty($bookmark->getId())) {
208 throw new Exception(t('This bookmarks already exists'));
210 $bookmark->setId($this->bookmarks
->getNextId());
211 $bookmark->validate();
213 $this->bookmarks
[$bookmark->getId()] = $bookmark;
214 if ($save === true) {
216 $this->history
->addLink($bookmark);
218 return $this->bookmarks
[$bookmark->getId()];
224 public function addOrSet(Bookmark
$bookmark, bool $save = true): Bookmark
226 if (true !== $this->isLoggedIn
) {
227 throw new Exception(t('You\'re not authorized to alter the datastore'));
229 if ($bookmark->getId() === null) {
230 return $this->add($bookmark, $save);
232 return $this->set($bookmark, $save);
238 public function remove(Bookmark
$bookmark, bool $save = true): void
240 if (true !== $this->isLoggedIn
) {
241 throw new Exception(t('You\'re not authorized to alter the datastore'));
243 if (! isset($this->bookmarks
[$bookmark->getId()])) {
244 throw new BookmarkNotFoundException();
247 unset($this->bookmarks
[$bookmark->getId()]);
248 if ($save === true) {
250 $this->history
->deleteLink($bookmark);
257 public function exists(int $id, string $visibility = null): bool
259 if (! isset($this->bookmarks
[$id])) {
263 if ($visibility === null) {
264 $visibility = $this->isLoggedIn
? 'all' : 'public';
267 $bookmark = $this->bookmarks
[$id];
268 if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
269 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
280 public function count(string $visibility = null): int
282 return count($this->search([], $visibility));
288 public function save(): void
290 if (true !== $this->isLoggedIn
) {
291 // TODO: raise an Exception instead
292 die('You are not authorized to change the database.');
295 $this->bookmarks
->reorder();
296 $this->bookmarksIO
->write($this->bookmarks
);
297 $this->pageCacheManager
->invalidateCaches();
303 public function bookmarksCountPerTag(array $filteringTags = [], string $visibility = null): array
305 $bookmarks = $this->search(['searchtags' => $filteringTags], $visibility);
308 foreach ($bookmarks as $bookmark) {
309 foreach ($bookmark->getTags() as $tag) {
311 || (! $this->isLoggedIn
&& startsWith($tag, '.'))
312 || $tag === BookmarkMarkdownFormatter
::NO_MD_TAG
313 || in_array($tag, $filteringTags, true)
318 // The first case found will be displayed.
319 if (!isset($caseMapping[strtolower($tag)])) {
320 $caseMapping[strtolower($tag)] = $tag;
321 $tags[$caseMapping[strtolower($tag)]] = 0;
323 $tags[$caseMapping[strtolower($tag)]]++
;
328 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
329 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
331 * So we now use array_multisort() to sort tags by DESC occurrences,
332 * then ASC alphabetically for equal values.
334 * @see https://github.com/shaarli/Shaarli/issues/1142
336 $keys = array_keys($tags);
337 $tmpTags = array_combine($keys, $keys);
338 array_multisort($tags, SORT_DESC
, $tmpTags, SORT_ASC
, $tags);
346 public function findByDate(
347 \DateTimeInterface
$from,
348 \DateTimeInterface
$to,
349 ?\DateTimeInterface
&$previous,
350 ?\DateTimeInterface
&$next
356 foreach ($this->search([], null, false, false, true) as $bookmark) {
357 if ($to < $bookmark->getCreated()) {
358 $next = $bookmark->getCreated();
359 } else if ($from < $bookmark->getCreated() && $to > $bookmark->getCreated()) {
362 if ($previous !== null) {
365 $previous = $bookmark->getCreated();
375 public function getLatest(): ?Bookmark
377 foreach ($this->search([], null, false, false, true) as $bookmark) {
387 public function initialize(): void
389 $initializer = new BookmarkInitializer($this);
390 $initializer->initialize();
392 if (true === $this->isLoggedIn
) {
398 * Handles migration to the new database format (BookmarksArray).
400 protected function migrate(): void
402 $bookmarkDb = new LegacyLinkDB(
403 $this->conf
->get('resource.datastore'),
407 $updater = new LegacyUpdater(
408 UpdaterUtils
::read_updates_file($this->conf
->get('resource.updates')),
413 $newUpdates = $updater->update();
414 if (! empty($newUpdates)) {
415 UpdaterUtils
::write_updates_file(
416 $this->conf
->get('resource.updates'),
417 $updater->getDoneUpdates()