<?php
defined('IN_TS') or die('Access Denied.');

function download($dir,$name)
{
	$arr=explode('.', $dir);
	$ext=end($arr);  //end()返回数组的最后一个元素
	if($ext=='pdf')
	{
		$file = fopen($dir,"r"); // 打开文件
		// 输入文件标签
		Header("Content-type: application/pdf");
		Header("filename:" . $name);
		// 输出文件内容
		echo fread($file,filesize($dir));
		fclose($file);
	}else
	{	
		$file = fopen($dir,"r"); // 打开文件
		// 输入文件标签
		Header("Content-type: application/octet-stream");
		Header("Accept-Ranges: bytes");
		Header("Accept-Length: ".filesize($dir));
		Header("Content-Disposition: attachment; filename=" . $name);
		// 输出文件内容
		echo fread($file,filesize($dir));
		fclose($file);			
		
	}

	
}

//***********************************************
	$userid = aac('user')->isLogin();
    if(aac('user')->isPublisher()==false) {tsNotice('你可能被限制或没有验证邮箱，检查邮箱是否认证。','->点击认证<-',tsUrl('user','verify'));}
	
	$attachid=intval($_GET['id']);
	
	$the_file=$new['attach']->find('attach',array(
                                                'attachid'=>$attachid,
                                                
                                                ));
	 if($the_file)                     //检查数据表
    {
        $file_dir = "uploadfile/attach/".$the_file['attachurl'];
        if (!file_exists($file_dir)) { //检查文件是否存在
            echo "文件已删除";
            exit;
        }else{
            if($the_file['userid']==$userid)
            {
            	$new['attach']->update('attach',array(
				'attachid'=>$attachid,
				),array(
					'count_view'=>$the_file['count_view']+1,
				));
				download($file_dir,$the_file['attachname']);
                exit;
            }else
            {
				if($the_file['pay']==0)//免费的
				{
					$new['attach']->update('attach',array(
					'attachid'=>$attachid,
					),array(
						'count_view'=>$the_file['count_view']+1,
					));
					download($file_dir,$the_file['attachname']);
					exit;
					
				}else
				{
					if(aac('user')->delScore($userid,"download file:" . $the_file['attachname'],$the_file['pay']))
					{
						$new['attach']->update('attach',array(
						'attachid'=>$attachid,
						),array(
							'count_view'=>$the_file['count_view']+1,
						));
						download($file_dir,$the_file['attachname']);
						aac('user')->addScore($the_file['userid'],$userme['username']."download:" . $the_file['attachname'],$the_file['pay'],1);
						exit;
					}else
					{
						tsNotice('下载文件需要支付'.$the_file['pay'].'积分，你似乎不够！');
					}
					
				}
            }
          
           
            
        }
        
    }else
    {
        echo "文件已删除";
        exit;
        
    }
	
	