<?php

include_once('apps/blog/modules/entry/actions/actions.class.php');

class documentActions extends entryActions
{
  public function executeShow() {
    parent::executeShow();
    $this->tbldocument = $this->tblblogentry->getTbldocument();
    $this->forward404Unless($this->tbldocument, 'Tài liệu gốc không tồn tại');
  }

  public function executeSame() {
    $this->forwardIf($this->getRequest()->getMethod() == sfRequest::GET, 'document', 'show');
    $this->executeShow();
    return $this->renderComponent('document', 'same', array('tblblogentry'=>$this->tblblogentry));
  }

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

  public function executeCreate() {
    $this->tbldocument = new Tbldocument();
    $this->createMethod = $this->getRequestParameter('createMethod', 'direct');
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->setTemplate('edit');
  }

  public function executeEdit() {
    $this->entry_id = $this->getRequestParameter('entry_id');
    $tblblogentry = TblblogentryPeer::retrieveByPk($this->entry_id);
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    $this->forwardUnless($tblblogentry->canEditEntry(), 'default', 'secure');
    $this->cat_id = $tblblogentry->getEntryCategory();
    $this->tbldocument = $tblblogentry->getTbldocument();
    $this->createMethod = 'direct';
  }

  public function executeInsert() {
    $doc_id = $this->getRequestParameter('doc_id');
    $cat_id = $this->getRequestParameter('cat_id');
    $tblblogentry = TblblogentryPeer::insertSource($cat_id, $doc_id);
    if ($tblblogentry == null) {
      $this->getRequest()->setError('selection', 'Tư liệu bạn vừa chọn đã có trong trang riêng này rồi');
      $this->forward('document', 'create');
    }
    $this->redirect('/document/show?entry_id='.$tblblogentry->getEntryId());
  }

  public function executePaste() {
    $url = $this->getRequestParameter('entry_link', '');
    $cat_id = $this->getRequestParameter('cat_id');
    $catItem = blogStore::$catTree->getCatItem($cat_id);

    try {
      $match = preg_match('@/document/show[/\?]entry_id[/=](\d+)@', $url, $value);
      if (!$match) throw new Exception('Hãy copy từ một trang riêng violet.vn bất kỳ và paste vào đây');
      $tblblogentry = TblblogentryPeer::retrieveByPK($value[1]);
      if ($tblblogentry == null) throw new Exception('Tư liệu này không tồn tại');
      if ($tblblogentry->getEntryType() != 1) throw new Exception('Bạn phải chọn link của một tư liệu tranh ảnh phim');
      $tblblogentry = TblblogentryPeer::insertSource($cat_id, $tblblogentry->getEntryLink());
      if ($tblblogentry == null) throw new Exception('Tư liệu đã có trong trang riêng này rồi');
      $this->redirect('/document/show?entry_id='.$tblblogentry->getEntryId());
    }
    catch (Exception $e) {
      $this->getRequest()->setError('entry_link', $e->getMessage());
      $this->forward('document', 'create');
    }
  }

  /**
   * Display predelete screen
   */
  public function executePredelete() {
    $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->getRequestParameter('entry_id'));
    $this->forward404Unless($this->tblblogentry, 'Tài liệu không tồn tại');
    $this->forwardUnless($this->tblblogentry->canDeleteEntry(), 'default', 'secure');

