<?php

/*================= 字符串函数 ========================*/

/*
字符串$str是否精确匹配
数组$stack里 的项目
*/
function strin($str,$stack,$ignorecase=true){
	$str=trim($str);
	if($ignorecase)$str=strtolower($str);

	//echo $str."--1--".$stack[0]."<br/>";
	for($i=0;$i< count($stack);$i++){ 
		if($ignorecase) $stacki=strtolower($stack[$i]); else $stacki= $stack[$i] ;
		if( $str==trim($stacki))return true;
	}
    return false;
}

/*
在数组$stack里 的每个项目
是否是字符串$str一部分
*/
function strinclude($str,$stack,$ignorecase=true){
	$str=trim($str);
	if($ignorecase)$str=strtolower($str);
	 

	//echo $str."--1--".$stack[0]."<br/>";
	for($i=0;$i< count($stack);$i++){ 
		if($ignorecase)$stacki=strtolower($stack[$i]);
		if(!( strpos($str,trim( $stacki ))===false))return true;
	}
    return false;
}	


function ggdecode($str){
    $str=str_replace("\\x26lt;","<",$str);
    $str=str_replace("\\x3d","=",$str);
    $str=str_replace("\\x26#39;","'",$str);
    $str=str_replace("\\x26gt;",">",$str);
    return $str;
}

/*
获得 title 里面的 keyword1,keyword2,brand(company name)
返回数组 0,1,2 分别是上面 变量
*/
function gettitlekeyword(){
	require_once('conn.php');
	$opendb=new mydb();
	require_once('char_set.php');
	
	$config_sql="select * from ls_config ";
	$config_query=$opendb->query($config_sql);
	$config_rows=mysql_fetch_assoc($config_query);
	
	$title=trim($config_rows['companyName']);
	$title=str_replace("_","|",$title);
	$title=str_replace(",","|",$title);
	$title=str_replace("-","|",$title);
	$title=str_replace(".|",".,",$title); // Co., Ltd
	$title=str_replace(". |",".,",$title); // Co., Ltd
	
	$titlea=explode("|",$title);
	$titlea2=array();

	for($i=0;$i<=count($titlea);$i++){
		if($i==0)	$titlea2[0]=trim($titlea[0]);
		if($i==1)	$titlea2[1]=trim($titlea[1]);
		if($i>1 && trim($titlea[$i])!="")	$title3=trim($titlea[$i]);
	}
	
	if($title3!="")	$titlea2[2]=$title3;
	 
	return $titlea2;
}



//去除固定开头结尾的串（注释）
//$content 输入字符串
//$str1="<!--" 开始
//$str2="-->" 结束

function strippattern($content,$str1="<!--",$str2="-->"){		 
		$p = "%".$str1."(.*?)".$str2."%si";    //正则表达式
		preg_match_all($p, $content, $arr);
		$temarr = $arr[1];

		foreach($temarr as $val){
			$content = str_replace($str1.$val.$str2.PHP_EOL , "", $content);
			$content = str_replace($str1.$val.$str2, "", $content);
			$content = str_replace("\r\n\r\n", "\r\n", $content); //去掉双空行
		}
		return  $content;
};



//给固定开头结尾的所有串（注释）增加 $addstr
//$content 输入字符串
//$str1="<!--" 开始
//$str2="-->" 结束

function addpattern($content,$addstr,$str1="<!--",$str2="-->"){		 
		$p = "%".$str1."(.*?)".$str2."%si";    //正则表达式
		preg_match_all($p, $content, $arr);
		$temarr = $arr[1];

		foreach($temarr as $val){
			$content = str_replace($str1.$val.$str2, $str1.$addstr." ".$val.$str2, $content);
		}
		return  $content;
}
//去除<translate>
//$procontent 输入字符串

function cleartranslate($procontent ){	
	  $p = "%<translate>(.*?)</translate>%si";    //正则表达式
	  preg_match_all($p, $procontent, $arr);
	  $temarr = $arr[1];
	  
	  foreach($temarr as $val){
		  $procontent = str_replace("<translate>".$val."</translate>", $val, $procontent);
	  }
	  return  $procontent;
}

//二维数组中查询查值，返回 查到的一维数组  翻译系统用到
function deep_in_array($value, $array) {
	$cars = array();
	foreach($array as $k=>$val){
		if($val['translate_name'] == $value){
			$cars = $val;
			return $cars;
		}
	}
	return $cars;
}

//1,2 维数组是否包含某值，区分大小写
function deep_in_array12($value, $array) {
    foreach($array as $item) {
        if(!is_array($item)) {
            if ($item == $value) {
                return true;
            } else {
                continue;
            }
        }
        if(in_array($value, $item)) {
            return true;
        } else if(deep_in_array($value, $item)) {
            return true;
        }
    }
    return false;
}

