<?php
// 主要模块： addWatermark ImageResize 
// 生成模块： writeMainMenuItemFile（写入主菜单项文件） writeIndexPages writeProPageIndex（写入产品页和产品详细页文件）
// 写入模块： writelog writeconstant writegeneralfile（写入一般文件） 
// 获取模块： getproductfolder 

	/*
------------------------------------------------------
参数：
$path	路径

程序功能：夹函数
------------------------------------------------------
*/
	function createFolder($path){
		if (!file_exists($path)){		//假如文件夹不存在
			createFolder(dirname($path));	//取得最后一个文件夹的全路径返回开始的地方
	//		$path=iconv("UTF-8","GB2312","$path");
			mkdir($path, 0775);
		}
	}

	/*
------------------------------------------------------
参数：
$path	路径

程序功能：清理文件夹字符串函数并同时将多余空格删除
------------------------------------------------------
*/
function clearFolder($path)
{
	//$clearstr=array("/","\\","'","\"",",",":",">","<","&","*","(",")","@","#","+","-","=","$","!","|",".","?",";","~","`","^","[","]","%","_","{","}");
	$clearstr=array("/","\\","'","\"",",",":",">","<","&","*","(",")","@","#","+","-","=","$","!","|",".","?",";","~","`","^","[","]","%","{","}");//要替换的字符中不能包含下划线
	$path=str_replace($clearstr,"",$path);
	$path=preg_replace("/\s+/"," ",$path);
	$path=trim(str_replace(" ","_",$path));
	return($path);
}

/*
------------------------------------------------------
参数：
$path	路径

程序功能：清理文件夹字符串函数
------------------------------------------------------
*/
function replaceCatesName($path)
{
	$searchstr=array(">","<");
	$replacestr=array("]","[");

	$path=str_replace($searchstr,$replacestr,$path);
  
	return($path);
}

/*
------------------------------------------------------
参数：
$path	路径

程序功能：清理文件夹字符串函数(替换多个空格)
------------------------------------------------------
*/
function clearSpace($path)
{
	$path=preg_replace("/\s+/"," ",$path);

	return($path);	
}

 

/*
------------------------------------------------------
参数：
$theValue  需要替换的字符

$theType   需要替换的字符类型

程序功能：字符替换函数
------------------------------------------------------
*/
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
	case "text":
	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
	  break;	
	case "long":
	case "int":
	  $theValue = ($theValue !== "") ? intval($theValue) : "NULL";
	  break;
	case "double":
	  $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
	  break;
	case "date":
	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
	  break;
	case "defined":
	  $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
	  break;
  }
  return $theValue;
}

/*
------------------------------------------------------
参数：
$str_cut	需要截断的字符串
$length	 允许字符串显示的最大长度 

程序功能：截取全角和半角（汉字和英文）混合的字符串以避免乱码
------------------------------------------------------
*/
function substr_cut($str_cut,$length)
{ 
	if (strlen($str_cut) > $length)
	{ 
		for($i=0; $i < $length; $i++) 
		if (ord($str_cut[$i]) > 128)	$i++; 
		$str_cut = substr($str_cut,0,$i); 
	} 
	return $str_cut; 
}

function getimagewh($srcFile)
{
	$info = "";
	$data = GetImageSize($srcFile,$info);
	switch ($data[2]) 
	{
	 case 1:
	   if(!function_exists("imagecreatefromgif")){
		echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！<a href='javascript:go(-1);'>返回</a>";
		exit();
	   }
	   $im = ImageCreateFromGIF($srcFile);
	   break;
	 case 2:
	   if(!function_exists("imagecreatefromjpeg")){
		echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！<a href='javascript:go(-1);'>返回</a>";
		exit();
	   }
	   $im = ImageCreateFromJpeg($srcFile);	
	   break;
	 case 3:
	   $im = ImageCreateFromPNG($srcFile);	
	   break;
   }
   $srcW=ImageSX($im);
   $srcH=ImageSY($im);
   $srcWH=$srcW/$srcH;
   return array($srcW,$srcH);
}
/*
------------------------------------------------------
参数：
$srcFile 源图片地址
$toW	 生成图片宽度 
$toH		 生成图片高度 
$toFile  输出目录

$sourceFile 源图片地址
$destinationWidth	 生成图片宽度 
$destinationHeight		 生成图片高度 
$destinationFile  输出文件
$useAutoPadding		是否使用自动补白，默认不使用
$qualityLevel		输出图片质量，默认8，可选值0-10
$sameSide			输出图默认高宽都限制，W 等宽， H等高

程序功能：生成缩略图
------------------------------------------------------
*/
function ImageResize($sourceFile,$destinationWidth,$destinationHeight,$destinationFile="",$useAutoPadding=false,$qualityLevel=8,$sameSide="N"){
	global $autoPaddingColor;
	
	list($sourceWidth,$sourceHeight,$sourceType)=getimagesize($sourceFile);
	$sourceRatio=$sourceWidth/$sourceHeight;
	
	switch($sourceType){
		case IMG_GIF:
			if(!function_exists("imagecreatefromgif")){
				echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！<a href='javascript:go(-1);'>返回</a>";
				exit();
			}
			$sourceImage=imagecreatefromgif($sourceFile);
			break;
		case IMG_JPG:
		case IMG_JPEG:
			if(!function_exists("imagecreatefromjpeg")){
				echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！<a href='javascript:go(-1);'>返回</a>";
				exit();
			}
			$sourceImage=imagecreatefromjpeg($sourceFile);
			break;
		case 3:
			if(!function_exists("imagecreatefrompng")){
				echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！<a href='javascript:go(-1);'>返回</a>";
				exit();
			}
			$sourceImage=imagecreatefrompng($sourceFile);
			break;
	}
	
	if($useAutoPadding){
		$compositeImage=imagecreatetruecolor($destinationWidth,$destinationHeight);
		imagefill($compositeImage,0,0,imagecolorallocate($compositeImage,$autoPaddingColor["red"],$autoPaddingColor["green"],$autoPaddingColor["blue"]));
		if($sourceRatio>=1){
			
			$newWidth=$destinationWidth;
			$newHeight=round($newWidth/$sourceRatio);
			$coordinatesX=0;
			$coordinatesY=round(($destinationHeight-$newHeight)/2);
		}else{
			$newHeight=$destinationHeight;
			$newWidth=round($newHeight*$sourceRatio);
			$coordinatesY=0;
			$coordinatesX=round(($destinationWidth-$newWidth)/2);
		}
		if($sameSide=="W")
		{
			$newWidth=$destinationWidth;
			$newHeight=round($newWidth/$sourceRatio);
			$coordinatesX=0;
			$coordinatesY=round(($destinationHeight-$newHeight)/2);
		}
		if($sameSide=="H")
		{
			$newHeight=$destinationHeight;
			$newWidth=round($newHeight*$sourceRatio);
			$coordinatesY=0;
			$coordinatesX=round(($destinationWidth-$newWidth)/2);
		}
		
		imagecopyresampled($compositeImage,$sourceImage,$coordinatesX,$coordinatesY,0,0,$newWidth,$newHeight,$sourceWidth,$sourceHeight);
	}else{
		if($sourceRatio>=1){
			$newWidth=$destinationWidth;
			$newHeight=round($newWidth/$sourceRatio);
		}else{
			$newHeight=$destinationHeight;
			$newWidth=round($newHeight*$sourceRatio);
		}
		
		if($sameSide=="W")
		{
				$newWidth=$destinationWidth;
				$newHeight=round($newWidth/$sourceRatio);

		}
		if($sameSide=="H")
		{
				$newHeight=$destinationHeight;
				$newWidth=round($newHeight*$sourceRatio);
		}

		$compositeImage=imagecreatetruecolor($newWidth,$newHeight);
		imagecopyresampled($compositeImage,$sourceImage,0,0,0,0,$newWidth,$newHeight,$sourceWidth,$sourceHeight);
	}
	
	switch($sourceType){
		case IMG_GIF:
			imagegif($compositeImage,$destinationFile);
			break;
		case IMG_JPG:
		case IMG_JPEG:
			$qualitySetting=round(($qualityLevel/10)*100);
			imagejpeg($compositeImage,$destinationFile,$qualitySetting);
			break;
		case 3:
			$qualitySetting=9-round(($qualityLevel/10)*9);
			imagepng($compositeImage,$destinationFile,$qualitySetting);
			break;
	}
	
	imagedestroy($sourceImage);
	imagedestroy($compositeImage);
}
/*
function ImageResize($srcFile,$toW,$toH,$toFile) 
{
	if($toFile==""){ $toFile = $srcFile; }
	$info = "";
	$data = GetImageSize($srcFile,$info);
	switch ($data[2]) 
	{
	 case 1:
	   if(!function_exists("imagecreatefromgif")){
		echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！<a href='javascript:go(-1);'>返回</a>";
		exit();
	   }
	   $im = ImageCreateFromGIF($srcFile);
	   break;
	 case 2:
	   if(!function_exists("imagecreatefromjpeg")){
		echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！<a href='javascript:go(-1);'>返回</a>";
		exit();
	   }
	   $im = ImageCreateFromJpeg($srcFile);	
	   break;
	 case 3:
	   $im = ImageCreateFromPNG($srcFile);	
	   break;
   }
   $srcW=ImageSX($im);
   $srcH=ImageSY($im);
   $toWH=$toW/$toH;
   $srcWH=$srcW/$srcH;
   if($toWH<=$srcWH){
		$ftoW=$toW;
		$ftoH=$ftoW*($srcH/$srcW);
   }
   else{
	   $ftoH=$toH;
	   $ftoW=$ftoH*($srcW/$srcH);
   }	
   if(!($srcW>$toW||$srcH>$toH))// 如果目标文件尺寸大于源文件，文件不变
   {
 	$ftoW=$srcW;
 	$ftoH=$srcH;
   }
   
	switch ($data[2]) 
	{
	 case 1:
 		$ni=ImageCreate($ftoW,$ftoH);
	 	ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		imagegif($ni,$toFile);
	   break;
	 case 2:
		@$ni = ImageCreateTrueColor($ftoW,$ftoH);
		 if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		 else
		 {
			$ni=ImageCreate($ftoW,$ftoH);
		 	ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		 }
			imagejpeg($ni,$toFile);
	   break;
	 case 3:
		$ni=ImageCreate($ftoW,$ftoH);
	 	ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		imagepng($ni,$toFile);
	   break;
   }   
   ImageDestroy($ni);
   ImageDestroy($im);
}
*/
/*
------------------------------------------------------
参数：
$srcPic 源图片文件名
$desPic 目标图片文件名
$wtString 水印字符串
$wtFont 水印字符串字体
$wtSize 水印字符串大小
$wtColor 水印字符串颜色
$wtPosition 水印字符串位置 1 2 3
$wtType 水印字符串或者图片
$picFile 水印图片文件名

程序功能：把水印图片或字符串加到$srcPic写到$desPic
------------------------------------------------------
*/
function addWatermark($srcPic,$desPic,$wtString,$wtFont,$wtSize,$wtColor,$wtPosition,$wtType,$picFile)
{
	list($srcwidth, $srcheight, $srctype, $srcattr) = getimagesize($srcPic);//获取文件类型
	switch($srctype) 
	{
 
		case 1:		$im = imageCreatefromgif($srcPic); break;
		case 2:		$im = imageCreatefromjpeg($srcPic); break;
		case 3:		$im = imageCreatefrompng($srcPic); break;
		default: return(" 测试图片文件类型错误，只能是.gif,.jpg.png ");
	}
	imagealphablending($im, true);
	//$wfilew=imagesx($im);//取得图片的宽
	//$wfileh=imagesy($im);//取得图片的高

	 if($wtType=="pic") 
	 { //图片水印  
		list($wtmwidth, $wtmheight, $wtmtype, $wtmattr)  = getimagesize($picFile);//获取文件类型
		switch($wtmtype)
		{
			case 1:   $im2 = imagecreatefromgif($picFile);  $wtmfile=$GLOBALS['waterMarkPic'].".gif";break;
			case 2:   $im2 = imagecreatefromjpeg($picFile); $wtmfile=$GLOBALS['waterMarkPic'].".jpg";break;
			case 3:   $im2 = imagecreatefrompng($picFile); $wtmfile=$GLOBALS['waterMarkPic'].".png";break;
			default: return("水印图片文件类型错误，只能是.gif,.jpg.png");
		}
	} else {  //文字水印
		$temp = imagettfbbox(ceil($wtFont*2.5),0,"./cour.ttf",$wtString);//取得使用 TrueType 字体的文本的范围
		$wtmwidth = $temp[2] - $temp[6];
		$wtmheight = $temp[3] - $temp[7];
		unset($temp);
	}
		copy($picFile,$wtmfile);
		$GLOBALS['wPic']=$wtmfile;

		switch($wtPosition) {
 
		case 3://1为顶端居中
			$posX = ($srcwidth - $wtmwidth) / 2;
			$posY = ($srcheight - $wtmheight) / 4;
			break;
		
		case 2://2为中部居中
			$posX = ($srcwidth - $wtmwidth) / 2;
			$posY = ($srcheight - $wtmheight) / 2;
			break;
	   
		case 1://8为底端居中
			$posX = ($srcwidth - $wtmwidth) / 2;
			$posY =($srcheight - $wtmheight) / 4 *3;
			break;
		  
	}
	//读取水印文件
	if($wtType=="pic")//水印图片
	{
		//拷贝水印到目标文件
		imagecopy($im, $im2,$posX,$posY, 0, 0, $wtmwidth,$wtmheight);
	}
	else// string
	{
		$R = hexdec(substr($wtColor,1,2));
		$G = hexdec(substr($wtColor,3,4));
		$B = hexdec(substr($wtColor,5));
		imagestring ($im, $wtFont, $posX, $posY, $wtString, imagecolorallocate($im, $R, $G, $B));	   
	}
	
	
	//输出图片
	$result="";
	if($srctype==1)
	{
		$result=imagegif($im,$desPic);
	}
   if($srctype==2)
   { //同上
		$result=imagejpeg($im,$desPic);
	}
	if($srctype==3)
	{
		$result=imagepng($im,$desPic);
	}

	imagedestroy($im);
	if($result!="")
	{return(TRUE);}
	else
	{return(FALSE);}
		//echo "addwater".$srcPic.$desPic.$leftmargin.$upmargin.$watermark;
}
/*
------------------------------------------------------
参数：
$productID 小类ID

$file  相对与于根目录的目录路径

程序功能：获取产品文件夹
------------------------------------------------------
*/
function getproductfolder($productID)
{
				//????
	require_once('conn.php');
	$opendb=new mydb();
	require('char_set.php');
	
	$search_subcate_sql="select * from ls_products where ID = ".$productID."";
	$search_subcate_query=$opendb->query($search_subcate_sql);
	$search_subcate_rows=mysql_fetch_assoc($search_subcate_query);
	
	if($search_subcate_rows['subcateName']=="")
	{

		if($search_subcate_rows['midcateName']=="")//??
		{		
		$procate=$search_subcate_rows['cateName'];
		$procateid=$search_subcate_rows['ID'];
		
		$file=$search_subcate_rows['cateFolders'];
		
		}
		else //??+??
		{
		$search_cate_sql="select * from ls_products where ID = ".$search_subcate_rows['midcateID']."";
		$search_cate_query=$opendb->query($search_cate_sql);
		$search_cate_rows=mysql_fetch_assoc($search_cate_query);

		//??????
		$file=$search_cate_rows['cateFolders']."/".$search_subcate_rows['midcateFolders'];
		
		}
		
	}
	else//??+??+??
	{
	  $procate=$search_subcate_rows['subcateName'];
	  $procateid=$search_subcate_rows['ID'];
	  //????
		$search_midcate_sql="select * from ls_products where ID = ".$search_subcate_rows['subcateID']."";
		$search_midcate_query=$opendb->query($search_midcate_sql);
		$search_midcate_rows=mysql_fetch_assoc($search_midcate_query);
	  
	  //????
		$search_cate_sql="select * from ls_products where ID = ".$search_midcate_rows['midcateID']."";
		$search_cate_query=$opendb->query($search_cate_sql);
		$search_cate_rows=mysql_fetch_assoc($search_cate_query);
		
					//??????
		$file=$search_cate_rows['cateFolders']."/".$search_midcate_rows['midcateFolders']."/".$search_subcate_rows['subcateFolders'];
		

	}
	$opendb->close();			
	return($file);			
}

