]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkFilter.php
Update LinkFilter to be able to filter only public links
[github/shaarli/Shaarli.git] / application / LinkFilter.php
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
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
35 /**
36 * @var LinkDB all available links.
37 */
38 private $links;
39
40 /**
41 * @param LinkDB $links initialization.
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.).
52 * @param mixed $request Filter content.
53 * @param bool $casesensitive Optional: Perform case sensitive filter if true.
54 * @param string $visibility Optional: return only all/private/public links
55 *
56 * @return array filtered link list.
57 */
58 public function filter($type, $request, $casesensitive = false, $visibility = 'all')
59 {
60 if (! in_array($visibility, ['all', 'public', 'private'])) {
61 $visibility = 'all';
62 }
63
64 switch($type) {
65 case self::$FILTER_HASH:
66 return $this->filterSmallHash($request);
67 case self::$FILTER_TAG | self::$FILTER_TEXT:
68 if (!empty($request)) {
69 $filtered = $this->links;
70 if (isset($request[0])) {
71 $filtered = $this->filterTags($request[0], $casesensitive, $visibility);
72 }
73 if (isset($request[1])) {
74 $lf = new LinkFilter($filtered);
75 $filtered = $lf->filterFulltext($request[1], $visibility);
76 }
77 return $filtered;
78 }
79 return $this->noFilter($visibility);
80 case self::$FILTER_TEXT:
81 return $this->filterFulltext($request, $visibility);
82 case self::$FILTER_TAG:
83 return $this->filterTags($request, $casesensitive, $visibility);
84 case self::$FILTER_DAY:
85 return $this->filterDay($request);
86 default:
87 return $this->noFilter($visibility);
88 }
89 }
90
91 /**
92 * Unknown filter, but handle private only.
93 *
94 * @param string $visibility Optional: return only all/private/public links
95 *
96 * @return array filtered links.
97 */
98 private function noFilter($visibility = 'all')
99 {
100 if ($visibility === 'all') {
101 return $this->links;
102 }
103
104 $out = array();
105 foreach ($this->links as $key => $value) {
106 if ($value['private'] && $visibility === 'private') {
107 $out[$key] = $value;
108 } else if (! $value['private'] && $visibility === 'public') {
109 $out[$key] = $value;
110 }
111 }
112
113 return $out;
114 }
115
116 /**
117 * Returns the shaare corresponding to a smallHash.
118 *
119 * @param string $smallHash permalink hash.
120 *
121 * @return array $filtered array containing permalink data.
122 *
123 * @throws LinkNotFoundException if the smallhash doesn't match any link.
124 */
125 private function filterSmallHash($smallHash)
126 {
127 $filtered = array();
128 foreach ($this->links as $key => $l) {
129 if ($smallHash == $l['shorturl']) {
130 // Yes, this is ugly and slow
131 $filtered[$key] = $l;
132 return $filtered;
133 }
134 }
135
136 if (empty($filtered)) {
137 throw new LinkNotFoundException();
138 }
139
140 return $filtered;
141 }
142
143 /**
144 * Returns the list of links corresponding to a full-text search
145 *
146 * Searches:
147 * - in the URLs, title and description;
148 * - are case-insensitive;
149 * - terms surrounded by quotes " are exact terms search.
150 * - terms starting with a dash - are excluded (except exact terms).
151 *
152 * Example:
153 * print_r($mydb->filterFulltext('hollandais'));
154 *
155 * mb_convert_case($val, MB_CASE_LOWER, 'UTF-8')
156 * - allows to perform searches on Unicode text
157 * - see https://github.com/shaarli/Shaarli/issues/75 for examples
158 *
159 * @param string $searchterms search query.
160 * @param string $visibility Optional: return only all/private/public links.
161 *
162 * @return array search results.
163 */
164 private function filterFulltext($searchterms, $visibility = 'all')
165 {
166 if (empty($searchterms)) {
167 return $this->noFilter($visibility);
168 }
169
170 $filtered = array();
171 $search = mb_convert_case(html_entity_decode($searchterms), MB_CASE_LOWER, 'UTF-8');
172 $exactRegex = '/"([^"]+)"/';
173 // Retrieve exact search terms.
174 preg_match_all($exactRegex, $search, $exactSearch);
175 $exactSearch = array_values(array_filter($exactSearch[1]));
176
177 // Remove exact search terms to get AND terms search.
178 $explodedSearchAnd = explode(' ', trim(preg_replace($exactRegex, '', $search)));
179 $explodedSearchAnd = array_values(array_filter($explodedSearchAnd));
180
181 // Filter excluding terms and update andSearch.
182 $excludeSearch = array();
183 $andSearch = array();
184 foreach ($explodedSearchAnd as $needle) {
185 if ($needle[0] == '-' && strlen($needle) > 1) {
186 $excludeSearch[] = substr($needle, 1);
187 } else {
188 $andSearch[] = $needle;
189 }
190 }
191
192 $keys = array('title', 'description', 'url', 'tags');
193
194 // Iterate over every stored link.
195 foreach ($this->links as $id => $link) {
196
197 // ignore non private links when 'privatonly' is on.
198 if ($visibility !== 'all') {
199 if (! $link['private'] && $visibility === 'private') {
200 continue;
201 } else if ($link['private'] && $visibility === 'public') {
202 continue;
203 }
204 }
205
206 // Concatenate link fields to search across fields.
207 // Adds a '\' separator for exact search terms.
208 $content = '';
209 foreach ($keys as $key) {
210 $content .= mb_convert_case($link[$key], MB_CASE_LOWER, 'UTF-8') . '\\';
211 }
212
213 // Be optimistic
214 $found = true;
215
216 // First, we look for exact term search
217 for ($i = 0; $i < count($exactSearch) && $found; $i++) {
218 $found = strpos($content, $exactSearch[$i]) !== false;
219 }
220
221 // Iterate over keywords, if keyword is not found,
222 // no need to check for the others. We want all or nothing.
223 for ($i = 0; $i < count($andSearch) && $found; $i++) {
224 $found = strpos($content, $andSearch[$i]) !== false;
225 }
226
227 // Exclude terms.
228 for ($i = 0; $i < count($excludeSearch) && $found; $i++) {
229 $found = strpos($content, $excludeSearch[$i]) === false;
230 }
231
232 if ($found) {
233 $filtered[$id] = $link;
234 }
235 }
236
237 return $filtered;
238 }
239
240 /**
241 * Returns the list of links associated with a given list of tags
242 *
243 * You can specify one or more tags, separated by space or a comma, e.g.
244 * print_r($mydb->filterTags('linux programming'));
245 *
246 * @param string $tags list of tags separated by commas or blank spaces.
247 * @param bool $casesensitive ignore case if false.
248 * @param string $visibility Optional: return only all/private/public links.
249 *
250 * @return array filtered links.
251 */
252 public function filterTags($tags, $casesensitive = false, $visibility = 'all')
253 {
254 // Implode if array for clean up.
255 $tags = is_array($tags) ? trim(implode(' ', $tags)) : $tags;
256 if (empty($tags)) {
257 return $this->noFilter($visibility);
258 }
259
260 $searchtags = self::tagsStrToArray($tags, $casesensitive);
261 $filtered = array();
262 if (empty($searchtags)) {
263 return $filtered;
264 }
265
266 foreach ($this->links as $key => $link) {
267 // ignore non private links when 'privatonly' is on.
268 if ($visibility !== 'all') {
269 if (! $link['private'] && $visibility === 'private') {
270 continue;
271 } else if ($link['private'] && $visibility === 'public') {
272 continue;
273 }
274 }
275
276 $linktags = self::tagsStrToArray($link['tags'], $casesensitive);
277
278 $found = true;
279 for ($i = 0 ; $i < count($searchtags) && $found; $i++) {
280 // Exclusive search, quit if tag found.
281 // Or, tag not found in the link, quit.
282 if (($searchtags[$i][0] == '-'
283 && $this->searchTagAndHashTag(substr($searchtags[$i], 1), $linktags, $link['description']))
284 || ($searchtags[$i][0] != '-')
285 && ! $this->searchTagAndHashTag($searchtags[$i], $linktags, $link['description'])
286 ) {
287 $found = false;
288 }
289 }
290
291 if ($found) {
292 $filtered[$key] = $link;
293 }
294 }
295 return $filtered;
296 }
297
298 /**
299 * Returns the list of articles for a given day, chronologically sorted
300 *
301 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
302 * print_r($mydb->filterDay('20120125'));
303 *
304 * @param string $day day to filter.
305 *
306 * @return array all link matching given day.
307 *
308 * @throws Exception if date format is invalid.
309 */
310 public function filterDay($day)
311 {
312 if (! checkDateFormat('Ymd', $day)) {
313 throw new Exception('Invalid date format');
314 }
315
316 $filtered = array();
317 foreach ($this->links as $key => $l) {
318 if ($l['created']->format('Ymd') == $day) {
319 $filtered[$key] = $l;
320 }
321 }
322
323 // sort by date ASC
324 return array_reverse($filtered, true);
325 }
326
327 /**
328 * Check if a tag is found in the taglist, or as an hashtag in the link description.
329 *
330 * @param string $tag Tag to search.
331 * @param array $taglist List of tags for the current link.
332 * @param string $description Link description.
333 *
334 * @return bool True if found, false otherwise.
335 */
336 protected function searchTagAndHashTag($tag, $taglist, $description)
337 {
338 if (in_array($tag, $taglist)) {
339 return true;
340 }
341
342 if (preg_match('/(^| )#'. $tag .'([^'. self::$HASHTAG_CHARS .']|$)/mui', $description) > 0) {
343 return true;
344 }
345
346 return false;
347 }
348
349 /**
350 * Convert a list of tags (str) to an array. Also
351 * - handle case sensitivity.
352 * - accepts spaces commas as separator.
353 *
354 * @param string $tags string containing a list of tags.
355 * @param bool $casesensitive will convert everything to lowercase if false.
356 *
357 * @return array filtered tags string.
358 */
359 public static function tagsStrToArray($tags, $casesensitive)
360 {
361 // We use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
362 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8');
363 $tagsOut = str_replace(',', ' ', $tagsOut);
364
365 return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY);
366 }
367 }
368
369 class LinkNotFoundException extends Exception
370 {
371 protected $message = 'The link you are trying to reach does not exist or has been deleted.';
372 }