<?php
class ArticlesController extends AppController {

  var $name = 'Articles';
  var $uses = array('Article', 'Item', 'ArticleItem', 'Category');
  var $helpers = array('Html', 'Form', 'ApArticleItem', 'ApCategoryList', 'Time', 'Number');
  var $components = array('Assoc');

  function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('view', 'search', 'assoc');
  }

  function view($id = null) {
    $this->Category->recursive = -1;
    $root_category = $this->Category->findByParent_Id('0');
    $this->set('heading_title', $root_category['Category']['title']);
    if (!$id) {
      $this->pageTitle = $root_category['Category']['title'];
      $this->set('meta_description', '');
      $this->set('meta_keywords', '');
      $cid = $root_category['Category']['id'];
      $error404 = true;
    } else {
      if (!$article = $this->Article->find('first', array('conditions' => array('id' => $id, 'status >' => '0'), 'recursive' => -1))) {
        $this->pageTitle = $root_category['Category']['title'];
        $this->set('meta_description', '');
        $this->set('meta_keywords', '');
        $cid = $root_category['Category']['id'];
        $error404 = true;
      } else {
        $this->data = $this->ArticleItem->find('all', array('conditions' => array('article_id' => $id, 'Item.status >' => '0'), 'order' => 'Item.sort_order', 'recursive' => 0));
        $this->pageTitle = $root_category['Category']['title'] . ' : ' . $article['Article']['title'];
        $this->set('meta_description', $article['Article']['meta_description']);
        $this->set('meta_keywords', $article['Article']['meta_keywords']);
        $error404 = false;
        $cid = $article['Article']['category_id'];
      }
    }
    $parent_category = $this->Category->getpath($cid);
    $conditions_array = array();
    if (!empty($parent_category)) {
      foreach ($parent_category as $val) {
        $conditions_array[] = 'parent_id = ' . $val['Category']['id'];
      }
    }
    $conditions = implode(' or ', $conditions_array);
    $cTree = $this->Category->find('all', array('conditions' => $conditions, 'order' => 'lft ASC', 'recursive' => -1));
    if (!empty($cTree)) {
      foreach ($cTree as $key => $val) {
        if (!empty($article['Article']['category_id']) && ($val['Category']['id'] == $article['Article']['category_id'])) {
          $cTree[$key]['Category']['current'] = true;
        }
      }
    }
    $this->set('cTree', $cTree);
    if ($error404) {
      header("HTTP/1.1 404 Not Found");
      $this->render('view404');
    }
  }

  function search() {
    $this->Category->recursive = -1;
    $root_category = $this->Category->findByParent_Id('0');
    $this->pageTitle = $root_category['Category']['title'] . ' : 検索結果';
    $this->set('heading_title', $root_category['Category']['title']);
    $this->set('meta_description', $root_category['Category']['meta_description']);
    $this->set('meta_keywords', $root_category['Category']['meta_keywords']);
    $this->set('current', $root_category);
    $conditions = 'parent_id = ' . $root_category['Category']['id'];
    $cTree = $this->Category->find('all', array('conditions' => $conditions, 'order' => 'lft ASC', 'recursive' => -1));
    $this->set('cTree', $cTree);
    $category = $this->Category->find('all', array('order' => 'lft ASC', 'recursive' => -1));
    $this->set('category', $category);
    
    if (!empty($this->params['form']['keywords']) || !empty($this->params['named']['keywords'])) {
      if (!empty($this->params['named']['keywords'])) {
        $keywords = $this->params['named']['keywords'];
      } else {
        $keywords = $this->params['form']['keywords'];
      }
      $search_conditions = $this->__parse_search_query($keywords, 'Article.search_text');
      $this->Article->recursive = -1;
      $this->paginate = array('conditions' => 'Article.status > 0 and ' . $search_conditions, 'sort' => 'Article.created desc', 'limit' => 10);
      $this->set('articles', $this->paginate());
      $this->set('keywords', $keywords);
    }
  }
  
  function __parse_search_query($query, $field) {
    $search_str = trim(strtolower($query));

    $pieces = split('[[:space:]]+', $search_str);
    $objects = array();
    $tmpstring = '';
    $flag = '';

    for ($k=0; $k<count($pieces); $k++) {
      while (substr($pieces[$k], 0, 1) == '(') {
        $objects[] = '(';
        if (strlen($pieces[$k]) > 1) {
          $pieces[$k] = substr($pieces[$k], 1);
        } else {
          $pieces[$k] = '';
        }
      }

      $post_objects = array();

      while (substr($pieces[$k], -1) == ')')  {
        $post_objects[] = ')';
        if (strlen($pieces[$k]) > 1) {
          $pieces[$k] = substr($pieces[$k], 0, -1);
        } else {
          $pieces[$k] = '';
        }
      }

      if ( (substr($pieces[$k], -1) != '"') && (substr($pieces[$k], 0, 1) != '"') ) {
        $objects[] = trim($pieces[$k]);

        for ($j=0; $j<count($post_objects); $j++) {
          $objects[] = $post_objects[$j];
        }
      } else {
        $tmpstring = trim(ereg_replace('"', ' ', $pieces[$k]));

        if (substr($pieces[$k], -1 ) == '"') {
          $flag = 'off';

          $objects[] = trim($pieces[$k]);

          for ($j=0; $j<count($post_objects); $j++) {
            $objects[] = $post_objects[$j];
          }

          unset($tmpstring);
          continue;
        }

        $flag = 'on';
        $k++;

        while ( ($flag == 'on') && ($k < count($pieces)) ) {
          while (substr($pieces[$k], -1) == ')') {
            $post_objects[] = ')';
            if (strlen($pieces[$k]) > 1) {
              $pieces[$k] = substr($pieces[$k], 0, -1);
            } else {
              $pieces[$k] = '';
            }
          }

          if (substr($pieces[$k], -1) != '"') {
            $tmpstring .= ' ' . $pieces[$k];

            $k++;
            continue;
          } else {
            $tmpstring .= ' ' . trim(ereg_replace('"', ' ', $pieces[$k]));

            $objects[] = trim($tmpstring);

            for ($j=0; $j<count($post_objects); $j++) {
              $objects[] = $post_objects[$j];
            }

            unset($tmpstring);

            $flag = 'off';
          }
        }
      }
    }

    $temp = array();
    for($i=0; $i<(count($objects)-1); $i++) {
      $temp[sizeof($temp)] = "(" . $field . " like '%" . addslashes($objects[$i]) . "%')";

      if ( ($objects[$i] != 'and') &&
           ($objects[$i] != 'or') &&
           ($objects[$i] != '(') &&
           ($objects[$i] != ')') &&
           ($objects[$i+1] != 'and') &&
           ($objects[$i+1] != 'or') &&
           ($objects[$i+1] != '(') &&
           ($objects[$i+1] != ')') ) {
        $temp[sizeof($temp)] = 'and';
      }
    }
    $temp[sizeof($temp)] = "(" . $field . " like '%" . addslashes($objects[$i]) . "%')";
    $objects = $temp;

    $keyword_count = 0;
    $operator_count = 0;
    $balance = 0;
    for($i=0; $i<count($objects); $i++) {
      if ($objects[$i] == '(') $balance --;
      if ($objects[$i] == ')') $balance ++;
      if ( ($objects[$i] == 'and') || ($objects[$i] == 'or') ) {
        $operator_count ++;
      } elseif ( ($objects[$i]) && ($objects[$i] != '(') && ($objects[$i] != ')') ) {
        $keyword_count ++;
      }
    }

    if ( ($operator_count < $keyword_count) && ($balance == 0) ) {
      $parsed_query = implode(' ', $objects);
      return $parsed_query;
    } else {
      return false;
    }
  }

  function assoc() {
    $this->Category->recursive = -1;
    $root_category = $this->Category->findByParent_Id('0');
    $this->pageTitle = $root_category['Category']['title'] . ' : 連想検索';
    $this->set('heading_title', $root_category['Category']['title']);
    $this->set('meta_description', $root_category['Category']['meta_description']);
    $this->set('meta_keywords', $root_category['Category']['meta_keywords']);
    $this->set('current', $root_category);
    $conditions = 'parent_id = ' . $root_category['Category']['id'];
    $cTree = $this->Category->find('all', array('conditions' => $conditions, 'order' => 'lft ASC', 'recursive' => -1));
    $this->set('cTree', $cTree);
    $category = $this->Category->find('all', array('order' => 'lft ASC', 'recursive' => -1));
    $this->set('category', $category);
    
    $assoc_text = '';
    $assoc_words = array();
    $assoc_articles = array();
    if (!empty($this->params['form']['assoc_text'])) {
      $assoc_text = $this->params['form']['assoc_text'];
    }
    if (!empty($this->params['form']['assoc_words'])) {
      $assoc_words = $this->params['form']['assoc_words'];
    }
    if (!empty($this->params['form']['assoc_articles'])) {
      $assoc_articles = $this->params['form']['assoc_articles'];
    }
    if (!empty($this->params['form']['limit_articles'])) {
      $limit = (int)$this->params['form']['limit_articles'];
    } else {
      $limit = 10;
    }
    if (empty($this->params['form']['page'])) {
      $page = 1;
    } else {
      $page = (int)$this->params['form']['page'];
    }
    $this->set('page', $page);
    $this->set('assoc_text', $assoc_text);
    if (empty($assoc_text) && empty($assoc_words) && empty($assoc_articles)) {
      $this->set('results', '');
    } else {
      $assoc_results = $this->Assoc->assoc_search(array('page' => $page, 'limit' => $limit), $assoc_text, $assoc_words, $assoc_articles);
      $this->set('last_assoc_text', $assoc_text);
      $this->set('last_assoc_words', $assoc_words);
      $this->set('last_assoc_articles', $assoc_articles);
      if ($assoc_results) {
        if (empty($assoc_results['results_count']) || ($assoc_results['results_count'] == 0)) {
          $this->set('results', '連想できる記事がありませんでした。');
        } else {
          $this->set('results', $assoc_results);
        }
      } else {
        $this->set('results', '連想できませんでした。');
      }
    }
  }

  function admin_index() {
    $this->pageTitle = '管理画面：記事の一覧';
    $this->layout = 'admin';
    $this->Article->recursive = 0;
    $this->paginate = array('sort' => 'Article.created desc', 'limit' => 10);
    $this->set('articles', $this->paginate());
  }

  function admin_add() {
    $this->pageTitle = '管理画面：記事の追加';
    $this->layout = 'admin';
    if (!empty($this->data)) {
      $this->data['Article']['status'] = 0;
      $this->Article->create();
      $this->Article->set($this->data);
      if ($this->Article->save()) {
        $article_id = $this->Article->getinsertid();
        $this->redirect('/admin/article_items/edit/' . $article_id);
      }
    }
    if (!$this->Item->find('count', array('conditions' => array('status' => '1'), 'order' => 'sort_order', 'recursive' => -1))) {
      $this->flash( '記事項目が設定されていません。まず、記事構成設定を行ってください。', 'error' );
      $this->redirect(array('action' => 'admin_index'));
    }
    $this->set('categories', $this->Article->Category->generateTreeList(null, "{n}.Category.id", "{n}.Category.title", '　', -1));
  }

  function admin_edit($id = null) {
    $this->pageTitle = '管理画面：記事基本情報の編集';
    $this->layout = 'admin';
    if (!$id && empty($this->data)) {
      $this->flash( '編集する記事を指定してください。', 'error' );
      $this->redirect(array('action' => 'admin_index'));
    }
    if (!empty($this->data)) {
      $this->Article->create();
      $this->Article->set($this->data);
      if ($this->Article->save()) {
        $this->flash( '記事基本情報を更新しました。', 'success' );
        $this->redirect(array('action' => 'admin_index'));
      }
    } else {
      $this->data = $this->Article->read(null, $id);
      $this->set('categories', $this->Article->Category->generateTreeList(null, "{n}.Category.id", "{n}.Category.title", '　', -1));
    }
  }

  function admin_delete($id = null) {
    if (!$id) {
      $this->flash( '削除する記事を指定してください。', 'error' );
      $this->redirect(array('action' => 'admin_index'));
    }
    if ($this->Article->del($id, true)) {
      $this->flash( '記事項目を削除しました。', 'success' );
      $this->redirect(array('action' => 'admin_index'));
    }
  }

  function admin_makewam() {
    $this->Assoc->makewam();
    $this->redirect(array('controller'=>'articles', 'action'=>'admin_index'));
  }

}
?>
