<?php

/**
 * ECSHOP 自定义数据调用函数包
*/

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}
/*----------二次开发调用类----------*/

if(!function_exists("index_comments")){

function index_comments($num)
{
   /*$sql = 'SELECT a.*,b.goods_id,b.goods_thumb,b.goods_name FROM '. $GLOBALS['ecs']->table('comment') .
            ' AS a,'. $GLOBALS['ecs']->table('goods') .'AS b WHERE a.status = 1 AND a.parent_id = 0 and a.comment_type=0 and a.id_value=b.goods_id'.
            ' GROUP BY a.id_value ORDER by a.comment_id DESC';*/
   $sql = 'SELECT DISTINCT a.id_value,b.goods_id,b.goods_thumb,b.goods_name FROM '. $GLOBALS['ecs']->table('comment') .' AS a,'. $GLOBALS['ecs']->table('goods') .'AS b WHERE a.status = 1 AND a.parent_id = 0 and a.comment_type=0 and a.id_value=b.goods_id'.' ORDER by a.comment_id DESC';
			
  if ($num > 0)
  {
   $sql .= ' LIMIT ' . $num;
  }
  $res = $GLOBALS['db']->getAll($sql);
  $comments = array();
  foreach ($res AS $idx => $row)
  {
       $comments[$idx]['id_value']       = $row['id_value'];
	       
		   $sqli='SELECT add_time,content,user_name FROM '. $GLOBALS['ecs']->table('comment') .' where id_value='.$row['id_value'].' and status = 1 AND parent_id = 0 and comment_type=0 ORDER by add_time desc';
		   $resi = $GLOBALS['db']->getRow($sqli);
		   
		   $result = mysql_query($sqli);
		   $getall = $GLOBALS['db']->num_rows($result);

	       $comments[$idx]['number']    = $getall;//条数
		   $comments[$idx]['add_time']       = local_date('Y-m-d H:i:s', $resi['add_time']);
		   $comments[$idx]['content']       = $resi['content'];
		   $comments[$idx]['user_name']       = $resi['user_name'];
	   
	   $comments[$idx]['goods_thumb']  = get_image_path($row['goods_id'], $row['goods_thumb'], true);
	   $comments[$idx]['goods_name']       = $row['goods_name'];
  }
  return $comments;
}
}

/**
 * 通过类型与传入的ID获取广告内容
 *
 * @param string $type
 * @param int $id
 * @return string
 */					
function get_adv($type,$id)
{
	
	 $sql = "select ap.ad_width,ap.ad_height,ad.ad_name,ad.ad_code,ad.ad_link from ".$GLOBALS['ecs']->table('ad_position')." as ap left join ".$GLOBALS['ecs']->table('ad')." as ad on ad.position_id = ap.position_id where ad.ad_name='".$type."_".$id."' and ad.media_type=0 and UNIX_TIMESTAMP()>ad.start_time and UNIX_TIMESTAMP()<ad.end_time and ad.enabled=1";
     $res = $GLOBALS['db']->getRow($sql);
     if($res)                        
     return  "<a href='".$res['ad_link']."' target='_blank'><img src='data/afficheimg/".$res['ad_code']."' width='".$res['ad_width']."' height='".$res['ad_height']."' /></a>";	
	 else
	 {
		return "";
	 }
}

function get_advname($type,$id)
{
	 $sql = "select ap.ad_width,ap.ad_height,ad.ad_name,ad.ad_code,ad.ad_link,ad.link_man from ".$GLOBALS['ecs']->table('ad_position')." as ap left join ".$GLOBALS['ecs']->table('ad')." as ad on ad.position_id = ap.position_id where ad.ad_name='".$type."_".$id."' and ad.media_type=0 and UNIX_TIMESTAMP()>ad.start_time and UNIX_TIMESTAMP()<ad.end_time and ad.enabled=1";
     $res = $GLOBALS['db']->getRow($sql);
     if($res)                        
     return  "<a href='".$res['ad_link']."' target='_blank'>".$res['link_man']."</a>";	
	 else
	 {
		return "";
	 }
}

