LinkFilter.php 11 KB

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