aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/bookmark
diff options
context:
space:
mode:
authorArthurHoaro <arthur@hoa.ro>2020-01-18 10:01:06 +0100
committerGitHub <noreply@github.com>2020-01-18 10:01:06 +0100
commit3fb29fdda04ca86e04422d49b86cf646d53c4f9d (patch)
treeadf8512f93f5559ba87d0c9931969ae4ebea7133 /application/bookmark
parent796c4c57d085ae4589b53dfe8369ae9ba30ffdaf (diff)
parente26e2060f5470ce8bf4c5973284bae07b8af170a (diff)
downloadShaarli-3fb29fdda04ca86e04422d49b86cf646d53c4f9d.tar.gz
Shaarli-3fb29fdda04ca86e04422d49b86cf646d53c4f9d.tar.zst
Shaarli-3fb29fdda04ca86e04422d49b86cf646d53c4f9d.zip
Store bookmarks as PHP objects and add a service layer to retriā€¦ (#1307)
Store bookmarks as PHP objects and add a service layer to retrieve them
Diffstat (limited to 'application/bookmark')
-rw-r--r--application/bookmark/Bookmark.php461
-rw-r--r--application/bookmark/BookmarkArray.php259
-rw-r--r--application/bookmark/BookmarkFileService.php373
-rw-r--r--application/bookmark/BookmarkFilter.php (renamed from application/bookmark/LinkFilter.php)145
-rw-r--r--application/bookmark/BookmarkIO.php108
-rw-r--r--application/bookmark/BookmarkInitializer.php59
-rw-r--r--application/bookmark/BookmarkServiceInterface.php180
-rw-r--r--application/bookmark/LinkDB.php578
-rw-r--r--application/bookmark/LinkUtils.php27
-rw-r--r--application/bookmark/exception/BookmarkNotFoundException.php (renamed from application/bookmark/exception/LinkNotFoundException.php)2
-rw-r--r--application/bookmark/exception/EmptyDataStoreException.php7
-rw-r--r--application/bookmark/exception/InvalidBookmarkException.php30
-rw-r--r--application/bookmark/exception/NotWritableDataStoreException.php19
13 files changed, 1583 insertions, 665 deletions
diff --git a/application/bookmark/Bookmark.php b/application/bookmark/Bookmark.php
new file mode 100644
index 00000000..f9b21d3d
--- /dev/null
+++ b/application/bookmark/Bookmark.php
@@ -0,0 +1,461 @@
1<?php
2
3namespace Shaarli\Bookmark;
4
5use DateTime;
6use Shaarli\Bookmark\Exception\InvalidBookmarkException;
7
8/**
9 * Class Bookmark
10 *
11 * This class represent a single Bookmark with all its attributes.
12 * Every bookmark should manipulated using this, before being formatted.
13 *
14 * @package Shaarli\Bookmark
15 */
16class Bookmark
17{
18 /** @var string Date format used in string (former ID format) */
19 const LINK_DATE_FORMAT = 'Ymd_His';
20
21 /** @var int Bookmark ID */
22 protected $id;
23
24 /** @var string Permalink identifier */
25 protected $shortUrl;
26
27 /** @var string Bookmark's URL - $shortUrl prefixed with `?` for notes */
28 protected $url;
29
30 /** @var string Bookmark's title */
31 protected $title;
32
33 /** @var string Raw bookmark's description */
34 protected $description;
35
36 /** @var array List of bookmark's tags */
37 protected $tags;
38
39 /** @var string Thumbnail's URL - false if no thumbnail could be found */
40 protected $thumbnail;
41
42 /** @var bool Set to true if the bookmark is set as sticky */
43 protected $sticky;
44
45 /** @var DateTime Creation datetime */
46 protected $created;
47
48 /** @var DateTime Update datetime */
49 protected $updated;
50
51 /** @var bool True if the bookmark can only be seen while logged in */
52 protected $private;
53
54 /**
55 * Initialize a link from array data. Especially useful to create a Bookmark from former link storage format.
56 *
57 * @param array $data
58 *
59 * @return $this
60 */
61 public function fromArray($data)
62 {
63 $this->id = $data['id'];
64 $this->shortUrl = $data['shorturl'];
65 $this->url = $data['url'];
66 $this->title = $data['title'];
67 $this->description = $data['description'];
68 $this->thumbnail = isset($data['thumbnail']) ? $data['thumbnail'] : null;
69 $this->sticky = isset($data['sticky']) ? $data['sticky'] : false;
70 $this->created = $data['created'];
71 if (is_array($data['tags'])) {
72 $this->tags = $data['tags'];
73 } else {
74 $this->tags = preg_split('/\s+/', $data['tags'], -1, PREG_SPLIT_NO_EMPTY);
75 }
76 if (! empty($data['updated'])) {
77 $this->updated = $data['updated'];
78 }
79 $this->private = $data['private'] ? true : false;
80
81 return $this;
82 }
83
84 /**
85 * Make sure that the current instance of Bookmark is valid and can be saved into the data store.
86 * A valid link requires:
87 * - an integer ID
88 * - a short URL (for permalinks)
89 * - a creation date
90 *
91 * This function also initialize optional empty fields:
92 * - the URL with the permalink
93 * - the title with the URL
94 *
95 * @throws InvalidBookmarkException
96 */
97 public function validate()
98 {
99 if ($this->id === null
100 || ! is_int($this->id)
101 || empty($this->shortUrl)
102 || empty($this->created)
103 || ! $this->created instanceof DateTime
104 ) {
105 throw new InvalidBookmarkException($this);
106 }
107 if (empty($this->url)) {
108 $this->url = '?'. $this->shortUrl;
109 }
110 if (empty($this->title)) {
111 $this->title = $this->url;
112 }
113 }
114
115 /**
116 * Set the Id.
117 * If they're not already initialized, this function also set:
118 * - created: with the current datetime
119 * - shortUrl: with a generated small hash from the date and the given ID
120 *
121 * @param int $id
122 *
123 * @return Bookmark
124 */
125 public function setId($id)
126 {
127 $this->id = $id;
128 if (empty($this->created)) {
129 $this->created = new DateTime();
130 }
131 if (empty($this->shortUrl)) {
132 $this->shortUrl = link_small_hash($this->created, $this->id);
133 }
134
135 return $this;
136 }
137
138 /**
139 * Get the Id.
140 *
141 * @return int
142 */
143 public function getId()
144 {
145 return $this->id;
146 }
147
148 /**
149 * Get the ShortUrl.
150 *
151 * @return string
152 */
153 public function getShortUrl()
154 {
155 return $this->shortUrl;
156 }
157
158 /**
159 * Get the Url.
160 *
161 * @return string
162 */
163 public function getUrl()
164 {
165 return $this->url;
166 }
167
168 /**
169 * Get the Title.
170 *
171 * @return string
172 */
173 public function getTitle()
174 {
175 return $this->title;
176 }
177
178 /**
179 * Get the Description.
180 *
181 * @return string
182 */
183 public function getDescription()
184 {
185 return ! empty($this->description) ? $this->description : '';
186 }
187
188 /**
189 * Get the Created.
190 *
191 * @return DateTime
192 */
193 public function getCreated()
194 {
195 return $this->created;
196 }
197
198 /**
199 * Get the Updated.
200 *
201 * @return DateTime
202 */
203 public function getUpdated()
204 {
205 return $this->updated;
206 }
207
208 /**
209 * Set the ShortUrl.
210 *
211 * @param string $shortUrl
212 *
213 * @return Bookmark
214 */
215 public function setShortUrl($shortUrl)
216 {
217 $this->shortUrl = $shortUrl;
218
219 return $this;
220 }
221
222 /**
223 * Set the Url.
224 *
225 * @param string $url
226 * @param array $allowedProtocols
227 *
228 * @return Bookmark
229 */
230 public function setUrl($url, $allowedProtocols = [])
231 {
232 $url = trim($url);
233 if (! empty($url)) {
234 $url = whitelist_protocols($url, $allowedProtocols);
235 }
236 $this->url = $url;
237
238 return $this;
239 }
240
241 /**
242 * Set the Title.
243 *
244 * @param string $title
245 *
246 * @return Bookmark
247 */
248 public function setTitle($title)
249 {
250 $this->title = trim($title);
251
252 return $this;
253 }
254
255 /**
256 * Set the Description.
257 *
258 * @param string $description
259 *
260 * @return Bookmark
261 */
262 public function setDescription($description)
263 {
264 $this->description = $description;
265
266 return $this;
267 }
268
269 /**
270 * Set the Created.
271 * Note: you shouldn't set this manually except for special cases (like bookmark import)
272 *
273 * @param DateTime $created
274 *
275 * @return Bookmark
276 */
277 public function setCreated($created)
278 {
279 $this->created = $created;
280
281 return $this;
282 }
283
284 /**
285 * Set the Updated.
286 *
287 * @param DateTime $updated
288 *
289 * @return Bookmark
290 */
291 public function setUpdated($updated)
292 {
293 $this->updated = $updated;
294
295 return $this;
296 }
297
298 /**
299 * Get the Private.
300 *
301 * @return bool
302 */
303 public function isPrivate()
304 {
305 return $this->private ? true : false;
306 }
307
308 /**
309 * Set the Private.
310 *
311 * @param bool $private
312 *
313 * @return Bookmark
314 */
315 public function setPrivate($private)
316 {
317 $this->private = $private ? true : false;
318
319 return $this;
320 }
321
322 /**
323 * Get the Tags.
324 *
325 * @return array
326 */
327 public function getTags()
328 {
329 return is_array($this->tags) ? $this->tags : [];
330 }
331
332 /**
333 * Set the Tags.
334 *
335 * @param array $tags
336 *
337 * @return Bookmark
338 */
339 public function setTags($tags)
340 {
341 $this->setTagsString(implode(' ', $tags));
342
343 return $this;
344 }
345
346 /**
347 * Get the Thumbnail.
348 *
349 * @return string|bool
350 */
351 public function getThumbnail()
352 {
353 return !$this->isNote() ? $this->thumbnail : false;
354 }
355
356 /**
357 * Set the Thumbnail.
358 *
359 * @param string|bool $thumbnail
360 *
361 * @return Bookmark
362 */
363 public function setThumbnail($thumbnail)
364 {
365 $this->thumbnail = $thumbnail;
366
367 return $this;
368 }
369
370 /**
371 * Get the Sticky.
372 *
373 * @return bool
374 */
375 public function isSticky()
376 {
377 return $this->sticky ? true : false;
378 }
379
380 /**
381 * Set the Sticky.
382 *
383 * @param bool $sticky
384 *
385 * @return Bookmark
386 */
387 public function setSticky($sticky)
388 {
389 $this->sticky = $sticky ? true : false;
390
391 return $this;
392 }
393
394 /**
395 * @return string Bookmark's tags as a string, separated by a space
396 */
397 public function getTagsString()
398 {
399 return implode(' ', $this->getTags());
400 }
401
402 /**
403 * @return bool
404 */
405 public function isNote()
406 {
407 // We check empty value to get a valid result if the link has not been saved yet
408 return empty($this->url) || $this->url[0] === '?';
409 }
410
411 /**
412 * Set tags from a string.
413 * Note:
414 * - tags must be separated whether by a space or a comma
415 * - multiple spaces will be removed
416 * - trailing dash in tags will be removed
417 *
418 * @param string $tags
419 *
420 * @return $this
421 */
422 public function setTagsString($tags)
423 {
424 // Remove first '-' char in tags.
425 $tags = preg_replace('/(^| )\-/', '$1', $tags);
426 // Explode all tags separted by spaces or commas
427 $tags = preg_split('/[\s,]+/', $tags);
428 // Remove eventual empty values
429 $tags = array_values(array_filter($tags));
430
431 $this->tags = $tags;
432
433 return $this;
434 }
435
436 /**
437 * Rename a tag in tags list.
438 *
439 * @param string $fromTag
440 * @param string $toTag
441 */
442 public function renameTag($fromTag, $toTag)
443 {
444 if (($pos = array_search($fromTag, $this->tags)) !== false) {
445 $this->tags[$pos] = trim($toTag);
446 }
447 }
448
449 /**
450 * Delete a tag from tags list.
451 *
452 * @param string $tag
453 */
454 public function deleteTag($tag)
455 {
456 if (($pos = array_search($tag, $this->tags)) !== false) {
457 unset($this->tags[$pos]);
458 $this->tags = array_values($this->tags);
459 }
460 }
461}
diff --git a/application/bookmark/BookmarkArray.php b/application/bookmark/BookmarkArray.php
new file mode 100644
index 00000000..d87d43b4
--- /dev/null
+++ b/application/bookmark/BookmarkArray.php
@@ -0,0 +1,259 @@
1<?php
2
3namespace Shaarli\Bookmark;
4
5use Shaarli\Bookmark\Exception\InvalidBookmarkException;
6
7/**
8 * Class BookmarkArray
9 *
10 * Implementing ArrayAccess, this allows us to use the bookmark list
11 * as an array and iterate over it.
12 *
13 * @package Shaarli\Bookmark
14 */
15class BookmarkArray implements \Iterator, \Countable, \ArrayAccess
16{
17 /**
18 * @var Bookmark[]
19 */
20 protected $bookmarks;
21
22 /**
23 * @var array List of all bookmarks IDS mapped with their array offset.
24 * Map: id->offset.
25 */
26 protected $ids;
27
28 /**
29 * @var int Position in the $this->keys array (for the Iterator interface)
30 */
31 protected $position;
32
33 /**
34 * @var array List of offset keys (for the Iterator interface implementation)
35 */
36 protected $keys;
37
38 /**
39 * @var array List of all recorded URLs (key=url, value=bookmark offset)
40 * for fast reserve search (url-->bookmark offset)
41 */
42 protected $urls;
43
44 public function __construct()
45 {
46 $this->ids = [];
47 $this->bookmarks = [];
48 $this->keys = [];
49 $this->urls = [];
50 $this->position = 0;
51 }
52
53 /**
54 * Countable - Counts elements of an object
55 *
56 * @return int Number of bookmarks
57 */
58 public function count()
59 {
60 return count($this->bookmarks);
61 }
62
63 /**
64 * ArrayAccess - Assigns a value to the specified offset
65 *
66 * @param int $offset Bookmark ID
67 * @param Bookmark $value instance
68 *
69 * @throws InvalidBookmarkException
70 */
71 public function offsetSet($offset, $value)
72 {
73 if (! $value instanceof Bookmark
74 || $value->getId() === null || empty($value->getUrl())
75 || ($offset !== null && ! is_int($offset)) || ! is_int($value->getId())
76 || $offset !== null && $offset !== $value->getId()
77 ) {
78 throw new InvalidBookmarkException($value);
79 }
80
81 // If the bookmark exists, we reuse the real offset, otherwise new entry
82 if ($offset !== null) {
83 $existing = $this->getBookmarkOffset($offset);
84 } else {
85 $existing = $this->getBookmarkOffset($value->getId());
86 }
87
88 if ($existing !== null) {
89 $offset = $existing;
90 } else {
91 $offset = count($this->bookmarks);
92 }
93
94 $this->bookmarks[$offset] = $value;
95 $this->urls[$value->getUrl()] = $offset;
96 $this->ids[$value->getId()] = $offset;
97 }
98
99 /**
100 * ArrayAccess - Whether or not an offset exists
101 *
102 * @param int $offset Bookmark ID
103 *
104 * @return bool true if it exists, false otherwise
105 */
106 public function offsetExists($offset)
107 {
108 return array_key_exists($this->getBookmarkOffset($offset), $this->bookmarks);
109 }
110
111 /**
112 * ArrayAccess - Unsets an offset
113 *
114 * @param int $offset Bookmark ID
115 */
116 public function offsetUnset($offset)
117 {
118 $realOffset = $this->getBookmarkOffset($offset);
119 $url = $this->bookmarks[$realOffset]->getUrl();
120 unset($this->urls[$url]);
121 unset($this->ids[$offset]);
122 unset($this->bookmarks[$realOffset]);
123 }
124
125 /**
126 * ArrayAccess - Returns the value at specified offset
127 *
128 * @param int $offset Bookmark ID
129 *
130 * @return Bookmark|null The Bookmark if found, null otherwise
131 */
132 public function offsetGet($offset)
133 {
134 $realOffset = $this->getBookmarkOffset($offset);
135 return isset($this->bookmarks[$realOffset]) ? $this->bookmarks[$realOffset] : null;
136 }
137
138 /**
139 * Iterator - Returns the current element
140 *
141 * @return Bookmark corresponding to the current position
142 */
143 public function current()
144 {
145 return $this[$this->keys[$this->position]];
146 }
147
148 /**
149 * Iterator - Returns the key of the current element
150 *
151 * @return int Bookmark ID corresponding to the current position
152 */
153 public function key()
154 {
155 return $this->keys[$this->position];
156 }
157
158 /**
159 * Iterator - Moves forward to next element
160 */
161 public function next()
162 {
163 ++$this->position;
164 }
165
166 /**
167 * Iterator - Rewinds the Iterator to the first element
168 *
169 * Entries are sorted by date (latest first)
170 */
171 public function rewind()
172 {
173 $this->keys = array_keys($this->ids);
174 $this->position = 0;
175 }
176
177 /**
178 * Iterator - Checks if current position is valid
179 *
180 * @return bool true if the current Bookmark ID exists, false otherwise
181 */
182 public function valid()
183 {
184 return isset($this->keys[$this->position]);
185 }
186
187 /**
188 * Returns a bookmark offset in bookmarks array from its unique ID.
189 *
190 * @param int $id Persistent ID of a bookmark.
191 *
192 * @return int Real offset in local array, or null if doesn't exist.
193 */
194 protected function getBookmarkOffset($id)
195 {
196 if (isset($this->ids[$id])) {
197 return $this->ids[$id];
198 }
199 return null;
200 }
201
202 /**
203 * Return the next key for bookmark creation.
204 * E.g. If the last ID is 597, the next will be 598.
205 *
206 * @return int next ID.
207 */
208 public function getNextId()
209 {
210 if (!empty($this->ids)) {
211 return max(array_keys($this->ids)) + 1;
212 }
213 return 0;
214 }
215
216 /**
217 * @param $url
218 *
219 * @return Bookmark|null
220 */
221 public function getByUrl($url)
222 {
223 if (! empty($url)
224 && isset($this->urls[$url])
225 && isset($this->bookmarks[$this->urls[$url]])
226 ) {
227 return $this->bookmarks[$this->urls[$url]];
228 }
229 return null;
230 }
231
232 /**
233 * Reorder links by creation date (newest first).
234 *
235 * Also update the urls and ids mapping arrays.
236 *
237 * @param string $order ASC|DESC
238 */
239 public function reorder($order = 'DESC')
240 {
241 $order = $order === 'ASC' ? -1 : 1;
242 // Reorder array by dates.
243 usort($this->bookmarks, function ($a, $b) use ($order) {
244 /** @var $a Bookmark */
245 /** @var $b Bookmark */
246 if ($a->isSticky() !== $b->isSticky()) {
247 return $a->isSticky() ? -1 : 1;
248 }
249 return $a->getCreated() < $b->getCreated() ? 1 * $order : -1 * $order;
250 });
251
252 $this->urls = [];
253 $this->ids = [];
254 foreach ($this->bookmarks as $key => $bookmark) {
255 $this->urls[$bookmark->getUrl()] = $key;
256 $this->ids[$bookmark->getId()] = $key;
257 }
258 }
259}
diff --git a/application/bookmark/BookmarkFileService.php b/application/bookmark/BookmarkFileService.php
new file mode 100644
index 00000000..a56cc92b
--- /dev/null
+++ b/application/bookmark/BookmarkFileService.php
@@ -0,0 +1,373 @@
1<?php
2
3
4namespace Shaarli\Bookmark;
5
6
7use Exception;
8use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
9use Shaarli\Bookmark\Exception\EmptyDataStoreException;
10use Shaarli\Config\ConfigManager;
11use Shaarli\History;
12use Shaarli\Legacy\LegacyLinkDB;
13use Shaarli\Legacy\LegacyUpdater;
14use Shaarli\Updater\UpdaterUtils;
15
16/**
17 * Class BookmarksService
18 *
19 * This is the entry point to manipulate the bookmark DB.
20 * It manipulates loads links from a file data store containing all bookmarks.
21 *
22 * It also triggers the legacy format (bookmarks as arrays) migration.
23 */
24class BookmarkFileService implements BookmarkServiceInterface
25{
26 /** @var Bookmark[] instance */
27 protected $bookmarks;
28
29 /** @var BookmarkIO instance */
30 protected $bookmarksIO;
31
32 /** @var BookmarkFilter */
33 protected $bookmarkFilter;
34
35 /** @var ConfigManager instance */
36 protected $conf;
37
38 /** @var History instance */
39 protected $history;
40
41 /** @var bool true for logged in users. Default value to retrieve private bookmarks. */
42 protected $isLoggedIn;
43
44 /**
45 * @inheritDoc
46 */
47 public function __construct(ConfigManager $conf, History $history, $isLoggedIn)
48 {
49 $this->conf = $conf;
50 $this->history = $history;
51 $this->bookmarksIO = new BookmarkIO($this->conf);
52 $this->isLoggedIn = $isLoggedIn;
53
54 if (!$this->isLoggedIn && $this->conf->get('privacy.hide_public_links', false)) {
55 $this->bookmarks = [];
56 } else {
57 try {
58 $this->bookmarks = $this->bookmarksIO->read();
59 } catch (EmptyDataStoreException $e) {
60 $this->bookmarks = new BookmarkArray();
61 if ($isLoggedIn) {
62 $this->save();
63 }
64 }
65
66 if (! $this->bookmarks instanceof BookmarkArray) {
67 $this->migrate();
68 exit(
69 'Your data store has been migrated, please reload the page.'. PHP_EOL .
70 'If this message keeps showing up, please delete data/updates.txt file.'
71 );
72 }
73 }
74
75 $this->bookmarkFilter = new BookmarkFilter($this->bookmarks);
76 }
77
78 /**
79 * @inheritDoc
80 */
81 public function findByHash($hash)
82 {
83 $bookmark = $this->bookmarkFilter->filter(BookmarkFilter::$FILTER_HASH, $hash);
84 // PHP 7.3 introduced array_key_first() to avoid this hack
85 $first = reset($bookmark);
86 if (! $this->isLoggedIn && $first->isPrivate()) {
87 throw new Exception('Not authorized');
88 }
89
90 return $bookmark;
91 }
92
93 /**
94 * @inheritDoc
95 */
96 public function findByUrl($url)
97 {
98 return $this->bookmarks->getByUrl($url);
99 }
100
101 /**
102 * @inheritDoc
103 */
104 public function search($request = [], $visibility = null, $caseSensitive = false, $untaggedOnly = false)
105 {
106 if ($visibility === null) {
107 $visibility = $this->isLoggedIn ? BookmarkFilter::$ALL : BookmarkFilter::$PUBLIC;
108 }
109
110 // Filter bookmark database according to parameters.
111 $searchtags = isset($request['searchtags']) ? $request['searchtags'] : '';
112 $searchterm = isset($request['searchterm']) ? $request['searchterm'] : '';
113
114 return $this->bookmarkFilter->filter(
115 BookmarkFilter::$FILTER_TAG | BookmarkFilter::$FILTER_TEXT,
116 [$searchtags, $searchterm],
117 $caseSensitive,
118 $visibility,
119 $untaggedOnly
120 );
121 }
122
123 /**
124 * @inheritDoc
125 */
126 public function get($id, $visibility = null)
127 {
128 if (! isset($this->bookmarks[$id])) {
129 throw new BookmarkNotFoundException();
130 }
131
132 if ($visibility === null) {
133 $visibility = $this->isLoggedIn ? 'all' : 'public';
134 }
135
136 $bookmark = $this->bookmarks[$id];
137 if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
138 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
139 ) {
140 throw new Exception('Unauthorized');
141 }
142
143 return $bookmark;
144 }
145
146 /**
147 * @inheritDoc
148 */
149 public function set($bookmark, $save = true)
150 {
151 if ($this->isLoggedIn !== true) {
152 throw new Exception(t('You\'re not authorized to alter the datastore'));
153 }
154 if (! $bookmark instanceof Bookmark) {
155 throw new Exception(t('Provided data is invalid'));
156 }
157 if (! isset($this->bookmarks[$bookmark->getId()])) {
158 throw new BookmarkNotFoundException();
159 }
160 $bookmark->validate();
161
162 $bookmark->setUpdated(new \DateTime());
163 $this->bookmarks[$bookmark->getId()] = $bookmark;
164 if ($save === true) {
165 $this->save();
166 $this->history->updateLink($bookmark);
167 }
168 return $this->bookmarks[$bookmark->getId()];
169 }
170
171 /**
172 * @inheritDoc
173 */
174 public function add($bookmark, $save = true)
175 {
176 if ($this->isLoggedIn !== true) {
177 throw new Exception(t('You\'re not authorized to alter the datastore'));
178 }
179 if (! $bookmark instanceof Bookmark) {
180 throw new Exception(t('Provided data is invalid'));
181 }
182 if (! empty($bookmark->getId())) {
183 throw new Exception(t('This bookmarks already exists'));
184 }
185 $bookmark->setId($this->bookmarks->getNextId());
186 $bookmark->validate();
187
188 $this->bookmarks[$bookmark->getId()] = $bookmark;
189 if ($save === true) {
190 $this->save();
191 $this->history->addLink($bookmark);
192 }
193 return $this->bookmarks[$bookmark->getId()];
194 }
195
196 /**
197 * @inheritDoc
198 */
199 public function addOrSet($bookmark, $save = true)
200 {
201 if ($this->isLoggedIn !== true) {
202 throw new Exception(t('You\'re not authorized to alter the datastore'));
203 }
204 if (! $bookmark instanceof Bookmark) {
205 throw new Exception('Provided data is invalid');
206 }
207 if ($bookmark->getId() === null) {
208 return $this->add($bookmark, $save);
209 }
210 return $this->set($bookmark, $save);
211 }
212
213 /**
214 * @inheritDoc
215 */
216 public function remove($bookmark, $save = true)
217 {
218 if ($this->isLoggedIn !== true) {
219 throw new Exception(t('You\'re not authorized to alter the datastore'));
220 }
221 if (! $bookmark instanceof Bookmark) {
222 throw new Exception(t('Provided data is invalid'));
223 }
224 if (! isset($this->bookmarks[$bookmark->getId()])) {
225 throw new BookmarkNotFoundException();
226 }
227
228 unset($this->bookmarks[$bookmark->getId()]);
229 if ($save === true) {
230 $this->save();
231 $this->history->deleteLink($bookmark);
232 }
233 }
234
235 /**
236 * @inheritDoc
237 */
238 public function exists($id, $visibility = null)
239 {
240 if (! isset($this->bookmarks[$id])) {
241 return false;
242 }
243
244 if ($visibility === null) {
245 $visibility = $this->isLoggedIn ? 'all' : 'public';
246 }
247
248 $bookmark = $this->bookmarks[$id];
249 if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
250 || (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
251 ) {
252 return false;
253 }
254
255 return true;
256 }
257
258 /**
259 * @inheritDoc
260 */
261 public function count($visibility = null)
262 {
263 return count($this->search([], $visibility));
264 }
265
266 /**
267 * @inheritDoc
268 */
269 public function save()
270 {
271 if (!$this->isLoggedIn) {
272 // TODO: raise an Exception instead
273 die('You are not authorized to change the database.');
274 }
275 $this->bookmarks->reorder();
276 $this->bookmarksIO->write($this->bookmarks);
277 invalidateCaches($this->conf->get('resource.page_cache'));
278 }
279
280 /**
281 * @inheritDoc
282 */
283 public function bookmarksCountPerTag($filteringTags = [], $visibility = null)
284 {
285 $bookmarks = $this->search(['searchtags' => $filteringTags], $visibility);
286 $tags = [];
287 $caseMapping = [];
288 foreach ($bookmarks as $bookmark) {
289 foreach ($bookmark->getTags() as $tag) {
290 if (empty($tag) || (! $this->isLoggedIn && startsWith($tag, '.'))) {
291 continue;
292 }
293 // The first case found will be displayed.
294 if (!isset($caseMapping[strtolower($tag)])) {
295 $caseMapping[strtolower($tag)] = $tag;
296 $tags[$caseMapping[strtolower($tag)]] = 0;
297 }
298 $tags[$caseMapping[strtolower($tag)]]++;
299 }
300 }
301
302 /*
303 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
304 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
305 *
306 * So we now use array_multisort() to sort tags by DESC occurrences,
307 * then ASC alphabetically for equal values.
308 *
309 * @see https://github.com/shaarli/Shaarli/issues/1142
310 */
311 $keys = array_keys($tags);
312 $tmpTags = array_combine($keys, $keys);
313 array_multisort($tags, SORT_DESC, $tmpTags, SORT_ASC, $tags);
314 return $tags;
315 }
316
317 /**
318 * @inheritDoc
319 */
320 public function days()
321 {
322 $bookmarkDays = [];
323 foreach ($this->search() as $bookmark) {
324 $bookmarkDays[$bookmark->getCreated()->format('Ymd')] = 0;
325 }
326 $bookmarkDays = array_keys($bookmarkDays);
327 sort($bookmarkDays);
328
329 return $bookmarkDays;
330 }
331
332 /**
333 * @inheritDoc
334 */
335 public function filterDay($request)
336 {
337 return $this->bookmarkFilter->filter(BookmarkFilter::$FILTER_DAY, $request);
338 }
339
340 /**
341 * @inheritDoc
342 */
343 public function initialize()
344 {
345 $initializer = new BookmarkInitializer($this);
346 $initializer->initialize();
347 }
348
349 /**
350 * Handles migration to the new database format (BookmarksArray).
351 */
352 protected function migrate()
353 {
354 $bookmarkDb = new LegacyLinkDB(
355 $this->conf->get('resource.datastore'),
356 true,
357 false
358 );
359 $updater = new LegacyUpdater(
360 UpdaterUtils::read_updates_file($this->conf->get('resource.updates')),
361 $bookmarkDb,
362 $this->conf,
363 true
364 );
365 $newUpdates = $updater->update();
366 if (! empty($newUpdates)) {
367 UpdaterUtils::write_updates_file(
368 $this->conf->get('resource.updates'),
369 $updater->getDoneUpdates()
370 );
371 }
372 }
373}
diff --git a/application/bookmark/LinkFilter.php b/application/bookmark/BookmarkFilter.php
index 9b966307..fd556679 100644
--- a/application/bookmark/LinkFilter.php
+++ b/application/bookmark/BookmarkFilter.php
@@ -3,14 +3,14 @@
3namespace Shaarli\Bookmark; 3namespace Shaarli\Bookmark;
4 4
5use Exception; 5use Exception;
6use Shaarli\Bookmark\Exception\LinkNotFoundException; 6use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
7 7
8/** 8/**
9 * Class LinkFilter. 9 * Class LinkFilter.
10 * 10 *
11 * Perform search and filter operation on link data list. 11 * Perform search and filter operation on link data list.
12 */ 12 */
13class LinkFilter 13class BookmarkFilter
14{ 14{
15 /** 15 /**
16 * @var string permalinks. 16 * @var string permalinks.
@@ -33,33 +33,49 @@ class LinkFilter
33 public static $FILTER_DAY = 'FILTER_DAY'; 33 public static $FILTER_DAY = 'FILTER_DAY';
34 34
35 /** 35 /**
36 * @var string filter by day.
37 */
38 public static $DEFAULT = 'NO_FILTER';
39
40 /** @var string Visibility: all */
41 public static $ALL = 'all';
42
43 /** @var string Visibility: public */
44 public static $PUBLIC = 'public';
45
46 /** @var string Visibility: private */
47 public static $PRIVATE = 'private';
48
49 /**
36 * @var string Allowed characters for hashtags (regex syntax). 50 * @var string Allowed characters for hashtags (regex syntax).
37 */ 51 */
38 public static $HASHTAG_CHARS = '\p{Pc}\p{N}\p{L}\p{Mn}'; 52 public static $HASHTAG_CHARS = '\p{Pc}\p{N}\p{L}\p{Mn}';
39 53
40 /** 54 /**
41 * @var LinkDB all available links. 55 * @var Bookmark[] all available bookmarks.
42 */ 56 */
43 private $links; 57 private $bookmarks;
44 58
45 /** 59 /**
46 * @param LinkDB $links initialization. 60 * @param Bookmark[] $bookmarks initialization.
47 */ 61 */
48 public function __construct($links) 62 public function __construct($bookmarks)
49 { 63 {
50 $this->links = $links; 64 $this->bookmarks = $bookmarks;
51 } 65 }
52 66
53 /** 67 /**
54 * Filter links according to parameters. 68 * Filter bookmarks according to parameters.
55 * 69 *
56 * @param string $type Type of filter (eg. tags, permalink, etc.). 70 * @param string $type Type of filter (eg. tags, permalink, etc.).
57 * @param mixed $request Filter content. 71 * @param mixed $request Filter content.
58 * @param bool $casesensitive Optional: Perform case sensitive filter if true. 72 * @param bool $casesensitive Optional: Perform case sensitive filter if true.
59 * @param string $visibility Optional: return only all/private/public links 73 * @param string $visibility Optional: return only all/private/public bookmarks
60 * @param string $untaggedonly Optional: return only untagged links. Applies only if $type includes FILTER_TAG 74 * @param bool $untaggedonly Optional: return only untagged bookmarks. Applies only if $type includes FILTER_TAG
75 *
76 * @return Bookmark[] filtered bookmark list.
61 * 77 *
62 * @return array filtered link list. 78 * @throws BookmarkNotFoundException
63 */ 79 */
64 public function filter($type, $request, $casesensitive = false, $visibility = 'all', $untaggedonly = false) 80 public function filter($type, $request, $casesensitive = false, $visibility = 'all', $untaggedonly = false)
65 { 81 {
@@ -81,13 +97,13 @@ class LinkFilter
81 if ($untaggedonly) { 97 if ($untaggedonly) {
82 $filtered = $this->filterUntagged($visibility); 98 $filtered = $this->filterUntagged($visibility);
83 } else { 99 } else {
84 $filtered = $this->links; 100 $filtered = $this->bookmarks;
85 } 101 }
86 if (!empty($request[0])) { 102 if (!empty($request[0])) {
87 $filtered = (new LinkFilter($filtered))->filterTags($request[0], $casesensitive, $visibility); 103 $filtered = (new BookmarkFilter($filtered))->filterTags($request[0], $casesensitive, $visibility);
88 } 104 }
89 if (!empty($request[1])) { 105 if (!empty($request[1])) {
90 $filtered = (new LinkFilter($filtered))->filterFulltext($request[1], $visibility); 106 $filtered = (new BookmarkFilter($filtered))->filterFulltext($request[1], $visibility);
91 } 107 }
92 return $filtered; 108 return $filtered;
93 case self::$FILTER_TEXT: 109 case self::$FILTER_TEXT:
@@ -108,21 +124,21 @@ class LinkFilter
108 /** 124 /**
109 * Unknown filter, but handle private only. 125 * Unknown filter, but handle private only.
110 * 126 *
111 * @param string $visibility Optional: return only all/private/public links 127 * @param string $visibility Optional: return only all/private/public bookmarks
112 * 128 *
113 * @return array filtered links. 129 * @return Bookmark[] filtered bookmarks.
114 */ 130 */
115 private function noFilter($visibility = 'all') 131 private function noFilter($visibility = 'all')
116 { 132 {
117 if ($visibility === 'all') { 133 if ($visibility === 'all') {
118 return $this->links; 134 return $this->bookmarks;
119 } 135 }
120 136
121 $out = array(); 137 $out = array();
122 foreach ($this->links as $key => $value) { 138 foreach ($this->bookmarks as $key => $value) {
123 if ($value['private'] && $visibility === 'private') { 139 if ($value->isPrivate() && $visibility === 'private') {
124 $out[$key] = $value; 140 $out[$key] = $value;
125 } elseif (!$value['private'] && $visibility === 'public') { 141 } elseif (!$value->isPrivate() && $visibility === 'public') {
126 $out[$key] = $value; 142 $out[$key] = $value;
127 } 143 }
128 } 144 }
@@ -137,28 +153,22 @@ class LinkFilter
137 * 153 *
138 * @return array $filtered array containing permalink data. 154 * @return array $filtered array containing permalink data.
139 * 155 *
140 * @throws \Shaarli\Bookmark\Exception\LinkNotFoundException if the smallhash doesn't match any link. 156 * @throws \Shaarli\Bookmark\Exception\BookmarkNotFoundException if the smallhash doesn't match any link.
141 */ 157 */
142 private function filterSmallHash($smallHash) 158 private function filterSmallHash($smallHash)
143 { 159 {
144 $filtered = array(); 160 foreach ($this->bookmarks as $key => $l) {
145 foreach ($this->links as $key => $l) { 161 if ($smallHash == $l->getShortUrl()) {
146 if ($smallHash == $l['shorturl']) {
147 // Yes, this is ugly and slow 162 // Yes, this is ugly and slow
148 $filtered[$key] = $l; 163 return [$key => $l];
149 return $filtered;
150 } 164 }
151 } 165 }
152 166
153 if (empty($filtered)) { 167 throw new BookmarkNotFoundException();
154 throw new LinkNotFoundException();
155 }
156
157 return $filtered;
158 } 168 }
159 169
160 /** 170 /**
161 * Returns the list of links corresponding to a full-text search 171 * Returns the list of bookmarks corresponding to a full-text search
162 * 172 *
163 * Searches: 173 * Searches:
164 * - in the URLs, title and description; 174 * - in the URLs, title and description;
@@ -174,7 +184,7 @@ class LinkFilter
174 * - see https://github.com/shaarli/Shaarli/issues/75 for examples 184 * - see https://github.com/shaarli/Shaarli/issues/75 for examples
175 * 185 *
176 * @param string $searchterms search query. 186 * @param string $searchterms search query.
177 * @param string $visibility Optional: return only all/private/public links. 187 * @param string $visibility Optional: return only all/private/public bookmarks.
178 * 188 *
179 * @return array search results. 189 * @return array search results.
180 */ 190 */
@@ -206,25 +216,23 @@ class LinkFilter
206 } 216 }
207 } 217 }
208 218
209 $keys = array('title', 'description', 'url', 'tags');
210
211 // Iterate over every stored link. 219 // Iterate over every stored link.
212 foreach ($this->links as $id => $link) { 220 foreach ($this->bookmarks as $id => $link) {
213 // ignore non private links when 'privatonly' is on. 221 // ignore non private bookmarks when 'privatonly' is on.
214 if ($visibility !== 'all') { 222 if ($visibility !== 'all') {
215 if (!$link['private'] && $visibility === 'private') { 223 if (!$link->isPrivate() && $visibility === 'private') {
216 continue; 224 continue;
217 } elseif ($link['private'] && $visibility === 'public') { 225 } elseif ($link->isPrivate() && $visibility === 'public') {
218 continue; 226 continue;
219 } 227 }
220 } 228 }
221 229
222 // Concatenate link fields to search across fields. 230 // Concatenate link fields to search across fields.
223 // Adds a '\' separator for exact search terms. 231 // Adds a '\' separator for exact search terms.
224 $content = ''; 232 $content = mb_convert_case($link->getTitle(), MB_CASE_LOWER, 'UTF-8') .'\\';
225 foreach ($keys as $key) { 233 $content .= mb_convert_case($link->getDescription(), MB_CASE_LOWER, 'UTF-8') .'\\';
226 $content .= mb_convert_case($link[$key], MB_CASE_LOWER, 'UTF-8') . '\\'; 234 $content .= mb_convert_case($link->getUrl(), MB_CASE_LOWER, 'UTF-8') .'\\';
227 } 235 $content .= mb_convert_case($link->getTagsString(), MB_CASE_LOWER, 'UTF-8') .'\\';
228 236
229 // Be optimistic 237 // Be optimistic
230 $found = true; 238 $found = true;
@@ -301,16 +309,16 @@ class LinkFilter
301 } 309 }
302 310
303 /** 311 /**
304 * Returns the list of links associated with a given list of tags 312 * Returns the list of bookmarks associated with a given list of tags
305 * 313 *
306 * You can specify one or more tags, separated by space or a comma, e.g. 314 * You can specify one or more tags, separated by space or a comma, e.g.
307 * print_r($mydb->filterTags('linux programming')); 315 * print_r($mydb->filterTags('linux programming'));
308 * 316 *
309 * @param string $tags list of tags separated by commas or blank spaces. 317 * @param string $tags list of tags separated by commas or blank spaces.
310 * @param bool $casesensitive ignore case if false. 318 * @param bool $casesensitive ignore case if false.
311 * @param string $visibility Optional: return only all/private/public links. 319 * @param string $visibility Optional: return only all/private/public bookmarks.
312 * 320 *
313 * @return array filtered links. 321 * @return array filtered bookmarks.
314 */ 322 */
315 public function filterTags($tags, $casesensitive = false, $visibility = 'all') 323 public function filterTags($tags, $casesensitive = false, $visibility = 'all')
316 { 324 {
@@ -326,6 +334,17 @@ class LinkFilter
326 return $this->noFilter($visibility); 334 return $this->noFilter($visibility);
327 } 335 }
328 336
337 // If we only have public visibility, we can't look for hidden tags
338 if ($visibility === self::$PUBLIC) {
339 $inputTags = array_values(array_filter($inputTags, function ($tag) {
340 return ! startsWith($tag, '.');
341 }));
342
343 if (empty($inputTags)) {
344 return [];
345 }
346 }
347
329 // build regex from all tags 348 // build regex from all tags
330 $re = '/^' . implode(array_map("self::tag2regex", $inputTags)) . '.*$/'; 349 $re = '/^' . implode(array_map("self::tag2regex", $inputTags)) . '.*$/';
331 if (!$casesensitive) { 350 if (!$casesensitive) {
@@ -334,27 +353,27 @@ class LinkFilter
334 } 353 }
335 354
336 // create resulting array 355 // create resulting array
337 $filtered = array(); 356 $filtered = [];
338 357
339 // iterate over each link 358 // iterate over each link
340 foreach ($this->links as $key => $link) { 359 foreach ($this->bookmarks as $key => $link) {
341 // check level of visibility 360 // check level of visibility
342 // ignore non private links when 'privateonly' is on. 361 // ignore non private bookmarks when 'privateonly' is on.
343 if ($visibility !== 'all') { 362 if ($visibility !== 'all') {
344 if (!$link['private'] && $visibility === 'private') { 363 if (!$link->isPrivate() && $visibility === 'private') {
345 continue; 364 continue;
346 } elseif ($link['private'] && $visibility === 'public') { 365 } elseif ($link->isPrivate() && $visibility === 'public') {
347 continue; 366 continue;
348 } 367 }
349 } 368 }
350 $search = $link['tags']; // build search string, start with tags of current link 369 $search = $link->getTagsString(); // build search string, start with tags of current link
351 if (strlen(trim($link['description'])) && strpos($link['description'], '#') !== false) { 370 if (strlen(trim($link->getDescription())) && strpos($link->getDescription(), '#') !== false) {
352 // description given and at least one possible tag found 371 // description given and at least one possible tag found
353 $descTags = array(); 372 $descTags = array();
354 // find all tags in the form of #tag in the description 373 // find all tags in the form of #tag in the description
355 preg_match_all( 374 preg_match_all(
356 '/(?<![' . self::$HASHTAG_CHARS . '])#([' . self::$HASHTAG_CHARS . ']+?)\b/sm', 375 '/(?<![' . self::$HASHTAG_CHARS . '])#([' . self::$HASHTAG_CHARS . ']+?)\b/sm',
357 $link['description'], 376 $link->getDescription(),
358 $descTags 377 $descTags
359 ); 378 );
360 if (count($descTags[1])) { 379 if (count($descTags[1])) {
@@ -373,25 +392,25 @@ class LinkFilter
373 } 392 }
374 393
375 /** 394 /**
376 * Return only links without any tag. 395 * Return only bookmarks without any tag.
377 * 396 *
378 * @param string $visibility return only all/private/public links. 397 * @param string $visibility return only all/private/public bookmarks.
379 * 398 *
380 * @return array filtered links. 399 * @return array filtered bookmarks.
381 */ 400 */
382 public function filterUntagged($visibility) 401 public function filterUntagged($visibility)
383 { 402 {
384 $filtered = []; 403 $filtered = [];
385 foreach ($this->links as $key => $link) { 404 foreach ($this->bookmarks as $key => $link) {
386 if ($visibility !== 'all') { 405 if ($visibility !== 'all') {
387 if (!$link['private'] && $visibility === 'private') { 406 if (!$link->isPrivate() && $visibility === 'private') {
388 continue; 407 continue;
389 } elseif ($link['private'] && $visibility === 'public') { 408 } elseif ($link->isPrivate() && $visibility === 'public') {
390 continue; 409 continue;
391 } 410 }
392 } 411 }
393 412
394 if (empty(trim($link['tags']))) { 413 if (empty(trim($link->getTagsString()))) {
395 $filtered[$key] = $link; 414 $filtered[$key] = $link;
396 } 415 }
397 } 416 }
@@ -418,8 +437,8 @@ class LinkFilter
418 } 437 }
419 438
420 $filtered = array(); 439 $filtered = array();
421 foreach ($this->links as $key => $l) { 440 foreach ($this->bookmarks as $key => $l) {
422 if ($l['created']->format('Ymd') == $day) { 441 if ($l->getCreated()->format('Ymd') == $day) {
423 $filtered[$key] = $l; 442 $filtered[$key] = $l;
424 } 443 }
425 } 444 }
diff --git a/application/bookmark/BookmarkIO.php b/application/bookmark/BookmarkIO.php
new file mode 100644
index 00000000..ae9ffcb4
--- /dev/null
+++ b/application/bookmark/BookmarkIO.php
@@ -0,0 +1,108 @@
1<?php
2
3namespace Shaarli\Bookmark;
4
5use Shaarli\Bookmark\Exception\EmptyDataStoreException;
6use Shaarli\Bookmark\Exception\NotWritableDataStoreException;
7use Shaarli\Config\ConfigManager;
8
9/**
10 * Class BookmarkIO
11 *
12 * This class performs read/write operation to the file data store.
13 * Used by BookmarkFileService.
14 *
15 * @package Shaarli\Bookmark
16 */
17class BookmarkIO
18{
19 /**
20 * @var string Datastore file path
21 */
22 protected $datastore;
23
24 /**
25 * @var ConfigManager instance
26 */
27 protected $conf;
28
29 /**
30 * string Datastore PHP prefix
31 */
32 protected static $phpPrefix = '<?php /* ';
33
34 /**
35 * string Datastore PHP suffix
36 */
37 protected static $phpSuffix = ' */ ?>';
38
39 /**
40 * LinksIO constructor.
41 *
42 * @param ConfigManager $conf instance
43 */
44 public function __construct($conf)
45 {
46 $this->conf = $conf;
47 $this->datastore = $conf->get('resource.datastore');
48 }
49
50 /**
51 * Reads database from disk to memory
52 *
53 * @return BookmarkArray instance
54 *
55 * @throws NotWritableDataStoreException Data couldn't be loaded
56 * @throws EmptyDataStoreException Datastore doesn't exist
57 */
58 public function read()
59 {
60 if (! file_exists($this->datastore)) {
61 throw new EmptyDataStoreException();
62 }
63
64 if (!is_writable($this->datastore)) {
65 throw new NotWritableDataStoreException($this->datastore);
66 }
67
68 // Note that gzinflate is faster than gzuncompress.
69 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
70 $links = unserialize(gzinflate(base64_decode(
71 substr(file_get_contents($this->datastore),
72 strlen(self::$phpPrefix), -strlen(self::$phpSuffix)))));
73
74 if (empty($links)) {
75 if (filesize($this->datastore) > 100) {
76 throw new NotWritableDataStoreException($this->datastore);
77 }
78 throw new EmptyDataStoreException();
79 }
80
81 return $links;
82 }
83
84 /**
85 * Saves the database from memory to disk
86 *
87 * @param BookmarkArray $links instance.
88 *
89 * @throws NotWritableDataStoreException the datastore is not writable
90 */
91 public function write($links)
92 {
93 if (is_file($this->datastore) && !is_writeable($this->datastore)) {
94 // The datastore exists but is not writeable
95 throw new NotWritableDataStoreException($this->datastore);
96 } else if (!is_file($this->datastore) && !is_writeable(dirname($this->datastore))) {
97 // The datastore does not exist and its parent directory is not writeable
98 throw new NotWritableDataStoreException(dirname($this->datastore));
99 }
100
101 file_put_contents(
102 $this->datastore,
103 self::$phpPrefix.base64_encode(gzdeflate(serialize($links))).self::$phpSuffix
104 );
105
106 invalidateCaches($this->conf->get('resource.page_cache'));
107 }
108}
diff --git a/application/bookmark/BookmarkInitializer.php b/application/bookmark/BookmarkInitializer.php
new file mode 100644
index 00000000..9eee9a35
--- /dev/null
+++ b/application/bookmark/BookmarkInitializer.php
@@ -0,0 +1,59 @@
1<?php
2
3namespace Shaarli\Bookmark;
4
5/**
6 * Class BookmarkInitializer
7 *
8 * This class is used to initialized default bookmarks after a fresh install of Shaarli.
9 * It is no longer call when the data store is empty,
10 * because user might want to delete default bookmarks after the install.
11 *
12 * To prevent data corruption, it does not overwrite existing bookmarks,
13 * even though there should not be any.
14 *
15 * @package Shaarli\Bookmark
16 */
17class BookmarkInitializer
18{
19 /** @var BookmarkServiceInterface */
20 protected $bookmarkService;
21
22 /**
23 * BookmarkInitializer constructor.
24 *
25 * @param BookmarkServiceInterface $bookmarkService
26 */
27 public function __construct($bookmarkService)
28 {
29 $this->bookmarkService = $bookmarkService;
30 }
31
32 /**
33 * Initialize the data store with default bookmarks
34 */
35 public function initialize()
36 {
37 $bookmark = new Bookmark();
38 $bookmark->setTitle(t('My secret stuff... - Pastebin.com'));
39 $bookmark->setUrl('http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=', []);
40 $bookmark->setDescription(t('Shhhh! I\'m a private link only YOU can see. You can delete me too.'));
41 $bookmark->setTagsString('secretstuff');
42 $bookmark->setPrivate(true);
43 $this->bookmarkService->add($bookmark);
44
45 $bookmark = new Bookmark();
46 $bookmark->setTitle(t('The personal, minimalist, super-fast, database free, bookmarking service'));
47 $bookmark->setUrl('https://shaarli.readthedocs.io', []);
48 $bookmark->setDescription(t(
49 'Welcome to Shaarli! This is your first public bookmark. '
50 . 'To edit or delete me, you must first login.
51
52To learn how to use Shaarli, consult the link "Documentation" at the bottom of this page.
53
54You use the community supported version of the original Shaarli project, by Sebastien Sauvage.'
55 ));
56 $bookmark->setTagsString('opensource software');
57 $this->bookmarkService->add($bookmark);
58 }
59}
diff --git a/application/bookmark/BookmarkServiceInterface.php b/application/bookmark/BookmarkServiceInterface.php
new file mode 100644
index 00000000..7b7a4f09
--- /dev/null
+++ b/application/bookmark/BookmarkServiceInterface.php
@@ -0,0 +1,180 @@
1<?php
2
3namespace Shaarli\Bookmark;
4
5
6use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
7use Shaarli\Bookmark\Exception\NotWritableDataStoreException;
8use Shaarli\Config\ConfigManager;
9use Shaarli\Exceptions\IOException;
10use Shaarli\History;
11
12/**
13 * Class BookmarksService
14 *
15 * This is the entry point to manipulate the bookmark DB.
16 */
17interface BookmarkServiceInterface
18{
19 /**
20 * BookmarksService constructor.
21 *
22 * @param ConfigManager $conf instance
23 * @param History $history instance
24 * @param bool $isLoggedIn true if the current user is logged in
25 */
26 public function __construct(ConfigManager $conf, History $history, $isLoggedIn);
27
28 /**
29 * Find a bookmark by hash
30 *
31 * @param string $hash
32 *
33 * @return mixed
34 *
35 * @throws \Exception
36 */
37 public function findByHash($hash);
38
39 /**
40 * @param $url
41 *
42 * @return Bookmark|null
43 */
44 public function findByUrl($url);
45
46 /**
47 * Search bookmarks
48 *
49 * @param mixed $request
50 * @param string $visibility
51 * @param bool $caseSensitive
52 * @param bool $untaggedOnly
53 *
54 * @return Bookmark[]
55 */
56 public function search($request = [], $visibility = null, $caseSensitive = false, $untaggedOnly = false);
57
58 /**
59 * Get a single bookmark by its ID.
60 *
61 * @param int $id Bookmark ID
62 * @param string $visibility all|public|private e.g. with public, accessing a private bookmark will throw an
63 * exception
64 *
65 * @return Bookmark
66 *
67 * @throws BookmarkNotFoundException
68 * @throws \Exception
69 */
70 public function get($id, $visibility = null);
71
72 /**
73 * Updates an existing bookmark (depending on its ID).
74 *
75 * @param Bookmark $bookmark
76 * @param bool $save Writes to the datastore if set to true
77 *
78 * @return Bookmark Updated bookmark
79 *
80 * @throws BookmarkNotFoundException
81 * @throws \Exception
82 */
83 public function set($bookmark, $save = true);
84
85 /**
86 * Adds a new bookmark (the ID must be empty).
87 *
88 * @param Bookmark $bookmark
89 * @param bool $save Writes to the datastore if set to true
90 *
91 * @return Bookmark new bookmark
92 *
93 * @throws \Exception
94 */
95 public function add($bookmark, $save = true);
96
97 /**
98 * Adds or updates a bookmark depending on its ID:
99 * - a Bookmark without ID will be added
100 * - a Bookmark with an existing ID will be updated
101 *
102 * @param Bookmark $bookmark
103 * @param bool $save
104 *
105 * @return Bookmark
106 *
107 * @throws \Exception
108 */
109 public function addOrSet($bookmark, $save = true);
110
111 /**
112 * Deletes a bookmark.
113 *
114 * @param Bookmark $bookmark
115 * @param bool $save
116 *
117 * @throws \Exception
118 */
119 public function remove($bookmark, $save = true);
120
121 /**
122 * Get a single bookmark by its ID.
123 *
124 * @param int $id Bookmark ID
125 * @param string $visibility all|public|private e.g. with public, accessing a private bookmark will throw an
126 * exception
127 *
128 * @return bool
129 */
130 public function exists($id, $visibility = null);
131
132 /**
133 * Return the number of available bookmarks for given visibility.
134 *
135 * @param string $visibility public|private|all
136 *
137 * @return int Number of bookmarks
138 */
139 public function count($visibility = null);
140
141 /**
142 * Write the datastore.
143 *
144 * @throws NotWritableDataStoreException
145 */
146 public function save();
147
148 /**
149 * Returns the list tags appearing in the bookmarks with the given tags
150 *
151 * @param array $filteringTags tags selecting the bookmarks to consider
152 * @param string $visibility process only all/private/public bookmarks
153 *
154 * @return array tag => bookmarksCount
155 */
156 public function bookmarksCountPerTag($filteringTags = [], $visibility = 'all');
157
158 /**
159 * Returns the list of days containing articles (oldest first)
160 *
161 * @return array containing days (in format YYYYMMDD).
162 */
163 public function days();
164
165 /**
166 * Returns the list of articles for a given day.
167 *
168 * @param string $request day to filter. Format: YYYYMMDD.
169 *
170 * @return Bookmark[] list of shaare found.
171 *
172 * @throws BookmarkNotFoundException
173 */
174 public function filterDay($request);
175
176 /**
177 * Creates the default database after a fresh install.
178 */
179 public function initialize();
180}
diff --git a/application/bookmark/LinkDB.php b/application/bookmark/LinkDB.php
deleted file mode 100644
index f01c7ee6..00000000
--- a/application/bookmark/LinkDB.php
+++ /dev/null
@@ -1,578 +0,0 @@
1<?php
2
3namespace Shaarli\Bookmark;
4
5use ArrayAccess;
6use Countable;
7use DateTime;
8use Iterator;
9use Shaarli\Bookmark\Exception\LinkNotFoundException;
10use Shaarli\Exceptions\IOException;
11use Shaarli\FileUtils;
12
13/**
14 * Data storage for links.
15 *
16 * This object behaves like an associative array.
17 *
18 * Example:
19 * $myLinks = new LinkDB();
20 * echo $myLinks[350]['title'];
21 * foreach ($myLinks as $link)
22 * echo $link['title'].' at url '.$link['url'].'; description:'.$link['description'];
23 *
24 * Available keys:
25 * - id: primary key, incremental integer identifier (persistent)
26 * - description: description of the entry
27 * - created: creation date of this entry, DateTime object.
28 * - updated: last modification date of this entry, DateTime object.
29 * - private: Is this link private? 0=no, other value=yes
30 * - tags: tags attached to this entry (separated by spaces)
31 * - title Title of the link
32 * - url URL of the link. Used for displayable links.
33 * Can be absolute or relative in the database but the relative links
34 * will be converted to absolute ones in templates.
35 * - real_url Raw URL in stored in the DB (absolute or relative).
36 * - shorturl Permalink smallhash
37 *
38 * Implements 3 interfaces:
39 * - ArrayAccess: behaves like an associative array;
40 * - Countable: there is a count() method;
41 * - Iterator: usable in foreach () loops.
42 *
43 * ID mechanism:
44 * ArrayAccess is implemented in a way that will allow to access a link
45 * with the unique identifier ID directly with $link[ID].
46 * Note that it's not the real key of the link array attribute.
47 * This mechanism is in place to have persistent link IDs,
48 * even though the internal array is reordered by date.
49 * Example:
50 * - DB: link #1 (2010-01-01) link #2 (2016-01-01)
51 * - Order: #2 #1
52 * - Import links containing: link #3 (2013-01-01)
53 * - New DB: link #1 (2010-01-01) link #2 (2016-01-01) link #3 (2013-01-01)
54 * - Real order: #2 #3 #1
55 */
56class LinkDB implements Iterator, Countable, ArrayAccess
57{
58 // Links are stored as a PHP serialized string
59 private $datastore;
60
61 // Link date storage format
62 const LINK_DATE_FORMAT = 'Ymd_His';
63
64 // List of links (associative array)
65 // - key: link date (e.g. "20110823_124546"),
66 // - value: associative array (keys: title, description...)
67 private $links;
68
69 // List of all recorded URLs (key=url, value=link offset)
70 // for fast reserve search (url-->link offset)
71 private $urls;
72
73 /**
74 * @var array List of all links IDS mapped with their array offset.
75 * Map: id->offset.
76 */
77 protected $ids;
78
79 // List of offset keys (for the Iterator interface implementation)
80 private $keys;
81
82 // Position in the $this->keys array (for the Iterator interface)
83 private $position;
84
85 // Is the user logged in? (used to filter private links)
86 private $loggedIn;
87
88 // Hide public links
89 private $hidePublicLinks;
90
91 /**
92 * Creates a new LinkDB
93 *
94 * Checks if the datastore exists; else, attempts to create a dummy one.
95 *
96 * @param string $datastore datastore file path.
97 * @param boolean $isLoggedIn is the user logged in?
98 * @param boolean $hidePublicLinks if true all links are private.
99 */
100 public function __construct(
101 $datastore,
102 $isLoggedIn,
103 $hidePublicLinks
104 ) {
105
106 $this->datastore = $datastore;
107 $this->loggedIn = $isLoggedIn;
108 $this->hidePublicLinks = $hidePublicLinks;
109 $this->check();
110 $this->read();
111 }
112
113 /**
114 * Countable - Counts elements of an object
115 */
116 public function count()
117 {
118 return count($this->links);
119 }
120
121 /**
122 * ArrayAccess - Assigns a value to the specified offset
123 */
124 public function offsetSet($offset, $value)
125 {
126 // TODO: use exceptions instead of "die"
127 if (!$this->loggedIn) {
128 die(t('You are not authorized to add a link.'));
129 }
130 if (!isset($value['id']) || empty($value['url'])) {
131 die(t('Internal Error: A link should always have an id and URL.'));
132 }
133 if (($offset !== null && !is_int($offset)) || !is_int($value['id'])) {
134 die(t('You must specify an integer as a key.'));
135 }
136 if ($offset !== null && $offset !== $value['id']) {
137 die(t('Array offset and link ID must be equal.'));
138 }
139
140 // If the link exists, we reuse the real offset, otherwise new entry
141 $existing = $this->getLinkOffset($offset);
142 if ($existing !== null) {
143 $offset = $existing;
144 } else {
145 $offset = count($this->links);
146 }
147 $this->links[$offset] = $value;
148 $this->urls[$value['url']] = $offset;
149 $this->ids[$value['id']] = $offset;
150 }
151
152 /**
153 * ArrayAccess - Whether or not an offset exists
154 */
155 public function offsetExists($offset)
156 {
157 return array_key_exists($this->getLinkOffset($offset), $this->links);
158 }
159
160 /**
161 * ArrayAccess - Unsets an offset
162 */
163 public function offsetUnset($offset)
164 {
165 if (!$this->loggedIn) {
166 // TODO: raise an exception
167 die('You are not authorized to delete a link.');
168 }
169 $realOffset = $this->getLinkOffset($offset);
170 $url = $this->links[$realOffset]['url'];
171 unset($this->urls[$url]);
172 unset($this->ids[$realOffset]);
173 unset($this->links[$realOffset]);
174 }
175
176 /**
177 * ArrayAccess - Returns the value at specified offset
178 */
179 public function offsetGet($offset)
180 {
181 $realOffset = $this->getLinkOffset($offset);
182 return isset($this->links[$realOffset]) ? $this->links[$realOffset] : null;
183 }
184
185 /**
186 * Iterator - Returns the current element
187 */
188 public function current()
189 {
190 return $this[$this->keys[$this->position]];
191 }
192
193 /**
194 * Iterator - Returns the key of the current element
195 */
196 public function key()
197 {
198 return $this->keys[$this->position];
199 }
200
201 /**
202 * Iterator - Moves forward to next element
203 */
204 public function next()
205 {
206 ++$this->position;
207 }
208
209 /**
210 * Iterator - Rewinds the Iterator to the first element
211 *
212 * Entries are sorted by date (latest first)
213 */
214 public function rewind()
215 {
216 $this->keys = array_keys($this->ids);
217 $this->position = 0;
218 }
219
220 /**
221 * Iterator - Checks if current position is valid
222 */
223 public function valid()
224 {
225 return isset($this->keys[$this->position]);
226 }
227
228 /**
229 * Checks if the DB directory and file exist
230 *
231 * If no DB file is found, creates a dummy DB.
232 */
233 private function check()
234 {
235 if (file_exists($this->datastore)) {
236 return;
237 }
238
239 // Create a dummy database for example
240 $this->links = array();
241 $link = array(
242 'id' => 1,
243 'title' => t('The personal, minimalist, super-fast, database free, bookmarking service'),
244 'url' => 'https://shaarli.readthedocs.io',
245 'description' => t(
246 'Welcome to Shaarli! This is your first public bookmark. '
247 . 'To edit or delete me, you must first login.
248
249To learn how to use Shaarli, consult the link "Documentation" at the bottom of this page.
250
251You use the community supported version of the original Shaarli project, by Sebastien Sauvage.'
252 ),
253 'private' => 0,
254 'created' => new DateTime(),
255 'tags' => 'opensource software',
256 'sticky' => false,
257 );
258 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
259 $this->links[1] = $link;
260
261 $link = array(
262 'id' => 0,
263 'title' => t('My secret stuff... - Pastebin.com'),
264 'url' => 'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
265 'description' => t('Shhhh! I\'m a private link only YOU can see. You can delete me too.'),
266 'private' => 1,
267 'created' => new DateTime('1 minute ago'),
268 'tags' => 'secretstuff',
269 'sticky' => false,
270 );
271 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
272 $this->links[0] = $link;
273
274 // Write database to disk
275 $this->write();
276 }
277
278 /**
279 * Reads database from disk to memory
280 */
281 private function read()
282 {
283 // Public links are hidden and user not logged in => nothing to show
284 if ($this->hidePublicLinks && !$this->loggedIn) {
285 $this->links = array();
286 return;
287 }
288
289 $this->urls = [];
290 $this->ids = [];
291 $this->links = FileUtils::readFlatDB($this->datastore, []);
292
293 $toremove = array();
294 foreach ($this->links as $key => &$link) {
295 if (!$this->loggedIn && $link['private'] != 0) {
296 // Transition for not upgraded databases.
297 unset($this->links[$key]);
298 continue;
299 }
300
301 // Sanitize data fields.
302 sanitizeLink($link);
303
304 // Remove private tags if the user is not logged in.
305 if (!$this->loggedIn) {
306 $link['tags'] = preg_replace('/(^|\s+)\.[^($|\s)]+\s*/', ' ', $link['tags']);
307 }
308
309 $link['real_url'] = $link['url'];
310
311 $link['sticky'] = isset($link['sticky']) ? $link['sticky'] : false;
312
313 // To be able to load links before running the update, and prepare the update
314 if (!isset($link['created'])) {
315 $link['id'] = $link['linkdate'];
316 $link['created'] = DateTime::createFromFormat(self::LINK_DATE_FORMAT, $link['linkdate']);
317 if (!empty($link['updated'])) {
318 $link['updated'] = DateTime::createFromFormat(self::LINK_DATE_FORMAT, $link['updated']);
319 }
320 $link['shorturl'] = smallHash($link['linkdate']);
321 }
322
323 $this->urls[$link['url']] = $key;
324 $this->ids[$link['id']] = $key;
325 }
326 }
327
328 /**
329 * Saves the database from memory to disk
330 *
331 * @throws IOException the datastore is not writable
332 */
333 private function write()
334 {
335 $this->reorder();
336 FileUtils::writeFlatDB($this->datastore, $this->links);
337 }
338
339 /**
340 * Saves the database from memory to disk
341 *
342 * @param string $pageCacheDir page cache directory
343 */
344 public function save($pageCacheDir)
345 {
346 if (!$this->loggedIn) {
347 // TODO: raise an Exception instead
348 die('You are not authorized to change the database.');
349 }
350
351 $this->write();
352
353 invalidateCaches($pageCacheDir);
354 }
355
356 /**
357 * Returns the link for a given URL, or False if it does not exist.
358 *
359 * @param string $url URL to search for
360 *
361 * @return mixed the existing link if it exists, else 'false'
362 */
363 public function getLinkFromUrl($url)
364 {
365 if (isset($this->urls[$url])) {
366 return $this->links[$this->urls[$url]];
367 }
368 return false;
369 }
370
371 /**
372 * Returns the shaare corresponding to a smallHash.
373 *
374 * @param string $request QUERY_STRING server parameter.
375 *
376 * @return array $filtered array containing permalink data.
377 *
378 * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link.
379 */
380 public function filterHash($request)
381 {
382 $request = substr($request, 0, 6);
383 $linkFilter = new LinkFilter($this->links);
384 return $linkFilter->filter(LinkFilter::$FILTER_HASH, $request);
385 }
386
387 /**
388 * Returns the list of articles for a given day.
389 *
390 * @param string $request day to filter. Format: YYYYMMDD.
391 *
392 * @return array list of shaare found.
393 */
394 public function filterDay($request)
395 {
396 $linkFilter = new LinkFilter($this->links);
397 return $linkFilter->filter(LinkFilter::$FILTER_DAY, $request);
398 }
399
400 /**
401 * Filter links according to search parameters.
402 *
403 * @param array $filterRequest Search request content. Supported keys:
404 * - searchtags: list of tags
405 * - searchterm: term search
406 * @param bool $casesensitive Optional: Perform case sensitive filter
407 * @param string $visibility return only all/private/public links
408 * @param bool $untaggedonly return only untagged links
409 *
410 * @return array filtered links, all links if no suitable filter was provided.
411 */
412 public function filterSearch(
413 $filterRequest = array(),
414 $casesensitive = false,
415 $visibility = 'all',
416 $untaggedonly = false
417 ) {
418
419 // Filter link database according to parameters.
420 $searchtags = isset($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
421 $searchterm = isset($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
422
423 // Search tags + fullsearch - blank string parameter will return all links.
424 $type = LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT; // == "vuotext"
425 $request = [$searchtags, $searchterm];
426
427 $linkFilter = new LinkFilter($this);
428 return $linkFilter->filter($type, $request, $casesensitive, $visibility, $untaggedonly);
429 }
430
431 /**
432 * Returns the list tags appearing in the links with the given tags
433 *
434 * @param array $filteringTags tags selecting the links to consider
435 * @param string $visibility process only all/private/public links
436 *
437 * @return array tag => linksCount
438 */
439 public function linksCountPerTag($filteringTags = [], $visibility = 'all')
440 {
441 $links = $this->filterSearch(['searchtags' => $filteringTags], false, $visibility);
442 $tags = [];
443 $caseMapping = [];
444 foreach ($links as $link) {
445 foreach (preg_split('/\s+/', $link['tags'], 0, PREG_SPLIT_NO_EMPTY) as $tag) {
446 if (empty($tag)) {
447 continue;
448 }
449 // The first case found will be displayed.
450 if (!isset($caseMapping[strtolower($tag)])) {
451 $caseMapping[strtolower($tag)] = $tag;
452 $tags[$caseMapping[strtolower($tag)]] = 0;
453 }
454 $tags[$caseMapping[strtolower($tag)]]++;
455 }
456 }
457
458 /*
459 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
460 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
461 *
462 * So we now use array_multisort() to sort tags by DESC occurrences,
463 * then ASC alphabetically for equal values.
464 *
465 * @see https://github.com/shaarli/Shaarli/issues/1142
466 */
467 $keys = array_keys($tags);
468 $tmpTags = array_combine($keys, $keys);
469 array_multisort($tags, SORT_DESC, $tmpTags, SORT_ASC, $tags);
470 return $tags;
471 }
472
473 /**
474 * Rename or delete a tag across all links.
475 *
476 * @param string $from Tag to rename
477 * @param string $to New tag. If none is provided, the from tag will be deleted
478 *
479 * @return array|bool List of altered links or false on error
480 */
481 public function renameTag($from, $to)
482 {
483 if (empty($from)) {
484 return false;
485 }
486 $delete = empty($to);
487 // True for case-sensitive tag search.
488 $linksToAlter = $this->filterSearch(['searchtags' => $from], true);
489 foreach ($linksToAlter as $key => &$value) {
490 $tags = preg_split('/\s+/', trim($value['tags']));
491 if (($pos = array_search($from, $tags)) !== false) {
492 if ($delete) {
493 unset($tags[$pos]); // Remove tag.
494 } else {
495 $tags[$pos] = trim($to);
496 }
497 $value['tags'] = trim(implode(' ', array_unique($tags)));
498 $this[$value['id']] = $value;
499 }
500 }
501
502 return $linksToAlter;
503 }
504
505 /**
506 * Returns the list of days containing articles (oldest first)
507 * Output: An array containing days (in format YYYYMMDD).
508 */
509 public function days()
510 {
511 $linkDays = array();
512 foreach ($this->links as $link) {
513 $linkDays[$link['created']->format('Ymd')] = 0;
514 }
515 $linkDays = array_keys($linkDays);
516 sort($linkDays);
517
518 return $linkDays;
519 }
520
521 /**
522 * Reorder links by creation date (newest first).
523 *
524 * Also update the urls and ids mapping arrays.
525 *
526 * @param string $order ASC|DESC
527 */
528 public function reorder($order = 'DESC')
529 {
530 $order = $order === 'ASC' ? -1 : 1;
531 // Reorder array by dates.
532 usort($this->links, function ($a, $b) use ($order) {
533 if (isset($a['sticky']) && isset($b['sticky']) && $a['sticky'] !== $b['sticky']) {
534 return $a['sticky'] ? -1 : 1;
535 }
536 if ($a['created'] == $b['created']) {
537 return $a['id'] < $b['id'] ? 1 * $order : -1 * $order;
538 }
539 return $a['created'] < $b['created'] ? 1 * $order : -1 * $order;
540 });
541
542 $this->urls = [];
543 $this->ids = [];
544 foreach ($this->links as $key => $link) {
545 $this->urls[$link['url']] = $key;
546 $this->ids[$link['id']] = $key;
547 }
548 }
549
550 /**
551 * Return the next key for link creation.
552 * E.g. If the last ID is 597, the next will be 598.
553 *
554 * @return int next ID.
555 */
556 public function getNextId()
557 {
558 if (!empty($this->ids)) {
559 return max(array_keys($this->ids)) + 1;
560 }
561 return 0;
562 }
563
564 /**
565 * Returns a link offset in links array from its unique ID.
566 *
567 * @param int $id Persistent ID of a link.
568 *
569 * @return int Real offset in local array, or null if doesn't exist.
570 */
571 protected function getLinkOffset($id)
572 {
573 if (isset($this->ids[$id])) {
574 return $this->ids[$id];
575 }
576 return null;
577 }
578}
diff --git a/application/bookmark/LinkUtils.php b/application/bookmark/LinkUtils.php
index 77eb2d95..88379430 100644
--- a/application/bookmark/LinkUtils.php
+++ b/application/bookmark/LinkUtils.php
@@ -1,6 +1,6 @@
1<?php 1<?php
2 2
3use Shaarli\Bookmark\LinkDB; 3use Shaarli\Bookmark\Bookmark;
4 4
5/** 5/**
6 * Get cURL callback function for CURLOPT_WRITEFUNCTION 6 * Get cURL callback function for CURLOPT_WRITEFUNCTION
@@ -188,30 +188,11 @@ function html_extract_tag($tag, $html)
188} 188}
189 189
190/** 190/**
191 * Count private links in given linklist. 191 * In a string, converts URLs to clickable bookmarks.
192 *
193 * @param array|Countable $links Linklist.
194 *
195 * @return int Number of private links.
196 */
197function count_private($links)
198{
199 $cpt = 0;
200 foreach ($links as $link) {
201 if ($link['private']) {
202 $cpt += 1;
203 }
204 }
205
206 return $cpt;
207}
208
209/**
210 * In a string, converts URLs to clickable links.
211 * 192 *
212 * @param string $text input string. 193 * @param string $text input string.
213 * 194 *
214 * @return string returns $text with all links converted to HTML links. 195 * @return string returns $text with all bookmarks converted to HTML bookmarks.
215 * 196 *
216 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722 197 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
217 */ 198 */
@@ -279,7 +260,7 @@ function format_description($description, $indexUrl = '')
279 */ 260 */
280function link_small_hash($date, $id) 261function link_small_hash($date, $id)
281{ 262{
282 return smallHash($date->format(LinkDB::LINK_DATE_FORMAT) . $id); 263 return smallHash($date->format(Bookmark::LINK_DATE_FORMAT) . $id);
283} 264}
284 265
285/** 266/**
diff --git a/application/bookmark/exception/LinkNotFoundException.php b/application/bookmark/exception/BookmarkNotFoundException.php
index f9414428..827a3d35 100644
--- a/application/bookmark/exception/LinkNotFoundException.php
+++ b/application/bookmark/exception/BookmarkNotFoundException.php
@@ -3,7 +3,7 @@ namespace Shaarli\Bookmark\Exception;
3 3
4use Exception; 4use Exception;
5 5
6class LinkNotFoundException extends Exception 6class BookmarkNotFoundException extends Exception
7{ 7{
8 /** 8 /**
9 * LinkNotFoundException constructor. 9 * LinkNotFoundException constructor.
diff --git a/application/bookmark/exception/EmptyDataStoreException.php b/application/bookmark/exception/EmptyDataStoreException.php
new file mode 100644
index 00000000..cd48c1e6
--- /dev/null
+++ b/application/bookmark/exception/EmptyDataStoreException.php
@@ -0,0 +1,7 @@
1<?php
2
3
4namespace Shaarli\Bookmark\Exception;
5
6
7class EmptyDataStoreException extends \Exception {}
diff --git a/application/bookmark/exception/InvalidBookmarkException.php b/application/bookmark/exception/InvalidBookmarkException.php
new file mode 100644
index 00000000..10c84a6d
--- /dev/null
+++ b/application/bookmark/exception/InvalidBookmarkException.php
@@ -0,0 +1,30 @@
1<?php
2
3namespace Shaarli\Bookmark\Exception;
4
5use Shaarli\Bookmark\Bookmark;
6
7class InvalidBookmarkException extends \Exception
8{
9 public function __construct($bookmark)
10 {
11 if ($bookmark instanceof Bookmark) {
12 if ($bookmark->getCreated() instanceof \DateTime) {
13 $created = $bookmark->getCreated()->format(\DateTime::ATOM);
14 } elseif (empty($bookmark->getCreated())) {
15 $created = '';
16 } else {
17 $created = 'Not a DateTime object';
18 }
19 $this->message = 'This bookmark is not valid'. PHP_EOL;
20 $this->message .= ' - ID: '. $bookmark->getId() . PHP_EOL;
21 $this->message .= ' - Title: '. $bookmark->getTitle() . PHP_EOL;
22 $this->message .= ' - Url: '. $bookmark->getUrl() . PHP_EOL;
23 $this->message .= ' - ShortUrl: '. $bookmark->getShortUrl() . PHP_EOL;
24 $this->message .= ' - Created: '. $created . PHP_EOL;
25 } else {
26 $this->message = 'The provided data is not a bookmark'. PHP_EOL;
27 $this->message .= var_export($bookmark, true);
28 }
29 }
30}
diff --git a/application/bookmark/exception/NotWritableDataStoreException.php b/application/bookmark/exception/NotWritableDataStoreException.php
new file mode 100644
index 00000000..95f34b50
--- /dev/null
+++ b/application/bookmark/exception/NotWritableDataStoreException.php
@@ -0,0 +1,19 @@
1<?php
2
3
4namespace Shaarli\Bookmark\Exception;
5
6
7class NotWritableDataStoreException extends \Exception
8{
9 /**
10 * NotReadableDataStore constructor.
11 *
12 * @param string $dataStore file path
13 */
14 public function __construct($dataStore)
15 {
16 $this->message = 'Couldn\'t load data from the data store file "'. $dataStore .'". '.
17 'Your data might be corrupted, or your file isn\'t readable.';
18 }
19}