LinkFilter.php 13 KB

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