<?php
defined('PP_PATH') or exit;
class attach_control extends admin_control {
	public $ueconfig ;
	
	public function __construct(){
		parent::__construct();
		$this->ueconfig = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(APP_PATH.'config/config.json')), true);
	}
	
    public function index(){
		$mid = max(1, (int)R('mid'));
		$cid = (int)R('cid');
		$id = (int)R('id');
		
		$action = R('uaction');
		switch ($action){
			case 'config':
				$result =  json_encode($this->ueconfig);
				break;
			case 'uploadimage':
				$result = $this->UEpload($mid,$cid,$id,$action);
				break;
			case 'uploadfile':
				$result = $this->UEpload($mid,$cid,$id,$action);
				break;
			default:
				$result = json_encode(array(
					'state'=> '请求地址出错'
				));
				break;
		}
		$callback = R('callback') ;
		if(isset($callback)){
			if (preg_match("/^[\w_]+$/", $callback)){
				echo htmlspecialchars($callback) . '(' . $result . ')';
			} else {
				echo json_encode(array(
					'state'=> 'callback参数不合法'
				));
			}
		}else{
			echo $result;
		}
    }
	
	// 上传图集和缩略图
	public function upload_image() {
		$type = R('type');
		$mid = max(2, (int)R('mid'));
		$cid = (int)R('cid');
		$id = (int)R('id');
		$aid = (int)R('pid');
		$table = $this->models->get_table($mid);
		$cfg = $this->runtime->xget();

		$updir = 'upload/'.$table.'/';
		$config = array(
			'maxSize'=>$cfg['up_img_max_size'],
			'allowExt'=>$cfg['up_img_ext'],
			'upDir'=>PP_PATH.$updir,
		);
		
		if($type != 'img') {
			$info = $this->cms_attach->uploads($config, $this->_user['uid'], $cid, $id,$mid,$aid);
		}else{ //图片组不需传送aid
			$info = $this->cms_attach->uploads($config, $this->_user['uid'], $cid, $id,$mid);
		}

		if($info['state'] == 'SUCCESS') {
			$path = $updir.$info['path'];
			$thumb = image::thumb_name($path);
			$src_file = PP_PATH.$path;
			image::thumb($src_file, PP_PATH.$thumb, $cfg['thumb_'.$table.'_w'], $cfg['thumb_'.$table.'_h'], $cfg['thumb_type'], $cfg['thumb_quality']);
			// 是否添加水印
			if(!empty($cfg['watermark_pos'])) {
				image::watermark($src_file, PP_PATH.'static/img/watermark.png', null, $cfg['watermark_pos'], $cfg['watermark_pct']);
			}

			if($type == 'img') { // 图集
				if(R('ajax')) {
					echo '{"path":"'.$path.'","thumb":"'.$thumb.'","state":"'.$info['state'].'","aid":"'.$info['maxid'].'"}';
				}else{
					echo '<script>parent.setDisplayImg("'.$path.'","'.$thumb.'","'.$info['maxid'].'");</script>';
				}
			}else{ // 缩略图
				echo '<script>parent.setDisplayPic("'.$path.'","'.$thumb.'","'.$info['maxid'].'");</script>';
			}
		}else{
			if(R('ajax')) {
				echo '{"path":"","state":"'.$info['state'].'"}';
			}else{
				echo '<script>parent.layeralert("'.$info['state'].'");</script>';
			}
		}
		exit;
	}
	
	public function upload_file(){
		$type = R('type');
		$mid = max(2, (int)R('mid'));
		$cid = (int)R('cid');
		$id = (int)R('id');
		$aid = (int)R('did');
		$table = $this->models->get_table($mid);
		$cfg = $this->runtime->xget();

		$updir = 'upload/'.$table.'/';
		$config = array(
			'maxSize'	=> $cfg['up_file_max_size'],
			'allowExt'	=> $cfg['up_file_ext'],
			'upDir'		=> PP_PATH.$updir,
		);
		$info = $this->cms_attach->uploads($config, $this->_user['uid'], $cid, $id ,$mid,$aid);

		if($info['state'] == 'SUCCESS') {
			$path = $updir.$info['path'];
			//$size = round($info['size'] / 1048576 * 100) / 100;
			$size = number_format($info['size'] / 1048580, 2, '.', '');
			$size =  ($size > 0) ? $size : '0.01';
			echo '<script>parent.setDisplayfile("'.$path.'","'.$info['maxid'].'","'.$size.'","'.$info['name'].'");</script>';
		}else{
			if(R('ajax')) {
				echo '{"path":"","state":"'.$info['state'].'"}';
			}else{
				echo '<script>parent.layeralert("'.$info['state'].'") ;</script>';
			}
		}
		exit;
	}

	//其他图片上传 幻灯－形象图等
	public function upload_other(){
		$dir = R('dir');
		$type = R('type');
		$cfg = $this->runtime->xget();
		$othercfg = $this->kv->xget('other_cfg');
		
		//$max = count($othercfg[$dir]) + 1;
		if(!empty($othercfg[$dir])){
			$tmp = max($othercfg[$dir]);
		}
		if(!empty($tmp)){
			$max = $tmp['aid'] + 1;
		}else{
			$max = 1;
		}
		
		$updir = 'upload/'.$dir.'/';
		$config = array(
			'maxSize'=>$cfg['up_img_max_size'],
			'allowExt'=>$cfg['up_img_ext'],
			'upDir'=>PP_PATH.$updir,
		);
		$up = new upload($config, 'upfile');
		$info = $up->getFileInfo();
		if($info['state'] == 'SUCCESS') {
			$path = $updir.$info['path'];
			$thumb = image::thumb_name($path);
			$src_file = PP_PATH.$path;
			image::thumb($src_file, PP_PATH.$thumb, $cfg['thumb_products_w'], $cfg['thumb_products_h'], $cfg['thumb_type'], $cfg['thumb_quality']);

			if(!empty($cfg['watermark_pos'])) {
				image::watermark($src_file, PP_PATH.'static/img/watermark.png', null, $cfg['watermark_pos'], $cfg['watermark_pct']);
			}
			if($type == 'img') { // 图集
				if(R('ajax')) {
					echo '{"path":"'.$path.'","thumb":"'.$thumb.'","state":"'.$info['state'].'","aid":"'.$max.'"}';
				}else{
					echo '<script>parent.setDisplayImg("'.$path.'","'.$thumb.'","'.$max.'");</script>';
				}
			}else{ // 缩略图
				echo '<script>parent.setDisplayPic("'.$path.'","'.$thumb.'");</script>';
			}
		}else{
			if(R('ajax')) {
				echo '{"path":"","state":"'.$info['state'].'"}';
			}else{
				echo '<script>alert("'.$info['state'].'");</script>';
			}
		}
	}
	// 编辑器上传图片
	private function up_image() {
		$type = R('type');
		$mid = max(1, (int)R('mid'));
		$cid = (int)R('cid');
		$id = (int)R('id');
		$cfg = $this->runtime->xget();

		if($mid == 1) {
			// 单页上传的图片量小，所以不保存到数据库。
			$updir = 'upload/page/';
			$config = array(
				'maxSize'=>$cfg['up_img_max_size'],
				'allowExt'=>$cfg['up_img_ext'],
				'upDir'=>PP_PATH.$updir,
			);
			$up = new upload($config, 'upfile');
			$info = $up->getFileInfo();
		}else{
			// 非单页模型
			$table = $this->models->get_table($mid);
			$updir = 'upload/'.$table.'/';
			$config = array(
				'maxSize'=>$cfg['up_img_max_size'],
				'allowExt'=>$cfg['up_img_ext'],
				'upDir'=>PP_PATH.$updir,
			);
			$info = $this->cms_attach->uploads($config, $this->_user['uid'], $cid, $id);
		}
		$path = $updir.$info['path'];

		// 是否添加水印
		if($info['state'] == 'SUCCESS' && !empty($cfg['watermark_pos'])) {
			image::watermark(PP_PATH.$path, PP_PATH.'static/img/watermark.png', null, $cfg['watermark_pos'], $cfg['watermark_pct']);
		}

		if($type == 'ajax') {
			echo '{"path":"'.$path.'","state":"'.$info['state'].'"}';
		}else{
			$editorid = preg_replace('/\W/', '', R('editorid'));
			echo "<script>parent.UM.getEditor('".$editorid."').getWidgetCallback('image')('".$path."','".$info['state']."')</script>";
		}
		exit;
	}
	private function UEpload($mid,$cid,$id,$action){	//baidu编辑器上传
		if(empty($_FILES)){
			return false;
		}
		$cfg = $this->runtime->xget();
		
		if($mid == 1) {
			// 单页上传的图片量小，所以不保存到数据库。
			$updir = 'upload/page/';
		}else{
			// 非单页模型，改ue同时不存数据库
			$table = $this->models->get_table($mid);
			$updir = 'upload/'.$table.'/';
		}
		$type = "upload" ;
		switch ($action){
			case 'uploadimage':
				$config = array(
					"pathFormat" 	=> $cfg['webdir'].$updir.$this->ueconfig['imagePathFormat'],
					"maxSize" 		=> $cfg['up_img_max_size'] * 1024,
					"allowFiles" 	=> $this->ueconfig['imageAllowFiles']
				);
				$fieldName = $this->ueconfig['imageFieldName'];
				break;
			case 'uploadfile':
			default:
				$config = array(
					"pathFormat" => $cfg['webdir'].$updir.$this->ueconfig['imagePathFormat'],
					"maxSize" => $cfg['up_file_max_size'] * 1024,
					"allowFiles" => $this->ueconfig['fileAllowFiles']
				);
				$fieldName = $this->ueconfig['fileFieldName'];
				break;
		}

		/* 生成上传实例对象并完成上传 */
		$up = new Uploader($fieldName, $config, $type);
		$info =  $up->getFileInfo();
		//$path = $updir.$info['url'];
		$path = $info['url'];
		if($action=='uploadimage'){
			// 是否添加水印
			if($info['state'] == 'SUCCESS' && !empty($cfg['watermark_pos'])) {
				image::watermark($_SERVER['DOCUMENT_ROOT'].$path, PP_PATH.'static/img/watermark.png', null, $cfg['watermark_pos'], $cfg['watermark_pct']);
			}
		}
		return json_encode($info);
	}
}