/*------------------------------------------------------
按照换行分割的网址串 分别设置url链接，并_blank打开网页，网址可以是 http，也可以是https

$urlstr 用'\r\n'割的字符串
 
$flag="\r\n" 
$blankrepl=""  分隔开的词组，空格如何处理
$breakflag="\r\n"  分割 默认是"\r\n"
*/

function clearkeywords($siteKeywords ) {
	$siteKeywords =str_replace("'","\'",$siteKeywords  );
	$siteKeywords =str_replace("，",",",$siteKeywords );
	$siteKeywords =str_replace("、",",",$siteKeywords );
	$siteKeywords =str_replace("|",",",$siteKeywords );
	$siteKeywords =str_replace("\r\n",",",$siteKeywords );
	$siteKeywords =str_replace(",,,,",",",$siteKeywords );
	$siteKeywords =str_replace(",,",",",$siteKeywords );
	$siteKeywords =str_replace("-",",",$siteKeywords );
	$siteKeywords =trim(str_replace(" - ",",",$siteKeywords ));
	return $siteKeywords ;
}


/*
getStrbyTag 通过匹配首串 和尾串 获得中间首串 和尾串 的字符串
$headTag,$tailTag 首串和尾串
true 包括首尾串
返回获得的串
$imgwidth=getStrbyTag('width=',' ',$newsImgStr,false);
*/

function getStrbyTag($headTag,$tailTag,$str,$includeHeadTail=true)
{
		$midStr=substr($str,strpos($str,$headTag),strlen($str));
		$gotStr=strtolower(substr($midStr,0,strpos($midStr,$tailTag)+strlen($tailTag)));
		
		if(!$includeHeadTail)
		{
			$gotStr=str_replace($headTag,"",$gotStr);
			$gotStr=str_replace($tailTag,"",$gotStr);
			
		}
		//echo "1--".$gotStr."--1";
		return $gotStr;
}

//数字字母随机取n位
function getrandchar($length=4)
{
	$str = "";
	$strPol = "0123456789abcdefghijklmnopqrstuvwxyz";
	//$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
	$max = strlen($strPol)-1;
 
	for($i=0;$i<$length;$i++){
	$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}
	return $str;
}


/*================= 文件夹函数 ========================*/

/*------------------------------------------------------
//  递归建立文件夹及子文件夹
//　使用方法crmkdir($folder)  $folder 多级文件夹
------------------------------------------------------*/
function crmkdir($folder)
{
	$mkfolder="";
	$allfolder=explode("/",$folder);
	for($i=0;$i<= count($allfolder);$i++)
	{
		if($allfolder[$i]=="..")
		{
			if($i==0)
			{
				$mkfolder=$allfolder[$i];
			}
			else
			{
				$mkfolder=$mkfolder."/".$allfolder[$i];
			}
		}
		else
		{
			$mkfolder=$mkfolder."/".$allfolder[$i];
			//echo 	$mkfolder."--";
			if(!file_exists($mkfolder))
			{
				mkdir($mkfolder);
			}
		}
		
	}
	
}

//创建3层2字母文件夹，没有就创建
function mrpicpath(){
	$l=chr(rand(97, 122));
	$n=rand(0, 9);
	$fd="i.bosscdn.com/product/".$l.$n;
	
	$l=chr(rand(97, 122));
	$n=rand(0, 9);
	$fd.="/".$l.$n;
	
	$l=chr(rand(97, 122));
	$n=rand(0, 9);
	$fd.="/".$l.$n;
	
	if (!is_dir("../".$fd)) crmkdir("../".$fd);
	
	return $fd;
}

/*================= 文件函数 ========================*/



/*
------------------------------------------------------
参数：
$srca= array(	'1' => $initCreatTypeHost,  //替换 192.168.2.20 为 域名
				'2' => '2.20', ); 
$obja= array(	'1' => $clearURL,
				'2' => $clearURL,); 

$filename  文件名
$stra 要替换的源字符数串数组
$obja 替换的目标字符数串数组
程序功能 读入文件$filename替换 源数组 $srca 为目标数组 $obj
a
------------------------------------------------------
*/
function writereplacestr($filename,$srca,$obja)
{
	
	$fp       = fopen ($filename,"r");
	$content  = fread ($fp,filesize ($filename));
	
	 for($i=1;$i<= count($srca);$i++){   
  		$content  = str_replace($srca[$i],$obja[$i],$content);
    }


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

	fclose ($handle); //关闭指针
	fclose ($fp); //关闭指针
}

/*================= 产品 类别函数 ========================*/

//返回是否第一个产品
function isfirstpro( $id){
		require_once('inc/conn.php');
		$opendb=new mydb();
		require_once('inc/char_set.php');
		$s_catepics="";
		$catepics_sql="select * from ls_products where  enable=1 order by ID asc";
		$catepics_query=$opendb->query($catepics_sql);
		$rows=mysql_fetch_assoc($catepics_query);
		if($rows['ID']==$id) return true; else return false; 
		 
}

