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

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

bug 3056: quick search - fix warning; better management of variants and short words

  • Property svn:eol-style set to LF
File size: 37.4 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 $nullable;
306
307  function __construct($id, $aliases, $nullable=false, $is_text=true)
308  {
309    $this->id = $id;
310    $this->aliases = $aliases;
311    $this->is_text = $is_text;
312    $this->nullable =$nullable;
313  }
314
315  function parse($token)
316  {
317    if (!$this->nullable && 0==strlen($token->term))
318      return false;
319    return true;
320  }
321}
322
323class QNumericRangeScope extends QSearchScope
324{
325  private $epsilon;
326  function __construct($id, $aliases, $nullable=false, $epsilon=0)
327  {
328    parent::__construct($id, $aliases, $nullable, false);
329    $this->epsilon = $epsilon;
330  }
331
332  function parse($token)
333  {
334    $str = $token->term;
335    if ( ($pos = strpos($str, '..')) !== false)
336      $range = array( substr($str,0,$pos), substr($str, $pos+2));
337    elseif ('>' == @$str[0])// ratio:>1
338      $range = array( substr($str,1), '');
339    elseif ('<' == @$str[0]) // size:<5mp
340      $range = array('', substr($str,1));
341    elseif( ($token->modifier & QST_WILDCARD_BEGIN) )
342      $range = array('', $str);
343    elseif( ($token->modifier & QST_WILDCARD_END) )
344      $range = array($str, '');
345    else
346      $range = array($str, $str);
347
348    foreach ($range as $i =>&$val)
349    {
350      if (preg_match('#^([0-9.]+)/([0-9.]+)$#i', $val, $matches))
351      {
352        $val = floatval($matches[1]/$matches[2]);
353      }
354      elseif (preg_match('/^([0-9.]+)([km])?/i', $val, $matches))
355      {
356        $val = floatval($matches[1]);
357        if (isset($matches[2]))
358        {
359          if ($matches[2]=='k' || $matches[2]=='K')
360          {
361            $val *= 1000;
362            if ($i) $val += 999;
363          }
364          if ($matches[2]=='m' || $matches[2]=='M')
365          {
366            $val *= 1000000;
367            if ($i) $val += 999999;
368          }
369        }
370      }
371      else
372        $val = '';
373      if (is_numeric($val))
374      {
375        if ($i)
376          $val += $this->epsilon;
377        else
378          $val -= $this->epsilon;
379      }
380    }
381
382    if (!$this->nullable && $range[0]=='' && $range[1] == '')
383      return false;
384    $token->scope_data = $range;
385    return true;
386  }
387
388  function get_sql($field, $token)
389  {
390    $clauses = array();
391    if ($token->scope_data[0]!=='')
392      $clauses[] = $field.' >= ' .$token->scope_data[0].' ';
393    if ($token->scope_data[1]!=='')
394      $clauses[] = $field.' <= ' .$token->scope_data[1].' ';
395
396    if (empty($clauses))
397    {
398      if ($token->modifier & QST_WILDCARD)
399        return $field.' IS NOT NULL';
400      else
401        return $field.' IS NULL';
402    }
403    return '('.implode(' AND ', $clauses).')';
404  }
405}
406
407
408class QDateRangeScope extends QSearchScope
409{
410  function __construct($id, $aliases, $nullable=false)
411  {
412    parent::__construct($id, $aliases, $nullable, false);
413  }
414
415  function parse($token)
416  {
417    $str = $token->term;
418    if ( ($pos = strpos($str, '..')) !== false)
419      $range = array( substr($str,0,$pos), substr($str, $pos+2));
420    elseif ('>' == @$str[0])
421      $range = array( substr($str,1), '');
422    elseif ('<' == @$str[0])
423      $range = array('', substr($str,1));
424    elseif( ($token->modifier & QST_WILDCARD_BEGIN) )
425      $range = array('', $str);
426    elseif( ($token->modifier & QST_WILDCARD_END) )
427      $range = array($str, '');
428    else
429      $range = array($str, $str);
430
431    foreach ($range as $i =>&$val)
432    {
433      if (preg_match('/([0-9]{4})-?((?:0?[0-9])|(?:1[0-2]))?-?(((?:0?[0-9])|(?:[1-3][0-9])))?/', $val, $matches))
434      {
435        array_shift($matches);
436        if (!isset($matches[1]))
437          $matches[1] = !$i ? 1 : 12;
438        if (!isset($matches[2]))
439          $matches[2] = !$i ? 1 : 31;
440        $val = $matches;
441      }
442      elseif (strlen($val))
443        return false;
444    }
445
446    if (!$this->nullable && $range[0]=='' && $range[1] == '')
447      return false;
448
449    $token->scope_data = $range;
450    return true;
451  }
452
453  function get_sql($field, $token)
454  {
455    $clauses = array();
456    if ($token->scope_data[0]!=='')
457      $clauses[] = $field.' >= \'' . implode('-',$token->scope_data[0]).'\'';
458    if ($token->scope_data[1]!=='')
459      $clauses[] = $field.' <= \'' . implode('-',$token->scope_data[1]).' 23:59:59\'';
460
461    if (empty($clauses))
462    {
463      if ($token->modifier & QST_WILDCARD)
464        return $field.' IS NOT NULL';
465      else
466        return $field.' IS NULL';
467    }
468    return '('.implode(' AND ', $clauses).')';
469  }
470}
471
472/**
473 * Analyzes and splits the quick/query search query $q into tokens.
474 * q='john bill' => 2 tokens 'john' 'bill'
475 * Special characters for MySql full text search (+,<,>,~) appear in the token modifiers.
476 * The query can contain a phrase: 'Pierre "New York"' will return 'pierre' qnd 'new york'.
477 *
478 * @param string $q
479 */
480
481/** Represents a single word or quoted phrase to be searched.*/
482class QSingleToken
483{
484  var $is_single = true;
485  var $modifier;
486  var $term; /* the actual word/phrase string*/
487  var $variants = array();
488  var $scope;
489
490  var $scope_data;
491  var $idx;
492
493  function __construct($term, $modifier, $scope)
494  {
495    $this->term = $term;
496    $this->modifier = $modifier;
497    $this->scope = $scope;
498  }
499
500  function __toString()
501  {
502    $s = '';
503    if (isset($this->scope))
504      $s .= $this->scope->id .':';
505    if ($this->modifier & QST_WILDCARD_BEGIN)
506      $s .= '*';
507    if ($this->modifier & QST_QUOTED)
508      $s .= '"';
509    $s .= $this->term;
510    if ($this->modifier & QST_QUOTED)
511      $s .= '"';
512    if ($this->modifier & QST_WILDCARD_END)
513      $s .= '*';
514    return $s;
515  }
516}
517
518/** Represents an expression of several words or sub expressions to be searched.*/
519class QMultiToken
520{
521  var $is_single = false;
522  var $modifier;
523  var $tokens = array(); // the actual array of QSingleToken or QMultiToken
524
525  function __toString()
526  {
527    $s = '';
528    for ($i=0; $i<count($this->tokens); $i++)
529    {
530      $modifier = $this->tokens[$i]->modifier;
531      if ($i)
532        $s .= ' ';
533      if ($modifier & QST_OR)
534        $s .= 'OR ';
535      if ($modifier & QST_NOT)
536        $s .= 'NOT ';
537      if (! ($this->tokens[$i]->is_single) )
538      {
539        $s .= '(';
540        $s .= $this->tokens[$i];
541        $s .= ')';
542      }
543      else
544      {
545        $s .= $this->tokens[$i];
546      }
547    }
548    return $s;
549  }
550
551  private function push(&$token, &$modifier, &$scope)
552  {
553    if (strlen($token) || (isset($scope) && $scope->nullable))
554    {
555      $this->tokens[] = new QSingleToken($token, $modifier, $scope);
556    }
557    $token = "";
558    $modifier = 0;
559    $scope = null;
560  }
561
562  /**
563  * Parses the input query string by tokenizing the input, generating the modifiers (and/or/not/quotation/wildcards...).
564  * Recursivity occurs when parsing ()
565  * @param string $q the actual query to be parsed
566  * @param int $qi the character index in $q where to start parsing
567  * @param int $level the depth from root in the tree (number of opened and unclosed opening brackets)
568  */
569  protected function parse_expression($q, &$qi, $level, $root)
570  {
571    $crt_token = "";
572    $crt_modifier = 0;
573    $crt_scope = null;
574
575    for ($stop=false; !$stop && $qi<strlen($q); $qi++)
576    {
577      $ch = $q[$qi];
578      if ( ($crt_modifier&QST_QUOTED)==0)
579      {
580        switch ($ch)
581        {
582          case '(':
583            if (strlen($crt_token))
584              $this->push($crt_token, $crt_modifier, $crt_scope);
585            $sub = new QMultiToken;
586            $qi++;
587            $sub->parse_expression($q, $qi, $level+1, $root);
588            $sub->modifier = $crt_modifier;
589            if (isset($crt_scope) && $crt_scope->is_text)
590            {
591              $sub->apply_scope($crt_scope); // eg. 'tag:(John OR Bill)'
592            }
593            $this->tokens[] = $sub;
594            $crt_modifier = 0;
595            $crt_scope = null;
596            break;
597          case ')':
598            if ($level>0)
599              $stop = true;
600            break;
601          case ':':
602            $scope = @$root->scopes[$crt_token];
603            if (!isset($scope) || isset($crt_scope))
604            { // white space
605              $this->push($crt_token, $crt_modifier, $crt_scope);
606            }
607            else
608            {
609              $crt_token = "";
610              $crt_scope = $scope;
611            }
612            break;
613          case '"':
614            if (strlen($crt_token))
615              $this->push($crt_token, $crt_modifier, $crt_scope);
616            $crt_modifier |= QST_QUOTED;
617            break;
618          case '-':
619            if (strlen($crt_token) || isset($crt_scope))
620              $crt_token .= $ch;
621            else
622              $crt_modifier |= QST_NOT;
623            break;
624          case '*':
625            if (strlen($crt_token))
626              $crt_token .= $ch; // wildcard end later
627            else
628              $crt_modifier |= QST_WILDCARD_BEGIN;
629            break;
630          case '.':
631            if (isset($crt_scope) && !$crt_scope->is_text)
632            {
633              $crt_token .= $ch;
634              break;
635            }
636            // else white space go on..
637          default:
638            if (preg_match('/[\s,.;!\?]+/', $ch))
639            { // white space
640              $this->push($crt_token, $crt_modifier, $crt_scope);
641            }
642            else
643              $crt_token .= $ch;
644            break;
645        }
646      }
647      else
648      {// quoted
649        if ($ch=='"')
650        {
651          if ($qi+1 < strlen($q) && $q[$qi+1]=='*')
652          {
653            $crt_modifier |= QST_WILDCARD_END;
654            $qi++;
655          }
656          $this->push($crt_token, $crt_modifier, $crt_scope);
657        }
658        else
659          $crt_token .= $ch;
660      }
661    }
662
663    $this->push($crt_token, $crt_modifier, $crt_scope);
664
665    for ($i=0; $i<count($this->tokens); $i++)
666    {
667      $token = $this->tokens[$i];
668      $remove = false;
669      if ($token->is_single)
670      {
671        if ( ($token->modifier & QST_QUOTED)==0
672          && substr($token->term, -1)=='*' )
673        {
674          $token->term = rtrim($token->term, '*');
675          $token->modifier |= QST_WILDCARD_END;
676        }
677
678        if ( !isset($token->scope)
679          && ($token->modifier & (QST_QUOTED|QST_WILDCARD))==0 )
680        {
681          if ('not' == strtolower($token->term))
682          {
683            if ($i+1 < count($this->tokens))
684              $this->tokens[$i+1]->modifier |= QST_NOT;
685            $token->term = "";
686          }
687          if ('or' == strtolower($token->term))
688          {
689            if ($i+1 < count($this->tokens))
690              $this->tokens[$i+1]->modifier |= QST_OR;
691            $token->term = "";
692          }
693          if ('and' == strtolower($token->term))
694          {
695            $token->term = "";
696          }
697        }
698
699        if (!strlen($token->term)
700          && (!isset($token->scope) || !$token->scope->nullable) )
701        {
702          $remove = true;
703        }
704
705        if ( isset($token->scope)
706          && !$token->scope->parse($token))
707          $remove = true;
708      }
709      elseif (!count($token->tokens))
710      {
711          $remove = true;
712      }
713      if ($remove)
714      {
715        array_splice($this->tokens, $i, 1);
716        $i--;
717      }
718    }
719  }
720
721  private function apply_scope(QSearchScope $scope)
722  {
723    for ($i=0; $i<count($this->tokens); $i++)
724    {
725      if ($this->tokens[$i]->is_single)
726      {
727        if (!isset($this->tokens[$i]->scope))
728          $this->tokens[$i]->scope = $scope;
729      }
730      else
731        $this->tokens[$i]->apply_scope($scope);
732    }
733  }
734
735  private static function priority($modifier)
736  {
737    return $modifier & QST_OR ? 0 :1;
738  }
739
740  /* because evaluations occur left to right, we ensure that 'a OR b c d' is interpreted as 'a OR (b c d)'*/
741  protected function check_operator_priority()
742  {
743    for ($i=0; $i<count($this->tokens); $i++)
744    {
745      if (!$this->tokens[$i]->is_single)
746        $this->tokens[$i]->check_operator_priority();
747      if ($i==1)
748        $crt_prio = self::priority($this->tokens[$i]->modifier);
749      if ($i<=1)
750        continue;
751      $prio = self::priority($this->tokens[$i]->modifier);
752      if ($prio > $crt_prio)
753      {// e.g. 'a OR b c d' i=2, operator(c)=AND -> prio(AND) > prio(OR) = operator(b)
754        $term_count = 2; // at least b and c to be regrouped
755        for ($j=$i+1; $j<count($this->tokens); $j++)
756        {
757          if (self::priority($this->tokens[$j]->modifier) >= $prio)
758            $term_count++; // also take d
759          else
760            break;
761        }
762
763        $i--; // move pointer to b
764        // crate sub expression (b c d)
765        $sub = new QMultiToken;
766        $sub->tokens = array_splice($this->tokens, $i, $term_count);
767
768        // rewrite ourseleves as a (b c d)
769        array_splice($this->tokens, $i, 0, array($sub));
770        $sub->modifier = $sub->tokens[0]->modifier & QST_OR;
771        $sub->tokens[0]->modifier &= ~QST_OR;
772
773        $sub->check_operator_priority();
774      }
775      else
776        $crt_prio = $prio;
777    }
778  }
779}
780
781class QExpression extends QMultiToken
782{
783  var $scopes = array();
784  var $stokens = array();
785  var $stoken_modifiers = array();
786
787  function __construct($q, $scopes)
788  {
789    foreach ($scopes as $scope)
790    {
791      $this->scopes[$scope->id] = $scope;
792      foreach ($scope->aliases as $alias)
793        $this->scopes[strtolower($alias)] = $scope;
794    }
795    $i = 0;
796    $this->parse_expression($q, $i, 0, $this);
797    //manipulate the tree so that 'a OR b c' is the same as 'b c OR a'
798    $this->check_operator_priority();
799    $this->build_single_tokens($this, 0);
800  }
801
802  private function build_single_tokens(QMultiToken $expr, $this_is_not)
803  {
804    for ($i=0; $i<count($expr->tokens); $i++)
805    {
806      $token = $expr->tokens[$i];
807      $crt_is_not = ($token->modifier ^ $this_is_not) & QST_NOT; // no negation OR double negation -> no negation;
808
809      if ($token->is_single)
810      {
811        $token->idx = count($this->stokens);
812        $this->stokens[] = $token;
813
814        $modifier = $token->modifier;
815        if ($crt_is_not)
816          $modifier |= QST_NOT;
817        else
818          $modifier &= ~QST_NOT;
819        $this->stoken_modifiers[] = $modifier;
820      }
821      else
822        $this->build_single_tokens($token, $crt_is_not);
823    }
824  }
825}
826
827/**
828  Structure of results being filled from different tables
829*/
830class QResults
831{
832  var $all_tags;
833  var $tag_ids;
834  var $tag_iids;
835  var $images_iids;
836  var $iids;
837}
838
839function qsearch_get_images(QExpression $expr, QResults $qsr)
840{
841  $qsr->images_iids = array_fill(0, count($expr->stokens), array());
842
843  $query_base = 'SELECT id from '.IMAGES_TABLE.' i WHERE
844';
845  for ($i=0; $i<count($expr->stokens); $i++)
846  {
847    $token = $expr->stokens[$i];
848    $scope_id = isset($token->scope) ? $token->scope->id : 'photo';
849    $clauses = array();
850
851    $like = addslashes($token->term);
852    $like = str_replace( array('%','_'), array('\\%','\\_'), $like); // escape LIKE specials %_
853    $file_like = 'CONVERT(file, CHAR) LIKE \'%'.$like.'%\'';
854
855    switch ($scope_id)
856    {
857      case 'photo':
858        $clauses[] = $file_like;
859
860        $variants = array_merge(array($token->term), $token->variants);
861        $fts = array();
862        foreach ($variants as $variant)
863        {
864          if (mb_strlen($variant)<=3
865            || strcspn($variant, '!"#$%&()*+,./:;<=>?@[\]^`{|}~') < 3)
866          {// odd term or too short for full text search; fallback to regex but unfortunately this is diacritic/accent sensitive
867            $pre = ($token->modifier & QST_WILDCARD_BEGIN) ? '' : '[[:<:]]';
868            $post = ($token->modifier & QST_WILDCARD_END) ? '' : '[[:>:]]';
869            foreach( array('i.name', 'i.comment') as $field)
870              $clauses[] = $field.' REGEXP \''.$pre.addslashes(preg_quote($variant)).$post.'\'';
871          }
872          else
873          {
874            $ft = $variant;
875            if ($expr->stoken_modifiers[$i] & QST_QUOTED)
876              $ft = '"'.$ft.'"';
877            if ($expr->stoken_modifiers[$i] & QST_WILDCARD_END)
878              $ft .= '*';
879            $fts[] = $ft;
880          }
881        }
882
883        if (count($fts))
884        {
885          $clauses[] = 'MATCH(i.name, i.comment) AGAINST( \''.addslashes(implode(' ',$fts)).'\' IN BOOLEAN MODE)';
886        }
887        break;
888
889      case 'file':
890        $clauses[] = $file_like;
891        break;
892      case 'width':
893      case 'height':
894        $clauses[] = $token->scope->get_sql($scope_id, $token);
895        break;
896      case 'ratio':
897        $clauses[] = $token->scope->get_sql('width/height', $token);
898        break;
899      case 'size':
900        $clauses[] = $token->scope->get_sql('width*height', $token);
901        break;
902      case 'hits':
903        $clauses[] = $token->scope->get_sql('hit', $token);
904        break;
905      case 'score':
906        $clauses[] = $token->scope->get_sql('rating_score', $token);
907        break;
908      case 'filesize':
909        $clauses[] = $token->scope->get_sql('1024*filesize', $token);
910        break;
911      case 'created':
912        $clauses[] = $token->scope->get_sql('date_creation', $token);
913        break;
914      case 'posted':
915        $clauses[] = $token->scope->get_sql('date_available', $token);
916        break;
917      default:
918        // allow plugins to have their own scope with columns added in db by themselves
919        $clauses = trigger_event('qsearch_get_images_sql_scopes', $clauses, $token, $expr);
920        break;
921    }
922    if (!empty($clauses))
923    {
924      $query = $query_base.'('.implode("\n OR ", $clauses).')';
925      $qsr->images_iids[$i] = query2array($query,null,'id');
926    }
927  }
928}
929
930function qsearch_get_tags(QExpression $expr, QResults $qsr)
931{
932  $tokens = $expr->stokens;
933  $token_modifiers = $expr->stoken_modifiers;
934
935  $token_tag_ids = array_fill(0, count($tokens), array() );
936  $all_tags = array();
937
938  $token_tag_scores = $token_tag_ids;
939  $transliterated_tokens = array();
940  foreach ($tokens as $token)
941  {
942    if (!isset($token->scope) || 'tag' == $token->scope->id)
943    {
944      $transliterated_tokens[] = transliterate($token->term);
945    }
946    else
947    {
948      $transliterated_tokens[] = '';
949    }
950  }
951
952  $query = '
953SELECT t.*, COUNT(image_id) AS counter
954  FROM '.TAGS_TABLE.' t
955    INNER JOIN '.IMAGE_TAG_TABLE.' ON id=tag_id
956  GROUP BY id';
957  $result = pwg_query($query);
958  while ($tag = pwg_db_fetch_assoc($result))
959  {
960    $transliterated_tag = transliterate($tag['name']);
961
962    // find how this tag matches query tokens
963    for ($i=0; $i<count($tokens); $i++)
964    {
965      $transliterated_token = $transliterated_tokens[$i];
966      if (strlen($transliterated_token)==0)
967        continue;
968
969      $match = false;
970      $pos = 0;
971      while ( ($pos = strpos($transliterated_tag, $transliterated_token, $pos)) !== false)
972      {
973        if ( ($token_modifiers[$i]&QST_WILDCARD)==QST_WILDCARD )
974        {// wildcard in this token
975          $match = 1;
976          break;
977        }
978        $token_len = strlen($transliterated_token);
979
980        // search begin of word
981        $wbegin_len=0; $wbegin_char=' ';
982        while ($pos-$wbegin_len > 0)
983        {
984          if (! is_word_char($transliterated_tag[$pos-$wbegin_len-1]) )
985          {
986            $wbegin_char = $transliterated_tag[$pos-$wbegin_len-1];
987            break;
988          }
989          $wbegin_len++;
990        }
991
992        // search end of word
993        $wend_len=0; $wend_char=' ';
994        while ($pos+$token_len+$wend_len < strlen($transliterated_tag))
995        {
996          if (! is_word_char($transliterated_tag[$pos+$token_len+$wend_len]) )
997          {
998            $wend_char = $transliterated_tag[$pos+$token_len+$wend_len];
999            break;
1000          }
1001          $wend_len++;
1002        }
1003
1004        $this_score = 0;
1005        if ( ($token_modifiers[$i]&QST_WILDCARD)==0 )
1006        {// no wildcard begin or end
1007          if ($token_len <= 2)
1008          {// search for 1 or 2 characters must match exactly to avoid retrieving too much data
1009            if ($wbegin_len==0 && $wend_len==0 && !is_odd_wbreak_begin($wbegin_char) && !is_odd_wbreak_end($wend_char) )
1010              $this_score = 1;
1011          }
1012          elseif ($token_len == 3)
1013          {
1014            if ($wbegin_len==0)
1015              $this_score = $token_len / ($token_len + $wend_len);
1016          }
1017          else
1018          {
1019            $this_score = $token_len / ($token_len + 1.1 * $wbegin_len + 0.9 * $wend_len);
1020          }
1021        }
1022
1023        if ($this_score>0)
1024          $match = max($match, $this_score );
1025        $pos++;
1026      }
1027
1028      if ($match)
1029      {
1030        $tag_id = (int)$tag['id'];
1031        $all_tags[$tag_id] = $tag;
1032        $token_tag_ids[$i][] = $tag_id;
1033        $token_tag_scores[$i][] = $match;
1034      }
1035    }
1036  }
1037
1038  // process tags
1039  $not_tag_ids = array();
1040  for ($i=0; $i<count($tokens); $i++)
1041  {
1042    array_multisort($token_tag_scores[$i], SORT_DESC|SORT_NUMERIC, $token_tag_ids[$i]);
1043    $is_not = $token_modifiers[$i]&QST_NOT;
1044    $counter = 0;
1045
1046    for ($j=0; $j<count($token_tag_scores[$i]); $j++)
1047    {
1048      if ($is_not)
1049      {
1050        if ($token_tag_scores[$i][$j] < 0.8 ||
1051              ($j>0 && $token_tag_scores[$i][$j] < $token_tag_scores[$i][0]) )
1052        {
1053          array_splice($token_tag_scores[$i], $j);
1054          array_splice($token_tag_ids[$i], $j);
1055        }
1056      }
1057      else
1058      {
1059        $tag_id = $token_tag_ids[$i][$j];
1060        $counter += $all_tags[$tag_id]['counter'];
1061        if ( $j>0 && (
1062          ($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
1063          || ($token_tag_scores[$i][0]==1 && $token_tag_scores[$i][$j]<0.8)
1064          || ($token_tag_scores[$i][0]>0.8 && $token_tag_scores[$i][$j]<0.5)
1065          ))
1066        {// 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
1067          array_splice($token_tag_ids[$i], $j);
1068          array_splice($token_tag_scores[$i], $j);
1069          break;
1070        }
1071      }
1072    }
1073
1074    if ($is_not)
1075    {
1076      $not_tag_ids = array_merge($not_tag_ids, $token_tag_ids[$i]);
1077    }
1078  }
1079
1080  $all_tags = array_diff_key($all_tags, array_flip($not_tag_ids));
1081  usort($all_tags, 'tag_alpha_compare');
1082  foreach ( $all_tags as &$tag )
1083  {
1084    $tag['name'] = trigger_event('render_tag_name', $tag['name'], $tag);
1085  }
1086  $qsr->all_tags = $all_tags;
1087
1088  $qsr->tag_ids = $token_tag_ids;
1089  $qsr->tag_iids = array_fill(0, count($tokens), array() );
1090
1091  for ($i=0; $i<count($tokens); $i++)
1092  {
1093    $tag_ids = $token_tag_ids[$i];
1094
1095    if (!empty($tag_ids))
1096    {
1097      $query = '
1098SELECT image_id FROM '.IMAGE_TAG_TABLE.'
1099  WHERE tag_id IN ('.implode(',',$tag_ids).')
1100  GROUP BY image_id';
1101      $qsr->tag_iids[$i] = query2array($query, null, 'image_id');
1102    }
1103    elseif (isset($tokens[$i]->scope) && 'tag' == $tokens[$i]->scope->id && strlen($token->term)==0)
1104    {
1105      if ($tokens[$i]->modifier & QST_WILDCARD)
1106      {// eg. 'tag:*' returns all tagged images
1107        $qsr->tag_iids[$i] = query2array('SELECT DISTINCT image_id FROM '.IMAGE_TAG_TABLE, null, 'image_id');
1108      }
1109      else
1110      {// eg. 'tag:' returns all untagged images
1111        $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');
1112      }
1113    }
1114  }
1115}
1116
1117
1118function qsearch_eval(QMultiToken $expr, QResults $qsr, &$qualifies, &$ignored_terms)
1119{
1120  $qualifies = false; // until we find at least one positive term
1121  $ignored_terms = array();
1122
1123  $ids = $not_ids = array();
1124
1125  for ($i=0; $i<count($expr->tokens); $i++)
1126  {
1127    $crt = $expr->tokens[$i];
1128    if ($crt->is_single)
1129    {
1130      $crt_ids = $qsr->iids[$crt->idx] = array_unique( array_merge($qsr->images_iids[$crt->idx], $qsr->tag_iids[$crt->idx]) );
1131      $crt_qualifies = count($crt_ids)>0 || count($qsr->tag_ids[$crt->idx])>0;
1132      $crt_ignored_terms = $crt_qualifies ? array() : array($crt->term);
1133    }
1134    else
1135      $crt_ids = qsearch_eval($crt, $qsr, $crt_qualifies, $crt_ignored_terms);
1136
1137    $modifier = $crt->modifier;
1138    if ($modifier & QST_NOT)
1139      $not_ids = array_unique( array_merge($not_ids, $crt_ids));
1140    else
1141    {
1142      $ignored_terms = array_merge($ignored_terms, $crt_ignored_terms);
1143      if ($modifier & QST_OR)
1144      {
1145        $ids = array_unique( array_merge($ids, $crt_ids) );
1146        $qualifies |= $crt_qualifies;
1147      }
1148      elseif ($crt_qualifies)
1149      {
1150        if ($qualifies)
1151          $ids = array_intersect($ids, $crt_ids);
1152        else
1153          $ids = $crt_ids;
1154        $qualifies = true;
1155      }
1156    }
1157  }
1158
1159  if (count($not_ids))
1160    $ids = array_diff($ids, $not_ids);
1161  return $ids;
1162}
1163
1164/**
1165 * Returns the search results corresponding to a quick/query search.
1166 * A quick/query search returns many items (search is not strict), but results
1167 * are sorted by relevance unless $super_order_by is true. Returns:
1168 *  array (
1169 *    'items' => array of matching images
1170 *    'qs'    => array(
1171 *      'unmatched_terms' => array of terms from the input string that were not matched
1172 *      'matching_tags' => array of matching tags
1173 *      'matching_cats' => array of matching categories
1174 *      'matching_cats_no_images' =>array(99) - matching categories without images
1175 *      )
1176 *    )
1177 *
1178 * @param string $q
1179 * @param bool $super_order_by
1180 * @param string $images_where optional additional restriction on images table
1181 * @return array
1182 */
1183function get_quick_search_results($q, $options)
1184{
1185  global $conf;
1186  //@TODO: maybe cache for 10 minutes the result set to avoid many expensive sql calls when navigating the pictures
1187  $q = trim(stripslashes($q));
1188  $search_results =
1189    array(
1190      'items' => array(),
1191      'qs' => array('q'=>$q),
1192    );
1193
1194  $scopes = array();
1195  $scopes[] = new QSearchScope('tag', array('tags'));
1196  $scopes[] = new QSearchScope('photo', array('photos'));
1197  $scopes[] = new QSearchScope('file', array('filename'));
1198  $scopes[] = new QNumericRangeScope('width', array());
1199  $scopes[] = new QNumericRangeScope('height', array());
1200  $scopes[] = new QNumericRangeScope('ratio', array(), false, 0.001);
1201  $scopes[] = new QNumericRangeScope('size', array());
1202  $scopes[] = new QNumericRangeScope('filesize', array());
1203  $scopes[] = new QNumericRangeScope('hits', array('hit', 'visit', 'visits'));
1204  $scopes[] = new QNumericRangeScope('score', array('rating'), true);
1205
1206  $createdDateAliases = array('taken', 'shot');
1207  $postedDateAliases = array('added');
1208  if ($conf['calendar_datefield'] == 'date_creation')
1209    $createdDateAliases[] = 'date';
1210  else
1211    $postedDateAliases[] = 'date';
1212  $scopes[] = new QDateRangeScope('created', $createdDateAliases, true);
1213  $scopes[] = new QDateRangeScope('posted', $postedDateAliases);
1214
1215  // allow plugins to add their own scopes
1216  $scopes = trigger_event('qsearch_get_scopes', $scopes);
1217  $expression = new QExpression($q, $scopes);
1218
1219  // get inflections for terms
1220  $inflector = null;
1221  $lang_code = substr(get_default_language(),0,2);
1222  @include_once(PHPWG_ROOT_PATH.'include/inflectors/'.$lang_code.'.php');
1223  $class_name = 'Inflector_'.$lang_code;
1224  if (class_exists($class_name))
1225  {
1226    $inflector = new $class_name;
1227    foreach( $expression->stokens as $token)
1228    {
1229      if (isset($token->scope) && !$token->scope->is_text)
1230        continue;
1231      if (strlen($token->term)>2
1232        && ($token->modifier & (QST_QUOTED|QST_WILDCARD))==0
1233        && strcspn($token->term, '\'0123456789') == strlen($token->term) )
1234      {
1235        $token->variants = array_unique( array_diff( $inflector->get_variants($token->term), array($token->term) ) );
1236      }
1237    }
1238  }
1239
1240
1241  trigger_action('qsearch_expression_parsed', $expression);
1242//var_export($expression);
1243
1244  if (count($expression->stokens)==0)
1245  {
1246    return $search_results;
1247  }
1248  $qsr = new QResults;
1249  qsearch_get_tags($expression, $qsr);
1250  qsearch_get_images($expression, $qsr);
1251
1252  // allow plugins to evaluate their own scopes
1253  trigger_action('qsearch_before_eval', $expression, $qsr);
1254
1255  $ids = qsearch_eval($expression, $qsr, $tmp, $search_results['qs']['unmatched_terms']);
1256
1257  $debug[] = "<!--\nparsed: ".$expression;
1258  $debug[] = count($expression->stokens).' tokens';
1259  for ($i=0; $i<count($expression->stokens); $i++)
1260  {
1261    $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'
1262      .( !empty($expression->stokens[$i]->variants) ? ' variants: '.implode(', ',$expression->stokens[$i]->variants): '');
1263  }
1264  $debug[] = 'before perms '.count($ids);
1265
1266  $search_results['qs']['matching_tags'] = $qsr->all_tags;
1267  global $template;
1268
1269  if (empty($ids))
1270  {
1271    $debug[] = '-->';
1272    $template->append('footer_elements', implode("\n", $debug) );
1273    return $search_results;
1274  }
1275
1276  $permissions = !isset($options['permissions']) ? true : $options['permissions'];
1277
1278  $where_clauses = array();
1279  $where_clauses[]='i.id IN ('. implode(',', $ids) . ')';
1280  if (!empty($options['images_where']))
1281  {
1282    $where_clauses[]='('.$images_where.')';
1283  }
1284  if ($permissions)
1285  {
1286    $where_clauses[] = get_sql_condition_FandF(
1287        array
1288          (
1289            'forbidden_categories' => 'category_id',
1290            'visible_categories' => 'category_id',
1291            'visible_images' => 'i.id'
1292          ),
1293        null,true
1294      );
1295  }
1296
1297  $query = '
1298SELECT DISTINCT(id) FROM '.IMAGES_TABLE.' i';
1299  if ($permissions)
1300  {
1301    $query .= '
1302    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id';
1303  }
1304  $query .= '
1305  WHERE '.implode("\n AND ", $where_clauses)."\n".
1306  $conf['order_by'];
1307
1308  $ids = query2array($query, null, 'id');
1309
1310  $debug[] = count($ids).' final photo count -->';
1311  $template->append('footer_elements', implode("\n", $debug) );
1312
1313  $search_results['items'] = $ids;
1314  return $search_results;
1315}
1316
1317/**
1318 * Returns an array of 'items' corresponding to the search id.
1319 * It can be either a quick search or a regular search.
1320 *
1321 * @param int $search_id
1322 * @param bool $super_order_by
1323 * @param string $images_where optional aditional restriction on images table
1324 * @return array
1325 */
1326function get_search_results($search_id, $super_order_by, $images_where='')
1327{
1328  $search = get_search_array($search_id);
1329  if ( !isset($search['q']) )
1330  {
1331    $result['items'] = get_regular_search_results($search, $images_where);
1332    return $result;
1333  }
1334  else
1335  {
1336    return get_quick_search_results($search['q'], array('super_order_by'=>$super_order_by, 'images_where'=>$images_where) );
1337  }
1338}
1339
1340?>
Note: See TracBrowser for help on using the repository browser.