source: branches/2.0/include/functions_search.inc.php @ 3046

Last change on this file since 3046 was 3046, checked in by plg, 15 years ago

Administration: happy new year 2009, all PHP headers updated.

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