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