PageRenderTime 28ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/inc/lib/Zend/Search/Lucene/Search/Query/Wildcard.php

https://bitbucket.org/yoander/mtrack
PHP | 362 lines | 167 code | 50 blank | 145 comment | 40 complexity | cd4ecb8ea7f72473ff60ca98140a8547 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Search_Lucene
  17. * @subpackage Search
  18. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Wildcard.php 23775 2011-03-01 17:25:24Z ralph $
  21. */
  22. /** Zend_Search_Lucene_Search_Query */
  23. require_once 'Zend/Search/Lucene/Search/Query.php';
  24. /**
  25. * @category Zend
  26. * @package Zend_Search_Lucene
  27. * @subpackage Search
  28. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  29. * @license http://framework.zend.com/license/new-bsd New BSD License
  30. */
  31. class Zend_Search_Lucene_Search_Query_Wildcard extends Zend_Search_Lucene_Search_Query
  32. {
  33. /**
  34. * Search pattern.
  35. *
  36. * Field has to be fully specified or has to be null
  37. * Text may contain '*' or '?' symbols
  38. *
  39. * @var Zend_Search_Lucene_Index_Term
  40. */
  41. private $_pattern;
  42. /**
  43. * Matched terms.
  44. *
  45. * Matched terms list.
  46. * It's filled during the search (rewrite operation) and may be used for search result
  47. * post-processing
  48. *
  49. * Array of Zend_Search_Lucene_Index_Term objects
  50. *
  51. * @var array
  52. */
  53. private $_matches = null;
  54. /**
  55. * Minimum term prefix length (number of minimum non-wildcard characters)
  56. *
  57. * @var integer
  58. */
  59. private static $_minPrefixLength = 3;
  60. /**
  61. * Zend_Search_Lucene_Search_Query_Wildcard constructor.
  62. *
  63. * @param Zend_Search_Lucene_Index_Term $pattern
  64. */
  65. public function __construct(Zend_Search_Lucene_Index_Term $pattern)
  66. {
  67. $this->_pattern = $pattern;
  68. }
  69. /**
  70. * Get minimum prefix length
  71. *
  72. * @return integer
  73. */
  74. public static function getMinPrefixLength()
  75. {
  76. return self::$_minPrefixLength;
  77. }
  78. /**
  79. * Set minimum prefix length
  80. *
  81. * @param integer $minPrefixLength
  82. */
  83. public static function setMinPrefixLength($minPrefixLength)
  84. {
  85. self::$_minPrefixLength = $minPrefixLength;
  86. }
  87. /**
  88. * Get terms prefix
  89. *
  90. * @param string $word
  91. * @return string
  92. */
  93. private static function _getPrefix($word)
  94. {
  95. $questionMarkPosition = strpos($word, '?');
  96. $astrericPosition = strpos($word, '*');
  97. if ($questionMarkPosition !== false) {
  98. if ($astrericPosition !== false) {
  99. return substr($word, 0, min($questionMarkPosition, $astrericPosition));
  100. }
  101. return substr($word, 0, $questionMarkPosition);
  102. } else if ($astrericPosition !== false) {
  103. return substr($word, 0, $astrericPosition);
  104. }
  105. return $word;
  106. }
  107. /**
  108. * Re-write query into primitive queries in the context of specified index
  109. *
  110. * @param Zend_Search_Lucene_Interface $index
  111. * @return Zend_Search_Lucene_Search_Query
  112. * @throws Zend_Search_Lucene_Exception
  113. */
  114. public function rewrite(Zend_Search_Lucene_Interface $index)
  115. {
  116. $this->_matches = array();
  117. if ($this->_pattern->field === null) {
  118. // Search through all fields
  119. $fields = $index->getFieldNames(true /* indexed fields list */);
  120. } else {
  121. $fields = array($this->_pattern->field);
  122. }
  123. $prefix = self::_getPrefix($this->_pattern->text);
  124. $prefixLength = strlen($prefix);
  125. $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';
  126. if ($prefixLength < self::$_minPrefixLength) {
  127. require_once 'Zend/Search/Lucene/Exception.php';
  128. throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard characters are required at the beginning of pattern.');
  129. }
  130. /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */
  131. if (@preg_match('/\pL/u', 'a') == 1) {
  132. // PCRE unicode support is turned on
  133. // add Unicode modifier to the match expression
  134. $matchExpression .= 'u';
  135. }
  136. $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit();
  137. foreach ($fields as $field) {
  138. $index->resetTermsStream();
  139. require_once 'Zend/Search/Lucene/Index/Term.php';
  140. if ($prefix != '') {
  141. $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field));
  142. while ($index->currentTerm() !== null &&
  143. $index->currentTerm()->field == $field &&
  144. substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) {
  145. if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
  146. $this->_matches[] = $index->currentTerm();
  147. if ($maxTerms != 0 && count($this->_matches) > $maxTerms) {
  148. require_once 'Zend/Search/Lucene/Exception.php';
  149. throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
  150. }
  151. }
  152. $index->nextTerm();
  153. }
  154. } else {
  155. $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field));
  156. while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) {
  157. if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
  158. $this->_matches[] = $index->currentTerm();
  159. if ($maxTerms != 0 && count($this->_matches) > $maxTerms) {
  160. require_once 'Zend/Search/Lucene/Exception.php';
  161. throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
  162. }
  163. }
  164. $index->nextTerm();
  165. }
  166. }
  167. $index->closeTermsStream();
  168. }
  169. if (count($this->_matches) == 0) {
  170. require_once 'Zend/Search/Lucene/Search/Query/Empty.php';
  171. return new Zend_Search_Lucene_Search_Query_Empty();
  172. } else if (count($this->_matches) == 1) {
  173. require_once 'Zend/Search/Lucene/Search/Query/Term.php';
  174. return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches));
  175. } else {
  176. require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
  177. $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
  178. foreach ($this->_matches as $matchedTerm) {
  179. $rewrittenQuery->addTerm($matchedTerm);
  180. }
  181. return $rewrittenQuery;
  182. }
  183. }
  184. /**
  185. * Optimize query in the context of specified index
  186. *
  187. * @param Zend_Search_Lucene_Interface $index
  188. * @return Zend_Search_Lucene_Search_Query
  189. */
  190. public function optimize(Zend_Search_Lucene_Interface $index)
  191. {
  192. require_once 'Zend/Search/Lucene/Exception.php';
  193. throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
  194. }
  195. /**
  196. * Returns query pattern
  197. *
  198. * @return Zend_Search_Lucene_Index_Term
  199. */
  200. public function getPattern()
  201. {
  202. return $this->_pattern;
  203. }
  204. /**
  205. * Return query terms
  206. *
  207. * @return array
  208. * @throws Zend_Search_Lucene_Exception
  209. */
  210. public function getQueryTerms()
  211. {
  212. if ($this->_matches === null) {
  213. require_once 'Zend/Search/Lucene/Exception.php';
  214. throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms');
  215. }
  216. return $this->_matches;
  217. }
  218. /**
  219. * Constructs an appropriate Weight implementation for this query.
  220. *
  221. * @param Zend_Search_Lucene_Interface $reader
  222. * @return Zend_Search_Lucene_Search_Weight
  223. * @throws Zend_Search_Lucene_Exception
  224. */
  225. public function createWeight(Zend_Search_Lucene_Interface $reader)
  226. {
  227. require_once 'Zend/Search/Lucene/Exception.php';
  228. throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
  229. }
  230. /**
  231. * Execute query in context of index reader
  232. * It also initializes necessary internal structures
  233. *
  234. * @param Zend_Search_Lucene_Interface $reader
  235. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  236. * @throws Zend_Search_Lucene_Exception
  237. */
  238. public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
  239. {
  240. require_once 'Zend/Search/Lucene/Exception.php';
  241. throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
  242. }
  243. /**
  244. * Get document ids likely matching the query
  245. *
  246. * It's an array with document ids as keys (performance considerations)
  247. *
  248. * @return array
  249. * @throws Zend_Search_Lucene_Exception
  250. */
  251. public function matchedDocs()
  252. {
  253. require_once 'Zend/Search/Lucene/Exception.php';
  254. throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
  255. }
  256. /**
  257. * Score specified document
  258. *
  259. * @param integer $docId
  260. * @param Zend_Search_Lucene_Interface $reader
  261. * @return float
  262. * @throws Zend_Search_Lucene_Exception
  263. */
  264. public function score($docId, Zend_Search_Lucene_Interface $reader)
  265. {
  266. require_once 'Zend/Search/Lucene/Exception.php';
  267. throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
  268. }
  269. /**
  270. * Query specific matches highlighting
  271. *
  272. * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
  273. */
  274. protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter)
  275. {
  276. $words = array();
  277. $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';
  278. if (@preg_match('/\pL/u', 'a') == 1) {
  279. // PCRE unicode support is turned on
  280. // add Unicode modifier to the match expression
  281. $matchExpression .= 'u';
  282. }
  283. $docBody = $highlighter->getDocument()->getFieldUtf8Value('body');
  284. require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';
  285. $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8');
  286. foreach ($tokens as $token) {
  287. if (preg_match($matchExpression, $token->getTermText()) === 1) {
  288. $words[] = $token->getTermText();
  289. }
  290. }
  291. $highlighter->highlight($words);
  292. }
  293. /**
  294. * Print a query
  295. *
  296. * @return string
  297. */
  298. public function __toString()
  299. {
  300. // It's used only for query visualisation, so we don't care about characters escaping
  301. if ($this->_pattern->field !== null) {
  302. $query = $this->_pattern->field . ':';
  303. } else {
  304. $query = '';
  305. }
  306. $query .= $this->_pattern->text;
  307. if ($this->getBoost() != 1) {
  308. $query = $query . '^' . round($this->getBoost(), 4);
  309. }
  310. return $query;
  311. }
  312. }