drupal6: ปรับปรุงมอดูล Thai Search

Topic: 
 

ยังไม่เข้าใจการทำงานมอดูลอย่างจริงจัง ตอนนี้ใช้วิธีตัดแปะจาก Core Module ไปก่อน

  • ปรับปรุงให้มีฟอร์มสำหรับใส่คำค้นในหน้าหลัก ซึ่งจะทำให้สามารถเปิดใช้เมนู Thaisearch ได้ด้วย
  • จัดเรียงตามลำดับน้ำหนัก, และเวลา
  • ใส่คำค้นได้หลายคำ โดยจัดน้ำหนักให้ด้วย - ทุกคำ น้ำหนัก10, คำแรกน้ำหนัก 3, คำที่เหลือ น้ำหนัก 1 และเพิ่มน้ำหนักให้กับส่วนที่ค้น คือ node.title น้ำหนัก 10, node.body น้ำหนัก 2, comments.comment น้ำหนัก 1
  • 50-01-25 เพิ่ม block เพิ่ม css เพิ่ม watchdog
  • รู้สึกจะมีปัญหากับ Drupal เรื่อง HTTP request ยังไม่แน่ใจว่าเป็นที่ใคร วิธีแก้คือ ย้ายทุกมอดูลออกจาก sites/all/modules -> สั่ง update.php -> สั่งอัปเดตด้วยมือ admin/reports/updates/check -> ย้ายมอดูลกลับ

ดาวน์โหลดได้แล้ว

ติดตั้งตามวิธีปกติ
$ cd /var/www/drupal/sites/all/modules
$ wget http://www.thaitux.info/files/modules/thaisearch-6.x-0.1.tar.gz
$ tar xfz thaisearch-6.x-0.1.tar.gz

หรือเขียนโค๊ดเอง
เพิ่มไฟล์ css
$ cd /var/www/drupal/sites/all/modules/thaisearch
$ vi thaisearch.css

/* $Id: thaisearch.css,v 1.3 2007/10/31 18:06:38 dries Exp $ */

.block-thaisearch .form-item {
  display: inline;
  margin: 0;
  padding: 0;
}

แก้เฉพาะไฟล์ thaisearch.module
$ vi thaisearch.module

<?php
// $Id: thaisearch.module,v 1.13 2007/10/17 19:38:36 litwol Exp $
// wd's: modify to thaisearch.module, simple search Thai words. v.2008/1/24.
/**
 * @file
 * This is an example outlining how a module can be used to display a
 * custom page at a given URL.
 */

/**
 * Implementation of hook_help().
 *
 * Throughout Drupal, hook_help() is used to display help text at the top of
 * pages. Some other parts of Drupal pages get explanatory text from these hooks
 * as well. We use it here to illustrate how to add help text to the pages your
 * module defines.
 */
