<?php
class AssocComponent extends Object {

  var $freqfile_dir = TMP;
  var $convert_kana = 'KVas';
  var $remove_signs = '[^0-9a-zA-Zぁ-んァ-龠 ]';
  var $stop_words = array();
  
  var $mecab_path = '/usr/local/bin/mecab -F"%m\t%h\n"';
  var $mecab_pos_list = '10|11|12|34|36|37|38|39|40|41|42|43|44|45|46|47|49|50|51|52|53|54|55|56|57|58|63|64|65|66|67';

  var $titlefile_dir = TMP;
  var $titlefile_delimiter_01 = '::';
  var $titlefile_delimiter_02 = '<>';

  var $_geta_short_name = 'ap_article';
  var $_geta_dir;
  var $_geta_mkw;
  var $_geta_mkaux;
  var $_geta_assoc;

  var $__limit_results = 20;
  var $__first_result = 1;

  var $_controller;

  function startup(&$controller) {
    $this->_controller = $controller;
    $this->_geta_dir = VENDORS . 'geta/';
    $this->_geta_mkw = $this->_geta_dir . 'mkw.sh';
    $this->_geta_mkaux = $this->_geta_dir . 'mkaux.sh';
    $this->_geta_assoc = $this->_geta_dir . 'assoc.pl';
    mb_regex_encoding('UTF-8');
  }

  function assoc_search($settings = array(), $text = '', $words = array(), $articles = array()) {
    if (empty($text) && empty($words) && empty($articles)) {
      return false;
    }
    if (!empty($settings['limit'])) {
      $this->__limit_results = $settings['limit'];
    }
    if (!empty($settings['page'])) {
      $this->__first_result = 1 + ($this->__limit_results * ( $settings['page'] - 1 ));
    }
    $max_results = $this->__first_result + $this->__limit_results - 1;

    $criteria = '';

    if (!empty($text)) {
      $text = str_replace("\r", "\n", $text);
      $text = strip_tags($text);
      $text = mb_convert_kana($text, $this->convert_kana, 'UTF-8');
      $text = mb_ereg_replace($this->remove_signs, '', $text);
      if (!empty($this->stop_words)) {
        foreach ($this->stop_words as $value) {
          if ($value) $text = mb_ereg_replace($value, "", $text);
        }
      }
      $text_lines = explode("\n", $text);
      foreach ($text_lines as $text_line) {
        if (!empty($text_line)) {
          $criteria .= '[t]' . $text_line . "\n";
        }
      }
    }
    if (!empty($words)) {
      if (is_array($words)) {
        foreach ($words as $word) {
          $criteria .= '[w]' . $word . "\n";
        }
      } else {
        $criteria .= '[w]' . $words . "\n";
      }
    }
    if (!empty($articles)) {
      if (is_array($articles)) {
        foreach ($articles as $article) {
          $criteria .= '[a]' . $article . "\n";
        }
      } else {
        $criteria .= '[a]' . $articles . "\n";
      }
    }
    if (empty($criteria)) {
      return false;
    }

    $output_array = array();

    $cmd = sprintf("perl %s %s %s %s 2>&1", $this->_geta_assoc, $this->_geta_short_name, $max_results, $this->__first_result);
    $spec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
    $assoc_proc = proc_open($cmd, $spec, $pipes);
    if (is_resource($assoc_proc)) {
      fwrite($pipes[0], $criteria);
      fclose($pipes[0]);
      while (!feof($pipes[1])) {
        $assoc_results = fgets($pipes[1]);
        $results_array = split("\t", $assoc_results);
        if (isset($results_array[0])) {
          switch ($results_array[0]) {
            case '[C]':
              if (empty($results_array[1])) {
                $output_array['results_count'] = 0;
              } else {
                $output_array['results_count'] = $results_array[1];
              }
              break;
            case '[A]':
              $items = split($this->titlefile_delimiter_02, $results_array[3]);
              foreach ($items as $item) {
                $value = split($this->titlefile_delimiter_01, $item);
                if (isset($value[0])) {
                  if (isset($value[1])) {
                    $title_value[$value[0]] = $value[1];
                  } else {
                    $title_value[$value[0]] = '';
                  }
                }
              }
              $output_array['articles'][] = array_merge(array('assoc_id' => $results_array[1],
                                               'assoc_weight' => $results_array[2]), $title_value);
              break;
            case '[W]':
              $output_array['words'][] = $results_array[1];
              break;
          }
        }
      }
      fclose($pipes[1]);
      proc_close($assoc_proc);

      if (!empty($output_array['results_count'])) {
        if ($this->__first_result == 1) {
          $output_array['previous_page'] = false;
        } else {
          $output_array['previous_page'] = true;
        }
        $output_array['first_result'] = $this->__first_result;
        if ($max_results >= $output_array['results_count']) {
          $output_array['max_results'] = $output_array['results_count'];
          $output_array['next_page'] = false;
        } else {
          $output_array['max_results'] = $max_results;
          $output_array['next_page'] = true;
        }
      }
    }
    if (!empty($output_array)) {
      return $output_array;
    } else {
      return false;
    }
  }

