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

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

bug 3056: quick search - fix + prepare for scoped/range searches

  • Property svn:eol-style set to LF
File size: 27.6 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/**
300 * Analyzes and splits the quick/query search query $q into tokens.
301 * q='john bill' => 2 tokens 'john' 'bill'
302 * Special characters for MySql full text search (+,<,>,~) appear in the token modifiers.
303 * The query can contain a phrase: 'Pierre "New York"' will return 'pierre' qnd 'new york'.
304 *
305 * @param string $q
306 */
307
308/** Represents a single word or quoted phrase to be searched.*/
309class QSingleToken
310{
311  var $is_single = true;
312  var $term; /* the actual word/phrase string*/
313  var $idx;
314
315  function __construct($term)
316  {
317    $this->term = $term;
318  }
319 
320  function __toString()
321  {
322    return $this->term;
323  }
324}
325
326/** Represents an expression of several words or sub expressions to be searched.*/
327class QMultiToken
328{
329  var $is_single = false;
330  var $tokens = array(); // the actual array of QSingleToken or QMultiToken
331  var $token_modifiers = array(); // modifiers (OR,NOT,...) for every token
332
333  function __toString()
334  {
335    $s = '';
336    for ($i=0; $i<count($this->tokens); $i++)
337    {
338      $modifier = $this->token_modifiers[$i];
339      if ($i)
340        $s .= ' ';
341      if ($modifier & QST_OR)
342        $s .= 'OR ';
343      if ($modifier & QST_NOT)
344        $s .= 'NOT ';
345      if ($modifier & QST_WILDCARD_BEGIN)
346        $s .= '*';
347      if ($modifier & QST_QUOTED)
348        $s .= '"';
349      if (! ($this->tokens[$i]->is_single) )
350      {
351        $s .= '(';
352        $s .= $this->tokens[$i];
353        $s .= ')';
354      }
355      else
356      {
357        $s .= $this->tokens[$i];
358      }
359      if ($modifier & QST_QUOTED)
360        $s .= '"';
361      if ($modifier & QST_WILDCARD_END)
362        $s .= '*';
363
364    }
365    return $s;
366  }
367
368  private function push(&$token, &$modifier)
369  {
370    $this->tokens[] = new QSingleToken($token);
371    $this->token_modifiers[] = $modifier;
372    $token = "";
373    $modifier = 0;
374  }
375
376  /**
377  * Parses the input query string by tokenizing the input, generating the modifiers (and/or/not/quotation/wildcards...).
378  * Recursivity occurs when parsing ()
379  * @param string $q the actual query to be parsed
380  * @param int $qi the character index in $q where to start parsing
381  * @param int $level the depth from root in the tree (number of opened and unclosed opening brackets)
382  */
383  protected function parse_expression($q, &$qi, $level)
384  {
385    $crt_token = "";
386    $crt_modifier = 0;
387
388    for ($stop=false; !$stop && $qi<strlen($q); $qi++)
389    {
390      $ch = $q[$qi];
391      if ( ($crt_modifier&QST_QUOTED)==0)
392      {
393        switch ($ch)
394        {
395          case '(':
396            if (strlen($crt_token))
397              $this->push($crt_token, $crt_modifier);
398            $sub = new QMultiToken;
399            $qi++;
400            $sub->parse_expression($q, $qi, $level+1);
401            $this->tokens[] = $sub;
402            $this->token_modifiers[] = $crt_modifier;
403            $crt_modifier = 0;
404            break;
405          case ')':
406            if ($level>0)
407              $stop = true;
408            break;
409          case '"':
410            if (strlen($crt_token))
411              $this->push($crt_token, $crt_modifier);
412            $crt_modifier |= QST_QUOTED;
413            break;
414          case '-':
415            if (strlen($crt_token))
416              $crt_token .= $ch;
417            else
418              $crt_modifier |= QST_NOT;
419            break;
420          case '*':
421            if (strlen($crt_token))
422              $crt_token .= $ch; // wildcard end later
423            else
424              $crt_modifier |= QST_WILDCARD_BEGIN;
425            break;
426          default:
427            if (preg_match('/[\s,.;!\?]+/', $ch))
428            { // white space
429              if (strlen($crt_token))
430                $this->push($crt_token, $crt_modifier);
431              $crt_modifier = 0;
432            }
433            else
434              $crt_token .= $ch;
435            break;
436        }
437      }
438      else
439      {// quoted
440        if ($ch=='"')
441        {
442          if ($qi+1 < strlen($q) && $q[$qi+1]=='*')
443          {
444            $crt_modifier |= QST_WILDCARD_END;
445            $qi++;
446          }
447          $this->push($crt_token, $crt_modifier);
448        }
449        else
450          $crt_token .= $ch;
451      }
452    }
453
454    if (strlen($crt_token))
455      $this->push($crt_token, $crt_modifier);
456
457    for ($i=0; $i<count($this->tokens); $i++)
458    {
459      $token = $this->tokens[$i];
460      $remove = false;
461      if ($token->is_single)
462      {
463        if ( ($this->token_modifiers[$i]&QST_QUOTED)==0 )
464        {
465          if ('not' == strtolower($token->term))
466          {
467            if ($i+1 < count($this->tokens))
468              $this->token_modifiers[$i+1] |= QST_NOT;
469            $token->term = "";
470          }
471          if ('or' == strtolower($token->term))
472          {
473            if ($i+1 < count($this->tokens))
474              $this->token_modifiers[$i+1] |= QST_OR;
475            $token->term = "";
476          }
477          if ('and' == strtolower($token->term))
478          {
479            $token->term = "";
480          }
481          if ( substr($token->term, -1)=='*' )
482          {
483            $token->term = rtrim($token->term, '*');
484            $this->token_modifiers[$i] |= QST_WILDCARD_END;
485          }
486        }
487        if (!strlen($token->term))
488          $remove = true;
489      }
490      else
491      {
492        if (!count($token->tokens))
493          $remove = true;
494      }
495      if ($remove)
496      {
497        array_splice($this->tokens, $i, 1);
498        array_splice($this->token_modifiers, $i, 1);
499        $i--;
500      }
501    }
502  }
503
504  private static function priority($modifier)
505  {
506    return $modifier & QST_OR ? 0 :1;
507  }
508
509  /* because evaluations occur left to right, we ensure that 'a OR b c d' is interpreted as 'a OR (b c d)'*/
510  protected function check_operator_priority()
511  {
512    for ($i=0; $i<count($this->tokens); $i++)
513    {
514      if (!$this->tokens[$i]->is_single)
515        $this->tokens[$i]->check_operator_priority();
516      if ($i==1)
517        $crt_prio = self::priority($this->token_modifiers[$i]);
518      if ($i<=1)
519        continue;
520      $prio = self::priority($this->token_modifiers[$i]);
521      if ($prio > $crt_prio)
522      {// e.g. 'a OR b c d' i=2, operator(c)=AND -> prio(AND) > prio(OR) = operator(b)
523        $term_count = 2; // at least b and c to be regrouped
524        for ($j=$i+1; $j<count($this->tokens); $j++)
525        {
526          if (self::priority($this->token_modifiers[$j]) >= $prio)
527            $term_count++; // also take d
528          else
529            break;
530        }
531
532        $i--; // move pointer to b
533        // crate sub expression (b c d)
534        $sub = new QMultiToken;
535        $sub->tokens = array_splice($this->tokens, $i, $term_count);
536        $sub->token_modifiers = array_splice($this->token_modifiers, $i, $term_count);
537
538        // rewrite ourseleves as a (b c d)
539        array_splice($this->tokens, $i, 0, array($sub));
540        array_splice($this->token_modifiers, $i, 0, array($sub->token_modifiers[0]&QST_OR));
541        $sub->token_modifiers[0] &= ~QST_OR;
542
543        $sub->check_operator_priority();
544      }
545      else
546        $crt_prio = $prio;
547    }
548  }
549}
550
551class QExpression extends QMultiToken
552{
553  var $stokens = array();
554  var $stoken_modifiers = array();
555
556  function __construct($q)
557  {
558    $i = 0;
559    $this->parse_expression($q, $i, 0);
560    //manipulate the tree so that 'a OR b c' is the same as 'b c OR a'
561    $this->check_operator_priority();
562    $this->build_single_tokens($this, 0);
563  }
564
565  private function build_single_tokens(QMultiToken $expr, $this_is_not)
566  {
567    for ($i=0; $i<count($expr->tokens); $i++)
568    {
569      $token = $expr->tokens[$i];
570      $crt_is_not = ($expr->token_modifiers[$i] ^ $this_is_not) & QST_NOT; // no negation OR double negation -> no negation;
571
572      if ($token->is_single)
573      {
574        $token->idx = count($this->stokens);
575        $this->stokens[] = $token;
576
577        $modifier = $expr->token_modifiers[$i];
578        if ($crt_is_not)
579          $modifier |= QST_NOT;
580        else
581          $modifier &= ~QST_NOT;
582        $this->stoken_modifiers[] = $modifier;
583      }
584      else
585        $this->build_single_tokens($token, $crt_is_not);
586    }
587  }
588}
589
590/**
591  Structure of results being filled from different tables
592*/
593class QResults
594{
595  var $all_tags;
596  var $tag_ids;
597  var $tag_iids;
598  var $images_iids;
599  var $iids;
600
601  var $variants;
602}
603
604function qsearch_get_images(QExpression $expr, QResults $qsr)
605{
606  //@TODO: inflections for english / french
607  $qsr->images_iids = array_fill(0, count($expr->tokens), array());
608
609  $inflector = null;
610  $lang_code = substr(get_default_language(),0,2);
611  include_once(PHPWG_ROOT_PATH.'include/inflectors/'.$lang_code.'.php');
612  $class_name = 'Inflector_'.$lang_code;
613  if (class_exists($class_name))
614  {
615    $inflector = new $class_name;
616  }
617
618  $query_base = 'SELECT id from '.IMAGES_TABLE.' i WHERE ';
619  for ($i=0; $i<count($expr->stokens); $i++)
620  {
621    $token = $expr->stokens[$i]->term;
622    $clauses = array();
623
624    $like = addslashes($token);
625    $like = str_replace( array('%','_'), array('\\%','\\_'), $like); // escape LIKE specials %_
626    $clauses[] = 'CONVERT(file, CHAR) LIKE \'%'.$like.'%\'';
627
628    if ($inflector!=null && strlen($token)>2
629      && ($expr->stoken_modifiers[$i] & (QST_QUOTED|QST_WILDCARD))==0
630      && strcspn($token, '\'0123456789') == strlen($token)
631      )
632    {
633      $variants = array_unique( array_diff( $inflector->get_variants($token), array($token) ) );
634      $qsr->variants[$token] = $variants;
635    }
636    else
637    {
638      $variants = array();
639    }
640
641    if (strlen($token)>3) // default minimum full text index
642    {
643      $ft = $token;
644      if ($expr->stoken_modifiers[$i] & QST_QUOTED)
645        $ft = '"'.$ft.'"';
646      if ($expr->stoken_modifiers[$i] & QST_WILDCARD_END)
647        $ft .= '*';
648      foreach ($variants as $variant)
649      {
650        $ft.=' '.$variant;
651      }
652      $clauses[] = 'MATCH(i.name, i.comment) AGAINST( \''.addslashes($ft).'\' IN BOOLEAN MODE)';
653    }
654    else
655    {
656      foreach( array('i.name', 'i.comment') as $field)
657      {
658        /*$clauses[] = $field.' LIKE \''.$like.' %\'';
659        $clauses[] = $field.' LIKE \'% '.$like.'\'';
660        $clauses[] = $field.' LIKE \'% '.$like.' %\'';*/
661        $clauses[] = $field.' REGEXP \'[[:<:]]'.addslashes(preg_quote($token)).'[[:>:]]\'';
662      }
663    }
664    $query = $query_base.'('.implode(' OR ', $clauses).')';
665    $qsr->images_iids[$i] = query2array($query,null,'id');
666  }
667}
668
669function qsearch_get_tags(QExpression $expr, QResults $qsr)
670{
671  $tokens = $expr->stokens;
672  $token_modifiers = $expr->stoken_modifiers;
673
674  $token_tag_ids = array_fill(0, count($tokens), array() );
675  $all_tags = array();
676
677  $token_tag_scores = $token_tag_ids;
678  $transliterated_tokens = array();
679  foreach ($tokens as $token)
680  {
681    $transliterated_tokens[] = transliterate($token->term);
682  }
683
684  $query = '
685SELECT t.*, COUNT(image_id) AS counter
686  FROM '.TAGS_TABLE.' t
687    INNER JOIN '.IMAGE_TAG_TABLE.' ON id=tag_id
688  GROUP BY id';
689  $result = pwg_query($query);
690  while ($tag = pwg_db_fetch_assoc($result))
691  {
692    $transliterated_tag = transliterate($tag['name']);
693
694    // find how this tag matches query tokens
695    for ($i=0; $i<count($tokens); $i++)
696    {
697      $transliterated_token = $transliterated_tokens[$i];
698
699      $match = false;
700      $pos = 0;
701      while ( ($pos = strpos($transliterated_tag, $transliterated_token, $pos)) !== false)
702      {
703        if ( ($token_modifiers[$i]&QST_WILDCARD)==QST_WILDCARD )
704        {// wildcard in this token
705          $match = 1;
706          break;
707        }
708        $token_len = strlen($transliterated_token);
709
710        // search begin of word
711        $wbegin_len=0; $wbegin_char=' ';
712        while ($pos-$wbegin_len > 0)
713        {
714          if (! is_word_char($transliterated_tag[$pos-$wbegin_len-1]) )
715          {
716            $wbegin_char = $transliterated_tag[$pos-$wbegin_len-1];
717            break;
718          }
719          $wbegin_len++;
720        }
721
722        // search end of word
723        $wend_len=0; $wend_char=' ';
724        while ($pos+$token_len+$wend_len < strlen($transliterated_tag))
725        {
726          if (! is_word_char($transliterated_tag[$pos+$token_len+$wend_len]) )
727          {
728            $wend_char = $transliterated_tag[$pos+$token_len+$wend_len];
729            break;
730          }
731          $wend_len++;
732        }
733
734        $this_score = 0;
735        if ( ($token_modifiers[$i]&QST_WILDCARD)==0 )
736        {// no wildcard begin or end
737          if ($token_len <= 2)
738          {// search for 1 or 2 characters must match exactly to avoid retrieving too much data
739            if ($wbegin_len==0 && $wend_len==0 && !is_odd_wbreak_begin($wbegin_char) && !is_odd_wbreak_end($wend_char) )
740              $this_score = 1;
741          }
742          elseif ($token_len == 3)
743          {
744            if ($wbegin_len==0)
745              $this_score = $token_len / ($token_len + $wend_len);
746          }
747          else
748          {
749            $this_score = $token_len / ($token_len + 1.1 * $wbegin_len + 0.9 * $wend_len);
750          }
751        }
752
753        if ($this_score>0)
754          $match = max($match, $this_score );
755        $pos++;
756      }
757
758      if ($match)
759      {
760        $tag_id = (int)$tag['id'];
761        $all_tags[$tag_id] = $tag;
762        $token_tag_ids[$i][] = $tag_id;
763        $token_tag_scores[$i][] = $match;
764      }
765    }
766  }
767
768  // process tags
769  $not_tag_ids = array();
770  for ($i=0; $i<count($tokens); $i++)
771  {
772    array_multisort($token_tag_scores[$i], SORT_DESC|SORT_NUMERIC, $token_tag_ids[$i]);
773    $is_not = $token_modifiers[$i]&QST_NOT;
774    $counter = 0;
775
776    for ($j=0; $j<count($token_tag_scores[$i]); $j++)
777    {
778      if ($is_not)
779      {
780        if ($token_tag_scores[$i][$j] < 0.8 ||
781              ($j>0 && $token_tag_scores[$i][$j] < $token_tag_scores[$i][0]) )
782        {
783          array_splice($token_tag_scores[$i], $j);
784          array_splice($token_tag_ids[$i], $j);
785        }
786      }
787      else
788      {
789        $tag_id = $token_tag_ids[$i][$j];
790        $counter += $all_tags[$tag_id]['counter'];
791        if ( $j>0 && (
792          ($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
793          || ($token_tag_scores[$i][0]==1 && $token_tag_scores[$i][$j]<0.8)
794          || ($token_tag_scores[$i][0]>0.8 && $token_tag_scores[$i][$j]<0.5)
795          ))
796        {// 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
797          array_splice($token_tag_ids[$i], $j);
798          array_splice($token_tag_scores[$i], $j);
799          break;
800        }
801      }
802    }
803
804    if ($is_not)
805    {
806      $not_tag_ids = array_merge($not_tag_ids, $token_tag_ids[$i]);
807    }
808  }
809
810  $all_tags = array_diff_key($all_tags, array_flip($not_tag_ids));
811  usort($all_tags, 'tag_alpha_compare');
812  foreach ( $all_tags as &$tag )
813  {
814    $tag['name'] = trigger_event('render_tag_name', $tag['name'], $tag);
815  }
816  $qsr->all_tags = $all_tags;
817
818  $qsr->tag_ids = $token_tag_ids;
819  $qsr->tag_iids = array_fill(0, count($tokens), array() );
820
821  for ($i=0; $i<count($tokens); $i++)
822  {
823    $tag_ids = $token_tag_ids[$i];
824
825    if (!empty($tag_ids))
826    {
827      $query = '
828SELECT image_id FROM '.IMAGE_TAG_TABLE.'
829  WHERE tag_id IN ('.implode(',',$tag_ids).')
830  GROUP BY image_id';
831      $qsr->tag_iids[$i] = query2array($query, null, 'image_id');
832    }
833  }
834}
835
836
837function qsearch_eval(QMultiToken $expr, QResults $qsr, &$qualifies, &$ignored_terms)
838{
839  $qualifies = false; // until we find at least one positive term
840  $ignored_terms = array();
841
842  $ids = $not_ids = array();
843
844  for ($i=0; $i<count($expr->tokens); $i++)
845  {
846    $crt = $expr->tokens[$i];
847    if ($crt->is_single)
848    {
849      $crt_ids = $qsr->iids[$crt->idx] = array_unique( array_merge($qsr->images_iids[$crt->idx], $qsr->tag_iids[$crt->idx]) );
850      $crt_qualifies = count($crt_ids)>0 || count($qsr->tag_ids[$crt->idx])>0;
851      $crt_ignored_terms = $crt_qualifies ? array() : array($crt->term);
852    }
853    else
854      $crt_ids = qsearch_eval($crt, $qsr, $crt_qualifies, $crt_ignored_terms);
855
856    $modifier = $expr->token_modifiers[$i];
857    if ($modifier & QST_NOT)
858      $not_ids = array_unique( array_merge($not_ids, $crt_ids));
859    else
860    {
861      $ignored_terms = array_merge($ignored_terms, $crt_ignored_terms);
862      if ($modifier & QST_OR)
863      {
864        $ids = array_unique( array_merge($ids, $crt_ids) );
865        $qualifies |= $crt_qualifies;
866      }
867      elseif ($crt_qualifies)
868      {
869        if ($qualifies)
870          $ids = array_intersect($ids, $crt_ids);
871        else
872          $ids = $crt_ids;
873        $qualifies = true;
874      }
875    }
876  }
877
878  if (count($not_ids))
879    $ids = array_diff($ids, $not_ids);
880  return $ids;
881}
882
883/**
884 * Returns the search results corresponding to a quick/query search.
885 * A quick/query search returns many items (search is not strict), but results
886 * are sorted by relevance unless $super_order_by is true. Returns:
887 *  array (
888 *    'items' => array of matching images
889 *    'qs'    => array(
890 *      'unmatched_terms' => array of terms from the input string that were not matched
891 *      'matching_tags' => array of matching tags
892 *      'matching_cats' => array of matching categories
893 *      'matching_cats_no_images' =>array(99) - matching categories without images
894 *      )
895 *    )
896 *
897 * @param string $q
898 * @param bool $super_order_by
899 * @param string $images_where optional additional restriction on images table
900 * @return array
901 */
902function get_quick_search_results($q, $super_order_by, $images_where='')
903{
904  global $conf;
905  //@TODO: maybe cache for 10 minutes the result set to avoid many expensive sql calls when navigating the pictures
906  $q = trim(stripslashes($q));
907  $search_results =
908    array(
909      'items' => array(),
910      'qs' => array('q'=>$q),
911    );
912
913  $expression = new QExpression($q);
914//var_export($expression);
915
916  $qsr = new QResults;
917  qsearch_get_tags($expression, $qsr);
918  qsearch_get_images($expression, $qsr);
919//var_export($qsr->all_tags);
920
921  $ids = qsearch_eval($expression, $qsr, $tmp, $search_results['qs']['unmatched_terms']);
922
923  $debug[] = "<!--\nparsed: ".$expression;
924  $debug[] = count($expression->stokens).' tokens';
925  for ($i=0; $i<count($expression->stokens); $i++)
926  {
927    $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'
928      .( !empty($qsr->variants[$expression->stokens[$i]->term]) ? ' variants: '.implode(', ',$qsr->variants[$expression->stokens[$i]->term]): '');
929  }
930  $debug[] = 'before perms '.count($ids);
931
932  $search_results['qs']['matching_tags'] = $qsr->all_tags;
933  global $template;
934
935  if (empty($ids))
936  {
937    $debug[] = '-->';
938    $template->append('footer_elements', implode("\n", $debug) );
939    return $search_results;
940  }
941
942  $where_clauses = array();
943  $where_clauses[]='i.id IN ('. implode(',', $ids) . ')';
944  if (!empty($images_where))
945  {
946    $where_clauses[]='('.$images_where.')';
947  }
948  $where_clauses[] = get_sql_condition_FandF(
949      array
950        (
951          'forbidden_categories' => 'category_id',
952          'visible_categories' => 'category_id',
953          'visible_images' => 'i.id'
954        ),
955      null,true
956    );
957
958  $query = '
959SELECT DISTINCT(id)
960  FROM '.IMAGES_TABLE.' i
961    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
962  WHERE '.implode("\n AND ", $where_clauses)."\n".
963  $conf['order_by'];
964
965  $ids = query2array($query, null, 'id');
966
967  $debug[] = count($ids).' final photo count -->';
968  $template->append('footer_elements', implode("\n", $debug) );
969
970  $search_results['items'] = $ids;
971  return $search_results;
972}
973
974/**
975 * Returns an array of 'items' corresponding to the search id.
976 * It can be either a quick search or a regular search.
977 *
978 * @param int $search_id
979 * @param bool $super_order_by
980 * @param string $images_where optional aditional restriction on images table
981 * @return array
982 */
983function get_search_results($search_id, $super_order_by, $images_where='')
984{
985  $search = get_search_array($search_id);
986  if ( !isset($search['q']) )
987  {
988    $result['items'] = get_regular_search_results($search, $images_where);
989    return $result;
990  }
991  else
992  {
993    return get_quick_search_results($search['q'], $super_order_by, $images_where);
994  }
995}
996
997?>
Note: See TracBrowser for help on using the repository browser.