<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOOPS_TRUST_PATH.'/libs/xoonips/class/core/File.class.php';
require_once XOONIPS_MAIN_PATH.'/class/core/Item.class.php';
require_once XOOPS_ROOT_PATH.'/class/class.zipfile.php';

function downLoadUnlink($file_path) {
  @unlink($file_path);
}

class model_download {
  private $dirname;
  private $trustDirname;
  private $itemVirtualBean;
  private $itemBean;
  private $itemFileBean;
  private $itemTypeBean;
  private $uid;
  
  public function Init() {
    $this->dirname = $this->trustDirname = 'xoonips';
    $this->itemVirtualBean = Xoonips_BeanFactory::getBean('ItemVirtualBean',  $this->dirname,  $this->trustDirname);
    $this->itemBean = Xoonips_BeanFactory::getBean('ItemBean',  $this->dirname,  $this->trustDirname);
    $this->itemFileBean = Xoonips_BeanFactory::getBean('ItemFileBean',  $this->dirname,  $this->trustDirname);
    $this->itemTypeBean = Xoonips_BeanFactory::getBean('ItemTypeBean',  $this->dirname,  $this->trustDirname);
    $this->configBean = Xoonips_BeanFactory::getBean('ConfigBean',  $this->dirname,  $this->trustDirname);
  }
  
  public function set_uid($uid) {
    $this->uid = $uid;
  }
  
  private function getFilePath($opTp, $file_id) {
    $uploadDir = $this->configBean->getConfig('upload_dir');
    $file_path = $uploadDir.'/'.(int)$file_id;
    return $file_path;
  }

  private function downloadCreateZipfile($xoonipsFile, $dirname, $file_id, $item_id, $file_name, $metadata) {
    $file_path = $xoonipsFile->getFilePath('item', $file_id);
    if (!file_exists($file_path)) {
      // file not found
      return false;
    }
    // get metafile
    $metadata .= _MD_XOONIPS_ITEM_DETAIL_URL.': '.XOOPS_URL.'/modules/'.$dirname.'/detail.php?item_id='.$item_id."\r\n";
    $metafile_body = Xoonips_Utils::encodeUtf8($metadata);
    // open zipfile
    $zipfile_path = tempnam('/tmp', 'XooNIpsDownloadZipFile');

	$zip = new ZipArchive();
	if (!$zip->open($zipfile_path, ZIPARCHIVE::CREATE)) {
		// failed to create temporary file for zip
		return false;
	}
	$zip->addFile($file_path, $file_name);
	$zip->addFromString('metainfo.txt', $metafile_body);
	$zip->close();    
    
    return $zipfile_path;
  }

  /**
   * check Ziped on config.
   * 
   * @return 1:on,0:off,-1:not define compress!! 
   */
  private function is_compress() {
    $rc = $this->configBean->getConfig('download_file_compression');
    if (is_null($rc)) {
      return -1;
    }
    if (strcmp($rc, 'on') == 0) {
      return 1;
    }
    return 0;
  }
  
  private function getFileInfo($file_id) {
    return $this->itemFileBean->getFile($file_id);
  }
  
  private function canDownload($item_id) {
    $item_virtual_bean = Xoonips_BeanFactory::getBean('ItemVirtualBean', $this->dirname, $this->trustDirname);
    return $item_virtual_bean->canItemUsersEdit($item_id,  $this->uid);
  }

  public function download($item_id, $file_id) {
    if ($this->canDownload($item_id) == false) {
      return -1;
    }
    // get item_name
    $itemInfo = $this->itemBean->getItemBasicInfo($item_id);
    $item_type_id = $itemInfo['item_type_id'];

    // get fileInfo
    $fileInfo = $this->getFileInfo($file_id);
    if (empty($fileInfo)) {
      return -1;
    }
    
    // Check download limitation
    $limit = $this->itemVirtualBean->getDownloadLimit($item_id, $item_type_id);
    $file_name = Xoonips_Utils::convertToClient($fileInfo['original_file_name']);
    $itemtypeName = $this->itemTypeBean->getItemTypeName($item_type_id);
    // zip or non-zip?
    $xoonips_file = new Xoonips_File($this->dirname, $this->trustDirname);
    switch ($this->is_compress()) {
    case 1:
      // do compress
      $item = new Xoonips_Item($item_type_id,  $this->dirname,$this->trustDirname);
      $metadata = $item->getMetaInfo($item_id);
      $itemtype = $this->itemTypeBean->getItemType($item_type_id);
      $dl_filepath = $this->downloadCreateZipfile($xoonips_file, $this->dirname, $file_id, $item_id, $file_name, $metadata);
      $dl_filename = Xoonips_Utils::convertToClient($itemtypeName.'_'.$file_id.'.zip');
      // $dl_filename =$itemtypeName.'_'.$file_id.'.zip';
      $dl_mimetype = 'application/zip';
      break;
    case 0:
      // don't compress
      $dl_filepath = $xoonips_file->getFilePath('item', $file_id);
      $dl_filename = Xoonips_Utils::convertToClient($fileInfo['original_file_name']);
      $dl_mimetype = $fileInfo['mime_type'];
      break;
    case -1:
      // Not detect zip on/off.
    return -2;
      break;
    }
    
    // File download
    $xoonips_file->downloadFile($dl_filepath, $dl_filename, $dl_mimetype);
    return 1;
  }
}