function thaisearch_help($path, $arg) {
  switch ($path) {
    case 'thaisearch':
      // Here is some help text for a custom page.
      return t('Search thai words. Type in URL: <code><strong>thaisearch/<em>WORD1 WORD2 ...</em></strong></code><br />Words separated by space, quote or double-quote are allowed.<br /><code>a "b c" d</code> gives <code>"<strong>a</strong>"</code> , <code>"<strong>b c</strong>"</code> , <code>"<strong>d</strong>"</code>');
    case 'search#noresults':
      return t('<ul>
<li>Check if your spelling is correct.</li>
<li>Remove quotes around phrases to match each word individually: <em>"blue smurf"</em> will match less than <em>blue smurf</em>.</li>
<li>Consider loosening your query with <em>OR</em>: <em>blue smurf</em> will match less than <em>blue OR smurf</em>.</li>
</ul>');
  }
}

/**
 * Implementation of hook_perm().
 *
 * Since the access to our new custom pages will be granted based on
 * special permissions, we need to define what those permissions are here.
 * This ensures that they are available to enable on the user role
 * administration pages.
 */
function thaisearch_perm() {
  return array('access thaisearch');
}

/**
 * Implementation of hook_block().
 */
function thaisearch_block($op='list', $delta=0) {
  // listing of blocks, such as on the admin/block page
  if ($op == "list") {
     $block[0]["info"] = t('Thai Search');
     return $block;
  } else if ($op == 'view' && user_access('access thaisearch')) {
    $block['content'] = drupal_get_form('thaisearch_form', $keys, $size=15);
    $block['subject'] = t('Thai Search');
    return $block;
  }
}

/**
 * Implementation of hook_menu().
 *
 * You must implement hook_menu() to emit items to place in the main menu.
 * This is a required step for modules wishing to display their own pages,
 * because the process of creating the links also tells Drupal what
 * callback function to use for a given URL. The menu items returned
 * here provide this information to the menu system.
 *
 * With the below menu definitions, URLs will be interpreted as follows:
 *
 * If the user accesses http://example.com/?q=foo, then the menu system
 * will first look for a menu item with that path. In this case it will
 * find a match, and execute thaisearch_foo().
 *
 * If the user accesses http://example.com/?q=bar, no match will be found,
 * and a 404 page will be displayed.
 *
 * If the user accesses http://example.com/?q=bar/baz, the menu system
 * will find a match and execute thaisearch_baz().
 *
 * If the user accesses http://example.com/?q=bar/baz/1/2, the menu system
 * will first look for bar/baz/1/2. Not finding a match, it will look for
 * bar/baz/1/%. Again not finding a match, it will look for bar/baz/%/2. Yet
 * again not finding a match, it will look for bar/baz/%/%. This time it finds
 * a match, and so will execute thaisearch_baz(1, 2). Note the parameters
 * being passed; this is a very useful technique.
 */
function thaisearch_menu() {

  // By using the MENU_CALLBACK type, we can register the callback for this
  // path but not have the item show up in the menu; the admin is not allowed
  // to enable the item in the menu, either.
  // 
  // Notice that the 'page arguments' is an array of numbers. These will be
  // replaced with the corresponding parts of the menu path. In this case a 0
  // would be replaced by 'thaisearch', and 1 will be Thai words to search.
  // These will be passed as arguments to the thaisearch_thaisearch() function.
  
  $items['thaisearch/%'] = array(
    'title' => 'Thai Search',
    'page callback' => 'thaisearch_thaisearch',
    'page arguments' => array(1),
    'access arguments' => array('access thaisearch'),
//    'type' => MENU_CALLBACK,
  );
 
  $items['thaisearch'] = array( 
    'title' => 'Thai Search',
    'page callback' => 'thaisearch_view',
    'access arguments' => array('access thaisearch'),
    'type' => MENU_SUGGESTED_ITEM,
 
  );
 
  return $items;
}
 
/**
 * Form builder; Output a search form for the search block and the theme's search box.
 * 
 * @ingroup forms
 * @see search_box_form_submit()
 * @see theme_search_box_form()
 */
function thaisearch_form(&$form_state, $form_id, $size=25) {
  // Add CSS
  drupal_add_css(drupal_get_path('module', 'thaisearch') .'/thaisearch.css', 'module', 'all', FALSE);

  $form['keys'] = array(
    '#title' => t('Search Thai words'),
    '#type' => 'textfield',
    '#size' => $size,
    '#default_value' => '',
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Search'));
  $form['#submit'][] = 'thaisearch_form_submit';
  $form['#validate'][] = 'thaisearch_form_validate';

  return $form;
}

/**
 * Process a block search form submission.
 */
function thaisearch_form_submit($form, &$form_state) {
  $keys = $form['keys']['#value'];
  $form_state['redirect'] = 'thaisearch/'. $keys;
}

/**
 * Helper function for grabbing search keys.
 */
function thaisearch_get_keys() {
  static $return;
  if (!isset($return)) {
    // Extract keys as remainder of path
    // Note: support old GET format of searches for existing links.
    $path = explode('/', $_GET['q'], 2);
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
    $return = count($path) == 2 ? $path[1] : $keys;
  }
  return $return;
}

/**
 * Menu callback; presents the search form and/or search results.
 */ 
function thaisearch_view() {
  // Search form submits with POST but redirects to GET. This way we can keep
  // the search query URL clean as a whistle:
  // search/type/keyword+keyword
  if (!isset($_POST['form_id'])) {
    
    $keys = thaisearch_get_keys(); 
    // Only perform search if there is non-whitespace search term:
    $results = '';
    if (trim($keys)) { 
      // Collect the search results:
      $results = thaisearch_thaisearch($keys);
  
      if ($results) {
        $results = theme('box', t('Search results'), $results);
      }
      else { 
        $results = theme('box', t('Your search yielded no results'), thaisearch_help('search#noresults', drupal_help_arg()));
      } 
    }
    // Construct the search form.
    $output = drupal_get_form('thaisearch_form', $keys);
    $output .= $results;
 
    return $output;
  }
  
  return drupal_get_form('thaisearch_form', empty($keys) ? '' : $keys);
}   
    
    
/** 
 * Helper function: is word in string 
 */
function _in_string($string, $word) {
  if (strpos($string, $word) === FALSE) { return FALSE; } else { return TRUE; }
}

/**
 * Helper function: get array of wordlist from words
 * 'a "b c" d' => ['a "b c" d', 'a', 'b c', 'd']
 */
function _get_wordlist($string) {
  $temp = trim($string);
  $wordlist = array();
  $wordlist[] = $string;
  while (strlen($temp) > 0) {
    $m = 9999;
    if (_in_string($temp, " ")) {
      $p1 = strpos($temp, " ");
      $m = ($m < $p1) ? $m : $p1;
    }
    if (_in_string($temp, '"')) {
      $p2 = strpos($temp, '"');
      $m = ($m < $p2) ? $m : $p2;
    }
    if (_in_string($temp, "'")) {
      $p3 = strpos($temp, "'");
      $m = ($m < $p3) ? $m : $p3;
    }
    if ($m == $p1) {
      $a = explode(" ",$temp,2);
      $wordlist[] = $a[0];
      $temp = trim($a[1]);
    } elseif ($m == $p2 and substr_count($temp, '"') > 1 and (_in_string($temp, '" ') or substr($temp, -1) == '"')) {
      $a = explode('"',$temp,3);
      $wordlist[] = $a[1];
      $temp = trim($a[2]);
    } elseif ($m == $p3 and substr_count($temp, "'") > 1 and (_in_string($temp, "' ") or substr($temp, -1) == "'")) {
      $a = explode("'",$temp,3);
      $wordlist[] = $a[1];
      $temp = trim($a[2]);
    } else {
      $wordlist[] = $temp;
      $temp = '';
    }
  }
  return($wordlist);
}
 
/**
 * Helper function for array_walk in thaisearch_except.
 */
function _thaisearch_excerpt_replace(&$text) {
  $text = preg_quote($text, '/');
}   
    
/**
 * Helper function for trim text
 */   
function _trim_text($text, $pos = 'first', $length = 50) {
  $l = drupal_strlen($text);
  if ($l > $length) {
    switch ($pos) {
      case 'first':
        return ' ...'.drupal_substr($text, $l-$length, $length);
      case 'middle':
        $b = intval($length / 2);
        return drupal_substr($text, 0, $b).'...'.drupal_substr($text, $l-$b, $b);
      case 'last': 
        return drupal_substr($text, 0, $length).'... ';
    } 
  }   
  return $text;
}

/**   
 * A more complex page callback that takes arguments.
 *  
 * The arguments are passed in from the page URL. The in our hook_menu
 * implementation we instructed the menu system to extract the last two
 * parameters of the path and pass them to this function as arguments.

 * do search from node_revision.title, node_revision.body and comments.comment

 */
function thaisearch_thaisearch($keys) {
 // Log the search keys:
 watchdog('thaisearchsearch', '%keys (@type).', array('%keys' => $keys, '@type' => module_invoke($type, 'thaisearch', 'name')), WATCHDOG_NOTICE, l(t('results'), 'thaisearch/'. $type .'/'. $keys));

  $max_item = 50;
  $wordlist = _get_wordlist($keys);

  $qarray = array();
  $arguments = array();

  for ($iwl = 0; $iwl < count($wordlist); $iwl++) {
    // first argument in full word: allscore*10
    switch ($iwl) {
      case 0:
        $w = 10;
      case 1:
        $w = 2;
      default:
        $w = 1;
    }
    // node.title: score*10
    $qarray[] = " SELECT ".strval($w*10)." AS score, n.nid, 0 AS cid, n.title, n.body, n.timestamp FROM {node_revisions} n WHERE n.title LIKE '%%%s%%' ";
    // node.body: score*2
    $qarray[] = " SELECT ".strval($w*2)." AS score, n.nid, 0 AS cid, n.title, n.body, n.timestamp FROM {node_revisions} n WHERE n.body LIKE '%%%s%%' ";
    // comments.comment: score*1
    $qarray[] = " SELECT ".strval($w*1)." AS score, c.nid, c.cid, n.title, c.comment, c.timestamp AS body FROM {comments} c INNER JOIN {node_revisions} n ON n.nid = c.nid WHERE c.comment LIKE '%%%s%%' ";

    $arguments = array_merge($arguments, array($wordlist[$iwl], $wordlist[$iwl], $wordlist[$iwl]));
  }

  $q = 'SELECT SUM(score) AS score, nid, cid, title, body, timestamp FROM ('.implode(' UNION ALL ',$qarray).') t GROUP BY t.nid, t.cid, t.title, t.body, t.timestamp ORDER BY score DESC, nid DESC, timestamp DESC';
 
  $sql_count = 'SELECT COUNT(*) AS num FROM ('.$q.') t';
  $count = db_fetch_object(db_query($sql_count, $arguments)); 
  $found = $count->num;
  
  $query = db_query_range($q, $arguments, 0, $max_item);
  
  // highlight words in trimmed output
  $dlist = '';
  $max_length= 50;
  while ($links = db_fetch_object($query)) {
    // highlight words
    $text = ' '. strip_tags(str_replace(array('<', '>'), array(' <', '> '), $links->body)) .' '; 
    array_walk($wordlist, '_thaisearch_excerpt_replace');
    $text = preg_replace('/('. implode('|', $wordlist) .')/iu', '<strong>\0</strong>', $text);

    // trim output
    $text_front = '';

    if (_in_string($text, '<strong>')) {
      $item_count = 0;
      $text_array = explode('<strong>', $text, 2);
      $text_front = _trim_text($text_array[0], 'first', $max_length).'<strong>';
      $text_array = explode('</strong>', $text_array[1], 2);
      $text_front .= $text_array[0].'</strong>';
      $text = $text_array[1];
      while (_in_string($text, '<strong>') and $item_count < 5) {
        $item_count++;
        $text_array = explode('<strong>', $text, 2);
        $text_front .= _trim_text($text_array[0], 'middle', $max_length).'<strong>';
        $text_array = explode('</strong>', $text_array[1], 2);
        $text_front .= $text_array[0].'</strong>';
        if (_in_string($text_array[1], '<strong>')) {
          $text = $text_array[1];
        } else {
          $text = _trim_text($text_array[1], 'last', $max_length);
        }
      }
      $text_front .=  _trim_text($text, 'last', $max_length);
    } else {
      $text_front = truncate_utf8($text, $max_length, TRUE);
    }
    $dlist .= '<dt><strong>'.l($links->title, 'node/'.$links->nid).'</strong></dt>';
    $dlist .= '<dd>'.$text_front.'</dd></strong><br />';
  }

  $output = thaisearch_help('thaisearch','').'<br />';
  $output .= drupal_get_form('thaisearch_form', $keys);
  $output .= t('Search words: <strong>'.$keys.'</strong>, found: <strong>'.$found.'</strong><br />');

  if ($dlist) {
    $output .= theme('box', t('Search results'), '<br /><dl>'.$dlist.'</dl>', 10, 0);
  } else {
    $output .= theme('box', t('Your search yielded no results'));
  }
  return $output;
}
?>

 

Syndicate

Subscribe to Syndicate

Who's online

There are currently 0 users online.