source: trunk/include/functions_search.inc.php @ 28066

Last change on this file since 28066 was 28066, checked in by rvelices, 10 years ago

bug 3056: quick search - fixes and better numeric range searches examples:
ratio:0.9..1.1
ratio:0.9..
ratio:>0.9
ratio:<1.1
ratio:>3/2
ratio:16/9

  • Property svn:eol-style set to LF
File size: 33.5 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**
25 * @package functions\search
26 */
27
28
29/**
30 * Returns search rules stored into a serialized array in "search"
31 * table. Each search rules set is numericaly identified.
32 *
33 * @param int $search_id
34 * @return array
35 */
36function get_search_array($search_id)
37{
38  if (!is_numeric($search_id))
39  {
40    die('Search id must be an integer');
41  }
42
43  $query = '
44SELECT rules
45  FROM '.SEARCH_TABLE.'
46  WHERE id = '.$search_id.'
47;';
48  list($serialized_rules) = pwg_db_fetch_row(pwg_query($query));
49
50  return unserialize($serialized_rules);
51}
52
53/**
54 * Returns the SQL clause for a search.
55 * Transforms the array returned by get_search_array() into SQL sub-query.
56 *
57 * @param array $search
58 * @return string
59 */
60function get_sql_search_clause($search)
61{
62  // SQL where clauses are stored in $clauses array during query
63  // construction
64  $clauses = array();
65
66  foreach (array('file','name','comment','author') as $textfield)
67  {
68    if (isset($search['fields'][$textfield]))
69    {
70      $local_clauses = array();
71      foreach ($search['fields'][$textfield]['words'] as $word)
72      {
73        $local_clauses[] = $textfield." LIKE '%".$word."%'";
74      }
75
76      // adds brackets around where clauses
77      $local_clauses = prepend_append_array_items($local_clauses, '(', ')');
78
79      $clauses[] = implode(
80        ' '.$search['fields'][$textfield]['mode'].' ',
81        $local_clauses
82        );
83    }
84  }
85
86  if (isset($search['fields']['allwords']))
87  {
88    $fields = array('file', 'name', 'comment', 'author');
89    // in the OR mode, request bust be :
90    // ((field1 LIKE '%word1%' OR field2 LIKE '%word1%')
91    // OR (field1 LIKE '%word2%' OR field2 LIKE '%word2%'))
92    //
93    // in the AND mode :
94    // ((field1 LIKE '%word1%' OR field2 LIKE '%word1%')
95    // AND (field1 LIKE '%word2%' OR field2 LIKE '%word2%'))
96    $word_clauses = array();
97    foreach ($search['fields']['allwords']['words'] as $word)
98    {
99      $field_clauses = array();
100      foreach ($fields as $field)
101      {
102        $field_clauses[] = $field." LIKE '%".$word."%'";
103      }
104      // adds brackets around where clauses
105      $word_clauses[] = implode(
106        "\n          OR ",
107        $field_clauses
108        );
109    }
110
111    array_walk(
112      $word_clauses,
113      create_function('&$s','$s="(".$s.")";')
114      );
115
116    // make sure the "mode" is either OR or AND
117    if ($search['fields']['allwords']['mode'] != 'AND' and $search['fields']['allwords']['mode'] != 'OR')
118    {
119      $search['fields']['allwords']['mode'] = 'AND';
120    }
121
122    $clauses[] = "\n         ".
123      implode(
124        "\n         ". $search['fields']['allwords']['mode']. "\n         ",
125        $word_clauses
126        );
127  }
128
129  foreach (array('date_available', 'date_creation') as $datefield)
130  {
131    if (isset($search['fields'][$datefield]))
132    {
133      $clauses[] = $datefield." = '".$search['fields'][$datefield]['date']."'";
134    }
135
136    foreach (array('after','before') as $suffix)
137    {
138      $key = $datefield.'-'.$suffix;
139
140      if (isset($search['fields'][$key]))
141      {
142        $clauses[] = $datefield.
143          ($suffix == 'after'             ? ' >' : ' <').
144          ($search['fields'][$key]['inc'] ? '='  : '').
145          " '".$search['fields'][$key]['date']."'";
146      }
147    }
148  }
149
150  if (isset($search['fields']['cat']))
151  {
152    if ($search['fields']['cat']['sub_inc'])
153    {
154      // searching all the categories id of sub-categories
155      $cat_ids = get_subcat_ids($search['fields']['cat']['words']);
156    }
157    else
158    {
159      $cat_ids = $search['fields']['cat']['words'];
160    }
161
162    $local_clause = 'category_id IN ('.implode(',', $cat_ids).')';
163    $clauses[] = $local_clause;
164  }
165
166  // adds brackets around where clauses
167  $clauses = prepend_append_array_items($clauses, '(', ')');
168
169  $where_separator =
170    implode(
171      "\n    ".$search['mode'].' ',
172      $clauses
173      );
174
175  $search_clause = $where_separator;
176
177  return $search_clause;
178}
179
180/**
181 * Returns the list of items corresponding to the advanced search array.
182 *
183 * @param array $search
184 * @param string $images_where optional additional restriction on images table
185 * @return array
186 */
187function get_regular_search_results($search, $images_where='')
188{
189  global $conf;
190  $forbidden = get_sql_condition_FandF(
191        array
192          (
193            'forbidden_categories' => 'category_id',
194            'visible_categories' => 'category_id',
195            'visible_images' => 'id'
196          ),
197        "\n  AND"
198    );
199
200  $items = array();
201  $tag_items = array();
202
203  if (isset($search['fields']['tags']))
204  {
205    $tag_items = get_image_ids_for_tags(
206      $search['fields']['tags']['words'],
207      $search['fields']['tags']['mode']
208      );
209  }
210
211  $search_clause = get_sql_search_clause($search);
212
213  if (!empty($search_clause))
214  {
215    $query = '
216SELECT DISTINCT(id)
217  FROM '.IMAGES_TABLE.' i
218    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
219  WHERE '.$search_clause;
220    if (!empty($images_where))
221    {
222      $query .= "\n  AND ".$images_where;
223    }
224    $query .= $forbidden.'
225  '.$conf['order_by'];
226    $items = array_from_query($query, 'id');
227  }
228
229  if ( !empty($tag_items) )
230  {
231    switch ($search['mode'])
232    {
233      case 'AND':
234        if (empty($search_clause))
235        {
236          $items = $tag_items;
237        }
238        else
239        {
240          $items = array_values( array_intersect($items, $tag_items) );
241        }
242        break;
243      case 'OR':
244        $before_count = count($items);
245        $items = array_unique(
246          array_merge(
247            $items,
248            $tag_items
249            )
250          );
251        break;
252    }
253  }
254
255  return $items;
256}
257
258/**
259 * Finds if a char is a letter, a figure or any char of the extended ASCII table (>127).
260 *
261 * @param char $ch
262 * @return bool
263 */
264function is_word_char($ch)
265{
266  return ($ch>='0' && $ch<='9') || ($ch>='a' && $ch<='z') || ($ch>='A' && $ch<='Z') || ord($ch)>127;
267}
268
269/**
270 * Finds if a char is a special token for word start: [{<=*+
271 *
272 * @param char $ch
273 * @return bool
274 */
275function is_odd_wbreak_begin($ch)
276{
277  return strpos('[{<=*+', $ch)===false ? false:true;
278}
279
280/**
281 * Finds if a char is a special token for word end: ]}>=*+
282 *
283 * @param char $ch
284 * @return bool
285 */
286function is_odd_wbreak_end($ch)
287{
288  return strpos(']}>=*+', $ch)===false ? false:true;
289}
290
291
292define('QST_QUOTED',         0x01);
293define('QST_NOT',            0x02);
294define('QST_OR',             0x04);
295define('QST_WILDCARD_BEGIN', 0x08);
296define('QST_WILDCARD_END',   0x10);
297define('QST_WILDCARD', QST_WILDCARD_BEGIN|QST_WILDCARD_END);
298
299
300class QSearchScope
301{
302  var $id;
303  var $aliases;
304  var $is_text;
305  var $allow_empty;
306
307  function __construct($id, $aliases, $allow_empty=false, $is_text=true)
308  {
309    $this->id = $id;
310    $this->aliases = $aliases;
311    $this->is_text = $is_text;
312    $this->allow_empty =$allow_empty;
313  }
314}
315
316class QNumericRangeScope extends QSearchScope
317{
318  private $epsilon;
319  function __construct($id, $aliases, $allow_empty=false, $epsilon=0)
320  {
321    parent::__construct($id, $aliases, $allow_empty, false);
322    $this->epsilon = $epsilon;
323  }
324
325  function parse($token)
326  {
327    $str = $token->term;
328    if ( ($pos = strpos($str, '..')) !== false)
329      $range = array( substr($str,0,$pos), substr($str, $pos+2));
330    else
331    {
332      if ('>' == @$str[0])// ratio:>1
333        $range = array( substr($str,1), '');
334      elseif ('<' == @$str[0]) // size:<5mp
335        $range = array('', substr($str,1));
336      else
337        $range = array($str, $str);
338    }
339
340    foreach ($range as $i =>&$val)
341    {
342      if (preg_match('#^([0-9.]+)/([0-9.]+)$#i', $val, $matches))
343      {
344        $val = floatval($matches[1]/$matches[2]);
345      }
346      elseif (preg_match('/^([0-9.]+)([km])?/i', $val, $matches))
347      {
348        $val = floatval($matches[1]);
349        if (isset($matches[2]))
350        {
351          if ($matches[2]=='k' || $matches[2]=='K')
352          {
353            $val *= 1000;
354            if ($i) $val += 999;
355          }
356          if ($matches[2]=='m' || $matches[2]=='M')
357          {
358            $val *= 1000000;
359            if ($i) $val += 999999;
360          }
361        }
362      }
363      else
364        $val = '';
365      if (is_numeric($val))
366      {
367        if ($i)
368          $val += $this->epsilon;
369        else
370          $val -= $this->epsilon;
371      }
372    }
373
374    if (!$this->allow_empty && $range[0]=='' && $range[1] == '')
375      return false;
376    $token->scope_data = $range;
377    return true;
378  }
379
380  function get_sql($field, $token)
381  {
382    $clauses = array();
383    if ($token->scope_data[0]!=='')
384      $clauses[] = $field.' >= ' .$token->scope_data[0].' ';
385    if ($token->scope_data[1]!=='')
386      $clauses[] = $field.' <= ' .$token->scope_data[1].' ';
387
388    if (empty($clauses))
389      return $field.' IS NULL';
390    return '('.implode(' AND ', $clauses).')';
391  }
392}
393
394/**
395 * Analyzes and splits the quick/query search query $q into tokens.
396 * q='john bill' => 2 tokens 'john' 'bill'
397 * Special characters for MySql full text search (+,<,>,~) appear in the token modifiers.
398 * The query can contain a phrase: 'Pierre "New York"' will return 'pierre' qnd 'new york'.
399 *
400 * @param string $q
401 */
402
403/** Represents a single word or quoted phrase to be searched.*/
404class QSingleToken
405{
406  var $is_single = true;
407  var $modifier;
408  var $term; /* the actual word/phrase string*/
409  var $scope;
410
411  var $scope_data;
412  var $idx;
413
414  function __construct($term, $modifier, $scope)
415  {
416    $this->term = $term;
417    $this->modifier = $modifier;
418    $this->scope = $scope;
419  }
420
421  function __toString()
422  {
423    $s = '';
424    if (isset($this->scope))
425      $s .= $this->scope->id .':';
426    if ($this->modifier & QST_WILDCARD_BEGIN)
427      $s .= '*';
428    if ($this->modifier & QST_QUOTED)
429      $s .= '"';
430    $s .= $this->term;
431    if ($this->modifier & QST_QUOTED)
432      $s .= '"';
433    if ($this->modifier & QST_WILDCARD_END)
434      $s .= '*';
435    return $s;
436  }
437}
438
439/** Represents an expression of several words or sub expressions to be searched.*/
440class QMultiToken
441{
442  var $is_single = false;
443  var $modifier;
444  var $tokens = array(); // the actual array of QSingleToken or QMultiToken
445
446  function __toString()
447  {
448    $s = '';
449    for ($i=0; $i<count($this->tokens); $i++)
450    {
451      $modifier = $this->tokens[$i]->modifier;
452      if ($i)
453        $s .= ' ';
454      if ($modifier & QST_OR)
455        $s .= 'OR ';
456      if ($modifier & QST_NOT)
457        $s .= 'NOT ';
458      if (! ($this->tokens[$i]->is_single) )
459      {
460        $s .= '(';
461        $s .= $this->tokens[$i];
462        $s .= ')';
463      }
464      else
465      {
466        $s .= $this->tokens[$i];
467      }
468    }
469    return $s;
470  }
471
472  private function push(&$token, &$modifier, &$scope)
473  {
474    if (strlen($token) || (isset($scope) && $scope->allow_empty))
475    {
476      $this->tokens[] = new QSingleToken($token, $modifier, $scope);
477    }
478    $token = "";
479    $modifier = 0;
480    $scope = null;
481  }
482
483  /**
484  * Parses the input query string by tokenizing the input, generating the modifiers (and/or/not/quotation/wildcards...).
485  * Recursivity occurs when parsing ()
486  * @param string $q the actual query to be parsed
487  * @param int $qi the character index in $q where to start parsing
488  * @param int $level the depth from root in the tree (number of opened and unclosed opening brackets)
489  */
490  protected function parse_expression($q, &$qi, $level, $root)
491  {
492    $crt_token = "";
493    $crt_modifier = 0;
494    $crt_scope = null;
495
496    for ($stop=false; !$stop && $qi<strlen($q); $qi++)
497    {
498      $ch = $q[$qi];
499      if ( ($crt_modifier&QST_QUOTED)==0)
500      {
501        switch ($ch)
502        {
503          case '(':
504            if (strlen($crt_token))
505              $this->push($crt_token, $crt_modifier, $crt_scope);
506            $sub = new QMultiToken;
507            $qi++;
508            $sub->parse_expression($q, $qi, $level+1, $root);
509            $sub->modifier = $crt_modifier;
510            if (isset($crt_scope) && $crt_scope->is_text)
511            {
512              $sub->apply_scope($crt_scope); // eg. 'tag:(John OR Bill)'
513            }
514            $this->tokens[] = $sub;
515            $crt_modifier = 0;
516            $crt_scope = null;
517            break;
518          case ')':
519            if ($level>0)
520              $stop = true;
521            break;
522          case ':':
523            $scope = @$root->scopes[$crt_token];
524            if (!isset($scope) || isset($crt_scope))
525            { // white space
526              $this->push($crt_token, $crt_modifier, $crt_scope);
527            }
528            else
529            {
530              $crt_token = "";
531              $crt_scope = $scope;
532            }
533            break;
534          case '"':
535            if (strlen($crt_token))
536              $this->push($crt_token, $crt_modifier, $crt_scope);
537            $crt_modifier |= QST_QUOTED;
538            break;
539          case '-':
540            if (strlen($crt_token) || isset($crt_scope))
541              $crt_token .= $ch;
542            else
543              $crt_modifier |= QST_NOT;
544            break;
545          case '*':
546            if (strlen($crt_token))
547              $crt_token .= $ch; // wildcard end later
548            else
549              $crt_modifier |= QST_WILDCARD_BEGIN;
550            break;
551          case '.':
552            if (isset($crt_scope) && !$crt_scope->is_text)
553            {
554              $crt_token .= $ch;
555              break;
556            }
557            // else white space go on..
558          default:
559            if (preg_match('/[\s,.;!\?]+/', $ch))
560            { // white space
561              if (strlen($crt_token))
562                $this->push($crt_token, $crt_modifier, $crt_scope);
563              $crt_modifier = 0;
564            }
565            else
566              $crt_token .= $ch;
567            break;
568        }
569      }
570      else
571      {// quoted
572        if ($ch=='"')
573        {
574          if ($qi+1 < strlen($q) && $q[$qi+1]=='*')
575          {
576            $crt_modifier |= QST_WILDCARD_END;
577            $qi++;
578          }
579          $this->push($crt_token, $crt_modifier, $crt_scope);
580        }
581        else
582          $crt_token .= $ch;
583      }
584    }
585
586    $this->push($crt_token, $crt_modifier, $crt_scope);
587
588    for ($i=0; $i<count($this->tokens); $i++)
589    {
590      $token = $this->tokens[$i];
591      $remove = false;
592      if ($token->is_single)
593      {
594        if (!isset($token->scope))
595        {
596          if ( ($token->modifier & QST_QUOTED)==0 )
597          {
598            if ('not' == strtolower($token->term))
599            {
600              if ($i+1 < count($this->tokens))
601                $this->tokens[$i+1]->modifier |= QST_NOT;
602              $token->term = "";
603            }
604            if ('or' == strtolower($token->term))
605            {
606              if ($i+1 < count($this->tokens))
607                $this->tokens[$i+1]->modifier |= QST_OR;
608              $token->term = "";
609            }
610            if ('and' == strtolower($token->term))
611            {
612              $token->term = "";
613            }
614            if ( substr($token->term, -1)=='*' )
615            {
616              $token->term = rtrim($token->term, '*');
617              $token->modifier |= QST_WILDCARD_END;
618            }
619          }
620          if (!strlen($token->term))
621            $remove = true;
622        }
623        elseif (!$token->scope->is_text)
624        {
625          if (!$token->scope->parse($token))
626            $remove = true;
627        }
628      }
629      else
630      {
631        if (!count($token->tokens))
632          $remove = true;
633      }
634      if ($remove)
635      {
636        array_splice($this->tokens, $i, 1);
637        $i--;
638      }
639    }
640  }
641
642  private function apply_scope(QSearchScope $scope)
643  {
644    for ($i=0; $i<count($this->tokens); $i++)
645    {
646      if ($this->tokens[$i]->is_single)
647      {
648        if (!isset($this->tokens[$i]->scope))
649          $this->tokens[$i]->scope = $scope;
650      }
651      else
652        $this->tokens[$i]->aooky_scope($scope);
653    }
654  }
655
656  private static function priority($modifier)
657  {
658    return $modifier & QST_OR ? 0 :1;
659  }
660
661  /* because evaluations occur left to right, we ensure that 'a OR b c d' is interpreted as 'a OR (b c d)'*/
662  protected function check_operator_priority()
663  {
664    for ($i=0; $i<count($this->tokens); $i++)
665    {
666      if (!$this->tokens[$i]->is_single)
667        $this->tokens[$i]->check_operator_priority();
668      if ($i==1)
669        $crt_prio = self::priority($this->tokens[$i]->modifier);
670      if ($i<=1)
671        continue;
672      $prio = self::priority($this->tokens[$i]->modifier);
673      if ($prio > $crt_prio)
674      {// e.g. 'a OR b c d' i=2, operator(c)=AND -> prio(AND) > prio(OR) = operator(b)
675        $term_count = 2; // at least b and c to be regrouped
676        for ($j=$i+1; $j<count($this->tokens); $j++)
677        {
678          if (self::priority($this->tokens[$j]->modifier) >= $prio)
679            $term_count++; // also take d
680          else
681            break;
682        }
683
684        $i--; // move pointer to b
685        // crate sub expression (b c d)
686        $sub = new QMultiToken;
687        $sub->tokens = array_splice($this->tokens, $i, $term_count);
688
689        // rewrite ourseleves as a (b c d)
690        array_splice($this->tokens, $i, 0, array($sub));
691        $sub->modifier = $sub->tokens[0]->modifier & QST_OR;
692        $sub->tokens[0]->modifier &= ~QST_OR;
693
694        $sub->check_operator_priority();
695      }
696      else
697        $crt_prio = $prio;
698    }
699  }
700}
701
702class QExpression extends QMultiToken
703{
704  var $scopes = array();
705  var $stokens = array();
706  var $stoken_modifiers = array();
707
708  function __construct($q, $scopes)
709  {
710    foreach ($scopes as $scope)
711    {
712      $this->scopes[$scope->id] = $scope;
713      foreach ($scope->aliases as $alias)
714        $this->scopes[strtolower($alias)] = $scope;
715    }
716    $i = 0;
717    $this->parse_expression($q, $i, 0, $this);
718    //manipulate the tree so that 'a OR b c' is the same as 'b c OR a'
719    $this->check_operator_priority();
720    $this->build_single_tokens($this, 0);
721  }
722
723  private function build_single_tokens(QMultiToken $expr, $this_is_not)
724  {
725    for ($i=0; $i<count($expr->tokens); $i++)
726    {
727      $token = $expr->tokens[$i];
728      $crt_is_not = ($token->modifier ^ $this_is_not) & QST_NOT; // no negation OR double negation -> no negation;
729
730      if ($token->is_single)
731      {
732        $token->idx = count($this->stokens);
733        $this->stokens[] = $token;
734
735        $modifier = $token->modifier;
736        if ($crt_is_not)
737          $modifier |= QST_NOT;
738        else
739          $modifier &= ~QST_NOT;
740        $this->stoken_modifiers[] = $modifier;
741      }
742      else
743        $this->build_single_tokens($token, $crt_is_not);
744    }
745  }
746}
747
748/**
749  Structure of results being filled from different tables
750*/
751class QResults
752{
753  var $all_tags;
754  var $tag_ids;
755  var $tag_iids;
756  var $images_iids;
757  var $iids;
758
759  var $variants;
760}
761
762function qsearch_get_images(QExpression $expr, QResults $qsr)
763{
764  $qsr->images_iids = array_fill(0, count($expr->stokens), array());
765
766  $inflector = null;
767  $lang_code = substr(get_default_language(),0,2);
768  include_once(PHPWG_ROOT_PATH.'include/inflectors/'.$lang_code.'.php');
769  $class_name = 'Inflector_'.$lang_code;
770  if (class_exists($class_name))
771  {
772    $inflector = new $class_name;
773  }
774
775  $query_base = 'SELECT id from '.IMAGES_TABLE.' i WHERE ';
776  for ($i=0; $i<count($expr->stokens); $i++)
777  {
778    $token = $expr->stokens[$i];
779    $term = $token->term;
780    $scope_id = isset($token->scope) ? $token->scope->id : 'photo';
781    $clauses = array();
782
783    $like = addslashes($term);
784    $like = str_replace( array('%','_'), array('\\%','\\_'), $like); // escape LIKE specials %_
785    $file_like = 'CONVERT(file, CHAR) LIKE \'%'.$like.'%\'';
786
787    switch ($scope_id)
788    {
789      case 'photo':
790        $clauses[] = $file_like;
791
792        if ($inflector!=null && strlen($term)>2
793          && ($expr->stoken_modifiers[$i] & (QST_QUOTED|QST_WILDCARD))==0
794          && strcspn($term, '\'0123456789') == strlen($term)
795          )
796        {
797          $variants = array_unique( array_diff( $inflector->get_variants($term), array($term) ) );
798          $qsr->variants[$term] = $variants;
799        }
800        else
801        {
802          $variants = array();
803        }
804
805        if (strlen($term)>3) // default minimum full text index
806        {
807          $ft = $term;
808          if ($expr->stoken_modifiers[$i] & QST_QUOTED)
809            $ft = '"'.$ft.'"';
810          if ($expr->stoken_modifiers[$i] & QST_WILDCARD_END)
811            $ft .= '*';
812          foreach ($variants as $variant)
813          {
814            $ft.=' '.$variant;
815          }
816          $clauses[] = 'MATCH(i.name, i.comment) AGAINST( \''.addslashes($ft).'\' IN BOOLEAN MODE)';
817        }
818        else
819        {
820          foreach( array('i.name', 'i.comment') as $field)
821          {
822            $clauses[] = $field.' REGEXP \'[[:<:]]'.addslashes(preg_quote($term)).'[[:>:]]\'';
823          }
824        }
825        break;
826
827      case 'file':
828        $clauses[] = $file_like;
829        break;
830      case 'width':
831      case 'height':
832      case 'hits':
833      case 'rating_score':
834        $clauses[] = $token->scope->get_sql($scope_id, $token);
835        break;
836      case 'ratio':
837        $clauses[] = $token->scope->get_sql('width/height', $token);
838        break;
839      case 'size':
840        $clauses[] = $token->scope->get_sql('width*height', $token);
841        break;
842      case 'filesize':
843        $clauses[] = $token->scope->get_sql('filesize', $token);
844        break;
845
846    }
847    if (!empty($clauses))
848    {
849      $query = $query_base.'('.implode(' OR ', $clauses).')';
850      $qsr->images_iids[$i] = query2array($query,null,'id');
851    }
852  }
853}
854
855function qsearch_get_tags(QExpression $expr, QResults $qsr)
856{
857  $tokens = $expr->stokens;
858  $token_modifiers = $expr->stoken_modifiers;
859
860  $token_tag_ids = array_fill(0, count($tokens), array() );
861  $all_tags = array();
862
863  $token_tag_scores = $token_tag_ids;
864  $transliterated_tokens = array();
865  foreach ($tokens as $token)
866  {
867    if (!isset($token->scope) || 'tag' == $token->scope->id)
868    {
869      $transliterated_tokens[] = transliterate($token->term);
870    }
871    else
872    {
873      $transliterated_tokens[] = '';
874    }
875  }
876
877  $query = '
878SELECT t.*, COUNT(image_id) AS counter
879  FROM '.TAGS_TABLE.' t
880    INNER JOIN '.IMAGE_TAG_TABLE.' ON id=tag_id
881  GROUP BY id';
882  $result = pwg_query($query);
883  while ($tag = pwg_db_fetch_assoc($result))
884  {
885    $transliterated_tag = transliterate($tag['name']);
886
887    // find how this tag matches query tokens
888    for ($i=0; $i<count($tokens); $i++)
889    {
890      $transliterated_token = $transliterated_tokens[$i];
891      if (strlen($transliterated_token)==0)
892        continue;
893
894      $match = false;
895      $pos = 0;
896      while ( ($pos = strpos($transliterated_tag, $transliterated_token, $pos)) !== false)
897      {
898        if ( ($token_modifiers[$i]&QST_WILDCARD)==QST_WILDCARD )
899        {// wildcard in this token
900          $match = 1;
901          break;
902        }
903        $token_len = strlen($transliterated_token);
904
905        // search begin of word
906        $wbegin_len=0; $wbegin_char=' ';
907        while ($pos-$wbegin_len > 0)
908        {
909          if (! is_word_char($transliterated_tag[$pos-$wbegin_len-1]) )
910          {
911            $wbegin_char = $transliterated_tag[$pos-$wbegin_len-1];
912            break;
913          }
914          $wbegin_len++;
915        }
916
917        // search end of word
918        $wend_len=0; $wend_char=' ';
919        while ($pos+$token_len+$wend_len < strlen($transliterated_tag))
920        {
921          if (! is_word_char($transliterated_tag[$pos+$token_len+$wend_len]) )
922          {
923            $wend_char = $transliterated_tag[$pos+$token_len+$wend_len];
924            break;
925          }
926          $wend_len++;
927        }
928
929        $this_score = 0;
930        if ( ($token_modifiers[$i]&QST_WILDCARD)==0 )
931        {// no wildcard begin or end
932          if ($token_len <= 2)
933          {// search for 1 or 2 characters must match exactly to avoid retrieving too much data
934            if ($wbegin_len==0 && $wend_len==0 && !is_odd_wbreak_begin($wbegin_char) && !is_odd_wbreak_end($wend_char) )
935              $this_score = 1;
936          }
937          elseif ($token_len == 3)
938          {
939            if ($wbegin_len==0)
940              $this_score = $token_len / ($token_len + $wend_len);
941          }
942          else
943          {
944            $this_score = $token_len / ($token_len + 1.1 * $wbegin_len + 0.9 * $wend_len);
945          }
946        }
947
948        if ($this_score>0)
949          $match = max($match, $this_score );
950        $pos++;
951      }
952
953      if ($match)
954      {
955        $tag_id = (int)$tag['id'];
956        $all_tags[$tag_id] = $tag;
957        $token_tag_ids[$i][] = $tag_id;
958        $token_tag_scores[$i][] = $match;
959      }
960    }
961  }
962
963  // process tags
964  $not_tag_ids = array();
965  for ($i=0; $i<count($tokens); $i++)
966  {
967    array_multisort($token_tag_scores[$i], SORT_DESC|SORT_NUMERIC, $token_tag_ids[$i]);
968    $is_not = $token_modifiers[$i]&QST_NOT;
969    $counter = 0;
970
971    for ($j=0; $j<count($token_tag_scores[$i]); $j++)
972    {
973      if ($is_not)
974      {
975        if ($token_tag_scores[$i][$j] < 0.8 ||
976              ($j>0 && $token_tag_scores[$i][$j] < $token_tag_scores[$i][0]) )
977        {
978          array_splice($token_tag_scores[$i], $j);
979          array_splice($token_tag_ids[$i], $j);
980        }
981      }
982      else
983      {
984        $tag_id = $token_tag_ids[$i][$j];
985        $counter += $all_tags[$tag_id]['counter'];
986        if ( $j>0 && (
987          ($counter > 100 && $token_tag_scores[$i][0] > $token_tag_scores[$i][$j]) // "many" images in previous tags and starting from this tag is less relevant
988          || ($token_tag_scores[$i][0]==1 && $token_tag_scores[$i][$j]<0.8)
989          || ($token_tag_scores[$i][0]>0.8 && $token_tag_scores[$i][$j]<0.5)
990          ))
991        {// we remove this tag from the results, but we still leave it in all_tags list so that if we are wrong, the user chooses it
992          array_splice($token_tag_ids[$i], $j);
993          array_splice($token_tag_scores[$i], $j);
994          break;
995        }
996      }
997    }
998
999    if ($is_not)
1000    {
1001      $not_tag_ids = array_merge($not_tag_ids, $token_tag_ids[$i]);
1002    }
1003  }
1004
1005  $all_tags = array_diff_key($all_tags, array_flip($not_tag_ids));
1006  usort($all_tags, 'tag_alpha_compare');
1007  foreach ( $all_tags as &$tag )
1008  {
1009    $tag['name'] = trigger_event('render_tag_name', $tag['name'], $tag);
1010  }
1011  $qsr->all_tags = $all_tags;
1012
1013  $qsr->tag_ids = $token_tag_ids;
1014  $qsr->tag_iids = array_fill(0, count($tokens), array() );
1015
1016  for ($i=0; $i<count($tokens); $i++)
1017  {
1018    $tag_ids = $token_tag_ids[$i];
1019
1020    if (!empty($tag_ids))
1021    {
1022      $query = '
1023SELECT image_id FROM '.IMAGE_TAG_TABLE.'
1024  WHERE tag_id IN ('.implode(',',$tag_ids).')
1025  GROUP BY image_id';
1026      $qsr->tag_iids[$i] = query2array($query, null, 'image_id');
1027    }
1028    elseif (isset($tokens[$i]->scope) && 'tag' == $tokens[$i]->scope->id && strlen($token->term)==0)
1029    {
1030      if ($tokens[$i]->modifier & QST_WILDCARD)
1031      {// eg. 'tag:*' returns all tagged images
1032        $qsr->tag_iids[$i] = query2array('SELECT DISTINCT image_id FROM '.IMAGE_TAG_TABLE, null, 'image_id');
1033      }
1034      else
1035      {// eg. 'tag:' returns all untagged images
1036        $qsr->tag_iids[$i] = query2array('SELECT id FROM '.IMAGES_TABLE.' LEFT JOIN '.IMAGE_TAG_TABLE.' ON id=image_id WHERE image_id IS NULL', null, 'id');
1037      }
1038    }
1039  }
1040}
1041
1042
1043function qsearch_eval(QMultiToken $expr, QResults $qsr, &$qualifies, &$ignored_terms)
1044{
1045  $qualifies = false; // until we find at least one positive term
1046  $ignored_terms = array();
1047
1048  $ids = $not_ids = array();
1049
1050  for ($i=0; $i<count($expr->tokens); $i++)
1051  {
1052    $crt = $expr->tokens[$i];
1053    if ($crt->is_single)
1054    {
1055      $crt_ids = $qsr->iids[$crt->idx] = array_unique( array_merge($qsr->images_iids[$crt->idx], $qsr->tag_iids[$crt->idx]) );
1056      $crt_qualifies = count($crt_ids)>0 || count($qsr->tag_ids[$crt->idx])>0;
1057      $crt_ignored_terms = $crt_qualifies ? array() : array($crt->term);
1058    }
1059    else
1060      $crt_ids = qsearch_eval($crt, $qsr, $crt_qualifies, $crt_ignored_terms);
1061
1062    $modifier = $crt->modifier;
1063    if ($modifier & QST_NOT)
1064      $not_ids = array_unique( array_merge($not_ids, $crt_ids));
1065    else
1066    {
1067      $ignored_terms = array_merge($ignored_terms, $crt_ignored_terms);
1068      if ($modifier & QST_OR)
1069      {
1070        $ids = array_unique( array_merge($ids, $crt_ids) );
1071        $qualifies |= $crt_qualifies;
1072      }
1073      elseif ($crt_qualifies)
1074      {
1075        if ($qualifies)
1076          $ids = array_intersect($ids, $crt_ids);
1077        else
1078          $ids = $crt_ids;
1079        $qualifies = true;
1080      }
1081    }
1082  }
1083
1084  if (count($not_ids))
1085    $ids = array_diff($ids, $not_ids);
1086  return $ids;
1087}
1088
1089/**
1090 * Returns the search results corresponding to a quick/query search.
1091 * A quick/query search returns many items (search is not strict), but results
1092 * are sorted by relevance unless $super_order_by is true. Returns:
1093 *  array (
1094 *    'items' => array of matching images
1095 *    'qs'    => array(
1096 *      'unmatched_terms' => array of terms from the input string that were not matched
1097 *      'matching_tags' => array of matching tags
1098 *      'matching_cats' => array of matching categories
1099 *      'matching_cats_no_images' =>array(99) - matching categories without images
1100 *      )
1101 *    )
1102 *
1103 * @param string $q
1104 * @param bool $super_order_by
1105 * @param string $images_where optional additional restriction on images table
1106 * @return array
1107 */
1108function get_quick_search_results($q, $super_order_by, $images_where='')
1109{
1110  global $conf;
1111  //@TODO: maybe cache for 10 minutes the result set to avoid many expensive sql calls when navigating the pictures
1112  $q = trim(stripslashes($q));
1113  $search_results =
1114    array(
1115      'items' => array(),
1116      'qs' => array('q'=>$q),
1117    );
1118
1119  $scopes = array();
1120  $scopes[] = new QSearchScope('tag', array('tags'));
1121  $scopes[] = new QSearchScope('photo', array('photos'));
1122  $scopes[] = new QSearchScope('file', array('filename'));
1123  $scopes[] = new QNumericRangeScope('width', array());
1124  $scopes[] = new QNumericRangeScope('height', array());
1125  $scopes[] = new QNumericRangeScope('ratio', array(), false, 0.001);
1126  $scopes[] = new QNumericRangeScope('size', array());
1127  $scopes[] = new QNumericRangeScope('filesize', array());
1128  $scopes[] = new QNumericRangeScope('hits', array('hit', 'visit', 'visits'));
1129  $scopes[] = new QNumericRangeScope('rating_score', array('score'), true);
1130  $expression = new QExpression($q, $scopes);
1131//var_export($expression);
1132
1133  $qsr = new QResults;
1134  qsearch_get_tags($expression, $qsr);
1135  qsearch_get_images($expression, $qsr);
1136//var_export($qsr->all_tags);
1137
1138  $ids = qsearch_eval($expression, $qsr, $tmp, $search_results['qs']['unmatched_terms']);
1139
1140  $debug[] = "<!--\nparsed: ".$expression;
1141  $debug[] = count($expression->stokens).' tokens';
1142  for ($i=0; $i<count($expression->stokens); $i++)
1143  {
1144    $debug[] = $expression->stokens[$i].': '.count($qsr->tag_ids[$i]).' tags, '.count($qsr->tag_iids[$i]).' tiids, '.count($qsr->images_iids[$i]).' iiids, '.count($qsr->iids[$i]).' iids'
1145      .( !empty($qsr->variants[$expression->stokens[$i]->term]) ? ' variants: '.implode(', ',$qsr->variants[$expression->stokens[$i]->term]): '');
1146  }
1147  $debug[] = 'before perms '.count($ids);
1148
1149  $search_results['qs']['matching_tags'] = $qsr->all_tags;
1150  global $template;
1151
1152  if (empty($ids))
1153  {
1154    $debug[] = '-->';
1155    $template->append('footer_elements', implode("\n", $debug) );
1156    return $search_results;
1157  }
1158
1159  $where_clauses = array();
1160  $where_clauses[]='i.id IN ('. implode(',', $ids) . ')';
1161  if (!empty($images_where))
1162  {
1163    $where_clauses[]='('.$images_where.')';
1164  }
1165  $where_clauses[] = get_sql_condition_FandF(
1166      array
1167        (
1168          'forbidden_categories' => 'category_id',
1169          'visible_categories' => 'category_id',
1170          'visible_images' => 'i.id'
1171        ),
1172      null,true
1173    );
1174
1175  $query = '
1176SELECT DISTINCT(id)
1177  FROM '.IMAGES_TABLE.' i
1178    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
1179  WHERE '.implode("\n AND ", $where_clauses)."\n".
1180  $conf['order_by'];
1181
1182  $ids = query2array($query, null, 'id');
1183
1184  $debug[] = count($ids).' final photo count -->';
1185  $template->append('footer_elements', implode("\n", $debug) );
1186
1187  $search_results['items'] = $ids;
1188  return $search_results;
1189}
1190
1191/**
1192 * Returns an array of 'items' corresponding to the search id.
1193 * It can be either a quick search or a regular search.
1194 *
1195 * @param int $search_id
1196 * @param bool $super_order_by
1197 * @param string $images_where optional aditional restriction on images table
1198 * @return array
1199 */
1200function get_search_results($search_id, $super_order_by, $images_where='')
1201{
1202  $search = get_search_array($search_id);
1203  if ( !isset($search['q']) )
1204  {
1205    $result['items'] = get_regular_search_results($search, $images_where);
1206    return $result;
1207  }
1208  else
1209  {
1210    return get_quick_search_results($search['q'], $super_order_by, $images_where);
1211  }
1212}
1213
1214?>
Note: See TracBrowser for help on using the repository browser.