]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkFilter.php
3 use Shaarli\Bookmark\LinkDB
;
8 * Perform search and filter operation on link data list.
13 * @var string permalinks.
15 public static $FILTER_HASH = 'permalink';
18 * @var string text search.
20 public static $FILTER_TEXT = 'fulltext';
23 * @var string tag filter.
25 public static $FILTER_TAG = 'tags';
28 * @var string filter by day.
30 public static $FILTER_DAY = 'FILTER_DAY';
33 * @var string Allowed characters for hashtags (regex syntax).
35 public static $HASHTAG_CHARS = '\p{Pc}\p{N}\p{L}\p{Mn}';
38 * @var LinkDB all available links.
43 * @param LinkDB $links initialization.
45 public function __construct($links)
47 $this->links
= $links;
51 * Filter links according to parameters.
53 * @param string $type Type of filter (eg. tags, permalink, etc.).
54 * @param mixed $request Filter content.
55 * @param bool $casesensitive Optional: Perform case sensitive filter if true.
56 * @param string $visibility Optional: return only all/private/public links
57 * @param string $untaggedonly Optional: return only untagged links. Applies only if $type includes FILTER_TAG
59 * @return array filtered link list.
61 public function filter($type, $request, $casesensitive = false, $visibility = 'all', $untaggedonly = false)
63 if (! in_array($visibility, ['all', 'public', 'private'])) {
68 case self
::$FILTER_HASH:
69 return $this->filterSmallHash($request);
70 case self
::$FILTER_TAG | self
::$FILTER_TEXT: // == "vuotext"
71 $noRequest = empty($request) || (empty($request[0]) && empty($request[1]));
74 return $this->filterUntagged($visibility);
76 return $this->noFilter($visibility);
79 $filtered = $this->filterUntagged($visibility);
81 $filtered = $this->links
;
83 if (!empty($request[0])) {
84 $filtered = (new LinkFilter($filtered))->filterTags($request[0], $casesensitive, $visibility);
86 if (!empty($request[1])) {
87 $filtered = (new LinkFilter($filtered))->filterFulltext($request[1], $visibility);
90 case self
::$FILTER_TEXT:
91 return $this->filterFulltext($request, $visibility);
92 case self
::$FILTER_TAG:
94 return $this->filterUntagged($visibility);
96 return $this->filterTags($request, $casesensitive, $visibility);
98 case self
::$FILTER_DAY:
99 return $this->filterDay($request);
101 return $this->noFilter($visibility);
106 * Unknown filter, but handle private only.
108 * @param string $visibility Optional: return only all/private/public links
110 * @return array filtered links.
112 private function noFilter($visibility = 'all')
114 if ($visibility === 'all') {
119 foreach ($this->links
as $key => $value) {
120 if ($value['private'] && $visibility === 'private') {
122 } elseif (! $value['private'] && $visibility === 'public') {
131 * Returns the shaare corresponding to a smallHash.
133 * @param string $smallHash permalink hash.
135 * @return array $filtered array containing permalink data.
137 * @throws LinkNotFoundException if the smallhash doesn't match any link.
139 private function filterSmallHash($smallHash)
142 foreach ($this->links
as $key => $l) {
143 if ($smallHash == $l['shorturl']) {
144 // Yes, this is ugly and slow
145 $filtered[$key] = $l;
150 if (empty($filtered)) {
151 throw new LinkNotFoundException();
158 * Returns the list of links corresponding to a full-text search
161 * - in the URLs, title and description;
162 * - are case-insensitive;
163 * - terms surrounded by quotes " are exact terms search.
164 * - terms starting with a dash - are excluded (except exact terms).
167 * print_r($mydb->filterFulltext('hollandais'));
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
173 * @param string $searchterms search query.
174 * @param string $visibility Optional: return only all/private/public links.
176 * @return array search results.
178 private function filterFulltext($searchterms, $visibility = 'all')
180 if (empty($searchterms)) {
181 return $this->noFilter($visibility);
185 $search = mb_convert_case(html_entity_decode($searchterms), MB_CASE_LOWER
, 'UTF-8');
186 $exactRegex = '/"([^"]+)"/';
187 // Retrieve exact search terms.
188 preg_match_all($exactRegex, $search, $exactSearch);
189 $exactSearch = array_values(array_filter($exactSearch[1]));
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));
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);
202 $andSearch[] = $needle;
206 $keys = array('title', 'description', 'url', 'tags');
208 // Iterate over every stored link.
209 foreach ($this->links
as $id => $link) {
210 // ignore non private links when 'privatonly' is on.
211 if ($visibility !== 'all') {
212 if (! $link['private'] && $visibility === 'private') {
214 } elseif ($link['private'] && $visibility === 'public') {
219 // Concatenate link fields to search across fields.
220 // Adds a '\' separator for exact search terms.
222 foreach ($keys as $key) {
223 $content .= mb_convert_case($link[$key], MB_CASE_LOWER
, 'UTF-8') . '\\';
229 // First, we look for exact term search
230 for ($i = 0; $i < count($exactSearch) && $found; $i++
) {
231 $found = strpos($content, $exactSearch[$i]) !== false;
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;
241 for ($i = 0; $i < count($excludeSearch) && $found; $i++
) {
242 $found = strpos($content, $excludeSearch[$i]) === false;
246 $filtered[$id] = $link;
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
258 private static function tag2regex($tag)
261 if (!$len || $tag === "-" || $tag === "*") {
262 // nothing to search, return empty regex
265 if ($tag[0] === "-") {
267 $i = 1; // use offset to start after '-' character
268 $regex = '(?!'; // create negative lookahead
270 $i = 0; // start at first character
271 $regex = '(?='; // use positive lookahead
273 $regex .= '.*(?:^| )'; // before tag may only be a space or the beginning
274 // iterate over string, separating it into placeholder and content
275 for (; $i < $len; $i++
) {
276 if ($tag[$i] === '*') {
280 // regular characters
281 $offset = strpos($tag, '*', $i);
282 if ($offset === false) {
283 // no placeholder found, set offset to end of string
286 // subtract one, as we want to get before the placeholder or end of string
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), '/');
294 $regex .= '(?:$| ))'; // after the tag may only be a space or the end
299 * Returns the list of links associated with a given list of tags
301 * You can specify one or more tags, separated by space or a comma, e.g.
302 * print_r($mydb->filterTags('linux programming'));
304 * @param string $tags list of tags separated by commas or blank spaces.
305 * @param bool $casesensitive ignore case if false.
306 * @param string $visibility Optional: return only all/private/public links.
308 * @return array filtered links.
310 public function filterTags($tags, $casesensitive = false, $visibility = 'all')
312 // get single tags (we may get passed an array, even though the docs say different)
314 if (!is_array($tags)) {
315 // we got an input string, split tags
316 $inputTags = preg_split('/(?:\s+)|,/', $inputTags, -1, PREG_SPLIT_NO_EMPTY
);
319 if (!count($inputTags)) {
321 return $this->noFilter($visibility);
324 // build regex from all tags
325 $re = '/^' . implode(array_map("self::tag2regex", $inputTags)) . '.*$/';
326 if (!$casesensitive) {
327 // make regex case insensitive
331 // create resulting array
334 // iterate over each link
335 foreach ($this->links
as $key => $link) {
336 // check level of visibility
337 // ignore non private links when 'privateonly' is on.
338 if ($visibility !== 'all') {
339 if (! $link['private'] && $visibility === 'private') {
341 } elseif ($link['private'] && $visibility === 'public') {
345 $search = $link['tags']; // build search string, start with tags of current link
346 if (strlen(trim($link['description'])) && strpos($link['description'], '#') !== false) {
347 // description given and at least one possible tag found
349 // find all tags in the form of #tag in the description
351 '/(?<![' . self
::$HASHTAG_CHARS . '])#([' . self
::$HASHTAG_CHARS . ']+?)\b/sm',
352 $link['description'],
355 if (count($descTags[1])) {
356 // there were some tags in the description, add them to the search string
357 $search .= ' ' . implode(' ', $descTags[1]);
360 // match regular expression with search string
361 if (!preg_match($re, $search)) {
362 // this entry does _not_ match our regex
365 $filtered[$key] = $link;
371 * Return only links without any tag.
373 * @param string $visibility return only all/private/public links.
375 * @return array filtered links.
377 public function filterUntagged($visibility)
380 foreach ($this->links
as $key => $link) {
381 if ($visibility !== 'all') {
382 if (! $link['private'] && $visibility === 'private') {
384 } elseif ($link['private'] && $visibility === 'public') {
389 if (empty(trim($link['tags']))) {
390 $filtered[$key] = $link;
398 * Returns the list of articles for a given day, chronologically sorted
400 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
401 * print_r($mydb->filterDay('20120125'));
403 * @param string $day day to filter.
405 * @return array all link matching given day.
407 * @throws Exception if date format is invalid.
409 public function filterDay($day)
411 if (! checkDateFormat('Ymd', $day)) {
412 throw new Exception('Invalid date format');
416 foreach ($this->links
as $key => $l) {
417 if ($l['created']->format('Ymd') == $day) {
418 $filtered[$key] = $l;
423 return array_reverse($filtered, true);
427 * Convert a list of tags (str) to an array. Also
428 * - handle case sensitivity.
429 * - accepts spaces commas as separator.
431 * @param string $tags string containing a list of tags.
432 * @param bool $casesensitive will convert everything to lowercase if false.
434 * @return array filtered tags string.
436 public static function tagsStrToArray($tags, $casesensitive)
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);
442 return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY
);
446 class LinkNotFoundException
extends Exception
449 * LinkNotFoundException constructor.
451 public function __construct()
453 $this->message
= t('The link you are trying to reach does not exist or has been deleted.');