source: branches/2.5/include/functions_search.inc.php @ 30740

Last change on this file since 30740 was 27934, checked in by plg, 10 years ago

fix typo (bad merge from trunk)

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