function get_adv_4cate()
{
	 $sql = "select ap.ad_width,ap.ad_height,ad.ad_name,ad.ad_code,ad.ad_link from ".$GLOBALS['ecs']->table('ad_position')." as ap left join ".$GLOBALS['ecs']->table('ad')." as ad on ad.position_id = ap.position_id where ad.ad_name like 'slider_%' and ad.media_type=0 and UNIX_TIMESTAMP()>ad.start_time and UNIX_TIMESTAMP()<ad.end_time and ad.enabled=1";
     $res = $GLOBALS['db']->getAll($sql);
     
     foreach ($res as $k=>$row)
     {
     	$adname = explode('_',$row['ad_name']);
     	$cid = $adname[1];
     	$cat_sql = "select cat_name from ".$GLOBALS['ecs']->table('category')." where cat_id =".$cid;
     	$res[$k]['ad_cate'] = $GLOBALS['db']->getOne($cat_sql);
     }    
     
	  return $res;
}

function get_subcate($pid)
{
	$sql = "select cat_id,cat_name from ".$GLOBALS['ecs']->table('category')." where parent_id=".$pid;

	$res = $GLOBALS['db']->getAll($sql);
	return $res;
}

function get_brandcate($bid)
{
	$sql = "select cat.cat_id,cat.cat_name from ".$GLOBALS['ecs']->table('category')." as cat where cat.cat_id in (select distinct cat_id from ".$GLOBALS['ecs']->table('goods')." where brand_id = ".$bid.")";
	$res = $GLOBALS['db']->getAll($sql);
	return $res;
}

function get_goods_field($pid,$field_name)
{
	$sql = "select ".$field_name." from ".$GLOBALS['ecs']->table('goods')." where goods_id='".$pid."'";
	return $GLOBALS['db']->getOne($sql);
}

function get_hotcate()
{
	$sql = "select cat_id,cat_name from ".$GLOBALS['ecs']->table('category')." where cat_id in (select distinct cat_id from ".$GLOBALS['ecs']->table('cat_recommend')." where recommend_type in (1,2,3)) and is_show=1";

	$res = $GLOBALS['db']->getAll($sql);
	return $res;
}

/**
 * 通过传入参数的url判断是否为目录分类，从而获取子菜单
 *
 * @param string $url
 */
function get_subcate_byurl($url)
{
	$rs = strpos($url,"category");
	if($rs!==false)
	{
		preg_match("/\d+/i",$url,$matches);
		$cid = $matches[0];
		$cat_arr = array();
		$sql = "select * from ".$GLOBALS['ecs']->table('category')." where parent_id=".$cid." and is_show=1";
		$res = $GLOBALS['db']->getAll($sql);
		
		foreach($res as $idx => $row)
		{
			$cat_arr[$idx]['id']   = $row['cat_id'];
            $cat_arr[$idx]['name'] = $row['cat_name'];
            $cat_arr[$idx]['url']  = build_uri('category', array('cid' => $row['cat_id']), $row['cat_name']);
			$cat_arr[$idx]['children'] = get_clild_list($row['cat_id']);
		}

		return $cat_arr;
	}
	else 
	{
		return false;
	}
}

function get_clild_list($pid)
{
   //开始获取子分类
    $sql_sub = "select * from ".$GLOBALS['ecs']->table('category')." where parent_id=".$pid." and is_show=1";

	$subres = $GLOBALS['db']->getAll($sql_sub);
	if($subres)
	{
		foreach ($subres as $sidx => $subrow)
		{
			$children[$sidx]['id']=$subrow['cat_id'];
			$children[$sidx]['name']=$subrow['cat_name'];
			$children[$sidx]['url']=build_uri('category', array('cid' => $subrow['cat_id']), $subrow['cat_name']);
		}
	}
	else 
	{
		$children = null;
	}
			
	return $children;
}