/*
------------------------------------------------------
参数：

$moduleFile 链接文件名

$allpages 总页数

返回 页间导航链接

程序功能：获取产品页页间导航链接
------------------------------------------------------
*/
function getPages($moduleFile,$allpages)
{
	for ($i=0; $i< $allpages; $i++)
	{ 
	if(($allpages-$i-1)==0)
	{
		$indexp=$moduleFile;
	}
	else
	{
		$indexp=str_replace(".",($allpages-$i-1).".",$moduleFile) ;
	}


	$propage.="<div class=\"propage\"><a href=\"".$indexp."\">".($allpages-$i)."</a></div>\n";
			}
	if($allpages==1)
	{$propage="";}
	else
	{$propage="<div class=\"propageall\">".$propage."</div>\n";}
	
	return($propage);
}

function getPagess($moduleFile,$allpages,$ls_current_page)
{
	for ($i=0; $i< $allpages; $i++){ 
		if(($allpages-$i-1)==0)
		{
			$indexp=$moduleFile;
		}
		else
		{
			$indexp=str_replace(".",($allpages-$i-1).".",$moduleFile) ;
		}
		$a_p = $allpages-$i;
		if($a_p != $ls_current_page){
			$propage.="<div class=\"propage\"><a href=\"".$indexp."\">".($allpages-$i)."</a></div>\n";
		}else{
			$propage.="<div class=\"propage\"><div class=\"current_page\">".($allpages-$i)."</div></div>\n";
		}
	}
	if($allpages==1)
	{$propage="";}
	else
	{$propage="<div class=\"propageall\">".$propage."</div>\n";}
	
	return($propage);
}

/*
------------------------------------------------------
参数：

$products_sql 某类的sql查询串
$PageNum


程序功能：写入某类下产品页所有index文件调用（writeIndexPages）和产品详细内容page文件
------------------------------------------------------
*/

