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

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

bug 3056 quick search - fix regex for date searches (was not working with months 11 and 12)

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