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

Last change on this file since 8726 was 8726, checked in by rvelices, 13 years ago

bug 2105 : Browsing tags is slow if tags contains many photos

  • Property svn:eol-style set to LF
File size: 16.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2010 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    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
188  return $search_clause;
189}
190
191/**
192 * returns the list of items corresponding to the advanced search array
193 *
194 * @param array search
195 * @return array
196 */
197function get_regular_search_results($search, $images_where)
198{
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
210  $items = array();
211  $tag_items = array();
212
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
221  $search_clause = get_sql_search_clause($search);
222
223  if (!empty($search_clause))
224  {
225    $query = '
226SELECT DISTINCT(id)
227  FROM '.IMAGES_TABLE.' i
228    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
229  WHERE '.$search_clause;
230    if (!empty($images_where))
231    {
232      $query .= "\n  AND ".$images_where;
233    }
234    $query .= $forbidden.'
235  '.$conf['order_by'];
236    $items = array_from_query($query, 'id');
237  }
238
239  if ( !empty($tag_items) )
240  {
241    switch ($search['mode'])
242    {
243      case 'AND':
244        if (empty($search_clause))
245        {
246          $items = $tag_items;
247        }
248        else
249        {
250          $items = array_values( array_intersect($items, $tag_items) );
251        }
252        break;
253      case 'OR':
254        $before_count = count($items);
255        $items = array_unique(
256          array_merge(
257            $items,
258            $tag_items
259            )
260          );
261        break;
262    }
263  }
264
265  return $items;
266}
267
268/**
269 * returns the LIKE sql clause corresponding to the quick search query $q
270 * and the field $field. example q='john bill', field='file' will return
271 * file LIKE '%john%' OR file LIKE '%bill%'. Special characters for MySql full
272 * text search (+,<,>,~) are omitted. The query can contain a phrase:
273 * 'Pierre "New York"' will return LIKE '%Pierre%' OR LIKE '%New York%'.
274 * @param string q
275 * @param string field
276 * @return string
277 */
278function get_qsearch_like_clause($q, $field, $before='%', $after='%')
279{
280  $q = stripslashes($q);
281  $tokens = array();
282  $token_modifiers = array();
283  $crt_token = "";
284  $crt_token_modifier = "";
285  $state = 0;
286
287  for ($i=0; $i<strlen($q); $i++)
288  {
289    $ch = $q[$i];
290    switch ($state)
291    {
292      case 0:
293        if ($ch=='"')
294        {
295          if (strlen($crt_token))
296          {
297            $tokens[] = $crt_token;
298            $token_modifiers[] = $crt_token_modifier;
299            $crt_token = "";
300            $crt_token_modifier = "";
301          }
302          $state=1;
303        }
304        elseif ( $ch=='*' )
305        { // wild card
306          $crt_token .= '%';
307        }
308        elseif ( strcspn($ch, '+-><~')==0 )
309        { //special full text modifier
310          if (strlen($crt_token))
311          {
312            $tokens[] = $crt_token;
313            $token_modifiers[] = $crt_token_modifier;
314            $crt_token = "";
315            $crt_token_modifier = "";
316          }
317          $crt_token_modifier .= $ch;
318        }
319        elseif (preg_match('/[\s,.;!\?]+/', $ch))
320        { // white space
321          if (strlen($crt_token))
322          {
323            $tokens[] = $crt_token;
324            $token_modifiers[] = $crt_token_modifier;
325            $crt_token = "";
326            $crt_token_modifier = "";
327          }
328        }
329        else
330        {
331          if ( strcspn($ch, '%_')==0)
332          {// escape LIKE specials %_
333            $ch = '\\'.$ch;
334          }
335          $crt_token .= $ch;
336        }
337        break;
338      case 1: // qualified with quotes
339        switch ($ch)
340        {
341          case '"':
342            $tokens[] = $crt_token;
343            $token_modifiers[] = $crt_token_modifier;
344            $crt_token = "";
345            $crt_token_modifier = "";
346            $state=0;
347            break;
348          default:
349            if ( strcspn($ch, '%_')==0)
350            {// escape LIKE specials %_
351                $ch = '\\'.$ch;
352            }
353            $crt_token .= $ch;
354        }
355        break;
356    }
357  }
358  if (strlen($crt_token))
359  {
360    $tokens[] = $crt_token;
361    $token_modifiers[] = $crt_token_modifier;
362  }
363
364  $clauses = array();
365  for ($i=0; $i<count($tokens); $i++)
366  {
367    $tokens[$i] = trim($tokens[$i], '%');
368    if (strstr($token_modifiers[$i], '-')!==false)
369      continue;
370    if ( strlen($tokens[$i])==0)
371      continue;
372    $clauses[] = $field.' LIKE \''.$before.addslashes($tokens[$i]).$after.'\'';
373  }
374
375  return count($clauses) ? '('.implode(' OR ', $clauses).')' : null;
376}
377
378
379/**
380 * returns the search results corresponding to a quick/query search.
381 * A quick/query search returns many items (search is not strict), but results
382 * are sorted by relevance unless $super_order_by is true. Returns:
383 * array (
384 * 'items' => array(85,68,79...)
385 * 'qs'    => array(
386 *    'matching_tags' => array of matching tags
387 *    'matching_cats' => array of matching categories
388 *    'matching_cats_no_images' =>array(99) - matching categories without images
389 *      ))
390 *
391 * @param string q
392 * @param bool super_order_by
393 * @param string images_where optional aditional restriction on images table
394 * @return array
395 */
396function get_quick_search_results($q, $super_order_by, $images_where='')
397{
398  $search_results =
399    array(
400      'items' => array(),
401      'qs' => array('q'=>stripslashes($q)),
402    );
403  $q = trim($q);
404  if (empty($q))
405  {
406    return $search_results;
407  }
408  $q_like_field = '@@__db_field__@@'; //something never in a search
409  $q_like_clause = get_qsearch_like_clause($q, $q_like_field );
410
411
412  // Step 1 - first we find matches in #images table ===========================
413  $where_clauses='MATCH(i.name, i.comment) AGAINST( \''.$q.'\' IN BOOLEAN MODE)';
414  if (!empty($q_like_clause))
415  {
416    $where_clauses .= '
417    OR '. str_replace($q_like_field, 'CONVERT(file, CHAR)', $q_like_clause);
418    $where_clauses = '('.$where_clauses.')';
419  }
420  $where_clauses = array($where_clauses);
421  if (!empty($images_where))
422  {
423    $where_clauses[]='('.$images_where.')';
424  }
425  $where_clauses[] .= get_sql_condition_FandF
426      (
427        array( 'visible_images' => 'i.id' ), null, true
428      );
429  $query = '
430SELECT i.id,
431    MATCH(i.name, i.comment) AGAINST( \''.$q.'\' IN BOOLEAN MODE) AS weight
432  FROM '.IMAGES_TABLE.' i
433  WHERE '.implode("\n AND ", $where_clauses);
434
435  $by_weights=array();
436  $result = pwg_query($query);
437  while ($row = pwg_db_fetch_assoc($result))
438  { // weight is important when sorting images by relevance
439    if ($row['weight'])
440    {
441      $by_weights[(int)$row['id']] =  2*$row['weight'];
442    }
443    else
444    {//full text does not match but file name match
445      $by_weights[(int)$row['id']] =  2;
446    }
447  }
448
449
450  // Step 2 - search tags corresponding to the query $q ========================
451  if (!empty($q_like_clause))
452  { // search name and url name (without accents)
453    $query = '
454SELECT id, name, url_name
455  FROM '.TAGS_TABLE.'
456  WHERE ('.str_replace($q_like_field, 'CONVERT(name, CHAR)', $q_like_clause).'
457    OR '.str_replace($q_like_field, 'url_name', $q_like_clause).')';
458    $tags = hash_from_query($query, 'id');
459    if ( !empty($tags) )
460    { // we got some tags; get the images
461      $search_results['qs']['matching_tags']=$tags;
462      $query = '
463SELECT image_id, COUNT(tag_id) AS weight
464  FROM '.IMAGE_TAG_TABLE.'
465  WHERE tag_id IN ('.implode(',',array_keys($tags)).')
466  GROUP BY image_id';
467      $result = pwg_query($query);
468      while ($row = pwg_db_fetch_assoc($result))
469      { // weight is important when sorting images by relevance
470        $image_id=(int)$row['image_id'];
471        @$by_weights[$image_id] += $row['weight'];
472      }
473    }
474  }
475
476
477  // Step 3 - search categories corresponding to the query $q ==================
478  global $user;
479  $query = '
480SELECT id, name, permalink, nb_images
481  FROM '.CATEGORIES_TABLE.'
482    INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
483  WHERE user_id='.$user['id'].'
484    AND MATCH(name, comment) AGAINST( \''.$q.'\' IN BOOLEAN MODE)'.
485  get_sql_condition_FandF (
486      array( 'visible_categories' => 'cat_id' ), "\n    AND"
487    );
488  $result = pwg_query($query);
489  while ($row = pwg_db_fetch_assoc($result))
490  { // weight is important when sorting images by relevance
491    if ($row['nb_images']==0)
492    {
493      $search_results['qs']['matching_cats_no_images'][] = $row;
494    }
495    else
496    {
497      $search_results['qs']['matching_cats'][$row['id']] = $row;
498    }
499  }
500
501  if ( empty($by_weights) and empty($search_results['qs']['matching_cats']) )
502  {
503    return $search_results;
504  }
505
506  // Step 4 - now we have $by_weights ( array image id => weight ) that need
507  // permission checks and/or matching categories to get images from
508  $where_clauses = array();
509  if ( !empty($by_weights) )
510  {
511    $where_clauses[]='i.id IN ('
512      . implode(',', array_keys($by_weights)) . ')';
513  }
514  if ( !empty($search_results['qs']['matching_cats']) )
515  {
516    $where_clauses[]='category_id IN ('.
517      implode(',',array_keys($search_results['qs']['matching_cats'])).')';
518  }
519  $where_clauses = array( '('.implode("\n    OR ",$where_clauses).')' );
520  if (!empty($images_where))
521  {
522    $where_clauses[]='('.$images_where.')';
523  }
524  $where_clauses[] = get_sql_condition_FandF(
525      array
526        (
527          'forbidden_categories' => 'category_id',
528          'visible_categories' => 'category_id',
529          'visible_images' => 'i.id'
530        ),
531      null,true
532    );
533
534  global $conf;
535  $query = '
536SELECT DISTINCT(id)
537  FROM '.IMAGES_TABLE.' i
538    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
539  WHERE '.implode("\n AND ", $where_clauses)."\n".
540  $conf['order_by'];
541
542  $allowed_images = array_from_query( $query, 'id');
543
544  if ( $super_order_by or empty($by_weights) )
545  {
546    $search_results['items'] = $allowed_images;
547    return $search_results;
548  }
549
550  $allowed_images = array_flip( $allowed_images );
551  $divisor = 5.0 * count($allowed_images);
552  foreach ($allowed_images as $id=>$rank )
553  {
554    $weight = isset($by_weights[$id]) ? $by_weights[$id] : 1;
555    $weight -= $rank/$divisor;
556    $allowed_images[$id] = $weight;
557  }
558  arsort($allowed_images, SORT_NUMERIC);
559  $search_results['items'] = array_keys($allowed_images);
560  return $search_results;
561}
562
563/**
564 * returns an array of 'items' corresponding to the search id
565 *
566 * @param int search id
567 * @param string images_where optional aditional restriction on images table
568 * @return array
569 */
570function get_search_results($search_id, $super_order_by, $images_where='')
571{
572  $search = get_search_array($search_id);
573  if ( !isset($search['q']) )
574  {
575    $result['items'] = get_regular_search_results($search, $images_where);
576    return $result;
577  }
578  else
579  {
580    return get_quick_search_results($search['q'], $super_order_by, $images_where);
581  }
582}
583?>
Note: See TracBrowser for help on using the repository browser.