function writeProPageIndex($products_sql,$cateid,$midcateid,$subcateid){
	global $PageNum,$s_pro_cate,$s_cate,$s_pro2_cate,$s_pro3_cate,
	$s_pro4_cate,$pro_cate,$cate,$pro2_cate,$pro3_cate,$pro4_cate,$menu,
	$menu_pro,$menu_pro2,$menu_pro3,$menu_pro4,$showproductsFolders,$lsproshowmenu,$foot,
	$SmallFoldersProducts,$BigFoldersProducts,$minCateDetailLength,$detail,$foot,$menuListscateid,$DetailPage,
	$ls_about,$ls_news,$ls_hotpro,$ls_designby,$ls_news,$ls_newsdongtai,$ls_newsgonggao,$ls_newstieshi,$ls_procurrentpage,
	$ls_newsall2,$ls_newsdongtai2,$ls_newsgonggao2,$ls_newstieshi2,
	$ls_newsall3,$ls_newsdongtai3,$ls_newsgonggao3,$ls_newstieshi3,
	$ls_newsall4,$ls_newsdongtai4,$ls_newsgonggao4,$ls_newstieshi4,
	$ls_link,$link,$pro_link,$pro2_link,$pro3_link,$pro4_link,$ls_catenews,$ls_addprolink,$ls_addnewprolink,
	$pro_revo,$pro2_revo,$pro3_revo,$pro4_revo;
	//echo $menuListscateid."writeProPageIndex";
	//echo $pro_revo."---".$pro2_revo;
	$mynum=0;//总产品数
	$allpages=0;//共有页数
	
	$opendb=new mydb();
	require('char_set.php');
	require('constant.php');
	
	$tem_sql="select * from ls_config order by ID";	
	$tem_query=$opendb->query($tem_sql);
	$row=mysql_fetch_array($tem_query);
	$templates_var = $row['templates'];
	echo $templates_var;

	//if $mynum=0 or $detail>$minCateDetailLength write index.html 没有产品或者类别详细页面有内容只生成 类别单页
	$detail="";  //set the cat subcat midcate detail flag

	$motif_sql="select * from ls_motif where enable=1 order by Num desc ";
	$motif_query=$opendb->query($motif_sql);
	
	$s_motif_cate.="
		<ul class=\"slides_container\">";
	while($motif_rows=mysql_fetch_assoc($motif_query))
	{
		$s_motif_cate.="
			<li><img src=\"../".$MotifFolders."/".$BigFoldersProducts."/".$motif_rows['motifPic']."\" border=\"0\"></li>";
	}
	$s_motif_cate.="
		</ul>\n ";
	
/*	$s_m_cate=str_replace("../","",$s_motif_cate);//cate
	$s_m2_cate=str_replace("../","../",$s_motif_cate);//pro2_cate
	$s_m3_cate=str_replace("../","../../",$s_motif_cate);//pro3_cate
	$s_m4_cate=str_replace("../","../../../",$s_motif_cate);//pro4_cate  */
	$s_m_cate=str_replace("../","../",$s_motif_cate);//cate
	$s_m2_cate=str_replace("../","../../",$s_motif_cate);//pro2_cate
	$s_m3_cate=str_replace("../","../../../",$s_motif_cate);//pro3_cate
	$s_m4_cate=str_replace("../","../../../../",$s_motif_cate);//pro4_cate

	if($cateid!="" && $midcateid=="" && $subcateid=="")//大类 catedetial
	{
		$sqldetail="select * from ls_products where ID =".$cateid." ";
		$querydetail=$opendb->query($sqldetail);
		$myrowsdetail=mysql_fetch_assoc($querydetail);
		if($myrowsdetail['cateDetail']!="")
		{$detail=$myrowsdetail['cateDetail'];
		}
		$procate=$myrowsdetail['cateName'];
		$indicatebar="Home-> ".$myrowsdetail['cateName'];

		$catetitle=$myrowsdetail['cateTitle'];
		$cateKeywords=$myrowsdetail['cateKeywords'];
		$cateDescription=$myrowsdetail['cateDescription'];
		$banner=$myrowsdetail['catePagePic'];
		$file=$myrowsdetail['cateFolders']."/"."index.html";
		$lsbrief=$myrowsdetail['cateBrief'];
		$echoname="大类".$myrowsdetail['cateName'];
		
		$url="";
		$leftcate=$pro_cate;
		$s_cate=$s_pro_cate;			//左侧产品类别
		$leftprocate=$pro2_cate;
		$lspro_menu=$menu_pro;
		$lsproshowmenu=$menu_pro2;
		$ls_link=$pro_link;
		$lspro_link=$pro2_link;
		$ls_revo=$pro_revo;
		$lspro_revo=$pro2_revo;
		$ls_motif=$s_m_cate;   //产品相册主题图片
		$lspro_motif=$s_m2_cate;  //产品详细页主题图片


		$ls_newsdongtai=$ls_newsdongtai2;
		$ls_newstieshi=$ls_newstieshi2;
		$ls_newsgonggao=$ls_newsgonggao2;
		$ls_newsall=$ls_newsall2;
	}

	if($cateid!="" && $midcateid!="" && $subcateid=="")//中类 midcatedetial
	{
		$sqldetail="select * from ls_products where ID =".$midcateid." ";
		$querydetail=$opendb->query($sqldetail);
		$myrowsdetail=mysql_fetch_assoc($querydetail);
		if($myrowsdetail['midcateDetail']!=""){
			$detail=$myrowsdetail['midcateDetail'];
		}
		$procate=$myrowsdetail['midcateName'];
		
		$catetitle=$myrowsdetail['cateTitle'];
		$cateKeywords=$myrowsdetail['cateKeywords'];
		$cateDescription=$myrowsdetail['cateDescription'];

		$sqldetail2="select * from ls_products where ID =".$myrowsdetail['midcateID']." ";
		$querydetail2=$opendb->query($sqldetail2);
		$myrowsdetail2=mysql_fetch_assoc($querydetail2);
		
		$catetitle=($catetitle=="")?$myrowsdetail2['cateTitle']:$catetitle;
		$cateKeywords=($cateKeywords=="")?$myrowsdetail2['cateKeywords']:$cateKeywords;
		$cateDescription=($cateDescription=="")?$myrowsdetail2['cateDescription']:$cateDescription;
		
		$banner="../".$myrowsdetail2['catePagePic'];
		$file=$myrowsdetail2['cateFolders']."/".$myrowsdetail['midcateFolders']."/"."index.html";
		$lsbrief=$myrowsdetail['midcateBrief'];
		$echoname=" 中类".$myrowsdetail['midcateName'];
		$indicatebar="Home-> ".$myrowsdetail2['cateName']." -> ".$myrowsdetail['midcateName'];
	
		$url="../";
		$leftcate=$pro2_cate;
		$s_cate=$s_pro2_cate;			//左侧产品类别
		$leftprocate=$pro3_cate;
		$lspro_menu=$menu_pro2;
		$lsproshowmenu=$menu_pro3;
		$ls_link=$pro2_link;
		$lspro_link=$pro3_link;
		$ls_revo=$pro2_revo;
		$lspro_revo=$pro3_revo;
		$ls_motif=$s_m2_cate;   //产品相册主题图片
		$lspro_motif=$s_m3_cate;  //产品详细页主题图片

		$ls_newsdongtai=$ls_newsdongtai3;
		$ls_newstieshi=$ls_newstieshi3;
		$ls_newsgonggao=$ls_newsgonggao3;
		$ls_newsall=$ls_newsall3;

	}				

	if($cateid!="" && $midcateid!="" && $subcateid!="")//小类 subcatedetial
	{
		$sqldetail="select * from ls_products where ID =".$subcateid." ";
		$querydetail=$opendb->query($sqldetail);
		$myrowsdetail=mysql_fetch_assoc($querydetail);
		if($myrowsdetail['subcateDetail']!="")
		{$detail=$myrowsdetail['subcateDetail'];
		}
		$procate=$myrowsdetail['subcateName'];
		
		$catetitle=$myrowsdetail['cateTitle'];
		$cateKeywords=$myrowsdetail['cateKeywords'];
		$cateDescription=$myrowsdetail['cateDescription'];
		
		$sqldetail2="select * from ls_products where ID =".$myrowsdetail['subcateID']." ";
		$querydetail2=$opendb->query($sqldetail2);
		$myrowsdetail2=mysql_fetch_assoc($querydetail2);
		
		$catetitle=($catetitle=="")?$myrowsdetail2['cateTitle']:$catetitle;
		$cateKeywords=($cateKeywords=="")?$myrowsdetail2['cateKeywords']:$cateKeywords;
		$cateDescription=($cateDescription=="")?$myrowsdetail2['cateDescription']:$cateDescription;

		$sqldetail3="select * from ls_products where ID =".$myrowsdetail2['midcateID']." ";
		$querydetail3=$opendb->query($sqldetail3);
		$myrowsdetail3=mysql_fetch_assoc($querydetail3);

		$catetitle=($catetitle=="")?$myrowsdetail3['cateTitle']:$catetitle;
		$cateKeywords=($cateKeywords=="")?$myrowsdetail3['cateKeywords']:$cateKeywords;
		$cateDescription=($cateDescription=="")?$myrowsdetail3['cateDescription']:$cateDescription;
		
		$banner="../../".$myrowsdetail3['catePagePic'];
		$file=$myrowsdetail3['cateFolders']."/".$myrowsdetail2['midcateFolders']."/".$myrowsdetail['subcateFolders']."/"."index.html";
		$lsbrief=$myrowsdetail['subcateBrief'];
		$echoname=" 小类".$myrowsdetail['subcateName'];
		$indicatebar="Home-> ".$myrowsdetail3['cateName']." -> ".$myrowsdetail2['midcateName']." -> ".$myrowsdetail['subcateName'];


		$url="../../";
		$s_cate=$s_pro3_cate;			//左侧产品类别
		$leftcate=$pro3_cate;
		$leftprocate=$pro4_cate;
		$lspro_menu=$menu_pro3;
		$lsproshowmenu=$menu_pro4;
		$ls_link=$pro3_link;
		$lspro_link=$pro4_link;
		$ls_revo=$pro3_revo;
		$lspro_revo=$pro4_revo;		
		$ls_motif=$s_m3_cate;   //产品相册主题图片
		$lspro_motif=$s_m4_cate;  //产品详细页主题图片

		$ls_newsdongtai=$ls_newsdongtai4;
		$ls_newstieshi=$ls_newstieshi4;
		$ls_newsgonggao=$ls_newsgonggao4;
		$ls_newsall=$ls_newsall4;
	}

		if(strlen($detail)>$minCateDetailLength)  // 叶类小于预定长度将不生成,否则生成一个详细页
		{
			$echoname="详细: ".$echoname;
			$index_path2="../".$templates_var."/catedetail.html";	//类详细页面
			$detailsfile=str_replace("index.html","indexdetails.html",$file);
						
			writeIndexPages($index_path2,$catetitle,$cateKeywords,$cateDescription,$url,$banner,$leftcate,$lspro_menu,
			$lsbrief,$procate,$procateid,$propage,$pro,$detailsfile,$echoname,$mynum,$allpages,$detail,$s_cate,$ls_motif,$ls_revo,$foot,$indicatebar);
			//echo $detail;
			
		}
		if($DetailPage==1)		//0 叶类生成详细说明页面，函数继续执行 1枝类生成详细说明页面，函数返回
		{
			$DetailPage=0; //reset flag
			return;
		}		
		$products_sql.=" order by Num asc ";
		$result=$opendb->query($products_sql);
		$result2=$opendb->query($products_sql);		//for the browseNo
		$mynum = mysql_num_rows($result);//总产品数
		// 每页数量
		$onepage = $PageNum; 
		//共有页数
		$allpages = ceil($mynum/$onepage);
		if($mynum==0)  // 没有产品
		{
			$echoname="无产品: ".$echoname;
			$mynum=0;
			$allpages=1;
			
			
			$index_path="../".$templates_var."/catedetail.html";	//没产品，输出 详细页或者 产品页没内容

			if(is_file($index_path)){}
			else
			{$index_path="../".$templates_var."/products.html";}
			writeIndexPages($index_path,$catetitle,$cateKeywords,$cateDescription,$url,$banner,$leftcate,$lspro_menu,
			$lsbrief,$procate,$procateid,$propage,$pro,$file,$echoname,$mynum,$allpages,$detail,$s_cate,$ls_motif,$ls_revo,$foot,$indicatebar);
			return;
		}
		
			//end  没有产品或者类别详细页面有内容只生成 类别单页
			
			//echo $products_sql."共有".$mynum."个产品。可以生成".$allpages."页.每页".$onepage."个<br>";
			
			//页码计算
			//$propage=getpages("index.html",$allpages);
			//页码计算
			
			$j=1;
			
			for ($i=0; $i<$allpages; $i++)
			{ 
				$ls_procurrentpage="";
				if ($i == 0)
				{ 
				$indexpath = "index.html";
				} 
				else 
				{ 
				  $indexpath = "index".$i.".html";
				}
				$start = $i * $onepage;
				if($allpages!=1){
					$ls_procurrentpage="[".($i+1)."]";		//当前页码
					$ls_current_page=$i+1;
				}
				$pro="<ul class=\"pro_list\">";
		 //查询产品
		 
			 $products_sql2=$products_sql." limit ".$start.",".$onepage." ";
			 //echo $products_sql2."<br>";
			 $products_query=$opendb->query($products_sql2);
			 while($products_rows=mysql_fetch_assoc($products_query))
			 {
				//查询小类
				$search_subcate_sql="select * from ls_products where ID = ".$products_rows['productID']."";
				$search_subcate_query=$opendb->query($search_subcate_sql);
				$search_subcate_rows=mysql_fetch_assoc($search_subcate_query);

				if($search_subcate_rows['subcateName']=="")
				{

					if($search_subcate_rows['midcateName']=="")//大类
					{						
					$procate=$search_subcate_rows['cateName'];//cate name in products 
					$procateid=$search_subcate_rows['ID'];
						
					$imgpic=$SmallFoldersProducts."/".$products_rows['productPic'];
						//生成文件地址
					$file=$search_subcate_rows['cateFolders']."/".$indexpath;
						//生成大图地址
					$profile=$search_subcate_rows['cateFolders']."/".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html";
						
					$catetitle=$search_subcate_rows['cateTitle'];
					$cateKeywords=$search_subcate_rows['cateKeywords'];
					$cateDescription=$search_subcate_rows['cateDescription'];
					$banner=$search_subcate_rows['catePagePic'];
					$lsbrief=$search_subcate_rows['cateBrief'];
						
					$url="";
					$s_cate=$s_pro_cate;
					$s_procate=$s_pro2_cate;	//左侧产品类别
					$leftcate=$pro_cate;
					$leftprocate=$pro2_cate;
					$lspro_menu=$menu_pro;
					$lsproshowmenu=$menu_pro2;
					$ls_link=$pro_link;
					$lspro_link=$pro2_link;
					$ls_revo=$pro_revo;
					$lspro_revo=$pro2_revo;
					}
					else //大类+中类
					{
					
					$catetitle=$search_subcate_rows['cateTitle'];
					$cateKeywords=$search_subcate_rows['cateKeywords'];
					$cateDescription=$search_subcate_rows['cateDescription'];
					
					$procate=$search_subcate_rows['midcateName'];
					$search_cate_sql="select * from ls_products where ID = ".$search_subcate_rows['midcateID']."";
					$search_cate_query=$opendb->query($search_cate_sql);
					$search_cate_rows=mysql_fetch_assoc($search_cate_query);

					$imgpic=$SmallFoldersProducts."/".$products_rows['productPic'];
					//生成文件地址
					$file=$search_cate_rows['cateFolders']."/".$search_subcate_rows['midcateFolders']."/".$indexpath;
					//生成大图文件地址
					$profile=$search_cate_rows['cateFolders']."/".$search_subcate_rows['midcateFolders']."/".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html";

					$catetitle=($catetitle=="")?$search_cate_rows['cateTitle']:$catetitle;
					$cateKeywords=($cateKeywords=="")?$search_cate_rows['cateKeywords']:$cateKeywords;
					$cateDescription=(($cateDescription==" ")||($cateDescription==""))?$search_cate_rows['cateDescription']:$cateDescription;
					
					$banner="../".$search_cate_rows['catePagePic'];
					$lsbrief=$search_subcate_rows['midcateBrief'];
					$url="../";
					$s_cate=$s_pro2_cate;	//左侧产品类别
					$s_procate=$s_pro3_cate;	//左侧产品类别
					$leftcate=$pro2_cate;
					$leftprocate=$pro3_cate;
					$lspro_menu=$menu_pro2;
					$lsproshowmenu=$menu_pro3;
					$ls_link=$pro2_link;
					$lspro_link=$pro3_link;
					$ls_revo=$pro2_revo;
					$lspro_revo=$pro3_revo;						
					}
						
				}
				else//大类+中类+小类
				{
					
					$catetitle=$search_subcate_rows['cateTitle'];
					$cateKeywords=$search_subcate_rows['cateKeywords'];
					$cateDescription=$search_subcate_rows['cateDescription'];
					
					$procate=$search_subcate_rows['subcateName'];
					$procateid=$search_subcate_rows['ID'];
				  //查询中类
					$search_midcate_sql="select * from ls_products where ID = ".$search_subcate_rows['subcateID']."";
					$search_midcate_query=$opendb->query($search_midcate_sql);
					$search_midcate_rows=mysql_fetch_assoc($search_midcate_query);
					
					$catetitle=($catetitle=="")?$search_midcate_rows['cateTitle']:$catetitle;
					$cateKeywords=($cateKeywords=="")?$search_midcate_rows['cateKeywords']:$cateKeywords;
					$cateDescription=(($cateDescription==" ")||($cateDescription==""))?$search_midcate_rows['cateDescription']:$cateDescription;
					  
				  //查询大类
					$search_cate_sql="select * from ls_products where ID = ".$search_midcate_rows['midcateID']."";
					$search_cate_query=$opendb->query($search_cate_sql);
					$search_cate_rows=mysql_fetch_assoc($search_cate_query);
					
					$catetitle=($catetitle=="")?$search_cate_rows['cateTitle']:$catetitle;
					$cateKeywords=($cateKeywords=="")?$search_cate_rows['cateKeywords']:$cateKeywords;
					$cateDescription=(($cateDescription==" ")||($cateDescription==""))?$search_cate_rows['cateDescription']:$cateDescription;
						
					$imgpic=$SmallFoldersProducts."/".$products_rows['productPic'];
					//生成文件地址
					$file=$search_cate_rows['cateFolders']."/".$search_midcate_rows['midcateFolders']."/".$search_subcate_rows['subcateFolders']."/".$indexpath;
					//生成大图地址
					$profile=$search_cate_rows['cateFolders']."/".$search_midcate_rows['midcateFolders']."/".$search_subcate_rows['subcateFolders']."/".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html";
					
					$banner="../../".$search_cate_rows['catePagePic'];
					$lsbrief=$search_subcate_rows['subcateBrief'];
						
					$url="../../";
					$s_cate=$s_pro3_cate;				//左侧产品类别
					$s_procate=$s_pro4_cate;				//左侧产品类别
					$leftcate=$pro3_cate;
					$leftprocate=$pro4_cate;
					$lspro_menu=$menu_pro3;
					$lsproshowmenu=$menu_pro4;
					$ls_link=$pro3_link;
					$lspro_link=$pro4_link;
					$ls_revo=$pro3_revo;
					$lspro_revo=$pro4_revo;					
					$ls_motif=$s_m3_cate;   //产品相册主题图片
					$lspro_motif=$s_m4_cate;  //产品详细页主题图片
				}
				
				
				//产品
				if($i==0){
					/*$pro.="<li><a href=\"".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html\" target=\"_blank\"><img src=\"".$imgpic."\" alt=\"".$products_rows['productName']."\" /></a><a href=\"".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html\" target=\"_blank\">".$products_rows['productName']."</a><a href=\"".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html\" target=\"_blank\">".$products_rows['productItemNo']."</a></li>";*/
					$pro.="<li><a href=\"".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html\" alt=\"".$products_rows['productItemNo']."\" target=\"_blank\"><img src=\"".$imgpic."\" alt=\"".$products_rows['productItemNo']."\" /></a>".$products_rows['productItemNo']."</li>";
				}else{
					$pro.="<li><a href=\"".$showproductsFolders."/".trim(str_replace(substr($products_rows['productPic'],-4),"",$products_rows['productPic'])).".html\" alt=\"".$products_rows['productItemNo']."\" target=\"_blank\"><img src=\"".$imgpic."\" alt=\"".$products_rows['productItemNo']."\" /></a>".$products_rows['productItemNo']."</li>";
				}				   
			
		//页码计算
		$propage=getPagess("index.html",$allpages,$ls_current_page);


		$proshow_path="../".$templates_var."/productsshow.html";			//大图模板地址
		if(!file_exists($proshow_path))
		{
			echo "模板文件".$proshow_path."不存在！请设计好模板后重新生成。</br></br>";
			return;
		}
		
			
			$ls_menu=$lsproshowmenu;	//主菜单
//			$ls_protitle=$catetitle;				  //title
//			$ls_prokeywords=$cateKeywords;			//Keywords
//			$ls_description=$cateDescription;		//Description
			$ls_protitle=$products_rows['productTitle']==""?$catetitle:$products_rows['productTitle'];				  		//产品title
			$ls_prokeywords=$products_rows['productKeywords']==""?$cateKeywords:$products_rows['productKeywords'];			//产品Keywords
			$ls_description=$products_rows['productDescription']==""?$cateDescription:$products_rows['productDescription'];		//产品Description
			$ls_prourl=$url;
			$ls_s_cate=$s_procate;				//左侧产品类别
			$needleonmouseover="<ul  id=\"menuLists".$menuListscateid."\" style=\"display:none;\">\n";	//替换悬停菜单内容
			$replaceonmouseover="<ul  id=\"menuLists".$menuListscateid."\" style=\"display:block;\">\n";

			if($menuListscateid!=0){$ls_s_cate=str_replace($needleonmouseover,$replaceonmouseover,$ls_s_cate);}
			//echo "list1--".$menuListscateid."--pp";
			$ls_probanner=$banner;						//大类主体图
			$ls_procate=$leftprocate;						//左侧产品类别
			$ls_indicatebar=$indicatebar;
			

			//$ls_proshow="../".$BigFoldersProducts."/".$products_rows['productPic'];				 
			$ls_proshow="../".$BigFoldersProducts."/".$products_rows['productPic']."\" ";//大图
			$ls_proitemno=$products_rows['productItemNo'];							//编号
			$ls_proname=$products_rows['productName'];								//名字
			$ls_prodescription=htmlspecialchars_decode($products_rows['productSpecification'],ENT_QUOTES);				//规格
			/****************************编号、名称外的其他参数***********************************/
			$ls_moreparamstr = "<ul class='moreparam'>";							
			$ls_moreparam = explode("\n",$products_rows['canshu']);					
			foreach($ls_moreparam as $val){
				if((trim($val)=='')||($val=="\r"))continue;
				$val = preg_replace('/[ \t]+/'," ",$val);//替换掉多余的空格只留一个
				$val = explode(" ",$val);//用空格分割一条参数
				$ls_moreparamstr .= "<li><span class='canshu_name'>".trim($val[0])."</span> &nbsp;<span class='canshu_val'>".trim($val[1])."</span></li>";
			}
			$ls_moreparamstr .= "</ul>";
			/**********************************************************************************/
			
			//整合产品页面详细信息
			$ls_proitemno_nonintegrate=$ls_proitemno;
			$ls_proname_nonintegrate=$ls_proname;
			$ls_proitemno="<b>Item No.</b>: ".$ls_proitemno."<br />";
			$ls_proname="<b>Name</b>:".$ls_proname."<br />";
			$ls_prodescription_test=preg_replace("/<[\/|\w+]+?.*?\/?>/",null,$ls_prodescription);		//替换html标签到null
			$ls_prodescription_test=preg_replace("/$\w{2,7};/",null,$ls_prodescription_test);			//替换html转义字符
			$ls_prodescription_test=preg_replace("/\s*?/",null,$ls_prodescription_test);			//替换所有不可见的字符
			$ls_prodescription_test=trim($ls_prodescription_test);			//删除两端的空白字符
			
			if(strlen($ls_prodescription_test)!=0){
				$ls_prodescription="<b>Description</b>: ".$ls_prodescription;
			} else {
				$ls_prodescription=null;
			}
			
			$ls_foot=$foot;	
			

// 深入一级目录，适应 productshow
			$ls_pronewsdongtai=str_replace('="../','="../../',$ls_newsdongtai);		
			$ls_pronewsgonggao=str_replace('="../','="../../',$ls_newsgonggao);
			$ls_pronewstieshi=str_replace('="../','="../../',$ls_newstieshi);
												//底部信息
												

//组合数字导航
			if($j>$productBrowerNoOffset)		
			{
				$startk=$j-$productBrowerNoOffset;
				$endk=$j+$productBrowerNoOffset;
			}
			else
			{
				$startk=1;
				$endk=$j+$productBrowerNoOffset;
			}
			if($endk>$mynum)
			{$endk=$mynum;}
			
			
			$k=1;									//产品大图数字导航下标
			$productBrowerStr='';					//产品大图数字导航页
			mysql_data_seek($result2, 0);
			while($products_rows_br=mysql_fetch_assoc($result2))
			{
				$productBrowerNo[$k]="<a href=\"".trim(str_replace(substr($products_rows_br['productPic'],-4),"",$products_rows_br['productPic'])).".html\" >".$k."</a>";		// get the array of no brower
				
				$k++;
			}
			
			for($ik=$startk;$ik<=$endk;$ik++)
			{
				if($ik==$j)
				{
					$productBrowerStr.="[".$productBrowerNo[$ik]."]";
				}
				else
				{
					$productBrowerStr.=$productBrowerNo[$ik];
				}
			}
			
			//echo $productBrowerStr;
			$ls_productBrowerStr=$productBrowerStr;
			
//组合数字导航 end
			$j++;
		
			$fp = fopen($proshow_path,"r");
			$procontent  = fread($fp,filesize ($proshow_path));
			$procontent  = str_replace("../","{ls_url}../../",$procontent);
			$procontent  = str_replace("{ls_title}",$ls_protitle,$procontent);
			$procontent  = str_replace("{ls_keywords}",$ls_prokeywords,$procontent);
			$procontent  = str_replace("{ls_prodescription}",$ls_prodescription,$procontent);
			$procontent  = str_replace("{ls_url}",$ls_prourl,$procontent);
			$procontent  = str_replace("{ls_banner}",$ls_probanner,$procontent);
			$procontent  = str_replace("{ls_menu}",$ls_menu,$procontent);
			$procontent  = str_replace("{ls_procate}",$ls_procate,$procontent);
			$procontent  = str_replace("{ls_s_cate}",$ls_s_cate,$procontent);
			$procontent  = str_replace("{ls_indicatebar}",$ls_indicatebar,$procontent);
			$procontent  = str_replace("{ls_proshow}",$ls_proshow,$procontent);
			$procontent  = str_replace("{ls_proitemno}",$ls_proitemno,$procontent);
			$procontent  = str_replace("{ls_proname}",$ls_proname,$procontent);
			$procontent  = str_replace("{ls_proitemno_nonintegrate}",$ls_proitemno_nonintegrate,$procontent);
			$procontent  = str_replace("{ls_proname_nonintegrate}",$ls_proname_nonintegrate,$procontent);
			$procontent  = str_replace("{ls_description}",$ls_description,$procontent);
			$procontent  = str_replace("{ls_foot}",$ls_foot,$procontent);
			$procontent  = str_replace("{ls_procurrentpage}",$ls_procurrentpage,$procontent);
			$procontent  = str_replace("{ls_revo}",$lspro_revo,$procontent);
			$procontent  = str_replace("{ls_motif}",$lspro_motif,$procontent);


			$procontent	= str_replace("{ls_newsdongtai}",$ls_pronewsdongtai,$procontent);
			$procontent	= str_replace("{ls_newsgonggao}",$ls_pronewsgonggao,$procontent);
			$procontent	= str_replace("{ls_newstieshi}",$ls_pronewstieshi,$procontent);

			$procontent	= str_replace("{ls_about}",$ls_about,$procontent);
			$procontent	= str_replace("{ls_news}",$ls_news,$procontent);
			$procontent	= str_replace("{ls_hotpro}",$ls_hotpro,$procontent);
			$procontent	= str_replace("{ls_designby}",$ls_designby,$procontent);
			$procontent	= str_replace("{ls_link}",$lspro_link,$procontent);
			$procontent	= str_replace("{ls_productBrowerStr}",$ls_productBrowerStr,$procontent);
			$procontent	= str_replace("{ls_left_contact}",$ls_left_contact,$procontent);
			$procontent = str_replace("{ls_addprolink}",$ls_addprolink,$procontent);	//指向主菜单中的Products链接
			$procontent = str_replace("{ls_addnewprolink}",$ls_addnewprolink,$procontent);	//指向主菜单中的NewProducts链接
			$procontent = str_replace("{ls_moreparam}",$ls_moreparamstr,$procontent);//产品详细页中，除了产品名称、编号外的更多信息。
			$procontent = str_replace("{ls_revo}",$ls_revo,$procontent);//滚动图片。

			$procontent = circleNavigationLink($products_rows['ID'],'B','{ls_previouslink}',$procontent);
			$procontent = circleNavigationLink($products_rows['ID'],'F','{ls_nextlink}',$procontent);

			//echo $procontent;
			//echo $content;

			$profilename="../".$profile;
			if (is_file ($profilename))
			{ 
				@unlink ($profilename); //若文件已存在，则删除
			  }

	  $handle   = fopen($profilename,"w"); //打开文件指针，
		  /*
		　检查文件是否被创建且可写
		  */
		  if (!is_writable ($profilename))
			{ 
					 echo "文件：".$profilename."不可写，请检查其属性后重试！";
			  }
		  if (!fwrite ($handle,$procontent))
		  {  //将信息写入文件
				echo "".$profilename."失败！";
		  } 
		  else
		  {
				echo "生成 <a href='".$profilename."'>".$profilename."</a><br>";
		  }
		  fclose ($handle); //关闭指针
					  //die ("创建<a href='".$filename."'>".$filename."</a>成功！<a href=\"temp.php?ls=normal\"><u>返回</u></a>");

		fclose ($fp);

	 } //end of while, end of one page
		$pro.="</ul>";
		
		$ls_motif = $s_m2_cate;
		$index_path="../".$templates_var."/products.html";	
		writeIndexPages($index_path,$catetitle,$cateKeywords,$cateDescription,$url,$banner,$leftcate,$lspro_menu,
			$lsbrief,$procate,$procateid,$propage,$pro,$file,$echoname,$mynum,$allpages,$detail,$s_cate,$ls_motif,$ls_revo,$foot,$indicatebar);
//echo $pro;

		}	// end of for, all pages


		$opendb->close();
}

