<?php

class Adsview extends Module{

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

	public static function naver(){
		global $_G;
		global $appid;
		
		//加载配置
		require_once dirname(__FILE__) . '/setting.php';
		
		//如果需要关闭
		if( $_G['setting']['adsview']['hooks'] == 'off' || !file_exists(VI_ROOT."module/adsview/content/service.php") ) return;
			
		$link = $_G['setting']['adsview']['domain'] ? $_G['setting']['adsview']['domain'] : VI_HOST.'module/adsview/content/';
		
		return '<a href="'.$link.'">'.$_G['module']['adsview']['search']['title'].'</a>';
	}

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

	/*
		生成广告缓存
		$tag	广告关键字,用于搜索广告
		$save	是否缓存数据
	*/
	public static function create( $sql, $tag="", $save=true, $charset='' ){
		global $_G;
		global $_CACHE;
		
		//加载替补缓存
		Cached :: loader( 'adsview', 'table.alternate' );	
		
		////////////////////////////
		
		//读取数据
		$result = System :: $db -> getAll( $sql );
		
		//基准地址
		$HOT = url_fore();
		
		//当前位置
		$address = '';
		
		//访问目录
		$http = Module::get_index( 'adsview' );
		
		//缓存目录
		$base	= create_dir( VI_ROOT.'static/adsview/' );
		
		//遍历广告位
		foreach( $result as $area ){
			
			//替补列表
			$spare = array();
			foreach( $_CACHE['adsview']['alternate'] as $a ){
				if( $a['type'] == $area["id"] ){
					$spare[] = $a;
				}
			}
			
			//////////////////////////////

			//缓存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;'.$http.'adsview.js&quot;);">VAD Halt!</span>\');
	}else{	
		'. self :: area( $API, $area ).( $area["variable"] ? str_replace('{SELF}','_'.$area["id"].'_',UnFilterHtml($area["variable"])):'');
		
			//遍历待播广告		
			$sql="SELECT start FROM `mod:adsview` WHERE `state`>0 and ( type=".$area["id"]." or CONCAT(',',share) like '%,".$area["id"].",%' ) and start>".time();
			
			$rows = System :: $db -> getAll( $sql );
			
			$data = array();
			
			foreach( $rows as $row ){
				array_push( $data, $row['start'] );
			}
			
			$script .= "	_".$area["id"]."_.adCheck( [". implode(",", $data) ."] );";
			
			///////////////////////
		
			//遍历有效广告		
			$sql="SELECT * FROM `mod:adsview` WHERE `state`>0 and `state`<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 = System :: $db -> getAll( $sql );
			
			//广告数量
			$i = 0;
			
			foreach( $result2 as $ad ){

				//转成数组
				$ad["config"] = fix_json( $ad["config"] );
				
				//地区限制
				if($ad["zone"] && !$save){
					
					//查询位置
					if(!$address){
					
						require_once(dirname(__FILE__)."/../include/client.php");
				
						//当前位置
						$address = convertip(GetIP());
						
						if(@file_exists(dirname(__FILE__).'/../source/wry.dat') && $_G['product']['charset'] != "gbk"){
							$address = iconv("gbk",$_G['product']['charset'],$address);
						}else{
							if($_G['product']['charset'] != "utf-8"){
								$address = iconv("utf-8",$_G['product']['charset'],$address);
							}
						}
					}
					
					//echo $address;
					$script .= chr(10).'/* 所在地:'.$address.' */'.chr(10);
					
					//未找到
					$find = false;
					
					$array = explode(',',$ad["zone"]);
					
					for($a=0; $a<count($array); $a++){
						
						//找到匹配位置
						if( strpos($address,trim($array[$a])) !== false ){
							$find = true;
						}
					}
					
					//未找到
					if(!$find){
						$script .= chr(10).'/* 不在所在地区 */'.chr(10);
					}
					
				}else{
					$find = true;
				}
				
				if($find){
				
					//转换图片地址
					$ad["file"] = self :: fixfile( $ad["file"], $HOT, $area["show"] == 9 ? true : false );
					
					$script .= self :: script( $API, $area, $ad );
					
					$i++;
				}
			}
			
			$script.=chr(10).'/* 匹配'.$i.'条 */'.chr(10);
			
			////////////////////////////
			
			//替补广告
			if( $i < $area["number"] ){
				
				foreach( $spare as $ad ){
				
					//$config = fix_json( $ad["config"] );
					
					//转换图片地址
					$ad["file"] = self :: fixfile( $ad["file"], $HOT, $area["show"] == 9 ? true : false );
					
					$temp = self :: script( $API, $area, $ad );
				
					//累加到现有广告
					$script = $script . $temp;
					
				}
			}
			
			////////////////////////////
			
			//插入广告
			$script.='	_'.$area["id"].'_.adInsert();'.chr(13)."}";
				
			//生成页面
			if($save){
				
				//创建根目录
				create_dir( $base );
			
				create_file($js,$script );
				
			}else{
			
				if( $charset && $charset != $_G['product']['charset'] ){			
					$ad_str = iconv($_G['product']['charset'],$charset,$script);				
				}
				
				return $script;
			}
		}	
	}

