]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkFilter.php
Merge pull request #910 from virtualtam/documentation/improvements
[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 * @param string $untaggedonly Optional: return only untagged links. Applies only if $type includes FILTER_TAG
56 *
57 * @return array filtered link list.
58 */
59 public function filter($type, $request, $casesensitive = false, $visibility = 'all', $untaggedonly = false)
60 {
61 if (! in_array($visibility, ['all', 'public', 'private'])) {
62 $visibility = 'all';
63 }
64
65 switch($type) {
66 case self::$FILTER_HASH:
67 return $this->filterSmallHash($request);
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);
73 }
74 return $this->noFilter($visibility);
75 }
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;
88 case self::$FILTER_TEXT:
89 return $this->filterFulltext($request, $visibility);
90 case self::$FILTER_TAG:
91 if ($untaggedonly) {
92 return $this->filterUntagged($visibility);
93 } else {
94 return $this->filterTags($request, $casesensitive, $visibility);
95 }
96 case self::$FILTER_DAY:
97 return $this->filterDay($request);
98 default:
99 return $this->noFilter($visibility);
100 }
101 }
102
103 /**
104 * Unknown filter, but handle private only.
105 *
106 * @param string $visibility Optional: return only all/private/public links
107 *
108 * @return array filtered links.
109 */
110 private function noFilter($visibility = 'all')
111 {
112 if ($visibility === 'all') {
113 return $this->links;
114 }
115
116 $out = array();
117 foreach ($this->links as $key => $value) {
118 if ($value['private'] && $visibility === 'private') {
119 $out[$key] = $value;
120 } else if (! $value['private'] && $visibility === 'public') {
121 $out[$key] = $value;
122 }
123 }
124
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.
134 *
135 * @throws LinkNotFoundException if the smallhash doesn't match any link.
136 */
137 private function filterSmallHash($smallHash)
138 {
139 $filtered = array();
140 foreach ($this->links as $key => $l) {
141 if ($smallHash == $l['shorturl']) {
142 // Yes, this is ugly and slow
143 $filtered[$key] = $l;
144 return $filtered;
145 }
146 }
147
148 if (empty($filtered)) {
149 throw new LinkNotFoundException();
150 }
151
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;
160 * - are case-insensitive;
161 * - terms surrounded by quotes " are exact terms search.
162 * - terms starting with a dash - are excluded (except exact terms).
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.
172 * @param string $visibility Optional: return only all/private/public links.
173 *
174 * @return array search results.
175 */
176 private function filterFulltext($searchterms, $visibility = 'all')
177 {
178 if (empty($searchterms)) {
179 return $this->noFilter($visibility);
180 }
181
182 $filtered = array();
183 $search = mb_convert_case(html_entity_decode($searchterms), MB_CASE_LOWER, 'UTF-8');
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
204 $keys = array('title', 'description', 'url', 'tags');
205
206 // Iterate over every stored link.
207 foreach ($this->links as $id => $link) {
208
209 // ignore non private links when 'privatonly' is on.
210 if ($visibility !== 'all') {
211 if (! $link['private'] && $visibility === 'private') {
212 continue;
213 } else if ($link['private'] && $visibility === 'public') {
214 continue;
215 }
216 }
217
218 // Concatenate link fields to search across fields.
219 // Adds a '\' separator for exact search terms.
220 $content = '';
221 foreach ($keys as $key) {
222 $content .= mb_convert_case($link[$key], MB_CASE_LOWER, 'UTF-8') . '\\';
223 }
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
244 if ($found) {
245 $filtered[$id] = $link;
246 }
247 }
248
249 return $filtered;
250 }
251
252 /**
253 * Returns the list of links associated with a given list of tags
254 *
255 * You can specify one or more tags, separated by space or a comma, e.g.
256 * print_r($mydb->filterTags('linux programming'));
257 *
258 * @param string $tags list of tags separated by commas or blank spaces.
259 * @param bool $casesensitive ignore case if false.
260 * @param string $visibility Optional: return only all/private/public links.
261 *
262 * @return array filtered links.
263 */
264 public function filterTags($tags, $casesensitive = false, $visibility = 'all')
265 {
266 // Implode if array for clean up.
267 $tags = is_array($tags) ? trim(implode(' ', $tags)) : $tags;
268 if (empty($tags)) {
269 return $this->noFilter($visibility);
270 }
271
272 $searchtags = self::tagsStrToArray($tags, $casesensitive);
273 $filtered = array();
274 if (empty($searchtags)) {
275 return $filtered;
276 }
277
278 foreach ($this->links as $key => $link) {
279 // ignore non private links when 'privatonly' is on.
280 if ($visibility !== 'all') {
281 if (! $link['private'] && $visibility === 'private') {
282 continue;
283 } else if ($link['private'] && $visibility === 'public') {
284 continue;
285 }
286 }
287
288 $linktags = self::tagsStrToArray($link['tags'], $casesensitive);
289
290 $found = true;
291 for ($i = 0 ; $i < count($searchtags) && $found; $i++) {
292 // Exclusive search, quit if tag found.
293 // Or, tag not found in the link, quit.
294 if (($searchtags[$i][0] == '-'
295 && $this->searchTagAndHashTag(substr($searchtags[$i], 1), $linktags, $link['description']))
296 || ($searchtags[$i][0] != '-')
297 && ! $this->searchTagAndHashTag($searchtags[$i], $linktags, $link['description'])
298 ) {
299 $found = false;
300 }
301 }
302
303 if ($found) {
304 $filtered[$key] = $link;
305 }
306 }
307 return $filtered;
308 }
309
310 /**
311 * Return only links without any tag.
312 *
313 * @param string $visibility return only all/private/public links.
314 *
315 * @return array filtered links.
316 */
317 public function filterUntagged($visibility)
318 {
319 $filtered = [];
320 foreach ($this->links as $key => $link) {
321 if ($visibility !== 'all') {
322 if (! $link['private'] && $visibility === 'private') {
323 continue;
324 } else if ($link['private'] && $visibility === 'public') {
325 continue;
326 }
327 }
328
329 if (empty(trim($link['tags']))) {
330 $filtered[$key] = $link;
331 }
332 }
333
334 return $filtered;
335 }
336
337 /**
338 * Returns the list of articles for a given day, chronologically sorted
339 *
340 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
341 * print_r($mydb->filterDay('20120125'));
342 *
343 * @param string $day day to filter.
344 *
345 * @return array all link matching given day.
346 *
347 * @throws Exception if date format is invalid.
348 */
349 public function filterDay($day)
350 {
351 if (! checkDateFormat('Ymd', $day)) {
352 throw new Exception('Invalid date format');
353 }
354
355 $filtered = array();
356 foreach ($this->links as $key => $l) {
357 if ($l['created']->format('Ymd') == $day) {
358 $filtered[$key] = $l;
359 }
360 }
361
362 // sort by date ASC
363 return array_reverse($filtered, true);
364 }
365
366 /**
367 * Check if a tag is found in the taglist, or as an hashtag in the link description.
368 *
369 * @param string $tag Tag to search.
370 * @param array $taglist List of tags for the current link.
371 * @param string $description Link description.
372 *
373 * @return bool True if found, false otherwise.
374 */
375 protected function searchTagAndHashTag($tag, $taglist, $description)
376 {
377 if (in_array($tag, $taglist)) {
378 return true;
379 }
380
381 if (preg_match('/(^| )#'. $tag .'([^'. self::$HASHTAG_CHARS .']|$)/mui', $description) > 0) {
382 return true;
383 }
384
385 return false;
386 }
387
388 /**
389 * Convert a list of tags (str) to an array. Also
390 * - handle case sensitivity.
391 * - accepts spaces commas as separator.
392 *
393 * @param string $tags string containing a list of tags.
394 * @param bool $casesensitive will convert everything to lowercase if false.
395 *
396 * @return array filtered tags string.
397 */
398 public static function tagsStrToArray($tags, $casesensitive)
399 {
400 // We use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
401 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8');
402 $tagsOut = str_replace(',', ' ', $tagsOut);
403
404 return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY);
405 }
406 }
407
408 class LinkNotFoundException extends Exception
409 {
410 protected $message = 'The link you are trying to reach does not exist or has been deleted.';
411 }