/*
------------------------------------------------------
参数：
$productID		当前页产品id
$direction		跳转方向(值:'F'下一条,'B'上一条)
$tag			替换标签
$content		需要处理的内容

返回值：替换完成的内容

程序功能：将指定标签替换成向前翻页以及向后翻页的链接

备注：仅支持本类中的页面跳转，不支持类间的。
------------------------------------------------------
*/

function circleNavigationLink($productID,$direction,$tag,$content){
	$opdb=new mydb();
	//Get product information
	$productInfoSql="select * from ls_products where ID={$productID}";
	$productInfoR=$opdb->query($productInfoSql);
	$productInfo=mysql_fetch_object($productInfoR);
	//Get Max and Min Num value
	$numLimitSql="select min(Num) as minNum, max(Num) as maxNum from ls_products where productID={$productInfo->productID}";
	$numLimitR=$opdb->query($numLimitSql);
	$numLimit=mysql_fetch_object($numLimitR);	
	//According to $direction, search the next product
	if(($productInfo->Num==$numLimit->minNum)&&('B'==strtoupper($direction))){
		$linkProductNum=$numLimit->maxNum;
	}else if(($productInfo->Num==$numLimit->maxNum)&&('F'==strtoupper($direction))){
		$linkProductNum=$numLimit->minNum;
	}else{
		$searchCount=0;
		do{
			$searchCount++;
			$linkProductNum=('B'==strtoupper($direction))?($productInfo->Num-$searchCount):($productInfo->Num+$searchCount);
			$checkSql="select ID from ls_products where productID={$productInfo->productID} and Num={$linkProductNum}";
			$checkR=$opdb->query($checkSql);
		}while(0==mysql_num_rows($checkR));
	}
	//Get target product information and return the ready content
	$targetProductSql="select * from ls_products where productID={$productInfo->productID} and Num={$linkProductNum}";
	$targetProductR=$opdb->query($targetProductSql);
	$targetProduct=mysql_fetch_object($targetProductR);
	$targetProductFile=strrev(ltrim(stristr(strrev($targetProduct->productPic),'.'),'.')).'.html';
	$targetProductLink="<a href=\"{$targetProductFile}\">".(('B'==strtoupper($direction))?'Previous':'Next')."</a>";
	return str_replace($tag,$targetProductLink,$content);
}

