<?php
    include_once("../lib/symfony/vendor/phing/lib/Zip.php");
    include_once("lib.backend/class.httpdownload.php");
/**
 * document actions.
 *
 * @package    sf_sandbox
 * @subpackage document
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class documentActions extends autodocumentActions
{
    //public $error = array();
	public function executeCreatebatch() {
	    ini_set("max_execution_time",3000);
	    if ($this->getRequest()->getMethod() != sfRequest::POST)
		{
			// display the form
			$this->getRequest()->setAttribute('referer', $this->getRequest()->getReferer());
			$this->reports = '';
		}
		else {
		    $dir = sfConfig::get('sf_upload_dir');
		    //handle the form submit
		    if(!is_dir("$dir/temp")){
		      mkdir("$dir/temp");
		      //chmod("$dir/temp", 777);
		    }
		    if (!$this->getRequest()->hasErrors() && $this->getRequest()->getFileSize('createbatch')) {
		        $filename = $this->getRequest()->getFileName('createbatch');
		        if(!$this->getRequest()->moveFile('createbatch', "$dir/temp/$filename")){
		            $this->getRequest()->setError('delete', 'Upload not success');
		            return $this->forward('document', 'list');
		            //exit();
		        }
		    }

		    if(file_exists("$dir/temp/$filename")) {
		       $zip = new Archive_Zip("$dir/temp/$filename");
		       if($zip->extract(array("add_path"=>"uploads/temp/")))
		          unlink("$dir/temp/$filename");
		    }
		    $tmp = substr($filename, 0, strlen($filename)-4);
		    $forder = "uploads/temp/".substr($filename, 0, strlen($filename)-4);
		    $strContent = file_get_contents("$forder/$tmp.txt");
		    if (ord($strContent[0])==255 && ord($strContent[1])==254)
		      $strContent = $this->unicode_to_utf8($strContent);
		    $lines = explode("\r\n", $strContent);

		    $succ = 0;
		    $error = 0;
		    foreach ($lines as $key1 => $line) {
		        if($key1 == 0)
		          continue;
		        if($line == "\r\n")
		          continue;
                $values = explode("\t", $line);
                $docTag = "";
                $docDesc = "";
                foreach ($values as $key => $value) {

                    if($key == 0)
                     $docName = $value;

                    if($key == 1)
                        $docSource = $value;

                    if($key == 2){
                        $docCat = trim($value);
                    }

                    if($key == 3)
                        $docFilename = trim($value);

                    if($key == 4)
                        $docTag = trim($value);

                    if($key == 5)
                        $docDesc = $value;

                }//foreach

                $docCat = intval($docCat);
                $cat = $this->checkPathCat($docCat);
                //var_dump($cat);
                if($cat != false) {
                    // $docCat = $cat->getCgId();
                    //move file to cat dir
                    if(file_exists("$forder/$docFilename") && !file_exists(sfConfig::get('sf_upload_dir')."/resources/$cat/$docFilename")){
                        rename("$forder/$docFilename", sfConfig::get('sf_upload_dir')."/resources/$cat/$docFilename");
                        $document = new Tbldocument();
                        $document->setDocName($docName);
                        $document->setDocSource($docSource);
                        $document->setDocCategory($cat);
                        $document->setDocFilename($docFilename);
                        $document->setDocType('');
                        $document->setDocKeyword($docTag);
                        $document->setDocDesc($docDesc);
                        $document->setDocUser(sfContext::getInstance()->getUser()->getUserId());
                        $document->setDocDate(date("m/d/Y H:i:s", time()));
                        $document->setDocStatus(1);
                        $document->save();

                        $succ ++;
                    }
                    else {//not exit image or flash file
                        $report[] = " not exits <b>$docFilename</b>";
                        $error ++;
                    }//else
                }//if
                else {
                    $report[] = "category <b>$docCat</b> not exits";
                    $error ++;
                }//else

		    }//foreach

		    $this->deleteDirNotEmpty($forder);

		    //report
		    $uploadInfo['name'] = $tmp;
		    $uploadInfo['succ'] = $succ;
		    $uploadInfo['error'] = $error;
		    $this->uploadInfo = $uploadInfo;
		    $this->reports= $report;
		    //end report

		    //$this->redirect("document");
		}//else

	}

	protected function unicode_to_utf8($str) {

        $utf8 = '';

        //foreach( $str as $unicode ) {
        for ($i = 2; $i < strlen( $str ); $i+=2 ) {

            $unicode = ord($str[$i]) + (ord($str[$i+1]) << 8);
            if ( $unicode < 128 ) {

                $utf8.= chr( $unicode );

            } elseif ( $unicode < 2048 ) {

                $utf8.= chr( 192 +  ( ( $unicode - ( $unicode % 64 ) ) / 64 ) );
                $utf8.= chr( 128 + ( $unicode % 64 ) );

            } else {

                $utf8.= chr( 224 + ( ( $unicode - ( $unicode % 4096 ) ) / 4096 ) );
                $utf8.= chr( 128 + ( ( ( $unicode % 4096 ) - ( $unicode % 64 ) ) / 64 ) );
                $utf8.= chr( 128 + ( $unicode % 64 ) );

            } // if

        } // for

        return $utf8;

    } // unicode_to_utf8

	public function handleError()
    {
        return sfView::ERROR;
    }

    public function handleErrorCreatebatch()
    {
    	return sfView::SUCCESS;
    }


    protected function addFiltersCriteria($c)
    {
        //autodocumentActions::addFiltersCriteria($c);
        if (isset($this->filters['doc_category_is_empty']))
        {
          $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_CATEGORY, '');
          $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_CATEGORY, null, Criteria::ISNULL));
          $c->add($criterion);
        }
        else if (isset($this->filters['doc_category']) && $this->filters['doc_category'] !== '')
        {
          //$c->add(TbldocumentPeer::DOC_CATEGORY, $this->filters['doc_category']);
          $c->addJoin(TbldocumentPeer::DOC_ID, TblcategorydocumentPeer::CD_DOCUMENT);
		  $c->add(TblcategorydocumentPeer::CD_CATEGORY, $this->filters['doc_category']);
        }
        if (isset($this->filters['doc_user_is_empty']))
        {
          $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_USER, '');
          $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_USER, null, Criteria::ISNULL));
          $c->add($criterion);
        }
        else if (isset($this->filters['doc_user']) && $this->filters['doc_user'] !== '')
        {
          $c->add(TbldocumentPeer::DOC_USER, $this->filters['doc_user']);
        }
        if (isset($this->filters['doc_name_is_empty']))
        {
          $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_NAME, '');
          $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_NAME, null, Criteria::ISNULL));
          $c->add($criterion);
        }
        else if (isset($this->filters['doc_name']) && $this->filters['doc_name'] !== '')
        {
          $c->add(TbldocumentPeer::DOC_NAME, '%'.$this->filters['doc_name'].'%', Criteria::LIKE);
        }
        if (isset($this->filters['doc_desc_is_empty']))
        {
          $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_DESC, '');
          $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_DESC, null, Criteria::ISNULL));
          $c->add($criterion);
        }
        else if (isset($this->filters['doc_desc']) && $this->filters['doc_desc'] !== '')
        {
          $c->add(TbldocumentPeer::DOC_DESC, '%'.$this->filters['doc_desc'].'%', Criteria::LIKE);
        }
        if (isset($this->filters['doc_status_is_empty']))
        {
          $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_STATUS, '');
          $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_STATUS, null, Criteria::ISNULL));
          $c->add($criterion);
        }
        else if (isset($this->filters['doc_status']) && $this->filters['doc_status'] !== '' && $this->filters['doc_status'] != '3')
        {
            $c->add(TbldocumentPeer::DOC_STATUS, $this->filters['doc_status']);
        }
        if (isset($this->filters['doc_status']) && $this->filters['doc_status'] == '3')
        {
            $c1 = new Criteria();
            $docs = TbldocumentPeer::doSelect($c1);
            foreach ($docs as $doc) {
                $docCat = $doc->getDocCategory();
                $docFilename = $doc->getDocFilename();
                if(!file_exists("uploads/resources/$docCat/$docFilename")){
                    $docError[] = $doc->getDocId();
                }
            }
            $c->add(TbldocumentPeer::DOC_ID , $docError, Criteria::IN );
        }
        /*if (isset($this->filters['doc_category_is_empty']))
        {
            $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_CATEGORY, '');
            $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_CATEGORY, null, Criteria::ISNULL));
            $c->add($criterion);
        }
        else if (isset($this->filters['doc_category']) && $this->filters['doc_category'] !== '')
        {
            $cTemp = new Criteria();
            $cTemp->addJoin(TbldocumentPeer::DOC_ID, TblcategorydocumentPeer::CD_DOCUMENT);
            $cTemp->add(TblcategorydocumentPeer::CD_CATEGORY, $this->filters['doc_category']);



            $cTemp = new Criteria();
            $cTemp->add(TblcategorydocumentPeer::CD_CATEGORY ,$this->filters['doc_category']);
            $docIds = TblcategorydocumentPeer::doSelect($cTemp);
            var_dump($docIds);
            foreach ($docIds as $key => $docId) {
                if ($key == 0)
                    $c->add(TbldocumentPeer::DOC_ID , $docId->getCdDocument);
                else
                    $c->addOr(TbldocumentPeer::DOC_ID, $docId->getCdDocument);
            }
            TbldocumentPeer::doSelect($cTemp);
        }
        if (isset($this->filters['doc_user_is_empty']))
        {
            $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_USER, '');
            $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_USER, null, Criteria::ISNULL));
            $c->add($criterion);
        }
        else if (isset($this->filters['doc_user']) && $this->filters['doc_user'] !== '')
        {
            $c->add(TbldocumentPeer::DOC_USER, $this->filters['doc_user']);
        }
        if (isset($this->filters['doc_name_is_empty']))
        {
            $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_NAME, '');
            $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_NAME, null, Criteria::ISNULL));
            $c->add($criterion);
        }
        else if (isset($this->filters['doc_name']) && $this->filters['doc_name'] !== '')
        {
            $c->add(TbldocumentPeer::DOC_NAME, strtr($this->filters['doc_name'], '*', '%'), Criteria::LIKE);
        }
        if (isset($this->filters['doc_desc_is_empty']))
        {
            $criterion = $c->getNewCriterion(TbldocumentPeer::DOC_DESC, '');
            $criterion->addOr($c->getNewCriterion(TbldocumentPeer::DOC_DESC, null, Criteria::ISNULL));
            $c->add($criterion);
        }
        else if (isset($this->filters['doc_desc']) && $this->filters['doc_desc'] !== '')
        {
            $c->add(TbldocumentPeer::DOC_DESC, strtr($this->filters['doc_desc'], '*', '%'), Criteria::LIKE);
        }*/
    }



  protected function saveTbldocument($tbldocument)
  {
    if($tbldocument->getDocUser()=='') {
        $tbldocument->setDocUser(sfContext::getInstance()->getUser()->getUserId());
    }//if
    $tbldocument->setDocDate(date("m/d/Y H:i:s", time()));
    $tbldocument->setDocType(' ');
    $tbldocument->save();
    $fileName = $tbldocument->getDocFilename();
    //var_dump($fileName);
    if (file_exists(sfConfig::get('sf_upload_dir')."/resources/".$fileName)) {
        rename(sfConfig::get('sf_upload_dir')."/resources/".$fileName, sfConfig::get('sf_upload_dir')."/resources/".$tbldocument->getDocCategory().'/'.$fileName);
    }

    //update tblcomment
    $cm_content = $this->getRequestParameter('new_comment', '');
    if($cm_content != '') {
        $comment = new Tblcomment();
        $comment->setCmUsers(sfContext::getInstance()->getUser()->getUserId());
        $comment->setCmDate(date("m/d/Y H:i:s",time()));
        $comment->setCmDocument($tbldocument->getDocId());
        $comment->setCmContent($cm_content);
        $comment->save();
    }
  }

  public function executeDel() {
      $id_list = $this->getRequestParameter('idList');
      $page = $this->getRequestParameter('page');
      $id_array = explode(",", $id_list);

      $c = new  Criteria();
      $c->add(TbldocumentPeer::DOC_ID , $id_array, Criteria::IN );
      $fileUnlinks = TbldocumentPeer::doSelect($c);
      //var_dump($fileUnlink);
      if(TbldocumentPeer::doDelete($c)) {
          //delete file
          foreach ($fileUnlinks as $fileUnlink) {
              $filename = sfConfig::get('sf_upload_dir')."/resources/".$fileUnlink->getDocCategory()."/".$fileUnlink->getDocFilename();
              $thumbnail = sfConfig::get('sf_upload_dir')."/resources/".$fileUnlink->getDocCategory()."/thumbnails".myUtility::getFileName($filename).".jpg";
              if(file_exists($filename))
                unlink($filename);
              if(file_exists($thumbnail))
                unlink($thumbnail);
          }
          //update tblcomment
          $c->clear();
          $c->add(TblcommentPeer::CM_DOCUMENT , $id_array, Criteria::IN );
          TblcommentPeer::doDelete($c);

          //update tbltagsearch
      }
      else {
          $this->getRequest()->setError('delete', "System error: count not delete");
          return $this->forward('document', 'list');
      }

      $this->redirect("document/list?page=$page");
  }

    public  function executeDownloadTemplate() {
        $filename = "images/excel/template.xls";
        $object = new httpdownload;
        $object->set_byfile($filename); //Download from a file
        $object->use_resume = true; //Enable Resume Mode
        $result = $object->download(); //Download File
    }

    public function deleteDirNotEmpty($dir){
        $handle = opendir($dir);
        while (false != ($filename = readdir($handle))) {
            if($filename !='.' && $filename != '..') {
                if(file_exists("$dir/$filename"))
                    unlink("$dir/$filename");
                if (is_dir("$dir/$filename"))
                    $this->deleteDirNotEmpty($dir/$filename);
            }
        }
        closedir($handle);
        rmdir($dir);
    }


    public  function getPathCat($patCat) {
        $catArr = explode("/", $patCat);
        $error = false;
        foreach ($catArr as $key => $cat) {
            $cat = trim($cat);
            $c = new Criteria();
            $c->add(TblcategoryPeer::CG_NAME ,$cat);
            $cat_tmp = TblcategoryPeer::doSelectOne($c);
            //var_dump($cat_tmp);
            if($cat_tmp) {
                $parentID[$key] = $cat_tmp->getCgParentid();
                $categoryID[$key] = $cat_tmp->getCgId();
                if( $parentID[0] != -1) {
                    $error =  true;
                    break;
                }

                if($key > 0) {
                   if ($parentID[$key] != $categoryID[$key-1] ) {
                    	$error = true;
                    	break;
                    }
                }//if
            }
            else {
                $error = true;
                break;
            }

        }//foreach
        if($error == false)
            return $categoryID[$key];
        else
            return false;
    }//getPathCat()
    
    public function checkPathCat ($cat) {
        $error = false;
        $c = new Criteria();
        $c->add(TblcategoryPeer::CG_NAME ,$cat);
        $cat_tmp = TblcategoryPeer::doSelectOne($c);
        if($cat_tmp)
            return false;
        else 
            return $cat; 
    }

}