function get_hotcate_tree($cat_id = 0)
{
    if ($cat_id > 0)
    {
        $sql = 'SELECT parent_id FROM ' . $GLOBALS['ecs']->table('category') . " WHERE cat_id = '$cat_id' ORDER BY sort_order ASC, cat_id ASC";
        $parent_id = $GLOBALS['db']->getOne($sql);
    }
    else
    {
        $parent_id = 0;
    }

    /*
     判断当前分类中全是是否是底级分类，
     如果是取出底级分类上级分类，
     如果不是取当前分类及其下的子分类
    */
    $sql = 'SELECT count(*) FROM ' . $GLOBALS['ecs']->table('category') . " WHERE parent_id = '$parent_id' AND is_show = 1 ORDER BY sort_order ASC, cat_id ASC";
    if ($GLOBALS['db']->getOne($sql) || $parent_id == 0)
    {
        /* 获取当前分类及其子分类 */
        $sql = 'SELECT cat_id,cat_name ,parent_id,is_show ' .
                'FROM ' . $GLOBALS['ecs']->table('category') .
                "WHERE parent_id = '$parent_id' AND is_show = 1 ORDER BY sort_order ASC, cat_id ASC";

        $res = $GLOBALS['db']->getAll($sql);

        foreach ($res AS $row)
        {
            if ($row['is_show'])
            {
                $cat_arr[$row['cat_id']]['id']   = $row['cat_id'];
                $cat_arr[$row['cat_id']]['name'] = $row['cat_name'];
                $cat_arr[$row['cat_id']]['url']  = build_uri('category', array('cid' => $row['cat_id']), $row['cat_name']);

                if (isset($row['cat_id']) != NULL)
                {
                    $cat_arr[$row['cat_id']]['cat_id'] = get_child_tree($row['cat_id']);
                }
            }
        }
    }
    if(isset($cat_arr))
    {
        return $cat_arr;
    }
}

/**
 * 获得最新的类别下文章列表。
 *
 * @access  private
 * @return  array
 */
function index_getad_new_articles($cat_id,$num)
{

    /**/$sql = 'SELECT a.article_id, a.title, ac.cat_name, a.add_time, a.file_url, a.link, a.open_type, ac.cat_id, ac.cat_name ' .
            ' FROM ' . $GLOBALS['ecs']->table('article') . ' AS a, ' .
                $GLOBALS['ecs']->table('article_cat') . ' AS ac' .
            ' WHERE a.is_open = 1 AND a.cat_id = '.$cat_id.'' .
            ' LIMIT ' . $num;
	 /*		
	$sql ='Select * FROM ' . $GLOBALS['ecs']->table('article') .
	       ' WHERE is_open = 1 AND cat_id = 15 ';*/
		   
			
    $res = $GLOBALS['db']->getAll($sql);

    $arr = array();
    foreach ($res AS $idx => $row)
    {
        $arr[$idx]['id']          = $row['article_id'];
        $arr[$idx]['title']       = $row['title'];
		$arr[$idx]['file_url']       = $row['file_url'];
		$arr[$idx]['link']       = $row['link'];
        $arr[$idx]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ?
                                        sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];
        $arr[$idx]['cat_name']    = $row['cat_name'];
        $arr[$idx]['add_time']    = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        $arr[$idx]['url']         = $row['open_type'] != 1 ?
                                        build_uri('article', array('aid' => $row['article_id']), $row['title']) : trim($row['file_url']);
        $arr[$idx]['cat_url']     = build_uri('article_cat', array('acid' => $row['cat_id']), $row['cat_name']);
    }

    return $arr;
}

/**
 * 获得热门分类
 *
 * @access  private
 * @return  array
 */