/*
------------------------------------------------------
参数：
$leftcate
$leftcate
$pro
$file
$echoname

$indicatebar
程序功能：写入类下产品列表页index文件
------------------------------------------------------
*/
function writeIndexPages($index_path,$catetitle,$cateKeywords,$cateDescription,$url,$banner,$leftcate,$lspro_menu,$lsbrief,$procate,$procateid,$propage,$pro,$file,$echoname,$mynum,$allpages,&$detail,$s_cate,$ls_motif,$ls_revo,$foot,$indicatebar){
	global $ls_procurrentpage,$menuListscateid,$ls_about,$ls_news,$ls_hotpro,$ls_link,$ls_designby,$ls_news,$ls_newsdongtai,$ls_newsgonggao,$ls_newstieshi,$ls_addprolink,$ls_addnewprolink,$ls_moreparam;
	
	$needleonmouseover="<ul id=\"menuLists".$menuListscateid."\" style=\"display:none;\">\n";	//替换悬停菜单内容
	$replaceonmouseover="<ul id=\"menuLists".$menuListscateid."\" style=\"display:block;\">\n";

	if($menuListscateid!=0){$s_cate=str_replace($needleonmouseover,$replaceonmouseover,$s_cate);}
	
	//echo $menuListscateid."-pp";
			
	if(!file_exists($index_path)){
		echo "模板文件".$index_path."不存在！请设计好模板后重新生成。</br></br>";
		return;
	}


	//产品模板地址
	$ls_title=$catetitle;//===================================网站标题
	$ls_keywords=$cateKeywords;	//============================网站关键字
	$ls_description=$cateDescription;//=======================网站描述
	$ls_url=$url;
	$ls_banner=$banner;//=====================================大类主体图
	$ls_cate=$leftcate;	
	$ls_s_cate=$s_cate;//=====================================左侧产品类别
	$ls_menu=$lspro_menu;//主菜单
	$ls_indicatebar=$indicatebar;
	if($lsbrief!=""){
		$ls_brief="<div id=\"brief\">".$lsbrief."</div>";
	}
	$ls_procate=$procate;//===================================产品类别
	$ls_procateid=$procateid;//===============================产品类别ID
	$ls_propage=$propage;//===================================产品分页数字
	$ls_pro=$pro;//===========================================产品信息
	$ls_foot=$foot;//=========================================底部信息
	$fp	= fopen($index_path,"r");//===========================打开产品详细页模版
	$content = fread($fp,filesize ($index_path));//===========读取产品详细页模版所有内容
	$content = str_replace("{ls_title}",$ls_title,$content);
	$content = str_replace("../","{ls_url}../",$content);
	$content = str_replace("{ls_keywords}",$ls_keywords,$content);
	$content = str_replace("{ls_url}",$ls_url,$content);
	$content = str_replace("{ls_banner}",$ls_banner,$content);
	$content = str_replace("{ls_menu}",$ls_menu,$content);
	$content = str_replace("{ls_cate}",$ls_cate,$content);
	$content = str_replace("{ls_s_cate}",$ls_s_cate,$content);
	$content = str_replace("{ls_motif}",$ls_motif,$content);
	$content = str_replace("{ls_foot}",$ls_foot,$content);
	$content = str_replace("{ls_procate}",$ls_procate,$content);
	$content = str_replace("{ls_brief}",$ls_brief,$content);
	$content = str_replace("{ls_detail}",$detail,$content);
	$content = str_replace("{ls_indicatebar}",$ls_indicatebar,$content);
	$content = str_replace("{ls_description}",$ls_description,$content);
	$content = str_replace("{ls_procateid}",$ls_procateid,$content);
	$content = str_replace("{ls_propage}",$ls_propage,$content);
	$content = str_replace("{ls_pro}",$ls_pro,$content);
	$content = str_replace("{ls_procurrentpage}",$ls_procurrentpage,$content);
	$content = str_replace("{ls_about}",$ls_about,$content);
	$content = str_replace("{ls_news}",$ls_news,$content);
	$content = str_replace("{ls_newsdongtai}",$ls_newsdongtai,$content);
	$content = str_replace("{ls_newsgonggao}",$ls_newsgonggao,$content);
	$content = str_replace("{ls_newstieshi}",$ls_newstieshi,$content);
	$content = str_replace("{ls_hotpro}",$ls_hotpro,$content); 
	$content = str_replace("{ls_designby}",$ls_designby,$content);
	$content = str_replace("{ls_link}",$ls_link,$content);
	$content = str_replace("{ls_addprolink}",$ls_addprolink,$content);	//指向主菜单中的Products链接
	$content = str_replace("{ls_addnewprolink}",$ls_addnewprolink,$content);	//指向主菜单中的NewProducts链接
	$content = str_replace("{ls_revo}",$ls_revo,$content);	//指向主菜单中的NewProducts链接
	$filename="../".$file;
	if (is_file($filename)){
		//若文件已存在，则删除
		@unlink($filename); 
	}

	$handle = fopen($filename,"w"); //打开文件指针，
	/*
	　检查文件是否被创建且可写
	*/
	if(!is_writable($filename)){ 
		echo "文件：".$filename."不可写，请检查其属性后重试！";
	}
	if(!fwrite($handle,$content)){
		//将信息写入文件
		echo "生成文件".$filename."失败！";
	}else{
		echo "生成 <a href='".$filename."'>".$filename."</a><br>";
	}
	
	fclose($handle);//关闭文件指针
	fclose($fp);	//关闭文件指针
	
	if($index_path=="../".$templates_var."/catedetail.html"){
		echo $echoname." 详细页面成功。<br><br>";
	}else{
		echo $echoname."共有".$mynum."个产品。总共生成".$allpages."类别页。<br><br>";
	}
}
/*
------------------------------------------------------
参数：
$index_path  //模板地址
$filename  //生成文件名
$mainpart  //主体内容
$mainpartsubject  //switch生成文件指针
globle:
	$ls_about			//首页About us
	$ls_news			//首页News
	$ls_hotpro			//首页 Hot products

程序功能：写主菜单项下的文件index,aboutus,contacuts,news,download
,rd,certificate,workshop,feedback,packing,quality
------------------------------------------------------
*/

