<?php

/********** Hock **********/

function ad_naver(){
	global $Modules;
	global $appid;
	return '<a href="'.readpath(GetHost().VI_BASE.'/module/adsview/content/').'">'.$Modules["adsview"]["search"]["title"].'</a>';
}

/********** Func **********/

/*
	生成广告缓存
	$tag	广告关键字,用于搜索广告
	$save	是否缓存数据
*/
function ad_create($sql,$mysql,$tag="",$save=true,$charset=''){
	global $Modules;
	global $Project;
	
	//读取数据
	$result=mysql_query($sql,$mysql);
	
	//VeryIDE 绝对地址
	$HOT = GetHost();
	
	//广告请求目录 URL
	//$API = readpath($HOT.VI_BASE.$Modules["adsview"]["path"]);
	
	//广告主JS
	$MGR = readpath($HOT.VI_BASE."/module/adsview/".$Modules["adsview"]["manager"]);
	
	//当前位置
	$address = '';
	
	//遍历广告位
	while( $area = mysql_fetch_assoc($result) ){
	
		//缓存目录
		$base	= VI_ROOT."module/adsview/content/cache/";

		//缓存JS
		$js		= $base .strtolower($area["key"]) .".js";
		
		//缓存内容
		$script = '/* '. date("Y-m-d H:i:s") .' */
if(typeof VAD == "undefined"){
	document.write(\'<span style="color:red" onclick="alert(&quot;'.$MGR.'&quot;);">VAD Halt!</span>\');
}else{	
	'.ad_area( $API, $area ).( $area["variable"] ? str_replace('{SELF}','_ad'.$area["id"].'',UnFilterHtml($area["variable"])):'');
	
	/*
	
	
  VAD.API="'.$API.'";
	var _ad'.$area["id"].' = new VAD.adLoad({ "key":"'.$area["key"].'", "id":'.$area["id"].', "name":"'.$area["name"].'", "show":'.$area["show"].', "number":'.$area["number"].',"width":'.$area["width"].', "height":'.$area["height"].', "price":'.$area["price"].', "unit":"'.$area["unit"].'", "tag":"'.$area["tag"].'", "config":'.($area["config"]?$area["config"]:'{}').'});
	
	*/
	
	
		//生成广告JS
		
		//遍历广告
		
		//$sql="SELECT * FROM ".VI_DBMODPRE."adsview where status>0 and status<3 and name<>'' and ( type=".$area["id"]." or ".$area["id"]." in(share) ) and start<=".time()." and expire>".time()." ";
		
		$sql="SELECT * FROM ".VI_DBMODPRE."adsview where status>0 and status<3 and name<>'' and ( type=".$area["id"]." or CONCAT(',',share) like '%,".$area["id"].",%' ) and start<=".time()." and expire>".time();
		
		//搜索广告
		if( $tag ){
			$keysql=str_replace(" ","%' or tags like '%",$tag);
			$sql.=" and ( tags like '%".$keysql."%' )";
		}
		
		//排序广告
		$sql.=" order by sort asc,id desc";

		//随机广告不限制数量
		if( $area["show"]!=2 && $save ){
			$sql.=" limit 0,".$area["number"];
		}
		
		$result2=mysql_query($sql,$mysql);
		
		//广告数量
		$i = 0;
		
		while($ad=mysql_fetch_assoc($result2)){

			$config = json_decode($ad["config"],true);
			
			//地区限制
			if($ad["zone"] && !$save){
				
				//查询位置
				if(!$address){
				
					require_once(dirname(__FILE__)."/../include/client.php");
			
					//当前位置
					//$address = convertip('123.114.20.52');
					$address = convertip(GetIP());
					//$address = convertip_full(GetIP(),dirname(__FILE__).'/../../source/ipdata.dat');
					
					if(@file_exists(dirname(__FILE__).'/../source/wry.dat') && $Project["charset"] != "gbk"){
						$address = iconv("gbk",$Project["charset"],$address);
					}else{
						if($Project["charset"] != "utf-8"){
							$address = iconv("utf-8",$Project["charset"],$address);
						}
					}
				}
				
				//echo $address;
				$script .= chr(10).'/* 所在地:'.$address.' */'.chr(10);
				
				//未找到
				$find = false;
				
				$array = explode(',',$ad["zone"]);
				
				for($a=0; $a<count($array); $a++){
					//echo "strpos($address,".trim($array[$a]).")";
					
					if( strpos($address,trim($array[$a])) !== false ){
						//找到了
						$find = true;
						//break;
					}
				}
				
				//未找到
				if(!$find){
					//echo '未找到';
					$script .= chr(10).'/* 不在所在地区 */'.chr(10);
					//break;
				}
			}else{
				$find = true;
			}
			
			if($find){
			
				//转换图片地址
				if($ad["file"] && stripos($ad["file"],"://") === false){
					$ad["file"] = str_replace("/../","/",$HOT.$ad["file"]);		
				}
				
				$script .= ad_script($API,$area,$ad,$config);
				
				$i++;
			}
		}
		
		$script.=chr(10).'/* 匹配'.$i.'条 */'.chr(10);
		
		//默认广告
		if( $i < $area["number"] ){
		
			//生成JS
			$spare = "";
			$temp = "";
			
			$sql="SELECT * FROM ".VI_DBMODPRE."adsview where status>0 and status<3 and type=".$area["id"]." and spare>0 order by id desc limit 0,1";
	
			$result2=mysql_query($sql,$mysql);
			
			if( mysql_num_rows($result2)==1 ){
				$ad = mysql_fetch_assoc($result2);
				
				$config = json_decode($ad["config"],true);
				
				//转换图片地址
				if($ad["file"] && stripos($ad["file"],"://") === false){					
					$ad["file"] = str_replace("/../","/",$HOT.$ad["file"]);		
				}
				
				$temp = ad_script($API,$area,$ad,$config);
				
			}
			
			//exit('/* 匹配'.$n.'='.$i.';'.($area["number"]-$i-1).'; '.$n.'++'.'条 */');
			
			//exit($i.'条');
			
			//exit( ($area["number"]-$i-1).'条' );

			//循环重复广告
			$n = $area["number"]-$i;
			if( $n>0 && $temp ){
				
				for( $x=0; $x < $n; $x++){
					$spare .= $temp;
					
					//echo $x;
					//echo '<br />';
				}
				
			}else{
				$spare .= $temp;	
			}
			
			//exit( $spare );
			
			/*
			for( $n=$i; $n < $area["number"]-$i-1; $n++){
				$spare .= $spare;
			}
			*/
			
			//累加到现有广告
			$script = $script . $spare;
		}
		
		//插入广告
		$script.='	_ad'.$area["id"].'.adInsert();'.chr(13)."}";
			
		//生成页面
		if($save){
			
			//创建根目录
			create_dir( $base );
		
			create_file($js,$script );
			
		}else{
		
			if($charset && $charset != $Project["charset"]){			
				$ad_str = iconv($Project["charset"],$charset,$script);				
			}
			
			return $script;
		}
	}	
}

/*
	广告位
	$API	API路径
	$area	广告位
*/
function ad_area( $API,$area ){

	//return 'VAD.API="'.$API.'";
	
	return 'var _ad'.$area["id"].' = new VAD.adLoad({ "key":"'.$area["key"].'", "id":'.$area["id"].', "name":"'.$area["name"].'", "show":'.$area["show"].', "number":'.$area["number"].',"width":'.$area["width"].', "height":'.$area["height"].', "price":"'.$area["price"].'", "unit":"'.$area["unit"].'", "tag":"'.$area["tag"].'", "config":'.($area["config"]?$area["config"]:'{}').'});';
}

/*
	广告
	$API	API路径
	$area	广告位
	$ad		广告
	$config	配置
*/
function ad_script($API,$area,$ad,$config){
	
	//代码广告
	if ( $ad["form"] ){
		$text = "	_ad".$area["id"].".adAdd({ 'id':".$ad["id"].", 'name':'".$ad["name"]."', 'file':'".$ad["file"]."', 'width':".$ad["width"].", 'height':".$ad["height"].", 'link':'".$ad["link"]."', 'target':'".$config["LINK-TARGET"]."', 'expire':'".$ad["expire"]."', 'views':'".$config['STAT-VIEWS']."', 'click':0, 'form':1, 'style':'', 'spare':".$ad["spare"].", 'time':'".$config["SHOW-TIME"]."', 'space':'".$config["SHOW-SPACE"]."'});
	";
		$script = str_replace('{LINK}',$API.'?action=click&id='.$ad["id"].'&url=',$ad["script"]);
		$script = str_replace('{VAR}','&variable=',$script);
		
		$text = $text.UnFilterHtml($script).chr(10);
		
	//普通广告
	}else{
		$text = "	_ad".$area["id"].".adAdd({ 'id':".$ad["id"].", 'name':'".$ad["name"]."', 'file':'".$ad["file"]."', 'width':".$ad["width"].", 'height':".$ad["height"].", 'link':'".$ad["link"]."', 'target':'".$config["LINK-TARGET"]."', 'expire':".$ad["expire"].", 'views':'".$config['STAT-VIEWS']."', 'click':'".$config['STAT-CLICK']."', 'form':0, 'style':'".$config["SHOW-STYLE"]."', 'spare':".$ad["spare"].", 'time':'".$config["SHOW-TIME"]."', 'space':'".$config["SHOW-SPACE"]."', 'tags':'".$ad["tags"]."'});
	";
	}
	
	return $text;	
	
}

//删除广告缓存
function ad_delete($sql,$mysql){
	global $Modules;
	
	//'读取数据
	$result=mysql_query($sql,$mysql);
	
	while($row=mysql_fetch_assoc($result)){
		$key=$row["key"];
		$id=$row["id"];
		$preview=$row["preview"];

		//删除JS
		$ad_file= $Modules["adsview"]["path"]. "/cache/" . strtolower($key) .".js";
		if(file_exists($ad_file)){
			@unlink($ad_file);
		}

		//删除预览图
		if($preview){
			if(function_exists("uploader_delete")){
				uploader_delete($preview,$mysql);
			}else{
				if(file_exists($preview)){
					@unlink($preview);
				}
			}
		}

		//删除广告记录
		$sql="SELECT file FROM ".VI_DBMODPRE."adsview where type=". $id;

		$result2=mysql_query($sql,$mysql);
		while($row2=mysql_fetch_assoc($result2)){
			$file=$row2["file"];
			
			//删除文件
			if($file){
				if(function_exists("uploader_delete")){
					uploader_delete($file,$mysql);
				}else{
					if(file_exists($file)){
						@unlink($file);
					}
				}
			}
		}
		
		//删除分类记录
		$sql="delete from ".VI_DBMODPRE."adsarea where id=". $id;
		mysql_query($sql,$mysql);
	}	
}
?>