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

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

bug 3056: quick search - fix variable name

  • 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
837    if ($use_ft)
838    {
839      $max = max( array_map( 'mb_strlen', 
840        preg_split('/['.preg_quote('!"#$%&()*+,./:;<=>?@[\]^`{|}~','/').']+/', $variant, PREG_SPLIT_NO_EMPTY)
841        ) );
842      if ($max<4)
843        $use_ft = false;
844    }
845
846    if (!$use_ft)
847    {// odd term or too short for full text search; fallback to regex but unfortunately this is diacritic/accent sensitive
848      $pre = ($token->modifier & QST_WILDCARD_BEGIN) ? '' : '[[:<:]]';
849      $post = ($token->modifier & QST_WILDCARD_END) ? '' : '[[:>:]]';
850      foreach( $fields as $field)
851        $clauses[] = $field.' REGEXP \''.$pre.addslashes(preg_quote($variant)).$post.'\'';
852    }
853    else
854    {
855      $ft = $variant;
856      if ($token->modifier & QST_QUOTED)
857        $ft = '"'.$ft.'"';
858      if ($token->modifier & QST_WILDCARD_END)
859        $ft .= '*';
860      $fts[] = $ft;
861    }
862  }
863
864  if (count($fts))
865  {
866    $clauses[] = 'MATCH('.implode(', ',$fields).') AGAINST( \''.addslashes(implode(' ',$fts)).'\' IN BOOLEAN MODE)';
867  }
868  return $clauses;
869}
870
871function qsearch_get_images(QExpression $expr, QResults $qsr)
872{
873  $qsr->images_iids = array_fill(0, count($expr->stokens), array());
874
875  $query_base = 'SELECT id from '.IMAGES_TABLE.' i WHERE
876';
877  for ($i=0; $i<count($expr->stokens); $i++)
878  {
879    $token = $expr->stokens[$i];
880    $scope_id = isset($token->scope) ? $token->scope->id : 'photo';
881    $clauses = array();
882
883    $like = addslashes($token->term);
884    $like = str_replace( array('%','_'), array('\\%','\\_'), $like); // escape LIKE specials %_
885    $file_like = 'CONVERT(file, CHAR) LIKE \'%'.$like.'%\'';
886
887    switch ($scope_id)
888    {
889      case 'photo':
890        $clauses[] = $file_like;
891        $clauses = array_merge($clauses, qsearch_get_text_token_search_sql($token, array('name','comment')));
892        break;
893
894      case 'file':
895        $clauses[] = $file_like;
896        break;
897      case 'width':
898      case 'height':
899        $clauses[] = $token->scope->get_sql($scope_id, $token);
900        break;
901      case 'ratio':
902        $clauses[] = $token->scope->get_sql('width/height', $token);
903        break;
904      case 'size':
905        $clauses[] = $token->scope->get_sql('width*height', $token);
906        break;
907      case 'hits':
908        $clauses[] = $token->scope->get_sql('hit', $token);
909        break;
910      case 'score':
911        $clauses[] = $token->scope->get_sql('rating_score', $token);
912        break;
913      case 'filesize':
914        $clauses[] = $token->scope->get_sql('1024*filesize', $token);
915        break;
916      case 'created':
917        $clauses[] = $token->scope->get_sql('date_creation', $token);
918        break;
919      case 'posted':
920        $clauses[] = $token->scope->get_sql('date_available', $token);
921        break;
922      default:
923        // allow plugins to have their own scope with columns added in db by themselves
924        $clauses = trigger_event('qsearch_get_images_sql_scopes', $clauses, $token, $expr);
925        break;
926    }
927    if (!empty($clauses))
928    {
929      $query = $query_base.'('.implode("\n OR ", $clauses).')';
930      $qsr->images_iids[$i] = query2array($query,null,'id');
931    }
932  }
933}
934
935function qsearch_get_tags(QExpression $expr, QResults $qsr)
936{
937  $token_tag_ids = $qsr->tag_iids = array_fill(0, count($expr->stokens), array() );
938  $all_tags = array();
939
940  for ($i=0; $i<count($expr->stokens); $i++)
941  {
942    $token = $expr->stokens[$i];
943    if (isset($token->scope) && 'tag' != $token->scope->id)
944      continue;
945    if (empty($token->term))
946      continue;
947
948    $clauses = qsearch_get_text_token_search_sql( $token, array('name'));
949    $query = 'SELECT * FROM '.TAGS_TABLE.'
950WHERE ('. implode("\n OR ",$clauses) .')';
951    $result = pwg_query($query);
952    while ($tag = pwg_db_fetch_assoc($result))
953    {
954      $token_tag_ids[$i][] = $tag['id'];
955      $all_tags[$tag['id']] = $tag;
956    }
957  }
958
959  // check adjacent short words
960  for ($i=0; $i<count($expr->stokens)-1; $i++)
961  {
962    if ( (strlen($expr->stokens[$i])<=3 || strlen($expr->stokens[$i+1])<=3)
963      && (($expr->stoken_modifiers[$i] & (QST_QUOTED|QST_WILDCARD)) == 0)
964      && (($expr->stoken_modifiers[$i+1] & (QST_BREAK|QST_QUOTED|QST_WILDCARD)) == 0) )
965    {
966      $common = array_intersect( $token_tag_ids[$i], $token_tag_ids[$i+1] );
967      if (count($common))
968      {
969        $token_tag_ids[$i] = $token_tag_ids[$i+1] = $common;
970      }
971    }
972  }
973
974  // get images
975  $positive_ids = $not_ids = array();
976  for ($i=0; $i<count($expr->stokens); $i++)
977  {
978    $tag_ids = $token_tag_ids[$i];
979    $token = $expr->stokens[$i];
980
981    if (!empty($tag_ids))
982    {
983      $query = '
984SELECT image_id FROM '.IMAGE_TAG_TABLE.'
985  WHERE tag_id IN ('.implode(',',$tag_ids).')
986  GROUP BY image_id';
987      $qsr->tag_iids[$i] = query2array($query, null, 'image_id');
988      if ($expr->stoken_modifiers[$i]&QST_NOT)
989        $not_ids = array_merge($not_ids, $tag_ids);
990      else
991        $positive_ids = array_merge($positive_ids, $tag_ids);
992    }
993    elseif (isset($token->scope) && 'tag' == $token->scope->id && strlen($token->term)==0)
994    {
995      if ($tokens[$i]->modifier & QST_WILDCARD)
996      {// eg. 'tag:*' returns all tagged images
997        $qsr->tag_iids[$i] = query2array('SELECT DISTINCT image_id FROM '.IMAGE_TAG_TABLE, null, 'image_id');
998      }
999      else
1000      {// eg. 'tag:' returns all untagged images
1001        $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');
1002      }
1003    }
1004  }
1005
1006  $all_tags = array_intersect_key($all_tags, array_flip( array_diff($positive_ids, $not_ids) ) );
1007  usort($all_tags, 'tag_alpha_compare');
1008  foreach ( $all_tags as &$tag )
1009  {
1010    $tag['name'] = trigger_event('render_tag_name', $tag['name'], $tag);
1011  }
1012  $qsr->all_tags = $all_tags;
1013  $qsr->tag_ids = $token_tag_ids;
1014}
1015
1016
1017
1018function qsearch_eval(QMultiToken $expr, QResults $qsr, &$qualifies, &$ignored_terms)
1019{
1020  $qualifies = false; // until we find at least one positive term
1021  $ignored_terms = array();
1022
1023  $ids = $not_ids = array();
1024
1025  for ($i=0; $i<count($expr->tokens); $i++)
1026  {
1027    $crt = $expr->tokens[$i];
1028    if ($crt->is_single)
1029    {
1030      $crt_ids = $qsr->iids[$crt->idx] = array_unique( array_merge($qsr->images_iids[$crt->idx], $qsr->tag_iids[$crt->idx]) );
1031      $crt_qualifies = count($crt_ids)>0 || count($qsr->tag_ids[$crt->idx])>0;
1032      $crt_ignored_terms = $crt_qualifies ? array() : array($crt->term);
1033    }
1034    else
1035      $crt_ids = qsearch_eval($crt, $qsr, $crt_qualifies, $crt_ignored_terms);
1036
1037    $modifier = $crt->modifier;
1038    if ($modifier & QST_NOT)
1039      $not_ids = array_unique( array_merge($not_ids, $crt_ids));
1040    else
1041    {
1042      $ignored_terms = array_merge($ignored_terms, $crt_ignored_terms);
1043      if ($modifier & QST_OR)
1044      {
1045        $ids = array_unique( array_merge($ids, $crt_ids) );
1046        $qualifies |= $crt_qualifies;
1047      }
1048      elseif ($crt_qualifies)
1049      {
1050        if ($qualifies)
1051          $ids = array_intersect($ids, $crt_ids);
1052        else
1053          $ids = $crt_ids;
1054        $qualifies = true;
1055      }
1056    }
1057  }
1058
1059  if (count($not_ids))
1060    $ids = array_diff($ids, $not_ids);
1061  return $ids;
1062}
1063
1064/**
1065 * Returns the search results corresponding to a quick/query search.
1066 * A quick/query search returns many items (search is not strict), but results
1067 * are sorted by relevance unless $super_order_by is true. Returns:
1068 *  array (
1069 *    'items' => array of matching images
1070 *    'qs'    => array(
1071 *      'unmatched_terms' => array of terms from the input string that were not matched
1072 *      'matching_tags' => array of matching tags
1073 *      'matching_cats' => array of matching categories
1074 *      'matching_cats_no_images' =>array(99) - matching categories without images
1075 *      )
1076 *    )
1077 *
1078 * @param string $q
1079 * @param bool $super_order_by
1080 * @param string $images_where optional additional restriction on images table
1081 * @return array
1082 */
1083function get_quick_search_results($q, $options)
1084{
1085  global $conf;
1086  //@TODO: maybe cache for 10 minutes the result set to avoid many expensive sql calls when navigating the pictures
1087  $q = trim(stripslashes($q));
1088  $search_results =
1089    array(
1090      'items' => array(),
1091      'qs' => array('q'=>$q),
1092    );
1093
1094  $scopes = array();
1095  $scopes[] = new QSearchScope('tag', array('tags'));
1096  $scopes[] = new QSearchScope('photo', array('photos'));
1097  $scopes[] = new QSearchScope('file', array('filename'));
1098  $scopes[] = new QNumericRangeScope('width', array());
1099  $scopes[] = new QNumericRangeScope('height', array());
1100  $scopes[] = new QNumericRangeScope('ratio', array(), false, 0.001);
1101  $scopes[] = new QNumericRangeScope('size', array());
1102  $scopes[] = new QNumericRangeScope('filesize', array());
1103  $scopes[] = new QNumericRangeScope('hits', array('hit', 'visit', 'visits'));
1104  $scopes[] = new QNumericRangeScope('score', array('rating'), true);
1105
1106  $createdDateAliases = array('taken', 'shot');
1107  $postedDateAliases = array('added');
1108  if ($conf['calendar_datefield'] == 'date_creation')
1109    $createdDateAliases[] = 'date';
1110  else
1111    $postedDateAliases[] = 'date';
1112  $scopes[] = new QDateRangeScope('created', $createdDateAliases, true);
1113  $scopes[] = new QDateRangeScope('posted', $postedDateAliases);
1114
1115  // allow plugins to add their own scopes
1116  $scopes = trigger_event('qsearch_get_scopes', $scopes);
1117  $expression = new QExpression($q, $scopes);
1118
1119  // get inflections for terms
1120  $inflector = null;
1121  $lang_code = substr(get_default_language(),0,2);
1122  @include_once(PHPWG_ROOT_PATH.'include/inflectors/'.$lang_code.'.php');
1123  $class_name = 'Inflector_'.$lang_code;
1124  if (class_exists($class_name))
1125  {
1126    $inflector = new $class_name;
1127    foreach( $expression->stokens as $token)
1128    {
1129      if (isset($token->scope) && !$token->scope->is_text)
1130        continue;
1131      if (strlen($token->term)>2
1132        && ($token->modifier & (QST_QUOTED|QST_WILDCARD))==0
1133        && strcspn($token->term, '\'0123456789') == strlen($token->term) )
1134      {
1135        $token->variants = array_unique( array_diff( $inflector->get_variants($token->term), array($token->term) ) );
1136      }
1137    }
1138  }
1139
1140
1141  trigger_action('qsearch_expression_parsed', $expression);
1142//var_export($expression);
1143
1144  if (count($expression->stokens)==0)
1145  {
1146    return $search_results;
1147  }
1148  $qsr = new QResults;
1149  qsearch_get_tags($expression, $qsr);
1150  qsearch_get_images($expression, $qsr);
1151
1152  // allow plugins to evaluate their own scopes
1153  trigger_action('qsearch_before_eval', $expression, $qsr);
1154
1155  $ids = qsearch_eval($expression, $qsr, $tmp, $search_results['qs']['unmatched_terms']);
1156
1157  $debug[] = "<!--\nparsed: ".$expression;
1158  $debug[] = count($expression->stokens).' tokens';
1159  for ($i=0; $i<count($expression->stokens); $i++)
1160  {
1161    $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'
1162      .' modifier:'.dechex($expression->stoken_modifiers[$i])
1163      .( !empty($expression->stokens[$i]->variants) ? ' variants: '.implode(', ',$expression->stokens[$i]->variants): '');
1164  }
1165  $debug[] = 'before perms '.count($ids);
1166
1167  $search_results['qs']['matching_tags'] = $qsr->all_tags;
1168  global $template;
1169
1170  if (empty($ids))
1171  {
1172    $debug[] = '-->';
1173    $template->append('footer_elements', implode("\n", $debug) );
1174    return $search_results;
1175  }
1176
1177  $permissions = !isset($options['permissions']) ? true : $options['permissions'];
1178
1179  $where_clauses = array();
1180  $where_clauses[]='i.id IN ('. implode(',', $ids) . ')';
1181  if (!empty($options['images_where']))
1182  {
1183    $where_clauses[]='('.$options['images_where'].')';
1184  }
1185  if ($permissions)
1186  {
1187    $where_clauses[] = get_sql_condition_FandF(
1188        array
1189          (
1190            'forbidden_categories' => 'category_id',
1191            'visible_categories' => 'category_id',
1192            'visible_images' => 'i.id'
1193          ),
1194        null,true
1195      );
1196  }
1197
1198  $query = '
1199SELECT DISTINCT(id) FROM '.IMAGES_TABLE.' i';
1200  if ($permissions)
1201  {
1202    $query .= '
1203    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id';
1204  }
1205  $query .= '
1206  WHERE '.implode("\n AND ", $where_clauses)."\n".
1207  $conf['order_by'];
1208
1209  $ids = query2array($query, null, 'id');
1210
1211  $debug[] = count($ids).' final photo count -->';
1212  $template->append('footer_elements', implode("\n", $debug) );
1213
1214  $search_results['items'] = $ids;
1215  return $search_results;
1216}
1217
1218/**
1219 * Returns an array of 'items' corresponding to the search id.
1220 * It can be either a quick search or a regular search.
1221 *
1222 * @param int $search_id
1223 * @param bool $super_order_by
1224 * @param string $images_where optional aditional restriction on images table
1225 * @return array
1226 */
1227function get_search_results($search_id, $super_order_by, $images_where='')
1228{
1229  $search = get_search_array($search_id);
1230  if ( !isset($search['q']) )
1231  {
1232    $result['items'] = get_regular_search_results($search, $images_where);
1233    return $result;
1234  }
1235  else
1236  {
1237    return get_quick_search_results($search['q'], array('super_order_by'=>$super_order_by, 'images_where'=>$images_where) );
1238  }
1239}
1240
1241?>
Note: See TracBrowser for help on using the repository browser.