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

Last change on this file since 28587 was 28587, checked in by mistic100, 10 years ago

feature 3010 : replace trigger_action/event by trigger_notify/change

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