<?php
/**
 *
 * Ajax评论
 *
 * @version        $Id: feedback_ajax.php 1 15:38 2010年7月8日Z tianya $
 * @package        DedeCMS.Site
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */
require_once(dirname(__FILE__).'/../include/common.inc.php');
require_once(DEDEINC.'/channelunit.func.php');
AjaxHead();

if($cfg_feedback_forbid=='Y') exit('<script>$("#conterr").html("系统已经禁止评论功能！");setTimeout(shuaxin,2000);</script>');

$aid = intval($aid);
if(empty($aid)) exit('<script>$("#conterr").html("没指定评论文档的ID，不能进行操作！");setTimeout(shuaxin,2000);</script>');

include_once(DEDEINC.'/memberlogin.class.php');
$cfg_ml = new MemberLogin();

if(empty($dopost)) $dopost = '';
$page = empty($page) || $page<1 ? 1 : intval($page);
$pagesize = 10;


/*----------------------
获得指定页的评论内容
function getlist(){ }
----------------------*/
if($dopost=='getlist')
{
    $totalcount = GetList($page);
    GetPageList($pagesize, $totalcount);
    exit();
}

/*----------------------
获得指定页的评论内容的条数
function getlist(){ }
----------------------*/
if($dopost=='nuus')
{
    $row = $dsql->GetOne("SELECT COUNT(*) FROM `#@__feedback` WHERE `aid`='$aid'");
    echo $row['COUNT(*)'];
    exit();
}

