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

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