You are here

similar_handler_argument_nid.inc in Similar Entries 6.2

Same filename and directory in other branches
  1. 7.2 views/similar_handler_argument_nid.inc

Defines the Similar entries node ID argument.

File

views/similar_handler_argument_nid.inc
View source
<?php

/**
 * @file
 * Defines the Similar entries node ID argument.
 */

/**
 * Defines the similar entries View node ID argument.
 */
class similar_handler_argument_nid extends views_handler_argument_numeric {

  /**
   * Alters the behavior of the Views title() method.
   */
  public function title_query() {
    $placeholders = implode(', ', array_fill(0, count($this->value), '%d'));
    $titles = array();
    $result = db_query("SELECT title FROM {node} WHERE nid IN ({$placeholders})");
    while ($node = db_fetch_object($result)) {
      $titles[] = check_plain($node->title);
    }
    return $titles;
  }

  /**
   * Defines default values for argument settings.
   */
  public function option_definition() {
    $common_words = array(
      '-not',
      '-and',
      '-a',
      '-or',
      '-the',
      '-but',
      '-therefore',
      '-because',
      '-can\'t',
      '-can',
      '-for',
      '-until',
      '-the',
      '-of',
      '-and',
      '-to',
      '-in',
      '-is',
      '-you',
      '-that',
      '-it',
      '-he',
      '-was',
      '-on',
      '-are',
      '-as',
      '-with',
      '-his',
      '-they',
      '-I',
      '-at',
      '-be',
      '-this',
      '-have',
      '-from',
      '-one',
      '-had',
      '-by',
      '-word',
      '-but',
      '-not',
      '-what',
      '-all',
      '-were',
      '-we',
      '-when',
      '-your',
      '-said',
      '-there',
      '-use',
      '-an',
      '-each',
      '-which',
      '-she',
      '-do',
      '-how',
      '-their',
      '-if',
      '-will',
      '-up',
      '-other',
      '-about',
      '-out',
      '-many',
      '-then',
      '-them',
      '-these',
      '-so',
      '-some',
      '-her',
      '-would',
      '-make',
      '-like',
      '-him',
      '-into',
      '-time',
      '-has',
      '-look',
      '-two',
      '-more',
      '-write',
      '-go',
      '-see',
      '-no',
      '-way',
      '-could',
      '-people',
      '-my',
      '-than',
      '-first',
      '-water',
      '-been',
      '-call',
      '-who',
      '-oil',
      '-its',
      '-now',
      '-find',
    );
    $options = parent::option_definition();
    $options['default_action'] = array(
      'default' => 'default',
    );
    $options['default_argument_type'] = array(
      'default' => 'node',
    );
    $options['validate_type'] = array(
      'default' => 'node',
    );
    $options['similar']['boolean_mode'] = array(
      'default' => 0,
    );
    $options['similar']['adjust_relevance'] = array(
      'default' => 1,
    );
    $options['similar']['relevance']['title_relevance'] = array(
      'default' => 1.4,
    );
    $options['similar']['relevance']['body_relevance'] = array(
      'default' => 0.8,
    );
    $options['similar']['boolean_options']['title_operator'] = array(
      'default' => 'increase',
    );
    $options['similar']['boolean_options']['enable_custom_operators'] = array(
      'default' => 0,
    );
    $options['similar']['boolean_options']['operators_fieldset']['custom_operators'] = array(
      'default' => implode(' | ', $common_words),
    );

    // Notify Views of individual field weights.
    // Note: the Views cache may need to be reset when fields are added.
    if (module_exists('content')) {
      $options['similar']['include_fields'] = array(
        'default' => 0,
      );
      foreach (self::get_field_options() as $table => $field) {
        $options['similar']['cck_fields']['included_fields:' . $table] = array(
          'default' => 1,
        );
      }
    }
    return $options;
  }

  /**
   * Defines the options form.
   */
  public function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    unset($form['not']);
    $form['similar'] = array(
      '#type' => 'fieldset',
      '#title' => t('FULLTEXT search options'),
    );

