TagLike.php 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. namespace Muzich\CoreBundle\Util;
  3. use Muzich\CoreBundle\Util\StrictCanonicalizer;
  4. use Doctrine\ORM\EntityManager;
  5. /**
  6. * Cette classe permet d'aider a la recherche de mot similaires a un mot
  7. *
  8. *
  9. */
  10. class TagLike
  11. {
  12. protected $entity_manager;
  13. public function __construct(EntityManager $entity_manager)
  14. {
  15. $this->entity_manager = $entity_manager;
  16. }
  17. /**
  18. * Ajoute le tag au début du tableau passé en paramètre si celui-ci
  19. * n'est pas a l'intérieur.
  20. *
  21. * @param array $array
  22. * @param Tag $tag
  23. * @return array
  24. */
  25. private function sort_addtop_if_isnt_in($array, $tag)
  26. {
  27. $in = false;
  28. for ($x=0;$x<=sizeof($array)-1;$x++)
  29. {
  30. if ($array[$x]['id'] == $tag['id'])
  31. {
  32. $in = true;
  33. break;
  34. }
  35. }
  36. if (!$in)
  37. {
  38. array_unshift($array, $tag);
  39. return $array;
  40. }
  41. return $array;
  42. }
  43. /**
  44. * Ajoute le tag a al fin du tableau passé en paramètre si celui-ci
  45. * n'est pas a l'intérieur.
  46. *
  47. * @param array $array
  48. * @param Tag $tag
  49. * @return array
  50. */
  51. private function sort_addbottom_if_isnt_in($array, $tag)
  52. {
  53. $in = false;
  54. for ($x=0;$x<=sizeof($array)-1;$x++)
  55. {
  56. if ($array[$x]['id'] == $tag['id'])
  57. {
  58. $in = true;
  59. break;
  60. }
  61. }
  62. if (!$in)
  63. {
  64. $array[] = $tag;
  65. return $array;
  66. }
  67. return $array;
  68. }
  69. /**
  70. * Construit un tableau de mot a partir du terme de recherche. Ces mots
  71. * permettrons la recherche de tags en base et le trie des tags trouvé.
  72. *
  73. * La déduction de ces mot est basé sur:
  74. * * Le remplacement des espaces par des tirets et inversement (virgules aussi)
  75. *
  76. * Et chaque mot doit dépasser deux caractères
  77. *
  78. * @param string $search
  79. * @return array
  80. */
  81. protected function getSearchWordsReplacing($search)
  82. {
  83. // En base les tags sont composé de mot a '-' ou a ' '.
  84. $words = array_unique(array(
  85. str_replace(' ', '-', $search),
  86. str_replace('-', ' ', $search),
  87. str_replace(',', ' ', $search),
  88. str_replace(', ', ' ', $search),
  89. str_replace(',', '-', $search),
  90. str_replace(', ', '-', $search),
  91. str_replace(' & ', ' AND ', $search)
  92. ));
  93. return $words;
  94. }
  95. /**
  96. * Construit un tableau de mot a partir du terme de recherche. Ces mots
  97. * permettrons la recherche de tags en base et le trie des tags trouvé.
  98. *
  99. * La déduction de ces mot est basé sur:
  100. * * La découpe du terme par espaces, tirets et virgules
  101. *
  102. * Et chaque mot doit dépasser deux caractères
  103. *
  104. * @param string $search
  105. */
  106. protected function getSearchWordsExploding($search)
  107. {
  108. $words = array_unique(array_merge(
  109. explode(' ', $search),
  110. explode('-', $search),
  111. explode('- ', $search),
  112. explode(' -', $search),
  113. explode(' - ', $search),
  114. explode(',', $search),
  115. explode(', ', $search),
  116. explode(' ,', $search),
  117. explode(' , ', $search)
  118. ));
  119. $words_filetereds = array();
  120. foreach ($words as $i => $word)
  121. {
  122. if (trim(strlen($word)) > 1)
  123. {
  124. $words_filetereds[] = trim($word);
  125. }
  126. }
  127. return $words_filetereds;
  128. }
  129. /**
  130. * Recherche en base les tags ressemblant a la recherche.
  131. *
  132. * @param array $words
  133. * @param int $user_id
  134. * @return array
  135. */
  136. protected function searchTags($words, $user_id)
  137. {
  138. $where = '';
  139. $params = array();
  140. foreach ($words as $i => $word)
  141. {
  142. if ($where == '')
  143. {
  144. $where .= 'WHERE UPPER(t.slug) LIKE :str'.$i;
  145. }
  146. else
  147. {
  148. $where .= ' OR UPPER(t.slug) LIKE :str'.$i;
  149. }
  150. $params['str'.$i] = '%'.$word.'%';
  151. }
  152. $private_tags_sql = '';
  153. if ($user_id)
  154. {
  155. $params['uid'] = '%"'.$user_id.'"%';
  156. $private_tags_sql = 'OR t.privateids LIKE :uid';
  157. }
  158. $tags_query = $this->entity_manager->createQuery("
  159. SELECT t.name, t.slug, t.id FROM MuzichCoreBundle:Tag t
  160. $where
  161. AND (t.tomoderate = '0' OR t.tomoderate IS NULL
  162. $private_tags_sql)
  163. ORDER BY t.name ASC"
  164. )
  165. ->setParameters($params)
  166. ->getScalarResult()
  167. ;
  168. $tags = array();
  169. foreach ($tags_query as $tag)
  170. {
  171. $tags[] = array(
  172. 'name' => $tag['name'],
  173. 'id' => $tag['id'],
  174. 'slug' => $tag['slug']
  175. );
  176. }
  177. return $tags;
  178. }
  179. /**
  180. * Trie les tags de manière a ce que les tags les plus ressemblant a la
  181. * recherche soient au début du tableau.
  182. *
  183. * @param array $tags
  184. * @param array $search
  185. * @param array $words
  186. * @param array $words_replacing
  187. * @param array $words_exploding
  188. * @return array
  189. */
  190. protected function sortTags($tags, $search, $words, $words_replacing, $words_exploding)
  191. {
  192. $same_found = false;
  193. $tag_sorted = array();
  194. /*
  195. * Première passe: Pas plus de trois caractères différents de la recherche
  196. * On se base ici sur le recherche non découpé
  197. */
  198. foreach ($tags as $i => $tag)
  199. {
  200. foreach ($words_replacing as $word)
  201. {
  202. $word = trim($word);
  203. if (strlen($word) > 1)
  204. {
  205. if (
  206. strlen(str_replace($word, '', strtoupper($tag['slug']))) < 4
  207. // Si on tombe sur le même nom, il ne faut pas le mettre en haut maintenant
  208. // ou il se fera décallé vers le bas
  209. && $word != $search
  210. )
  211. {
  212. $tag_sorted = $this->sort_addtop_if_isnt_in($tag_sorted, $tag);
  213. }
  214. }
  215. }
  216. }
  217. /*
  218. * Pour une recherche en plusieurs mots, on cherche la similitude avec
  219. * des tags. De façon a ce que "dark psytrance" soit reconnue comme proche de
  220. * "psytrance dark".
  221. */
  222. if (count($words_exploding) > 1)
  223. {
  224. $tags_counteds = array();
  225. /*
  226. * Pour chaque mot qui compose la recherche on regarde si ce mot
  227. * est compris dans un des tags
  228. */
  229. foreach ($tags as $i => $tag)
  230. {
  231. foreach ($words_exploding as $word)
  232. {
  233. if (strpos(strtoupper($tag['slug']), $word) !== false)
  234. {
  235. $count = 1;
  236. if (array_key_exists($tag['id'], $tags_counteds))
  237. {
  238. $count = ($tags_counteds[$tag['id']]['count'])+1;
  239. }
  240. $tags_counteds[$tag['id']] = array(
  241. 'count' => $count,
  242. 'tag' => $tag
  243. );
  244. }
  245. }
  246. }
  247. /*
  248. * Maintenant que l'on a un tableau contenant les tags comportant au moins
  249. * un mot identique a recherche
  250. */
  251. foreach ($tags_counteds as $id => $counted)
  252. {
  253. // Si le tag a eu plus d'une fois le même mot
  254. if ($counted['count'] > 1)
  255. {
  256. // Ci-dessous on va chercher a voir si le tag et la recherche on le
  257. // même nombre de mots, si c'est le cas on pourra considérer cette
  258. // recherche comme lié a un tag connu.
  259. if (count($words_exploding) == count($this->getSearchWordsExploding($counted['tag']['slug'])))
  260. {
  261. $same_found = true;
  262. }
  263. // Cette verif permet de ne pas ajouter les tags qui n'ont qu'un mot
  264. // Si on ajouté ce tag maintenant il ne serais pas ajouté au controle en dessous
  265. // (nom identique) et donc pas au dessus.
  266. $tag_sorted = $this->sort_addtop_if_isnt_in($tag_sorted, $counted['tag']);
  267. }
  268. }
  269. }
  270. /*
  271. * On recherche maintenant les noms de tags identique a la recherche
  272. */
  273. foreach ($tags as $i => $tag)
  274. {
  275. foreach ($words_replacing as $word)
  276. {
  277. if ($word == strtoupper($tag['slug']))
  278. {
  279. // Ci-dessous on déduit si le mot est identique au tag .
  280. // De façon a ce que si c'est le cas, pouvoir dire:
  281. // oui le terme recherché est connu.
  282. if (in_array($word, $words_replacing))
  283. {
  284. $same_found = true;
  285. }
  286. $tag_sorted = $this->sort_addtop_if_isnt_in($tag_sorted, $tag);
  287. }
  288. }
  289. }
  290. foreach ($tags as $i => $tag)
  291. {
  292. $tag_sorted = $this->sort_addbottom_if_isnt_in($tag_sorted, $tag);
  293. }
  294. return array(
  295. 'tags' => $tag_sorted,
  296. 'same_found' => $same_found
  297. );
  298. }
  299. public function getSimilarTags($search, $user_id)
  300. {
  301. $canonicalizer = new StrictCanonicalizer();
  302. $search = strtoupper($canonicalizer->canonicalize(trim($search)));
  303. if (strlen($search) < 2)
  304. {
  305. // Le terme de recherche doit faire au moins 2 caractéres
  306. return array('tags' => array(), 'same_found' => false);
  307. }
  308. $words_e = $this->getSearchWordsExploding($search);
  309. $words_r = $this->getSearchWordsReplacing($search);
  310. $words = array_unique(array_merge($words_e, $words_r));
  311. $tags = $this->searchTags($words, $user_id);
  312. return $this->sortTags($tags, $search, $words, $words_r, $words_e);
  313. }
  314. }