<?php
/**
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
* @version $Id 5 2008-08-31 22:46 $
*/
!defined('IN_MUDDER') && exit('Access Denied');

// 取得一个点评内容的详细信息
function getReview($reviewid) {
    global $db,$dbpre;

    $query = $db->query("select a.*,b.shopname,b.subname,b.classcode,b.areacode,b.streetcode,b.address,
        c.face,c.reviews as member_reviews, c.flowers as member_flowers,c.point as member_point,
        c.coin as member_coin FROM {$dbpre}reviews a LEFT JOIN {$dbpre}shops b ON(a.shopid=b.sid) 
        LEFT JOIN {$dbpre}members c ON(a.uid=c.uid) WHERE rid='$reviewid'");

    if($row = $db->fetch_array($query)) {
        $row['member'] = array(
            'uid' => $row['uid'],
            'username' => $row['username'],
            'face' => $row['face'],
            'reviews' => $row['member_reviews'],
            'flowers' => $row['member_flowers'],
            'point' => $row['member_point'],
            'coin' => $row['member_coin'],
        );
        $row['item'] = array(
            'sid' => $row['shopid'],
            'shopname' => $row['shopname'],
            'subname' => $row['subname'],
            'classcode' => $row['classcode'],
            'streetcode' => $row['streetcode'],
            'address' => $row['address'],
        );
        return reviewToArray($row);
    } else {
        return array();
    }
}

// 提交点评内容
function postReview($post) {
    global $db,$dbpre;

    // 检查点评对象
    $item = $db->get_one("SELECT status,classcode,adduid FROM {$dbpre}shops WHERE sid='{$post['shopid']}'");
    empty($item) and redirect("点评对象不存在，无法提交点评。");
    $item['status']!=1 and redirect("点评对象未审核或已锁定，无法提交点评。");
    // 检查是否点评过
    checkReviewed($post['uid'],$post['shopid']) and redirect("您已经点评过了。");
    // 检测
    $post = checkReviewPost($post, $item['classcode']);
    $db->insert_new($dbpre.'reviews', $post);
    $reviewid = $db->insert_id();
    empty($reviewid) and redirect("提交失败。");
    if($post['status'] == 1) {
        $post['rid'] = $reviewid; // 关联表更新需要
        ReviewBeRelated($post, substr($item['classcode'], 0, 2), $item['reviews']==0);
        $_webtotal['totalreview']++;
        update_webtotal();
        // 标签
        // posttags($shopid, 0, $post['classcode'], $tags, 'shop');
    }
    return $reviewid;
}

// 编辑点评内容
function updateReview($post, $reviewid, $opuid=-1) {
    global $db, $dbpre, $_modules;

    $showmsg = defined('IN_ADMIN') ? 'cpmsg' : 'redirect';
    $old = $db->get_one("SELECT * FROM {$dbpre}reviews WHERE rid='$reviewid'");
    empty($old) and $showmsg("点评记录不存在或已删除，请返回刷新。");
    $access = defined('IN_ADMIN') || $opuid==-1 || $opuid==$old['uid'];
    $access or $showmsg('您没有足够的权限来完成本次操作，请返回。');
    // 检查点评对象
    $item = $db->get_one("SELECT status,classcode,adduid FROM {$dbpre}shops WHERE sid='{$old['shopid']}'");
    empty($item) and redirect("点评对象不存在，无法提交点评。");
    $pcd = substr($item['classcode'], 0, 2);
    $post = checkReviewPost($post, $pcd);
    $post = array_merge($old, $post); // 覆盖
    if($post['status']==1 && $opuid==$old['uid']) {
       // 本人操作且有效点评时,做更新标记
       $post['isupdate'] = 1;
    }
    $db->update_new($dbpre.'reviews', "rid='$reviewid'", $post);
    if($post['status']!=2 && $old['status']==2) {
    	// 更新关联表数据
    	ReviewBeRelated($post,$pcd,$item['review']==0);
    	//checkupRespond(array($reviewid));
        $_webtotal['totalreview']++;
        update_webtotal();
    } elseif($post['status']!=2 && $old['status']!=2) {
        modilyItemPoint($post, $old);
        // 标签处理
        if(!function_exists('uniteTagAndPost')) {
            require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_tag.php');
        }
        uniteTagAndPost($post, $pcd, true, $old);
    }
}

// 批量审核点评内容
function checkupReview($reviewids) {
    global $db, $dbpre, $_webtotal;

    if(empty($reviewids)||!is_array($reviewids)) return; 
    $showmsg = defined('IN_ADMIN') ? 'cpmsg' : 'redirect';
    $upids = array();
    $ids = "'".implode("','", $reviewids)."'";
    $query = $db->query("SELECT r.*,s.classcode,s.reviews FROM {$dbpre}reviews r LEFT JOIN {$dbpre}shops s ON(r.shopid=s.sid) WHERE r.rid IN ($ids)");
    while($row = $db->fetch_array($query)) {
        if($row['status'] == 2) {
            $upids[] = $row['rid'];
            // 更新有效的关联数据
            ReviewBeRelated($row, substr($row['classcode'], 0,2), $row['reviews']==0);
            // 全局统计
            $_webtotal['totalreview']++;
        }
    }
    if($upids) {
        $ids = "'".implode("','", $upids)."'";
        $db->query("UPDATE {$dbpre}reviews SET status=1 WHERE rid IN ($ids)");
        update_webtotal();
    }
}

// 增加新点评后，需要更新的关联数据操作
function ReviewBeRelated($review, $pcd, $isFirst=false) {
    global $db, $dbpre, $ucenter_enable, $_modules;
    // 更新会员统计和积分
    if(!function_exists('updateCredit')) {
        require_once(MUDDER_ROOT.'./member/include/fun_member.php');
    }
    $sqlset = updateCredit($review['uid'],'addreview','sqlset');
    $sqlset = ($sqlset ? "$sqlset," : '') . 'reviews=reviews+1';
    $db->update("UPDATE {$dbpre}members SET $sqlset WHERE uid='{$review['uid']}'");
    // 会员的活跃记录
    $op = array('reviews');
    $isFirst && $op[] = 'fristreviews';
    updateActivity($review['uid'], $review['username'], $op);
    // 标签处理
    if(!function_exists('uniteTagAndPost')) {
        require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_tag.php');
    }
    uniteTagAndPost($review, $pcd, true);
    // 更新点评对象统计
    // 增加积分
    addItemPoint($review, $isFirst, true);
    // Feed 事件
    if($ucenter_enable) {
        if(!class_exists('Feed_UC')) {
            require_once(MUDDER_ROOT.'./include/feed_uc.class.php');
        }
        $item = $db->get_one("SELECT shopname,subname FROM {$dbpre}shops WHERE sid='{$review['shopid']}'");
        $fullname = $item['shopname'] . ($item['subname'] ? '('.$item['subname'].')' : '');
        Feed_UC::add_review($review['rid'], $fullname, $review['content']);
    }
}

// 给商铺增加点评分数
function addItemPoint($review,$isFirest) {
    global $db, $dbpre;

    $set = array();
    if($isFirest) {
        $set[] = "firstuid='$uid'";
        $set[] = "firstname='$username'";
    }
    $set[] = "reviews=reviews+1";
    $sumreview = 0;
    foreach($review as $key => $val) {
        if(preg_match("/^sort[1-9]{1}$/", $key)) {
            $val = intval($val);
            $sortname = sprintf("sum%s",$key);
            $set[] = "$sortname=$sortname+'$val'";
            $sumreview += $val; //总和
        }
    }
    $set[] = "sumenjoy=sumenjoy+{$review['enjoy']}";
    $set[] = "sumreview=sumreview+'$sumreview'";
    //平均消费价格
    $avgprice = $db->get_value("SELECT ROUND(AVG(avgprice)) AS avgprice FROM {$dbpre}reviews WHERE `shopid`='{$review['shopid']}' AND avgprice > 0 AND status<>2");
    if($avgprice=intval($avgprice)) {
        $set[] = "avgprice = '$avgprice'";
    }
    $sqlset = implode(',', $set);
    $db->update("UPDATE {$dbpre}shops SET $sqlset WHERE sid='{$review['shopid']}'");
}

// 更新点评分数
function modilyItemPoint($newreview, $oldreview) {
    global $db, $dbpre;

    $set = array();
    foreach($newreview as $key => $val) {
        if(preg_match("/^sort[1-9]{1}$/", $key)) {
            $val = intval($val);
            $sortname = sprintf("sum%s",$key);
            $set[] = "$sortname=$sortname+'".($val-intval($oldreview[$key]))."'";
            $sumreview += $val-intval($oldreview[$key]); //总和
        }
    }
    $set[] = "sumreview=sumreview+'$sumreview'";
    $sumenjoy = intval($newreview['enjoy']) - intval($oldreview['enjoy']);
    $set[] = "sumenjoy=sumenjoy+'$sumenjoy'";
    // 平均费用
    //平均消费价格
    $avgprice = $db->get_value("SELECT ROUND(AVG(avgprice)) AS avgprice FROM {$dbpre}reviews WHERE `shopid`='{$oldreview['shopid']}' AND avgprice>0 AND status<>2");
    if($avgprice=intval($avgprice)) {
        $set[] = "avgprice = '$avgprice'";
    }
    $db->update("UPDATE {$dbpre}shops SET ".implode(',',$set)." WHERE sid='{$newreview['shopid']}'");
}

// 商铺减分
function decItemPoint($review) {
    global $db, $dbpre;

    $set = array();
    $set[] = "reviews=reviews-1";
    $sumreview = 0;
    foreach($review as $key => $val) {
        if(preg_match("/^sort[1-9]{1}$/", $key)) {
            $val = intval($val);
            $sortname = sprintf("sum%s",$key);
            $set[] = "$sortname=$sortname-'$val'";
            $sumreview += $val; //总和
        }
    }
    $set[] = "sumreview=sumreview-'$sumreview'";
    $set[] = "sumenjoy=sumenjoy-'{$review['enjoy']}'";

    if(is_numeric($row['avgprice']) && $row['avgprice'] > 0) {
        $avgprice = $db->get_value("SELECT ROUND(AVG(avgprice)) AS avgprice FROM {$dbpre}reviews WHERE shopid='{$review['shopid']}' AND avgprice>0 AND rid<>'{$review['rid']}' AND status<>2");
        if($avgprice=intval($avgprice)) {
            $set[] = "avgprice='$avgprice'";
        }
    }
    $db->update("UPDATE {$dbpre}shops SET ".implode(',',$set)." WHERE sid='{$review['shopid']}'");
}

// 批量删除点评内容
function deleteReview($myids,$idtype='rid',$opuid='-1', $upItem=true, $credit=false) {
    global $db, $dbpre, $_modules;

    if(empty($myids)||!is_array($myids)) return;
    $showmsg = defined('IN_ADMIN') ? 'cpmsg' : 'redirect';
    $ids = "'".implode("','", $myids)."'";
    $delreviews = array();
    $query = $db->query("SELECT * FROM {$dbpre}reviews WHERE $idtype IN ($ids)");
    while($row = $db->fetch_array($query)) {
        $access = defined('IN_ADMIN') || $opuid=='-1' || $opuid==$row['uid'];
        !$access and $showmsg('您没有足够的权限来完成本次操作，请返回。');
        $delreviews[] = $row['rid'];
        if($row['status']!=2) {
            // 更新会员表
            $sqlset = "reviews=reviews-1";
            if($credit) {
                if(!function_exists('updateCredit')) {
                    require_once(MUDDER_ROOT.'./member/include/fun_member.php');
                }
                $sqlset .= ",".updateCredit($row['uid'], 'deletereview', 'sqlset');
            }
            $db->update("UPDATE {$dbpre}members SET $sqlset WHERE uid='{$row['uid']}'");
            // 更新点评表统计
            if($upItem) {
                // 更新商铺的统计
                decItemPoint($row);
            }
        }
    }
    $db->free_result($query);
    // 删除点评下的回应信息
    if(!function_exists('deleteRespond')) {
        require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_respond.php');
    }
    deleteRespond($delreviews, 'reviewid', -1, false, $credit);
    // 最后删除点评内容
    if($delreviews) {
        $ids = "'".implode("','", $delreviews)."'";
        $db->query("DELETE FROM {$dbpre}reviews WHERE rid IN ($ids)");
    }
}

// 转换数据到显示数组
function reviewToArray($row, $isEdit = false) {
    global $_config, $_modules;
    // Tag类型
    $tag_arr = array('shoptags', 'producttags', 'suitplacetags');
    // Tag 分类
    
    $row['reviewid'] = $row['reviewid'] ? $row['reviewid'] : $row['rid'];
    !$isEdit and $row['content'] = strip_textarea($row['content']);
    $row['statusname'] = $row['status'] == 1 ? '正常' : '未审核';
    if(!$isEdit) {
    	if(!function_exists('parseTagstr')) {
    		require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_tag.php');
    	}
    	foreach ($tag_arr as $val) {
    		$row[$val] = !empty($row[$val]) ? tagToArray(parseTagstr($row[$val])) : array();
    	}
    }

    // 如果存在会员信息
    if($row['member']) {
        if(!function_exists('memberToArray')) {
            require_once(MUDDER_ROOT.'./member/include/fun_member.php');
        }
        $row['member'] = memberToArray($row['member']);
    }
    // 如果存在商铺信息
    if($row['item']) {
       
        if(!function_exists('itemToArray')) {
            require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_item.php');
        }
        $row['item'] = itemToArray($row['item']);

    }
    if($_config['compatible']) {
        // 兼容老版本
        $sort_arr = array('sort1', 'sort2', 'sort3', 'sort4', 'sort5', 'sort6', 'sort7', 'sort8');
        foreach($sort_arr as $val) {
            $row['score'][$val] = $row[$val];
        }
        $row['sumscore'] = $row['sumsort'];
        foreach($tag_arr as $val) {
            $tmp_tags = $row[$val] ? explode(' ', $row[$val]) : '';
            if($tmp_tags) {
                foreach ($tmp_tags as $s_val) {
                    if(!$s_val) continue;
                    $tmptagnecs[] = array (
                        'tagname' => $s_val,
                        'tagnameenc' => rawurlencode($s_val),
                    );
                    $row[$val] = $tmptagnecs;
                }
            }
            unset($tmptagnecs, $tmp_tags);
        }
    }
    return $row;
}

// 检查提交的参数
function checkReviewPost($post,$classcode) {
    global $_seccode, $_panel_config, $_inputlimit, $_modules, $_DCOOKIE;

    $showmsg = defined('IN_ADMIN') ? 'cpmsg' : 'redirect';
    if(!defined('IN_ADMIN') && $_seccode['newreview'] && 
       ($_DCOOKIE['seccode'] != formhash(strtolower($post['seccode']),'',''))) {
        $showmsg('验证码错误，请返回修改。'.$_DCOOKIE['seccode'].'-'.$post['seccode']);
    }
    unset($post['seccode']);

    $pcd = substr($classcode,0,2);
    $panelcfg = $_panel_config[$pcd];
    for($i=1; $i<=8; $i++) {
        $val = sprintf("sort%d", $i);
        if($panelcfg['review'][$val]) {
            // 有效的评分项目
            $post[$val] = isset($post[$val]) && is_numeric($post[$val]) ? $post[$val] : '-';
        } else {
            $post[$val] = 0;
        }
    }

    $post['avgprice'] = isset($post['avgprice']) && is_numeric($post['avgprice']) && $post['avgprice'] > 0 ? $post['avgprice'] : 0;
    $post['enjoy'] = isset($post['enjoy']) && is_numeric($post['enjoy']) ? $post['enjoy'] : '-';
    $post['shoptags'] = isset($post['shoptags']) ? html_special_chars_ex($post['shoptags']) : '';
    $post['producttags'] = isset($post['producttags']) ? html_special_chars_ex($post['producttags']) : '';
    $post['suitplacetags'] = isset($post['suitplacetags']) ? html_special_chars_ex($post['suitplacetags']) : '';
    $post['content'] = isset($post['content']) ? unite_textarea($post['content']) : '';
    $post['sumsort'] = 0; // 总分计算
    for($i=1; $i<=8; $i++) {
        // 检测评分
        $val = sprintf("sort%d", $i);
        is_numeric($post[$val]) or $showmsg('评分选项未填写完整，请返回修改。');
        $post['sumsort'] += $post[$val];
    }
    if(empty($post['avgprice']) && $panelcfg['avgprice_need']) {
        $showmsg('未填写人均消费额，请返回填写。');
    } elseif($post['avgprice'] > 16777215) {
        $showmsg('人均消费额不能超过 16777215 元，请返回填写。');
    } elseif(empty($post['content'])) {
        $showmsg('未填写点评内容，请返回填写。');
    } elseif(strlen($post['content']) < $_inputlimit['review']['min'] || 
             strlen($post['content']) > $_inputlimit['review']['max']) {
        $showmsg('点评内容请控制在 '.$_inputlimit['review']['min'].' - '.$_inputlimit['review']['max'].' 个字符以内。');
    } elseif(!is_numeric($post['enjoy'])) {
        $showmsg('未选择喜欢程度，请返回修改。');
    }
    // 标签判断和标准化处理
    if(!function_exists('checkTagPost')) {
        require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_tag.php');
    }
    $post = checkTagPost($post, $pcd);
    return $post;
}

// 检查会员是否点评
function checkReviewed($uid, $shopid) {
    global $db,$dbpre;
    return $db->get_value("SELECT rid FROM {$dbpre}reviews WHERE uid='$uid' AND shopid='$shopid'");
}

// 举报点评
function reportReview($post, $reviewid) {
    global $db,$dbpre;

    $post['username'] = isset($post['username']) ? html_special_chars_ex($post['username']) : '';
    $post['email'] = isset($post['email']) ? html_special_chars_ex($post['email']) : '';
    $post['sort'] = isset($post['sort']) && is_numeric($post['sort']) ? $post['sort'] : 0;
    $post['reportcontent'] = isset($post['reportcontent']) ? strip_textarea(unite_textarea($post['reportcontent'])) : '';
    
    if(!is_numeric($post['reviewid']) || $post['reviewid'] <= 0) {
        $error = '未知的举报对象';
    } elseif(!$review = $db->get_one("SELECT * FROM {$dbpre}reviews WHERE rid='$reviewid'")) {
        $error = '举报对象不存在或已删除，请返回刷新。';
    } elseif(!$post['username']) {
        $error = '未填写昵称';
    } elseif(strlen($post['username']) < 2 || strlen($post['username']) > 16) {
        $error = '昵称不能小于2个字符或者大于16个字符';
    } elseif(!$post['email']) {
        $error = '未填写邮箱';
    } elseif(!isemail($post['email'])) {
        $error = '您填写的邮箱地址格式不规范';
    } elseif(!$post['sort']) {
        $error = '未选择举报类型';
    } elseif(strlen($post['reportcontent']) > 500) {
        $error = '举报说明不能大于500个字符';
    } else {
        $db->insert_new($dbpre.'reports', $post);
        $insert_id = $db->insert_id();
        empty($insert_id) and $error = '提交失败。';
    }
    if($error) {
        return '<script type="text/javascript">alert("'.$error.'");</script>';
    } else {
        return '<script type="text/javascript">window.parent.document.forms["frmreport"].hide.click();
        alert("提交完毕，谢谢您的监督支持。");</script>';
    }
}

// 审核处理举报点评
function checkupReportReview($reportid, $post) {
    global $db,$dbpre;
    if(empty($reportid)) {
        cpmsg('无效的补充信息ID。', 'stop');
    }
    $db->update("UPDATE {$dbpre}reports SET disposal='1',reportremark='{$post['reportremark']}',disposaltime='{$post['disposaltime']}' WHERE reportid='$reportid'");
}

// 某个点点评对象的点评内容
function getItemReviews($shopid, $orderby, $limit) {
    global $db,$dbpre;

    $where[] = "a.shopid='$shopid'";
    $where[] = "a.status=1";
    $where = implode(" AND ", $where);
    $orderby = 'ORDER BY ' . ($orderby ? $orderby : 'posttime DESC');
    $limit = 'LIMIT ' . ($limit ? $limit : '0,10');
    $query = $db->query("SELECT a.*,b.username,b.face,b.reviews as member_reviews,
    	b.flowers as member_flowers,b.point as member_point,b.coin as member_coin 
    	FROM {$dbpre}reviews a LEFT JOIN {$dbpre}members b ON(a.uid=b.uid) WHERE 
    	$where $orderby $limit");
    $result = array();
    while($row = $db->fetch_array($query)) {
        $row['member'] = array(
            'uid' => $row['uid'],
            'username' => $row['username'],
            'face' => $row['face'],
            'reviews' => $row['member_reviews'],
            'flowers' => $row['member_flowers'],
            'point' => $row['member_point'],
            'coin' => $row['member_coin'],
        );
        $result[] = reviewToArray($row);
    }
    return $result;
}

// 某个会员的所有点评
function & getMemberReviews($uid, $limit) {
    global $db, $dbpre;

    $from = "{$dbpre}reviews r LEFT JOIN {$dbpre}shops s ON(r.shopid=s.sid)";
    $where = "r.uid='$uid' AND r.status=1";

    $total = $db->get_value("SELECT COUNT(*) FROM $from WHERE $where");
    if($total > 0) {
        $select = "r.*,s.shopname,s.subname,s.areacode,s.address,s.tel1,s.tel2,s.mobile,s.mappoint";
        $query = $db->query("SELECT $select FROM $from WHERE $where ORDER BY posttime DESC LIMIT $limit");
        while($row = $db->fetch_array($query)) {
            $row['item'] = array(
                'sid' => $row['shopid'],
                'shopname' => $row['shopname'],
                'subname' => $row['subname'],
                'classcode' => $row['classcode'],
                'streetcode' => $row['streetcode'],
                'address' => $row['address'],
                'tel1' => $row['tel1'],
                'tel2' => $row['tel2'],
                'mobile' => $row['mobile'],
                'mappoint' => $row['mappoint'],
            );
            $tmp = reviewToArray($row);
            $tmp['shop'] =& $tmp['item'];
            $reviews[] = $tmp;
        }
        $db->free_result($query);
    }
    return array($total, $reviews);
}

// 全方位搜索点评信息
function searchReview($params) {
}
?>