]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/bookmark/BookmarkFileService.php
New plugin hook: ability to add custom filters to Shaarli search engine
[github/shaarli/Shaarli.git] / application / bookmark / BookmarkFileService.php
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Shaarli\Bookmark;
6
7 use DateTime;
8 use Exception;
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;
15 use Shaarli\History;
16 use Shaarli\Legacy\LegacyLinkDB;
17 use Shaarli\Legacy\LegacyUpdater;
18 use Shaarli\Plugin\PluginManager;
19 use Shaarli\Render\PageCacheManager;
20 use Shaarli\Updater\UpdaterUtils;
21
22 /**
23 * Class BookmarksService
24 *
25 * This is the entry point to manipulate the bookmark DB.
26 * It manipulates loads links from a file data store containing all bookmarks.
27 *
28 * It also triggers the legacy format (bookmarks as arrays) migration.
29 */
30 class BookmarkFileService implements BookmarkServiceInterface
31 {
32 /** @var Bookmark[] instance */
33 protected $bookmarks;
34
35 /** @var BookmarkIO instance */
36 protected $bookmarksIO;
37
38 /** @var BookmarkFilter */
39 protected $bookmarkFilter;
40
41 /** @var ConfigManager instance */
42 protected $conf;
43
44 /** @var PluginManager */
45 protected $pluginManager;
46
47 /** @var History instance */
48 protected $history;
49
50 /** @var PageCacheManager instance */
51 protected $pageCacheManager;
52
53 /** @var bool true for logged in users. Default value to retrieve private bookmarks. */
54 protected $isLoggedIn;
55
56 /** @var Mutex */
57 protected $mutex;
58
59 /**
60 * @inheritDoc
61 */
62 public function __construct(
63 ConfigManager $conf,
64 PluginManager $pluginManager,
65 History $history,
66 Mutex $mutex,
67 bool $isLoggedIn
68 ) {
69 $this->conf = $conf;
70 $this->history = $history;
71 $this->mutex = $mutex;
72 $this->pageCacheManager = new PageCacheManager($this->conf->get('resource.page_cache'), $isLoggedIn);
73 $this->bookmarksIO = new BookmarkIO($this->conf, $this->mutex);
74 $this->isLoggedIn = $isLoggedIn;
75
76 if (!$this->isLoggedIn && $this->conf->get('privacy.hide_public_links', false)) {
77 $this->bookmarks = [];
78 } else {
79 try {
80 $this->bookmarks = $this->bookmarksIO->read();
81 } catch (EmptyDataStoreException | DatastoreNotInitializedException $e) {
82 $this->bookmarks = new BookmarkArray();
83
84 if ($this->isLoggedIn) {
85 // Datastore file does not exists, we initialize it with default bookmarks.
86 if ($e instanceof DatastoreNotInitializedException) {
87 $this->initialize();
88 } else {
89 $this->save();
90 }
91 }
92 }
93
94 if (! $this->bookmarks instanceof BookmarkArray) {
95 $this->migrate();
96 exit(
97 'Your data store has been migrated, please reload the page.' . PHP_EOL .
98 'If this message keeps showing up, please delete data/updates.txt file.'
99 );
100 }
101 }
102
103 $this->pluginManager = $pluginManager;
104 $this->bookmarkFilter = new BookmarkFilter($this->bookmarks, $this->conf, $this->pluginManager);
105 }
106
107 /**
108 * @inheritDoc
109 */
110 public function findByHash(string $hash, string $privateKey = null): Bookmark
111 {
112 $bookmark = $this->bookmarkFilter->filter(BookmarkFilter::$FILTER_HASH, $hash);
113 // PHP 7.3 introduced array_key_first() to avoid this hack
114 $first = reset($bookmark);
115 if (
116 !$this->isLoggedIn
117 && $first->isPrivate()
118 && (empty($privateKey) || $privateKey !== $first->getAdditionalContentEntry('private_key'))
119 ) {
120 throw new BookmarkNotFoundException();
121 }
122
123 return $first;
124 }
125
126 /**
127 * @inheritDoc
128 */
129 public function findByUrl(string $url): ?Bookmark
130 {
131 return $this->bookmarks->getByUrl($url);
132 }
133
134 /**
135 * @inheritDoc
136 */
137 public function search(
138 array $request = [],
139 string $visibility = null,
140 bool $caseSensitive = false,
141 bool $untaggedOnly = false,
142 bool $ignoreSticky = false,
143 array $pagination = []
144 ): SearchResult {
145 if ($visibility === null) {
146 $visibility = $this->isLoggedIn ? BookmarkFilter::$ALL : BookmarkFilter::$PUBLIC;
147 }
148
149 // Filter bookmark database according to parameters.
150 $searchTags = isset($request['searchtags']) ? $request['searchtags'] : '';
151 $searchTerm = isset($request['searchterm']) ? $request['searchterm'] : '';
152
153 if ($ignoreSticky) {
154 $this->bookmarks->reorder('DESC', true);
155 }
156
157 $bookmarks = $this->bookmarkFilter->filter(
158 BookmarkFilter::$FILTER_TAG | BookmarkFilter::$FILTER_TEXT,
159 [$searchTags, $searchTerm],
160 $caseSensitive,
161 $visibility,
162 $untaggedOnly
163 );
164
165 return SearchResult::getSearchResult(
166 $bookmarks,
167 $pagination['offset'] ?? 0,
168 $pagination['limit'] ?? null,
169 $pagination['allowOutOfBounds'] ?? false
170 );
171 }
172
173 /**
174 * @inheritDoc
175 */
176 public function get(int $id, string $visibility = null): Bookmark
177 {
178 if (! isset($this->bookmarks[$id])) {
179 throw new BookmarkNotFoundException();
180 }
181
182 if ($visibility === null) {
183 $visibility = $this->isLoggedIn ? BookmarkFilter::$ALL : BookmarkFilter::$PUBLIC;
184 }
185
186 $bookmark = $this->bookmarks[$id];
187 if (
188 ($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
189 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
190 ) {
191 throw new Exception('Unauthorized');
192 }
193
194 return $bookmark;
195 }
196
197 /**
198 * @inheritDoc
199 */
200 public function set(Bookmark $bookmark, bool $save = true): Bookmark
201 {
202 if (true !== $this->isLoggedIn) {
203 throw new Exception(t('You\'re not authorized to alter the datastore'));
204 }
205 if (! isset($this->bookmarks[$bookmark->getId()])) {
206 throw new BookmarkNotFoundException();
207 }
208 $bookmark->validate();
209
210 $bookmark->setUpdated(new DateTime());
211 $this->bookmarks[$bookmark->getId()] = $bookmark;
212 if ($save === true) {
213 $this->save();
214 $this->history->updateLink($bookmark);
215 }
216 return $this->bookmarks[$bookmark->getId()];
217 }
218
219 /**
220 * @inheritDoc
221 */
222 public function add(Bookmark $bookmark, bool $save = true): Bookmark
223 {
224 if (true !== $this->isLoggedIn) {
225 throw new Exception(t('You\'re not authorized to alter the datastore'));
226 }
227 if (!empty($bookmark->getId())) {
228 throw new Exception(t('This bookmarks already exists'));
229 }
230 $bookmark->setId($this->bookmarks->getNextId());
231 $bookmark->validate();
232
233 $this->bookmarks[$bookmark->getId()] = $bookmark;
234 if ($save === true) {
235 $this->save();
236 $this->history->addLink($bookmark);
237 }
238 return $this->bookmarks[$bookmark->getId()];
239 }
240
241 /**
242 * @inheritDoc
243 */
244 public function addOrSet(Bookmark $bookmark, bool $save = true): Bookmark
245 {
246 if (true !== $this->isLoggedIn) {
247 throw new Exception(t('You\'re not authorized to alter the datastore'));
248 }
249 if ($bookmark->getId() === null) {
250 return $this->add($bookmark, $save);
251 }
252 return $this->set($bookmark, $save);
253 }
254
255 /**
256 * @inheritDoc
257 */
258 public function remove(Bookmark $bookmark, bool $save = true): void
259 {
260 if (true !== $this->isLoggedIn) {
261 throw new Exception(t('You\'re not authorized to alter the datastore'));
262 }
263 if (! isset($this->bookmarks[$bookmark->getId()])) {
264 throw new BookmarkNotFoundException();
265 }
266
267 unset($this->bookmarks[$bookmark->getId()]);
268 if ($save === true) {
269 $this->save();
270 $this->history->deleteLink($bookmark);
271 }
272 }
273
274 /**
275 * @inheritDoc
276 */
277 public function exists(int $id, string $visibility = null): bool
278 {
279 if (! isset($this->bookmarks[$id])) {
280 return false;
281 }
282
283 if ($visibility === null) {
284 $visibility = $this->isLoggedIn ? 'all' : 'public';
285 }
286
287 $bookmark = $this->bookmarks[$id];
288 if (
289 ($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
290 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
291 ) {
292 return false;
293 }
294
295 return true;
296 }
297
298 /**
299 * @inheritDoc
300 */
301 public function count(string $visibility = null): int
302 {
303 return $this->search([], $visibility)->getResultCount();
304 }
305
306 /**
307 * @inheritDoc
308 */
309 public function save(): void
310 {
311 if (true !== $this->isLoggedIn) {
312 // TODO: raise an Exception instead
313 die('You are not authorized to change the database.');
314 }
315
316 $this->bookmarks->reorder();
317 $this->bookmarksIO->write($this->bookmarks);
318 $this->pageCacheManager->invalidateCaches();
319 }
320
321 /**
322 * @inheritDoc
323 */
324 public function bookmarksCountPerTag(array $filteringTags = [], string $visibility = null): array
325 {
326 $searchResult = $this->search(['searchtags' => $filteringTags], $visibility);
327 $tags = [];
328 $caseMapping = [];
329 foreach ($searchResult->getBookmarks() as $bookmark) {
330 foreach ($bookmark->getTags() as $tag) {
331 if (
332 empty($tag)
333 || (! $this->isLoggedIn && startsWith($tag, '.'))
334 || $tag === BookmarkMarkdownFormatter::NO_MD_TAG
335 || in_array($tag, $filteringTags, true)
336 ) {
337 continue;
338 }
339
340 // The first case found will be displayed.
341 if (!isset($caseMapping[strtolower($tag)])) {
342 $caseMapping[strtolower($tag)] = $tag;
343 $tags[$caseMapping[strtolower($tag)]] = 0;
344 }
345 $tags[$caseMapping[strtolower($tag)]]++;
346 }
347 }
348
349 /*
350 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
351 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
352 *
353 * So we now use array_multisort() to sort tags by DESC occurrences,
354 * then ASC alphabetically for equal values.
355 *
356 * @see https://github.com/shaarli/Shaarli/issues/1142
357 */
358 $keys = array_keys($tags);
359 $tmpTags = array_combine($keys, $keys);
360 array_multisort($tags, SORT_DESC, $tmpTags, SORT_ASC, $tags);
361
362 return $tags;
363 }
364
365 /**
366 * @inheritDoc
367 */
368 public function findByDate(
369 \DateTimeInterface $from,
370 \DateTimeInterface $to,
371 ?\DateTimeInterface &$previous,
372 ?\DateTimeInterface &$next
373 ): array {
374 $out = [];
375 $previous = null;
376 $next = null;
377
378 foreach ($this->search([], null, false, false, true)->getBookmarks() as $bookmark) {
379 if ($to < $bookmark->getCreated()) {
380 $next = $bookmark->getCreated();
381 } elseif ($from < $bookmark->getCreated() && $to > $bookmark->getCreated()) {
382 $out[] = $bookmark;
383 } else {
384 if ($previous !== null) {
385 break;
386 }
387 $previous = $bookmark->getCreated();
388 }
389 }
390
391 return $out;
392 }
393
394 /**
395 * @inheritDoc
396 */
397 public function getLatest(): ?Bookmark
398 {
399 foreach ($this->search([], null, false, false, true)->getBookmarks() as $bookmark) {
400 return $bookmark;
401 }
402
403 return null;
404 }
405
406 /**
407 * @inheritDoc
408 */
409 public function initialize(): void
410 {
411 $initializer = new BookmarkInitializer($this);
412 $initializer->initialize();
413
414 if (true === $this->isLoggedIn) {
415 $this->save();
416 }
417 }
418
419 /**
420 * Handles migration to the new database format (BookmarksArray).
421 */
422 protected function migrate(): void
423 {
424 $bookmarkDb = new LegacyLinkDB(
425 $this->conf->get('resource.datastore'),
426 true,
427 false
428 );
429 $updater = new LegacyUpdater(
430 UpdaterUtils::readUpdatesFile($this->conf->get('resource.updates')),
431 $bookmarkDb,
432 $this->conf,
433 true
434 );
435 $newUpdates = $updater->update();
436 if (! empty($newUpdates)) {
437 UpdaterUtils::writeUpdatesFile(
438 $this->conf->get('resource.updates'),
439 $updater->getDoneUpdates()
440 );
441 }
442 }
443 }