/*----------------------
发送评论
function send(){ }
----------------------*/
else if($dopost=='send')
{
    require_once(DEDEINC.'/charset.func.php');
    
    //检查验证码
    if($cfg_feedback_ck=='Y')
    {
        $svali = strtolower(trim(GetCkVdValue()));
        if(strtolower($validate) != $svali || $svali=='')
        {
            ResetVdValue();
            echo '<script>$("#conterr").html("验证码错误，请点击验证码图片更新验证码！");setTimeout(shuaxin,2000);</script>';
            exit();
        }
    }
    
    $arcRow = GetOneArchive($aid);
    if(empty($arcRow['aid']))
    {
        echo '<script>$("#conterr").html("无法查看未知文档的评论！");setTimeout(shuaxin,2000);</script>';
        exit();
    }
    if(isset($arcRow['notpost']) && $arcRow['notpost']==1)
    {
        echo '<script>$("#conterr").html("这篇文档禁止评论！");</script>';
        exit();
    }
    
    if( $cfg_soft_lang != 'utf8' )
    {
        $msg = UnicodeUrl2Gbk($msg);
        if(!empty($username)) $username = UnicodeUrl2Gbk($username);
    }
    //词汇过滤检查
    if( $cfg_notallowstr != '' )
    {
        if(preg_match("#".$cfg_notallowstr."#i", $msg))
        {
            echo '<script>$("#conterr").html("评论内容含有禁用词汇！");setTimeout(shuaxin,2000);</script>';
            exit();
        }
    }
    if( $cfg_replacestr != '' )
    {
        $msg = preg_replace("#".$cfg_replacestr."#i", '***', $msg);
    }
    if( empty($msg) )
    {
        echo '<script>$("#conterr").html("评论内容可能不合法或为空！");setTimeout(shuaxin,2000);</script>';
        exit();
    }
	if($cfg_feedback_guest == 'N' && $cfg_ml->M_ID < 1)
	{
		echo "<script>$('#conterr').html('管理员禁用了游客评论，正在为您跳转到登录页面。');setTimeout(nologin,2000);</script>";
		exit();
	}
    //检查用户
    $username = empty($username) ? '游客' : $username;
    if(empty($notuser)) $notuser = 0;
    if($notuser==1)
    {
        $username = $cfg_ml->M_ID > 0 ? '匿名' : '游客';
    }
    else if($cfg_ml->M_ID > 0)
    {
        $username = $cfg_ml->M_UserName;
    }
    else if($username!='' && $pwd!='')
    {
        $rs = $cfg_ml->CheckUser($username, $pwd);
        if($rs==1)
        {
            $dsql->ExecuteNoneQuery("Update `#@__member` set logintime='".time()."',loginip='".GetIP()."' where mid='{$cfg_ml->M_ID}'; ");
        }
        $cfg_ml = new MemberLogin();
    }
    
    //检查评论间隔时间
    $ip = GetIP();
    $dtime = time();
    if(!empty($cfg_feedback_time))
    {
        //检查最后发表评论时间，如果未登陆判断当前IP最后评论时间
        $where = ($cfg_ml->M_ID > 0 ? "WHERE `mid` = '$cfg_ml->M_ID' " : "WHERE `ip` = '$ip' ");
        $row = $dsql->GetOne("SELECT dtime FROM `#@__feedback` $where ORDER BY `id` DESC ");
        if(is_array($row) && $dtime - $row['dtime'] < $cfg_feedback_time)
        {
            ResetVdValue();
            echo '<script>$("#conterr").html("管理员设置了评论间隔时间，请稍等休息一下！");setTimeout(shuaxin,2000);</script>';
            exit();
        }
    }
    $face = 1;
    extract($arcRow, EXTR_SKIP);
    $msg = cn_substrR(TrimMsg($msg), 500);
    $username = cn_substrR(HtmlReplace($username,2), 20);
    if(empty($feedbacktype) || ($feedbacktype!='good' && $feedbacktype!='bad'))
    {
        $feedbacktype = 'feedback';
    }
    //保存评论内容
    if(!empty($fid))
    {
        $row = $dsql->GetOne("SELECT username,msg from `#@__feedback` WHERE id ='$fid' ");
        $qmsg = '{quote}{content}'.$row['msg'].'{/content}{title}'.$row['username'].' 的原帖：{/title}{/quote}';
        $msg = addslashes($qmsg).$msg;
    }
    $ischeck = ($cfg_feedbackcheck=='Y' ? 0 : 1);
    $arctitle = addslashes(RemoveXSS($title));
    $typeid = intval($typeid);
    $feedbacktype = preg_replace("#[^0-9a-z]#i", "", $feedbacktype);
    $inquery = "INSERT INTO `#@__feedback`(`aid`,`typeid`,`username`,`arctitle`,`ip`,`ischeck`,`dtime`, `mid`,`bad`,`good`,`ftype`,`face`,`msg`)
                   VALUES ('$aid','$typeid','$username','$arctitle','$ip','$ischeck','$dtime', '{$cfg_ml->M_ID}','0','0','$feedbacktype','$face','$msg'); ";
    $rs = $dsql->ExecuteNoneQuery($inquery);
    if( !$rs )
    {
            echo '<script>$("#conterr").html("发表评论出错了！");setTimeout(shuaxin,2000);</script>';
            //echo $dslq->GetError();
            exit();
    }
    $newid = $dsql->GetLastID();
    
	//给文章评分
    if($feedbacktype=='bad')
    {
        $dsql->ExecuteNoneQuery("UPDATE `#@__archives` SET scores=scores-{cfg_feedback_sub},badpost=badpost+1,lastpost='$dtime' WHERE id='$aid' ");
    }
    else if($feedbacktype=='good')
    {
        $dsql->ExecuteNoneQuery("UPDATE `#@__archives` SET scores=scores+{$cfg_feedback_add},goodpost=goodpost+1,lastpost='$dtime' WHERE id='$aid' ");
    }
    else
    {
        $dsql->ExecuteNoneQuery("UPDATE `#@__archives` SET scores=scores+1,lastpost='$dtime' WHERE id='$aid' ");
    }
    //给用户增加积分
    if($cfg_ml->M_ID > 0)
    {
        #api{{
        if(defined('UC_API') && @include_once DEDEROOT.'/api/uc.func.php')
        {
            //同步积分
            uc_credit_note($cfg_ml->M_LoginID, $cfg_sendfb_scores);
            
            //推送事件
            $arcRow = GetOneArchive($aid);
            $feed['icon'] = 'thread';
            $feed['title_template'] = '<b>{username} 在网站发表了评论</b>';
            $feed['title_data'] = array('username' => $cfg_ml->M_UserName);
            $feed['body_template'] = '<b>{subject}</b><br>{message}';
            $url = !strstr($arcRow['arcurl'],'http://') ? ($cfg_basehost.$arcRow['arcurl']) : $arcRow['arcurl'];        
            $feed['body_data'] = array('subject' => "<a href=\"".$url."\">$arcRow[arctitle]</a>", 'message' => cn_substr(strip_tags(preg_replace("/\[.+?\]/is", '', $msg)), 150));
            $feed['images'][] = array('url' => $cfg_basehost.'/images/scores.gif', 'link'=> $cfg_basehost);
            uc_feed_note($cfg_ml->M_LoginID,$feed); unset($arcRow);
        }
        #/aip}}
        $dsql->ExecuteNoneQuery("UPDATE `#@__member` set scores=scores+{$cfg_sendfb_scores} WHERE mid='{$cfg_ml->M_ID}' ");
        $row = $dsql->GetOne("SELECT COUNT(*) AS nums FROM `#@__feedback` WHERE `mid`='".$cfg_ml->M_ID."'");
        $dsql->ExecuteNoneQuery("UPDATE `#@__member_tj` SET `feedback`='$row[nums]' WHERE `mid`='".$cfg_ml->M_ID."'");
    }
    $_SESSION['sedtime'] = time();
    if($ischeck==0)
    {
        echo '<script>$("#conterr").html("成功发表评论，但需审核后才会显示你的评论！");setTimeout(shuaxin,2000);</script>';
        exit();
    }
    else
    {
        $spaceurl = '#';
        if($cfg_ml->M_ID > 0) $spaceurl = $cfg_cmsurl."/i/?uid=".urlencode($cfg_ml->M_LoginID);
        $id = $newid;
        $msg = stripslashes($msg);
        $msg = str_replace('<', '&lt;', $msg);
        $msg = str_replace('>', '&gt;', $msg);
		helper('smiley');
        $msg = RemoveXSS(Quote_replace(parseSmileys($msg, $cfg_cmspath.'/images/smiley')));
        //$msg = RemoveXSS(Quote_replace($msg));
        if($feedbacktype=='bad') $bgimg = 'cmt-bad.gif';
        else if($feedbacktype=='good') $bgimg = 'cmt-good.gif';
        else $bgimg = 'cmt-neu.gif';
        global $dsql, $aid, $pagesize, $cfg_templeturl;
?>
<li class="comment odd alt thread-odd thread-alt depth-1">
    <div id="div-comment-<?php echo $i; ?>" class="comment-body"> 
    <div class="comment-author vcard">
    <a href='<?php echo $spaceurl; ?>' class='plpic' target="_blank"><img src='<?php echo $cfg_cmsurl."/images/noface.gif";?>'  height='44' width='44'/></a>
    </div>
    <div class="comment-meta">
    <span class="author"><cite><a href="<?php echo $spaceurl; ?>" target="_blank"><?php echo $username; ?></a></cite></span>
    <span class="date"> <?php echo GetDateMk($dtime); ?> </span>
     </div> 
    <div class="comment-main">
    <p><?php echo ubb($msg); ?></p>
     </div> 
     <div class="comment-floor">*<span style="font-size:12px;">F</span></div>
 </div>
</li>
<?php
    }
    exit();
}