function writeMainMenuItemFile($index_path,$ls_title,$ls_keywords,$ls_description,$ls_cate,$ls_motif,$ls_menu,$ls_foot,
$filename,$mainpart,$mainpartsubject,$ls_feedbackemail,$ls_propage,$s_cate,$ls_addprolink,$ls_addnewprolink){
	require_once('conn.php');
	if(!file_exists($index_path)){
		echo "模板文件".$index_path."不存在！请设计好模板后重新生成。</br></br>";
		return;
	}
	global $ls,$subFolder;
	global $ls_about,$ls_news,$ls_homepro,$ls_newpro,$ls_hotpro,$ls_designby,$ls_news,$ls_link,$ls_newsdongtai,$ls_newsgonggao,$ls_newstieshi,	$ls_revo;	//首页About us, 首页News, 首页 Hot products


	$opendb=new mydb();
	require('char_set.php');
	
	$tem_sql="select * from ls_config order by ID";	
	$tem_query=$opendb->query($tem_sql);
	$row=mysql_fetch_array($tem_query);
	$templates_var = $row['templates'];
	echo $templates_var;

	$menu_sql="select * from ls_menu where argument='".$mainpartsubject."' ";
	$menu_query=$opendb->query($menu_sql);
	$menu_row=mysql_fetch_assoc($menu_query);
	//echo $ls."kk".$menu_row['enable'];
	if($menu_row['enable']==0&&$menu_row['argument']==$mainpartsubject){
		// 如果主菜单项没有启动则退出函数 
		return;
	}
	
	$fp = fopen($index_path,"r");
	$ls_s_cate = $s_cate;				//左侧产品类别
	$ls_motif = $ls_motif;
	$content = fread($fp,filesize ($index_path));
	$content = str_replace("href=\"css/","href=\"Templates/css/",$content);
	$content = str_replace("src=\"images/","src=\"Templates/images/",$content);
	if($subFolder){
		//如果在子目录里面有"../../"则换成"../"
		$content = str_replace("../../","../",$content);}
	else{
		//用来预防根目录下有其他语言版本
		$content = str_replace("../.","../x",$content);
		$content = str_replace("../","",$content);
		$content = str_replace("x./","../",$content);
	}
	
	$content = str_replace("template=\"/Templates/all.dwt\"","",$content);	//清除模板地址
	$content = str_replace("{ls_title}",$ls_title,$content);
	$content = str_replace("{ls_keywords}",$ls_keywords,$content);
	$content = str_replace("{ls_description}",$ls_description,$content);
	$content = str_replace("{ls_menu}",$ls_menu,$content);
	$content = str_replace("{ls_s_cate}",$ls_s_cate,$content);
	$content = str_replace("{ls_motif}",$ls_motif,$content);
	$content = str_replace("{ls_link}",$ls_link,$content);
	$content = str_replace("{ls_about}",$ls_about,$content);
	$content = str_replace("{ls_news}",$ls_news,$content);
	$content = str_replace("{ls_newsdongtai}",$ls_newsdongtai,$content);
	$content = str_replace("{ls_newsgonggao}",$ls_newsgonggao,$content);
	$content = str_replace("{ls_newstieshi}",$ls_newstieshi,$content);
	$content = str_replace("{ls_homepro}",$ls_homepro,$content);
	$content = str_replace("{ls_designby}",$ls_designby,$content);
	$content = str_replace("{ls_cate}",$ls_cate,$content);
	$content = str_replace("{ls_foot}",$ls_foot,$content);
	$content = str_replace("{ls_addprolink}",$ls_addprolink,$content);	//指向主菜单中的Products链接
	$content = str_replace("{ls_addnewprolink}",$ls_addnewprolink,$content);	//指向主菜单中的NewProducts链接
	$content = str_replace("{ls_hotpro}",$ls_hotpro,$content); //热点产品链接
	$content = str_replace("{ls_revo}",$ls_revo,$content); //主题流动图片

	
	switch($mainpartsubject){
		case "index":
		break;
		case "aboutus":
		$content = str_replace("{ls_allabout}",$mainpart,$content);
		break;
		case "feedback": 
		$content = str_replace("{ls_feedbackemail}",$ls_feedbackemail,$content);
		$content = str_replace("{ls_feedback}",$mainpart,$content);
		break;
		case "contactus":
		$content = str_replace("{ls_contactus}",$mainpart,$content);
		break;
		case "news":
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_newslist}",$mainpart,$content);
		break;
		case "download": //生成下载
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_downlist}",$mainpart,$content);
		break;
		case "management": //生成管理团队(Management)
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_list}",$mainpart,$content);
		break;
		case "workshop": //生成车间图片(Workshop)
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_list}",$mainpart,$content);
		break;
		case "qualitycontrol": //生成车间图片(Workshop)
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_list}",$mainpart,$content);
		break;
		case "rd": //生成研发(R&D)
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_list}",$mainpart,$content);
		break;
		case "certificate": //生成证书(Certificate)
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_list}",$mainpart,$content);
		break;
		case "packing": //生成包装(Packing)
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_list}",$mainpart,$content);
		break;
		case "brand": //生成品牌(Brand)
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_list}",$mainpart,$content);
		break;
		case "hotpro.html":
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_hotpro}",$ls_hotpro,$content);
		break;
		case "newpro.html":
		$content = str_replace("{ls_propage}",$ls_propage,$content);
		$content = str_replace("{ls_newpro}",$ls_newpro,$content);
		break;
		case "links.html":
		$linkssql="select * from ls_links where enable=1 order by linkNum asc";
		$linksquery=$opendb->query($linkssql);
		$ls_links="<div class='link'>";
		while($linksitem=mysql_fetch_assoc($linksquery)){			
			$imagepath="uploadfiles/".$linksitem["linkIconPic"];
			if(!file_exists($imagepath) && strlen($linksitem["linkTitle"])!=0){
				$ls_links.="<div class='link_onlytext'>";
				$fontsize=(round(10-strlen($linksitem["linkTitle"])*1.3)>=3)?round(10-strlen($linksitem["linkTitle"])):3;
				$ls_links.="<a href='".$linksitem["linkURL"]."'><font size='".$fontsize."px'>".$linksitem["linkTitle"]."</font></a>";
				$ls_links.="</div>";
				continue;
			}
			$ls_links.="<div class='link_list'>";
			if(file_exists($imagepath)){
				$ls_links.="<a href='".$linksitem["linkURL"]."'><img src='ls_admin/".$imagepath."' border='0' /></a>";
			}
			$ls_links.="<br />";
			if(strlen($linksitem["linkTitle"])!=0){
				$ls_links.="<a href='".$linksitem["linkURL"]."'>".$linksitem["linkTitle"]."</a>";
			}
			$ls_links.="</div>";
		}
		$ls_links.="</div>";
		$content = str_replace("{ls_url}",$ls_links,$content);
		break;

	}
		  
	$handle   = fopen($filename,"w"); //打开文件指针，
		  /*
		　检查文件是否被创建且可写
		  */
		
	if (!is_writable ($filename))
	{ 
		echo "<script>alert('文件：".$filename."不可写，请检查其属性后重试！');history.go(-1);</script>";
	}
	if (!fwrite ($handle,$content))
	{  //将信息写入文件
		echo "<script>alert('生成文件".$filename."失败！');history.go(-1);</script>";
	} 
	fclose ($handle); //关闭指针
	echo "创建 <a href='".$filename."'>".$filename."</a>成功！<a href=\"temp.php?ls=normal\"><u>返回</u></a><br/><br/>";
}
/*
------------------------------------------------------
参数：
$filename 
&$str  content str 的引用

程序功能：写入类下产品页ini文件
------------------------------------------------------
*/
function writegeneralfile($filename,&$str)// 避免字符串太大不方便传递值，只传递引用
{
	$content=$str;
	if (is_file ($filename))
	{ 
	   @unlink ($filename); //若文件已存在，则删除
	}

	$handle   = fopen($filename,"w"); //打开文件指针，
		  /*
		　检查文件是否被创建且可写
		  */
	if (!is_writable ($filename))
	{ 
		echo "文件：".$filename."不可写，请检查其属性后重试！";
	}
	if (!fwrite ($handle,$content))
	{  //将信息写入文件
		//echo " 写入文件".$filename."失败！"
		return false;
	} 
	else
	{ 
		return true;
		//echo " 写入".$filename." 成功<br>";
	}

	fclose ($handle); //关闭指针
					  //die ("创建<a href='".$filename."'>".$filename."</a>成功！<a href=\"temp.php?ls=normal\"><u>返回</u></a>");

}

	/*
------------------------------------------------------
参数：
$varstr   	变量名
$valuestr 	变量值
$vartype 	变量类型 str or 
参数举例	 	writeconstant("lsVer", 1.181 ,"int","","//----版本号参数");	
程序功能：	写入参数文件函数 constant
如果没有插入标志，先插入插入标志;如果没有这个变量，那么 插入这个变量
------------------------------------------------------
*/

