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

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

fix parse error from r25018

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