<?php

class spaceActions extends sfActions
{
  private function CreateSpaceDir($folderName, $parentId, $userId) {
    $c = new Criteria();
    $c->add(TblspacecategoryPeer::CAT_PARENT, $parentId);
    $c->add(TblspacecategoryPeer::CAT_USER, $userId);
    $c->add(TblspacecategoryPeer::CAT_NAME, $folderName);
    $category = TblspacecategoryPeer::doSelectOne($c);
    if ($category == null) {
      $category = new Tblspacecategory();
      $category->setCatName($folderName);
      $category->setCatParent($parentId);
      $category->setCatUser($userId);
      $category->setCatDate(date('Y-m-d H:i:s'));
      $category->save();
    }
    return $category->getCatId();
  }

  private function CreateSpaceFile($file, $fileName, $fileSize, $catId, $userId) {
    $tblres = new Tblspaceresource();
    $tblres->setResFilename($fileName);
    $tblres->setResFilesize($fileSize);
    $tblres->setResFilecrc(crc32(file_get_contents($file)));
    $tblres->save();
    $tblfile = new Tblspacefile();
    $tblfile->setFileResource($tblres->getResId());
    $tblfile->setFileCategory($catId);
    $tblfile->setFileUser($userId);
    $tblfile->setFileName($fileName);
    $tblfile->setFileDate(date('Y-m-d H:i:s'));
    $tblfile->save();

    $type = $tblfile->getFileType();
    $filePath = $tblres->getFullFilename();
    if (in_array($type, array('avi', 'mpg', 'mpeg', 'mpe', 'mpa', 'wmv', 'asf', 'mov', 'qt', '3gp'))) {
      $flvName = myUtility::getFileName($filePath).'.flv';
      sfConversion::MovieToFlv($filePath, $flvName);
    }
    if (in_array($type, array('bmp', 'ico', 'wmf', 'emf'))) {
      $jpgName = myUtility::getFileName($filePath).'.jpg';
      sfConversion::ImageToJpg($filePath, $jpgName);
    }
  }

  private function MoveDirToSpace($path, $catId, $userId) {
    foreach (scandir($path) as $dir) {
      if ($dir=='.' || $dir=='..') continue;
      $dname = $path.'/'.$dir;
      if (is_dir($dname)) {
        $subCatId = $this->CreateSpaceDir($dir, $catId, $userId);
        $this->MoveDirToSpace($dname, $subCatId, $userId);
      } else {
        $this->CreateSpaceFile($dname, $dir, filesize($dname), $catId, $userId);
      }
    }
    rmdir($path);
  }

  public function executeDir() {
    $this->catId = $this->getRequestParameter('id', -1);
    $userId = $this->getRequestParameter('userid');
    $filter = $this->getRequestParameter('filter');
    
    // find parent ID of this category
    if ($this->catId != -1) {
      $c = new Criteria();
      $c->add(TblspacecategoryPeer::CAT_ID, $this->catId);
      $c->add(TblspacecategoryPeer::CAT_USER, $userId);
      $thisCat = TblspacecategoryPeer::doSelectOne($c);
      $this->parentId = $thisCat? $thisCat->getCatParent(): '-1';
    }
    else $this->parentId = '';

    // find subcategory of this category
    $c = new Criteria();
    $c->add(TblspacecategoryPeer::CAT_PARENT, $this->catId);
    $c->add(TblspacecategoryPeer::CAT_USER, $userId);
    $c->addAscendingOrderByColumn(TblspacecategoryPeer::CAT_NAME);
    $this->tblcategories = TblspacecategoryPeer::doSelect($c);

    // find files in this category folder
    $c = new Criteria();
    $c->add(TblspacefilePeer::FILE_CATEGORY, $this->catId);
    $c->add(TblspacefilePeer::FILE_USER, $userId);
    if ($filter) $c->add(TblspacefilePeer::FILE_TYPE, explode(';', $filter), Criteria::IN);
    $c->addAscendingOrderByColumn(TblspacefilePeer::FILE_NAME);
    $this->tblfiles = TblspacefilePeer::doSelect($c);
    
    $this->errMsg = '';
    $this->errCode = '';
  }
  
  public function executeMkdir() {
    $userId = $this->getRequestParameter('userid');
    $parentId = $this->getRequestParameter('parent_id');
    $folderName = $this->getRequestParameter('name');
    $this->catId = $this->CreateSpaceDir($folderName, $parentId, $userId);
    $this->errCode = '';
    $this->errMsg = '';
  }

