<?php

/**
 * space actions.
 *
 * @package    violetspace
 * @subpackage space
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class spaceActions extends sfActions
{
  /**
   * Executes index action
   *
   */
  public function executeIndex()
  {
    $this->forward('default', 'module');
  }
  
   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) {
    	$folderName = 'Copy of '.$folderName;
    }
    
    $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();
    rename($file, $tblres->getFullFilename(true));

    $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';
      myUtility::MovieToFlv($filePath, $flvName);
    }
    if (in_array($type, array('bmp', 'ico', 'wmf', 'emf'))) {
      $jpgName = myUtility::getFileName($filePath).'.jpg';
      myUtility::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);
  }

  private function CopySpaceDir ($sourceObj, $destination, $userId, &$aryNewTree) {
    $dirId = $sourceObj->id;
    $c = new Criteria();
    $c->add(TblspacecategoryPeer::CAT_ID, $dirId);
    $c->add(TblspacecategoryPeer::CAT_USER, $userId);
    $currentDir = TblspacecategoryPeer::doSelectOne($c);
	
    $newDirID =  $this->CreateSpaceDir($currentDir->getCatName(), $destination, $userId);
    
    $c = new Criteria();
    $c->add(TblspacecategoryPeer::CAT_ID, $newDirID);
    $c->add(TblspacecategoryPeer::CAT_USER, $userId);
    $newCat = TblspacecategoryPeer::doSelectOne($c);
    
    $newDir = new stdClass();
    $newDir->id = $newDirID;
    $newDir->name = $newCat->getCatName();
    $newDir->parentID = $newCat->getCatParent();
    
    $aryNewTree['DIRECTORIES'][] = $newDir;

    if (isset($sourceObj->files)) {
      $aryChidlFiles = $sourceObj->files;
      foreach ($aryChidlFiles as $key => $file) {
        $aryNewTree['FILES'][] = $this->CopySpaceFile($file->id, $newDirID, $userId);
      }
    }

    if (isset($sourceObj->childs)) {
      $aryChidlDirs = $sourceObj->childs;
      foreach ($aryChidlDirs as $key => $dir) {
        $this->CopySpaceDir($dir, $newDirID, $userId, $aryNewTree);
      }
    }
  }

  private function CopySpaceFile ($fileId, $destination, $userId) {
  	$newFile = new stdClass();
    $c = new Criteria();
    $c->add(TblspacefilePeer::FILE_ID, $fileId);
    $c->add(TblspacefilePeer::FILE_USER, $userId);
    $currentFile = TblspacefilePeer::doSelectOne($c);
    $fileName = $currentFile->getFileCategory() == $destination ? 'Copy of '.$currentFile->getFileName():$currentFile->getFileName();    
      
    $tblfile = new Tblspacefile();
    $tblfile->setFileResource($currentFile->getFileResource());
    $tblfile->setFileCategory($destination);
    $tblfile->setFileUser($userId);
    $tblfile->setFileName($fileName);
    $tblfile->setFileType($currentFile->getFileType());
    $tblfile->setFileDate(date('Y-m-d H:i:s'));
    $tblfile->save();
    $newFile->id = $tblfile->getFileId();
    $newFile->name = $fileName;
    $newFile->parentID = $destination;
    $newFile->minetype = $currentFile->getFileType();
    return $newFile;
  }
  
  private function changeParentDir ($item, $destination) {
  	if ($item->type == 'directory') {
  		$tblfile = TblspacefilePeer::retrieveByPk($item->id);
  		$tblfile->setFileCategory($destination);
  		$tblfile->save();
  	}
  	else if ($item->type == 'file') {
  		$tblCategory = TblspacecategoryPeer::retrieveByPk($item->id);
  		$tblCategory->setCatParent($destination);
  		$tblCategory->save();
  	}
  	
  	$item->parentID = $destination;
  	return $item;
  }

  public function executeDir() {
  	$this->catId = $this->getRequestParameter('id', -1);
    $userId = $this->getRequestParameter('userid');
    $filter = $this->getRequestParameter('filter');
    $isGetAll = $this->getRequestParameter('isgetall');
    $sortDirBy = $this->getRequestParameter('sortdirby');
    $sortFileBy = $this->getRequestParameter('sortfileby');

    $isGetAll = $isGetAll != 1 ? 0:1;
    // 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();
    if ($isGetAll == 0)
    	$c->add(TblspacecategoryPeer::CAT_PARENT, $this->catId);
    
    $c->add(TblspacecategoryPeer::CAT_USER, $userId);
    $c->addAscendingOrderByColumn(TblspacecategoryPeer::CAT_PARENT);
    $c->addAscendingOrderByColumn(TblspacecategoryPeer::CAT_ID);
    $this->tblcategories = TblspacecategoryPeer::doSelect($c);

    // find files in this category folder
    $c = new Criteria();
    if ($isGetAll == 0)
    	$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 executeDeletemulti () {
  	$userId = $this->getRequestParameter('userid');
  	$aryDel = $this->getRequestParameter('delobj');
  	$this->aryDeletedObj = json_decode($aryDel);
  	
  	$aryDirID = array();
  	$aryFileID = array();
  	
  	if (is_array($this->aryDeletedObj)) {
  		foreach ($this->aryDeletedObj as $key => $obj) {
  			if ($obj->type == 'directory') {
  				if (is_array($obj->childDirs)) {
  					foreach ($obj->childDirs as $childDir) {
  						$aryDirID[] = $childDir->id;
  					}
  				}
  				
  				if (is_array($obj->childFiles)) {
  					foreach ($obj->childFiles as $childFile) {
  						$aryFileID[] = $childFile->id;
  					}
  				}
  				$aryDirID[] = $obj->id;
  			}
  			else {
  				$aryFileID[] = $obj->id;
  			}
  		}
  	}
  	
   	if (count($aryFileID) > 0) {
   		foreach ($aryFileID as $id) {
   			$c = new Criteria();
   			$c->add(TblspacefilePeer::FILE_ID, $id);
   			$c->add(TblspacefilePeer::FILE_USER, $userId);
   			$tblfile = TblspacefilePeer::doSelectOne($c);
   			if ($tblfile) $tblfile->delete();
   		}
   	}  	
  	
   	if (count($aryDirID) > 0) {
 	  	$c = new Criteria();
 	  	$c->add(TblspacecategoryPeer::CAT_USER, $userId);
 	  	$c->add(TblspacecategoryPeer::CAT_ID, $aryDirID, Criteria::IN);
 	  	TblspacecategoryPeer::doDelete($c);
   	}
  	
  	$this->errMsg = '';
  	$this->errCode = '';
  }

  public function executeCopy () {
    $userId = $this->getRequestParameter('userid');
    $destination = $this->getRequestParameter('destination');
    $act = $this->getRequestParameter('act');
    $data = $this->getRequestParameter('data');
	$aryNewTree = array('DIRECTORIES' => array(),'FILES' => array(), );
    $aryTreeObj = json_decode($data);
    
    if (is_array($aryTreeObj)) {
    	foreach ($aryTreeObj as $key => $treeObj){
    		 if ($act == 'copy') {
	    		if ($treeObj->type == 'directory') {
	    			$this->CopySpaceDir($treeObj, $destination, $userId, $aryNewTree);
	    		}
	    		else {
	    			$aryNewTree['FILES'] = $this->CopySpaceFile($treeObj->id, $destination, $userId);
	    		}
    		}
    		else if ($act == 'move') {
    			$this->changeParentDir($treeObj, $destination);
    			if ($treeObj->type == 'directory') $aryNewTree['DIRECTORIES'][] = $treeObj;
    			if ($treeObj->type == 'file') $aryNewTree['FILES'][] = $treeObj;
    		} 
    	}
    }
    
    $this->errMsg = '';
    $this->errCode = '';
    $this->aryNewTree = $aryNewTree;
  }

 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);
    }
echo '{"status":"error"}';
    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));
      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;
  }
}
