source: branches/2.6/include/functions_search.inc.php @ 27715

Last change on this file since 27715 was 26825, checked in by plg, 10 years ago

bug 3020 and bug 3021 fixed: additionnal checks in search inputs

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