function writeconstant($varstr,$valuestr,$vartype,$oprconstant="modify",$insertflag="//----insert flag9",$filename="../ls_admin/inc/constant.php")
{
	
	$handle = fopen($filename,"r");
	$partstr="";
	$partstr0="";
	$modifyOK=false;	//是否成功修改，插入
	while (!feof ($handle)) 
	{
		$partstr0 =  fgets ($handle, 3000);
		//echo rawurlencode($partstr0);
		if(($oprconstant=="modify" || $oprconstant=="" )&& strpos(trim($partstr0),"\$".$varstr."=")===0 )  // 空参数认为是modify
		{
			if($vartype=="str")
			{$partstr0="	\$".$varstr."=\"".$valuestr."\";\n";}
			else
			{$partstr0="	\$".$varstr."=".$valuestr.";\n";}
			$modifyOK=true;
		}

		if($oprconstant=="insert" && strpos(trim($partstr0),$insertflag)===0 && strpos($partstr0,$insertflag."end")===false  )	//插入标志行后面
		{
			//echo (strlen($insertflag)+strpos($partstr0,$insertflag))."mm".strlen($partstr0).$partstr0; exit;
			if($vartype=="str")
			{$partstr0="	\$".$varstr."='".$valuestr."';\n";}
			else
			{$partstr0="	\$".$varstr."=".$valuestr.";\n";}	
			$partstr0="	".$insertflag."\n".$partstr0;
			$modifyOK=true;
		}

		$partstr.=$partstr0;
	}
	//echo strlen($partstr);
	fclose ($handle);
	
	if(!$modifyOK && $oprconstant=="insert")  //如果没有插入标志，先插入插入标志
	{
		if($vartype=="str")
		{$partstr0="	\$".$varstr."=\"".$valuestr."\";\n";}
		else
		{$partstr0="	\$".$varstr."=".$valuestr.";\n";}	
		$partstr0="\n	".$insertflag."\n".$partstr0;
		$partstr=str_replace("?>",$partstr0."?>",$partstr);
		$modifyOK=true;
	}
	
	writegeneralfile($filename,$partstr); // write the constant.php
	if(!$modifyOK) writeconstant($varstr,$valuestr,$vartype,"insert",$insertflag,$filename);  //如果没有修改成功，则没有这个变量，那么 插入这个变量
	
}

/*
------------------------------------------------------
参数：
$currentProgram   目前运行程序
$currentFunction 目前功能
$parameter  参数
程序功能：写入日志函数
------------------------------------------------------
*/

function writelog($currentProgram,$currentFunction,$parameter)
{
	require_once('conn.php');
	global $logSpace,$logStat;
	if($logStat=='stop'){return;}

	$opendb=new mydb();
	require('char_set.php');
	

	$select_sql2="select * from ls_log ";
	$select_query2=$opendb->query($select_sql2);
	$select_rows2=mysql_num_rows($select_query2); //总数

	if($select_rows2>=$logSpace)
	{
		$del_sql="delete  from  ls_log where 1 limit 30";
		$insert_query=$opendb->query($del_sql);	
	}
	$currentFunction=str_replace("'","`",$currentFunction);

	$insert_sql="insert into ls_log(currentDateTime,currentProgram,currentFunction,parameter,memo,ip) values ('".date('Y-m-d G:i:s')."','".$currentProgram."','".$currentFunction."','".$parameter."','','".$_SERVER['REMOTE_ADDR']."')";
	//echo $insert_sql;
	$insert_query=$opendb->query($insert_sql);	
}