  function makewam() {
    $freqfile_path = tempnam($this->freqfile_dir, 'makewam_ff_');
    $ff = fopen($freqfile_path, 'w');
    $titlefile_path = tempnam($this->titlefile_dir, 'makewam_tf_');
    $tf = fopen($titlefile_path, 'w');
    $articles = $this->_controller->Article->find('all', array('recursive' => -1));
    foreach ($articles as $article) {
      fwrite($ff, '#' . $article['Article']['id'] . "\n");
      $article_data = $article['Article']['title'];
      $article_data .= ' ' . $article['Article']['meta_description'];
      $article_data .= ' ' . $article['Article']['meta_keywords'];
      $article_data .= ' ' . $article['Article']['search_text'];
      $article_data = str_replace("\r", "", $article_data);
      $article_data = str_replace("\n", "", $article_data);
      $article_data = strip_tags($article_data);
      $article_data = mb_convert_kana($article_data, $this->convert_kana, 'UTF-8');
      $article_data = mb_ereg_replace($this->remove_signs, '', $article_data);
      if (!empty($this->stop_words)) {
        foreach ($this->stop_words as $value) {
          if ($value) $article_data = mb_ereg_replace($value, "", $article_data);
        }
      }

      $freqfile_data = '';
      $spec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
      $mecab_proc = proc_open($this->mecab_path, $spec, $pipes);
      if (is_resource($mecab_proc)) {
        fwrite($pipes[0], $article_data);
        fclose($pipes[0]);
        while (!feof($pipes[1])) {
          $mecab_result = fgets($pipes[1]);
          $mr_array = split("\t", $mecab_result);
          if (isset($mr_array[1])) {
            if (ereg($this->mecab_pos_list, $mr_array[1])) {
              $freqfile_data .= ' ' . $mr_array[0] . "\n";
            }
          }
        }
        fclose($pipes[1]);
        proc_close($mecab_proc);
      }
      fwrite($ff, $freqfile_data);

      fwrite($tf, "%" . $article['Article']['id'] . "\n");
      $titlefile_data = ' ';
      $titlefile_data .= 'title' . $this->titlefile_delimiter_01 . $article['Article']['title'];
      $titlefile_data .= $this->titlefile_delimiter_02;
      $titlefile_data .= 'meta_description' . $this->titlefile_delimiter_01 . $article['Article']['meta_description'];
      $titlefile_data = str_replace("\r\n", "\n", $titlefile_data);
      $titlefile_data = str_replace("\r", "\n", $titlefile_data);
      $titlefile_data = str_replace("\n", "\\n", $titlefile_data);
      fwrite($tf, $titlefile_data . "\n");
    }
    fclose($ff);
    fclose($tf);
    
    system($this->_geta_mkw . ' ' . $this->_geta_short_name . ' ' . $this->_geta_dir . ' ' . $freqfile_path . ' &');
    system($this->_geta_mkaux . ' ' . $this->_geta_short_name . ' ' . $this->_geta_dir . ' ' . $titlefile_path . ' &');
    
    unlink($freqfile_path);
    unlink($titlefile_path);

  }

}
?>
