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

Last change on this file since 24743 was 22175, checked in by rvelices, 11 years ago

fix quick search php warnings in some very rare cases

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