<?php
/*
	[Phpup.Net!] (C)2009-2011 Phpup.net.
	This is NOT a freeware, use is subject to license terms

	$Id: common.php 2010-08-24 10:42 $
*/

if(!defined('IN_PHPUP')) {
	exit('Access Denied');
}
class attach
{
	/**
	 * 初始化
	 *
	 * @param string $content
	 * @param array $site
	 */
	public function attach($site=array())
	{
		include ROOT_PATH.'/inc/curl.class.php';
		$this->curl=new curl();
		$this->site=$site;
		
	}

	//规则
	public function parse_rule($content,$apirule)
	{
		$temp_rule = explode('=', $apirule);
		$rule = $temp_rule[1];
		$tmp = explode('-', $temp_rule[0]);
		$content=trim($content);
		$content=str_replace("\n","",$content);
		$content=str_replace("\t","",$content);
		$content=str_replace("&","shift7",$content);
		$node=new SimpleXMLElement($content);
		
		unset($tmp[0]);
		foreach ($tmp as $r)
		{
			$node = $node->$r;
		
		}
		$data = array();
		$total = count($node);
		
		if ($total <= 0)
		{
			return false;
		}
		
		for($i = 0; $i < $total; $i++)
		{
			$fields = explode(',', $rule);
			foreach ($fields as $row)
			{
				$tmp = explode(':', $row);
				
				$local_field_name = $tmp[0];
				$local_field_struct = $tmp[1];
				$struct = str_replace('limengqikey', '(string)$node[' . $i . ']', $local_field_struct);
				
				$struct = '$tmp_data = ' . str_replace('-', '->', $struct) . ';';
				
				eval($struct);
				
				$data[$i][$local_field_name] = str_replace('shift7','&',$tmp_data);
				
			}
		}
		return $data;
	}
	//根据规则得到城市列表
	public function parse_city($limitcity=true,$focus=false)
	{
		$content='';
		
		if(!empty($this->site['cityapi']) && !empty($this->site['cityrep']) && !empty($this->site['citysiteapi']))
		{
			$content=$this->curl->get($this->site['cityapi']);
		}
		elseif($focus)
		{
			$content=$this->curl->get($this->site['cityapi']);
		}
		else
		{
			return array();
		}
		
		$apirule=$this->site['cityrep'];
		$data=$this->parse_rule($content,$apirule);
		if(!empty($this->site['limitcity']))
		{
			$mylimit=$this->site['limitcity'];
		}
		elseif(!empty($GLOBALS['setting']['site_limit_citys']))
		{
			$mylimit=$GLOBALS['setting']['site_limit_citys'];
		}
		if($limitcity)
		{
			if($mylimit)
			{
				foreach($data as $k=>$v)
				{
					if(strpos('-'.$mylimit,$v['cityname']))
					{
						$citys[]=$v;
					}
				}
				unset($data);
				return $citys;
			}
			else
			{
				return $data;
			}
		}
		return $data;
	}
	//分析多城市api
	public function parse_cityapi($cityrule=array('cityid'=>'','cityname'=>''))
	{
		if(strpos($this->site['citysiteapi'],'+')>0 && (!empty($cityrule['cityid']) || !empty($cityrule['cityname']))) //根据规则得到多城市采集api
		{
			$siteapi=str_replace('http://','',$this->site['citysiteapi']);
			$siteapi=str_replace('+cityid+',$cityrule['cityid'],$siteapi);
			$siteapi=str_replace('+cityname+',urlencode($cityrule['cityname']),$siteapi);
		}
		elseif(!empty($this->site['localapi']) && is_file(ROOT_PATH.'/'.$this->site['localapi']))
		{
			$siteapi=str_replace('http://','',SITE_ROOT).'/'.$this->site['localapi'];
		}
		elseif(!empty($this->site['siteapi']))
		{
			$siteapi=str_replace('http://','',$this->site['siteapi']);
		}
		else
		{
			return false;
		}
		return 'http://'.$siteapi;
	}
	/**
	 * 根据规则解析接口数据
	 *
	 */
	public function parse_group($siteapi='')
	{
		$content='';
		$data=array();
		$citys=false;
		
		if(!empty($siteapi))
		{
			$content=$this->curl->get($siteapi);
		}
		else
		{
			return false;
		}
		
		$apikey=!empty($this->site['apikey'])?$GLOBALS['apirep'][$this->site['apikey']][1]:$this->site['apirep'];
		
		if(!empty($apikey))
		{
			
			$mydata=$this->parse_rule($content,$apikey);
			
			if(strpos($this->site['citysiteapi'],'+')>0 && !empty($this->site['cityrep']) && !empty($this->site['cityapi'])) //根据规则得到多城市采集api
			{
				$citys=true;
			}
			if($citys)
			{
				$j=0;
				foreach($mydata as $i=>$v)
				{
					if($this->site['limitnum']>0 && $j>=$this->site['limitnum'])
					{
						break;
					}
					$data[$i]=$this->process_fields($v);
					
					if (empty($data[$i]['subject']) || $data[$i]['lasttime']<time())
					{
						unset($data[$i]);
					}
					
					$j++;
				}
			}
			else
			{
				if(!empty($this->site['limitcity']))
				{
					$limitcity='-'.$this->site['limitcity'];
					if($this->site['limitnum']>0)
					{
						$limitcity_arr= explode(",",$this->site['limitcity']);
						$citynum_arr= array();
						foreach($limitcity_arr AS $key_city => $val_city)
						{
							$citynum_arr[$val_city] = 0;	
						}
						foreach($mydata as $i=>$v)
						{
							$lcityname=charset_encode($v['cityname'],$GLOBALS['charset']);
							if($citynum_arr[$lcityname] < $this->site['limitnum'] && strpos($limitcity,$lcityname) )
							{
								$data[$i]=$this->process_fields($v);			
								if (empty($data[$i]['subject']) || $data[$i]['lasttime']<time())
								{
									unset($data[$i]);
								}	
								$citynum_arr[$lcityname]++;
							}
						}
					}
					else
					{
						foreach($mydata as $i=>$v)
						{
							$v['cityname']=charset_encode($v['cityname'],$GLOBALS['charset']);
							if( strpos($limitcity,$v['cityname']))
							{
								$data[$i]=$this->process_fields($v);			
								if (empty($data[$i]['subject']) || $data[$i]['lasttime']<time())
								{
									unset($data[$i]);
								}					
							}

						}
					}
				}
				else
				{
					if($this->site['limitnum']>0)
					{
						$citynum_arr= array();
						
						foreach($GLOBALS['city'] AS $key_city => $val_city)
						{
							$citynum_arr[$val_city['cityname']] = 0;	
						}
						foreach($mydata as $i=>$v)
						{
							$lcityname=charset_encode($v['cityname'],$GLOBALS['charset']);
							if($citynum_arr[$lcityname] < $this->site['limitnum'] && in_array($lcityname,array_keys($citynum_arr)) )
							{
								$data[$i]=$this->process_fields($v);	
								if (empty($data[$i]['subject']) || $data[$i]['lasttime']<time())
								{
									unset($data[$i]);
								}	
								$citynum_arr[$lcityname]++;
							}
						}
					}
					else
					{
						foreach($mydata as $i=>$v)
						{
							$data[$i]=$this->process_fields($v);
							
							if (empty($data[$i]['subject']) || $data[$i]['lasttime']<time())
							{
								unset($data[$i]);
							}
						}
					}
				}
			}
			if(!empty($this->site['gather_method']) && $this->site['goodorder']>0 && $this->site['gather_method']!='all')
			{
				if($this->site['gather_method']=='last')
				{
					krsort($data);
				}
				foreach($data as $j=>$v)
				{
					if(!isset($sort[$data[$j]['siteid']][$data[$j]['cityid']]))
					{
						$data[$j]['sortorder']=$this->site['goodorder'];
						
						$sort[$data[$j]['siteid']][$data[$j]['cityid']]=1;
					}
				}
			}
			if($this->site['gather_method']=='last')
			{
				ksort($data);
			}
			
			
			return $data;
		}
		return false;
	}
	public function insert_temp_table($data = array(), $type = 'nav')
	{
		$id=0;
		if (empty($data))
		{
			return false;
		}
		else
		{
			$data=array_values($data);
			$fields='`'.implode('`,`',array_keys($data[0])).'`';
			$count=count($data);
			$all =ceil($count/200);
			
			for($i=0;$i<$all;$i++)
			{
				$start=$i*200;
				$last=($i+1)*200>$count?$count:($i+1)*200;
				for($j=$start;$j<$last;$j++)
				{
					$linedata[]='"'.implode('","',$data[$j]).'"';
				}
				$sql="replace into ".tname('tempsite')."(".$fields.") values(".implode("),(",$linedata).");\n";
				
				$id=$GLOBALS['db']->query($sql);
				if($id)
				{
					$GLOBALS['db']->query("update ".tname('site')." set localapi='' where id=".$this->site['id']);
					@unlink(ROOT_PATH.'/'.$this->site['localapi']);
				}
				$linedata=array();
			}
			return $id;
		}
	}
	/**
	 * 处理解析后的字段数据
	 *
	 * @param array $data
	*/
	private function process_fields($data = array())
	{
		if (empty($data['subject']))
		{
			return array();
		}
		/*
		if (isset($GLOBALS['cfg']['site_gather_single_city']) && !empty($GLOBALS['cfg']['site_gather_single_city']))
		{
			$allow_citys = explode(',', $GLOBALS['cfg']['site_gather_single_city']);
			$is_correct = false;
			foreach ($allow_citys as $allow_city)
			{
				$allow_city = $this->city_data[$allow_city];
				if (($data['cityname'] == $allow_city) || mb_stripos($data['cityname'], $allow_city) !== false)
				{
					$is_correct = true;
					continue;
				}
			}
			if (!$is_correct)
			{
				return false;
			}
		}
		*/
		$data['subject']=global_addslashes(str_replace("\n","",charset_encode($data['subject'],$GLOBALS['charset'],'utf-8')));
		$data['groupsite'] = $this->site['sitename'];
		$data['sortorder']=0;
		if (!isset($data['shortsubject']))
		{
			$data['shortsubject'] = global_addslashes(sysSubStr($data['subject'], 15));
		}
		if (empty($data['cityname']))
		{
			$data['cityname'] = '全国';
			
		}
		
		if (!isset($data['cityid']))
		{
			if (empty($data['cityname']))
			{
				$data['cityname'] = '全国';
				$data['cityid']='quanguo';
			}
			else
			{
				$cityname=explode(',',$data['cityname']);
				$data['citysname']=charset_encode($data['cityname'],$GLOBALS['charset'],'utf-8');
				$data['cityname']=charset_encode($cityname[0],$GLOBALS['charset'],'utf-8');
				$data['cityid'] = Pinyin($data['cityname'],$GLOBALS['charset']);
			}
			
		}
		if (isset($data['starttime']))
		{
			if (strlen($data['starttime']) == 14)
			{
				$data['starttime'] = mysql_to_unix($data['starttime']);
			}
			else if (stripos($data['starttime'], '+') !== false)
			{
				$data['starttime'] = strtotime($data['starttime']);
			}
			else if (stripos($data['starttime'], '-') !== false && strlen($data['starttime']) == 19)
			{
				$data['starttime'] = mysql_to_unix($data['starttime']);
			}
		}
		
		if (isset($data['lasttime']))
		{
			$data['lasttime'] = trim($data['lasttime']);
			if (strlen($data['lasttime']) == 14)
			{
				$data['lasttime'] = mysql_to_unix($data['lasttime']);
			}
			else if (stripos($data['lasttime'], '+') !== false)
			{
				$data['lasttime'] = strtotime($data['lasttime']);
			}
			else if (stripos($data['lasttime'], '-') !== false && strlen($data['lasttime']) == 19)
			{
				$data['lasttime'] = mysql_to_unix($data['lasttime']);
			}
		}
		if(isset($data['thumb']) && $GLOBALS['setting']['site_allow_remote'])
		{

		}
		if (!isset($data['big_catelist']))
		{
			$data['big_catelist'] = 0;
		}
		if (!empty($data['bizname']))
		{
			$data['bizname'] = charset_encode($data['bizname'],$GLOBALS['charset'],'utf-8');
		}
		if(!empty($this->site['gather_method']) && $this->site['goodorder']>0)
		{
			if($this->site['gather_method']=='all')
			{
				$data['sortorder']=$this->site['goodorder'];
			}
		}
		
		
		if (!isset($data['big_catelist_catename']))
		{
			$data['big_catelist_catename'] = '';
		}
		
		
		if (!isset($data['recommend']))
		{
			$data['recommend'] = 0;
		}
		if (!isset($data['keyword']))
		{
			$data['keyword'] = '';
		}
		if (empty($data['nowpeople']))
		{
			$data['nowpeople'] = 0;
		}
		$data['oldprice'] = floatval($data['oldprice']);
		$data['nowprice'] = floatval($data['nowprice']);
		if (!isset($data['discount']))
		{
			if ($data['oldprice'] == 0 || $data['nowprice'] == 0)
			{
				$data['discount'] = $data['oldprice'];
			}
			else
			{
				$data['discount'] = round(($data['nowprice']*100 / $data['oldprice'])/10,1);
			}
		}
		$data['siteid'] = $this->site['id'];
		$data['groupkey']=md5(trim(strip_tags($data['subject'])).intval($data['siteid']).$data['cityid']);
		$data['updatetime'] = time();
		
		
		return $data;
	}
	
}