/**
 *  读取列表内容
 *
 * @param     int  $page  页码
 * @return    string
 */
function GetList($page=1)
{
    global $dsql, $aid, $pagesize, $cfg_templeturl,$cfg_cmspath,$cfg_memberurl;
    $querystring = "SELECT fb.*,mb.userid,mb.face as mface,mb.spacesta,mb.scores,mb.sex FROM `#@__feedback` fb
                 LEFT JOIN `#@__member` mb on mb.mid = fb.mid WHERE fb.aid='$aid' AND fb.ischeck='1' ORDER BY fb.id DESC";
    $row = $dsql->GetOne("SELECT COUNT(*) AS dd FROM `#@__feedback` WHERE aid='$aid' AND ischeck='1' ");
    $totalcount = (empty($row['dd']) ? 0 : $row['dd']);
    $startNum = $pagesize * ($page-1);
    if($startNum > $totalcount)
    {
        echo "参数错误！";
        return $totalcount;
    }
    $dsql->Execute('fb', $querystring." LIMIT $startNum, $pagesize ");
    $i=0;
	if($totalcount > 0){
		echo '<div id="msg_err"></div>';
	}
	while($fields = $dsql->GetArray('fb'))
    {
        $i++;
		if($fields['userid']!='') $spaceurl = $cfg_cmsurl.'/i/?uid='.$fields['userid'];
        else $spaceurl = '#';
        if($fields['username']=='匿名') $spaceurl = '#';
		if(empty($fields['mface']))
        {
            if($fields['sex']=="女") $fields['mface']=$cfg_cmsurl."/images/noface.gif";
            else $fields['mface']=$cfg_cmsurl."/images/noface.gif";
        }
        $fields['face'] = empty($fields['face']) ? 6 : $fields['face'];
        $fields['msg'] = str_replace('<', '&lt;', $fields['msg']);
        $fields['msg'] = str_replace('>', '&gt;', $fields['msg']);
		helper('smiley');
        $fields['msg'] = RemoveXSS(Quote_replace(parseSmileys($fields['msg'], $cfg_cmspath.'/images/smiley')));
        extract($fields, EXTR_OVERWRITE);
		if($glyhf != ''){
			$dk = "display:block";
		}else{
			$dk = "display:none";
		}
?>
<li class="comment odd alt thread-odd thread-alt depth-1">
    <div id="div-comment-<?php echo $i; ?>" class="comment-body"> 
    <div class="comment-author vcard">
    <a href='<?php echo $spaceurl; ?>' class='plpic' target="_blank"><img src='<?php echo $mface;?>'  height='44' width='44'/></a>
    </div>
    <div class="comment-meta">
    <span class="author"><cite><a href="<?php echo $spaceurl; ?>" target="_blank"><?php echo $username; ?></a></cite></span>
    <span class="date"> <?php echo GetDateMk($dtime); ?> </span>
     </div> 
    <div class="comment-main">
    <p><?php echo ubb($msg); ?></p>
     </div> 
     <div class="comment-floor"><?php echo $i; ?><span style="font-size:12px;">F</span></div>
   <ol class="children" style="<?php echo $dk; ?>"> 
   <li class="comment byuser comment-author-xiaojia bypostauthor odd alt depth-2 parent"> 
    <div id="div-comment-<?php echo $i; ?>" class="comment-body"> 
     <div class="comment-author vcard"> 
      <img src="<?php echo $cfg_cmsurl; ?>/images/admin_pic.png" class="avatar" width="44" height="44" />
     </div> 
     <div class="comment-main"> 
      <p><?php echo $glyhf; ?></p> 
      <div class="comment-meta" style="margin-left:0;"> 
       <span class="admin-author">管理员</span> 
       <span class="author"><cite><?php echo $admin_name; ?></cite></span> 
       <span class="date"> <?php echo GetDateMk($dtime); ?> </span> 
      </div> 
     </div> 
    </div> 
    <!-- .children --> 
   </li>
   <!-- #comment-## --> 
  </ol>
 </div>
</li>

<?php 

	}
    return $totalcount;            
}