function cat_recommend_hot($num)
{

    $sql = "SELECT c.cat_id, c.cat_name, cr.recommend_type FROM " . $GLOBALS['ecs']->table('cat_recommend') . " AS cr INNER JOIN " . $GLOBALS['ecs']->table('category') . " AS c ON cr.cat_id=c.cat_id Where cr.recommend_type=3 LIMIT ".$num;
		   	
    $res = $GLOBALS['db']->getAll($sql);

    $arr = array();
    foreach ($res AS $idx => $row)
	{
		$arr[$idx]['cat_id']          = $row['cat_id'];
        $arr[$idx]['cat_name']       = $row['cat_name'];
	}

    return $arr;
}

function get_brand()
{
    $sql = "SELECT brand_id,brand_name,brand_logo FROM " . $GLOBALS['ecs']->table('brand') . " LIMIT 6";
    $res = $GLOBALS['db']->getAll($sql);

    $brand_list = array();
    foreach ($res AS $idx => $row)
    {
        $brand_list[$idx]['brand_id']       = $row['brand_id'];
		$brand_list[$idx]['brand_name']       = $row['brand_name'];
		$brand_list[$idx]['brand_logo']       = $row['brand_logo'];
    }

    return $brand_list;
}
/**
 * 获得指定分类促销商品，带倒计时信息
 *
 * @access  public
 * @return  array
 */
function myget_promote_goods($cats = '')
{
    $time = gmtime();
    $order_type = $GLOBALS['_CFG']['recommend_order'];

    /* 取得促销lbi的数量限制 若需要使用模板设置在这里读取设置数量即可*/
    $num = get_library_number("recommend_promotion");
    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_number,g.goods_name_style, g.market_price, g.shop_price AS org_price, g.promote_price, ' .
                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ".
                "promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, goods_img, b.brand_name, " .
                "g.is_best, g.is_new, g.is_hot, g.is_promote, RAND() AS rnd " .
            'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id ' .
            "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ".
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
            'WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ' .
            " AND g.is_promote = 1 AND promote_start_date <= '$time' AND promote_end_date >= '$time' ";
    $sql .= $order_type == 0 ? ' ORDER BY g.sort_order, g.last_update DESC' : ' ORDER BY rnd';
    $sql .= " LIMIT 1 ";
    $result = $GLOBALS['db']->getAll($sql);

    $goods = array();
    foreach ($result AS $idx => $row)
    {
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : '';
        }
        else
        {
            $goods[$idx]['promote_price'] = '';
        }

        $goods[$idx]['id']           = $row['goods_id'];
        $goods[$idx]['name']         = $row['goods_name'];
		$goods[$idx]['num']         = $row['goods_number'];
        $goods[$idx]['brief']        = $row['goods_brief'];
        $goods[$idx]['brand_name']   = $row['brand_name'];
        $goods[$idx]['goods_style_name']   = add_style($row['goods_name'],$row['goods_name_style']);
        $goods[$idx]['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $goods[$idx]['short_style_name']   = add_style($goods[$idx]['short_name'],$row['goods_name_style']);
        $goods[$idx]['market_price'] = price_format($row['market_price']);
        $goods[$idx]['shop_price']   = price_format($row['shop_price']);
        $goods[$idx]['thumb']        = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $goods[$idx]['goods_img']    = get_image_path($row['goods_id'], $row['goods_img']);
        $goods[$idx]['url']          = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']);
		$goods[$idx]['dz_price']     = round(($row['promote_price']/$row['market_price'])*100)/10+"";
		$goods[$idx]['js_price']     = $row['market_price']-$row['promote_price'];

		//设置时间
		if ($time >= $row['promote_start_date'] && $time <= $row['promote_end_date'])
        {
			$goods[$idx]['gmt_end_time'] = $row['promote_end_date'];
        }
        else
        {
			$goods[$idx]['gmt_end_time']  =  0;
        }

    }

    return $goods;
}

