<?php
if(!defined('APP_PATH')||!defined('I_PATH')){exit('Access Denied');}

class ld_product extends controllerBase
{
	function __construct(){
		parent::__construct();
		$this->gopage=$this->sysParams('page',0,1);
		$this->molds = 'product';
		$this->sqldb= func_get_iglobal(array('db','prefix')).$this->molds;
		$this->moldname=moldsinfo($this->molds,'moldname');
		$this->ClassADD = syClass('ldi_'.$this->molds);
		$this->chtml = syClass("syhtml");
		$this->ClassT=syClass('ldi_classtype');
		$this->ClassF=syClass('ldi_fields');
		$this->auser=syClass('syauser');
		$classtype=syDB('classtype')->findAll(array('molds'=>$this->molds),null,'tid,classname,pid,molds');
		$this->types=syClass('syclasstype');
		$this->typesdb=$this->types->type_txt();
		if(funsinfo('member','isshow')==1){
		$this->member_group = syDB('member_group')->findAll(null,'weight');
		}
		$this->traits=syDB('traits')->findAll(array('molds'=>$this->molds));
		if(funsinfo('special','isshow')==1){
			$this->specials=syDB('special')->findAll(array('molds'=>$this->molds,'isshow'=>1));
		}
		$this->gocid=$this->sysParams('cid');
		if(($this->sysParams('a',1)=='add'||$this->sysParams('a',1)=='edit')&&$this->sysParams('run')==1){
			$addtime=strtotime($this->sysParams('addtime',1));
			$style=$this->sysParams('style1',1).$this->sysParams('style2',1);
			if($this->sysParams('trait',2)){$trait=','.implode(',',$this->sysParams('trait',2)).',';}else{$trait='';}
			if($this->sysParams('tid')){$tid=$this->sysParams('tid');}
			if($this->sysParams('photofile',2)){
				$phototxt=$this->sysParams('phototxt',2);$ns='';
				foreach($this->sysParams('photofile',2) as $k=>$v){
					$ns.='|-|'.$v.'|,|'.$phototxt[$k];

				////////////////////////////////////////////////////
				
					if(func_get_iglobal(array('ext','site_product_thumb_off'))=='1')
					{
						$thumb_w = func_get_iglobal(array('ext','site_product_thumb_width'));
						$thumb_h = func_get_iglobal(array('ext','site_product_thumb_height'));
						$thumb_prev = func_get_iglobal(array('ext','site_product_thumb_prev'));
						$this->agentimgsize($thumb_w,$thumb_h,APP_PATH.$v,$thumb_prev);
					}
					
				}
				$photo=substr($ns,3);
			}

			//////////////////////////////
			if(''!=$this->sysParams('litpic',1))
			{
				$thumb_w = func_get_iglobal(array('ext','site_product_thumb_width'));
				$thumb_h = func_get_iglobal(array('ext','site_product_thumb_height'));
				$thumb_prev = func_get_iglobal(array('ext','site_product_thumb_prev'));
				$this->agentimgsize($thumb_w,$thumb_h,APP_PATH.$this->sysParams('litpic',1),$thumb_prev);
			}	
		
			$this->newrow1 = array(
				'tid' => $tid,
				'sid' => $this->sysParams('sid'),
				'title' => $this->sysParams('title',1),
				'style' => $style,
				'trait' => $trait,
				'gourl' => $this->sysParams('gourl',1),
				'htmlfile' => strtolower($this->sysParams('htmlfile',1)),
				'htmlurl' => '',
				'addtime' => $addtime,
				'hits' => $this->sysParams('hits'),
				'litpic' => $this->sysParams('litpic',1),
				'photo' => $photo,
				'orders' => $this->sysParams('orders'),
				'price' => $this->sysParams('price',3),
				'mrank' => $this->sysParams('mrank'),
				'mgold' => $this->sysParams('mgold',3),
				'isshow' => $this->sysParams('isshow'),
				'keywords' => $this->sysParams('keywords',1),
				'description' => $this->sysParams('description',1),
			);
			if($this->sysParams('a',1)=='add'){$this->newrow1=array_merge($this->newrow1,array('user' => $_SESSION['auser']['auser']));}
			$this->newrow2 = array(
				'body' => $this->sysParams('body',4),
			);
			$v=$this->ClassF->findAll(" molds='".$this->molds."' and types like '%|".$this->sysParams('tid')."|%' ");
			include(I_PATH.'/agentImg.php');
			foreach($v as $f){
				if($f['fieldstype']=='varchar' || $f['fieldstype']=='files' || $f['fieldstype']=='select'){$ns=$this->sysParams($f['fields'],1);}
				if($f['fieldstype']=='int'){$ns=$this->sysParams($f['fields']);}
				if($f['fieldstype']=='decimal'){$ns=$this->sysParams($f['fields'],3);}
				if($f['fieldstype']=='text'){$ns=$this->sysParams($f['fields'],4);}
				if($f['fieldstype']=='time'){$ns=strtotime($this->sysParams($f['fields'],1));}
				if($f['fieldstype']=='fileall'){
					$fieldsall=$this->sysParams($f['fields'].'file',2);
					if($fieldsall){
						$txt=$this->sysParams($f['fields'].'txt',2);$ns='';
						foreach($fieldsall as $k=>$v){
							$ns.='|-|'.$v.'|,|'.$txt[$k];
						}
						$ns=substr($ns,3);
					}
				}
				if($f['fieldstype']=='checkbox'){if($this->sysParams($f['fields'],2)){$ns='|'.implode('|',$this->sysParams($f['fields'],2)).'|';}else{$ns='';}}
				$n=array($f['fields'] => $ns);
				$this->newrow2=array_merge($this->newrow2,$n);
			}
		}
	}
	function index(){
		$this->toptxt=$this->moldname.'列表';
		$this->isshow=$this->sysParams('isshow',1);
		if($this->isshow==1){
			$this->toptxt='已审'.$this->toptxt;
			$conditions.="and isshow=1 ";
		}
		if($this->isshow==2){
			$this->toptxt='待审'.$this->toptxt;
			$conditions.="and isshow=0 ";
		}
		if($_SESSION['auser']['level']==1){
			if($this->sysParams("tid")){$conditions.= "and tid in(".$this->types->leafid($this->sysParams('tid')).") ";}
		}else{
			if($this->sysParams("tid") && $this->auser->checkclass($this->sysParams("tid"))){$conditions.= "and tid in(".$this->types->leafid($this->sysParams('tid')).") and tid in(".trim($_SESSION['auser']['pclasstype'],',').") ";}
			else{if($this->auser->checkclass()==false)message_a("您没有栏目权限");$conditions.= "and tid in(".trim($_SESSION['auser']['pclasstype'],',').") ";}
		}
		if($this->sysParams("sid")){$conditions.= "and sid=".$this->sysParams('sid')." ";}
		if($this->sysParams("trait")){$conditions.= "and trait like '%,".$this->sysParams('trait').",%' ";}
		if($this->sysParams("litpic")){
			if($this->sysParams("litpic")==1){
				$conditions.="and litpic!='' ";}else{$conditions.= "and litpic='' ";
				}
		}
		if($this->sysParams("title",1)){$conditions.= "and title like '%".$this->sysParams('title',1)."%' ";}
		if($conditions!=''){$conditions=' where '.substr($conditions,3);}
		$sql='select * from '.$this->sqldb.$conditions.' order by orders desc,addtime desc,id desc';
		$this->listarray = $this->ClassADD->syPager($this->gopage,15)->findSql($sql); 
		$this->pages = pagetxt($this->ClassADD->syPager()->getPager());
		$this->display($this->molds.".html");
	}
	function getlitpic($rows)
	{	
		global $iConfig;
		return  $iConfig['ext']['http_path'].$iConfig['ext']['site_logo'];
		if(!empty($rows['litpic']))
		{
			return $rows['litpic'];
		}
		if(!empty($iConfig['ext']['http_path']))
		{
			return $iConfig['ext']['site_logo'];
		}
		return false;
	}
	
