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

Last change on this file since 25933 was 25658, checked in by mistic100, 11 years ago

feature 2999: documentation of functions_search and functions_tag

  • Property svn:eol-style set to LF
File size: 22.7 KB
RevLine 
[1113]1<?php
2// +-----------------------------------------------------------------------+
[8728]3// | Piwigo - a PHP based photo gallery                                    |
[2297]4// +-----------------------------------------------------------------------+
[19703]5// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
[2297]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// +-----------------------------------------------------------------------+
[1113]23
[25658]24/**
25 * @package functions\search
26 */
[1113]27
[25658]28
[1113]29/**
[25658]30 * Returns search rules stored into a serialized array in "search"
[1113]31 * table. Each search rules set is numericaly identified.
32 *
[25658]33 * @param int $search_id
[1113]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;';
[4325]48  list($serialized_rules) = pwg_db_fetch_row(pwg_query($query));
[1113]49
50  return unserialize($serialized_rules);
51}
52
53/**
[25658]54 * Returns the SQL clause for a search.
55 * Transforms the array returned by get_search_array() into SQL sub-query.
[1113]56 *
[25658]57 * @param array $search
[1113]58 * @return string
59 */
[1537]60function get_sql_search_clause($search)
[1113]61{
62  // SQL where clauses are stored in $clauses array during query
63  // construction
64  $clauses = array();
65
[1119]66  foreach (array('file','name','comment','author') as $textfield)
[1113]67  {
68    if (isset($search['fields'][$textfield]))
69    {
70      $local_clauses = array();
71      foreach ($search['fields'][$textfield]['words'] as $word)
72      {
[25018]73        $local_clauses[] = $textfield." LIKE '%".$word."%'";
[1113]74      }
75
76      // adds brackets around where clauses
77      $local_clauses = prepend_append_array_items($local_clauses, '(', ')');
78
[25018]79      $clauses[] = implode(
80        ' '.$search['fields'][$textfield]['mode'].' ',
81        $local_clauses
[1113]82        );
83    }
84  }
85
86  if (isset($search['fields']['allwords']))
87  {
[1119]88    $fields = array('file', 'name', 'comment', 'author');
[1113]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      {
[25018]102        $field_clauses[] = $field." LIKE '%".$word."%'";
[1113]103      }
104      // adds brackets around where clauses
[25018]105      $word_clauses[] = implode(
106        "\n          OR ",
107        $field_clauses
[1113]108        );
109    }
110
111    array_walk(
112      $word_clauses,
113      create_function('&$s','$s="(".$s.")";')
114      );
115
[25018]116    $clauses[] = "\n         ".
[1113]117      implode(
[25018]118        "\n         ". $search['fields']['allwords']['mode']. "\n         ",
[1113]119        $word_clauses
[25018]120        );
[1113]121  }
122
123  foreach (array('date_available', 'date_creation') as $datefield)
124  {
125    if (isset($search['fields'][$datefield]))
126    {
[25026]127      $clauses[] = $datefield." = '".$search['fields'][$datefield]['date']."'";
[1113]128    }
129
130    foreach (array('after','before') as $suffix)
131    {
132      $key = $datefield.'-'.$suffix;
133
134      if (isset($search['fields'][$key]))
135      {
[25018]136        $clauses[] = $datefield.
[1113]137          ($suffix == 'after'             ? ' >' : ' <').
138          ($search['fields'][$key]['inc'] ? '='  : '').
[25018]139          " '".$search['fields'][$key]['date']."'";
[1113]140      }
141    }
142  }
143
144  if (isset($search['fields']['cat']))
145  {
146    if ($search['fields']['cat']['sub_inc'])
147    {
148      // searching all the categories id of sub-categories
149      $cat_ids = get_subcat_ids($search['fields']['cat']['words']);
150    }
151    else
152    {
153      $cat_ids = $search['fields']['cat']['words'];
154    }
155
156    $local_clause = 'category_id IN ('.implode(',', $cat_ids).')';
[25018]157    $clauses[] = $local_clause;
[1113]158  }
159
160  // adds brackets around where clauses
161  $clauses = prepend_append_array_items($clauses, '(', ')');
162
163  $where_separator =
164    implode(
165      "\n    ".$search['mode'].' ',
166      $clauses
167      );
168
169  $search_clause = $where_separator;
170
[1119]171  return $search_clause;
172}
173
174/**
[25658]175 * Returns the list of items corresponding to the advanced search array.
[1119]176 *
[25658]177 * @param array $search
178 * @param string $images_where optional additional restriction on images table
[1119]179 * @return array
180 */
[25658]181function get_regular_search_results($search, $images_where='')
[1119]182{
[2451]183  global $conf;
184  $forbidden = get_sql_condition_FandF(
185        array
186          (
187            'forbidden_categories' => 'category_id',
188            'visible_categories' => 'category_id',
189            'visible_images' => 'id'
190          ),
191        "\n  AND"
192    );
193
[1119]194  $items = array();
[2451]195  $tag_items = array();
[1537]196
[2451]197  if (isset($search['fields']['tags']))
198  {
199    $tag_items = get_image_ids_for_tags(
200      $search['fields']['tags']['words'],
201      $search['fields']['tags']['mode']
202      );
203  }
204
[1537]205  $search_clause = get_sql_search_clause($search);
206
[1119]207  if (!empty($search_clause))
[1113]208  {
[1119]209    $query = '
[8611]210SELECT DISTINCT(id)
[2451]211  FROM '.IMAGES_TABLE.' i
[1119]212    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
[2451]213  WHERE '.$search_clause;
214    if (!empty($images_where))
215    {
216      $query .= "\n  AND ".$images_where;
217    }
[8726]218    $query .= $forbidden.'
[2451]219  '.$conf['order_by'];
[1119]220    $items = array_from_query($query, 'id');
[1113]221  }
222
[2451]223  if ( !empty($tag_items) )
[1119]224  {
225    switch ($search['mode'])
226    {
227      case 'AND':
228        if (empty($search_clause))
229        {
230          $items = $tag_items;
231        }
232        else
233        {
[5691]234          $items = array_values( array_intersect($items, $tag_items) );
[1119]235        }
236        break;
237      case 'OR':
[2451]238        $before_count = count($items);
[1119]239        $items = array_unique(
240          array_merge(
241            $items,
242            $tag_items
243            )
244          );
245        break;
[2451]246    }
[1119]247  }
[1537]248
[1119]249  return $items;
[1113]250}
[1537]251
[25658]252/**
253 * Finds if a char is a letter, a figure or any char of the extended ASCII table (>127).
254 *
255 * @param char $ch
256 * @return bool
257 */
[10340]258function is_word_char($ch)
259{
260  return ($ch>='0' && $ch<='9') || ($ch>='a' && $ch<='z') || ($ch>='A' && $ch<='Z') || ord($ch)>127;
261}
262
[25658]263/**
264 * Finds if a char is a special token for word start: [{<=*+
265 *
266 * @param char $ch
267 * @return bool
268 */
[18207]269function is_odd_wbreak_begin($ch)
270{
271  return strpos('[{<=*+', $ch)===false ? false:true;
272}
273
[25658]274/**
275 * Finds if a char is a special token for word end: ]}>=*+
276 *
277 * @param char $ch
278 * @return bool
279 */
[18207]280function is_odd_wbreak_end($ch)
281{
282  return strpos(']}>=*+', $ch)===false ? false:true;
283}
284
[25658]285
286define('QST_QUOTED',         0x01);
287define('QST_NOT',            0x02);
288define('QST_WILDCARD_BEGIN', 0x04);
289define('QST_WILDCARD_END',   0x08);
[18207]290define('QST_WILDCARD', QST_WILDCARD_BEGIN|QST_WILDCARD_END);
291
[1619]292/**
[25658]293 * Analyzes and splits the quick/query search query $q into tokens.
[10340]294 * q='john bill' => 2 tokens 'john' 'bill'
295 * Special characters for MySql full text search (+,<,>,~) appear in the token modifiers.
296 * The query can contain a phrase: 'Pierre "New York"' will return 'pierre' qnd 'new york'.
[25658]297 *
298 * @param string $q
299 * @param array &$qtokens
300 * @param array &$qtoken_modifiers
[1619]301 */
[10340]302function analyse_qsearch($q, &$qtokens, &$qtoken_modifiers)
[1537]303{
[2135]304  $q = stripslashes($q);
305  $tokens = array();
306  $token_modifiers = array();
307  $crt_token = "";
[18207]308  $crt_token_modifier = 0;
[2135]309
310  for ($i=0; $i<strlen($q); $i++)
[1537]311  {
[2135]312    $ch = $q[$i];
[18636]313    if ( ($crt_token_modifier&QST_QUOTED)==0)
[1537]314    {
[2135]315        if ($ch=='"')
316        {
[18207]317          if (strlen($crt_token))
318          {
319            $tokens[] = $crt_token; $token_modifiers[] = $crt_token_modifier;
320            $crt_token = ""; $crt_token_modifier = 0;
321          }
322          $crt_token_modifier |= QST_QUOTED;
[2135]323        }
[18207]324        elseif ( strcspn($ch, '*+-><~')==0 )
325        { //special full text modifier
[10340]326          if (strlen($crt_token))
327          {
328            $crt_token .= $ch;
329          }
330          else
331          {
[18207]332            if ( $ch=='*' )
333              $crt_token_modifier |= QST_WILDCARD_BEGIN;
334            if ( $ch=='-' )
335              $crt_token_modifier |= QST_NOT;
[10340]336          }
[2135]337        }
338        elseif (preg_match('/[\s,.;!\?]+/', $ch))
339        { // white space
340          if (strlen($crt_token))
341          {
[10340]342            $tokens[] = $crt_token; $token_modifiers[] = $crt_token_modifier;
[18207]343            $crt_token = "";
[2135]344          }
[18207]345          $crt_token_modifier = 0;
[2135]346        }
347        else
348        {
349          $crt_token .= $ch;
350        }
[18207]351    }
352    else // qualified with quotes
353    {
354      if ($ch=='"')
355      {
356        if ($i+1 < strlen($q) && $q[$i+1]=='*')
[2135]357        {
[18207]358          $crt_token_modifier |= QST_WILDCARD_END;
359          $i++;
[2135]360        }
[18207]361        $tokens[] = $crt_token; $token_modifiers[] = $crt_token_modifier;
362        $crt_token = ""; $crt_token_modifier = 0;
363        $state=0;
364      }
365      else
366        $crt_token .= $ch;
[1537]367    }
368  }
[18636]369
[2135]370  if (strlen($crt_token))
371  {
372    $tokens[] = $crt_token;
373    $token_modifiers[] = $crt_token_modifier;
374  }
[1537]375
[10340]376  $qtokens = array();
377  $qtoken_modifiers = array();
378  for ($i=0; $i<count($tokens); $i++)
379  {
[22175]380    if ( !($token_modifiers[$i] & QST_QUOTED) )
[10340]381    {
382      if ( substr($tokens[$i], -1)=='*' )
383      {
384        $tokens[$i] = rtrim($tokens[$i], '*');
[22175]385        $token_modifiers[$i] |= QST_WILDCARD_END;
[10340]386      }
387    }
388    if ( strlen($tokens[$i])==0)
389      continue;
390    $qtokens[] = $tokens[$i];
391    $qtoken_modifiers[] = $token_modifiers[$i];
392  }
393}
394
395/**
[25658]396 * Returns the LIKE SQL clause corresponding to the quick search query
397 * that has been split into tokens.
[10340]398 * for example file LIKE '%john%' OR file LIKE '%bill%'.
[25658]399 *
400 * @param array $tokens
401 * @param array $token_modifiers
402 * @param string $field
403 * @return string|null
[10340]404 */
405function get_qsearch_like_clause($tokens, $token_modifiers, $field)
406{
[2135]407  $clauses = array();
408  for ($i=0; $i<count($tokens); $i++)
[1537]409  {
[10340]410    $token = trim($tokens[$i], '%');
[18207]411    if ($token_modifiers[$i]&QST_NOT)
[2135]412      continue;
[11979]413    if ( strlen($token)==0 )
[2135]414      continue;
[10340]415    $token = addslashes($token);
416    $token = str_replace( array('%','_'), array('\\%','\\_'), $token); // escape LIKE specials %_
417    $clauses[] = $field.' LIKE \'%'.$token.'%\'';
[1537]418  }
[2135]419
420  return count($clauses) ? '('.implode(' OR ', $clauses).')' : null;
[1537]421}
422
423/**
[25658]424 * Returns tags corresponding to the quick search query that has been split into tokens.
425 *
426 * @param array $tokens
427 * @param array $token_modifiers
428 * @param array &$token_tag_ids
429 * @param array &$not_tag_ids
430 * @param array &$all_tags
431 */
[18636]432function get_qsearch_tags($tokens, $token_modifiers, &$token_tag_ids, &$not_tag_ids, &$all_tags)
[1537]433{
[18636]434  $token_tag_ids = array_fill(0, count($tokens), array() );
435  $not_tag_ids = $all_tags = array();
[10340]436
[18636]437  $token_tag_scores = $token_tag_ids;
[10340]438  $transliterated_tokens = array();
439  foreach ($tokens as $token)
440  {
441    $transliterated_tokens[] = transliterate($token);
442  }
443
444  $query = '
[18636]445SELECT t.*, COUNT(image_id) AS counter
446  FROM '.TAGS_TABLE.' t
[10340]447    INNER JOIN '.IMAGE_TAG_TABLE.' ON id=tag_id
448  GROUP BY id';
449  $result = pwg_query($query);
450  while ($tag = pwg_db_fetch_assoc($result))
451  {
452    $transliterated_tag = transliterate($tag['name']);
453
454    // find how this tag matches query tokens
455    for ($i=0; $i<count($tokens); $i++)
456    {
457      $transliterated_token = $transliterated_tokens[$i];
458
459      $match = false;
460      $pos = 0;
461      while ( ($pos = strpos($transliterated_tag, $transliterated_token, $pos)) !== false)
462      {
[18207]463        if ( ($token_modifiers[$i]&QST_WILDCARD)==QST_WILDCARD )
[10340]464        {// wildcard in this token
465          $match = 1;
466          break;
467        }
468        $token_len = strlen($transliterated_token);
469
[18207]470        // search begin of word
471        $wbegin_len=0; $wbegin_char=' ';
472        while ($pos-$wbegin_len > 0)
[10340]473        {
[18207]474          if (! is_word_char($transliterated_tag[$pos-$wbegin_len-1]) )
475          {
476            $wbegin_char = $transliterated_tag[$pos-$wbegin_len-1];
[10340]477            break;
[18207]478          }
479          $wbegin_len++;
[10340]480        }
481
[18207]482        // search end of word
483        $wend_len=0; $wend_char=' ';
484        while ($pos+$token_len+$wend_len < strlen($transliterated_tag))
[10340]485        {
[18207]486          if (! is_word_char($transliterated_tag[$pos+$token_len+$wend_len]) )
487          {
488            $wend_char = $transliterated_tag[$pos+$token_len+$wend_len];
489            break;
490          }
491          $wend_len++;
[10340]492        }
493
[18207]494        $this_score = 0;
495        if ( ($token_modifiers[$i]&QST_WILDCARD)==0 )
496        {// no wildcard begin or end
497          if ($token_len <= 2)
498          {// search for 1 or 2 characters must match exactly to avoid retrieving too much data
499            if ($wbegin_len==0 && $wend_len==0 && !is_odd_wbreak_begin($wbegin_char) && !is_odd_wbreak_end($wend_char) )
500              $this_score = 1;
501          }
502          elseif ($token_len == 3)
503          {
504            if ($wbegin_len==0)
505              $this_score = $token_len / ($token_len + $wend_len);
506          }
507          else
508          {
509            $this_score = $token_len / ($token_len + 1.1 * $wbegin_len + 0.9 * $wend_len);
510          }
511        }
512
[10340]513        if ($this_score>0)
514          $match = max($match, $this_score );
515        $pos++;
516      }
517
518      if ($match)
519      {
520        $tag_id = (int)$tag['id'];
521        $all_tags[$tag_id] = $tag;
[18636]522        $token_tag_ids[$i][] = $tag_id;
523        $token_tag_scores[$i][] = $match;
[10340]524      }
525    }
526  }
527
[18636]528  // process not tags
529  for ($i=0; $i<count($tokens); $i++)
[10340]530  {
[18636]531    if ( ! ($token_modifiers[$i]&QST_NOT) )
532      continue;
533
534    array_multisort($token_tag_scores[$i], SORT_DESC|SORT_NUMERIC, $token_tag_ids[$i]);
535
536    for ($j=0; $j<count($token_tag_scores[$i]); $j++)
[10340]537    {
[18636]538      if ($token_tag_scores[$i][$j] < 0.8)
539        break;
540      if ($j>0 && $token_tag_scores[$i][$j] < $token_tag_scores[$i][0])
541        break;
542      $tag_id = $token_tag_ids[$i][$j];
543      if ( isset($all_tags[$tag_id]) )
544      {
545        unset($all_tags[$tag_id]);
546        $not_tag_ids[] = $tag_id;
547      }
548    }
549    $token_tag_ids[$i] = array();
550  }
551
552  // process regular tags
553  for ($i=0; $i<count($tokens); $i++)
554  {
555    if ( $token_modifiers[$i]&QST_NOT )
556      continue;
557
558    array_multisort($token_tag_scores[$i], SORT_DESC|SORT_NUMERIC, $token_tag_ids[$i]);
559
560    $counter = 0;
561    for ($j=0; $j<count($token_tag_scores[$i]); $j++)
562    {
563      $tag_id = $token_tag_ids[$i][$j];
564      if ( ! isset($all_tags[$tag_id]) )
565      {
566        array_splice($token_tag_ids[$i], $j, 1);
567        array_splice($token_tag_scores[$i], $j, 1);
[22175]568        $j--;
569        continue;
[18636]570      }
571
572      $counter += $all_tags[$tag_id]['counter'];
573      if ($counter > 200 && $j>0 && $token_tag_scores[$i][0] > $token_tag_scores[$i][$j] )
[10340]574      {// "many" images in previous tags and starting from this tag is less relevent
[18636]575        array_splice($token_tag_ids[$i], $j);
576        array_splice($token_tag_scores[$i], $j);
[10340]577        break;
578      }
579    }
580  }
[22175]581
[18636]582  usort($all_tags, 'tag_alpha_compare');
583  foreach ( $all_tags as &$tag )
[25658]584  {
[18636]585    $tag['name'] = trigger_event('render_tag_name', $tag['name']);
[25658]586  }
[18636]587}
[10340]588
[18636]589/**
[25658]590 * Returns the search results corresponding to a quick/query search.
[18636]591 * A quick/query search returns many items (search is not strict), but results
592 * are sorted by relevance unless $super_order_by is true. Returns:
[25658]593 *  array (
594 *    'items' => array of matching images
595 *    'qs'    => array(
596 *      'matching_tags' => array of matching tags
597 *      'matching_cats' => array of matching categories
598 *      'matching_cats_no_images' =>array(99) - matching categories without images
599 *      )
600 *    )
[18636]601 *
[25658]602 * @param string $q
603 * @param bool $super_order_by
604 * @param string $images_where optional additional restriction on images table
[18636]605 * @return array
606 */
607function get_quick_search_results($q, $super_order_by, $images_where='')
608{
609  global $user, $conf;
610
611  $search_results =
612    array(
613      'items' => array(),
614      'qs' => array('q'=>stripslashes($q)),
615    );
616  $q = trim($q);
617  analyse_qsearch($q, $tokens, $token_modifiers);
618  if (count($tokens)==0)
[10340]619  {
[18636]620    return $search_results;
621  }
622  $debug[] = '<!--'.count($tokens).' tokens';
623
624  $q_like_field = '@@__db_field__@@'; //something never in a search
625  $q_like_clause = get_qsearch_like_clause($tokens, $token_modifiers, $q_like_field );
626
627  // Step 1 - first we find matches in #images table ===========================
628  $where_clauses='MATCH(i.name, i.comment) AGAINST( \''.$q.'\' IN BOOLEAN MODE)';
629  if (!empty($q_like_clause))
630  {
631    $where_clauses .= '
632    OR '. str_replace($q_like_field, 'CONVERT(file, CHAR)', $q_like_clause);
633    $where_clauses = '('.$where_clauses.')';
634  }
635  $where_clauses = array($where_clauses);
636  if (!empty($images_where))
637  {
638    $where_clauses[]='('.$images_where.')';
639  }
640  $where_clauses[] .= get_sql_condition_FandF
641      (
642        array( 'visible_images' => 'i.id' ), null, true
643      );
644  $query = '
645SELECT i.id,
646    MATCH(i.name, i.comment) AGAINST( \''.$q.'\' IN BOOLEAN MODE) AS weight
647  FROM '.IMAGES_TABLE.' i
648  WHERE '.implode("\n AND ", $where_clauses);
649
650  $by_weights=array();
651  $result = pwg_query($query);
652  while ($row = pwg_db_fetch_assoc($result))
653  { // weight is important when sorting images by relevance
654    if ($row['weight'])
655    {
656      $by_weights[(int)$row['id']] =  2*$row['weight'];
657    }
658    else
659    {//full text does not match but file name match
660      $by_weights[(int)$row['id']] =  2;
661    }
662  }
663  $debug[] = count($by_weights).' fulltext';
664  if (!empty($by_weights))
665  {
666    $debug[] = 'ft score min:'.min($by_weights).' max:'.max($by_weights);
667  }
668
669
670  // Step 2 - get the tags and the images for tags
671  get_qsearch_tags($tokens, $token_modifiers, $token_tag_ids, $not_tag_ids, $search_results['qs']['matching_tags']);
672  $debug[] = count($search_results['qs']['matching_tags']).' tags';
673
674  for ($i=0; $i<count($token_tag_ids); $i++)
675  {
676    $tag_ids = $token_tag_ids[$i];
[18207]677    $debug[] = count($tag_ids).' unique tags';
[10340]678
679    if (!empty($tag_ids))
680    {
[18207]681      $tag_photo_count=0;
[1837]682      $query = '
[18636]683SELECT image_id FROM '.IMAGE_TAG_TABLE.'
[10340]684  WHERE tag_id IN ('.implode(',',$tag_ids).')
[1837]685  GROUP BY image_id';
686      $result = pwg_query($query);
[4325]687      while ($row = pwg_db_fetch_assoc($result))
[1837]688      { // weight is important when sorting images by relevance
689        $image_id=(int)$row['image_id'];
[10340]690        @$by_weights[$image_id] += 1;
[18207]691        $tag_photo_count++;
[1837]692      }
[18636]693      $debug[] = $tag_photo_count.' photos for tag';
694      $debug[] = count($by_weights).' photos after';
[1837]695    }
[1537]696  }
697
[2135]698  // Step 3 - search categories corresponding to the query $q ==================
699  $query = '
[2138]700SELECT id, name, permalink, nb_images
[2135]701  FROM '.CATEGORIES_TABLE.'
702    INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
703  WHERE user_id='.$user['id'].'
[6664]704    AND MATCH(name, comment) AGAINST( \''.$q.'\' IN BOOLEAN MODE)'.
[2135]705  get_sql_condition_FandF (
706      array( 'visible_categories' => 'cat_id' ), "\n    AND"
707    );
708  $result = pwg_query($query);
[4325]709  while ($row = pwg_db_fetch_assoc($result))
[2135]710  { // weight is important when sorting images by relevance
711    if ($row['nb_images']==0)
712    {
[2138]713      $search_results['qs']['matching_cats_no_images'][] = $row;
[2135]714    }
715    else
716    {
[2138]717      $search_results['qs']['matching_cats'][$row['id']] = $row;
[2135]718    }
719  }
[18207]720  $debug[] = count(@$search_results['qs']['matching_cats']).' albums with images';
[2135]721
722  if ( empty($by_weights) and empty($search_results['qs']['matching_cats']) )
[1537]723  {
[2135]724    return $search_results;
725  }
726
[18636]727  if (!empty($not_tag_ids))
728  {
729    $query = '
730SELECT image_id FROM '.IMAGE_TAG_TABLE.'
731  WHERE tag_id IN ('.implode(',',$not_tag_ids).')
732  GROUP BY image_id';
733      $result = pwg_query($query);
734      while ($row = pwg_db_fetch_row($result))
735      {
736        $id = $row[0];
737        unset($by_weights[$id]);
738      }
739      $debug[] = count($by_weights).' after not tags';
740  }
[2135]741  // Step 4 - now we have $by_weights ( array image id => weight ) that need
742  // permission checks and/or matching categories to get images from
743  $where_clauses = array();
744  if ( !empty($by_weights) )
745  {
746    $where_clauses[]='i.id IN ('
747      . implode(',', array_keys($by_weights)) . ')';
748  }
749  if ( !empty($search_results['qs']['matching_cats']) )
750  {
751    $where_clauses[]='category_id IN ('.
[2138]752      implode(',',array_keys($search_results['qs']['matching_cats'])).')';
[2135]753  }
754  $where_clauses = array( '('.implode("\n    OR ",$where_clauses).')' );
755  if (!empty($images_where))
756  {
757    $where_clauses[]='('.$images_where.')';
758  }
759  $where_clauses[] = get_sql_condition_FandF(
760      array
761        (
762          'forbidden_categories' => 'category_id',
763          'visible_categories' => 'category_id',
764          'visible_images' => 'i.id'
765        ),
766      null,true
767    );
768
769  $query = '
[1537]770SELECT DISTINCT(id)
[2135]771  FROM '.IMAGES_TABLE.' i
[1537]772    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
[2135]773  WHERE '.implode("\n AND ", $where_clauses)."\n".
774  $conf['order_by'];
775
776  $allowed_images = array_from_query( $query, 'id');
777
[18207]778  $debug[] = count($allowed_images).' final photo count -->';
779  global $template;
780  $template->append('footer_elements', implode(', ', $debug) );
781
[2451]782  if ( $super_order_by or empty($by_weights) )
[2135]783  {
784    $search_results['items'] = $allowed_images;
785    return $search_results;
[1537]786  }
[2135]787
788  $allowed_images = array_flip( $allowed_images );
789  $divisor = 5.0 * count($allowed_images);
[22175]790  foreach ($allowed_images as $id=> &$rank )
[1837]791  {
[2135]792    $weight = isset($by_weights[$id]) ? $by_weights[$id] : 1;
793    $weight -= $rank/$divisor;
[22175]794    $rank = $weight;
[1837]795  }
[22175]796  unset($rank);
797
[2135]798  arsort($allowed_images, SORT_NUMERIC);
799  $search_results['items'] = array_keys($allowed_images);
[1537]800  return $search_results;
801}
802
803/**
[25658]804 * Returns an array of 'items' corresponding to the search id.
805 * It can be either a quick search or a regular search.
[1537]806 *
[25658]807 * @param int $search_id
808 * @param bool $super_order_by
809 * @param string $images_where optional aditional restriction on images table
[1537]810 * @return array
811 */
[2451]812function get_search_results($search_id, $super_order_by, $images_where='')
[1537]813{
814  $search = get_search_array($search_id);
815  if ( !isset($search['q']) )
816  {
[2451]817    $result['items'] = get_regular_search_results($search, $images_where);
[1537]818    return $result;
819  }
820  else
821  {
[2451]822    return get_quick_search_results($search['q'], $super_order_by, $images_where);
[1537]823  }
824}
[25658]825
[1113]826?>
Note: See TracBrowser for help on using the repository browser.