]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/bookmark/BookmarkFilter.php
Merge pull request #1570 from ArthurHoaro/feature/datastore-mutex
[github/shaarli/Shaarli.git] / application / bookmark / BookmarkFilter.php
CommitLineData
822bffce
A
1<?php
2
6696729b
V
3namespace Shaarli\Bookmark;
4
5use Exception;
336a28fa 6use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
f24896b2 7
822bffce
A
8/**
9 * Class LinkFilter.
10 *
11 * Perform search and filter operation on link data list.
12 */
336a28fa 13class BookmarkFilter
822bffce
A
14{
15 /**
16 * @var string permalinks.
17 */
6696729b 18 public static $FILTER_HASH = 'permalink';
822bffce
A
19
20 /**
21 * @var string text search.
22 */
6696729b 23 public static $FILTER_TEXT = 'fulltext';
822bffce
A
24
25 /**
26 * @var string tag filter.
27 */
6696729b 28 public static $FILTER_TAG = 'tags';
822bffce
A
29
30 /**
31 * @var string filter by day.
32 */
6696729b 33 public static $FILTER_DAY = 'FILTER_DAY';
822bffce 34
336a28fa
A
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
9ccca401
A
49 /**
50 * @var string Allowed characters for hashtags (regex syntax).
51 */
52 public static $HASHTAG_CHARS = '\p{Pc}\p{N}\p{L}\p{Mn}';
53
822bffce 54 /**
336a28fa 55 * @var Bookmark[] all available bookmarks.
822bffce 56 */
336a28fa 57 private $bookmarks;
822bffce
A
58
59 /**
336a28fa 60 * @param Bookmark[] $bookmarks initialization.
822bffce 61 */
336a28fa 62 public function __construct($bookmarks)
822bffce 63 {
336a28fa 64 $this->bookmarks = $bookmarks;
822bffce
A
65 }
66
67 /**
336a28fa 68 * Filter bookmarks according to parameters.
822bffce
A
69 *
70 * @param string $type Type of filter (eg. tags, permalink, etc.).
528a6f8a 71 * @param mixed $request Filter content.
822bffce 72 * @param bool $casesensitive Optional: Perform case sensitive filter if true.
336a28fa
A
73 * @param string $visibility Optional: return only all/private/public bookmarks
74 * @param bool $untaggedonly Optional: return only untagged bookmarks. Applies only if $type includes FILTER_TAG
75 *
76 * @return Bookmark[] filtered bookmark list.
822bffce 77 *
336a28fa 78 * @throws BookmarkNotFoundException
822bffce 79 */
f210d94f 80 public function filter($type, $request, $casesensitive = false, $visibility = 'all', $untaggedonly = false)
822bffce 81 {
6696729b 82 if (!in_array($visibility, ['all', 'public', 'private'])) {
7f96d9ec
A
83 $visibility = 'all';
84 }
85
f211e417 86 switch ($type) {
822bffce
A
87 case self::$FILTER_HASH:
88 return $this->filterSmallHash($request);
f210d94f
LC
89 case self::$FILTER_TAG | self::$FILTER_TEXT: // == "vuotext"
90 $noRequest = empty($request) || (empty($request[0]) && empty($request[1]));
91 if ($noRequest) {
92 if ($untaggedonly) {
93 return $this->filterUntagged($visibility);
c51fae92 94 }
f210d94f 95 return $this->noFilter($visibility);
c51fae92 96 }
f210d94f
LC
97 if ($untaggedonly) {
98 $filtered = $this->filterUntagged($visibility);
99 } else {
336a28fa 100 $filtered = $this->bookmarks;
f210d94f
LC
101 }
102 if (!empty($request[0])) {
336a28fa 103 $filtered = (new BookmarkFilter($filtered))->filterTags($request[0], $casesensitive, $visibility);
f210d94f
LC
104 }
105 if (!empty($request[1])) {
336a28fa 106 $filtered = (new BookmarkFilter($filtered))->filterFulltext($request[1], $visibility);
f210d94f
LC
107 }
108 return $filtered;
822bffce 109 case self::$FILTER_TEXT:
7f96d9ec 110 return $this->filterFulltext($request, $visibility);
822bffce 111 case self::$FILTER_TAG:
f210d94f
LC
112 if ($untaggedonly) {
113 return $this->filterUntagged($visibility);
114 } else {
115 return $this->filterTags($request, $casesensitive, $visibility);
116 }
822bffce 117 case self::$FILTER_DAY:
27ddfec3 118 return $this->filterDay($request, $visibility);
822bffce 119 default:
7f96d9ec 120 return $this->noFilter($visibility);
822bffce
A
121 }
122 }
123
124 /**
125 * Unknown filter, but handle private only.
126 *
336a28fa 127 * @param string $visibility Optional: return only all/private/public bookmarks
822bffce 128 *
336a28fa 129 * @return Bookmark[] filtered bookmarks.
822bffce 130 */
7f96d9ec 131 private function noFilter($visibility = 'all')
822bffce 132 {
7f96d9ec 133 if ($visibility === 'all') {
336a28fa 134 return $this->bookmarks;
822bffce
A
135 }
136
137 $out = array();
336a28fa
A
138 foreach ($this->bookmarks as $key => $value) {
139 if ($value->isPrivate() && $visibility === 'private') {
7f96d9ec 140 $out[$key] = $value;
336a28fa 141 } elseif (!$value->isPrivate() && $visibility === 'public') {
01878a75 142 $out[$key] = $value;
822bffce
A
143 }
144 }
145
822bffce
A
146 return $out;
147 }
148
149 /**
150 * Returns the shaare corresponding to a smallHash.
151 *
152 * @param string $smallHash permalink hash.
153 *
154 * @return array $filtered array containing permalink data.
528a6f8a 155 *
336a28fa 156 * @throws \Shaarli\Bookmark\Exception\BookmarkNotFoundException if the smallhash doesn't match any link.
822bffce
A
157 */
158 private function filterSmallHash($smallHash)
159 {
336a28fa
A
160 foreach ($this->bookmarks as $key => $l) {
161 if ($smallHash == $l->getShortUrl()) {
822bffce 162 // Yes, this is ugly and slow
336a28fa 163 return [$key => $l];
822bffce
A
164 }
165 }
528a6f8a 166
336a28fa 167 throw new BookmarkNotFoundException();
822bffce
A
168 }
169
170 /**
336a28fa 171 * Returns the list of bookmarks corresponding to a full-text search
822bffce
A
172 *
173 * Searches:
174 * - in the URLs, title and description;
bedd176a
A
175 * - are case-insensitive;
176 * - terms surrounded by quotes " are exact terms search.
177 * - terms starting with a dash - are excluded (except exact terms).
822bffce
A
178 *
179 * Example:
180 * print_r($mydb->filterFulltext('hollandais'));
181 *
182 * mb_convert_case($val, MB_CASE_LOWER, 'UTF-8')
183 * - allows to perform searches on Unicode text
184 * - see https://github.com/shaarli/Shaarli/issues/75 for examples
185 *
186 * @param string $searchterms search query.
336a28fa 187 * @param string $visibility Optional: return only all/private/public bookmarks.
822bffce
A
188 *
189 * @return array search results.
190 */
7f96d9ec 191 private function filterFulltext($searchterms, $visibility = 'all')
822bffce 192 {
c51fae92 193 if (empty($searchterms)) {
7f96d9ec 194 return $this->noFilter($visibility);
c51fae92
A
195 }
196
522b278b 197 $filtered = array();
ebd8075a 198 $search = mb_convert_case(html_entity_decode($searchterms), MB_CASE_LOWER, 'UTF-8');
bedd176a
A
199 $exactRegex = '/"([^"]+)"/';
200 // Retrieve exact search terms.
201 preg_match_all($exactRegex, $search, $exactSearch);
202 $exactSearch = array_values(array_filter($exactSearch[1]));
203
204 // Remove exact search terms to get AND terms search.
205 $explodedSearchAnd = explode(' ', trim(preg_replace($exactRegex, '', $search)));
206 $explodedSearchAnd = array_values(array_filter($explodedSearchAnd));
207
208 // Filter excluding terms and update andSearch.
209 $excludeSearch = array();
210 $andSearch = array();
211 foreach ($explodedSearchAnd as $needle) {
212 if ($needle[0] == '-' && strlen($needle) > 1) {
213 $excludeSearch[] = substr($needle, 1);
214 } else {
215 $andSearch[] = $needle;
216 }
217 }
218
822bffce 219 // Iterate over every stored link.
336a28fa
A
220 foreach ($this->bookmarks as $id => $link) {
221 // ignore non private bookmarks when 'privatonly' is on.
7f96d9ec 222 if ($visibility !== 'all') {
336a28fa 223 if (!$link->isPrivate() && $visibility === 'private') {
7f96d9ec 224 continue;
336a28fa 225 } elseif ($link->isPrivate() && $visibility === 'public') {
7f96d9ec
A
226 continue;
227 }
822bffce
A
228 }
229
522b278b
A
230 // Concatenate link fields to search across fields.
231 // Adds a '\' separator for exact search terms.
336a28fa
A
232 $content = mb_convert_case($link->getTitle(), MB_CASE_LOWER, 'UTF-8') .'\\';
233 $content .= mb_convert_case($link->getDescription(), MB_CASE_LOWER, 'UTF-8') .'\\';
234 $content .= mb_convert_case($link->getUrl(), MB_CASE_LOWER, 'UTF-8') .'\\';
235 $content .= mb_convert_case($link->getTagsString(), MB_CASE_LOWER, 'UTF-8') .'\\';
522b278b
A
236
237 // Be optimistic
238 $found = true;
239
240 // First, we look for exact term search
241 for ($i = 0; $i < count($exactSearch) && $found; $i++) {
242 $found = strpos($content, $exactSearch[$i]) !== false;
243 }
244
245 // Iterate over keywords, if keyword is not found,
246 // no need to check for the others. We want all or nothing.
247 for ($i = 0; $i < count($andSearch) && $found; $i++) {
248 $found = strpos($content, $andSearch[$i]) !== false;
249 }
250
251 // Exclude terms.
252 for ($i = 0; $i < count($excludeSearch) && $found; $i++) {
253 $found = strpos($content, $excludeSearch[$i]) === false;
254 }
255
822bffce 256 if ($found) {
01878a75 257 $filtered[$id] = $link;
822bffce
A
258 }
259 }
260
822bffce
A
261 return $filtered;
262 }
263
341527ba
WE
264 /**
265 * generate a regex fragment out of a tag
6696729b 266 *
341527ba 267 * @param string $tag to to generate regexs from. may start with '-' to negate, contain '*' as wildcard
6696729b 268 *
341527ba
WE
269 * @return string generated regex fragment
270 */
271 private static function tag2regex($tag)
272 {
273 $len = strlen($tag);
f211e417 274 if (!$len || $tag === "-" || $tag === "*") {
341527ba
WE
275 // nothing to search, return empty regex
276 return '';
277 }
f211e417 278 if ($tag[0] === "-") {
341527ba
WE
279 // query is negated
280 $i = 1; // use offset to start after '-' character
281 $regex = '(?!'; // create negative lookahead
282 } else {
283 $i = 0; // start at first character
284 $regex = '(?='; // use positive lookahead
285 }
286 $regex .= '.*(?:^| )'; // before tag may only be a space or the beginning
287 // iterate over string, separating it into placeholder and content
f211e417
V
288 for (; $i < $len; $i++) {
289 if ($tag[$i] === '*') {
341527ba
WE
290 // placeholder found
291 $regex .= '[^ ]*?';
292 } else {
293 // regular characters
294 $offset = strpos($tag, '*', $i);
f211e417 295 if ($offset === false) {
341527ba
WE
296 // no placeholder found, set offset to end of string
297 $offset = $len;
298 }
299 // subtract one, as we want to get before the placeholder or end of string
300 $offset -= 1;
301 // we got a tag name that we want to search for. escape any regex characters to prevent conflicts.
302 $regex .= preg_quote(substr($tag, $i, $offset - $i + 1), '/');
303 // move $i on
304 $i = $offset;
305 }
306 }
307 $regex .= '(?:$| ))'; // after the tag may only be a space or the end
308 return $regex;
309 }
310
822bffce 311 /**
336a28fa 312 * Returns the list of bookmarks associated with a given list of tags
822bffce
A
313 *
314 * You can specify one or more tags, separated by space or a comma, e.g.
315 * print_r($mydb->filterTags('linux programming'));
316 *
317 * @param string $tags list of tags separated by commas or blank spaces.
318 * @param bool $casesensitive ignore case if false.
336a28fa 319 * @param string $visibility Optional: return only all/private/public bookmarks.
822bffce 320 *
336a28fa 321 * @return array filtered bookmarks.
822bffce 322 */
7f96d9ec 323 public function filterTags($tags, $casesensitive = false, $visibility = 'all')
822bffce 324 {
341527ba
WE
325 // get single tags (we may get passed an array, even though the docs say different)
326 $inputTags = $tags;
f211e417 327 if (!is_array($tags)) {
341527ba
WE
328 // we got an input string, split tags
329 $inputTags = preg_split('/(?:\s+)|,/', $inputTags, -1, PREG_SPLIT_NO_EMPTY);
330 }
331
f211e417 332 if (!count($inputTags)) {
341527ba 333 // no input tags
7f96d9ec 334 return $this->noFilter($visibility);
c51fae92
A
335 }
336
336a28fa
A
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
341527ba
WE
348 // build regex from all tags
349 $re = '/^' . implode(array_map("self::tag2regex", $inputTags)) . '.*$/';
f211e417 350 if (!$casesensitive) {
341527ba
WE
351 // make regex case insensitive
352 $re .= 'i';
21979ff1 353 }
822bffce 354
341527ba 355 // create resulting array
336a28fa 356 $filtered = [];
341527ba
WE
357
358 // iterate over each link
336a28fa 359 foreach ($this->bookmarks as $key => $link) {
341527ba 360 // check level of visibility
336a28fa 361 // ignore non private bookmarks when 'privateonly' is on.
7f96d9ec 362 if ($visibility !== 'all') {
336a28fa 363 if (!$link->isPrivate() && $visibility === 'private') {
7f96d9ec 364 continue;
336a28fa 365 } elseif ($link->isPrivate() && $visibility === 'public') {
7f96d9ec
A
366 continue;
367 }
822bffce 368 }
336a28fa
A
369 $search = $link->getTagsString(); // build search string, start with tags of current link
370 if (strlen(trim($link->getDescription())) && strpos($link->getDescription(), '#') !== false) {
341527ba
WE
371 // description given and at least one possible tag found
372 $descTags = array();
373 // find all tags in the form of #tag in the description
374 preg_match_all(
375 '/(?<![' . self::$HASHTAG_CHARS . '])#([' . self::$HASHTAG_CHARS . ']+?)\b/sm',
336a28fa 376 $link->getDescription(),
341527ba
WE
377 $descTags
378 );
f211e417 379 if (count($descTags[1])) {
341527ba
WE
380 // there were some tags in the description, add them to the search string
381 $search .= ' ' . implode(' ', $descTags[1]);
21979ff1 382 }
341527ba
WE
383 };
384 // match regular expression with search string
f211e417 385 if (!preg_match($re, $search)) {
341527ba
WE
386 // this entry does _not_ match our regex
387 continue;
21979ff1 388 }
341527ba 389 $filtered[$key] = $link;
822bffce 390 }
822bffce
A
391 return $filtered;
392 }
393
7d86f40b 394 /**
336a28fa 395 * Return only bookmarks without any tag.
7d86f40b 396 *
336a28fa 397 * @param string $visibility return only all/private/public bookmarks.
7d86f40b 398 *
336a28fa 399 * @return array filtered bookmarks.
7d86f40b
A
400 */
401 public function filterUntagged($visibility)
402 {
403 $filtered = [];
336a28fa 404 foreach ($this->bookmarks as $key => $link) {
7d86f40b 405 if ($visibility !== 'all') {
336a28fa 406 if (!$link->isPrivate() && $visibility === 'private') {
7d86f40b 407 continue;
336a28fa 408 } elseif ($link->isPrivate() && $visibility === 'public') {
7d86f40b
A
409 continue;
410 }
411 }
412
336a28fa 413 if (empty(trim($link->getTagsString()))) {
7d86f40b
A
414 $filtered[$key] = $link;
415 }
416 }
417
418 return $filtered;
419 }
420
822bffce
A
421 /**
422 * Returns the list of articles for a given day, chronologically sorted
423 *
424 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
425 * print_r($mydb->filterDay('20120125'));
426 *
427 * @param string $day day to filter.
27ddfec3
A
428 * @param string $visibility return only all/private/public bookmarks.
429
822bffce
A
430 * @return array all link matching given day.
431 *
432 * @throws Exception if date format is invalid.
433 */
27ddfec3 434 public function filterDay($day, $visibility)
822bffce 435 {
6696729b 436 if (!checkDateFormat('Ymd', $day)) {
822bffce
A
437 throw new Exception('Invalid date format');
438 }
439
69e29ff6 440 $filtered = [];
27ddfec3
A
441 foreach ($this->bookmarks as $key => $bookmark) {
442 if ($visibility === static::$PUBLIC && $bookmark->isPrivate()) {
443 continue;
444 }
445
446 if ($bookmark->getCreated()->format('Ymd') == $day) {
447 $filtered[$key] = $bookmark;
822bffce
A
448 }
449 }
01878a75
A
450
451 // sort by date ASC
452 return array_reverse($filtered, true);
822bffce
A
453 }
454
455 /**
456 * Convert a list of tags (str) to an array. Also
457 * - handle case sensitivity.
458 * - accepts spaces commas as separator.
822bffce
A
459 *
460 * @param string $tags string containing a list of tags.
461 * @param bool $casesensitive will convert everything to lowercase if false.
462 *
463 * @return array filtered tags string.
7f96d9ec 464 */
21979ff1 465 public static function tagsStrToArray($tags, $casesensitive)
822bffce
A
466 {
467 // We use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
468 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8');
469 $tagsOut = str_replace(',', ' ', $tagsOut);
470
b3051a6a 471 return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY);
822bffce
A
472 }
473}