<?php
function litimgurls($imgid=0)
{
    global $lit_imglist,$dsql;
    //获取附加表
    $row = $dsql->GetOne("SELECT c.addtable FROM #@__archives AS a LEFT JOIN #@__channeltype AS c 
                                                            ON a.channel=c.id where a.id='$imgid'");
    $addtable = trim($row['addtable']);
    
    //获取图片附加表imgurls字段内容进行处理
    $row = $dsql->GetOne("Select imgurls From `$addtable` where aid='$imgid'");
    
    //调用inc_channel_unit.php中ChannelUnit类
    $ChannelUnit = new ChannelUnit(2,$imgid);
    
    //调用ChannelUnit类中GetlitImgLinks方法处理缩略图
    $lit_imglist = $ChannelUnit->GetlitImgLinks($row['imgurls']);
    
    //返回结果
    return $lit_imglist;
}

/**
* 获取一个类目的顶级栏目
* @param string $tid 栏目ID
* @return string
*/
if ( ! function_exists('gettoptype'))
{
	function gettoptype($tid,$action)
	{
		global $dsql,$cfg_Cs;
		if(!is_array($cfg_Cs))
		{
			require_once(DEDEDATA."/cache/inc_catalog_base.inc");
		}
		if(!isset($cfg_Cs[$tid][0]) || $cfg_Cs[$tid][0]==0)
		{
			$topid = $tid;
		}
		else
		{
			$topid = GetTopid($cfg_Cs[$tid][0]);
		}
		$row = $dsql->GetOne("SELECT * FROM `#@__arctype` WHERE id=$topid");
		$toptypename = $row['typename'];
		$toptypeurl = $topid;
		if($action=='id') return $topid;
		if($action=='name') return $toptypename;
		if($action=='link') return GetOneTypeUrlA($row);
		if($action=='pic') return $row['typelitpic'] ? $row['typelitpic'] : '/images/notypelitpic.jpg';
		if($action=='typenamedir') return $row['typenamedir'];
		if($action=='seotitle') return $row['seotitle'];
		if($action=='description') return $row['description'];
	}
}

/**
* 获取一个类目的url
* @param string $tid 栏目ID
* @return string
*/
if ( ! function_exists('mygettype'))
{
	function mygettype($tid,$action)
	{
		global $dsql;
		$row = $dsql->GetOne("SELECT * FROM `#@__arctype` WHERE id=$tid");
		$typename = $row['typename'];
		$typeurl = $tid;
		if($action=='id') return $tid;
		if($action=='name') return $typename;
		if($action=='link') return GetOneTypeUrlA($row);
		if($action=='pic') return $row['typelitpic'] ? $row['typelitpic'] : gettoptype($tid,'pic');
		if($action=='typenamedir') return $row['typenamedir'];
		if($action=='seotitle') return $row['seotitle'];
		if($action=='description') return $row['description'];
	}
}

//取第一张图地址
function firstimg($str_pic)
{
	$ext = strrchr($str_pic,'.');//获取图片后缀
	$str_sub=substr($str_pic,0,-7)."$ext";//删除缩略图字符串最后七位，然后再补上后缀
	return $str_sub;
}

//取原图地址
function bigimg($str_pic)
{
	$str_houzhi=substr($str_pic,-4);
	$str_sub=substr($str_pic,0,-7).$str_houzhi;//删除缩略图字符串最后七位，然后再补上后缀.jpg
	return $str_sub;
}

//tag字体
function getTagStyle()
{
	$minFontSize=8; //最小字体大小,可根据需要自行更改
	$maxFontSize=18; //最大字体大小,可根据需要自行更改
	return 'font-size:'.($minFontSize+lcg_value()*(abs($maxFontSize-$minFontSize))).'px;color:#'.dechex(rand(0,255)).dechex(rand(0,196)).dechex(rand(0,255));
}

/**
*  获得软件模型soft下载地址
*/
if (!function_exists('GetDownLink'))
{
    function GetDownLink($aid)
    {
       global $dsql;
       $row= $dsql->GetOne("SELECT softlinks FROM `#@__addonsoft` WHERE aid = {$aid}");
           if(!is_array($row)){
            return '';
            }
           else{
            $dtp = new DedeTagParse();
            $dtp->LoadSource($row['softlinks']);
                foreach($dtp->CTags as $ctag)
                {
                    if($ctag->GetName()=='link')
                {
                    $link = trim($ctag->GetInnerText());
                }
            }
       }
       return  $link;
    }
}

/**
*  获得自定义模型图片地址
*  [field:bigpic function='GetOneImgUrl(@me,0)'/]	有html
*  [field:bigpic function='GetOneImgUrl(@me)'/]
*  {dede:field.bigpic function='GetConImgUrl(@me)'/}
*/
if (!function_exists('GetOneImgUrl'))
{
	function GetOneImgUrl($img, $ftype = 1)
	{
		if ($img != '') {
			$dtp = new DedeTagParse();
			$dtp->LoadSource($img);
			if (is_array($dtp->CTags)) {
				foreach ($dtp->CTags as $ctag) {
					
					if ($ctag->GetName() == 'img') {
						$width = $ctag->GetAtt('width');
						$height = $ctag->GetAtt('height');
						$imgurl = trim($ctag->GetInnerText());
						$img = '';
						if ($imgurl != '') {
							if ($ftype == 1) {
								$img .= $imgurl;
							} else {
								$img .= '<img src="' . $imgurl . '" width="' . $width . '" height="' . $height . '" />';
							}
						}
					}
				}
			}
			$dtp->Clear();
			return $img;
		}
	}
}


/**
*  自定义模型内容页获得自定义模型图片地址
*/
if (!function_exists('GetConImgUrl'))
{
	function GetConImgUrl($img){
		preg_match("/<img src='(.*)'/isU",$img,$imgurl);
		return $imgurl[1];
	}
}

/**
*  加载模板文件
*
<?php
	pasterTempletDiy("head.htm");
?>
*
*/
function pasterTempletDiy($path)
{
	require_once(DEDEINC."/arc.partview.class.php");
	global $cfg_basedir,$cfg_templets_dir,$cfg_df_style;
	$tmpfile = $cfg_basedir.$cfg_templets_dir.'/'.$cfg_df_style.'/'.$path;//模版文件
	$dtp = new PartView();
	$dtp->SetTemplet($tmpfile);
	$dtp->Display();
}

/**
*  获取图集图片数量
*  共[field:id  function="Getimgnum(@me)"/]张
*/
function Getimgnum($aid)     
{
    global $dsql;
    $imgurls = '';
    $row =$dsql->getone( "Select imgurls From `#@__addonimages` where aid='$aid' ");
    $imgurls= $row['imgurls'];
    preg_match_all("/{dede:img (.*){\/dede:img/isU",$imgurls,$wordcount);
    $count=count($wordcount[1]);
    return $count;
}

//统计栏目文章数 [field:id function="GetTotalArc(@me)" /] / {dede:field.id runphp='yes'}@me=GetTotalArc(@me);{/dede:field.id}
function GetTotalArc($tid){
	global $dsql;
	$sql = GetSonIds($tid);
	$row = $dsql->GetOne("Select count(id) as total From `#@__archives` where typeid in({$sql})");
	return $row['total'];
}
/*
*
*
{dede:field name='typename'/}</b>(此栏目共{dede:type}[field:id 
function="dynamic_num(@me)" /]{/dede:type}条记录)
{dede:channel type='son' }
<li><a href='[field:typelink/]'>[field:typename/]</a>(<span>[field:ID 
runphp='yes'] @me = GetTotalArc(@me);[/field:ID]</span>)</li>
{/dede:channel}
*
*/
//统计当前栏目信息数
function dynamic_num($current_id){
	global $dsql;
	//读取当前栏目的子ID
	$sql = "SELECT id FROM `#@__arctype` WHERE id='$current_id' ||
	topid='$current_id'";
	$dsql->SetQuery($sql);
	$dsql->Execute();
	while($row = $dsql->GetArray()){
		$arr[]=$row[id];
	}
	foreach($arr as $key=>$value){
		$type .= $value . ',';
	}
	$ty= "".$type."0";
	$t_num = $dsql->GetOne("select count(*) as num from `#@__archives` where typeid
	in($ty)");
	if(is_array($t_num)){
		return " ".$t_num[num]." ";
	}else{
		return "0" ;
	}
}
//从ID里拿URL
//[field:aid function=IDReturnURL(@me)/]
function IDReturnURL($ID)
{
	//lonely
	global $dsql;
	$query = "Select arc.*,tp.typedir,tp.typename,tp.corank,tp.isdefault,
	tp.defaultname,tp.namerule,tp.moresite,tp.siteurl,tp.sitepath
	from `#@__archives` arc left join `#@__arctype` tp on arc.typeid=tp.id where arc.id = ".$ID;
	$row = $dsql->GetOne($query);
	$ReturnURL = GetFileUrl($row['id'],$row['typeid'],$row['senddate'],$row['title'],$row['ismake'],
	$row['arcrank'],$row['namerule'],$row['typedir'],$row['money'],$row['filename'],$row['moresite'],$row['siteurl'],$row['sitepath']);
	return $ReturnURL;
}

function thumb($imgurl, $width, $height, $bg = true) 
{ 
	global $cfg_mainsite,$cfg_multi_site;
	$thumb = eregi("http://",$imgurl)?str_replace($cfg_mainsite,'',$imgurl):$imgurl; 
	list($thumbname,$extname) = explode('.',$thumb); 
	$newthumb = $thumbname.'_'.$width.'_'.$height.'.'.$extname;
	if(!$thumbname || !$extname || !file_exists(DEDEROOT.$thumb)) return $imgurl;
	if(!file_exists(DEDEROOT.$newthumb))
	{ 
	include_once DEDEINC.'/image.func.php';
	if($bg==true)
	{
	ImageResizeNew(DEDEROOT.$thumb, $width, $height, DEDEROOT.$newthumb);
	}
	else
	{
	ImageResize(DEDEROOT.$thumb, $width, $height, DEDEROOT.$newthumb);
	} 
	}
	return $cfg_multi_site=='Y'?$cfg_mainsite.$newthumb:$newthumb;
}

function GetArcTitle($id)
{
	global $dsql;
	$row = $dsql->GetOne("SELECT title FROM `#@__archives` WHERE id=$id");
	return $row['title'];
}

/*
首页，列表调用图集图片 [field:id function="Getimg(@me,268,471,3)" /]
*/
function Getimg($aid,$imgwith=110,$imgheight=110,$num=0)    
{    
	global $dsql;
	
	$imgurls = '';
	$row = $dsql->GetOne( "Select imgurls From `#@__addonimages` where aid='$aid' ");
	$imgurls= $row['imgurls'];
	preg_match_all("/{dede:img (.*)} (.*){\/dede:img/isU",$imgurls,$wordcount);
	$count = count($wordcount[2]);
	if ($num>$count || $num==0){$num=$count;}
	
	for($i=0;$i<$num;$i++)
	{
		$imglist.="<li><img src=".trim($wordcount[2][$i])." width=".$imgwith." height=".$imgheight."></li>";
	}
	return $imglist;     
}
/*
首页，列表调用图集第一个图片 [field:id function="get_firstbigimg(@me)" /]
首页，列表调用图集第一个图片 {dede:field.typeid function='get_firstbigimg(@me)'/}
*/
function get_firstbigimg($aid){
	global $dsql; 
	$row = $dsql->GetOne( "Select imgurls From `#@__addonimages` where aid='$aid' ");
	$imgurls= $row['imgurls'];
	preg_match_all("|height='.*'}(.*){/dede:img}|Uis",$imgurls,$imgurls2);
    $get_firestimg = $imgurls2[1][0];  
    return $get_firestimg;  
}

//获得某文档的所有tag 
//[field:id function=MyGetTags(@me)/]
function MyGetTags($aid,$num=3) 
{ 
     global $dsql; 
     $tags = ''; 
     $query = "Select tag From `#@__taglist` Where aid='$aid' limit $num "; 
     $dsql->Execute('tag',$query); 
     while($row = $dsql->GetArray('tag')) 
     { 
         $tags.= ($tags=='' ? "<a  href=/tags.php?/{$row['tag']} target=_blank>{$row['tag']}</a>" : ','."<a href=/tags.php?/{$row['tag']} target=_blank>{$row['tag']}</a>"); 
     } 
     return $tags; 
}
//统计评论数
//{dede:field.id function="feedback_num(@me)"/}
function feedback_num($aid)
{
	global $dsql;
	$row = $dsql->GetOne("Select count(id) as c From `#@__feedback` Where aid=$aid");
	if($row['c'])
		return $row['c'] ;
	else
		return '0 ';
}
function deldir($dir)
{
	$dh=opendir($dir);
	while ($file=readdir($dh))
	{
		if($file!="." && $file!="..")
		{
			$fullpath=$dir."/".$file;
			if(!is_dir($fullpath))
			{
				unlink($fullpath);
			}
			else
			{
				deldir($fullpath);
			}
		}
	}
	closedir($dh);
	if(rmdir($dir))
	{
		return true;
	}
	else
	{
		return false;
	}
}

/*
*获取字符串的第一个图片地址
*/
function getbodyfirstpic($str_img){
    preg_match_all("/<img.*\>/isU",$str_img,$ereg);//正则表达式把图片的整个都获取出来了 
    $img=$ereg[0][0];//图片 
    $p="#src=('|\")(.*)('|\")#isU";//正则表达式
    preg_match_all ($p, $img, $img1); 
    $img_path =$img1[2][0];//获取第一张图片路径  
    return $img_path; //仅返回地址
	//return $img; //返回整个图片
}


//dedecms联动筛选功能 字符过滤函数
function wwwcms_filter($str, $stype = 'inject')
{
    if ($stype == 'inject') {
        $str = str_replace(array('select', 'insert', 'update', 'delete', 'alter', 'cas', 'union', 'into', 'load_file', 'outfile', 'create', 'join', 'where', 'like', 'drop', 'modify', 'rename', '\'', '/*', '*', '../', './'), array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''), $str);
    } else {
        if ($stype == 'xss') {
            $farr = array('/\\s+/', '/<(\\/?)(script|META|STYLE|HTML|HEAD|BODY|STYLE |i?frame|b|strong|style|html|img|P|o:p|iframe|u |em|strike|BR|div|a|TABLE|TBODY|object|tr|td |st1:chsdate|FONT|span|MARQUEE|body|title |
|link |meta|\\?|\\%)([^>]*?)>/isU', '/(<[^>]*)on[a-zA-Z]+\\s*=([^>]*>)/isU');
            $tarr = array(' ', '', '\\1\\2');
            $str = preg_replace($farr, $tarr, $str);
            $str = str_replace(array('<', '>', '\'', '"', ';', '/*', '*', '../', './'), array('&lt;', '&gt;', '', '', '', '', '', '', ''), $str);
        }
    }
    return $str;
}
/**
 *  载入自定义表单(用于发布)
 *
 * @access    public
 * @param     string  $fieldset  字段列表
 * @param     string  $loadtype  载入类型
 * @return    string
 */
function AddFilter($channelid, $type = 1, $fieldsnamef, $defaulttid, $loadtype = 'autofield')
{
    global $tid, $dsql, $id;
    $tid = $defaulttid ? $defaulttid : $tid;
    if ($id != '') {
        $tidsq = $dsql->GetOne(" Select typeid From `#@__archives` where id='{$id}' ");
        $tid = $tidsq['typeid'];
    }
    $nofilter = (isset($_REQUEST['TotalResult']) ? '&TotalResult=' . $_REQUEST['TotalResult'] : '') . (isset($_REQUEST['PageNo']) ? '&PageNo=' . $_REQUEST['PageNo'] : '');
    $filterarr = wwwcms_filter(stripos($_SERVER['REQUEST_URI'], 'list.php?tid=') ? str_replace($nofilter, '', $_SERVER['REQUEST_URI']) : $GLOBALS['cfg_cmsurl'] . '/plus/list.php?tid=' . $tid);
    $cInfos = $dsql->GetOne(" Select * From  `#@__channeltype` where id='{$channelid}' ");
    $fieldset = $cInfos['fieldset'];
    $dtp = new DedeTagParse();
    $dtp->SetNameSpace('field', '<', '>');
    $dtp->LoadSource($fieldset);
    $dede_addonfields = '';
    if (is_array($dtp->CTags)) {
        foreach ($dtp->CTags as $tid => $ctag) {
            $fieldsname = $fieldsnamef ? explode(',', $fieldsnamef) : explode(',', $ctag->GetName());
            if (($loadtype != 'autofield' || $loadtype == 'autofield' && $ctag->GetAtt('autofield') == 1) && in_array($ctag->GetName(), $fieldsname)) {
                $href1 = explode($ctag->GetName() . '=', $filterarr);
                $href2 = explode('&', $href1[1]);
                $fields_value = $href2[0];
                $dede_addonfields .= '<div class="scv-shaixuan"><b>' . $ctag->GetAtt('itemname') . '：</b>';
                switch ($type) {
                    case 1:
                        $dede_addonfields .= (preg_match('/&' . $ctag->GetName() . '=/is', $filterarr, $regm) ? '<a title="全部" href="' . str_replace('&' . $ctag->GetName() . '=' . $fields_value, '', $filterarr) . '">全部</a>' : '<span>全部</span>') . '&nbsp;';
                        $addonfields_items = explode(',', $ctag->GetAtt('default'));
                        for ($i = 0; $i < count($addonfields_items); $i++) {
                            $href = stripos($filterarr, $ctag->GetName() . '=') ? str_replace('=' . $fields_value, '=' . urlencode($addonfields_items[$i]), $filterarr) : $filterarr . '&' . $ctag->GetName() . '=' . urlencode($addonfields_items[$i]);
                            $dede_addonfields .= ($fields_value != urlencode($addonfields_items[$i]) ? '<a title="' . $addonfields_items[$i] . '" href="' . $href . '">' . $addonfields_items[$i] . '</a>' : '<span>' . $addonfields_items[$i] . '</span>') . '&nbsp;';
                        }
                        $dede_addonfields .= '</div>';
                        break;
                    case 2:
                        $dede_addonfields .= '<select name="filter"' . $ctag->GetName() . ' onchange="window.location=this.options[this.selectedIndex].value">' . '<option value="' . str_replace('&' . $ctag->GetName() . '=' . $fields_value, '', $filterarr) . '">全部</option>';
                        $addonfields_items = explode(',', $ctag->GetAtt('default'));
                        for ($i = 0; $i < count($addonfields_items); $i++) {
                            $href = stripos($filterarr, $ctag->GetName() . '=') ? str_replace('=' . $fields_value, '=' . urlencode($addonfields_items[$i]), $filterarr) : $filterarr . '&' . $ctag->GetName() . '=' . urlencode($addonfields_items[$i]);
                            $dede_addonfields .= '<option value="' . $href . '"' . ($fields_value == urlencode($addonfields_items[$i]) ? ' selected="selected"' : '') . '>' . $addonfields_items[$i] . '</option>';
                        }
                        $dede_addonfields .= '</select><br/>';
                        break;
                }
            }
        }
    }
    echo $dede_addonfields;
}