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