/*
------------------------------------------------------
参数：
$cateName 大类名，为空查所有大类数量；不空查此大类中类数
$midcatename  中类名，
------------------------------------------------------
*/
function getcatetotal($catename="",$midcatename="")
{
	if($catename==""){
		$select_sql2="select * from ls_products where cateName!='' ";
		$select_query2=$opendb->query($select_sql2);
		$select_rows2=mysql_num_rows($select_query2); //总产品数
		return $select_rows2;
	}else{
		if($midcatename==""){
			$select_sql2="select * from ls_products where cateName!='".$catename."' ";
			$select_query2=$opendb->query($select_sql2);
			$select_rows2=mysql_num_rows($select_query2); //总产品数
			return $select_rows2;
		}
	}
}

//测试url 打开是否正常，如果显示为200则正常，如果显示其它值表示不正常；$timeout后面的3是设置超时秒数
function httptest($url){
	//设置最大执行时间是8秒
	$maxtime=ini_get('max_execution_time') ;
	
	ini_set('max_execution_time',8);
	$ch = curl_init();
	$timeout = 4;
	
	if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
   		 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	}
	
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt($ch,CURLOPT_URL,$url);
	
	curl_exec($ch);
	return $httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
	curl_close($ch);
	ini_set('max_execution_time', $maxtime);
}

//根据关键词 获得产品页链接，先 类别 后产品
function  getproducturl($keyw){
	$opendb=new mydb();
 	
	//ls_products
	$sql="SELECT * FROM `ls_products` WHERE lower(cateName)='".strtolower($keyw)."' or  lower(midcateName)='".strtolower($keyw)."' or  lower(subcateName)='".strtolower($keyw)."' or  lower(productName)='".strtolower($keyw)."'  and enable=1     order by ID desc";
	 
	$query=$opendb->query($sql);
	$Num=1;
	while($rows=mysql_fetch_assoc($query)){
		if($rows['cateName']!=""||$rows['midcateName']!=""||$rows['subcateName']!="")
		{
			if($rows['cateName']!=""){
				$writeurl1="/".$rows['cateFolders']."/";
			}
			if($rows['midcateName']!=""){
				$writeurl1=getproductpath($rows['midcateID'])."/".$rows['midcateFolders']."/";
			}
			$writeurl2="products_".$rows['ID'].".html";
			$keywords=$rows['cateKeywords'];
		}
		else{
			 $writeurl1=getproductfolder($rows['productID'])."/".$rows['productName']."_".$rows['ID'].".html";
			 $writeurl2="productsshow_".$rows['ID'].".html";
			 $keywords=str_replace("'","''",$rows['productKeywords']);

		}
		
 
		$Num++;
	
	}
	return  $writeurl1;
	//return $writeurl2;
}

//根据产品productID, 查询大类名称
function get_cateName($productID){
	
	$opendb=new mydb();
	require('char_set.php');
	require('constant.php');
	$midcate_pic_sql="SELECT * FROM `ls_products` WHERE ID = ".$productID."";
	$midcate_pic_query=$opendb->query($midcate_pic_sql);
	$midcate_pic_rows=mysql_fetch_assoc($midcate_pic_query);
	
	if($midcate_pic_rows['cateName'] != "" && $midcate_pic_rows['midcateName'] == "" && $midcate_pic_rows['subcateName'] == ""){  //大类
		return $midcate_pic_rows['cateName'];
	}elseif($midcate_pic_rows['cateName'] == "" && $midcate_pic_rows['midcateName'] != "" && $midcate_pic_rows['subcateName'] == ""){  //中类
		
		$subcate_pic_sql="SELECT * FROM `ls_products` WHERE `ID`=".$midcate_pic_rows['midcateID']."";
		$subcate_pic_query=$opendb->query($subcate_pic_sql);
		$subcate_pic_rows=mysql_fetch_assoc($subcate_pic_query);
		
		return $subcate_pic_rows['cateName'];
	}elseif($midcate_pic_rows['cateName'] == "" && $midcate_pic_rows['midcateName'] == "" && $midcate_pic_rows['subcateName'] != ""){  //小类
		
		$subcate_sql="SELECT * FROM `ls_products` WHERE `ID`=".$midcate_pic_rows['subcateID']."";
		$subcate_query=$opendb->query($subcate_sql);
		$subcate_rows=mysql_fetch_assoc($subcate_query);
		
		
		$subcate_pic_sql="SELECT * FROM `ls_products` WHERE `ID`=".$subcate_rows['midcateID']."";
		$subcate_pic_query=$opendb->query($subcate_pic_sql);
		$subcate_pic_rows=mysql_fetch_assoc($subcate_pic_query);
		
		return $subcate_pic_rows['cateName'];
	}

}

?>