]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkDB.php
lint: apply phpcbf to application/
[github/shaarli/Shaarli.git] / application / LinkDB.php
1 <?php
2 /**
3 * Data storage for links.
4 *
5 * This object behaves like an associative array.
6 *
7 * Example:
8 * $myLinks = new LinkDB();
9 * echo $myLinks[350]['title'];
10 * foreach ($myLinks as $link)
11 * echo $link['title'].' at url '.$link['url'].'; description:'.$link['description'];
12 *
13 * Available keys:
14 * - id: primary key, incremental integer identifier (persistent)
15 * - description: description of the entry
16 * - created: creation date of this entry, DateTime object.
17 * - updated: last modification date of this entry, DateTime object.
18 * - private: Is this link private? 0=no, other value=yes
19 * - tags: tags attached to this entry (separated by spaces)
20 * - title Title of the link
21 * - url URL of the link. Used for displayable links (no redirector, relative, etc.).
22 * Can be absolute or relative.
23 * Relative URLs are permalinks (e.g.'?m-ukcw')
24 * - real_url Absolute processed URL.
25 * - shorturl Permalink smallhash
26 *
27 * Implements 3 interfaces:
28 * - ArrayAccess: behaves like an associative array;
29 * - Countable: there is a count() method;
30 * - Iterator: usable in foreach () loops.
31 *
32 * ID mechanism:
33 * ArrayAccess is implemented in a way that will allow to access a link
34 * with the unique identifier ID directly with $link[ID].
35 * Note that it's not the real key of the link array attribute.
36 * This mechanism is in place to have persistent link IDs,
37 * even though the internal array is reordered by date.
38 * Example:
39 * - DB: link #1 (2010-01-01) link #2 (2016-01-01)
40 * - Order: #2 #1
41 * - Import links containing: link #3 (2013-01-01)
42 * - New DB: link #1 (2010-01-01) link #2 (2016-01-01) link #3 (2013-01-01)
43 * - Real order: #2 #3 #1
44 */
45 class LinkDB implements Iterator, Countable, ArrayAccess
46 {
47 // Links are stored as a PHP serialized string
48 private $datastore;
49
50 // Link date storage format
51 const LINK_DATE_FORMAT = 'Ymd_His';
52
53 // List of links (associative array)
54 // - key: link date (e.g. "20110823_124546"),
55 // - value: associative array (keys: title, description...)
56 private $links;
57
58 // List of all recorded URLs (key=url, value=link offset)
59 // for fast reserve search (url-->link offset)
60 private $urls;
61
62 /**
63 * @var array List of all links IDS mapped with their array offset.
64 * Map: id->offset.
65 */
66 protected $ids;
67
68 // List of offset keys (for the Iterator interface implementation)
69 private $keys;
70
71 // Position in the $this->keys array (for the Iterator interface)
72 private $position;
73
74 // Is the user logged in? (used to filter private links)
75 private $loggedIn;
76
77 // Hide public links
78 private $hidePublicLinks;
79
80 // link redirector set in user settings.
81 private $redirector;
82
83 /**
84 * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched.
85 *
86 * Example:
87 * anonym.to needs clean URL while dereferer.org needs urlencoded URL.
88 *
89 * @var boolean $redirectorEncode parameter: true or false
90 */
91 private $redirectorEncode;
92
93 /**
94 * Creates a new LinkDB
95 *
96 * Checks if the datastore exists; else, attempts to create a dummy one.
97 *
98 * @param string $datastore datastore file path.
99 * @param boolean $isLoggedIn is the user logged in?
100 * @param boolean $hidePublicLinks if true all links are private.
101 * @param string $redirector link redirector set in user settings.
102 * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true).
103 */
104 public function __construct(
105 $datastore,
106 $isLoggedIn,
107 $hidePublicLinks,
108 $redirector = '',
109 $redirectorEncode = true
110 ) {
111 $this->datastore = $datastore;
112 $this->loggedIn = $isLoggedIn;
113 $this->hidePublicLinks = $hidePublicLinks;
114 $this->redirector = $redirector;
115 $this->redirectorEncode = $redirectorEncode === true;
116 $this->check();
117 $this->read();
118 }
119
120 /**
121 * Countable - Counts elements of an object
122 */
123 public function count()
124 {
125 return count($this->links);
126 }
127
128 /**
129 * ArrayAccess - Assigns a value to the specified offset
130 */
131 public function offsetSet($offset, $value)
132 {
133 // TODO: use exceptions instead of "die"
134 if (!$this->loggedIn) {
135 die(t('You are not authorized to add a link.'));
136 }
137 if (!isset($value['id']) || empty($value['url'])) {
138 die(t('Internal Error: A link should always have an id and URL.'));
139 }
140 if (($offset !== null && ! is_int($offset)) || ! is_int($value['id'])) {
141 die(t('You must specify an integer as a key.'));
142 }
143 if ($offset !== null && $offset !== $value['id']) {
144 die(t('Array offset and link ID must be equal.'));
145 }
146
147 // If the link exists, we reuse the real offset, otherwise new entry
148 $existing = $this->getLinkOffset($offset);
149 if ($existing !== null) {
150 $offset = $existing;
151 } else {
152 $offset = count($this->links);
153 }
154 $this->links[$offset] = $value;
155 $this->urls[$value['url']] = $offset;
156 $this->ids[$value['id']] = $offset;
157 }
158
159 /**
160 * ArrayAccess - Whether or not an offset exists
161 */
162 public function offsetExists($offset)
163 {
164 return array_key_exists($this->getLinkOffset($offset), $this->links);
165 }
166
167 /**
168 * ArrayAccess - Unsets an offset
169 */
170 public function offsetUnset($offset)
171 {
172 if (!$this->loggedIn) {
173 // TODO: raise an exception
174 die('You are not authorized to delete a link.');
175 }
176 $realOffset = $this->getLinkOffset($offset);
177 $url = $this->links[$realOffset]['url'];
178 unset($this->urls[$url]);
179 unset($this->ids[$realOffset]);
180 unset($this->links[$realOffset]);
181 }
182
183 /**
184 * ArrayAccess - Returns the value at specified offset
185 */
186 public function offsetGet($offset)
187 {
188 $realOffset = $this->getLinkOffset($offset);
189 return isset($this->links[$realOffset]) ? $this->links[$realOffset] : null;
190 }
191
192 /**
193 * Iterator - Returns the current element
194 */
195 public function current()
196 {
197 return $this[$this->keys[$this->position]];
198 }
199
200 /**
201 * Iterator - Returns the key of the current element
202 */
203 public function key()
204 {
205 return $this->keys[$this->position];
206 }
207
208 /**
209 * Iterator - Moves forward to next element
210 */
211 public function next()
212 {
213 ++$this->position;
214 }
215
216 /**
217 * Iterator - Rewinds the Iterator to the first element
218 *
219 * Entries are sorted by date (latest first)
220 */
221 public function rewind()
222 {
223 $this->keys = array_keys($this->ids);
224 $this->position = 0;
225 }
226
227 /**
228 * Iterator - Checks if current position is valid
229 */
230 public function valid()
231 {
232 return isset($this->keys[$this->position]);
233 }
234
235 /**
236 * Checks if the DB directory and file exist
237 *
238 * If no DB file is found, creates a dummy DB.
239 */
240 private function check()
241 {
242 if (file_exists($this->datastore)) {
243 return;
244 }
245
246 // Create a dummy database for example
247 $this->links = array();
248 $link = array(
249 'id' => 1,
250 'title'=> t('The personal, minimalist, super-fast, database free, bookmarking service'),
251 'url'=>'https://shaarli.readthedocs.io',
252 'description'=>t('Welcome to Shaarli! This is your first public bookmark. To edit or delete me, you must first login.
253
254 To learn how to use Shaarli, consult the link "Documentation" at the bottom of this page.
255
256 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.'),
257 'private'=>0,
258 'created'=> new DateTime(),
259 'tags'=>'opensource software'
260 );
261 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
262 $this->links[1] = $link;
263
264 $link = array(
265 'id' => 0,
266 'title'=> t('My secret stuff... - Pastebin.com'),
267 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
268 'description'=> t('Shhhh! I\'m a private link only YOU can see. You can delete me too.'),
269 'private'=>1,
270 'created'=> new DateTime('1 minute ago'),
271 'tags'=>'secretstuff',
272 );
273 $link['shorturl'] = link_small_hash($link['created'], $link['id']);
274 $this->links[0] = $link;
275
276 // Write database to disk
277 $this->write();
278 }
279
280 /**
281 * Reads database from disk to memory
282 */
283 private function read()
284 {
285 // Public links are hidden and user not logged in => nothing to show
286 if ($this->hidePublicLinks && !$this->loggedIn) {
287 $this->links = array();
288 return;
289 }
290
291 $this->urls = [];
292 $this->ids = [];
293 $this->links = FileUtils::readFlatDB($this->datastore, []);
294
295 $toremove = array();
296 foreach ($this->links as $key => &$link) {
297 if (! $this->loggedIn && $link['private'] != 0) {
298 // Transition for not upgraded databases.
299 unset($this->links[$key]);
300 continue;
301 }
302
303 // Sanitize data fields.
304 sanitizeLink($link);
305
306 // Remove private tags if the user is not logged in.
307 if (! $this->loggedIn) {
308 $link['tags'] = preg_replace('/(^|\s+)\.[^($|\s)]+\s*/', ' ', $link['tags']);
309 }
310
311 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
312 if (!empty($this->redirector) && !startsWith($link['url'], '?')) {
313 $link['real_url'] = $this->redirector;
314 if ($this->redirectorEncode) {
315 $link['real_url'] .= urlencode(unescape($link['url']));
316 } else {
317 $link['real_url'] .= $link['url'];
318 }
319 } else {
320 $link['real_url'] = $link['url'];
321 }
322
323 // To be able to load links before running the update, and prepare the update
324 if (! isset($link['created'])) {
325 $link['id'] = $link['linkdate'];
326 $link['created'] = DateTime::createFromFormat(self::LINK_DATE_FORMAT, $link['linkdate']);
327 if (! empty($link['updated'])) {
328 $link['updated'] = DateTime::createFromFormat(self::LINK_DATE_FORMAT, $link['updated']);
329 }
330 $link['shorturl'] = smallHash($link['linkdate']);
331 }
332
333 $this->urls[$link['url']] = $key;
334 $this->ids[$link['id']] = $key;
335 }
336 }
337
338 /**
339 * Saves the database from memory to disk
340 *
341 * @throws IOException the datastore is not writable
342 */
343 private function write()
344 {
345 $this->reorder();
346 FileUtils::writeFlatDB($this->datastore, $this->links);
347 }
348
349 /**
350 * Saves the database from memory to disk
351 *
352 * @param string $pageCacheDir page cache directory
353 */
354 public function save($pageCacheDir)
355 {
356 if (!$this->loggedIn) {
357 // TODO: raise an Exception instead
358 die('You are not authorized to change the database.');
359 }
360
361 $this->write();
362
363 invalidateCaches($pageCacheDir);
364 }
365
366 /**
367 * Returns the link for a given URL, or False if it does not exist.
368 *
369 * @param string $url URL to search for
370 *
371 * @return mixed the existing link if it exists, else 'false'
372 */
373 public function getLinkFromUrl($url)
374 {
375 if (isset($this->urls[$url])) {
376 return $this->links[$this->urls[$url]];
377 }
378 return false;
379 }
380
381 /**
382 * Returns the shaare corresponding to a smallHash.
383 *
384 * @param string $request QUERY_STRING server parameter.
385 *
386 * @return array $filtered array containing permalink data.
387 *
388 * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link.
389 */
390 public function filterHash($request)
391 {
392 $request = substr($request, 0, 6);
393 $linkFilter = new LinkFilter($this->links);
394 return $linkFilter->filter(LinkFilter::$FILTER_HASH, $request);
395 }
396
397 /**
398 * Returns the list of articles for a given day.
399 *
400 * @param string $request day to filter. Format: YYYYMMDD.
401 *
402 * @return array list of shaare found.
403 */
404 public function filterDay($request)
405 {
406 $linkFilter = new LinkFilter($this->links);
407 return $linkFilter->filter(LinkFilter::$FILTER_DAY, $request);
408 }
409
410 /**
411 * Filter links according to search parameters.
412 *
413 * @param array $filterRequest Search request content. Supported keys:
414 * - searchtags: list of tags
415 * - searchterm: term search
416 * @param bool $casesensitive Optional: Perform case sensitive filter
417 * @param string $visibility return only all/private/public links
418 * @param string $untaggedonly return only untagged links
419 *
420 * @return array filtered links, all links if no suitable filter was provided.
421 */
422 public function filterSearch($filterRequest = array(), $casesensitive = false, $visibility = 'all', $untaggedonly = false)
423 {
424 // Filter link database according to parameters.
425 $searchtags = isset($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
426 $searchterm = isset($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
427
428 // Search tags + fullsearch - blank string parameter will return all links.
429 $type = LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT; // == "vuotext"
430 $request = [$searchtags, $searchterm];
431
432 $linkFilter = new LinkFilter($this);
433 return $linkFilter->filter($type, $request, $casesensitive, $visibility, $untaggedonly);
434 }
435
436 /**
437 * Returns the list tags appearing in the links with the given tags
438 *
439 * @param array $filteringTags tags selecting the links to consider
440 * @param string $visibility process only all/private/public links
441 *
442 * @return array tag => linksCount
443 */
444 public function linksCountPerTag($filteringTags = [], $visibility = 'all')
445 {
446 $links = $this->filterSearch(['searchtags' => $filteringTags], false, $visibility);
447 $tags = [];
448 $caseMapping = [];
449 foreach ($links as $link) {
450 foreach (preg_split('/\s+/', $link['tags'], 0, PREG_SPLIT_NO_EMPTY) as $tag) {
451 if (empty($tag)) {
452 continue;
453 }
454 // The first case found will be displayed.
455 if (!isset($caseMapping[strtolower($tag)])) {
456 $caseMapping[strtolower($tag)] = $tag;
457 $tags[$caseMapping[strtolower($tag)]] = 0;
458 }
459 $tags[$caseMapping[strtolower($tag)]]++;
460 }
461 }
462
463 /*
464 * Formerly used arsort(), which doesn't define the sort behaviour for equal values.
465 * Also, this function doesn't produce the same result between PHP 5.6 and 7.
466 *
467 * So we now use array_multisort() to sort tags by DESC occurrences,
468 * then ASC alphabetically for equal values.
469 *
470 * @see https://github.com/shaarli/Shaarli/issues/1142
471 */
472 $keys = array_keys($tags);
473 $tmpTags = array_combine($keys, $keys);
474 array_multisort($tags, SORT_DESC, $tmpTags, SORT_ASC, $tags);
475 return $tags;
476 }
477
478 /**
479 * Rename or delete a tag across all links.
480 *
481 * @param string $from Tag to rename
482 * @param string $to New tag. If none is provided, the from tag will be deleted
483 *
484 * @return array|bool List of altered links or false on error
485 */
486 public function renameTag($from, $to)
487 {
488 if (empty($from)) {
489 return false;
490 }
491 $delete = empty($to);
492 // True for case-sensitive tag search.
493 $linksToAlter = $this->filterSearch(['searchtags' => $from], true);
494 foreach ($linksToAlter as $key => &$value) {
495 $tags = preg_split('/\s+/', trim($value['tags']));
496 if (($pos = array_search($from, $tags)) !== false) {
497 if ($delete) {
498 unset($tags[$pos]); // Remove tag.
499 } else {
500 $tags[$pos] = trim($to);
501 }
502 $value['tags'] = trim(implode(' ', array_unique($tags)));
503 $this[$value['id']] = $value;
504 }
505 }
506
507 return $linksToAlter;
508 }
509
510 /**
511 * Returns the list of days containing articles (oldest first)
512 * Output: An array containing days (in format YYYYMMDD).
513 */
514 public function days()
515 {
516 $linkDays = array();
517 foreach ($this->links as $link) {
518 $linkDays[$link['created']->format('Ymd')] = 0;
519 }
520 $linkDays = array_keys($linkDays);
521 sort($linkDays);
522
523 return $linkDays;
524 }
525
526 /**
527 * Reorder links by creation date (newest first).
528 *
529 * Also update the urls and ids mapping arrays.
530 *
531 * @param string $order ASC|DESC
532 */
533 public function reorder($order = 'DESC')
534 {
535 $order = $order === 'ASC' ? -1 : 1;
536 // Reorder array by dates.
537 usort($this->links, function ($a, $b) use ($order) {
538 if (isset($a['sticky']) && isset($b['sticky']) && $a['sticky'] !== $b['sticky']) {
539 return $a['sticky'] ? -1 : 1;
540 }
541 return $a['created'] < $b['created'] ? 1 * $order : -1 * $order;
542 });
543
544 $this->urls = [];
545 $this->ids = [];
546 foreach ($this->links as $key => $link) {
547 $this->urls[$link['url']] = $key;
548 $this->ids[$link['id']] = $key;
549 }
550 }
551
552 /**
553 * Return the next key for link creation.
554 * E.g. If the last ID is 597, the next will be 598.
555 *
556 * @return int next ID.
557 */
558 public function getNextId()
559 {
560 if (!empty($this->ids)) {
561 return max(array_keys($this->ids)) + 1;
562 }
563 return 0;
564 }
565
566 /**
567 * Returns a link offset in links array from its unique ID.
568 *
569 * @param int $id Persistent ID of a link.
570 *
571 * @return int Real offset in local array, or null if doesn't exist.
572 */
573 protected function getLinkOffset($id)
574 {
575 if (isset($this->ids[$id])) {
576 return $this->ids[$id];
577 }
578 return null;
579 }
580 }