LinkFilter.php 12 KB

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