LinkFilter.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 ($tags === false) {
  227. return $this->filterUntagged($visibility);
  228. }
  229. if (empty($tags)) {
  230. return $this->noFilter($visibility);
  231. }
  232. $searchtags = self::tagsStrToArray($tags, $casesensitive);
  233. $filtered = array();
  234. if (empty($searchtags)) {
  235. return $filtered;
  236. }
  237. foreach ($this->links as $key => $link) {
  238. // ignore non private links when 'privatonly' is on.
  239. if ($visibility !== 'all') {
  240. if (! $link['private'] && $visibility === 'private') {
  241. continue;
  242. } else if ($link['private'] && $visibility === 'public') {
  243. continue;
  244. }
  245. }
  246. $linktags = self::tagsStrToArray($link['tags'], $casesensitive);
  247. $found = true;
  248. for ($i = 0 ; $i < count($searchtags) && $found; $i++) {
  249. // Exclusive search, quit if tag found.
  250. // Or, tag not found in the link, quit.
  251. if (($searchtags[$i][0] == '-'
  252. && $this->searchTagAndHashTag(substr($searchtags[$i], 1), $linktags, $link['description']))
  253. || ($searchtags[$i][0] != '-')
  254. && ! $this->searchTagAndHashTag($searchtags[$i], $linktags, $link['description'])
  255. ) {
  256. $found = false;
  257. }
  258. }
  259. if ($found) {
  260. $filtered[$key] = $link;
  261. }
  262. }
  263. return $filtered;
  264. }
  265. /**
  266. * Return only links without any tag.
  267. *
  268. * @param string $visibility return only all/private/public links.
  269. *
  270. * @return array filtered links.
  271. */
  272. public function filterUntagged($visibility)
  273. {
  274. $filtered = [];
  275. foreach ($this->links as $key => $link) {
  276. if ($visibility !== 'all') {
  277. if (! $link['private'] && $visibility === 'private') {
  278. continue;
  279. } else if ($link['private'] && $visibility === 'public') {
  280. continue;
  281. }
  282. }
  283. if (empty(trim($link['tags']))) {
  284. $filtered[$key] = $link;
  285. }
  286. }
  287. return $filtered;
  288. }
  289. /**
  290. * Returns the list of articles for a given day, chronologically sorted
  291. *
  292. * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
  293. * print_r($mydb->filterDay('20120125'));
  294. *
  295. * @param string $day day to filter.
  296. *
  297. * @return array all link matching given day.
  298. *
  299. * @throws Exception if date format is invalid.
  300. */
  301. public function filterDay($day)
  302. {
  303. if (! checkDateFormat('Ymd', $day)) {
  304. throw new Exception('Invalid date format');
  305. }
  306. $filtered = array();
  307. foreach ($this->links as $key => $l) {
  308. if ($l['created']->format('Ymd') == $day) {
  309. $filtered[$key] = $l;
  310. }
  311. }
  312. // sort by date ASC
  313. return array_reverse($filtered, true);
  314. }
  315. /**
  316. * Check if a tag is found in the taglist, or as an hashtag in the link description.
  317. *
  318. * @param string $tag Tag to search.
  319. * @param array $taglist List of tags for the current link.
  320. * @param string $description Link description.
  321. *
  322. * @return bool True if found, false otherwise.
  323. */
  324. protected function searchTagAndHashTag($tag, $taglist, $description)
  325. {
  326. if (in_array($tag, $taglist)) {
  327. return true;
  328. }
  329. if (preg_match('/(^| )#'. $tag .'([^'. self::$HASHTAG_CHARS .']|$)/mui', $description) > 0) {
  330. return true;
  331. }
  332. return false;
  333. }
  334. /**
  335. * Convert a list of tags (str) to an array. Also
  336. * - handle case sensitivity.
  337. * - accepts spaces commas as separator.
  338. *
  339. * @param string $tags string containing a list of tags.
  340. * @param bool $casesensitive will convert everything to lowercase if false.
  341. *
  342. * @return array filtered tags string.
  343. */
  344. public static function tagsStrToArray($tags, $casesensitive)
  345. {
  346. // We use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
  347. $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8');
  348. $tagsOut = str_replace(',', ' ', $tagsOut);
  349. return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY);
  350. }
  351. }
  352. class LinkNotFoundException extends Exception
  353. {
  354. protected $message = 'The link you are trying to reach does not exist or has been deleted.';
  355. }