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