3 namespace Shaarli\Bookmark
;
6 use Shaarli\Bookmark\Exception\BookmarkNotFoundException
;
11 * Perform search and filter operation on link data list.
16 * @var string permalinks.
18 public static $FILTER_HASH = 'permalink';
21 * @var string text search.
23 public static $FILTER_TEXT = 'fulltext';
26 * @var string tag filter.
28 public static $FILTER_TAG = 'tags';
31 * @var string filter by day.
33 public static $FILTER_DAY = 'FILTER_DAY';
36 * @var string filter by day.
38 public static $DEFAULT = 'NO_FILTER';
40 /** @var string Visibility: all */
41 public static $ALL = 'all';
43 /** @var string Visibility: public */
44 public static $PUBLIC = 'public';
46 /** @var string Visibility: private */
47 public static $PRIVATE = 'private';
50 * @var string Allowed characters for hashtags (regex syntax).
52 public static $HASHTAG_CHARS = '\p{Pc}\p{N}\p{L}\p{Mn}';
55 * @var Bookmark[] all available bookmarks.
60 * @param Bookmark[] $bookmarks initialization.
62 public function __construct($bookmarks)
64 $this->bookmarks
= $bookmarks;
68 * Filter bookmarks according to parameters.
70 * @param string $type Type of filter (eg. tags, permalink, etc.).
71 * @param mixed $request Filter content.
72 * @param bool $casesensitive Optional: Perform case sensitive filter if true.
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
76 * @return Bookmark[] filtered bookmark list.
78 * @throws BookmarkNotFoundException
80 public function filter($type, $request, $casesensitive = false, $visibility = 'all', $untaggedonly = false)
82 if (!in_array($visibility, ['all', 'public', 'private'])) {
87 case self
::$FILTER_HASH:
88 return $this->filterSmallHash($request);
89 case self
::$FILTER_TAG | self
::$FILTER_TEXT: // == "vuotext"
90 $noRequest = empty($request) || (empty($request[0]) && empty($request[1]));
93 return $this->filterUntagged($visibility);
95 return $this->noFilter($visibility);
98 $filtered = $this->filterUntagged($visibility);
100 $filtered = $this->bookmarks
;
102 if (!empty($request[0])) {
103 $filtered = (new BookmarkFilter($filtered))->filterTags($request[0], $casesensitive, $visibility);
105 if (!empty($request[1])) {
106 $filtered = (new BookmarkFilter($filtered))->filterFulltext($request[1], $visibility);
109 case self
::$FILTER_TEXT:
110 return $this->filterFulltext($request, $visibility);
111 case self
::$FILTER_TAG:
113 return $this->filterUntagged($visibility);
115 return $this->filterTags($request, $casesensitive, $visibility);
117 case self
::$FILTER_DAY:
118 return $this->filterDay($request, $visibility);
120 return $this->noFilter($visibility);
125 * Unknown filter, but handle private only.
127 * @param string $visibility Optional: return only all/private/public bookmarks
129 * @return Bookmark[] filtered bookmarks.
131 private function noFilter($visibility = 'all')
133 if ($visibility === 'all') {
134 return $this->bookmarks
;
138 foreach ($this->bookmarks
as $key => $value) {
139 if ($value->isPrivate() && $visibility === 'private') {
141 } elseif (!$value->isPrivate() && $visibility === 'public') {
150 * Returns the shaare corresponding to a smallHash.
152 * @param string $smallHash permalink hash.
154 * @return array $filtered array containing permalink data.
156 * @throws \Shaarli\Bookmark\Exception\BookmarkNotFoundException if the smallhash doesn't match any link.
158 private function filterSmallHash($smallHash)
160 foreach ($this->bookmarks
as $key => $l) {
161 if ($smallHash == $l->getShortUrl()) {
162 // Yes, this is ugly and slow
167 throw new BookmarkNotFoundException();
171 * Returns the list of bookmarks corresponding to a full-text search
174 * - in the URLs, title and description;
175 * - are case-insensitive;
176 * - terms surrounded by quotes " are exact terms search.
177 * - terms starting with a dash - are excluded (except exact terms).
180 * print_r($mydb->filterFulltext('hollandais'));
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
186 * @param string $searchterms search query.
187 * @param string $visibility Optional: return only all/private/public bookmarks.
189 * @return array search results.
191 private function filterFulltext($searchterms, $visibility = 'all')
193 if (empty($searchterms)) {
194 return $this->noFilter($visibility);
198 $search = mb_convert_case(html_entity_decode($searchterms), MB_CASE_LOWER
, 'UTF-8');
199 $exactRegex = '/"([^"]+)"/';
200 // Retrieve exact search terms.
201 preg_match_all($exactRegex, $search, $exactSearch);
202 $exactSearch = array_values(array_filter($exactSearch[1]));
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));
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);
215 $andSearch[] = $needle;
219 // Iterate over every stored link.
220 foreach ($this->bookmarks
as $id => $link) {
221 // ignore non private bookmarks when 'privatonly' is on.
222 if ($visibility !== 'all') {
223 if (!$link->isPrivate() && $visibility === 'private') {
225 } elseif ($link->isPrivate() && $visibility === 'public') {
230 // Concatenate link fields to search across fields.
231 // Adds a '\' separator for exact search terms.
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') .'\\';
240 // First, we look for exact term search
241 for ($i = 0; $i < count($exactSearch) && $found; $i++
) {
242 $found = strpos($content, $exactSearch[$i]) !== false;
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;
252 for ($i = 0; $i < count($excludeSearch) && $found; $i++
) {
253 $found = strpos($content, $excludeSearch[$i]) === false;
257 $filtered[$id] = $link;
265 * generate a regex fragment out of a tag
267 * @param string $tag to to generate regexs from. may start with '-' to negate, contain '*' as wildcard
269 * @return string generated regex fragment
271 private static function tag2regex($tag)
274 if (!$len || $tag === "-" || $tag === "*") {
275 // nothing to search, return empty regex
278 if ($tag[0] === "-") {
280 $i = 1; // use offset to start after '-' character
281 $regex = '(?!'; // create negative lookahead
283 $i = 0; // start at first character
284 $regex = '(?='; // use positive lookahead
286 $regex .= '.*(?:^| )'; // before tag may only be a space or the beginning
287 // iterate over string, separating it into placeholder and content
288 for (; $i < $len; $i++
) {
289 if ($tag[$i] === '*') {
293 // regular characters
294 $offset = strpos($tag, '*', $i);
295 if ($offset === false) {
296 // no placeholder found, set offset to end of string
299 // subtract one, as we want to get before the placeholder or end of string
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), '/');
307 $regex .= '(?:$| ))'; // after the tag may only be a space or the end
312 * Returns the list of bookmarks associated with a given list of tags
314 * You can specify one or more tags, separated by space or a comma, e.g.
315 * print_r($mydb->filterTags('linux programming'));
317 * @param string $tags list of tags separated by commas or blank spaces.
318 * @param bool $casesensitive ignore case if false.
319 * @param string $visibility Optional: return only all/private/public bookmarks.
321 * @return array filtered bookmarks.
323 public function filterTags($tags, $casesensitive = false, $visibility = 'all')
325 // get single tags (we may get passed an array, even though the docs say different)
327 if (!is_array($tags)) {
328 // we got an input string, split tags
329 $inputTags = preg_split('/(?:\s+)|,/', $inputTags, -1, PREG_SPLIT_NO_EMPTY
);
332 if (!count($inputTags)) {
334 return $this->noFilter($visibility);
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, '.');
343 if (empty($inputTags)) {
348 // build regex from all tags
349 $re = '/^' . implode(array_map("self::tag2regex", $inputTags)) . '.*$/';
350 if (!$casesensitive) {
351 // make regex case insensitive
355 // create resulting array
358 // iterate over each link
359 foreach ($this->bookmarks
as $key => $link) {
360 // check level of visibility
361 // ignore non private bookmarks when 'privateonly' is on.
362 if ($visibility !== 'all') {
363 if (!$link->isPrivate() && $visibility === 'private') {
365 } elseif ($link->isPrivate() && $visibility === 'public') {
369 $search = $link->getTagsString(); // build search string, start with tags of current link
370 if (strlen(trim($link->getDescription())) && strpos($link->getDescription(), '#') !== false) {
371 // description given and at least one possible tag found
373 // find all tags in the form of #tag in the description
375 '/(?<![' . self
::$HASHTAG_CHARS . '])#([' . self
::$HASHTAG_CHARS . ']+?)\b/sm',
376 $link->getDescription(),
379 if (count($descTags[1])) {
380 // there were some tags in the description, add them to the search string
381 $search .= ' ' . implode(' ', $descTags[1]);
384 // match regular expression with search string
385 if (!preg_match($re, $search)) {
386 // this entry does _not_ match our regex
389 $filtered[$key] = $link;
395 * Return only bookmarks without any tag.
397 * @param string $visibility return only all/private/public bookmarks.
399 * @return array filtered bookmarks.
401 public function filterUntagged($visibility)
404 foreach ($this->bookmarks
as $key => $link) {
405 if ($visibility !== 'all') {
406 if (!$link->isPrivate() && $visibility === 'private') {
408 } elseif ($link->isPrivate() && $visibility === 'public') {
413 if (empty(trim($link->getTagsString()))) {
414 $filtered[$key] = $link;
422 * Returns the list of articles for a given day, chronologically sorted
424 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
425 * print_r($mydb->filterDay('20120125'));
427 * @param string $day day to filter.
428 * @param string $visibility return only all/private/public bookmarks.
430 * @return array all link matching given day.
432 * @throws Exception if date format is invalid.
434 public function filterDay($day, $visibility)
436 if (!checkDateFormat('Ymd', $day)) {
437 throw new Exception('Invalid date format');
441 foreach ($this->bookmarks
as $key => $bookmark) {
442 if ($visibility === static::$PUBLIC && $bookmark->isPrivate()) {
446 if ($bookmark->getCreated()->format('Ymd') == $day) {
447 $filtered[$key] = $bookmark;
452 return array_reverse($filtered, true);
456 * Convert a list of tags (str) to an array. Also
457 * - handle case sensitivity.
458 * - accepts spaces commas as separator.
460 * @param string $tags string containing a list of tags.
461 * @param bool $casesensitive will convert everything to lowercase if false.
463 * @return array filtered tags string.
465 public static function tagsStrToArray($tags, $casesensitive)
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);
471 return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY
);