<?php
	require_once('_approot.php');	
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
// 前1-2位一定是数字1, 01,02,11 后面分隔符 ；; ,，、空格等
// 导入文件夹在网站根目录下
// 196行是核心

	$ls_msg="自动添加产品操作";
	
	$config_sql="select * from ls_config ";
	$config_query=$opendb->query($config_sql);
	$config_row=mysqli_fetch_assoc($config_query);
	$brand=$config_row['MSN4'];
	
	$filepath=$_POST['filepath'];
	$ls=$_POST['ls'];
	
	function getSubstr1($str, $leftStr, $rightStr)
	{
		//echo $leftStr."<br />";
	 $left = strpos($str, $leftStr);
	 //echo '左边:'.$left;
	 if($rightStr != ""){
		$right = strpos($str, $rightStr,$left + strlen($leftStr));
		$r_postion=$right-$left-strlen($leftStr);
	 }else{
		$r_postion=strlen($str)-strlen($leftStr);
	 }
	 //echo '<br>右边:'.$right;
	 //if($left < 0 or $right < $left) return '';
	 return substr($str, $left + strlen($leftStr), $r_postion);
	}
	function clearCateNum($catestr){
		$catestrtrim( str_replace("；","", str_replace(";","",str_replace("，","", str_replace("、","", str_replace(",","", $catestr))))));
		return($catestr);
	}
	function getCateName($allcate){
		$numcate = substr($allcate, 0, 2);
		if(is_numeric($numcate)){
			$allcate =clearCateNum(str_replace($numcate,"",$allcate)); 
		}else{
			$allcate =clearCateNum(str_replace(substr($allcate, 0, 1),"",$allcate)); 
		}
		return $allcate;
	}

	function get_filetree($filepath){
		global $brand;
		
		$path = "../".$filepath;
		
		$catename1 = array();
		$catename2 = array();
		
		$catemidnameArray1 = array();
		$catemidnameArray2 = array();
		
		$tree = array();
		$tree2 = array();
		$tree3 = array();
	
		foreach(glob($path.'/*') as $single){
			if(is_dir($single)){
				//$tree = array_merge($tree,get_filetree($single));
				$tree[] = $single."<br />";
				
				$allcate = getSubstr1($single, $filepath."/", "");
				$numcate = substr($allcate, 0, 2);
				if(is_numeric($numcate)){
					$catename2[] =clearCateNum(str_replace($numcate,"",$allcate));    //大类两位编号
				}else{
					$catename1[] = clearCateNum(str_replace(substr($allcate, 0, 1),"",$allcate));   //大类一位编号
				}
	
				foreach(glob($single.'/*') as $single2){
					if(is_dir($single2)){
						$tree2[] = $single2."<br />";
						
						$allcate = getSubstr1($single2, $filepath."/", "/");
						$allmidcate = getSubstr1($single2, $filepath."/".$allcate."/", "");
						
						$numcate = substr($allmidcate, 0, 2);
						if(is_numeric($numcate)){  //中类两位编号
							$catemidnameArray2[]['catename'] = getCateName($allcate);
							$catemidnameArray2[]['catemidname'] = getCateName($allmidcate);
						}else{    //中类一位编号
							$catemidnameArray1[]['catename'] = getCateName($allcate);
							$catemidnameArray1[]['catemidname'] = getCateName($allmidcate);
						}
						
						foreach(glob($single2.'/*') as $single3){
							if(is_dir($single3)){
								$tree3[] = $single3."<br />";
							}
						}
					}
				}
			}
			else{
				$tree[] = $single;
			}
		}
		//添加大类  开始

		foreach ($catename2 as $cate1){
			$cateName=trim($cate1);
			$cateName=str_replace("'","`",$cateName);
			//$cateFolders=$cateName;
			$cateFolders=clearFolder(strtolower($cateName));
			$cateTitle=$cateName." - ".$brand;
			$cateKeywords=strtolower($cateName);
			$cateDescription=$cateName;
			//$catePagePic = $_POST['catePagePic'];
			$catePagePicWidth=$_POST['width'];
			$catePagePicHeight=$_POST['height'];
			
			$cateBrief=str_replace("\n","<br />",htmlspecialchars($_POST['cateBrief'], ENT_QUOTES));
			$cateDetail=$_POST['cateDetail'];
			
			$imageicon=$_FILES['cateIconPic']['name'];
			$ls = "insert";
			
			switch ($ls)
			{
				case "insert":  ///添加大类 Start
				
				//开始判断图像类型
				// 开始判断是否有重复的
				$cateName = str_replace("'","''",$cateName);
				$select_sql="select * from ls_products where cateName='".$cateName."' ";
				$opendb=new mydb();
				$select_query=$opendb->query($select_sql);
				$select_rows=mysqli_num_rows($select_query);
				if ($select_rows == 0)
				{
					$path ="../".$cateFolders;
					//调用建立文件夹函数 createFolder
					createFolder($path);
																	
					$arr=array(" ",".");   
					//产生文件名   
					$catePagePic=str_replace($arr ,"",$cateFolders."_banner").".".substr($image,-3);
					$BannerPath =$path ."/".$catePagePic;
					//echo $BannerPath;
					
					$cateIconPic=str_replace($arr ,"",$cateFolders."_icon").".".substr($imageicon,-3);
					$IconPath =$path ."/".$cateIconPic;
	
					$select_sql2="select * from ls_products where cateName<>'' ";
					$select_query2=$opendb->query($select_sql2);
					$select_rows2=mysqli_num_rows($select_query2); //总类数
		
					$insert_sql=sprintf("insert into ls_products 												(cateName,cateFolders,cateTitle,cateKeywords,cateDescription,catePagePic,catePagePicWidth,catePagePicHeight,cateIconPic,cateBrief,cateDetail,date,Num,enable) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ",
								GetSQLValueString(ucwords($cateName), "text"),
								GetSQLValueString($cateFolders, "text"),
								GetSQLValueString($cateTitle, "text"),
								GetSQLValueString($cateKeywords, "text"),
								GetSQLValueString($cateDescription, "text"),
								GetSQLValueString($catePagePic, "text"),
								GetSQLValueString($catePagePicWidth, "text"),
								GetSQLValueString($catePagePicHeight, "text"),
								GetSQLValueString($cateIconPic, "text"),
								GetSQLValueString($cateBrief, "text"),
								GetSQLValueString($cateDetail, "text"),
								GetSQLValueString(date('Y-m-d'), "text"),
								GetSQLValueString($select_rows2+1, "int"),
								GetSQLValueString("1", "int")
					);
					//echo $insert_sql;
					$insert_query=$opendb->query($insert_sql);
					echo "添加大类".ucwords($cateName)."成功。<br />";
												
				}
				else
				{
					echo "<script>alert('已存在此大类名！\\n请填写别的大类名！');history.go(-1);</script>";	
				}
												
				writelog($_SERVER['PHP_SELF'],"add category: ".$cateName,"ID: ".$id);
		
				 break;	 ///添加大类 End
			  
			  }
		}
		//添加大类  结束
	
		//添加中类  开始

		$middir=0;
		$i = 0;
		foreach($catemidnameArray1 as $k=>$val){
			$i++;
			if($i%2 == 0){
				if(is_dir($val['catemidname'])){$middir++;}
			}
		}
		
		foreach($catemidnameArray2 as $k=>$val){
			$i++;
			if($i%2 == 0){
				if(is_dir($val['catemidname'])){$middir++;}
			}
		}
		// 统计目录数量结束： 目录 =1 或者没有， 此目录是 产品内容， 否则是目录分类
		
		$i = 0;
		foreach($catemidnameArray1 as $k=>$val){
			$i++;
			if($i%2 != 0){
				$name = $val['catename'];
			}
			
				if($i%2 == 0){
					if($middir>=1 && is_dir($val['catemidname']) ){include_once("autoarticle.php");}
					else
					{$getcate=$name; include_once("autoarticle.php");}	 //需要判断 是否是目录
				}
		}
		
		foreach($catemidnameArray2 as $k=>$val){
			$i++;
			if($i%2 != 0){
				$name = $val['catename'];
			}
			
			if($i%2 == 0){
					if($middir>=1 && is_dir($val['catemidname']) ){include_once("autoarticle.php");}
					else
					{$getcate=$name; include_once("autoarticle.php");}	 //需要判断 是否是目录
			}
		}
		
		
//		if($nodir==1){   }
//		if($nodir==0){ include_once("autoarticle.php");}
		
/*		$nodir=0;
		foreach($catemidnameArray1 as $k=>$val){
			if(is_dir($val)){}
			else
			{$nodir++;}
		}

		foreach($catemidnameArray2 as $k=>$val){
			if(is_dir($val)){}
			else
			{$nodir++;}
		}
		var_dump($catemidnameArray2);
		//echo $nodir;  exit;
		if($nodir>1){include_once("_automidcate.php");}  //内容处理
		else
		{ include_once("autoarticle.php");} //中类处理
		*/
		
		//添加中类  结束
		
		//return array_merge($tree,$tree2,$tree3);
	}
	
	function copyfiles($file1,$file2){
		$contentx =@file_get_contents($file1);
		$openedfile = fopen($file2, "w");
		fwrite($openedfile, $contentx);
		fclose($openedfile);
		if($contentx === FALSE){
			$status=false;
		}else{
			$status=true;
		}
		return $status;
	} 
	
	function checkstr($str, $needle){
		$tmparray = explode($needle,$str);
		if(count($tmparray)>1){
			return true;
		}else{
			return false;
		}
    }
	
	function text($text_path,$text_name,$text_type,$text_category,$text_similarcate,$text_keyworks){
		$fp = fopen ($text_path,"r");
		$newscontent = fread ($fp,filesize ($text_path));
		$newscontent = str_replace("{name}",$text_name,$newscontent);
		$newscontent = str_replace("{type}",$text_type,$newscontent);
		$newscontent = str_replace("{category}",$text_category,$newscontent);
		$newscontent = str_replace("{similarcate}",$text_similarcate,$newscontent);
		$newscontent = str_replace("{itemno}",$text_type,$newscontent);
		$newscontent = str_replace("{keywords}",$text_keyworks,$newscontent);

		return $newscontent;
	}
	
	function add_imgs($path){ 
		$tree_imgs = array(); 
		foreach(glob($path.'/*') as $single){ 
			if(is_dir($single)){ 
				$tree_imgs = array_merge($tree_imgs,add_imgs($single)); 
			}else{ 
				$tree_imgs[] = $single; 
			} 
		} 
		return $tree_imgs; 
	}

	
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>无标题文档</title>
		<link href="css/admin.css" rel="stylesheet" type="text/css">
		<link rel="stylesheet" href="../themes/default/default.css" />
		<script language="JavaScript" src="js/ls.js"></script>
