<?php

/**
 *--------------------------------------
 * 上传文件
 *--------------------------------------
 * @project		: uwa
 * @author		: cblee
 * @created		: 2012-11-05
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class UploadModl extends Modl
{
	/* 上传列表 */
	public function get_uploadList($where, $order, $limit = 500)
	{
		$_UL = $this->where($where)->order($order)->limit($limit)->select();
		return $_UL;
	}

	public function get_uploadInfo($uploadId)
	{
		$_UI = $this->where('upload_id = \''.$uploadId.'\'')->find();
		return $_UI;
	}

	public function edit_upload($data)
	{
		$result = array('data' => '', 'error' => '');

		$_t_id = $this->update($data);
		if(false === $_t_id)
		{
			$result['error'] = L('EDIT_FAILED');
			return $result;
		}
		$result['data'] = $_t_id;

		return $result;
	}

	public function delete_upload($uploadId)
	{
		$result = array('data' => '', 'error' => '');

		$_UI = $this->get_uploadInfo($uploadId);
		if(empty($_UI))
		{
			$result['error'] = L('ITEM_NOT_EXSIT');
			return $result;
		}

		if(false === $this->delete($uploadId))
		{
			$result['error'] = L('DELETE_FAILED');
			return $result;
		}

		/* 删除文件 */
		@unlink(realpath($_SERVER['DOCUMENT_ROOT'].$_UI['u_src']));

		return $result;
	}

	/* 上传文件 $returnType:editor, normal */
	public function upload_file($field, $typeSet, $thumb, $watermark, $returnType, $uploadType, $fn = '')
	{
		$result = array('data' => '', 'error' => '');

		/* 判断编辑器是否非法调用 */
		if('editor' == $returnType and empty($fn))
		{
			$result['error'] = $this->get_editorJs(1, '', L('ERROR_REQUEST'));
			return $result;
		}
		$o_upload = M('Option')->get_option('upload');
		$u_params = array();
		$uploadDir = APP_PATH.$o_upload['dir'].D_S.$uploadType.D_S.date('Ym/d');
		$thumbDir = APP_PATH.$o_upload['dir'].D_S.$uploadType.D_S.date('Ym/d');
		$uploadPath = ROOT.$o_upload['dir'].'/'.$uploadType.'/'.date('Ym/d').'/';
		$u_params['uploadDir'] = $uploadDir;
		switch($typeSet)
		{
			case 'image':
				$u_params['typeSet'] = explode(',', $o_upload['imgtype']);
				break;
			case 'file':
				$u_params['typeSet'] = explode(',', $o_upload['filetype']);
				break;
			case 'all':
				$u_params['typeSet'] = array_merge(explode(',', $o_upload['imgtype']), explode(',', $o_upload['filetype']));
				break;
			default:
				$u_params['typeSet'] = explode(',', $o_upload['imgtype']);
				break;
		}
		$u_params['maxsize'] = $o_upload['maxsize'] * 1024;
		$_u = get_instance('AUpload', $u_params);
		$upload = $_u->do_upload($field);
		if(empty($upload))
		{
			if('editor' == $returnType)
			{
				$result['error'] = $this->get_editorJs($fn, '', L('UPLOAD_FAILED'));
				return $result;
			}
			$result['error'] = L('UPLOAD_FAILED');
			return $result;
		}
		$err = $_u->uploadError['msg'][0];
		if(!empty($err))
		{
			if('editor' == $returnType)
			{
				$result['error'] = $this->get_editorJs($fn, '', $err);
				return $result;
			}
			$result['error'] = $err;
			return $result;
		}

		$file = array();
		if('image' == $typeSet)
		{
			/* 是否缩略图 */
			$o_image = M('Option')->get_option('image');
			$i_params = array();
			$i_params['sourceDir'] = $uploadDir;
			$i_params['outputDir'] = $uploadDir;
			$_i = get_instance('AImage', $i_params);
			if($thumb)
			{
				$file = $_i->thumbnail($upload['name'], $o_image['thumb_width'], $o_image['thumb_height'], $o_image['thumb_prefix'], $o_image['thumb_proportional']);
				@unlink(realpath($uploadDir.D_S.$upload['name'])); /* 删除临时图片 */
			}
			elseif($watermark && $o_image['watermark']) /* 是否水印 */
			{
				$file = $_i->mark($upload['name'], $_SERVER['DOCUMENT_ROOT'].$o_image['watermark_image'], $o_image['watermark_position'], '');
				$file = $upload;
			}
		}
		/* 合并文件信息 */
		$file = array_merge($upload, $file);

		/* 插入upload表 */
		$_t_data = array();
		$_t_data['u_filename'] = $file['original_name'];
		$_t_data['u_src'] = $uploadPath.$file['name'];
		$_t_data['u_type'] = $file['type'];
		$_t_data['u_size'] = $file['size'];
		$_t_data['u_add_time'] = time();
		$_t_data['u_item_type'] = $uploadType;
		M('Upload')->insert($_t_data);

		/* 设置上传文件 */
		$uploadFile = ASession::get('_upload') ? ASession::get('_upload') : array();
		$uploadFile[] = $uploadPath.$file['name'];
		ASession::set('_upload', $uploadFile);

		/* 处理完成输出 */
		if('editor' == $returnType)
		{
			$result['data'] = $this->get_editorJs($fn, $uploadPath.$file['name'], '');
			return $result;
		}
		$result['data'] = $uploadPath.$file['name'];
		return $result;
	}
	/* 输出editor js调用 */
	private function get_editorJs($fn, $fileurl, $message)
	{
		$str='<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$fn.', \''.$fileurl.'\', \''.$message.'\');</script>';
		exit($str);
	}

	/* 从内容获取缩略图 */
	public function get_thumb($content, $uploadType = 'archive')
	{
		$o_upload = M('Option')->get_option('upload');
		$o_image = M('Option')->get_option('image');

		$uploadDir = APP_PATH.$o_upload['dir'].D_S.$uploadType.D_S.date('Ym/d');
		$u_params = array();
		$u_params['uploadDir'] = $uploadDir;
		$u_params['typeSet'] = explode(',', $o_upload['imgtype']);
		$u_params['maxsize'] = $o_upload['maxsize'] * 1024;
		$_u = get_instance('AUpload', $u_params);

		$i_params = array();
		$i_params['sourceDir'] = $uploadDir;
		$i_params['outputDir'] = $uploadDir;
		$_i = get_instance('AImage', $i_params);

		if(MAGIC_QUOTES_GPC)
		{
			$content = stripslashes($content);
		}
		preg_match_all('/<img.*?src=[\'|\"](.*?\.(?:'.str_replace(',', '|', $o_upload['imgtype']).'))[\'|\"].*?\/>/si', $content, $file);
		$_t_thumb = $file[1][0];
		if(empty($_t_thumb))
		{
			return '';
		}
		/* 本域名图片 */
		if(!preg_match('/http:\/\//si', $_t_thumb))
		{
			$_t_thumb = __HOST__.$_t_thumb;
		}
		$localFile = $_u->save_remoteFile(trim($_t_thumb));
		$_t_thumb = $localFile['name'];
		$thumb = $_i->thumbnail($_t_thumb, $o_image['thumb_width'], $o_image['thumb_height'], $o_image['thumb_prefix'], $o_image['thumb_proportional']);
		@unlink(realpath($uploadDir.D_S.$_t_thumb)); /* 删除临时图片 */
		$local = ROOT.$o_upload['dir'].'/'.$uploadType.'/'.date('Ym/d').'/'.$thumb['name'];
		/* 插入upload表 */
		$_t_data = array();
		$_t_data['u_filename'] = $thumb['name'];
		$_t_data['u_src'] = $local;
		$_t_data['u_type'] = $localFile['type'];
		$_t_data['u_size'] = $localFile['size'];
		$_t_data['u_add_time'] = time();
		$_t_data['u_item_type'] = $uploadType;
		$this->insert($_t_data);
		/*设置文件*/
		$uploadFile = ASession::get('_upload') ? ASession::get('_upload') : array();
		$uploadFile[] = $local;
		ASession::set('_upload', $uploadFile);

		return $local;
	}

	/* 处理远程文件 */
	public function deal_reomote_file($content, $watermark = false, $uploadType = 'archive')
	{
		$uploadFile = array();

		$o_upload = M('Option')->get_option('upload');
		$o_image = M('Option')->get_option('image');

		$uploadDir = APP_PATH.$o_upload['dir'].D_S.$uploadType.D_S.date('Ym/d');
		$u_params = array();
		$u_params['uploadDir'] = $uploadDir;
		$u_params['typeSet'] = array_merge(explode(',', $o_upload['imgtype']), explode(',', $o_upload['filetype']));
		$u_params['maxsize'] = $o_upload['maxsize'] * 1024;
		$_u = get_instance('AUpload', $u_params);

		$i_params = array();
		$i_params['sourceDir'] = $uploadDir;
		$i_params['outputDir'] = $uploadDir;
		$_i = get_instance('AImage', $i_params);
		$waterfile = $_SERVER['DOCUMENT_ROOT'].$o_image['watermark_image'];

		if(MAGIC_QUOTES_GPC)
		{
			$content = stripslashes($content);
		}
		/* 图片 */
		preg_match_all('/<img.*?src=[\'|\"](http\:\/\/.*?\.(?:'.str_replace(',', '|', $o_upload['imgtype']).'))[\'|\"].*?\/>/si', $content, $file);
		$file = array_unique($file[1]);
		foreach($file as $v)
		{
			$localFile = $_u->save_remoteFile(trim($v));
			/* 添加水印 */
			if($watermark)
			{
				$_i->mark($localFile['name'], $waterfile, $o_image['watermark_position'], '');
			}
			$local = ROOT.$o_upload['dir'].'/'.$uploadType.'/'.date('Ym/d').'/'.$localFile['name'];
			if($localFile['name'])
			{
				$content = str_ireplace($v, $local, $content);
			}
			/* 插入upload表 */
			$_t_data = array();
			$_t_data['u_filename'] = $localFile['name'];
			$_t_data['u_src'] = $local;
			$_t_data['u_type'] = $localFile['type'];
			$_t_data['u_size'] = $localFile['size'];
			$_t_data['u_add_time'] = time();
			$_t_data['u_item_type'] = $uploadType;
			$this->insert($_t_data);
			/* 记录文件名 */
			$uploadFile[] = $local;
		}
		/* 资源 */
		preg_match_all('/<a.*?href=[\'|\"](http\:\/\/.*?\.(?:'.str_replace(',', '|', $o_upload['filetype']).'))[\'|\"].*?\/>/si', $content, $file);
		$file = array_unique($file[1]);
		foreach($file as $v)
		{
			$localFile = $_u->save_remoteFile(trim($v));
			$local = ROOT.$o_upload['dir'].'/'.$uploadType.'/'.date('Ym/d').'/'.$localFile['name'];
			if($localFile['name'])
			{
				$content = str_ireplace($v, $local, $content);
			}
			/* 插入upload表 */
			$_t_data = array();
			$_t_data['u_filename'] = $localFile['name'];
			$_t_data['u_src'] = $local;
			$_t_data['u_type'] = $localFile['type'];
			$_t_data['u_size'] = $localFile['size'];
			$_t_data['u_add_time'] = time();
			$_t_data['u_item_type'] = $uploadType;
			$this->insert($_t_data);
			/* 记录文件名 */
			$uploadFile[] = $local;
		}
		if(MAGIC_QUOTES_GPC)
		{
			$content = addslashes($content);
		}
		/*设置档案文件*/
		$_f = ASession::get('_upload') ? ASession::get('_upload') : array();
		$_f = array_merge($_f, $uploadFile);
		ASession::set('_upload', $_f);

		return $content;
	}

	/* 更新附件 */
	public function update_upload($uItemId, $memberId)
	{
		$upload = ASession::get('_upload');
		if(!empty($upload))
		{
			$data = array();
			$data['u_item_id'] = $uItemId;
			$data['member_id'] = $memberId;
			foreach($upload as $upload)
			{
				$this->where("`u_src` = '".$upload."'")->update($data);
			}
		}
		ASession::del('_upload');
	}

}

?>