function getecy_cart_goods()
{
    /* 初始化 */
    $goods_list = array();
    $total = array(
        'goods_price'  => 0, // 本店售价合计（有格式）
        'market_price' => 0, // 市场售价合计（有格式）
        'saving'       => 0, // 节省金额（有格式）
        'save_rate'    => 0, // 节省百分比
        'goods_amount' => 0, // 本店售价合计（无格式）
    );

    /* 循环、统计 */
    $sql = "SELECT *, IF(parent_id, parent_id, goods_id) AS pid " .
            " FROM " . $GLOBALS['ecs']->table('cart') . " " .
            " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'" .
            " ORDER BY pid, parent_id";
    $res = $GLOBALS['db']->query($sql);

    /* 用于统计购物车中实体商品和虚拟商品的个数 */
    $virtual_goods_count = 0;
    $real_goods_count    = 0;

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $total['goods_price']  += $row['goods_price'] * $row['goods_number'];
        $total['market_price'] += $row['market_price'] * $row['goods_number'];
		$total['goods_name'] =$row['goods_name'];
		$total['goods_id'] =$row['goods_id'];
		$total['goods_number'] =$row['goods_number'];

        $row['subtotal']     = price_format($row['goods_price'] * $row['goods_number'], false);
        $row['goods_price']  = price_format($row['goods_price'], false);
        $row['market_price'] = price_format($row['market_price'], false);

        /* 统计实体商品和虚拟商品的个数 */
        if ($row['is_real'])
        {
            $real_goods_count++;
        }
        else
        {
            $virtual_goods_count++;
        }

        /* 查询规格 */
        if (trim($row['goods_attr']) != '')
        {
            $sql = "SELECT attr_value FROM " . $GLOBALS['ecs']->table('goods_attr') . " WHERE goods_attr_id " .
            db_create_in($row['goods_attr']);
            $attr_list = $GLOBALS['db']->getCol($sql);
            foreach ($attr_list AS $attr)
            {
                $row['goods_name'] .= ' [' . $attr . '] ';
            }
        }
        /* 增加是否在购物车里显示商品图 */
        if (($GLOBALS['_CFG']['show_goods_in_cart'] == "2" || $GLOBALS['_CFG']['show_goods_in_cart'] == "3") && $row['extension_code'] != 'package_buy')
        {
            $goods_thumb = $GLOBALS['db']->getOne("SELECT `goods_thumb` FROM " . $GLOBALS['ecs']->table('goods') . " WHERE `goods_id`='{$row['goods_id']}'");
            $row['goods_thumb'] = get_image_path($row['goods_id'], $goods_thumb, true);
			$total['goods_thumb'] = $row['goods_thumb'];
        }
        if ($row['extension_code'] == 'package_buy')
        {
            $row['package_goods_list'] = get_package_goods($row['goods_id']);
        }
        $goods_list[] = $row;
    }
    $total['goods_amount'] = $total['goods_price'];
    $total['saving']       = price_format($total['market_price'] - $total['goods_price'], false);
    if ($total['market_price'] > 0)
    {
        $total['save_rate'] = $total['market_price'] ? round(($total['market_price'] - $total['goods_price']) *
        100 / $total['market_price']).'%' : 0;
    }
    $total['goods_price']  = price_format($total['goods_price'], false);
    $total['market_price'] = price_format($total['market_price'], false);
    $total['real_goods_count']    = $real_goods_count;
    $total['virtual_goods_count'] = $virtual_goods_count;

    return $goods_list;
}

/**
 * ============================================================================
 * 文章自定义数据调用函数
 * ============================================================================
*/
//取得文章里面的图片
function GetImageSrc($body) {
   if( !isset($body) ) {
   		return '';
   }
   else {
    	preg_match_all ("/<(img|IMG)(.*)(src|SRC)=[\"|'|]{0,}([h|\/].*(jpg|JPG|gif|GIF|png|PNG))[\"|'|\s]{0,}/isU",$body,$out);
		return $out[4];
   }
}

