source: branches/1.7/include/functions_search.inc.php @ 27153

Last change on this file since 27153 was 2452, checked in by rvelices, 16 years ago
  • merge r2451 from trunk: 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.4 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | file          : $Id: functions_search.inc.php 2452 2008-07-23 00:56:53Z rvelices $
8// | last update   : $Date: 2008-07-23 00:56:53 +0000 (Wed, 23 Jul 2008) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Revision: 2452 $
11// +-----------------------------------------------------------------------+
12// | This program is free software; you can redistribute it and/or modify  |
13// | it under the terms of the GNU General Public License as published by  |
14// | the Free Software Foundation                                          |
15// |                                                                       |
16// | This program is distributed in the hope that it will be useful, but   |
17// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
18// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
19// | General Public License for more details.                              |
20// |                                                                       |
21// | You should have received a copy of the GNU General Public License     |
22// | along with this program; if not, write to the Free Software           |
23// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
24// | USA.                                                                  |
25// +-----------------------------------------------------------------------+
26
27
28/**
29 * returns search rules stored into a serialized array in "search"
30 * table. Each search rules set is numericaly identified.
31 *
32 * @param int search_id
33 * @return array
34 */
35function get_search_array($search_id)
36{
37  if (!is_numeric($search_id))
38  {
39    die('Search id must be an integer');
40  }
41
42  $query = '
43SELECT rules
44  FROM '.SEARCH_TABLE.'
45  WHERE id = '.$search_id.'
46;';
47  list($serialized_rules) = mysql_fetch_row(pwg_query($query));
48
49  return unserialize($serialized_rules);
50}
51
52/**
53 * returns the SQL clause from a search identifier
54 *
55 * Search rules are stored in search table as a serialized array. This array
56 * need to be transformed into an SQL clause to be used in queries.
57 *
58 * @param array search
59 * @return string
60 */
61function get_sql_search_clause($search)
62{
63  // SQL where clauses are stored in $clauses array during query
64  // construction
65  $clauses = array();
66
67  foreach (array('file','name','comment','author') as $textfield)
68  {
69    if (isset($search['fields'][$textfield]))
70    {
71      $local_clauses = array();
72      foreach ($search['fields'][$textfield]['words'] as $word)
73      {
74        array_push($local_clauses, $textfield." LIKE '%".$word."%'");
75      }
76
77      // adds brackets around where clauses
78      $local_clauses = prepend_append_array_items($local_clauses, '(', ')');
79
80      array_push(
81        $clauses,
82        implode(
83          ' '.$search['fields'][$textfield]['mode'].' ',
84          $local_clauses
85          )
86        );
87    }
88  }
89
90  if (isset($search['fields']['allwords']))
91  {
92    $fields = array('file', 'name', 'comment', 'author');
93    // in the OR mode, request bust be :
94    // ((field1 LIKE '%word1%' OR field2 LIKE '%word1%')
95    // OR (field1 LIKE '%word2%' OR field2 LIKE '%word2%'))
96    //
97    // in the AND mode :
98    // ((field1 LIKE '%word1%' OR field2 LIKE '%word1%')
99    // AND (field1 LIKE '%word2%' OR field2 LIKE '%word2%'))
100    $word_clauses = array();
101    foreach ($search['fields']['allwords']['words'] as $word)
102    {
103      $field_clauses = array();
104      foreach ($fields as $field)
105      {
106        array_push($field_clauses, $field." LIKE '%".$word."%'");
107      }
108      // adds brackets around where clauses
109      array_push(
110        $word_clauses,
111        implode(
112          "\n          OR ",
113          $field_clauses
114          )
115        );
116    }
117
118    array_walk(
119      $word_clauses,
120      create_function('&$s','$s="(".$s.")";')
121      );
122
123    array_push(
124      $clauses,
125      "\n         ".
126      implode(
127        "\n         ".
128              $search['fields']['allwords']['mode'].
129        "\n         ",
130        $word_clauses
131        )
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    if (empty($tag_items) or $search['mode']=='AND')
238    { // directly use forbidden and order by
239      $query .= $forbidden.'
240  '.$conf['order_by'];
241    }
242    $items = array_from_query($query, 'id');
243  }
244
245  if ( !empty($tag_items) )
246  {
247    $need_permission_check = false;
248    switch ($search['mode'])
249    {
250      case 'AND':
251        if (empty($search_clause))
252        {
253          $need_permission_check = true;
254          $items = $tag_items;
255        }
256        else
257        {
258          $items = array_intersect($items, $tag_items);
259        }
260        break;
261      case 'OR':
262        $before_count = count($items);
263        $items = array_unique(
264          array_merge(
265            $items,
266            $tag_items
267            )
268          );
269        if ( $before_count < count($items) )
270        {
271          $need_permission_check = true;
272        }
273        break;
274    }
275    if ($need_permission_check and count($items) )
276    {
277      $query = '
278SELECT DISTINCT(id)
279  FROM '.IMAGES_TABLE.' i
280    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
281  WHERE id IN ('.implode(',', $items).') '.$forbidden;
282      if (!empty($images_where))
283      {
284        $query .= "\n  AND ".$images_where;
285      }
286      $query .= '
287  '.$conf['order_by'];
288      $items = array_from_query($query, 'id');
289    }
290  }
291
292  return $items;
293}
294
295/**
296 * returns the LIKE sql clause corresponding to the quick search query $q
297 * and the field $field. example q='john bill', field='file' will return
298 * file LIKE '%john%' OR file LIKE '%bill%'. Special characters for MySql full
299 * text search (+,<,>,~) are omitted. The query can contain a phrase:
300 * 'Pierre "New York"' will return LIKE '%Pierre%' OR LIKE '%New York%'.
301 * @param string q
302 * @param string field
303 * @return string
304 */
305function get_qsearch_like_clause($q, $field)
306{
307  $q = stripslashes($q);
308  $tokens = array();
309  $token_modifiers = array();
310  $crt_token = "";
311  $crt_token_modifier = "";
312  $state = 0;
313
314  for ($i=0; $i<strlen($q); $i++)
315  {
316    $ch = $q[$i];
317    switch ($state)
318    {
319      case 0:
320        if ($ch=='"')
321        {
322          if (strlen($crt_token))
323          {
324            $tokens[] = $crt_token;
325            $token_modifiers[] = $crt_token_modifier;
326            $crt_token = "";
327            $crt_token_modifier = "";
328          }
329          $state=1;
330        }
331        elseif ( $ch=='*' )
332        { // wild card
333          $crt_token .= '%';
334        }
335        elseif ( strcspn($ch, '+-><~')==0 )
336        { //special full text modifier
337          if (strlen($crt_token))
338          {
339            $tokens[] = $crt_token;
340            $token_modifiers[] = $crt_token_modifier;
341            $crt_token = "";
342            $crt_token_modifier = "";
343          }
344          $crt_token_modifier .= $ch;
345        }
346        elseif (preg_match('/[\s,.;!\?]+/', $ch))
347        { // white space
348          if (strlen($crt_token))
349          {
350            $tokens[] = $crt_token;
351            $token_modifiers[] = $crt_token_modifier;
352            $crt_token = "";
353            $crt_token_modifier = "";
354          }
355        }
356        else
357        {
358          $crt_token .= $ch;
359        }
360        break;
361      case 1: // qualified with quotes
362        switch ($ch)
363        {
364          case '"':
365            $tokens[] = $crt_token;
366            $token_modifiers[] = $crt_token_modifier;
367            $crt_token = "";
368            $crt_token_modifier = "";
369            $state=0;
370            break;
371          default:
372            $crt_token .= $ch;
373        }
374        break;
375    }
376  }
377  if (strlen($crt_token))
378  {
379    $tokens[] = $crt_token;
380    $token_modifiers[] = $crt_token_modifier;
381  }
382
383  $clauses = array();
384  for ($i=0; $i<count($tokens); $i++)
385  {
386    $tokens[$i] = trim($tokens[$i], '%');
387    if (strstr($token_modifiers[$i], '-')!==false)
388      continue;
389    if ( strlen($tokens[$i])==0)
390      continue;
391    $clauses[] = $field.' LIKE "%'.addslashes($tokens[$i]).'%"';
392  }
393
394  return count($clauses) ? '('.implode(' OR ', $clauses).')' : null;
395}
396
397
398/**
399 * returns the search results corresponding to a quick/query search.
400 * A quick/query search returns many items (search is not strict), but results
401 * are sorted by relevance unless $super_order_by is true. Returns:
402 * array (
403 * 'items' => array(85,68,79...)
404 * 'qs'    => array(
405 *    'matching_tags' => array of matching tags
406 *    'matching_cats' => array of matching categories
407 *    'matching_cats_no_images' =>array(99) - matching categories without images
408 *      ))
409 *
410 * @param string q
411 * @param bool super_order_by
412 * @param string images_where optional aditional restriction on images table
413 * @return array
414 */
415function get_quick_search_results($q, $super_order_by, $images_where='')
416{
417  $search_results =
418    array(
419      'items' => array(),
420      'qs' => array('q'=>stripslashes($q)),
421    );
422  $q = trim($q);
423  if (empty($q))
424  {
425    return $search_results;
426  }
427  $q_like_field = '@@__db_field__@@'; //something never in a search
428  $q_like_clause = get_qsearch_like_clause($q, $q_like_field );
429
430
431  // Step 1 - first we find matches in #images table ===========================
432  $where_clauses='MATCH(i.name, i.comment) AGAINST( "'.$q.'" IN BOOLEAN MODE)';
433  if (!empty($q_like_clause))
434  {
435    $where_clauses .= '
436    OR '. str_replace($q_like_field, 'file', $q_like_clause);
437    $where_clauses = '('.$where_clauses.')';
438  }
439  $where_clauses = array($where_clauses);
440  if (!empty($images_where))
441  {
442    $where_clauses[]='('.$images_where.')';
443  }
444  $where_clauses[] .= get_sql_condition_FandF
445      (
446        array( 'visible_images' => 'i.id' ), null, true
447      );
448  $query = '
449SELECT i.id,
450    MATCH(i.name, i.comment) AGAINST( "'.$q.'" IN BOOLEAN MODE) AS weight
451  FROM '.IMAGES_TABLE.' i
452  WHERE '.implode("\n AND ", $where_clauses);
453
454  $by_weights=array();
455  $result = pwg_query($query);
456  while ($row = mysql_fetch_array($result))
457  { // weight is important when sorting images by relevance
458    if ($row['weight'])
459    {
460      $by_weights[(int)$row['id']] =  2*$row['weight'];
461    }
462    else
463    {//full text does not match but file name match
464      $by_weights[(int)$row['id']] =  2;
465    }
466  }
467
468
469  // Step 2 - search tags corresponding to the query $q ========================
470  if (!empty($q_like_clause))
471  { // search name and url name (without accents)
472    $query = '
473SELECT id, name, url_name
474  FROM '.TAGS_TABLE.'
475  WHERE ('.str_replace($q_like_field, 'CONVERT(name, CHAR)', $q_like_clause).'
476    OR '.str_replace($q_like_field, 'url_name', $q_like_clause).')';
477    $tags = hash_from_query($query, 'id');
478    if ( !empty($tags) )
479    { // we got some tags; get the images
480      $search_results['qs']['matching_tags']=$tags;
481      $query = '
482SELECT image_id, COUNT(tag_id) AS weight
483  FROM '.IMAGE_TAG_TABLE.'
484  WHERE tag_id IN ('.implode(',',array_keys($tags)).')
485  GROUP BY image_id';
486      $result = pwg_query($query);
487      while ($row = mysql_fetch_assoc($result))
488      { // weight is important when sorting images by relevance
489        $image_id=(int)$row['image_id'];
490        @$by_weights[$image_id] += $row['weight'];
491      }
492    }
493  }
494
495
496  // Step 3 - search categories corresponding to the query $q ==================
497  global $user;
498  $query = '
499SELECT id, name, permalink, nb_images
500  FROM '.CATEGORIES_TABLE.'
501    INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
502  WHERE user_id='.$user['id'].'
503    AND MATCH(name, comment) AGAINST( "'.$q.'" IN BOOLEAN MODE)'.
504  get_sql_condition_FandF (
505      array( 'visible_categories' => 'cat_id' ), "\n    AND"
506    );
507  $result = pwg_query($query);
508  while ($row = mysql_fetch_assoc($result))
509  { // weight is important when sorting images by relevance
510    if ($row['nb_images']==0)
511    {
512      $search_results['qs']['matching_cats_no_images'][] = $row;
513    }
514    else
515    {
516      $search_results['qs']['matching_cats'][$row['id']] = $row;
517    }
518  }
519
520  if ( empty($by_weights) and empty($search_results['qs']['matching_cats']) )
521  {
522    return $search_results;
523  }
524
525  // Step 4 - now we have $by_weights ( array image id => weight ) that need
526  // permission checks and/or matching categories to get images from
527  $where_clauses = array();
528  if ( !empty($by_weights) )
529  {
530    $where_clauses[]='i.id IN ('
531      . implode(',', array_keys($by_weights)) . ')';
532  }
533  if ( !empty($search_results['qs']['matching_cats']) )
534  {
535    $where_clauses[]='category_id IN ('.
536      implode(',',array_keys($search_results['qs']['matching_cats'])).')';
537  }
538  $where_clauses = array( '('.implode("\n    OR ",$where_clauses).')' );
539  if (!empty($images_where))
540  {
541    $where_clauses[]='('.$images_where.')';
542  }
543  $where_clauses[] = get_sql_condition_FandF(
544      array
545        (
546          'forbidden_categories' => 'category_id',
547          'visible_categories' => 'category_id',
548          'visible_images' => 'i.id'
549        ),
550      null,true
551    );
552
553  global $conf;
554  $query = '
555SELECT DISTINCT(id)
556  FROM '.IMAGES_TABLE.' i
557    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
558  WHERE '.implode("\n AND ", $where_clauses)."\n".
559  $conf['order_by'];
560
561  $allowed_images = array_from_query( $query, 'id');
562
563  if ( $super_order_by or empty($by_weights) )
564  {
565    $search_results['items'] = $allowed_images;
566    return $search_results;
567  }
568
569  $allowed_images = array_flip( $allowed_images );
570  $divisor = 5.0 * count($allowed_images);
571  foreach ($allowed_images as $id=>$rank )
572  {
573    $weight = isset($by_weights[$id]) ? $by_weights[$id] : 1;
574    $weight -= $rank/$divisor;
575    $allowed_images[$id] = $weight;
576  }
577  arsort($allowed_images, SORT_NUMERIC);
578  $search_results['items'] = array_keys($allowed_images);
579  return $search_results;
580}
581
582/**
583 * returns an array of 'items' corresponding to the search id
584 *
585 * @param int search id
586 * @param string images_where optional aditional restriction on images table
587 * @return array
588 */
589function get_search_results($search_id, $super_order_by, $images_where='')
590{
591  $search = get_search_array($search_id);
592  if ( !isset($search['q']) )
593  {
594    $result['items'] = get_regular_search_results($search, $images_where);
595    return $result;
596  }
597  else
598  {
599    return get_quick_search_results($search['q'], $super_order_by, $images_where);
600  }
601}
602?>
Note: See TracBrowser for help on using the repository browser.