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

Last change on this file since 28913 was 28709, checked in by plg, 10 years ago

feature 3093: search form, ability to select the list of properties on which
the search terms applies.

feature 3094: minor redesign on search form.

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