]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/LinkFilter.php
Add a persistent 'shorturl' key to all 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 bool $privateonly Optional: Only returns private links if true.
55 *
56 * @return array filtered link list.
57 */
58 public function filter($type, $request, $casesensitive = false, $privateonly = false)
59 {
60 switch($type) {
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);
68 }
69 if (isset($request[1])) {
70 $lf = new LinkFilter($filtered);
71 $filtered = $lf->filterFulltext($request[1], $privateonly);
72 }
73 return $filtered;
74 }
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);
82 default:
83 return $this->noFilter($privateonly);
84 }
85 }
86
87 /**
88 * Unknown filter, but handle private only.
89 *
90 * @param bool $privateonly returns private link only if true.
91 *
92 * @return array filtered links.
93 */
94 private function noFilter($privateonly = false)
95 {
96 if (! $privateonly) {
97 return $this->links;
98 }
99
100 $out = array();
101 foreach ($this->links as $key => $value) {
102 if ($value['private']) {
103 $out[$key] = $value;
104 }
105 }
106
107 return $out;
108 }
109
110 /**
111 * Returns the shaare corresponding to a smallHash.
112 *
113 * @param string $smallHash permalink hash.
114 *
115 * @return array $filtered array containing permalink data.
116 *
117 * @throws LinkNotFoundException if the smallhash doesn't match any link.
118 */
119 private function filterSmallHash($smallHash)
120 {
121 $filtered = array();
122 foreach ($this->links as $key => $l) {
123 if ($smallHash == $l['shorturl']) {
124 // Yes, this is ugly and slow
125 $filtered[$key] = $l;
126 return $filtered;
127 }
128 }
129
130 if (empty($filtered)) {
131 throw new LinkNotFoundException();
132 }
133
134 return $filtered;
135 }
136
137 /**
138 * Returns the list of links corresponding to a full-text search
139 *
140 * Searches:
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).
145 *
146 * Example:
147 * print_r($mydb->filterFulltext('hollandais'));
148 *
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
152 *
153 * @param string $searchterms search query.
154 * @param bool $privateonly return only private links if true.
155 *
156 * @return array search results.
157 */
158 private function filterFulltext($searchterms, $privateonly = false)
159 {
160 if (empty($searchterms)) {
161 return $this->links;
162 }
163
164 $filtered = array();
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]));
170
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));
174
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);
181 } else {
182 $andSearch[] = $needle;
183 }
184 }
185
186 $keys = array('title', 'description', 'url', 'tags');
187
188 // Iterate over every stored link.
189 foreach ($this->links as $id => $link) {
190
191 // ignore non private links when 'privatonly' is on.
192 if (! $link['private'] && $privateonly === true) {
193 continue;
194 }
195
196 // Concatenate link fields to search across fields.
197 // Adds a '\' separator for exact search terms.
198 $content = '';
199 foreach ($keys as $key) {
200 $content .= mb_convert_case($link[$key], MB_CASE_LOWER, 'UTF-8') . '\\';
201 }
202
203 // Be optimistic
204 $found = true;
205
206 // First, we look for exact term search
207 for ($i = 0; $i < count($exactSearch) && $found; $i++) {
208 $found = strpos($content, $exactSearch[$i]) !== false;
209 }
210
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;
215 }
216
217 // Exclude terms.
218 for ($i = 0; $i < count($excludeSearch) && $found; $i++) {
219 $found = strpos($content, $excludeSearch[$i]) === false;
220 }
221
222 if ($found) {
223 $filtered[$id] = $link;
224 }
225 }
226
227 return $filtered;
228 }
229
230 /**
231 * Returns the list of links associated with a given list of tags
232 *
233 * You can specify one or more tags, separated by space or a comma, e.g.
234 * print_r($mydb->filterTags('linux programming'));
235 *
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.
239 *
240 * @return array filtered links.
241 */
242 public function filterTags($tags, $casesensitive = false, $privateonly = false)
243 {
244 // Implode if array for clean up.
245 $tags = is_array($tags) ? trim(implode(' ', $tags)) : $tags;
246 if (empty($tags)) {
247 return $this->links;
248 }
249
250 $searchtags = self::tagsStrToArray($tags, $casesensitive);
251 $filtered = array();
252 if (empty($searchtags)) {
253 return $filtered;
254 }
255
256 foreach ($this->links as $key => $link) {
257 // ignore non private links when 'privatonly' is on.
258 if (! $link['private'] && $privateonly === true) {
259 continue;
260 }
261
262 $linktags = self::tagsStrToArray($link['tags'], $casesensitive);
263
264 $found = true;
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'])
272 ) {
273 $found = false;
274 }
275 }
276
277 if ($found) {
278 $filtered[$key] = $link;
279 }
280 }
281 return $filtered;
282 }
283
284 /**
285 * Returns the list of articles for a given day, chronologically sorted
286 *
287 * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
288 * print_r($mydb->filterDay('20120125'));
289 *
290 * @param string $day day to filter.
291 *
292 * @return array all link matching given day.
293 *
294 * @throws Exception if date format is invalid.
295 */
296 public function filterDay($day)
297 {
298 if (! checkDateFormat('Ymd', $day)) {
299 throw new Exception('Invalid date format');
300 }
301
302 $filtered = array();
303 foreach ($this->links as $key => $l) {
304 if ($l['created']->format('Ymd') == $day) {
305 $filtered[$key] = $l;
306 }
307 }
308
309 // sort by date ASC
310 return array_reverse($filtered, true);
311 }
312
313 /**
314 * Check if a tag is found in the taglist, or as an hashtag in the link description.
315 *
316 * @param string $tag Tag to search.
317 * @param array $taglist List of tags for the current link.
318 * @param string $description Link description.
319 *
320 * @return bool True if found, false otherwise.
321 */
322 protected function searchTagAndHashTag($tag, $taglist, $description)
323 {
324 if (in_array($tag, $taglist)) {
325 return true;
326 }
327
328 if (preg_match('/(^| )#'. $tag .'([^'. self::$HASHTAG_CHARS .']|$)/mui', $description) > 0) {
329 return true;
330 }
331
332 return false;
333 }
334
335 /**
336 * Convert a list of tags (str) to an array. Also
337 * - handle case sensitivity.
338 * - accepts spaces commas as separator.
339 *
340 * @param string $tags string containing a list of tags.
341 * @param bool $casesensitive will convert everything to lowercase if false.
342 *
343 * @return array filtered tags string.
344 */
345 public static function tagsStrToArray($tags, $casesensitive)
346 {
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);
350
351 return array_values(array_filter(explode(' ', trim($tagsOut)), 'strlen'));
352 }
353 }
354
355 class LinkNotFoundException extends Exception
356 {
357 protected $message = 'The link you are trying to reach does not exist or has been deleted.';
358 }