]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkFilter.php
6 * Perform search and filter operation on link data list.
11 * @var string permalinks.
13 public static $FILTER_HASH = 'permalink';
16 * @var string text search.
18 public static $FILTER_TEXT = 'fulltext';
21 * @var string tag filter.
23 public static $FILTER_TAG = 'tags';
26 * @var string filter by day.
28 public static $FILTER_DAY = 'FILTER_DAY';
31 * @var string Allowed characters for hashtags (regex syntax).
33 public static $HASHTAG_CHARS = '\p{Pc}\p{N}\p{L}\p{Mn}';
36 * @var LinkDB all available links.
41 * @param LinkDB $links initialization.
43 public function __construct($links)
45 $this->links
= $links;
49 * Filter links according to parameters.
51 * @param string $type Type of filter (eg. tags, permalink, etc.).
52 * @param mixed $request Filter content.
53 * @param bool $casesensitive Optional: Perform case sensitive filter if true.
54 * @param bool $privateonly Optional: Only returns private links if true.
56 * @return array filtered link list.
58 public function filter($type, $request, $casesensitive = false, $privateonly = false)
61 case self
::$FILTER_HASH:
62 return $this->filterSmallHash($request);
63 case self
::$FILTER_TAG | self
::$FILTER_TEXT:
64 if (!empty($request)) {
65 $filtered = $this->links
;
66 if (isset($request[0])) {
67 $filtered = $this->filterTags($request[0], $casesensitive, $privateonly);
69 if (isset($request[1])) {
70 $lf = new LinkFilter($filtered);
71 $filtered = $lf->filterFulltext($request[1], $privateonly);
75 return $this->noFilter($privateonly);
76 case self
::$FILTER_TEXT:
77 return $this->filterFulltext($request, $privateonly);
78 case self
::$FILTER_TAG:
79 return $this->filterTags($request, $casesensitive, $privateonly);
80 case self
::$FILTER_DAY:
81 return $this->filterDay($request);
83 return $this->noFilter($privateonly);
88 * Unknown filter, but handle private only.
90 * @param bool $privateonly returns private link only if true.
92 * @return array filtered links.
94 private function noFilter($privateonly = false)
101 foreach ($this->links
as $key => $value) {
102 if ($value['private']) {
111 * Returns the shaare corresponding to a smallHash.
113 * @param string $smallHash permalink hash.
115 * @return array $filtered array containing permalink data.
117 * @throws LinkNotFoundException if the smallhash doesn't match any link.
119 private function filterSmallHash($smallHash)
122 foreach ($this->links
as $key => $l) {
123 if ($smallHash == $l['shorturl']) {
124 // Yes, this is ugly and slow
125 $filtered[$key] = $l;
130 if (empty($filtered)) {
131 throw new LinkNotFoundException();
138 * Returns the list of links corresponding to a full-text search
141 * - in the URLs, title and description;
142 * - are case-insensitive;
143 * - terms surrounded by quotes " are exact terms search.
144 * - terms starting with a dash - are excluded (except exact terms).
147 * print_r($mydb->filterFulltext('hollandais'));
149 * mb_convert_case($val, MB_CASE_LOWER, 'UTF-8')
150 * - allows to perform searches on Unicode text
151 * - see https://github.com/shaarli/Shaarli/issues/75 for examples
153 * @param string $searchterms search query.
154 * @param bool $privateonly return only private links if true.
156 * @return array search results.
158 private function filterFulltext($searchterms, $privateonly = false)
160 if (empty($searchterms)) {
165 $search = mb_convert_case(html_entity_decode($searchterms), MB_CASE_LOWER
, 'UTF-8');
166 $exactRegex = '/"([^"]+)"/';
167 // Retrieve exact search terms.
168 preg_match_all($exactRegex, $search, $exactSearch);
169 $exactSearch = array_values(array_filter($exactSearch[1]));
171 // Remove exact search terms to get AND terms search.
172 $explodedSearchAnd = explode(' ', trim(preg_replace($exactRegex, '', $search)));
173 $explodedSearchAnd = array_values(array_filter($explodedSearchAnd));
175 // Filter excluding terms and update andSearch.
176 $excludeSearch = array();
177 $andSearch = array();
178 foreach ($explodedSearchAnd as $needle) {
179 if ($needle[0] == '-' && strlen($needle) > 1) {
180 $excludeSearch[] = substr($needle, 1);
182 $andSearch[] = $needle;
186 $keys = array('title', 'description', 'url', 'tags');
188 // Iterate over every stored link.
189 foreach ($this->links
as $id => $link) {
191 // ignore non private links when 'privatonly' is on.
192 if (! $link['private'] && $privateonly === true) {
196 // Concatenate link fields to search across fields.
197 // Adds a '\' separator for exact search terms.
199 foreach ($keys as $key) {
200 $content .= mb_convert_case($link[$key], MB_CASE_LOWER
, 'UTF-8') . '\\';
206 // First, we look for exact term search
207 for ($i = 0; $i < count($exactSearch) && $found; $i++
) {
208 $found = strpos($content, $exactSearch[$i]) !== false;
211 // Iterate over keywords, if keyword is not found,
212 // no need to check for the others. We want all or nothing.
213 for ($i = 0; $i < count($andSearch) && $found; $i++
) {
214 $found = strpos($content, $andSearch[$i]) !== false;
218 for ($i = 0; $i < count($excludeSearch) && $found; $i++
) {
219 $found = strpos($content, $excludeSearch[$i]) === false;
223 $filtered[$id] = $link;
231 * Returns the list of links associated with a given list of tags
233 * You can specify one or more tags, separated by space or a comma, e.g.
234 * print_r($mydb->filterTags('linux programming'));
236 * @param string $tags list of tags separated by commas or blank spaces.
237 * @param bool $casesensitive ignore case if false.
238 * @param bool $privateonly returns private links only.
240 * @return array filtered links.
242 public function filterTags($tags, $casesensitive = false, $privateonly = false)
244 // Implode if array for clean up.
245 $tags = is_array($tags) ? trim(implode(' ', $tags)) : $tags;
250 $searchtags = self
::tagsStrToArray($tags, $casesensitive);
252 if (empty($searchtags)) {
256 foreach ($this->links
as $key => $link) {
257 // ignore non private links when 'privatonly' is on.
258 if (! $link['private'] && $privateonly === true) {
262 $linktags = self
::tagsStrToArray($link['tags'], $casesensitive);
265 for ($i = 0 ; $i < count($searchtags) && $found; $i++
) {
266 // Exclusive search, quit if tag found.
267 // Or, tag not found in the link, quit.
268 if (($searchtags[$i][0] == '-'
269 && $this->searchTagAndHashTag(substr($searchtags[$i], 1), $linktags, $link['description']))
270 || ($searchtags[$i][0] != '-')
271 && ! $this->searchTagAndHashTag($searchtags[$i], $linktags, $link['description'])
278 $filtered[$key] = $link;
285 * Returns the list of articles for a given day, chronologically sorted
287 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
288 * print_r($mydb->filterDay('20120125'));
290 * @param string $day day to filter.
292 * @return array all link matching given day.
294 * @throws Exception if date format is invalid.
296 public function filterDay($day)
298 if (! checkDateFormat('Ymd', $day)) {
299 throw new Exception('Invalid date format');
303 foreach ($this->links
as $key => $l) {
304 if ($l['created']->format('Ymd') == $day) {
305 $filtered[$key] = $l;
310 return array_reverse($filtered, true);
314 * Check if a tag is found in the taglist, or as an hashtag in the link description.
316 * @param string $tag Tag to search.
317 * @param array $taglist List of tags for the current link.
318 * @param string $description Link description.
320 * @return bool True if found, false otherwise.
322 protected function searchTagAndHashTag($tag, $taglist, $description)
324 if (in_array($tag, $taglist)) {
328 if (preg_match('/(^| )#'. $tag .'([^'. self
::$HASHTAG_CHARS .']|$)/mui', $description) > 0) {
336 * Convert a list of tags (str) to an array. Also
337 * - handle case sensitivity.
338 * - accepts spaces commas as separator.
340 * @param string $tags string containing a list of tags.
341 * @param bool $casesensitive will convert everything to lowercase if false.
343 * @return array filtered tags string.
345 public static function tagsStrToArray($tags, $casesensitive)
347 // We use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
348 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER
, 'UTF-8');
349 $tagsOut = str_replace(',', ' ', $tagsOut);
351 return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY
);
355 class LinkNotFoundException
extends Exception
357 protected $message = 'The link you are trying to reach does not exist or has been deleted.';