    // Add fields for increasing or decreasing relevance of destination ndoe fields.
    $relevance_options = array(
      '0' => '0%',
      '0.1' => '10%',
      '0.2' => '20%',
      '0.3' => '30%',
      '0.4' => '40%',
      '0.5' => '50%',
      '0.6' => '60%',
      '0.7' => '70%',
      '0.8' => '80%',
      '0.9' => '90%',
      '1.0' => '100%',
      '1.1' => '110%',
      '1.2' => '120%',
      '1.3' => '130%',
      '1.4' => '140%',
      '1.5' => '150%',
      '1.6' => '160%',
      '1.7' => '170%',
      '1.8' => '180%',
      '1.9' => '190%',
      '2.0' => '200%',
    );
    $form['similar']['adjust_relevance'] = array(
      '#type' => 'checkbox',
      '#title' => t('Adjust relevance of fields'),
      '#default_value' => $this->options['similar']['adjust_relevance'],
      '#description' => t('Adjust the relevance of content titles, bodies, and other fields in matching.'),
    );
    $form['similar']['relevance'] = array(
      '#type' => 'fieldset',
      '#title' => t('Match Relevance'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    $form['similar']['relevance']['title_relevance'] = array(
      '#type' => 'select',
      '#title' => t('Relevance of content\'s title'),
      '#options' => $relevance_options,
      '#default_value' => $this->options['similar']['relevance']['title_relevance'],
      '#description' => t('Increase or decrease the relevance of matches in destination content\'s title field.'),
    );
    $form['similar']['relevance']['body_relevance'] = array(
      '#type' => 'select',
      '#title' => t('Relevance of content\'s body'),
      '#options' => $relevance_options,
      '#default_value' => $this->options['similar']['relevance']['body_relevance'],
      '#description' => t('Increase or decrease the relevance of matches in destination content\'s body field.'),
    );

    // Add fields for enabling matching in fields defined by field module.
    if (module_exists('content')) {
      $field_options = self::get_field_options();
      $form['similar']['include_fields'] = array(
        '#type' => 'checkbox',
        '#title' => t('Include CCK fields in matching'),
        '#default_value' => !empty($this->options['similar']['include_fields']),
        '#description' => t('Enable FULLTEXT queries on fields defined with Field module.'),
      );
      $form['similar']['cck_fields'] = array(
        '#type' => 'fieldset',
        '#title' => t('CCK Fields'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
      );
      foreach ($field_options as $table => $field) {
        $form['similar']['cck_fields']['included_fields:' . $table] = array(
          '#type' => 'select',
          '#title' => $field,
          '#options' => $relevance_options,
          '#default_value' => isset($this->options['similar']['cck_fields']['included_fields:' . $table]) ? $this->options['similar']['cck_fields']['included_fields:' . $table] : 1,
          '#fieldset' => 'similar',
        );
      }
    }
    $form['similar']['boolean_mode'] = array(
      '#type' => 'checkbox',
      '#title' => t('Execute search in boolean mode'),
      '#default_value' => !empty($this->options['similar']['boolean_mode']),
      '#description' => t('Boolean mode enables the ability to increase or decrease the relevance of certain fields.<br />' . 'Note: Boolean mode may negatively affect the accuracy of view results.'),
    );
    $form['similar']['boolean_options'] = array(
      '#type' => 'fieldset',
      '#title' => t('Boolean Mode Options'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );

    // Add options for increasing or decreasing relevance of source node.
    $form['similar']['boolean_options']['title_operator'] = array(
      '#type' => 'select',
      '#title' => t('Relevance of source content\'s title'),
      '#options' => array(
        'none' => t('No change'),
        'increase' => t('Increase title relevance'),
        'decrease' => t('Decrease title relevance'),
        'require_all' => t('Require all terms'),
        'require_some' => t('Require at least one term'),
        'require_complete' => t('Require complete title'),
        'exclude_all' => t('Exclude all terms'),
        'exclude_some' => t('Exclude at least one term'),
        'exclude_complete' => t('Exclude complete title'),
      ),
      '#default_value' => $this->options['similar']['boolean_options']['title_operator'],
    );

    // Add fields for creating custom relevance rules for specific words or phrases.
    $form['similar']['boolean_options']['enable_custom_operators'] = array(
      '#type' => 'checkbox',
      '#title' => t('Set custom operators in words and phrases'),
      '#default_value' => !empty($this->options['similar']['boolean_options']['enable_custom_operators']),
    );
    $form['similar']['boolean_options']['operators_fieldset'] = array(
      '#type' => 'fieldset',
      '#title' => t('Custom Operators'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    $form['similar']['boolean_options']['operators_fieldset']['custom_operators'] = array(
      '#type' => 'textfield',
      '#title' => t('Operators'),
      '#default_value' => $this->options['similar']['boolean_options']['operators_fieldset']['custom_operators'],
      '#description' => t('Use boolean logical operators to customize the FULLTEXT query. Each expression should ' . 'be separated by a vertical bar |.<br />' . 'Available operators:  +  -  >  <  (  )  ~  "<br />' . 'See http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html for more information.'),
      '#maxlength' => 1024,
    );
  }

  /**
   * Validates that the argument works.
   */
  public function validate_arg($arg) {
    if (!parent::validate_arg($arg)) {
      return FALSE;
    }
    if (!empty($this->options['break_phrase'])) {
      views_break_phrase($this->argument, $this);
    }
    else {
      $this->value = array(
        $this->argument,
      );
    }
    $this->view->nids = $this->value;
    return TRUE;
  }

  /**
   * Builds the query.
   */
  public function query() {
    $boolean = !empty($this->options['similar']['boolean_mode']);
    $text = '';

    // Since the view could have multiple nid arguments, load each node
    // and populate the $text variable with node titles and bodies.
    foreach ($this->value as $nid) {
      $node = node_load($nid);

      // Remove punctuation from the title.
      $title = preg_replace('/[^a-z0-9 _-]+/i', '', $node->title);

      // Alter the relevancy of words in the node title if option is selected.
      if ($boolean && isset($this->options['similar']['boolean_options']['title_operator'])) {
        $title = $this
          ->alter_node_title($title);
      }

      // Strip tags and add slashes only to the body before adding the title.
      $body = trim(addslashes(strip_tags($node->body)));
      $text .= " {$title} {$body}";
    }

    // Perform replacements to add custom operators to node body and title words.
    if ($boolean && !empty($this->options['similar']['boolean_options']['enable_custom_operators']) && !empty($this->options['similar']['boolean_options']['custom_operators'])) {
      $replacements = array_map('trim', explode('|', $this->options['similar']['boolean_options']['custom_operators']));
      $words = array_map('similar_handler_argument_nid::get_search_word', $replacements);
      $text = preg_replace($words, $replacements, $text);
    }
    $text = trim($text);
    $this
      ->ensure_my_table();
    $query = $boolean ? $this
      ->similar_build_query($text, 'IN BOOLEAN MODE') : $this
      ->similar_build_query($text);
    $this->query
      ->add_field('', $query, 'score');

    // Exclude the current node(s).
    if (count($this->value) > 1) {
      $placeholders = implode(', ', array_fill(0, count($this->value), '%d'));
      $this->query
        ->add_where(0, "node.nid NOT IN ({$placeholders})", $this->value);
    }
    else {
      $this->query
        ->add_where(0, 'node_revisions.nid <> %d', $this->value[0]);
    }
  }

  /**
   * Builds a query from argument configuration options.
   * @param $text
   *   The text of the current node to be used in the query.
   * @param $modifier
   *   An optional FULLTEXT search modifer. ie 'IN BOOLEAN MODE'.
   * @see similar_handler_argument_nid::query()
   */
  public function similar_build_query($text, $modifier = '') {
    $query = array();
    if (!empty($modifier)) {
      $modifier = " {$modifier}";
    }
    $revisions = $this->query
      ->ensure_table('node_revisions');

    // Add the node title to the query.
    $weight = !empty($this->options['similar']['adjust_relevance']) && isset($this->options['similar']['relevance']['title_relevance']) ? $this->options['similar']['relevance']['title_relevance'] : 1;
    $query[] = "({$weight} * (MATCH({$revisions}.title) AGAINST('{$text}'{$modifier})))";

    // Add the node body to the query.
    $weight = !empty($this->options['similar']['adjust_relevance']) && isset($this->options['similar']['relevance']['body_relevance']) ? $this->options['similar']['relevance']['body_relevance'] : 1;
    $query[] = "({$weight} * (MATCH({$revisions}.body) AGAINST('{$text}'{$modifier})))";
    if (module_exists('content') && !empty($this->options['similar']['include_fields'])) {
      $indices = similar_get_indices();
      foreach (self::get_field_options() as $field => $label) {
        $weight = !empty($this->options['similar']['relevance']['adjust_relevance']) && isset($this->options['similar']['cck_fields']['included_fields:' . $field]) ? $this->options['similar']['cck_fields']['included_fields:' . $field] : 1;

        // Tables and columns are stored as table:column.
        list($table, $column) = explode(':', $field);
        $alias = $this->query
          ->ensure_table($table);
        $query[] = "({$weight} * (MATCH({$table}.{$column}) AGAINST('{$text}'{$modifier})))";
      }
    }

    // Return a query that calculates an average score to prevent scores from fluctuating too much.
    // We multiply the score by different amounts depending on the modifier used.
    return "((" . implode(" + ", $query) . ") / " . count($query) . ")";
  }

  /**
   * Converts a user-defined word with operator into a search word for use
   * in preg_replace().
   *
   * @see similar_handler_argument_nid::query()
   */
  public static function get_search_word($word) {
    return '/\\b' . trim($word, '+-<>~()"') . '\\b/i';
  }

  /**
   * Alters the node title's relevance for boolean searches.
   *
   * @param $title
   *   The node title with punctuation removed.
   * @param $operator
   *   The operator to apply to the node title.
   * @see similar_handler_argument_nid::query()
   */
  private function alter_node_title($title) {
    switch ($this->options['similar']['boolean_options']['title_operator']) {
      case 'increase':
        return '>' . implode(' >', explode(' ', $title));
      case 'decrease':
        return '<' . implode(' <', explode(' ', $title));
      case 'require_all':
        return '+' . implode(' +', explode(' ', $title));
      case 'require_some':
        return "+({$title})";
      case 'require_complete':
        return '"' . $title . '"';
      case 'exclude_all':
        return '-' . implode(' -', explode(' ', $title));
      case 'exclude_some':
        return "-({$title})";
      case 'exclude_complete':
        return '-("' . $title . '")';
      default:
        return $title;
    }
  }

  /**
   * Returns an array of fields that have been indexed by Similar Entries.
   */
  private static function get_field_options() {
    $field_options = array();
    $indices = similar_get_indices();
    foreach (content_fields() as $field) {
      if ($field['type'] == 'text') {
        $info = content_database_info($field);
        foreach ($info['columns'] as $column) {
          if (isset($indices[$info['table']][$column['column']])) {
            $field_options[$info['table'] . ':' . $column['column']] = $field['widget']['label'];
          }
        }
      }
    }
    return $field_options;
  }

}

Classes

Namesort descending Description
similar_handler_argument_nid Defines the similar entries View node ID argument.