  public function executeDelete() {
    //if (!$this->checkAuthentication()) return sfView::NONE;
    $userId = $this->getRequestParameter('userid');
    $type = $this->getRequestParameter('type');
    $id = $this->getRequestParameter('id');

    switch ($type) {
      case 'folder': 
        $c1 = new Criteria();
        $c2 = new Criteria();
        $c1->add(TblspacecategoryPeer::CAT_USER, $userId);
        $c1->add(TblspacecategoryPeer::CAT_PARENT, $id);
        $c2->add(TblspacefilePeer::FILE_USER, $userId);
        $c2->add(TblspacefilePeer::FILE_CATEGORY, $id);
        if (TblspacecategoryPeer::doCount($c1) > 0 || TblspacefilePeer::doCount($c2) > 0) {
          $this->errMsg = 'Folder is not empty!';
          $this->errCode = 'errFolderNotEmpty';
          return;
        }
        $c = new Criteria();
        $c->add(TblspacecategoryPeer::CAT_ID, $id);
        $c->add(TblspacecategoryPeer::CAT_USER, $userId);
        TblspacecategoryPeer::doDelete($c);
        break;

      case 'file':
        $c = new Criteria();
        $c->add(TblspacefilePeer::FILE_ID, $id);
        $c->add(TblspacefilePeer::FILE_USER, $userId);
        $tblfile = TblspacefilePeer::doSelectOne($c);
        if ($tblfile) $tblfile->delete();
        break;
    }
    $this->errMsg = '';
    $this->errCode = '';
  }

  public function executeUpload() {
	
    //if (!$this->checkAuthentication()) return sfView::NONE;
    $userId = $this->getRequestParameter('userid');
    $catId = $this->getRequestParameter('dir');

    if ($this->getRequest()->hasErrors()) return false;
    if (!$this->getRequest()->hasFiles()) return true;
	
    $file = reset($this->getRequest()->getFileNames());
    $fileName = $this->getRequest()->getFileName($file);
    $fileType = $this->getRequest()->getFileType($file);
    $fileSize = $this->getRequest()->getFileSize($file);
    $fileError = $this->getRequest()->hasFileError($file);
    $fileErrorNum = $this->getRequest()->getFileError($file);

    if ($fileErrorNum || $fileError) return false;

    $tempFile = violetUtil::getTempPath().$userId.'_'.$fileName;
		
    $this->getRequest()->moveFile($file, $tempFile);

	if ($this->getRequestParameter('unpack') == 'true') {
      $tempPath = violetUtil::getTempPath($userId.'_'.date("YmdHis"), true);
      myZip::Unzip($tempFile, $tempPath);
      $this->MoveDirToSpace($tempPath, $catId, $userId);
      unlink($tempFile);
    } else {
      $this->CreateSpaceFile($tempFile, $fileName, $fileSize, $catId, $userId);
    }

    return sfView::NONE;
  }

  public function executeSave() {
    $content = file_get_contents('php://input');
    if ($content == '') {
      $this->errMsg = 'Error when saving file';
      $this->errCode = 'errSave6'; // khong tim thay noi dung bai giang
      return;
    }
    $this->fileId = $this->getRequestParameter('fileid', '');
    if ($this->fileId == '') {
      $userId = $this->getRequestParameter('userid');
      $fileName = $this->getRequestParameter('name');
      $catId = $this->getRequestParameter('dir', -1);

      $tblres = new Tblspaceresource();
      $tblres->setResFilename($fileName);
      $tblres->setResFilesize(strlen($content));
      $tblres->setResFilecrc(crc32($content));
      $tblres->save();
      file_put_contents($tblres->getFullFilename(true), $content);

      $tblfile = new Tblspacefile();
      $tblfile->setFileResource($tblres->getResId());
      $tblfile->setFileCategory($catId);
      $tblfile->setFileUser($userId);
      $tblfile->setFileName($fileName);
      $tblfile->setFileDate(date('Y-m-d H:i:s'));
      $tblfile->save();
      $this->fileId = $tblfile->getFileId();
    } else {
      $tblfile = TblspacefilePeer::retrieveByPk($this->fileId);
      $tblfile->setFileDate(date('Y-m-d H:i:s'));
      $tblfile->save();

      $tblres = $tblfile->getTblspaceresource();
      $tblres->setResFilesize(strlen($content));
      $tblres->setResFilecrc(crc32($content));
      $tblres->save();
      file_put_contents($tblres->getFullFilename(), $content);
    }
	
    $this->fileName = $fileName;
    $this->errCode = '';
    $this->errMsg = '';
  }

  public function executeFile() {
    $fileId = $this->getRequestParameter('id');
    $tblres = TblspacefilePeer::retrieveByPk($fileId)->getTblspaceresource();
    $fileName = $tblres->getFullFilename();
    $ext = strtolower(substr($fileName, strrpos($fileName, '.') + 1));

    $userFileName = $this->getRequestParameter('filename');
    if ($userFileName != null) {
      $userExt = strtolower(substr($userFileName, strrpos($userFileName, '.') + 1));

      fwrite ($fh, var_export($userExt, TRUE));

      if ($userExt != $ext) {
        $fileName = substr($fileName, 0, strrpos($fileName, '.')) . ".$userExt";
        $ext = $userExt;
      }
    }

	header('Content-Type: '.violetUtil::getContentType($ext));
    header('Content-Length: '.filesize($fileName));
    fpassthru(fopen($fileName, 'rb'));
    return sfView::NONE;
  }
}
?>