<?php

/**
 * entry actions.
 *
 * @package    violet
 * @subpackage entry
 * @author     Dinh Hai Minh
 * @delivery   Jul 2014
 */
class entryActions extends sfMyActions
{
  public function executeIndex() {
    $prev_url = $this->getRequest()->getReferer();
    if (preg_match('@show[\?&/]entry_id[=/](\d+)@', $prev_url, $match)) {
      $tblblogentry = TblblogentryPeer::retrieveByPK($match[1]);
      $this->redirect($tblblogentry->getListUrl());
    }
    if (preg_match('@list[\?&/]cat_id[=/](\d+)@', $prev_url, $match)) {
      $catItem = blogStore::$catTree->getCatItem($match[1]);
      if ($catItem->parent == -1) $this->redirect('/');
      else $this->redirect($catItem->mod.'/list?cat_id='.$catItem->parent);
    }
    $this->forward404('Đường dẫn không đầy đủ');
  }

  /**
   * List all entry in category
   */
  public function executeList() {
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->categoryItem = blogStore::$catTree->getCatItem($this->cat_id);
    $this->forward404Unless($this->categoryItem, 'Thư mục không tồn tại');
    $this->forward404Unless($this->categoryItem->mod == $this->getModuleName(), 'Thư mục không hợp lệ');

    $this->sort = $this->getUser()->getUserSort();
    $sort_date = ($this->sort != 'download' || $this->categoryItem->type == 2);
    $sort_id = $sort_date? TblblogcategoryentryPeer::CE_MODIFYDATE: TblblogcategoryentryPeer::CE_HIT;
    $this->listType = $this->categoryItem->config['listtype'];
    $this->multiple_cat = $this->categoryItem->isRootBranch() || ($this->listType == 'category' && count($this->categoryItem->items) > 0);
    $layout = $this->getRequestParameter('same', $this->multiple_cat? 'multiple': 'list');

    $this->forward404Unless($layout=='list' || $layout=='multiple', 'Kiểu hiển thị không hợp lệ');
    $this->setTemplate($layout);

    if ($layout == 'multiple') {
      $this->categoryItems = $this->categoryItem->items;
      $this->pagers = array();
      foreach ($this->categoryItems as $key => $categoryItem) {
        $c = new Criteria();
        $c->add(TblblogcategoryentryPeer::CE_CATEGORY, $key);
        $c->add(TblblogcategoryentryPeer::CE_STATUS, 0);
        $c->addDescendingOrderByColumn($sort_id);
        $this->pagers[$key] = new PropelPager($c, 'TblblogcategoryentryPeer', 'doSelect', 1, $this->categoryItem->getListItemCount());
      }
    } else {
      $this->page = $this->getRequestParameter('page', 1);
      $entry_id = $this->getRequestParameter('entry_id');
      if ($entry_id && $sort_date) {
        if ($tblblogentry = TblblogentryPeer::retrieveByPK($entry_id)) {
          $c2 = new Criteria();
          $c2->add(TblblogcategoryentryPeer::CE_CATEGORY, $this->cat_id);
          $c2->add(TblblogcategoryentryPeer::CE_STATUS, 0);
          $c2->add(TblblogcategoryentryPeer::CE_MODIFYDATE, $tblblogentry->getEntryModifydate(), Criteria::GREATER_THAN);
          $num = TblblogcategoryentryPeer::doCount($c2);
          $this->page = intval($num / $this->categoryItem->getDetailListItemCount()) + 1;
        }
      }
      $c = new Criteria();
      $c->add(TblblogcategoryentryPeer::CE_CATEGORY, $this->cat_id);
      $c->add(TblblogcategoryentryPeer::CE_STATUS, 0);
      $c->addDescendingOrderByColumn($sort_id);
      $this->pager = new PropelPager($c, 'TblblogcategoryentryPeer', 'doSelect', $this->page, $this->categoryItem->getDetailListItemCount());
    }
  }