	function add(){
		global $iConfig;
		$this->itid=$this->sysParams('tid');
		if ($this->sysParams('run')==1){
			if(!$this->auser->checkclass($this->newrow1['tid'])){message_a("无权操作本栏目内容");}
			$newVerifier=$this->ClassADD->syVerifier($this->newrow1);
				if(false == $newVerifier){
					$addnewrow1=$this->ClassADD->create($this->newrow1);
					if($addnewrow1==FALSE){message_a("主表数据写入失败，请重新提交");}
					$arrays = array(
						'aid' => $addnewrow1,
					);
					if($this->sysParams('all_down_images')==1){
						$upall=syClass('syupload');
						if(!get_magic_quotes_gpc()){$bodynew=$this->newrow2['body'];}else{$bodynew=stripslashes($this->newrow2['body']);}
						preg_match_all('/<img.*?src=[\'|\"](.*?)[\'|\"].*?\/>/si',$bodynew,$pic);
						$pic=array_unique($pic[1]);
						foreach($pic as $v){
							$localUrl=$upall->saveRemoteImg(trim($v));
							if($localUrl){$bodynew=str_ireplace($v,$GLOBALS['WWW'].$localUrl,$bodynew);}
						}
						$arrays=array_merge($arrays,array('body'=>$bodynew));
					}
					$this->newrow2=array_merge($this->newrow2,$arrays);
					if(syDB($this->molds.'_field')->create($this->newrow2)){
						if(func_get_iglobal(array('rewrite','rewrite_open'))!=1&&syExt('site_html')==1&&$this->newrow1['isshow']==1&&$this->newrow1['mrank']==0&&$this->newrow1['mgold']==0){
						$c_html_f = html_dir_rules($this->newrow1['tid'], $addnewrow1, $this->newrow1 ['htmlfile'] );
							syDB($this->molds)->updateField(array('id'=>$addnewrow1),'htmlurl',$c_html_f);
							$this->chtml->c_molds('product',array('id'=>$addnewrow1),$c_html_f);
							$body=array_filter(explode("[i|page]",$this->newrow2['body']));
							$allb=count($body);
							if($allb>1){
								for ($i = 1; $i <= $allb; $i++) {
									if($i>1){
									$this->chtml->c_molds('product',array('id'=>$addnewrow1,'page'=>$i),str_replace('.',$i.'.',$c_html_f));
									}
								}
							}
						}
						deleteDir(func_get_iglobal(array('sp_cache')));
						$litpic=$this->getlitpic($this->newrow1);
							/**
							 * 添加一个QQ分享
							 * Enter description here ...
							 * @param array $content 结构
								$content=array();
								$content['title']="东莞蓝鼎网智能建站系统ICMS盛世推出";
								$content['url']="http://www.5545.cn/icms/";
								$content['comment']="好东西分享一下";
								$content['summary']="超过1W企业选择我们;相信大家没有错的；第一个社区营销类建站系统";
								$content['images']="http://www.5545.cn/icms/template/other/images//logo.gif";
								$content['nswb']="1";
							 */
							$content = array ();
							$content ['title'] = $this->newrow1 ['title']; // "东莞蓝鼎网智能建站系统ICMS盛世推出";
							$content ['url'] =$GLOBALS['iConfig']['ext'] ['http_path'] . '/index.php?c=product&id=' . $addnewrow1; // "http://www.5545.cn/icms/";
							$content ['comment'] =$GLOBALS['iConfig']['ext']['site_title']."新增产品".$this->newrow1 ['title']."发布新产品";//
							$content ['summary'] = isset ( $this->newrow1 ['description'] ) ? $this->newrow1 ['description'] : substr ( $this->newrow1 ['body'], 0, 200 ); // "超过1W企业选择我们;相信大家没有错的；第一个社区营销类建站系统";
							if (isset ( $this->newrow1 ['litpic'] )) {
								$content ['images'] = "http://" . $_SERVER ['HTTP_HOST'] . "/" . $this->newrow1 ['litpic'];
							}
							$content ['nswb'] = "0";
							$this->share_qq($content);
							//-->同步微博开始：如果开启了同步微博则把内容同步到微博
							if($GLOBALS ['iConfig'] ['ext'] ['weibo_sync'] ==1){								
								require_once APP_PATH."/weibo/weibolist.php";							
								$status = array();							
								$title =$this->newrow1 ['title'];//标题	
								$word = $this->newrow1['description']. $this->newrow2['body'];//文章内容
								$status['content'] =$iConfig['ext']['site_title']."【新增产品" .$title."】".$word;
								 if($litpic!==false)$status['images'] = $litpic;
								weibo_add($status);									
							}//<--同步微博结束
						message_a($this->moldname.'添加成功','?c=ld_'.$this->molds,'<a href="?c=ld_'.$this->molds.'">返回列表</a><a href="?c=ld_'.$this->molds.'&a=add&tid='.$this->newrow1['tid'].'">继续添加</a>',"8");
					}else{
						syDB($this->molds)->delete(array('id'=>$addnewrow1));
						message_a("附表数据写入失败，请重新提交");
					}
				}else{message_b($newVerifier);}
		}
		$this->toptxt='添加'.$this->moldname;
		$this->postgo='add';
		$this->display($this->molds."_edit.html");
	}
	function edit(){
		global $iConfig;
		$this->carray=$this->ClassADD->findSql('select * from '.$this->sqldb.' a left join '.$this->sqldb.'_field b on (a.id=b.aid) where id='.$this->sysParams('id').' limit 0,1');
		$this->carray=$this->carray[0];
		if(!$this->auser->checkclass($this->carray['tid'])){message_a("无权操作本栏目内容");}
		if ($this->sysParams('run')==1){
			$newVerifier=$this->ClassADD->syVerifier($this->newrow1);
				if(false == $newVerifier){
					if($this->ClassADD->update(array('id'=>$this->sysParams('id')),$this->newrow1)==FALSE)
					{message_a("主表数据修改失败，请重新提交");}
					if($this->sysParams('all_down_images')==1){
						$upall=syClass('syupload');
						if(!get_magic_quotes_gpc()){$bodynew=$this->newrow2['body'];}else{$bodynew=stripslashes($this->newrow2['body']);}
						preg_match_all('/<img.*?src=[\'|\"](.*?)[\'|\"].*?\/>/si',$bodynew,$pic);
						$pic=array_unique($pic[1]);
						foreach($pic as $v){
							$localUrl=$upall->saveRemoteImg(trim($v));
							if($localUrl){$bodynew=str_ireplace($v,$GLOBALS['WWW'].$localUrl,$bodynew);}
						}
						$this->newrow2=array_merge($this->newrow2,array('body'=>$bodynew));
					}
					if(!syDB($this->molds.'_field')->find(array('aid'=>$this->sysParams('id')))){
						$this->newrow2=array_merge($this->newrow2,array('aid'=>$this->sysParams('id')));
						$edit_field=syDB($this->molds.'_field')->create($this->newrow2);
					}else{
						$edit_field=syDB($this->molds.'_field')->update(array('aid'=>$this->sysParams('id')),$this->newrow2);
					}
					if($edit_field){
						if(func_get_iglobal(array('rewrite','rewrite_open'))!=1&&syExt('site_html')==1&&$this->newrow1['isshow']==1&&$this->newrow1['mrank']==0&&$this->newrow1['mgold']==0){
							$c_html_f = html_dir_rules($this->newrow1['tid'], $this->sysParams('id'), $this->newrow1 ['htmlfile'] );
							syDB($this->molds)->updateField(array('id'=>$addnewrow1),'htmlurl',$c_html_f);
							syDB($this->molds)->updateField(array('id'=>$this->sysParams('id')),'htmlurl',$c_html_f);
							$this->chtml->c_molds('product',array('id'=>$this->sysParams('id')),$c_html_f);
							$body=array_filter(explode("[i|page]",$this->newrow2['body']));
							$allb=count($body);
							if($allb>1){
								for ($i = 1; $i <= $allb; $i++) {
									if($i>1){
									$this->chtml->c_molds('product',array('id'=>$this->sysParams('id'),'page'=>$i),str_replace('.',$i.'.',$c_html_f));
									}
								}
							}
						}
						deleteDir(func_get_iglobal(array('sp_cache')));
						$litpic=$this->getlitpic($this->newrow1);
						/**
							 * 添加一个QQ分享
							 * Enter description here ...
							 * @param array $content 结构
								$content=array();
								$content['title']="东莞蓝鼎网智能建站系统ICMS盛世推出";
								$content['url']="http://www.5545.cn/icms/";
								$content['comment']="好东西分享一下";
								$content['summary']="超过1W企业选择我们;相信大家没有错的；第一个社区营销类建站系统";
								$content['images']="http://www.5545.cn/icms/template/other/images//logo.gif";
								$content['nswb']="1";
							 */
							$content = array ();
							$content ['title'] = $this->newrow1 ['title']; // "东莞蓝鼎网智能建站系统ICMS盛世推出";
							$content ['url'] =$GLOBALS['iConfig']['ext'] ['http_path'] . '/index.php?c=product&id=' . $addnewrow1; // "http://www.5545.cn/icms/";
							$content ['comment'] =$GLOBALS['iConfig']['ext']['site_title']."修改产品".$this->newrow1 ['title']."发布新产品";//
							$content ['summary'] = isset ( $this->newrow1 ['description'] ) ? $this->newrow1 ['description'] : substr ( $this->newrow1 ['body'], 0, 200 ); // "超过1W企业选择我们;相信大家没有错的；第一个社区营销类建站系统";
							if (isset ( $this->newrow1 ['litpic'] )) {
								$content ['images'] = "http://" . $_SERVER ['HTTP_HOST'] . "/" . $this->newrow1 ['litpic'];
							}
							$content ['nswb'] = "0";
							$this->share_qq($content);
							//-->同步微博开始：如果开启了同步微博则把内容同步到微博
							if($GLOBALS ['iConfig'] ['ext'] ['weibo_sync'] ==1){								
								require_once APP_PATH."/weibo/weibolist.php";							
								$status = array();							
								$title =$this->newrow1 ['title'];//标题	
								$word =$this->newrow1['description'].$this->newrow2['body'];//文章内容 $this->newrow2['body'];//文章内容
								$status['content'] =$iConfig['ext']['site_title']."【修改产品" .$title."】".$word;
								 if($litpic!==false)$status['images'] = $litpic;
								weibo_add($status);									
							}//<--同步微博结束
						message_a($this->moldname."修改成功","?c=ld_".$this->molds);
					}else{message_a("附表数据修改失败，请重新提交");}
				}else{message_b($newVerifier);}
		}
		$this->traits=syDB('traits')->findAll(array('molds'=>$this->molds));
		$this->toptxt=$this->moldname.'修改内容';
		$this->postgo='edit';
		$this->display($this->molds."_edit.html");
	}
	function del(){
		$this->toptxt=$this->moldname.'删除内容';
		$this->del=$this->ClassADD->find(array('id'=>$this->sysParams('id')));
		if(!$this->auser->checkclass($this->del['tid'])){message_a("无权操作本栏目内容");}
		$id=$this->del['id'];
		if ($this->sysParams('run')==1){
			if(syDB($this->molds)->delete(array('id'=>$id))&&syDB($this->molds.'_field')->delete(array('aid'=>$id))){
				deleteDir(func_get_iglobal(array('sp_cache')));
				message_a("删除成功","?c=ld_".$this->molds);
			}else{message_a("删除失败,请重新提交");}
		}
		$this->msgtitle='确定要删除 <strong>['.$this->del['title'].']</strong> 吗？';
		$this->msg='';
		$this->msggo='<a href="?c=ld_'.$this->molds.'&a=del&run=1&id='.$id.'">确定删除</a><a href="?c=ld_'.$this->molds.'">取消操作</a>';
		$this->display("msg.html");
	}
	function alledit(){
		if($this->sysParams('ids',2)===NULL || $this->sysParams('go')===NULL){message_a("请选择操作对象");}
		if($this->sysParams('run')==1){
			$ids=explode(',',$this->sysParams('ids',1));
			switch ($this->sysParams('go')) {
				case 0:
					foreach($ids as $tp){
						$a=$this->ClassADD->find(array('id'=>$tp), null, " id,tid ");
						if($this->auser->checkclass($a['tid']))$this->ClassADD->update(array('id'=>$tp),array('isshow'=>1));
					}
					$this->jump("?c=ld_".$this->molds);
					break;
				case 1:
					foreach($ids as $tp){
						$a=$this->ClassADD->find(array('id'=>$tp), null, " id,tid ");
						if($this->auser->checkclass($a['tid']))$this->ClassADD->update(array('id'=>$tp),array('isshow'=>0));
					}
					$this->jump("?c=ld_".$this->molds);
					break;
				case 2:
					foreach($ids as $tp){
						$a=$this->ClassADD->find(array('id'=>$tp), null, " id,tid ");
						if($this->auser->checkclass($a['tid'])){
							syDB($this->molds)->delete(array('id'=>$tp));
							syDB($this->molds.'_field')->delete(array('aid'=>$tp));
						}
					}
					$this->jump("?c=ld_".$this->molds);
					break;
				case 3:
					foreach($ids as $tp){
						$a=$this->ClassADD->find(array('id'=>$tp), null, " id,tid ");
						if($this->auser->checkclass($a['tid']))$this->ClassADD->update(array('id'=>$tp),array('tid'=>$this->sysParams('tid')));
					}
					$this->jump("?c=ld_".$this->molds);
					break;
			}
			deleteDir(func_get_iglobal(array('sp_cache')));
		}
		if($this->sysParams('go')==0)$txt='审核';
		if($this->sysParams('go')==1)$txt='取消审核';
		if($this->sysParams('go')==2)$txt='删除';
		if($this->sysParams('go')==3)$txt='移动';
		$this->toptxt='批量'.$txt.$this->moldname.'内容';
		$ids=implode(',',$this->sysParams('ids',2));
		$this->msgtitle='确定要'.$txt.'这些'.$this->moldname.'内容吗？';
		$this->msg='本操作将批量'.$txt.'ID为['.$ids.']的内容<br>';
		$this->msggo='<a href="?c=ld_'.$this->molds.'&a=alledit&run=1&ids='.$ids.'&go='.$this->sysParams('go').'&tid='.$this->sysParams('tid').'">确定'.$toptxt.'</a><a href="?c=ld_'.$this->molds.'">取消操作</a>';
		$this->display("msg.html");
	}
	
