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