	/*
		转换图片地址
		$file		原始图片地址
		$base		基准目录地址
		$proxy		是否需要跨域
	*/
	public static function fixfile( $file, $base, $proxy = false ){
		
		if( $file ){
			
			//本地绝对地址
			if( stripos($file,"://") === false ){		
			
				$file = str_replace("/../","/",$base.$file);
				
			}elseif( $proxy && stripos($file,VI_HOST) === false ){
				
				//跨域支持
				$file = VI_HOST.'proxy.php?'.urlencode($file);
				
			}
			
		}
		
		return $file;
		
	}

	/*
		广告位
		$API	API路径
		$area	广告位
	*/
	public static function area( $API, $area ){
			
		//删除空白字符
		//$config = preg_replace("/([\r\n\t\f])/"," ",$area["config"]);
		
		return 'var _'.$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	配置
	*/
	public static function script( $API, $area, $ad ){
		
		//基准地址
		$HOT = url_fore();
		
		//自定义广告
		if( $area["show"] == 13 ){
			
			foreach( $ad["config"] as $key => $val ){			
				if( strpos( $key , "FILE:" ) !== false && $val ){			
					$ad["config"][$key] = self :: fixfile( $val, $HOT );
				}			
			}
			
			$temp = format_json( fix_json( $ad["config"] ) );

			$text = "	_".$area["id"]."_.adAdd({ 'id':".$ad["id"].", 'name':'".$ad["name"]."', 'file':'".$ad["file"]."', 'width':".$ad["width"].", 'height':".$ad["height"].", 'link':'".$ad["link"]."', 'expire':".$ad["expire"].", 'form':0, 'spare':".$ad["spare"].", 'tags':'".$ad["tags"]."', 'config':".$temp."});";
			
		}else{
		
			//代码广告
			if ( $ad["form"] ){
			
				$text = "	_".$area["id"]."_.adAdd({ 'id':".$ad["id"].", 'name':'".$ad["name"]."', 'file':'".$ad["file"]."', 'width':".$ad["width"].", 'height':".$ad["height"].", 'link':'".$ad["link"]."', 'expire':'".$ad["expire"]."', 'form':1, 'spare':".$ad["spare"].", 'config':". ( $ad["config"] ? fix_json( $ad["config"] ) : '{}' ) ."});";
				
				$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 = "	_".$area["id"]."_.adAdd({ 'id':".$ad["id"].", 'name':'".$ad["name"]."', 'file':'".$ad["file"]."', 'width':".$ad["width"].", 'height':".$ad["height"].", 'link':'".$ad["link"]."', 'expire':".$ad["expire"].", 'form':0, 'spare':".$ad["spare"].", 'tags':'".$ad["tags"]."', 'config':". ( $ad["config"] ? fix_json( $ad["config"] ) : '{}' ) ."});";
				
			}
			
		}
		
		return $text;	
		
	}

	//删除广告缓存
	public static function delete($sql,$mysql){
		
		//缓存目录
		$base	= create_dir( VI_ROOT.'static/adsview/' );
		
		$result = System :: $db -> getAll( $sql );

		foreach( $result as $row ){
			
			$key	= $row["key"];
			$id		= $row['id'];
			$preview= $row["preview"];

			//删除JS
			$ad_file= $base . 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 `mod:adsview` WHERE type=". $id;			
			$result2 = System :: $db -> getAll( $sql );
			foreach( $result2 as $row2 ){
				
				$file=$row2["file"];
				
				//删除文件
				if($file){
					if(function_exists("uploader_delete")){
						uploader_delete($file,$mysql);
					}else{
						if(file_exists($file)){
							@unlink($file);
						}
					}
				}
			}
			
			//删除分类记录
			$sql="DELETE FROM `mod:adsarea` WHERE id=". $id;
			System :: $db -> execute( $sql );
		}
		
	}
	
	/*
		统计广告数量
		$cate	类别
	*/
	public static function count( $cate ){
		global $_G;
		
		switch( $cate ){
			
			//全部广告
			case 'all':
				$sql = "SELECT count(id) FROM `mod:adsview`";
			break;
			
			//正常广告
			case 'normal':
				$sql = "SELECT count(id) FROM `mod:adsview` WHERE `state`>0 and `state`<3 and expire>=". time() ." and start<=".time();
			break;
			
			//快到期
			case 'last':
				$sql = "SELECT count(id) FROM `mod:adsview` WHERE expire < ". strtotime("+". $_G['setting']['adsview']["expire"] ." days", strtotime('23:59:59')) ." and expire >= ". time();
			break;
			
			//已过期
			case 'expire':
				$sql = "SELECT count(id) FROM `mod:adsview` WHERE expire<".time();
			break;
			
			//已停止
			case 'stop':
				$sql = "SELECT count(id) FROM `mod:adsview` WHERE state =0";
			break;
			
		}
		
		return $sql ? System :: $db -> getValue( $sql ) : '';
		
	}
	
	/*
		广告审核后回调
		$summary	摘要
	*/
	public static function examine( $summary ){
	
		//生成广告
		self :: create("SELECT * FROM `mod:adsarea` WHERE id =".$summary["type"]);
	
	}

}

?>