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

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

bug 3056: quick search - better handling of short words and photo acronyms such as AF-S EF-S X-E2 etc ...

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