    if ($this->tblblogentry->canDeleteAll()) {
      $sql = 'select distinct entry_blog, (select bl_shortname from tblblog where bl_id=entry_blog)'.
      ' from tblblogentry where entry_link='.$this->tblblogentry->getEntryLink().
      ' and entry_status<2 and entry_type=1';
      $this->tblblogs = myUtility::execSql($sql);
    }
  }

  /**
   * Delete entry (set status to 2)
   */
  public function executeDelete() {
    $all = $this->getRequestParameter('all');
    $tblblogentry = TblblogentryPeer::retrieveByPk($this->getRequestParameter('entry_id'));
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    $this->forwardUnless($tblblogentry->canDeleteEntry() && ($tblblogentry->canDeleteAll() || $all != 1), 'default', 'secure');
    $tblblogentry->deleteByUser($all == 1);
    return $this->renderModalbox('Đã xóa tư liệu thành công', $tblblogentry->getListUrl());
  }

  /**
   * Download document
   */
  public function executeDownload()
  {
    $doc_id = $this->getRequestParameter('doc_id');
    $document = TbldocumentPeer::retrieveByPk($doc_id);
    $this->forward404Unless($document, 'Tài liệu không tồn tại');
    $tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);
    userStatistics::recordDownloadDocument($tbluser, $document);

    $file_name = myUtility::vietDecode($document->getDocName());
    $file_name = preg_replace('@[^A-Za-z0-9 ]+@', '', $file_name);
    $file_path = $document->getObject()->getFullFileName(false);
    $code = 'dl'.abs(crc32($doc_id.'@'.$file_path));
    $_SESSION[$code] = 1;
    session_commit();

    $this->redirect(sfConfig::get('app_resource_root').'download.php?id='.$doc_id.
      '&path='.urlencode($file_path).
      '&file='.urlencode($file_name).
      '&user='.blogStore::$userId);
  }

  public function handleErrorUpdate() {
    if ($this->getRequestParameter('entry_id')) $this->executeEdit();
    else $this->executeCreate();
    $this->tbldocument->setDocName($this->getRequestParameter('doc_name'));
    $this->tbldocument->setDocSource($this->getRequestParameter('doc_source'));
    $this->tbldocument->setDocDesc($this->getRequestParameter('doc_desc'));
    $this->setTemplate('edit');
    return sfView::SUCCESS;
  }

  /**
   * Create new, update or change information of document
   */
  public function executeUpdate()
  {
    if ($this->getRequest()->getMethod() != sfRequest::POST) $this->forward404();
    $this->createMethod = $this->getRequestParameter('createMethod', 'direct');
    $this->setTemplate('edit');

    myUtility::log("Execute update document ".$this->getRequestParameter('doc_name'), "uploads.log", "\n");
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->created = ($this->entry_id == null);
    $this->cat_id = $this->getRequestParameter('cat_id');

    if ($this->created) {
      $this->tbldocument = new Tbldocument();
    } else {
      $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->entry_id);
      $this->tbldocument = $this->tblblogentry->getTbldocument();
      $this->forward404Unless($this->tbldocument, 'Tài liệu không tồn tại');
      $this->forwardUnless($this->tblblogentry->canEditEntry(), 'default', 'secure');
    }
    $this->tbldocument->setDocName(myUtility::htmlToText($this->getRequestParameter('doc_name')));
    $this->tbldocument->setDocSource(myUtility::htmlToText($this->getRequestParameter('doc_source')));
    $this->tbldocument->setDocDesc($this->getRequestParameter('doc_desc'));
    $this->tbldocument->setDocCategory(blogStore::$catTree->getCatItem($this->cat_id)->base);
    if ($this->tbldocument->getDocUser() == null) $this->tbldocument->setDocUser(blogStore::$userId);
    if ($this->tbldocument->getDocUser() == blogStore::$userId) $this->tbldocument->setDocDate(date('Y-m-d H:i:s'));

    try {
      if ($this->getRequest()->GetFileFromRequest(!$this->created, $this)) {
        $docObj = new docBase($this->tbldocument);
        $docObj->onUpload($this);
      }
    } catch (Exception $e) {
      myUtility::log(myUtility::mb_truncate_text($e->getMessage(), 60), "uploads.log");
      $this->getRequest()->setError('doc_filename', $e->getMessage());
      return sfView::SUCCESS;
    }

    try {
      $this->UpdateDocDatabase();
    } catch (Exception $e) {
      Propel::close();
      $this->UpdateDocDatabase(' (retry)');
    }
    $this->redirect('/document/show?entry_id='.$this->tblblogentry->getEntryId() );
  }

  /**
   * Update document into following tables:
   * tbldocument, tblblogentry, tblblogcategoryentry, tbluser
   */
  public function UpdateDocDatabase($try = '') {
    myUtility::log("Update database$try", "uploads.log");
    $this->tbldocument->save();
    if ($this->created) {
      $this->tblblogentry = TblblogentryPeer::insertSource($this->cat_id, $this->tbldocument->getDocId(), $this->tbldocument->getDocStatus());
    } else {
      $this->tblblogentry->setEntryCategory($this->cat_id);
      $this->tblblogentry->save();
    }
    $this->tbldocument->getTbluser()->incUpload();
    myUtility::log("Finish update document", "uploads.log");
  }

  /**
   * Create manual thumbnail for flv document
   *
   * @return unknown
   */
  public function executeFlvthumb()
  {
    $docId = $this->getRequestParameter('docId');
    $time = $this->getRequestParameter('time', 0);
    $time = urldecode($time);
    if ($docId!=null) {
      $tbldocument = TbldocumentPeer::retrieveByPK($docId);
      $tbldocument->updateBlogCategoryEntryPath(null);
      $fileName = $tbldocument->getObject()->getFullFileName();
      $thumbFileName = $tbldocument->getObject()->getThumbFileName();

      if (sfConversion::FlvToThumbnail($fileName, $thumbFileName, $time)) {
        myUtility::track_upload($thumbFileName, 'thumbnails');
        $tbldocument->setDocThumbnail(1);
        $tbldocument->save();
      } else {
        $tbldocument->setDocThumbnail(2);
        $tbldocument->save();
      }
    }
    return sfView::NONE;
  }

  /**
   * Create manual thumbnail for swf document
   *
   * @return unknown
   */
  public function executeSwfthumb()
  {
    $docId = $this->getRequestParameter('docId');
    $s = $_REQUEST["dulieu"];
    $tbldocument = TbldocumentPeer::retrieveByPK($docId);

    if ($docId && $s && $tbldocument)
    {
      $thumbnail = ImageCreateTrueColor(150, 100);
      for ($x=0; $x<150; $x++) {
        for ($y=0; $y<100; $y++) {
          $t = ($x + $y*150)*6;
          $hex = substr($s, $t, 6);
          imagesetpixel($thumbnail, $x, $y, hexdec($hex) );
        }
      }
      $thumbFileName = $tbldocument->getObject()->getThumbFileName();
      imagejpeg($thumbnail, $thumbFileName, 70);
      myUtility::track_upload($thumbFileName, 'thumbnails');
      $tbldocument->updateBlogCategoryEntryPath(null);
      $tbldocument->setDocThumbnail(1);
      $tbldocument->save();
    }
    return sfView::NONE;
  }
}