</head>
<body>
<?php
switch($ls)
{
	case "insert":
		if(file_exists("../".$filepath) && $filepath != ""){
			get_filetree($filepath);  //添加类别（大、中类）
			 
		}else{
			echo "	<script>alert('您输入的文件夹不存在或者内容错误，请重新输入！');history.go(-1);</script>";
		}
		
	break;
}
?>
		<table width="96%" border="0" align="center" cellpadding="1" cellspacing="1" bgcolor="#6396d6" <?php if($ls == "insert") echo "style='display:none;' ";?>>
			<tr>
				<td height="18" background="images/admin_bg.gif"><div align="center"><font color="#ffffff"><strong>自动添加产品</strong></font></div>
				</td>
			</tr>
			<tr>
				<td height="213" valign="top" bgcolor="#dee7ff"><br>
				 <form name="newsform" enctype="multipart/form-data" method="post" action="" >
					<input type="hidden" value="insert" name="ls">
					<table border="0" width="90%" align="center">
						<tr>
							<td>提示：<font color="#FF0000"><?php echo $ls_msg; ?></font></td>
							<td align="right">&nbsp;</td>
						</tr>
					</table>
					<table width="90%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
					 
					  <tr bgcolor="#B9DAFF"> 
						<td width="40%" height="28" ></td>
                        <td width="60%" height="28" ></td>
					  </tr>
					  <tr bgcolor="#f4f4f4"> 
						<td align="right">
                        产品目录名称：
						</td>
                        <td><input name="filepath" type="text" size="50" /></td>
						</tr>
					  <tr bgcolor="#B9DAFF">
					    <td height="25" colspan="2" align="center"><input type="submit" value="提交" />
                          <label>
                            <input type="reset" name="button" id="button" value="重置" />
                        </label></td>
				      </tr>
					  <tr bgcolor="#B9DAFF"> 
						<td height="163" colspan="2" style="padding-left:20px;padding-right:20px;"><p>1、产品分类不超过2级</p>
					    <p>2、类名作为文件夹名，前面加序号</p>
					    <p>3、产品名可以作为文件夹名，产品介绍可用doc，txt，标题title可以给放到 title.doc,title.txt,图片可以放到产品文件夹下，可用 jpg,gif,pngd 等格式。</p></td>
					  </tr>
					</table>
					<p>&nbsp;</p>
                 </form>
				</td>
			</tr>
		</table>
	</body>
</html>

