]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkDB.php
Merge pull request #532 from ArthurHoaro/hotfix/title-retrieve-the-return
[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['20110826_161819']['title'];
10 * foreach ($myLinks as $link)
11 * echo $link['title'].' at url '.$link['url'].'; description:'.$link['description'];
12 *
13 * Available keys:
14 * - description: description of the entry
15 * - linkdate: date of the creation of this entry, in the form YYYYMMDD_HHMMSS
16 * (e.g.'20110914_192317')
17 * - private: Is this link private? 0=no, other value=yes
18 * - tags: tags attached to this entry (separated by spaces)
19 * - title Title of the link
20 * - url URL of the link. Used for displayable links (no redirector, relative, etc.).
21 * Can be absolute or relative.
22 * Relative URLs are permalinks (e.g.'?m-ukcw')
23 * - real_url Absolute processed URL.
24 *
25 * Implements 3 interfaces:
26 * - ArrayAccess: behaves like an associative array;
27 * - Countable: there is a count() method;
28 * - Iterator: usable in foreach () loops.
29 */
30 class LinkDB implements Iterator, Countable, ArrayAccess
31 {
32 // Links are stored as a PHP serialized string
33 private $_datastore;
34
35 // Link date storage format
36 const LINK_DATE_FORMAT = 'Ymd_His';
37
38 // Datastore PHP prefix
39 protected static $phpPrefix = '<?php /* ';
40
41 // Datastore PHP suffix
42 protected static $phpSuffix = ' */ ?>';
43
44 // List of links (associative array)
45 // - key: link date (e.g. "20110823_124546"),
46 // - value: associative array (keys: title, description...)
47 private $_links;
48
49 // List of all recorded URLs (key=url, value=linkdate)
50 // for fast reserve search (url-->linkdate)
51 private $_urls;
52
53 // List of linkdate keys (for the Iterator interface implementation)
54 private $_keys;
55
56 // Position in the $this->_keys array (for the Iterator interface)
57 private $_position;
58
59 // Is the user logged in? (used to filter private links)
60 private $_loggedIn;
61
62 // Hide public links
63 private $_hidePublicLinks;
64
65 // link redirector set in user settings.
66 private $_redirector;
67
68 /**
69 * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched.
70 *
71 * Example:
72 * anonym.to needs clean URL while dereferer.org needs urlencoded URL.
73 *
74 * @var boolean $redirectorEncode parameter: true or false
75 */
76 private $redirectorEncode;
77
78 /**
79 * Creates a new LinkDB
80 *
81 * Checks if the datastore exists; else, attempts to create a dummy one.
82 *
83 * @param string $datastore datastore file path.
84 * @param boolean $isLoggedIn is the user logged in?
85 * @param boolean $hidePublicLinks if true all links are private.
86 * @param string $redirector link redirector set in user settings.
87 * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true).
88 */
89 function __construct(
90 $datastore,
91 $isLoggedIn,
92 $hidePublicLinks,
93 $redirector = '',
94 $redirectorEncode = true
95 )
96 {
97 $this->_datastore = $datastore;
98 $this->_loggedIn = $isLoggedIn;
99 $this->_hidePublicLinks = $hidePublicLinks;
100 $this->_redirector = $redirector;
101 $this->redirectorEncode = $redirectorEncode === true;
102 $this->_checkDB();
103 $this->_readDB();
104 }
105
106 /**
107 * Countable - Counts elements of an object
108 */
109 public function count()
110 {
111 return count($this->_links);
112 }
113
114 /**
115 * ArrayAccess - Assigns a value to the specified offset
116 */
117 public function offsetSet($offset, $value)
118 {
119 // TODO: use exceptions instead of "die"
120 if (!$this->_loggedIn) {
121 die('You are not authorized to add a link.');
122 }
123 if (empty($value['linkdate']) || empty($value['url'])) {
124 die('Internal Error: A link should always have a linkdate and URL.');
125 }
126 if (empty($offset)) {
127 die('You must specify a key.');
128 }
129 $this->_links[$offset] = $value;
130 $this->_urls[$value['url']]=$offset;
131 }
132
133 /**
134 * ArrayAccess - Whether or not an offset exists
135 */
136 public function offsetExists($offset)
137 {
138 return array_key_exists($offset, $this->_links);
139 }
140
141 /**
142 * ArrayAccess - Unsets an offset
143 */
144 public function offsetUnset($offset)
145 {
146 if (!$this->_loggedIn) {
147 // TODO: raise an exception
148 die('You are not authorized to delete a link.');
149 }
150 $url = $this->_links[$offset]['url'];
151 unset($this->_urls[$url]);
152 unset($this->_links[$offset]);
153 }
154
155 /**
156 * ArrayAccess - Returns the value at specified offset
157 */
158 public function offsetGet($offset)
159 {
160 return isset($this->_links[$offset]) ? $this->_links[$offset] : null;
161 }
162
163 /**
164 * Iterator - Returns the current element
165 */
166 function current()
167 {
168 return $this->_links[$this->_keys[$this->_position]];
169 }
170
171 /**
172 * Iterator - Returns the key of the current element
173 */
174 function key()
175 {
176 return $this->_keys[$this->_position];
177 }
178
179 /**
180 * Iterator - Moves forward to next element
181 */
182 function next()
183 {
184 ++$this->_position;
185 }
186
187 /**
188 * Iterator - Rewinds the Iterator to the first element
189 *
190 * Entries are sorted by date (latest first)
191 */
192 function rewind()
193 {
194 $this->_keys = array_keys($this->_links);
195 rsort($this->_keys);
196 $this->_position = 0;
197 }
198
199 /**
200 * Iterator - Checks if current position is valid
201 */
202 function valid()
203 {
204 return isset($this->_keys[$this->_position]);
205 }
206
207 /**
208 * Checks if the DB directory and file exist
209 *
210 * If no DB file is found, creates a dummy DB.
211 */
212 private function _checkDB()
213 {
214 if (file_exists($this->_datastore)) {
215 return;
216 }
217
218 // Create a dummy database for example
219 $this->_links = array();
220 $link = array(
221 'title'=>' Shaarli: the personal, minimalist, super-fast, no-database delicious clone',
222 'url'=>'https://github.com/shaarli/Shaarli/wiki',
223 'description'=>'Welcome to Shaarli! This is your first public bookmark. To edit or delete me, you must first login.
224
225 To learn how to use Shaarli, consult the link "Help/documentation" at the bottom of this page.
226
227 You use the community supported version of the original Shaarli project, by Sebastien Sauvage.',
228 'private'=>0,
229 'linkdate'=> date('Ymd_His'),
230 'tags'=>'opensource software'
231 );
232 $this->_links[$link['linkdate']] = $link;
233
234 $link = array(
235 'title'=>'My secret stuff... - Pastebin.com',
236 'url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
237 'description'=>'Shhhh! I\'m a private link only YOU can see. You can delete me too.',
238 'private'=>1,
239 'linkdate'=> date('Ymd_His', strtotime('-1 minute')),
240 'tags'=>'secretstuff'
241 );
242 $this->_links[$link['linkdate']] = $link;
243
244 // Write database to disk
245 $this->writeDB();
246 }
247
248 /**
249 * Reads database from disk to memory
250 */
251 private function _readDB()
252 {
253
254 // Public links are hidden and user not logged in => nothing to show
255 if ($this->_hidePublicLinks && !$this->_loggedIn) {
256 $this->_links = array();
257 return;
258 }
259
260 // Read data
261 // Note that gzinflate is faster than gzuncompress.
262 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
263 $this->_links = array();
264
265 if (file_exists($this->_datastore)) {
266 $this->_links = unserialize(gzinflate(base64_decode(
267 substr(file_get_contents($this->_datastore),
268 strlen(self::$phpPrefix), -strlen(self::$phpSuffix)))));
269 }
270
271 // If user is not logged in, filter private links.
272 if (!$this->_loggedIn) {
273 $toremove = array();
274 foreach ($this->_links as $link) {
275 if ($link['private'] != 0) {
276 $toremove[] = $link['linkdate'];
277 }
278 }
279 foreach ($toremove as $linkdate) {
280 unset($this->_links[$linkdate]);
281 }
282 }
283
284 $this->_urls = array();
285 foreach ($this->_links as &$link) {
286 // Keep the list of the mapping URLs-->linkdate up-to-date.
287 $this->_urls[$link['url']] = $link['linkdate'];
288
289 // Sanitize data fields.
290 sanitizeLink($link);
291
292 // Remove private tags if the user is not logged in.
293 if (! $this->_loggedIn) {
294 $link['tags'] = preg_replace('/(^| )\.[^($| )]+/', '', $link['tags']);
295 }
296
297 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
298 if (!empty($this->_redirector) && !startsWith($link['url'], '?')) {
299 $link['real_url'] = $this->_redirector;
300 if ($this->redirectorEncode) {
301 $link['real_url'] .= urlencode(unescape($link['url']));
302 } else {
303 $link['real_url'] .= $link['url'];
304 }
305 }
306 else {
307 $link['real_url'] = $link['url'];
308 }
309 }
310 }
311
312 /**
313 * Saves the database from memory to disk
314 *
315 * @throws IOException the datastore is not writable
316 */
317 private function writeDB()
318 {
319 if (is_file($this->_datastore) && !is_writeable($this->_datastore)) {
320 // The datastore exists but is not writeable
321 throw new IOException($this->_datastore);
322 } else if (!is_file($this->_datastore) && !is_writeable(dirname($this->_datastore))) {
323 // The datastore does not exist and its parent directory is not writeable
324 throw new IOException(dirname($this->_datastore));
325 }
326
327 file_put_contents(
328 $this->_datastore,
329 self::$phpPrefix.base64_encode(gzdeflate(serialize($this->_links))).self::$phpSuffix
330 );
331
332 }
333
334 /**
335 * Saves the database from memory to disk
336 *
337 * @param string $pageCacheDir page cache directory
338 */
339 public function savedb($pageCacheDir)
340 {
341 if (!$this->_loggedIn) {
342 // TODO: raise an Exception instead
343 die('You are not authorized to change the database.');
344 }
345
346 $this->writeDB();
347
348 invalidateCaches($pageCacheDir);
349 }
350
351 /**
352 * Returns the link for a given URL, or False if it does not exist.
353 *
354 * @param string $url URL to search for
355 *
356 * @return mixed the existing link if it exists, else 'false'
357 */
358 public function getLinkFromUrl($url)
359 {
360 if (isset($this->_urls[$url])) {
361 return $this->_links[$this->_urls[$url]];
362 }
363 return false;
364 }
365
366 /**
367 * Returns the shaare corresponding to a smallHash.
368 *
369 * @param string $request QUERY_STRING server parameter.
370 *
371 * @return array $filtered array containing permalink data.
372 *
373 * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link.
374 */
375 public function filterHash($request)
376 {
377 $request = substr($request, 0, 6);
378 $linkFilter = new LinkFilter($this->_links);
379 return $linkFilter->filter(LinkFilter::$FILTER_HASH, $request);
380 }
381
382 /**
383 * Returns the list of articles for a given day.
384 *
385 * @param string $request day to filter. Format: YYYYMMDD.
386 *
387 * @return array list of shaare found.
388 */
389 public function filterDay($request) {
390 $linkFilter = new LinkFilter($this->_links);
391 return $linkFilter->filter(LinkFilter::$FILTER_DAY, $request);
392 }
393
394 /**
395 * Filter links according to search parameters.
396 *
397 * @param array $filterRequest Search request content. Supported keys:
398 * - searchtags: list of tags
399 * - searchterm: term search
400 * @param bool $casesensitive Optional: Perform case sensitive filter
401 * @param bool $privateonly Optional: Returns private links only if true.
402 *
403 * @return array filtered links, all links if no suitable filter was provided.
404 */
405 public function filterSearch($filterRequest = array(), $casesensitive = false, $privateonly = false)
406 {
407 // Filter link database according to parameters.
408 $searchtags = !empty($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
409 $searchterm = !empty($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
410
411 // Search tags + fullsearch.
412 if (empty($type) && ! empty($searchtags) && ! empty($searchterm)) {
413 $type = LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT;
414 $request = array($searchtags, $searchterm);
415 }
416 // Search by tags.
417 elseif (! empty($searchtags)) {
418 $type = LinkFilter::$FILTER_TAG;
419 $request = $searchtags;
420 }
421 // Fulltext search.
422 elseif (! empty($searchterm)) {
423 $type = LinkFilter::$FILTER_TEXT;
424 $request = $searchterm;
425 }
426 // Otherwise, display without filtering.
427 else {
428 $type = '';
429 $request = '';
430 }
431
432 $linkFilter = new LinkFilter($this->_links);
433 return $linkFilter->filter($type, $request, $casesensitive, $privateonly);
434 }
435
436 /**
437 * Returns the list of all tags
438 * Output: associative array key=tags, value=0
439 */
440 public function allTags()
441 {
442 $tags = array();
443 foreach ($this->_links as $link) {
444 foreach (explode(' ', $link['tags']) as $tag) {
445 if (!empty($tag)) {
446 $tags[$tag] = (empty($tags[$tag]) ? 1 : $tags[$tag] + 1);
447 }
448 }
449 }
450 // Sort tags by usage (most used tag first)
451 arsort($tags);
452 return $tags;
453 }
454
455 /**
456 * Returns the list of days containing articles (oldest first)
457 * Output: An array containing days (in format YYYYMMDD).
458 */
459 public function days()
460 {
461 $linkDays = array();
462 foreach (array_keys($this->_links) as $day) {
463 $linkDays[substr($day, 0, 8)] = 0;
464 }
465 $linkDays = array_keys($linkDays);
466 sort($linkDays);
467
468 return $linkDays;
469 }
470 }