<?php
/**
 * @package iCMS
 * @copyright 2007-2010, iDreamSoft
 * @license http://www.idreamsoft.cn iDreamSoft
 * @author coolmoo <idreamsoft@qq.com>
 */
!defined('iPATH') && exit('What are you doing?');
switch ($operation) {
	case 'manage':
		$Admin->MP("menu_file_manage");
		$method=$_GET['method'];
		if($method=='database'){
			$sql="";
			$_GET['aid'] && $sql=" WHERE `aid`='".(int)$_GET['aid']."'";
			$_GET['type']=='image' && $sql=" WHERE ext IN('jpg','gif','png','bmp','jpeg')";
			$_GET['type']=='other' && $sql=" WHERE ext NOT IN('jpg','gif','png','bmp','jpeg')";
			$maxperpage =30;
			$total=$iCMS->db->getValue("SELECT count(*) FROM `#iCMS@__file` {$sql} order by `id` DESC");
			$totalSize=$iCMS->db->getValue("SELECT SUM(size) FROM `#iCMS@__file` {$sql} order by `id` DESC");
			page($total,$maxperpage,"个文件");
			$rs=$iCMS->db->getArray("SELECT * FROM `#iCMS@__file` {$sql} order by `id` DESC LIMIT {$firstcount} , {$maxperpage}");
			$_count=count($rs);
			include iCMS_admincp_tpl("file.manage.database");
		}else{
			$Folder=$operation=='template'?'templates':$iCMS->config['uploadfiledir'];
			$L=FS::folder('',$Folder,$type);
			include iCMS_admincp_tpl("file.manage.file");
		}
	break;
	case 'filejosn':
		$type=$_GET["type"];
		$click=$_GET["click"];
		$from=$_GET["from"];
		$in=$_GET["in"];
		$dir=trim($_GET["dir"]);
		$opt=$_GET["opt"];
		$Folder=$opt=='template'?'templates':$iCMS->config['uploadfiledir'];
		$L=FS::folder($dir,$Folder,$type);
		$_dir=$L['folder'];
		$_count=count($_dir);
		$ul='<ul id="'.str_replace('/','-',$dir).'">';
    	for($i=0;$i<$_count;$i++){
    		$ul.='<li class="closedir" folder="'.$_dir[$i]['path'].'" onclick="iFM.dir(this);"><span onclick=iFM.dir(this,"p");>'.$_dir[$i]['dir'].'</span></li>';
    	}
		$ul.='</ul>';
		$_FL=$L['FileList'];
		$_fCount=count($_FL);
		$filelist='';
		for($i=0;$i<$_fCount;$i++){
			$href=$opt=='template'?$iCMS->config['url'].'/templates/'.$_FL[$i]['path']:uploadpath($_FL[$i]['path']);
			$filepath=$from=='editor'?$href:$_FL[$i]['path'];
	        $filelist.='<li class="name bg" title="'.$_FL[$i]['name'].'"><a href="'.$href.'" class="icon" target="_blank" title="点击查看">'.$_FL[$i]['icon'].'</a> ';
	        if($click=='file'){
	        	$filelist.="<a href=\"javascript:void(0)\" onclick=insert(\"".$filepath."\",\"".$in."\");>".$_FL[$i]['name']."</a></li>";
	        }else{
	        	$filelist.=$_FL[$i]['name'].'</li>';
	        }
	        $filelist.='<li class="size">'.$_FL[$i]['size'].'</li>';
	        $filelist.='<li class="author">上传者</li>';
	        $filelist.='<li class="date">'.$_FL[$i]['time'].'</li>';
	        $filelist.='<li class="manage">重新上传 | 删除</li>';
		}
		echo $_GET['jsoncallback']."({dir:'".HTML2JS($ul)."',file:'".HTML2JS($filelist)."'})";
	break;
	case 'page':
		include_once(iPATH."include/fckeditor.php") ;
		$cid=(int)$_GET['cid'];
		$catalog=$iCMS->db->getRow("SELECT * FROM `#iCMS@__catalog` WHERE id='$cid'");
		$rs=$iCMS->db->getRow("SELECT * FROM `#iCMS@__page` WHERE cid='$cid'");
		if(empty($rs)){
			$rs->createtime=$rs->updatetime=time();
			$rs->creater=$rs->updater=$administrator;
			$rs->body='';
		}
		$editor = new FCKeditor('body');
		$editor->Value= $rs->body;
	//	$editor->CreateHtml()
		$rs->createtime=get_date($rs->createtime,'Y-m-d H:i:s');
		$rs->updatetime=get_date($rs->updatetime,'Y-m-d H:i:s');
		include iCMS_admincp_tpl("file.page");
	break;
	case 'delete':
		deletefile((int)$_GET['fid'])&&_header();
	break;
	case 'reremote':
		require_once(iPATH.'include/snoopy.class.php');
		$Snoopy = new Snoopy;
		$Snoopy->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5";
		$Snoopy->accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
		$Snoopy->fetch($_GET['url']);
		$path=urldecode($_GET['path']);
		FS::write(iPATH.$path,$Snoopy->results);
		redirect("下载完成!",$_SERVER['HTTP_REFERER']);
	break;
	case 'reupload':
		$fid=(int)$_GET['fid'];
		$rs=$iCMS->db->getRow("SELECT * FROM `#iCMS@__file` WHERE `id`='$fid' LIMIT 1");
		$path=str_replace($rs->filename,'',$rs->path);
		include iCMS_admincp_tpl("file.reupload");
	break;
	case 'swfupload':
		require_once iPATH.'include/upload.class.php';
		$F = iUpload::FILES("Filedata");
		echo '<div><ul><li>文件:'.$F["OriginalFileName"].'上传成功！</li><li>路径:'.$F["FilePath"].'</ul></div>';
	break;
	case 'upload':
		$Admin->MP("menu_file_upload");
		include iCMS_admincp_tpl("file.upload");
	break;
	case 'extract':
		$Admin->MP("menu_extract_pic");
		include iPATH.'include/catalog.class.php';
		if(empty($_GET['o'])){
			$catalog =new catalog();
			include iCMS_admincp_tpl("file.extract.pic");
		}else{
			set_time_limit(0);
			$action		=$_GET['action'];
			$QUERY_STRING="&o=1&action=".$action;
			$speed		=100;//提取速度
			$cids		=$_GET['cid'];
			$startid	=(int)$_GET['startid'];
			$endid		=(int)$_GET['endid'];
			$starttime	=$_GET['starttime'];
			$endtime	=$_GET['endtime'];
			$totle		=isset($_GET['totle'])?$_GET['totle']:0;
			$loop		=isset($_GET['loop'])?$_GET['loop']:1;
			$i			=isset($_GET['i'])?$_GET['i']:0;
			empty($action) && alert("请选择操作");
			if($cids){
				empty($cids) && alert("请选择栏目");
				is_array($cids) && $cids = implode(",", $cids);
				if(strstr($cids,'all')){
					$catalog =new catalog();
					$cids=substr($catalog->id(),0,-1);
					if(empty($cids)){
						redirect("提取完毕",__SELF__.'?do=file&operation=extract');
					}else{
						_header(__SELF__.'?do=file&operation=extract&cid='.$cids.$QUERY_STRING);
					}
				}else{
					$cArray	=explode(',',$cids);
					$_Ccount=count($cArray);
					$k		=isset($_GET['k'])?$_GET['k']:0;
					$rs=$iCMS->db->getArray("SELECT id FROM #iCMS@__article WHERE cid in ($cids) and `status`='1'");
					empty($totle)&&$totle=count($rs);
					$tloop=ceil($totle/$speed);
					if($loop<=$tloop){
						$max=$i+$speed>$totle?$totle:$i+$speed;
						for($j=$i;$j<$max;$j++){
							if($action=="thumb"){
								if(extractThumb($rs[$j]['id'])){
									echo "文章ID:".$rs[$j]['id']."提取…<span style='color:green;'>√</span><br />";flush();
								}
							}elseif($action=="into"){
								if(into($rs[$j]['id'])){
									echo "文章ID:".$rs[$j]['id']."提取…<span style='color:green;'>√</span><br />";flush();
								}
							}
						}
						_header(__SELF__.'?do=file&operation=extract&cid='.$cids.'&totle='.$totle.'&loop='.($loop+1).'&i='.$j.$QUERY_STRING);
					}else{
						redirect("提取完毕",__SELF__.'?do=file&operation=extract');
					}
				}
			}elseif($startid && $endid){
				($startid>$endid &&!isset($_GET['g'])) && alert("开始ID不能大于结束ID");
				empty($totle)&&$totle=($endid-$startid)+1;
				empty($i)&&$i=$startid;
				$tloop=ceil($totle/$speed);
				if($loop<=$tloop){
					$max=$i+$speed>$endid?$endid:$i+$speed;
					for($j=$i;$j<=$max;$j++){
							if($action=="thumb"){
								if(extractThumb($j)){
									echo "文章ID:".$j."提取…<span style='color:green;'>√</span><br />";flush();
								}
							}elseif($action=="into"){
								if(into($j)){
									echo "文章ID:".$j."提取…<span style='color:green;'>√</span><br />";flush();
								}
							}
					}
					_header(__SELF__.'?do=file&operation=extract&startid='.$startid.'&endid='.$endid.'&g&loop='.($loop+1).'&i='.$j.$QUERY_STRING);
				}else{
					redirect("提取完毕",__SELF__.'?do=file&operation=extract');
				}
			}elseif($starttime){
				$s	= strtotime($starttime);
				$e	= empty($endtime)?time()+86400:strtotime($endtime);
				$rs=$iCMS->db->getArray("SELECT id FROM #iCMS@__article WHERE `pubdate`>='$s' and `pubdate`<='$e' and `status`='1'");
				empty($totle)&&$totle=count($rs);
				$tloop=ceil($totle/$speed);
				if($loop<=$tloop){
					$max=$i+$speed>$totle?$totle:$i+$speed;
					for($j=$i;$j<$max;$j++){
							if($action=="thumb"){
								if(extractThumb($rs[$j]['id'])){
									echo "文章ID:".$rs[$j]['id']."提取…<span style='color:green;'>√</span><br />";flush();
								}
							}elseif($action=="into"){
								if(into($rs[$j]['id'])){
									echo "文章ID:".$rs[$j]['id']."提取…<span style='color:green;'>√</span><br />";flush();
								}
							}
					}
					_header(__SELF__.'?do=file&operation=extract&starttime='.$starttime.'&endtime='.$endtime.'&totle='.$totle.'&loop='.($loop+1).'&i='.$j.$QUERY_STRING);
				}else{
					redirect("提取完毕",__SELF__.'?do=file&operation=extract');
				}
			}else{
				alert("请选择方式");
			}
		}
	break;
	case 'post':
		if($action=='pagedit'){
		    $id				= intval($_POST['id']);
		    $cid			= intval($_POST['cid']);
		    $name			= dhtmlspecialchars($_POST['name']);
		    $title			= dhtmlspecialchars(HtmToText($_POST['title']));
		    $keyword		= dhtmlspecialchars(HtmToText($_POST['keyword']));
		    $description	= dhtmlspecialchars(HtmToText($_POST['description']));
		    $body			= $_POST['body'];
		    $creater		= $updater=$administrator;
		    $createtime		= _strtotime($_POST['createtime']);
		    $updatetime		= time();
		    $data			= compact('cid','title','keyword','description','body','creater','updater','createtime','updatetime');
		    if(empty($id)){
		    	$iCMS->db->insert('page',$data);
		    	redirect($name."页面添加完成!",__SELF__."?do=catalog");
		    }else{
		    	$iCMS->db->update('page',$data,compact('id'));
		    	redirect($name."编辑完成!",__SELF__."?do=catalog");
		    }
		}
		if($action=='reupload'){
			$fid=(int)$_POST['fid'];
			$rs=$iCMS->db->getRow("SELECT * FROM `#iCMS@__file` WHERE `id`='$fid' LIMIT 1");
			$path=dirname($rs->path);
			require_once iPATH.'include/upload.class.php';
			iUpload::FILES('file','',$path,$rs->filename,'reupload');
			alert($rs->filename.'重新上传成功！','javascript:window.parent.location.reload();');	
		}
		if(isset($_POST['delete'])){
			$i=0;
			foreach($_POST['delete'] as $fid){
				deletefile($fid)&&$i++;
			}
			alert("共删除{$i}个文件！","url:1");
		}else{
			_header();
		}
	break;
}
function deletefile($fid){
	global $iCMS;
	$rs=$iCMS->db->getRow("SELECT * FROM `#iCMS@__file` WHERE `id`='$fid' LIMIT 1");
	$thumbfilepath=gethumb($rs->path,'','',true,true);
	FS::del(iPATH.$rs->path,false);
	echo $rs->path.' 文件删除…<span style="color:green;">√</span><br />';
	if($thumbfilepath)foreach($thumbfilepath as $wh=>$fp){
		FS::del($fp,false);
		echo '缩略图 '.$wh.' 文件删除…<span style="color:green;">√</span><br />';
	}
	$iCMS->db->query("UPDATE `#iCMS@__article` SET `pic`='' WHERE `pic`='{$rs->path}'");
	$iCMS->db->query("DELETE FROM `#iCMS@__file` WHERE `id`='$fid' LIMIT 1");
	return true;
}
function extractThumb($id){
	global $iCMS;
	$content	= $iCMS->db->getValue("SELECT body FROM `#iCMS@__articledata` WHERE aid='$id'");
	$img 		= array();
	preg_match_all("/<img.*?src\s*=[\"|'|\s]*(http:\/\/.*?\.(gif|jpg|jpeg|bmp|png)).*?>/is",$content,$img);
	$_array = array_unique($img[1]);
	foreach($_array as $key =>$value){
		$value = uploadpath($value,'http2iPATH');
		if(file_exists($value)){
			$value = uploadpath($value,'-iPATH');
			$iCMS->db->query("UPDATE `#iCMS@__article` SET `isPic`='1',`pic` = '$value' WHERE `id` = '$id'");
			break;
		}
	}
}
function into($id){
	global $iCMS;
	$rs	= $iCMS->db->getRow("SELECT body FROM `#iCMS@__articledata`WHERE aid='$id'");
	$img 		= array();
	preg_match_all("/<img.*?src\s*=[\"|'|\s]*(http:\/\/.*?\.(gif|jpg|jpeg|bmp|png)).*?>/is",$rs->body,$img);
	$_array = array_unique($img[1]);
	foreach($_array as $key =>$value){
		$value = uploadpath($value,'-http');
		$rootpf	= uploadpath($value,'+iPATH');
		if(file_exists($rootpf)){
			$filename	=substr(strrchr($value, "/"), 1);
			$FileExt	=substr(strrchr($filename, "."), 1);
			$_FileSize	= @filesize($rootpf);
			if($iCMS->db->getValue("SELECT `id` FROM `#iCMS@__file` WHERE `path`='$value'")){
				echo "库中已有…<span style='color:green;'>×</span><br />";flush();
			}else{
				$iCMS->db->query("INSERT INTO `#iCMS@__file` (`aid`,`filename`,`ofilename`,`path`,`intro`,`ext`,`size` ,`time`,`type`) VALUES ('$id','$filename', '', '$value','{$rs->title}', '$FileExt', '$_FileSize', '".time()."', '0')");
				echo "图片: ".$value." 入库…<span style='color:green;'>√</span><br />";flush();
			}
		}else{
			$data="AID: ".$id." 路径: [".$value."] 标题: ".$rs->title."\n";
			FS::write(iPATH."admin/logs/pic_exist.txt",$data,true,"a+");
		}
	}
}
?>