<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class bug_tracker_file extends DefaultObject
{
	protected $cache_key='bt_file_';

	public function __construct($mapper=null)
	{
		if (is_object($mapper)) {
			$this->mapper=$mapper;
		} else {
			$this->mapper=Factory::create('bug_tracker.mapper');
		}
		Factory::load('bug_tracker.file_entity');
	}

	public function getFilesByPosts($posts)
	{
		$key='bug_tracker_files_by_posts_'.implode('_', array_keys($posts));
		if (false === ($data=TCache::get($key))) {
			if ($data=$this->mapper->getFilesByPosts($posts)) {
				$data = $this->getFilesByArrayId($data);
			}
			TCache::set($data, $key, array($this->_getCacheKeyCommon()));
		}

		return $data;
	}

	public function getFilesByArrayId($id)
	{
		return $this->_getItemsByArrayId($id);
	}

	protected function _getItemsByArrayIdFromStorage($id)
	{
		return $this->mapper->getFilesByArrayId($id);
	}

	public function delete($file)
	{
		if (is_array($file->path)) {
			$files=$file->path;
		} else {
			$files=array($file->path);
		}
		foreach ($files as $path) {
			unlink(LAB_PATH_ROOT.$path);
		}
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		return $this->mapper->deleteFile($file);
	}

	public function update($file)
	{
		TCache::remove($this->_getCacheKey().$file->id);
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
		return $this->mapper->updateFile($file);
	}
	
	public function upload($data, $post=null)
	{
		foreach ($data['size'] as $key=>$size) {
			if (!$size) continue;
			$file=array(
				'name'=>$data['name'][$key],
				'type'=>$data['type'][$key],
				'tmp_name'=>$data['tmp_name'][$key],
				'error'=>$data['error'][$key],
				'size'=>$data['size'][$key],
			);

			if (in_array($data['type'][$key], array('image/gif', 'image/jpeg', 'image/png'))) {
				$this->_upload_image($file, $post);
			} else {
				$this->_upload_file($file, $post);
			}
		}
		TCache::clean('MATCH_TAG', array($this->_getCacheKeyCommon()));
	}
	
	protected function _upload_file($upload, $post)
	{
		require_once dirname(__FILE__)."/zip.class.php";
		$ctn=config::get('tn');
		if (!is_dir(LAB_PATH_ROOT.$ctn['file_path'])) mkdir(LAB_PATH_ROOT.$ctn['file_path'], 0777, true);
		
		$data=array(
			'post_id'=>(empty($post->id)?0:$post->id),
			'name'=>$upload['name'],
			'type'=>'zip'
		);
		$file=Factory::create('bug_tracker.file_entity', $data);
			$this->mapper->addFile($file);

		$id=$this->_insert($upload['name'], 'zip', $post);
		
		$zipfile = new zipfile();
		$filedata = file_get_contents($upload['tmp_name']);
		$zipfile -> add_file($filedata, basename($upload['name']));
		if (file_put_contents(LAB_PATH_ROOT.$ctn['file_path'].'/'.$id.'.zip', $zipfile -> file())) {
			chmod(LAB_PATH_ROOT.$ctn['file_path'].'/'.$id.'.zip', 0644);
		} else {
			$this->delete($file);
		}

		$post->addFile($file);
	}
	
	protected function _upload_image($upload, $post)
	{
		$ctn=config::get('tn');
	
		$img_info=getimagesize($upload['tmp_name']);
		if ($img_info[2]>0 && $img_info[2]<4) {
			$ext=image_type_to_extension($img_info[2], false);
			
			$data=array(
				'post_id'=>(empty($post->id)?0:$post->id),
				'name'=>$upload['name'],
				'type'=>$ext
			);
			$file=Factory::create('bug_tracker.file_entity', $data);
			$this->mapper->addFile($file);
	
			foreach ($ctn['images'] as $tn) {
				$img=Factory::create('Image_Resize');
				if (!empty($tn['type'])) {
					$new_name=$file->id.".".$tn['type'];
					$img->new_type=$tn['type'];
				} else {
					$new_name=$file->id.'.'.$ext;
				}
				
				if (!is_dir(LAB_PATH_ROOT.$ctn['img_path']."/".$tn['path'])) {
					mkdir(LAB_PATH_ROOT.$ctn['img_path']."/".$tn['path'], 0777, true);
				}
				$img->file= $upload['tmp_name'];
				$img->file_dest= LAB_PATH_ROOT.$ctn['img_path']."/".$tn['path']."/".$new_name;
				$img->width=$tn['w'];
				$img->height=$tn['h'];
				if (isset($tn['crop'])) $img->crop=$tn['crop'];
				if ($img->go()) {
					$done[]= LAB_PATH_ROOT.$ctn['img_path']."/".$tn['path']."/".$new_name;
					chmod($img->file_dest, 0644);
				} else {
					$this->delete($file);
				}
			}

			$post->addFile($file);
		}
	}
	
	public function getAllByPosts($ids)
	{
		if (!$ids) return;
		if ($result=Db::i()->select("SELECT * FROM ?_bt_files WHERE post_id IN (?a)", $ids)) {
			foreach ($result as $item) {
				$obj=Factory::create('bug_tracker.file');
				$obj->set($item);
				$files[]=$obj;
			}
			return $files;
		}
	}
}