LinkFilter.php 11 KB

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