LinkFilter.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. } elseif (! $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. } elseif ($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. * generate a regex fragment out of a tag
  224. * @param string $tag to to generate regexs from. may start with '-' to negate, contain '*' as wildcard
  225. * @return string generated regex fragment
  226. */
  227. private static function tag2regex($tag)
  228. {
  229. $len = strlen($tag);
  230. if (!$len || $tag === "-" || $tag === "*") {
  231. // nothing to search, return empty regex
  232. return '';
  233. }
  234. if ($tag[0] === "-") {
  235. // query is negated
  236. $i = 1; // use offset to start after '-' character
  237. $regex = '(?!'; // create negative lookahead
  238. } else {
  239. $i = 0; // start at first character
  240. $regex = '(?='; // use positive lookahead
  241. }
  242. $regex .= '.*(?:^| )'; // before tag may only be a space or the beginning
  243. // iterate over string, separating it into placeholder and content
  244. for (; $i < $len; $i++) {
  245. if ($tag[$i] === '*') {
  246. // placeholder found
  247. $regex .= '[^ ]*?';
  248. } else {
  249. // regular characters
  250. $offset = strpos($tag, '*', $i);
  251. if ($offset === false) {
  252. // no placeholder found, set offset to end of string
  253. $offset = $len;
  254. }
  255. // subtract one, as we want to get before the placeholder or end of string
  256. $offset -= 1;
  257. // we got a tag name that we want to search for. escape any regex characters to prevent conflicts.
  258. $regex .= preg_quote(substr($tag, $i, $offset - $i + 1), '/');
  259. // move $i on
  260. $i = $offset;
  261. }
  262. }
  263. $regex .= '(?:$| ))'; // after the tag may only be a space or the end
  264. return $regex;
  265. }
  266. /**
  267. * Returns the list of links associated with a given list of tags
  268. *
  269. * You can specify one or more tags, separated by space or a comma, e.g.
  270. * print_r($mydb->filterTags('linux programming'));
  271. *
  272. * @param string $tags list of tags separated by commas or blank spaces.
  273. * @param bool $casesensitive ignore case if false.
  274. * @param string $visibility Optional: return only all/private/public links.
  275. *
  276. * @return array filtered links.
  277. */
  278. public function filterTags($tags, $casesensitive = false, $visibility = 'all')
  279. {
  280. // get single tags (we may get passed an array, even though the docs say different)
  281. $inputTags = $tags;
  282. if (!is_array($tags)) {
  283. // we got an input string, split tags
  284. $inputTags = preg_split('/(?:\s+)|,/', $inputTags, -1, PREG_SPLIT_NO_EMPTY);
  285. }
  286. if (!count($inputTags)) {
  287. // no input tags
  288. return $this->noFilter($visibility);
  289. }
  290. // build regex from all tags
  291. $re = '/^' . implode(array_map("self::tag2regex", $inputTags)) . '.*$/';
  292. if (!$casesensitive) {
  293. // make regex case insensitive
  294. $re .= 'i';
  295. }
  296. // create resulting array
  297. $filtered = array();
  298. // iterate over each link
  299. foreach ($this->links as $key => $link) {
  300. // check level of visibility
  301. // ignore non private links when 'privateonly' is on.
  302. if ($visibility !== 'all') {
  303. if (! $link['private'] && $visibility === 'private') {
  304. continue;
  305. } elseif ($link['private'] && $visibility === 'public') {
  306. continue;
  307. }
  308. }
  309. $search = $link['tags']; // build search string, start with tags of current link
  310. if (strlen(trim($link['description'])) && strpos($link['description'], '#') !== false) {
  311. // description given and at least one possible tag found
  312. $descTags = array();
  313. // find all tags in the form of #tag in the description
  314. preg_match_all(
  315. '/(?<![' . self::$HASHTAG_CHARS . '])#([' . self::$HASHTAG_CHARS . ']+?)\b/sm',
  316. $link['description'],
  317. $descTags
  318. );
  319. if (count($descTags[1])) {
  320. // there were some tags in the description, add them to the search string
  321. $search .= ' ' . implode(' ', $descTags[1]);
  322. }
  323. };
  324. // match regular expression with search string
  325. if (!preg_match($re, $search)) {
  326. // this entry does _not_ match our regex
  327. continue;
  328. }
  329. $filtered[$key] = $link;
  330. }
  331. return $filtered;
  332. }
  333. /**
  334. * Return only links without any tag.
  335. *
  336. * @param string $visibility return only all/private/public links.
  337. *
  338. * @return array filtered links.
  339. */
  340. public function filterUntagged($visibility)
  341. {
  342. $filtered = [];
  343. foreach ($this->links as $key => $link) {
  344. if ($visibility !== 'all') {
  345. if (! $link['private'] && $visibility === 'private') {
  346. continue;
  347. } elseif ($link['private'] && $visibility === 'public') {
  348. continue;
  349. }
  350. }
  351. if (empty(trim($link['tags']))) {
  352. $filtered[$key] = $link;
  353. }
  354. }
  355. return $filtered;
  356. }
  357. /**
  358. * Returns the list of articles for a given day, chronologically sorted
  359. *
  360. * Day must be in the form 'YYYYMMDD' (e.g. '20120125'), e.g.
  361. * print_r($mydb->filterDay('20120125'));
  362. *
  363. * @param string $day day to filter.
  364. *
  365. * @return array all link matching given day.
  366. *
  367. * @throws Exception if date format is invalid.
  368. */
  369. public function filterDay($day)
  370. {
  371. if (! checkDateFormat('Ymd', $day)) {
  372. throw new Exception('Invalid date format');
  373. }
  374. $filtered = array();
  375. foreach ($this->links as $key => $l) {
  376. if ($l['created']->format('Ymd') == $day) {
  377. $filtered[$key] = $l;
  378. }
  379. }
  380. // sort by date ASC
  381. return array_reverse($filtered, true);
  382. }
  383. /**
  384. * Convert a list of tags (str) to an array. Also
  385. * - handle case sensitivity.
  386. * - accepts spaces commas as separator.
  387. *
  388. * @param string $tags string containing a list of tags.
  389. * @param bool $casesensitive will convert everything to lowercase if false.
  390. *
  391. * @return array filtered tags string.
  392. */
  393. public static function tagsStrToArray($tags, $casesensitive)
  394. {
  395. // We use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
  396. $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8');
  397. $tagsOut = str_replace(',', ' ', $tagsOut);
  398. return preg_split('/\s+/', $tagsOut, -1, PREG_SPLIT_NO_EMPTY);
  399. }
  400. }
  401. class LinkNotFoundException extends Exception
  402. {
  403. /**
  404. * LinkNotFoundException constructor.
  405. */
  406. public function __construct()
  407. {
  408. $this->message = t('The link you are trying to reach does not exist or has been deleted.');
  409. }
  410. }