  public function executeShow() {
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->entry_id);
    $this->forward404Unless($this->tblblogentry, 'Tài liệu không tồn tại');
    $this->forward404Unless($this->tblblogentry->getEntryCategory(), 'Tài liệu không hợp lệ');
    $this->forwardUnless($this->tblblogentry->getEntryStatus() < 2, 'entry', 'lostentry');
    $this->forwardUnless($this->tblblogentry->getEntryBlog() == blogStore::$blogId, 'entry', 'astray');
    $this->forwardUnless($this->tblblogentry->getModule() == $this->getModuleName(), 'entry', 'astray');
  }

  public function executeShowprint() {
    $this->setLayout(false);
    return $this->executeShow();
  }

  public function executeAstray() {
    myUtility::log($this->getRequest()->getUri(), 'astray.log');
    $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->getRequestParameter('entry_id'));
    $this->name = $this->tblblogentry->getObject()->getName();
    $this->type = commonData::getCatTypeName($this->tblblogentry->getEntryType());
  }

  public function executeLostentry() {
    myUtility::log($this->getRequest()->getUri(), 'lostentry.log');
    $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->getRequestParameter('entry_id'));
    $this->entrytitle = $this->tblblogentry->getObject()->getName();
    $this->author = $this->tblblogentry->getTbluser();
    $this->us_title = $this->author->getObject()->getTitle();
    $this->us_titlename = $this->us_title.' '.$this->author->getUsFullName();

    $this->currentUrl = $this->getRequest()->getUri();
    $this->prevUrl = $this->getRequest()->getReferer();
  }

  /**
   * Insert comment of entry with ajax calling
   */
  public function executeInsertcomment() {
    $entry_id = $this->getRequestParameter('entry_id');
    $cm_content = $this->getRequestParameter('cm_content');
    try {
      $tblblogentry = TblblogentryPeer::retrieveByPK($entry_id);
      if (!$tblblogentry) throw new Exception('Tài liệu không tồn tại');
      if (!$tblblogentry->canPostComment()) {
        if (blogStore::getBlogStyle() > 1) throw new Exception('Bạn phải là thành viên đơn vị và được xác thực thì mới được gửi ý kiến ở mục này');
        else throw new Exception('Bạn phải gia nhập làm thành viên trang web thì mới được gửi ý kiến ở mục này');
      }
      if (strlen($cm_content)<5) throw new Exception('Xin lỗi, ý kiến của bạn quá ngắn');
      if (time() - $this->getUser()->getAttribute('post', 0) < 30) throw new Exception('You cannot post 2 comment between 30 seconds');
      if (!myUtility::validate('sfFilterValidator', $cm_content, $error)) throw new Exception($error);

      $tblblogentrycomment = new Tblblogentrycomment();
      $tblblogentrycomment->setCmContent(htmlFilter::preFilter($cm_content));
      $tblblogentrycomment->setCmEntry($entry_id);
      $tblblogentrycomment->setCmUser(blogStore::$userId);
      $tblblogentrycomment->setCmBlog(blogStore::$blogId);
      $tblblogentrycomment->setCmDate(date('Y-m-d H:i:s'));
      $tblblogentrycomment->save();

      $cm_id = $tblblogentrycomment->getCmId();
      $this->getUser()->setAttribute('post', time());
    } catch (Exception $e) {
      $this->setRequestError('cm_content', $e->getMessage());
    }
    return $this->renderComponent('entry', 'listcomment', array('entry_id'=>$entry_id, 'cm_id'=>$cm_id, 'insertOk'=>isset($cm_id)));
  }

  public function executeDeletecomment() {
    $cmId = $this->getRequestParameter('cmid');
    $tblblogentrycomment = TblblogentrycommentPeer::retrieveByPK($cmId);
    $this->forward404Unless($tblblogentrycomment, 'Ý kiến này không tồn tại');
    $this->forwardUnless($tblblogentrycomment->canDelete(), 'default', 'secure');
    $entry_id = $tblblogentrycomment->getCmEntry();
    $tblblogentrycomment->delete();
    $this->redirect($this->getModuleName().'/show?entry_id='.$entry_id);
  }

  /**
   * Create, edit, update and delete entry
   */
  public function executeCreate() {
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->tblblogentry = new Tblblogentry();
    $this->setTemplate('edit');
  }

  public function executeEdit() {
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->entry_id);
    $this->forward404Unless($this->tblblogentry, 'Bài viết không tồn tại');
    $this->forwardUnless($this->tblblogentry->canEditEntry(), 'default', 'secure');
    $this->cat_id = $this->tblblogentry->getEntryCategory();
    $this->tblblogentry->setEntryContent(htmlFilter::filterText($this->tblblogentry->getEntryContent(), ''));
  }

  public function handleErrorUpdate() {
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->tblblogentry = new Tblblogentry();
    $this->tblblogentry->setEntryTitle($this->getRequestParameter('entry_title'));
    $this->tblblogentry->setEntryContent($this->getRequestParameter('entry_content'));
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->setTemplate('edit');
    return sfView::SUCCESS;
  }

  public function executeUpdate() {
    $entry_id = $this->getRequestParameter('entry_id');
    $title = $this->getRequestParameter('entry_title');
    $content = $this->getRequestParameter('entry_content');
    $cat_id = $this->getRequestParameter('cat_id');

    if ($entry_id == null) {
      $tblblogentry = new Tblblogentry();
      $tblblogentry->setEntryCategory($cat_id);
      $tblblogentry->setEntryUser(blogStore::$userId);
      $tblblogentry->setEntryBlog(blogStore::$blogId);
      $tblblogentry->setEntryCreatedate(date("Y-m-d H:i:s"));
      $tblblogentry->setEntryModifydate(date("Y-m-d H:i:s"));
    } else {
      $tblblogentry = TblblogentryPeer::retrieveByPK($entry_id);
      $this->forward404Unless($tblblogentry, 'Bài viết không tồn tại');
      $this->forwardUnless($tblblogentry->canEditEntry(), 'default', 'secure');
      if ($tblblogentry->getEntryUser() == blogStore::$userId) $tblblogentry->setEntryModifydate(date("Y-m-d H:i:s"));
    }
    $tblblogentry->setEntryTitle(myUtility::htmlToText($title));
    $tblblogentry->setEntryContent(htmlFilter::preFilter($content));
    $tblblogentry->save();

    $tblblogentry->getObject()->createThumbnail(true);
    $this->redirect('/entry/show?entry_id='.$tblblogentry->getEntryId());
  }

  public function executeDelete() {
    $tblblogentry = TblblogentryPeer::retrieveByPk($this->getRequestParameter('entry_id'));
    $this->forward404Unless($tblblogentry, 'Bài viết không tồn tại');
    $this->forwardUnless($tblblogentry->canDeleteEntry(), 'default', 'secure');
    $tblblogentry->setEntryStatus(2);
    $tblblogentry->save();
    $this->redirect($tblblogentry->getListUrl());
  }

  /**
   * Approve (for category moderators) and complain (for all users)
   */
  public function executeCheck() {
    $entry_id = $this->getRequestParameter('entry_id');
    $this->tblblogentry = TblblogentryPeer::retrieveByPK($entry_id);
    $this->forward404Unless($this->tblblogentry, 'Tài liệu không tồn tại');
    $this->forwardUnless($this->tblblogentry->canMod(), 'default', 'secure');
    $this->forward404If($this->tblblogentry->getEntryInvalid(), 'Tài liệu đã được xét duyệt');

    $status = $this->getRequestParameter('status');
    if ($status == 1) {
      $this->tblblogentry->setEntryStatus($status);
      $this->tblblogentry->save();
      $this->redirect($this->getRequest()->getReferer());
    }
    if ($status == 2) {
      $content = $this->getRequestParameter('content');
      $other = $this->getRequestParameter('othercontent');
      if (count($content) == 0 && $other == '') return $this->setRequestError('reason', 'Hãy điền lý do không duyệt');
      $str = '<ul>';
      foreach ($content as $c) $str .= '<li>'.$c.'</li>';
      if ($other != '') $str .= '<li>'.$other.'</li>';
      $str .= '</ul>';
      $this->tblblogentry->addEntryInvalid($str);
      $this->tblblogentry->setEntryStatus($status);
      $this->tblblogentry->save();
      return $this->renderModalbox('Bạn đã kiểm duyệt thành công', $this->tblblogentry->getListUrl());
    }
  }

  public function executeComplain() {
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->tblblogentry = TblblogentryPeer::retrieveByPK($this->entry_id);
    $this->forward404Unless($this->tblblogentry && $this->tblblogentry->getEntryStatus() < 2, 'Tài liệu không tồn tại hoặc đã bị xóa');

    if ($this->getRequestParameter('submit')) {
      $tblcomplain = new Tblcomplain();
      $tblcomplain->setCpUser(blogStore::$userId);
      $tblcomplain->setCpNote($this->getRequestParameter('cp_note'));
      $tblcomplain->setCpType($this->getRequestParameter('cp_type'));
      $tblcomplain->setCpEntry($this->entry_id);
      $tblcomplain->setCpBlog(blogStore::$blogId);
      $tblcomplain->setCpCategory(blogStore::$catTree->getCatItem($this->tblblogentry->getEntryCategory())->base);
      $tblcomplain->setCpDate(date("Y-m-d H:i:s"));
      $tblcomplain->save();
      return $this->renderModalbox('Bạn đã gửi thông báo thành công');
    }
  }

  public function handleErrorComplain() {
    $this->cp_note = $this->getRequestParameter('cp_note');
    $this->cp_type = $this->getRequestParameter('cp_type');
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->tblblogentry = TblblogentryPeer::retrieveByPK($this->entry_id);
    if (!$this->getRequestParameter('submit')) $this->getRequest()->removeAllError();
    return sfView::SUCCESS;
  }

  /**
   * Show entry from global entry_id, pr_id or doc_id
   */
  public function executeShowglobal() {
    if ($entry_id = $this->getRequestParameter('entry_id')) {
      $tblblogentry = TblblogentryPeer::retrieveByPK($entry_id);
    } else {
      $app_modules = sfConfig::get('app_resource_module');
      if ($link = $this->getRequestParameter('pr_id')) $type = 'present';
      else if ($link = $this->getRequestParameter('doc_id')) $type = 'document';
      $c = new Criteria();
      $c->add(TblblogentryPeer::ENTRY_LINK, $link);
      $c->add(TblblogentryPeer::ENTRY_TYPE, $app_modules[$type], Criteria::IN);
      $c->add(TblblogentryPeer::ENTRY_STATUS, 2, Criteria::LESS_THAN);
      if ($blog_id = $this->getRequestParameter('blog_id')) $c->add(TblblogentryPeer::ENTRY_BLOG, $blog_id);
      $tblblogentry = TblblogentryPeer::doSelectOne($c);
    }
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    $this->forward404Unless($tblblogentry->getEntryStatus() < 2, 'Tài liệu đã bị xóa');

    if ($tblblogentry->getEntryBlog() == blogStore::$blogId)
      $baseUrl = $this->getController()->genUrl('/', true);
    else {
      $tblblog = TblblogPeer::retrieveByPK($tblblogentry->getEntryBlog());
      $this->forward404Unless($tblblog, 'Không tìm thấy trang riêng chứa tài liệu');
      $baseUrl = $tblblog->getRootUrl();
    }
    $cm_id = $this->getRequestParameter('cm_id');
    $this->redirect($baseUrl.$tblblogentry->getModule().'/show/entry_id/'.$tblblogentry->getEntryId().($cm_id? "/cm_id/$cm_id#$cm_id": ''));
  }

  public function executeSort() {
    $this->getUser()->setUserSort($this->getRequestParameter('type'));
    $this->redirect($this->getRequest()->getReferer());
  }

  public function executeSelectfolder() {
    return $this->renderComponent('entry', 'selectfolder');
  }

  /**
   * Like and unlike function
   */
  public function executeShowlike() {
    $showAllLike = $this->getRequestParameter('all');
    $entry_id = $this->getRequestParameter('entry_id');
    $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    return $this->renderComponent('entry', 'showlike', array('tblblogentry'=>$tblblogentry, 'showAllLike'=>$showAllLike));
  }

  public function executeUpdatelike() {
    $entry_id = $this->getRequestParameter('entry');
    $user_id = $this->getRequestParameter('user');
    $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    $this->forward404Unless($user_id == blogStore::$userId, 'Tài khoản không hợp lệ');

    $like = $this->getRequestParameter('like');
    if ($like == 1) $tblblogentry->addLikeUser($user_id);
    else $tblblogentry->removeLikeUser($user_id);
    return $this->renderComponent('entry', 'showlike', array('tblblogentry'=>$tblblogentry));
  }
}
