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

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