//提取文里面的URL
function GetArticleUrl($body) {
	if( !isset($body) ) {
		return '';
	}
	else {
		preg_match_all("/<(a|A)(.*)(href|HREF)=[\"|'|](.*)[\"|'|\s]{0,}>(.*)<\/(a|A)>/isU",$body,$out);
		return $out;
	}
}

function get_article_children_new ($cat = 0)
{
    return db_create_in(array_unique(array_merge(array($cat), array_keys(article_cat_list($cat, 0, false)))), 'a.cat_id');
}

/**
* 按文章ID号/分类ID/商品ID号/商品分类ID号取得文章
* @param  array    $id       文章ID或文章分类ID
* @param  string   $getwhat  以何种方式取文章其中可选参数有:
								[1]art_cat(以文章分类ID获取)    [2]art_id(以文章ID获取)
								[3]goods_cat(以商品分类ID获取)  [4]goods_id(以商品ID获取)
								其中的[3]和[4]必须有商品关联文章或文章关联商品
* @param  integer  $num      控制显示多少条文章.当参数为0时则全部显示
* @param  integer  $start    从第几条数据开始取
* @param  boolean  $isrand   是否随机显示文章(默认为不显示)
* @param  boolean  $showall   是否显示隐藏的文章(黑认为不显示隐藏文章)
* @return array
*/
function get_article_new( $id = array(0), $getwhat = 'art_id', $num = 0, $article_type=0, $isrand = false, $showall = false, $start = 0 ) {
	$sql = '';
	$findkey = '';
	$search = '';
	$wherestr = '';
	
	for( $i=0; $i<count($id); $i++ ) {
		if( $i<count($id)-1 ) {
			$findkey .= $id[$i] .',';
		}
		else {
			$findkey .= $id[$i];
		}
	}
	
	if( $getwhat == 'art_cat' ){
		for( $i=0; $i<count($id); $i++ ) {
			if( $i<count($id)-1 ) {
				$search .= get_article_children_new($id[$i]) . ' OR ';
			}
			else {
				$search .= get_article_children_new($id[$i]);
			}
		}
	}
	elseif($getwhat == 'goods_cat') {
		for( $i=0; $i<count($id); $i++) {
			if( $i<count($id)-1 ) {
				$search .= get_children($id[$i]) . ' OR ';
			}
			else {
				$search .= get_children($id[$i]);
			}
		}
	}
	elseif( $getwhat == 'art_id' ) {
		$search = 'a.article_id IN' . '(' . $findkey . ')';
	}
	elseif( $getwhat == 'goods_id' ) {
		$search = 'g.goods_id IN' . '(' . $findkey . ')';
	}
	$wherestr = '(' . $search . ')';
	
	if( $getwhat == 'art_cat' || $getwhat == 'art_id' || $getwhat = 'art_sort' ) {
		$sql = 'SELECT a.*,ac.cat_id,ac.cat_name,ac.keywords as cat_keywords,ac.cat_desc 
		FROM ' . $GLOBALS['ecs']->table('article') . ' AS a, ' .
		 $GLOBALS['ecs']->table('article_cat') . ' AS ac' .
		' WHERE (a.cat_id = ac.cat_id) AND ' . $wherestr;
	}
	elseif( $getwhat == 'goods_cat' || $getwhat == 'goods_id' ) {
		$sql = 'SELECT DISTINCT a.*,ac.cat_id,ac.cat_name,ac.keywords as cat_keywords,ac.cat_desc FROM ' . 
		$GLOBALS['ecs']->table('goods') .' AS g ' .
		'LEFT JOIN ' . $GLOBALS['ecs']->table('goods_article') . ' AS ga ON g.goods_id=ga.goods_id INNER JOIN ' . 
		$GLOBALS['ecs']->table('article') . ' AS a ON ga.article_id = a.article_id, ' .
		$GLOBALS['ecs']->table('article_cat') . 'AS ac ' .
		'WHERE (a.cat_id = ac.cat_id) AND ' . $wherestr;
	}
	
	
	if( ($article_type == 1)) {
		$sql .= ' AND a.article_type=1';
	}
	else
	{
	    $sql .= ' AND a.article_type=0';
	}
	if( ($showall == false) && ( $getwhat == 'art_cat' || $getwhat == 'art_id' ) ) {
		$sql .= ' AND a.is_open=1';
	}
	elseif( ($showall == false) && ( $getwhat == 'goods_cat' || $getwhat == 'goods_id' ) ) {
		$sql .= ' AND a.is_open=1';
	}
	
	if( $isrand == true ) {
		$sql .= ' ORDER BY rand()';
	}
	elseif( ($isrand == false) && ( $getwhat == 'art_cat' || $getwhat == 'art_id' ) ) {
		$sql .= ' ORDER BY a.add_time DESC, a.article_id DESC';
	}
	elseif( ($isrand == false) && ( $getwhat == 'goods_cat' || $getwhat == 'goods_id' ) ) {
		$sql .= ' ORDER BY a.add_time DESC, a.article_id DESC';
	}
	
	if( $start == 0 && $num>0 ) {
		$sql .= ' LIMIT ' . $num;
	}
	elseif( $start>0 && $num>0 ) {
		$sql .= ' LIMIT ' . $start . ',' . $num;
	}
	
	//开始查询
	$arr = $GLOBALS['db']->getAll($sql);
	$articles = array();
	foreach ($arr AS $id => $row) {
		$articles[$id]['cat_id']       = $row['cat_id'];
		$articles[$id]['cat_name']     = $row['cat_name'];
		$articles[$id]['cat_url']      = build_uri('article_cat', array('acid' => $row['cat_id']));
		$articles[$id]['cat_keywords'] = $row['cat_keywords'];
		$articles[$id]['cat_desc']     = $row['cat_desc'];
		$articles[$id]['title']        = $row['title'];
		$articles[$id]['url']          = build_uri('article', array('aid'=>$row['article_id']), $row['title']);
		$articles[$id]['author']       = $row['author'];
		$articles[$id]['content']      = $row['content'];
		$articles[$id]['keywords']     = $row['keywords'];
		$articles[$id]['description']     = $row['description'];
		$articles[$id]['file_url']     = $row['file_url'];
		$articles[$id]['link']         = $row['link'];
		$articles[$id]['addtime']      = date($GLOBALS['_CFG']['date_format'], $row['add_time']);
		$articles[$id]['content']      = $row['content'];
		$imgsrc                        = GetImageSrc($row['content']);
		$articles[$id]['img']          = $imgsrc; 	
		$link                          = GetArticleUrl($row['content']);
		$articles[$id]['link_url']     = $link[4];                        //提取文章中所有的链接地址
		$articles[$id]['link_title']   = $link[5];                        //提取文章中所有的链接名称
	}
	return $articles;
}

function get_buyi_sum($goods_id)
{

    $sql = "select sum(goods_number) from " . $GLOBALS['ecs']->table('order_goods') . " AS g ,".$GLOBALS['ecs']->table('order_info') . " AS o WHERE o.order_id=g.order_id and g.goods_id = " . $goods_id . ""  ;//o.order_status=1 表示确认了的订单才算

    return $GLOBALS['db']->getOne($sql);
}

function get_evaluation_sum($goods_id)
{
    $sql = "SELECT count(*) FROM " . $GLOBALS['ecs']->table('comment') . " WHERE status=1 and  comment_type =0 and id_value =".$goods_id ;
    return $GLOBALS['db']->getOne($sql);
}

function get_user_sum()
{
    $sql = "SELECT count(*) FROM " . $GLOBALS['ecs']->table('users') . "";
    return $GLOBALS['db']->getOne($sql);
}

?>