4 namespace Shaarli\Bookmark
;
8 use Shaarli\Bookmark\Exception\BookmarkNotFoundException
;
9 use Shaarli\Bookmark\Exception\DatastoreNotInitializedException
;
10 use Shaarli\Bookmark\Exception\EmptyDataStoreException
;
11 use Shaarli\Config\ConfigManager
;
12 use Shaarli\Formatter\BookmarkMarkdownFormatter
;
14 use Shaarli\Legacy\LegacyLinkDB
;
15 use Shaarli\Legacy\LegacyUpdater
;
16 use Shaarli\Render\PageCacheManager
;
17 use Shaarli\Updater\UpdaterUtils
;
20 * Class BookmarksService
22 * This is the entry point to manipulate the bookmark DB.
23 * It manipulates loads links from a file data store containing all bookmarks.
25 * It also triggers the legacy format (bookmarks as arrays) migration.
27 class BookmarkFileService
implements BookmarkServiceInterface
29 /** @var Bookmark[] instance */
32 /** @var BookmarkIO instance */
33 protected $bookmarksIO;
35 /** @var BookmarkFilter */
36 protected $bookmarkFilter;
38 /** @var ConfigManager instance */
41 /** @var History instance */
44 /** @var PageCacheManager instance */
45 protected $pageCacheManager;
47 /** @var bool true for logged in users. Default value to retrieve private bookmarks. */
48 protected $isLoggedIn;
53 public function __construct(ConfigManager
$conf, History
$history, $isLoggedIn)
56 $this->history
= $history;
57 $this->pageCacheManager
= new PageCacheManager($this->conf
->get('resource.page_cache'), $isLoggedIn);
58 $this->bookmarksIO
= new BookmarkIO($this->conf
);
59 $this->isLoggedIn
= $isLoggedIn;
61 if (!$this->isLoggedIn
&& $this->conf
->get('privacy.hide_public_links', false)) {
62 $this->bookmarks
= [];
65 $this->bookmarks
= $this->bookmarksIO
->read();
66 } catch (EmptyDataStoreException
|DatastoreNotInitializedException
$e) {
67 $this->bookmarks
= new BookmarkArray();
69 if ($this->isLoggedIn
) {
70 // Datastore file does not exists, we initialize it with default bookmarks.
71 if ($e instanceof DatastoreNotInitializedException
) {
79 if (! $this->bookmarks
instanceof BookmarkArray
) {
82 'Your data store has been migrated, please reload the page.'. PHP_EOL
.
83 'If this message keeps showing up, please delete data/updates.txt file.'
88 $this->bookmarkFilter
= new BookmarkFilter($this->bookmarks
);
94 public function findByHash($hash)
96 $bookmark = $this->bookmarkFilter
->filter(BookmarkFilter
::$FILTER_HASH, $hash);
97 // PHP 7.3 introduced array_key_first() to avoid this hack
98 $first = reset($bookmark);
99 if (! $this->isLoggedIn
&& $first->isPrivate()) {
100 throw new Exception('Not authorized');
109 public function findByUrl($url)
111 return $this->bookmarks
->getByUrl($url);
117 public function search($request = [], $visibility = null, $caseSensitive = false, $untaggedOnly = false)
119 if ($visibility === null) {
120 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
123 // Filter bookmark database according to parameters.
124 $searchtags = isset($request['searchtags']) ? $request['searchtags'] : '';
125 $searchterm = isset($request['searchterm']) ? $request['searchterm'] : '';
127 return $this->bookmarkFilter
->filter(
128 BookmarkFilter
::$FILTER_TAG | BookmarkFilter
::$FILTER_TEXT,
129 [$searchtags, $searchterm],
139 public function get($id, $visibility = null)
141 if (! isset($this->bookmarks
[$id])) {
142 throw new BookmarkNotFoundException();
145 if ($visibility === null) {
146 $visibility = $this->isLoggedIn
? BookmarkFilter
::$ALL : BookmarkFilter
::$PUBLIC;
149 $bookmark = $this->bookmarks
[$id];
150 if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
151 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
153 throw new Exception('Unauthorized');
162 public function set($bookmark, $save = true)
164 if (true !== $this->isLoggedIn
) {
165 throw new Exception(t('You\'re not authorized to alter the datastore'));
167 if (! $bookmark instanceof Bookmark
) {
168 throw new Exception(t('Provided data is invalid'));
170 if (! isset($this->bookmarks
[$bookmark->getId()])) {
171 throw new BookmarkNotFoundException();
173 $bookmark->validate();
175 $bookmark->setUpdated(new \
DateTime());
176 $this->bookmarks
[$bookmark->getId()] = $bookmark;
177 if ($save === true) {
179 $this->history
->updateLink($bookmark);
181 return $this->bookmarks
[$bookmark->getId()];
187 public function add($bookmark, $save = true)
189 if (true !== $this->isLoggedIn
) {
190 throw new Exception(t('You\'re not authorized to alter the datastore'));
192 if (! $bookmark instanceof Bookmark
) {
193 throw new Exception(t('Provided data is invalid'));
195 if (! empty($bookmark->getId())) {
196 throw new Exception(t('This bookmarks already exists'));
198 $bookmark->setId($this->bookmarks
->getNextId());
199 $bookmark->validate();
201 $this->bookmarks
[$bookmark->getId()] = $bookmark;
202 if ($save === true) {
204 $this->history
->addLink($bookmark);
206 return $this->bookmarks
[$bookmark->getId()];
212 public function addOrSet($bookmark, $save = true)
214 if (true !== $this->isLoggedIn
) {
215 throw new Exception(t('You\'re not authorized to alter the datastore'));
217 if (! $bookmark instanceof Bookmark
) {
218 throw new Exception('Provided data is invalid');
220 if ($bookmark->getId() === null) {
221 return $this->add($bookmark, $save);
223 return $this->set($bookmark, $save);
229 public function remove($bookmark, $save = true)
231 if (true !== $this->isLoggedIn
) {
232 throw new Exception(t('You\'re not authorized to alter the datastore'));
234 if (! $bookmark instanceof Bookmark
) {
235 throw new Exception(t('Provided data is invalid'));
237 if (! isset($this->bookmarks
[$bookmark->getId()])) {
238 throw new BookmarkNotFoundException();
241 unset($this->bookmarks
[$bookmark->getId()]);
242 if ($save === true) {
244 $this->history
->deleteLink($bookmark);
251 public function exists($id, $visibility = null)
253 if (! isset($this->bookmarks
[$id])) {
257 if ($visibility === null) {
258 $visibility = $this->isLoggedIn
? 'all' : 'public';
261 $bookmark = $this->bookmarks
[$id];
262 if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
263 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
274 public function count($visibility = null)
276 return count($this->search([], $visibility));
282 public function save()
284 if (true !== $this->isLoggedIn
) {
285 // TODO: raise an Exception instead
286 die('You are not authorized to change the database.');
289 $this->bookmarks
->reorder();
290 $this->bookmarksIO
->write($this->bookmarks
);
291 $this->pageCacheManager
->invalidateCaches();
297 public function bookmarksCountPerTag($filteringTags = [], $visibility = null)
299 $bookmarks = $this->search(['searchtags' => $filteringTags], $visibility);
302 foreach ($bookmarks as $bookmark) {
303 foreach ($bookmark->getTags() as $tag) {
305 || (! $this->isLoggedIn
&& startsWith($tag, '.'))
306 || $tag === BookmarkMarkdownFormatter
::NO_MD_TAG
307 || in_array($tag, $filteringTags, true)
312 // The first case found will be displayed.
313 if (!isset($caseMapping[strtolower($tag)])) {
314 $caseMapping[strtolower($tag)] = $tag;
315 $tags[$caseMapping[strtolower($tag)]] = 0;
317 $tags[$caseMapping[strtolower($tag)]]++
;
322 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
323 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
325 * So we now use array_multisort() to sort tags by DESC occurrences,
326 * then ASC alphabetically for equal values.
328 * @see https://github.com/shaarli/Shaarli/issues/1142
330 $keys = array_keys($tags);
331 $tmpTags = array_combine($keys, $keys);
332 array_multisort($tags, SORT_DESC
, $tmpTags, SORT_ASC
, $tags);
339 public function days()
342 foreach ($this->search() as $bookmark) {
343 $bookmarkDays[$bookmark->getCreated()->format('Ymd')] = 0;
345 $bookmarkDays = array_keys($bookmarkDays);
348 return $bookmarkDays;
354 public function filterDay($request)
356 return $this->bookmarkFilter
->filter(BookmarkFilter
::$FILTER_DAY, $request);
362 public function initialize()
364 $initializer = new BookmarkInitializer($this);
365 $initializer->initialize();
367 if (true === $this->isLoggedIn
) {
373 * Handles migration to the new database format (BookmarksArray).
375 protected function migrate()
377 $bookmarkDb = new LegacyLinkDB(
378 $this->conf
->get('resource.datastore'),
382 $updater = new LegacyUpdater(
383 UpdaterUtils
::read_updates_file($this->conf
->get('resource.updates')),
388 $newUpdates = $updater->update();
389 if (! empty($newUpdates)) {
390 UpdaterUtils
::write_updates_file(
391 $this->conf
->get('resource.updates'),
392 $updater->getDoneUpdates()