/*
------------------------------------------------------
参数：
$querys   传递进入的查询结果
$srDirection 排序方向，目前本参数不起作用
程序功能：对传入的查询结果中的Num字段进行降序赋值。
注意：请不要随意调用本函数，本函数是为之后的排序函数缩减重复代码所设立。
------------------------------------------------------
*/

function SortRows($querys,$srDirection){
	$sortdb=new mydb();
	$totalRows=mysql_num_rows($querys);
	while($queryRows=mysql_fetch_assoc($querys)){
		$updateSql="update ls_products set Num=".$totalRows." where ID=".$queryRows['ID']." ";
		$updateQuery=$sortdb->query($updateSql);
		$totalRows--;
	}
}

/*
------------------------------------------------------
参数：
$spCate   排序产品所属的大类ID
$spMidCate 排序产品所属的中类ID
$spSubCate  排序产品所属的小类ID
$spKind  排序所采用的字段名称
$spDirection  排序方向
$ignore  是否开启整类排序功能
程序功能：对指定的类别中的产品进行批量排序。
注意：本函数中部分参数直接参与SQL语句的组装，直接键入参数时请注意格式是否正确。Products.php文件中的参数指定均为预先固定的，可参考。
------------------------------------------------------
*/
function SortPros($spCate,$spMidCate,$spSubCate,$spKind,$spDirection,$ignore,$onlyGrandCate){
	$sortdb=new mydb();
	if($spCate!="" && $spMidCate=="" && $spSubCate=="" )
	{
		$sortSql="select * from ls_products where productID=".$spCate." order by ".$spKind." ".$spDirection." ";
		//echo $sortSql;
		$sortQuery=$sortdb->query($sortSql);
		SortRows($sortQuery,$spDirection);
	}
	
	if($spCate!="" && $spMidCate!="" && $spSubCate=="" )
	{
		$sortSql="select * from ls_products where productID=".$spMidCate." order by ".$spKind." ".$spDirection." ";
		$sortQuery=$sortdb->query($sortSql);
		SortRows($sortQuery,$spDirection);
	}

	if($spCate!="" && $spMidCate!="" && $spSubCate!="" )
	{
		$sortSql="select * from ls_products where productID=".$spSubCate." order by ".$spKind." ".$spDirection." ";
		$sortQuery=$sortdb->query($sortSql);
		SortRows($sortQuery,$spDirection);
	}
	return true;
}
/*
function SortPros($spCate,$spMidCate,$spSubCate,$spKind,$spDirection,$ignore,$onlyGrandCate){
	$sortdb=new mydb();
	if($onlyGrandCate){
		if($spCate==-1){
			echo "<script language='javascript'>alert('请先进入要排序的类别。'); location.href='products.php';</script>";
		} else {
			$sortSql="select * from ls_products where productID=".$spCate." order by ".$spKind." ".$spDirection." ";
			$sortQuery=$sortdb->query($sortSql);
			SortRows($sortQuery,$spDirection);
		}
		return true;
	}
	if($ignore){
		if($spSubCate==-1){
			if($spMidCate==-1){
				echo "<script language='javascript'>alert('请先进入要排序的类别。'); location.href='products.php';</script>";
			} else {
				$totalSql="select * from ls_products where subcateID=".$spMidCate." ";
				$totalQuery=$sortdb->query($totalSql);
				$sortSql="select * from ls_products where (";
				$conFlagi=0; 
				if(mysql_num_rows($totalQuery)!=0){
					while($totalRow=mysql_fetch_assoc($totalQuery)){
						if($conFlagi==0){
							  $sortSql.="productID=".$totalRow['ID'];
						} else {
							  $sortSql.=" or productID=".$totalRow['ID'];
						}
						$conFlagi++;
					}
				} else {
					$sortSql.="productID=".$spMidCate;
				}
				$sortSql.=") order by ".$spKind." ".$spDirection." ";	
				$sortQuery=$sortdb->query($sortSql);
				SortRows($sortQuery,$spDirection);
			}
		} else {
			$sortSql="select * from ls_products where productID=".$spSubCate." order by ".$spKind." ".$spDirection." ";
			$sortQuery=$sortdb->query($sortSql);
			SortRows($sortQuery,$spDirection);
		}
	} else {
		if($spSubCate==-1){
			if($spMidCate==-1){
				echo "<script language='javascript'>alert('请先进入要排序的类别。'); location.href='products.php';</script>";
			} else {
				$checkSubCateSql="select ID from ls_products where subcateID=".$spMidCate." ";
				$checkSubCateQuery=$sortdb->query($checkSubCateSql);
				if(mysql_num_rows($checkSubCateQuery)!=0){
					echo "<script language='javascript'>alert('非法跨类排序操作，排序中止，程序返回。');location.href='products.php?cateid=".$spCate."&midcateid=".$spMidCate."';</script>";
				} else {
					$sortSql="select * from ls_products where productID=".$spMidCate." order by ".$spKind." ".$spDirection." ";
					$sortQuery=$sortdb->query($sortSql);
					SortRows($sortQuery,$spDirection);
				}
			}
		} else {
			$sortSql="select * from ls_products where productID=".$spSubCate." order by ".$spKind." ".$spDirection." ";
			$sortQuery=$sortdb->query($sortSql);
			SortRows($sortQuery,$spDirection);
		}
	}
	return true;
}

*/

/*
------------------------------------------------------
参数：

程序功能：格式化输出变量内容。用于调试。
------------------------------------------------------
*/

function dump()
{
	$argAmount=func_num_args();
	if ($argAmount==0)
	{
		echo "<pre>";
		echo "Arguements can NOT be empty.";
		echo "</pre>";
	}
	else 
	{
		ob_start();
		echo "<pre>";
		for($i=0;$i<$argAmount;$i++)
		{
			echo "Arguement ".($i+1)."<br>";
			var_dump(func_get_arg($i));
			echo "<br>";
		}
		echo "</pre>";
		$output=ob_get_clean();
		$output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
		echo $output;
	}
}

/*
------------------------------------------------------
参数：

程序功能：对类别进行扫描，并对有错误的类别进行纠正。
------------------------------------------------------
*/

function scancates()
{
	$opdb=new mydb();
	$startsql="select ID from ls_products where cateName is not null order by Num asc, ID asc";
	$startq=$opdb->query($startsql);
	$sentryi=1;
	while($gcate=mysql_fetch_assoc($startq))
	{
		repairseq($gcate['ID'],$sentryi);
		$secondsql="select ID from ls_products where midcateName is not null and midcateID='{$gcate['ID']}' order by Num asc, ID asc";
		$secondq=$opdb->query($secondsql);
		$sentryj=1;
		while($mcate=mysql_fetch_assoc($secondq))
		{
			repairseq($mcate['ID'],$sentryj);
			$thirdsql="select ID from ls_products where subcateID is not null and subcateID={$mcate['ID']} order by Num asc, ID asc";
			$thirdq=$opdb->query($thirdsql);
			$sentryk=1;
			while($scate=mysql_fetch_assoc($thirdq))
			{
				repairseq($scate['ID'],$sentryk);
				$sentryk++;
			}
			$sentryj++;
		}
		$sentryi++;
	}
}

/*
------------------------------------------------------
参数：	$opid		要操作的记录ID
		$opnum		设定的数值

返回值：无

程序功能：重新将指定ID的Num字段赋值，此为复杂功能拆解模块，请勿直接调用
------------------------------------------------------
*/

function repairseq($opid,$opnum)
{
	$opdb=new mydb();
	$resetsql="update ls_products set Num={$opnum} where ID={$opid}";
	$resetq=$opdb->query($resetsql);
}

/*
------------------------------------------------------
参数：	$opid		查询产品ID

返回值：布尔值

程序功能：查询与产品是否有同级别的类别，有返回真，无返回假。
------------------------------------------------------
*/

function hassameclass($opid)
{
	$opdb=new mydb();
	$checksql="select * from ls_products where midcateID='{$opid}' or subcateID={$opid}";
	$checkq=$opdb->query($checksql);
	if(mysql_num_rows($checkq)!=0){
		return true;
	}else{
		return false;
	}
}



/*------------------------------------------------------
//  发送邮件的函数，适用于webmotor,从数据库获得反馈邮箱
//　在一般php文件中，用于php文件头的下面，适用于一个form反馈
//　使用方法：sendmail($_POST)  返回相关信息
------------------------------------------------------*/
function sendmail($postvars){

require_once('ls_admin/inc/conn.php');
$opendb=new mydb();
require_once('ls_admin/inc/char_set.php');
global $sendmailOKMsg,$sendmailFailMsg;

$Back=($HTTP_REFERER==""?$_SERVER['HTTP_HOST']:$HTTP_REFERER);      /* 返回路径 */
$Subject="Information from ".$Back;  /* 标题*/
$Content="";

$config_sql="select * from ls_config ";
$config_query=$opendb->query($config_sql);
$config_rows=mysql_fetch_assoc($config_query);
$emailAddress=$config_rows['feedbackEmail'];

	if(count($postvars)!=0)  //pass vars fron URL
	{
		while(list($akey,$avalue)=each($postvars))
		{
    		switch ($akey)
    		{
    		case "Mr":
       		$Mr=$avalue;
       		break;
    		case "name":
        	$name=$avalue;
       		break;
    		case "Submit":
        	break;
			//sino-parts.com 定制
    		case "ec_cid":
        	break;
    		case "guid":
        	break;
    		case "ls2":
        	break;
			
   			default:
			if(strpos($akey,"select")===0||strpos($akey,"button")===0){break;}
	    	$Content.=urldecode($akey).":  ";
	    	$Content.=urldecode($avalue)."\n";
        	break;
    		}
		}
	}


	if(mail($emailAddress,$Subject,$Content))
	{
		return($sendmailOKMsg);//成功没信息，失败给提示
	}
	else
	{
		return($sendmailFailMsg);
	}
}

?>
