<?php
class presentBase extends resourceBase {

  public $present;

  public function presentBase(Tblpresentation $pre) {
    parent::resourceBase();
    $this->present = $pre;
  }

  public function getPath($absolute = true, $data_dir = 'resources') {
    $pr_cat = $this->present->getPrCategory();
    $pr_id = $this->present->getPrId();
    if ($absolute) return sfConfig::get('sf_upload_dir')."/$data_dir/$pr_cat/$pr_id/";
    else return '/'.sfConfig::get('sf_upload_dir_name')."/$data_dir/$pr_cat/$pr_id/";
  }

  public function getFullFileName($absolute = false) {
    return $this->getPath($absolute).$this->present->getPrFilename();
  }

  public function getViewPath($realpath = true) {
    return ($realpath? '': $this->viewRoot) . $this->getPath($realpath, $this->viewdir);
  }

  public function getThumbPath($realpath = true) {
    return ($realpath? '': $this->thumbRoot) . $this->getPath($realpath, $this->thumbdir);
  }

  public function getThumbFileName($absolute = true) {
    $path = $this->getThumbPath($absolute);
    if ($absolute && !file_exists($path)) {umask(0); mkdir($path, 0777, true);}
    return $path.'thumbnail.jpg';
  }

  public function getThumbnail($options = null) {
    return image_tag($this->getThumbFileName(false), $options);
  }

  public function getGlobalThumb($type = 'thumb') {
    return $this->getHtmlThumb('/entry/showglobal?pr_id='.$this->present->getPrId(), $type);
  }

  public function onUpload($action)
  {
    // Check file extension and duplicate uploading
    $fileName = $action->fileName;
    $ext = myUtility::getFileExt($fileName);
    $catItem = blogStore::$catTree->getCatItem($action->cat_id);
    $allowExts = $catItem->getAllowExts();
    $zipExts = sfConfig::get('app_zip_extensions');
    if (!in_array($ext, $allowExts) && !in_array($ext, $zipExts)) {
      $action->getRequest()->setError('filetype', true);
      throw new Exception('Chỉ đưa lên được các file: '.strtoupper(join(', ', $allowExts)).' và các file nén');
    }

    $fileSize = $action->fileSize;
    if ($action->created) $this->checkDuplicate($fileName, $fileSize);
    $tempFile = $action->getRequest()->CopyTempFile($action->uploaded, $this->present->getPrDate().'_'.$fileName);

    // Get playername and type (include zip file) and update database
    if (!in_array($ext, $zipExts)) $playerName = $fileName;
    else {
      $allowExts = $catItem->getAllowExts(true);
      $playerName = myZip::ListFile($tempFile)->findFirstFile($allowExts);
      if ($playerName == '') {
        unlink($tempFile);
        $action->getRequest()->setError('filetype', true);
        throw new Exception('File nén phải có chứa <b>'.strtoupper(join(', ', $allowExts)).'</b>');
      }
    }
    $type = $this->getPresentType($playerName);
    $this->present->setPrFileName($fileName);
    $this->present->setPrFileSize($fileSize);
    $this->present->setPrPlayerName($playerName);
    $this->present->setPrType($type);
    $this->present->setPrStatus(5);
    $this->present->save();

    // Copy temp file to resource directory (on remote server)
    myUtility::log("Copy to resource $fileName ".$this->present->getPrId(), "uploads.log");
    $path = $this->getPath();
    if (!file_exists($path)) {
       umask(0000);
       if (!mkdir($path, 0777, true)) {
          myUtility::log("Can not create directory $path", "uploads.log");
          $this->present->setPrContent("Can not create directory");
          return;
       }
    }
    copy($tempFile, $path . $fileName);
    myUtility::track_upload($path . $fileName, 'resources');

    // Private process, update status and delete temp file
    $this->present->setPrStatus(3);
    $this->present->getObject()->onPrivateUpload($tempFile);
    $this->present->updateBlogCategoryEntryPath(null);
    unlink($tempFile);
  }

  public function onPrivateUpload($tempFile) {
  }

  public function onThumbUpload($thumbSrc) {
    // Move directory before create new thumbnail
    if ($this->present->isColumnModified(TblpresentationPeer::PR_CATEGORY)) $this->present->save();

    $thumb = $this->getThumbFileName();
    if (sfConversion::SizeImage(150, 100, $thumbSrc, $thumb)) {
      myUtility::track_upload($thumb, 'thumbnails');
      $this->present->setPrThumbnail(1);
      $this->present->updateBlogCategoryEntryPath(null);
    }
  }

  /**
   * Check duplicated uploading from file size and file name
   */
  private function checkDuplicate($fileName, $fileSize) {
    $c = new Criteria();
    $c->add(TblpresentationPeer::PR_USER, blogStore::$userId);
    $c->add(TblpresentationPeer::PR_STATUS, array(0, 1, 3, 50), Criteria::IN);
    $c->add(TblpresentationPeer::PR_DATE, date('Y-m-d H:i:s', time()-86400), Criteria::GREATER_THAN);
    $c->addDescendingOrderByColumn(TblpresentationPeer::PR_DATE);
    $c->setLimit(10);
    $tblpresentations = TblpresentationPeer::doSelect($c);
    $equal_size = 0;
    foreach ($tblpresentations as $pr)
      if ($pr->getPrFileSize() == $fileSize)
        if ($pr->getPrFilename() == $fileName || ++$equal_size >= 3)
          throw new Exception(
          'Bạn đã đưa tài liệu này lên hệ thống<br/>'.
          'Nếu bạn muốn đưa 1 tài liệu lên nhiều blog, hãy sử dụng chức năng "Đưa từ bài giảng của tôi"<br/>'.
          'Nếu bài của bạn chưa được cập nhật, vui lòng liên hệ trợ giúp trực tuyến');
  }

  /**
   * Get presentation type from player file name
   */
  private function getPresentType($fileName) {
    $ext = myUtility::getFileExt($fileName);
    if ($ext == 'pps') return 'ppt';
    if ($ext == 'ppsx') return 'pptx';
    if ($ext == 'rtf') return 'doc';
    if (preg_match('@(ims|breeze\-)manifest\.xml$@', $fileName)) return 'sco';
    return $ext;
  }

  public function getDownloadLink($icon = false) {
    $title = 'Nhấn vào đây để tải về';
    $link = '/present/predownload?pr_id='.$this->present->getPrId();
    if ($icon) return mm_link_need_login(image_tag('/images/layout1/download.png'), $link, true, array('title'=>$title));
    else return mm_link_need_login($title, $link, true);
  }

  public function getName() {
    return $this->present->getPrName();
  }

  public function getStatus() {
    return $this->present->getPrStatus();
  }

  public function getModifydate() {
    return $this->present->getPrDate();
  }

  public function getUser() {
    return $this->present->getPrUser();
  }

  public function getFileType() {
    return $this->present->getPrType();
  }
}
?>