	public function agentimgsize($max_width,$max_height,$imgFile,$newFilePrev = '')
	{
		$imgFile = str_replace('\\',DIRECTORY_SEPARATOR,$imgFile);
		$imgFile = str_replace('/',DIRECTORY_SEPARATOR,$imgFile);

		$newFilePrev = $newFilePrev == ''?'small':$newFilePrev;
		$size = getimagesize($imgFile);   //得到图像的大小
		$width = $size[0]; //原图宽
		$height = $size[1];//原图高
		
		$x_ratio = $max_width / $width;
		$y_ratio = $max_height / $height;
		
		if (($width <= $max_width) && ($height <= $max_height))
		{
			$tn_width = $width;
			$tn_height = $height;
		}
		elseif (($x_ratio * $height) < $max_height)
		{
			$tn_height = ceil($x_ratio * $height);
			$tn_width = $max_width;
		}
		else 
		{
			$tn_width = ceil($y_ratio * $width);
			$tn_height = $max_height;
		}
		
		$newfile = str_replace(basename($imgFile),'',$imgFile).$newFilePrev.basename($imgFile);//新文件名
		
		$im = imagecreatetruecolor($tn_width, $tn_height); //新建一个真彩色图像

		$imgtype = strtolower(end(explode('.', $newfile)));

		if ($imgtype == 'jpg' || $imgtype == 'jpeg')
		{
			
			$src = imagecreatefromjpeg($imgFile);
			imagecopyresampled($im, $src, 0, 0, 0, 0,$tn_width, $tn_height, $width, $height);
			imagejpeg($im,$newfile);

		}else if ($imgtype == 'png'){

			$src = imagecreatefrompng($imgFile);
			imagecopyresampled($im, $src, 0, 0, 0, 0,$tn_width, $tn_height, $width, $height);
			imagepng($im,$newfile);

		}else if($imgtype == 'gif') {

			$src = imagecreatefromgig($imgFile);
			imagecopyresampled($im, $src, 0, 0, 0, 0,$tn_width, $tn_height, $width, $height);
			imagegif($im,$newfile,100);
		}
	}
}	