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

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

Update headers to 2014. Happy new year!!

  • Property svn:eol-style set to LF
File size: 22.7 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    $clauses[] = "\n         ".
117      implode(
118        "\n         ". $search['fields']['allwords']['mode']. "\n         ",
119        $word_clauses
120        );
121  }
122
123  foreach (array('date_available', 'date_creation') as $datefield)
124  {
125    if (isset($search['fields'][$datefield]))
126    {
127      $clauses[] = $datefield." = '".$search['fields'][$datefield]['date']."'";
128    }
129
130    foreach (array('after','before') as $suffix)
131    {
132      $key = $datefield.'-'.$suffix;
133
134      if (isset($search['fields'][$key]))
135      {
136        $clauses[] = $datefield.
137          ($suffix == 'after'             ? ' >' : ' <').
138          ($search['fields'][$key]['inc'] ? '='  : '').
139          " '".$search['fields'][$key]['date']."'";
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).')';
157    $clauses[] = $local_clause;
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
171  return $search_clause;
172}
173
174/**
175 * Returns the list of items corresponding to the advanced search array.
176 *
177 * @param array $search
178 * @param string $images_where optional additional restriction on images table
179 * @return array
180 */
181function get_regular_search_results($search, $images_where='')
182{
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
194  $items = array();
195  $tag_items = array();
196
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
205  $search_clause = get_sql_search_clause($search);
206
207  if (!empty($search_clause))
208  {
209    $query = '
210SELECT DISTINCT(id)
211  FROM '.IMAGES_TABLE.' i
212    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
213  WHERE '.$search_clause;
214    if (!empty($images_where))
215    {
216      $query .= "\n  AND ".$images_where;
217    }
218    $query .= $forbidden.'
219  '.$conf['order_by'];
220    $items = array_from_query($query, 'id');
221  }
222
223  if ( !empty($tag_items) )
224  {
225    switch ($search['mode'])
226    {
227      case 'AND':
228        if (empty($search_clause))
229        {
230          $items = $tag_items;
231        }
232        else
233        {
234          $items = array_values( array_intersect($items, $tag_items) );
235        }
236        break;
237      case 'OR':
238        $before_count = count($items);
239        $items = array_unique(
240          array_merge(
241            $items,
242            $tag_items
243            )
244          );
245        break;
246    }
247  }
248
249  return $items;
250}
251
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 */
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
263/**
264 * Finds if a char is a special token for word start: [{<=*+
265 *
266 * @param char $ch
267 * @return bool
268 */
269function is_odd_wbreak_begin($ch)
270{
271  return strpos('[{<=*+', $ch)===false ? false:true;
272}
273
274/**
275 * Finds if a char is a special token for word end: ]}>=*+
276 *
277 * @param char $ch
278 * @return bool
279 */
280function is_odd_wbreak_end($ch)
281{
282  return strpos(']}>=*+', $ch)===false ? false:true;
283}
284
285
286define('QST_QUOTED',         0x01);
287define('QST_NOT',            0x02);
288define('QST_WILDCARD_BEGIN', 0x04);
289define('QST_WILDCARD_END',   0x08);
290define('QST_WILDCARD', QST_WILDCARD_BEGIN|QST_WILDCARD_END);
291
292/**
293 * Analyzes and splits the quick/query search query $q into tokens.
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'.
297 *
298 * @param string $q
299 * @param array &$qtokens
300 * @param array &$qtoken_modifiers
301 */
302function analyse_qsearch($q, &$qtokens, &$qtoken_modifiers)
303{
304  $q = stripslashes($q);
305  $tokens = array();
306  $token_modifiers = array();
307  $crt_token = "";
308  $crt_token_modifier = 0;
309
310  for ($i=0; $i<strlen($q); $i++)
311  {
312    $ch = $q[$i];
313    if ( ($crt_token_modifier&QST_QUOTED)==0)
314    {
315        if ($ch=='"')
316        {
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;
323        }
324        elseif ( strcspn($ch, '*+-><~')==0 )
325        { //special full text modifier
326          if (strlen($crt_token))
327          {
328            $crt_token .= $ch;
329          }
330          else
331          {
332            if ( $ch=='*' )
333              $crt_token_modifier |= QST_WILDCARD_BEGIN;
334            if ( $ch=='-' )
335              $crt_token_modifier |= QST_NOT;
336          }
337        }
338        elseif (preg_match('/[\s,.;!\?]+/', $ch))
339        { // white space
340          if (strlen($crt_token))
341          {
342            $tokens[] = $crt_token; $token_modifiers[] = $crt_token_modifier;
343            $crt_token = "";
344          }
345          $crt_token_modifier = 0;
346        }
347        else
348        {
349          $crt_token .= $ch;
350        }
351    }
352    else // qualified with quotes
353    {
354      if ($ch=='"')
355      {
356        if ($i+1 < strlen($q) && $q[$i+1]=='*')
357        {
358          $crt_token_modifier |= QST_WILDCARD_END;
359          $i++;
360        }
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;
367    }
368  }
369
370  if (strlen($crt_token))
371  {
372    $tokens[] = $crt_token;
373    $token_modifiers[] = $crt_token_modifier;
374  }
375
376  $qtokens = array();
377  $qtoken_modifiers = array();
378  for ($i=0; $i<count($tokens); $i++)
379  {
380    if ( !($token_modifiers[$i] & QST_QUOTED) )
381    {
382      if ( substr($tokens[$i], -1)=='*' )
383      {
384        $tokens[$i] = rtrim($tokens[$i], '*');
385        $token_modifiers[$i] |= QST_WILDCARD_END;
386      }
387    }
388    if ( strlen($tokens[$i])==0)
389      continue;
390    $qtokens[] = $tokens[$i];
391    $qtoken_modifiers[] = $token_modifiers[$i];
392  }
393}
394
395/**
396 * Returns the LIKE SQL clause corresponding to the quick search query
397 * that has been split into tokens.
398 * for example file LIKE '%john%' OR file LIKE '%bill%'.
399 *
400 * @param array $tokens
401 * @param array $token_modifiers
402 * @param string $field
403 * @return string|null
404 */
405function get_qsearch_like_clause($tokens, $token_modifiers, $field)
406{
407  $clauses = array();
408  for ($i=0; $i<count($tokens); $i++)
409  {
410    $token = trim($tokens[$i], '%');
411    if ($token_modifiers[$i]&QST_NOT)
412      continue;
413    if ( strlen($token)==0 )
414      continue;
415    $token = addslashes($token);
416    $token = str_replace( array('%','_'), array('\\%','\\_'), $token); // escape LIKE specials %_
417    $clauses[] = $field.' LIKE \'%'.$token.'%\'';
418  }
419
420  return count($clauses) ? '('.implode(' OR ', $clauses).')' : null;
421}
422
423/**
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 */
432function get_qsearch_tags($tokens, $token_modifiers, &$token_tag_ids, &$not_tag_ids, &$all_tags)
433{
434  $token_tag_ids = array_fill(0, count($tokens), array() );
435  $not_tag_ids = $all_tags = array();
436
437  $token_tag_scores = $token_tag_ids;
438  $transliterated_tokens = array();
439  foreach ($tokens as $token)
440  {
441    $transliterated_tokens[] = transliterate($token);
442  }
443
444  $query = '
445SELECT t.*, COUNT(image_id) AS counter
446  FROM '.TAGS_TABLE.' t
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      {
463        if ( ($token_modifiers[$i]&QST_WILDCARD)==QST_WILDCARD )
464        {// wildcard in this token
465          $match = 1;
466          break;
467        }
468        $token_len = strlen($transliterated_token);
469
470        // search begin of word
471        $wbegin_len=0; $wbegin_char=' ';
472        while ($pos-$wbegin_len > 0)
473        {
474          if (! is_word_char($transliterated_tag[$pos-$wbegin_len-1]) )
475          {
476            $wbegin_char = $transliterated_tag[$pos-$wbegin_len-1];
477            break;
478          }
479          $wbegin_len++;
480        }
481
482        // search end of word
483        $wend_len=0; $wend_char=' ';
484        while ($pos+$token_len+$wend_len < strlen($transliterated_tag))
485        {
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++;
492        }
493
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
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;
522        $token_tag_ids[$i][] = $tag_id;
523        $token_tag_scores[$i][] = $match;
524      }
525    }
526  }
527
528  // process not tags
529  for ($i=0; $i<count($tokens); $i++)
530  {
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++)
537    {
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);
568        $j--;
569        continue;
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] )
574      {// "many" images in previous tags and starting from this tag is less relevent
575        array_splice($token_tag_ids[$i], $j);
576        array_splice($token_tag_scores[$i], $j);
577        break;
578      }
579    }
580  }
581
582  usort($all_tags, 'tag_alpha_compare');
583  foreach ( $all_tags as &$tag )
584  {
585    $tag['name'] = trigger_event('render_tag_name', $tag['name']);
586  }
587}
588
589/**
590 * Returns the search results corresponding to a quick/query search.
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:
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 *    )
601 *
602 * @param string $q
603 * @param bool $super_order_by
604 * @param string $images_where optional additional restriction on images table
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)
619  {
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];
677    $debug[] = count($tag_ids).' unique tags';
678
679    if (!empty($tag_ids))
680    {
681      $tag_photo_count=0;
682      $query = '
683SELECT image_id FROM '.IMAGE_TAG_TABLE.'
684  WHERE tag_id IN ('.implode(',',$tag_ids).')
685  GROUP BY image_id';
686      $result = pwg_query($query);
687      while ($row = pwg_db_fetch_assoc($result))
688      { // weight is important when sorting images by relevance
689        $image_id=(int)$row['image_id'];
690        @$by_weights[$image_id] += 1;
691        $tag_photo_count++;
692      }
693      $debug[] = $tag_photo_count.' photos for tag';
694      $debug[] = count($by_weights).' photos after';
695    }
696  }
697
698  // Step 3 - search categories corresponding to the query $q ==================
699  $query = '
700SELECT id, name, permalink, nb_images
701  FROM '.CATEGORIES_TABLE.'
702    INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
703  WHERE user_id='.$user['id'].'
704    AND MATCH(name, comment) AGAINST( \''.$q.'\' IN BOOLEAN MODE)'.
705  get_sql_condition_FandF (
706      array( 'visible_categories' => 'cat_id' ), "\n    AND"
707    );
708  $result = pwg_query($query);
709  while ($row = pwg_db_fetch_assoc($result))
710  { // weight is important when sorting images by relevance
711    if ($row['nb_images']==0)
712    {
713      $search_results['qs']['matching_cats_no_images'][] = $row;
714    }
715    else
716    {
717      $search_results['qs']['matching_cats'][$row['id']] = $row;
718    }
719  }
720  $debug[] = count(@$search_results['qs']['matching_cats']).' albums with images';
721
722  if ( empty($by_weights) and empty($search_results['qs']['matching_cats']) )
723  {
724    return $search_results;
725  }
726
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  }
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 ('.
752      implode(',',array_keys($search_results['qs']['matching_cats'])).')';
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 = '
770SELECT DISTINCT(id)
771  FROM '.IMAGES_TABLE.' i
772    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
773  WHERE '.implode("\n AND ", $where_clauses)."\n".
774  $conf['order_by'];
775
776  $allowed_images = array_from_query( $query, 'id');
777
778  $debug[] = count($allowed_images).' final photo count -->';
779  global $template;
780  $template->append('footer_elements', implode(', ', $debug) );
781
782  if ( $super_order_by or empty($by_weights) )
783  {
784    $search_results['items'] = $allowed_images;
785    return $search_results;
786  }
787
788  $allowed_images = array_flip( $allowed_images );
789  $divisor = 5.0 * count($allowed_images);
790  foreach ($allowed_images as $id=> &$rank )
791  {
792    $weight = isset($by_weights[$id]) ? $by_weights[$id] : 1;
793    $weight -= $rank/$divisor;
794    $rank = $weight;
795  }
796  unset($rank);
797
798  arsort($allowed_images, SORT_NUMERIC);
799  $search_results['items'] = array_keys($allowed_images);
800  return $search_results;
801}
802
803/**
804 * Returns an array of 'items' corresponding to the search id.
805 * It can be either a quick search or a regular search.
806 *
807 * @param int $search_id
808 * @param bool $super_order_by
809 * @param string $images_where optional aditional restriction on images table
810 * @return array
811 */
812function get_search_results($search_id, $super_order_by, $images_where='')
813{
814  $search = get_search_array($search_id);
815  if ( !isset($search['q']) )
816  {
817    $result['items'] = get_regular_search_results($search, $images_where);
818    return $result;
819  }
820  else
821  {
822    return get_quick_search_results($search['q'], $super_order_by, $images_where);
823  }
824}
825
826?>
Note: See TracBrowser for help on using the repository browser.