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