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