/**
 *  获取分页列表
 *
 * @param     int  $pagesize  显示条数
 * @param     int  $totalcount  总数
 * @return    string
 */
function GetPageList($pagesize, $totalcount)
{
    global $page;
    $curpage = empty($page) ? 1 : intval($page);
    $allpage = ceil($totalcount / $pagesize);
    if($allpage < 2) 
    {
        echo '';
        return ;
    }
  echo "<div id='commetpages'>";
  echo "<span>共 {$allpage} 页/{$totalcount} 条评论</span> ";
  $listsize = 5;
  $total_list = $listsize * 2 + 1;
  $totalpage = $allpage;
  $listdd = '';
  if($curpage-1 > 0 )
  {
  echo "<a onclick='LoadCommets(".($curpage-1).");'>上一页</a> ";
  }
  if($curpage >= $total_list)
  {
  $j = $curpage - $listsize;
  $total_list = $curpage + $listsize;
  if($total_list > $totalpage)
  {
  $total_list = $totalpage;
  }
  }
  else
  {
  $j = 1;
  if($total_list > $totalpage) $total_list = $totalpage;
  }
  for($j; $j <= $total_list; $j++)
  {
  echo ($j==$curpage ? "<span class='hover'>$j</span> " : "<a onclick='LoadCommets($j);'>{$j}</a> ");
  }
  if($curpage+1 <= $totalpage )
  {
  echo "<a onclick='LoadCommets(".($curpage+1).");'>下一页</a> ";
  }
  echo "</div>
";
}