<?php
/**
* 点评对象处理
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
* @version $Id 3 2008-08-29 19:55 $
*/
!defined('IN_MUDDER') && exit('Access Denied');

// 添加对象
function postItem($post) {
    global $db,$dbpre,$_webtotal;

    $post = checkItemPost($post);
    if(itemExist($post['shopname'],$post['subname'])) redirect('您提交的商铺已存在，请返回修改。');
    // 获取标签
    $tags = $post['tags'];
    unset($post['tags']);
    // 添加
    $db->insert_new($dbpre.'shops', $post);
    $shopid = $db->insert_id();
    empty($shopid) and redirect('提交失败。');
    if($post['status'] == 1) {
        // 审核通过
        ItemBeRelated($shopid,$post);
        // 分类统计
        $db->update("UPDATE {$dbpre}classcode SET total=total+1 WHERE classcode='{$post['classcode']}'");
        // 标签
        // postTags($shopid,0,$pcd,parseTagstr($review[$val]),'shoptags');
        // 更新统计缓存
        $_webtotal['totalshop']++;
        update_webtotal();
    }
    return $shopid;
}

// 更新对象
function updateItem($shopid, $post, $opuid='') {
    global $db,$dbpre;

    $showmsg = defined("IN_ADMIN") ? 'cpmsg' : 'redirect';
    $old = $db->get_one("SELECT * FROM {$dbpre}shops WHERE sid='$shopid'");
    empty($old) and $showmsg('您编辑的对象不能在，请返回。');
    $access = defined("IN_ADMIN") || !empty($old['ownerid']) && $old['ownerid'] == $opuid;
    if(!$access) $showmsg('您没有足够的权限来完成本次操作，请返回。');
    $post = array_merge($old, $post); // 覆盖
    unset($post['sid']);
    $post = checkItemPost($post);
    if($old['status'] != 2 && $post['status'] == 2) {
        $showmsg('不能再次将商铺修改为未审核状态');
    }
    if($old['classcode'] != $post['classcode']) {
        // 分类移动后的操作
        if($old['status'] != 2) {
            $db->update("UPDATE {$dbpre}classcode SET `total`=`total`-1 WHERE classcode='{$old['classcode']}'");
        }
        if($old['status'] != 2 && $post['status'] != 2) {
            $db->update("UPDATE {$dbpre}classcode SET `total`=`total`+1 WHERE classcode='{$post['classcode']}'");
        }
    }
    // 获取标签
    $tags = $post['tags'];
    unset($post['tags']);
    if(defined('IN_ADMIN') && ($old['owner'] != $post['owner'])) {
        // 店主变更，重新设置店主
        $owner = setItemOwner($post['owner']);
        $post = array_merge($post, $owner); // 覆盖
    } else {
        unset($post['ownerid'], $post['owner']);
    }
    $db->update_new($dbpre.'shops', "sid='$shopid'", $post);
    if($old['status'] == 2 && $post['status'] != 2) {
        // 更细关联表数据
        ItemBeRelated($shopid,$post);
        // 分类统计
        $db->update("UPDATE {$dbpre}classcode SET total=total+1 WHERE classcode='{$post['classcode']}'");
        // 更新统计缓存
        $_webtotal['totalshop']++;
        update_webtotal();
    }
}

// 删除对象
function deleteItem($shopids, $opuid='', $credit=false) {
    global $db, $dbpre, $_modules;

    if(empty($shopids)||!is_array($shopids)) return; 
    $showmsg = defined("IN_ADMIN") ? 'cpmsg' : 'redirect';
    $ids = "'".implode("','", $shopids)."'";
    $query = $db->query("SELECT sid,adduid,classcode,status,ownerid FROM {$dbpre}shops WHERE sid IN ($ids)");
    $delitems = array();
    if(!function_exists('updateCredit')) {
        require_once(MUDDER_ROOT.'./member/include/fun_member.php');
    }
    while($row = $db->fetch_array($query)) {
        $access = defined("IN_ADMIN") || (!empty($row['ownerid']) && $row['ownerid'] == $opuid);
        if(!$access) $showmsg('您没有足够的权限来完成本次操作，请返回。');
        $sqlset = '';
        $delitems[] = $row['sid'];
        if($row['adduid'] && $shop['status'] != 2) {
            $sqlset = "addshops=addshops-1";
            if($credit) {
                $sqlset .= ",".updateCredit($row['adduid'], 'deleteshop', 'sqlset');
            }
            $db->update("UPDATE {$dbpre}members SET $sqlset WHERE uid='{$row['adduid']}'");
        }
        if($shop['status'] != 2) {
            $db->update("UPDATE {$dbpre}classcode SET total=total-1 WHERE classcode='{$row['classcode']}'");
        }
    }
    $db->free_result($query);
    // 删除点评
    if(!function_exists('deleteReview')) {
        require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_review.php');
    }
    deleteReview($delitems,'shopid',-1,false,$credit);
    // 删除图片
    if(!function_exists('deletePicture')) {
        require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_picture.php');
    }
    deletePicture($delitems,'shopid',-1,false,$credit);
    // 最后删除item
    if($delitems) {
        $ids = "'".implode("','", $delitems)."'";
        $db->query("DELETE FROM {$dbpre}shops WHERE sid IN ($ids)");
    }
}

// 删除某个分类下的所有商铺
function deleteItemFromClass($classcode) {
    global $db,$dbpre;
    $query = $db->query("SELECT sid FROM {$dbpre}shops WHERE classcode='$classcode'");
    $shopids = array();
    while($row=$db->fetch_array($query)) {
        $shopids[] = $row['sid'];
    }
    if(count($shopids)>0) {
        deleteItem($shopids);
    }
}

// 审核对象
function checkupItem($shopids) {
    global $db,$dbpre;

    $ids = "'".implode("','", $shopids)."'";
    $query = $db->query("SELECT * FROM {$dbpre}shops WHERE sid IN ($ids)");
    $upitems = array();
    require_once(MUDDER_ROOT.'./member/include/fun_member.php');
    while($row = $db->fetch_array($query)) {
        if($row['status'] != 2) continue;
        $upitems[] = $row['sid'];
        ItemBeRelated($row['sid'],$row);
        $db->update("UPDATE {$dbpre}classcode SET total=total+1 WHERE classcode='{$row['classcode']}'");
        //更新统计缓存
        $_webtotal['totalshop']++;
    }
    $db->free_result($query);
    if($upitems) {
        $ids = "'".implode("','", $upitems)."'";
        $db->update("UPDATE {$dbpre}shops SET status=1 WHERE sid IN ($ids)");
        update_webtotal();
    }
}

// 检查提交的内容
function checkItemPost($post) {
    global $_seccode,$_DCOOKIE, $_modules;

    $post['shopname'] = html_special_chars_ex($post['shopname']);
    $post['subname'] = isset($post['subname']) ? html_special_chars_ex($post['subname']) : '';
    $post['classcode'] = isset($post['classcode']) ? $post['classcode'] : '';
    $post['areacode'] = isset($post['areacode']) ? $post['areacode'] : '';
    $post['address'] = isset($post['address']) ? html_special_chars_ex($post['address']) : '';
    $post['tel1'] = isset($post['tel1']) ? trim($post['tel1']) : '';
    $post['tel2'] = isset($post['tel2']) ? trim($post['tel2']) : '';
    $post['mobile'] = isset($post['mobile']) ? trim($post['mobile']) : '';
    $post['content'] = isset($post['content']) ? unite_textarea($post['content']) : '';
    $post['video'] = isset($post['video']) ? html_special_chars_ex($post['video']) : '';
    $post['website'] = isset($post['website']) ? html_special_chars_ex($post['website']) : '';
    isset($post['mappoint']) && $post['mappoint'] = trim($post['mappoint']);

    //pr($post);
    //exit;

    // 标签
    if(!function_exists('parseTagstr')) {
        require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_tag.php');
    }
    // $post['tags'] = tagTostr(parseTagstr($post['tags']));

    if(!defined('IN_ADMIN') && $_seccode['newshop'] && 
       ($_DCOOKIE['seccode'] != formhash(strtolower($post['seccode']),'',''))) {
        $error = '验证码错误, 请返回修改。';
    } elseif(!$post['shopname']) {
         $error = '未填写商铺名，请返回修改。';
    } elseif(strlen($post['shopname']) > 40 || strlen($post['shopname']) < 2) {
         $error = '商铺名不能小于2个字符或者大于40个字符，请返回修改。';
    } elseif(strlen($post['subname']) > 40) {
        $error = '分店名不能大于40个字符，请返回修改。';
    } elseif(!$post['classcode']) {
        $error = '未选择分类，请返回修改。';
    } elseif(!preg_match("/^[0-9]{4}$/", $post['classcode'])) {
        $error = '无效的分类信息，请返回修改。';
    } elseif(!$post['areacode']) {
        $error = '未选择地区，请返回修改。';
    } elseif(!preg_match("/[0-9]{4,6}/", $post['areacode'])) {
        $error = '无效的地区信息，请返回修改。';
    } elseif(!$post['address']) {
        $error = '未填写商铺地址，请返回修改。';
    } elseif(strlen($post['address']) > 60 || strlen($post['address']) < 4) {
        $error = '商铺地址不能小于4个字符或者大于60个字符，请返回修改。';
    } elseif(strlen($post['tel1']) > 15 || strlen($post['tel2']) > 15) {
        $error = '电话号码不能大于15个字符，请返回修改。';
    } elseif($post['tel1'] && !preg_match("/^[0-9\-]*$/", $post['tel1'])) {
        $error = '电话号码 1 格式不正确，正确公式为“区号-号码(0574-27712345)或者号码(27712345)”，请返回修改。';
    } elseif($post['tel2'] && !preg_match("/^[0-9\-]*$/", $post['tel2'])) {
        $error = '电话号码 2 格式不正确，正确公式为“区号-号码(0574-27712345)或者号码(27712345)”，请返回修改。';
    } elseif(strlen($post['mobile']) > 11) {
        $error = '手机号码不能大于11位，请返回修改。';
    } elseif($post['mobile'] && !preg_match("/^[0-9]{11,15}$/", $post['mobile'])) {
        $error = '手机号码格式不正确，请返回修改。';
    // } elseif(strlen($post['shoptags']) > 60) {
    //   $error = '商铺标签不能大于60个字符，请返回修改。';
    } elseif(strlen($post['content']) > 1000) {
        $error = '商铺介绍不能大于1000个字符，请返回修改。';
    } elseif($post['mappoint'] && !checkMappoint($post['mappoint'])) {
        $error = '地图坐标无效，请返回修改。';
    }

    if($error) {
        defined("IN_ADMIN") and cpmsg($error);
        redirect($error);
    }

    // 街道处理
    if(strlen($post['areacode']) == 4) {
        unset($post['post']);
    } else {
        $post['streetcode'] = $post['areacode'];
        $post['areacode'] = substr($post['areacode'], 0, 4);
    }
    unset($post['seccode']);

    return $post;
}

// 增加点评对象后更新关联表
function ItemBeRelated($shopid, $row) {
    global $db,$dbpre,$ucenter_enable;

    if(!empty($row['adduid'])) {
        // 更新会员积分和统计
        if(!function_exists('updateCredit')) {
            require_once(MUDDER_ROOT.'./member/include/fun_member.php');
        }
        $sqlset = updateCredit($row['adduid'], 'addshop', 'sqlset');
        $sqlset = ($sqlset ? "$sqlset," : '') . "addshops=addshops+1";
        $db->update("UPDATE {$dbpre}members SET $sqlset WHERE uid='{$row['adduid']}'");
        // 活跃记录
        updateActivity($row['adduid'], $row['addname'], 'addshops');
        if($ucenter_enable) {
            if(!class_exists('Feed_UC')) {
                require_once(MUDDER_ROOT.'./include/feed_uc.class.php');
            }
            $fullname = $row['shopname'] . ($row['subname'] ? '('.$row['subname'].')' : '');
            Feed_UC::add_newshop($shopid, $fullname);
        }
    }
}

// 设定店主
function setItemOwner($user, $isUid=false) {
    global $db,$dbpre;

    if($isUid) {
        $where = "uid='$user'";
    } else {
        $where = "username='$user'";
    }
    $member = $db->get_one("SELECT uid,username FROM {$dbpre}members WHERE $where");
    $result = array('ownerid' => 0, 'owner' => '');
    if(empty($member)) {
        if(defined('IN_ADMIN')) {
            cpmsg('无效的店主，请返回重新设立。');
        }
        return $result;
    }
    $result['ownerid'] = $member['uid'];
    $result['owner'] = $member['username'];

    return $result;
}

// 判断是否存在相同的
function itemExist($name, $subname) {
    global $db, $dbpre;

    $where = "WHERE shopname='$name'";
    !empty($subname) and $where .= " AND subname='$subname'";
    return $db->get_value("SELECT count(*) FROM {$dbpre}shops $where") >= 1;
}

// 检查地图坐标
function checkMappoint($point) {
    return preg_match('/^[A-Za-z0-9\.\-]+,[A-Za-z0-9\.\-]+$/', $point);
}

// 取得点评对象的内容
function getItem($shopid) {
    global $db,$dbpre;
    $query = $db->query("select s.*,c.cardsort,c.discount,c.largess,c.exception,c.available as membercard_available FROM {$dbpre}shops s LEFT JOIN {$dbpre}carddiscounts c ON(s.sid=c.shopid) WHERE sid='$shopid'");
    return itemToArray($db->fetch_array($query));
}

// 点评对象分数计算
function calcScore($cfg, $sumScore, $reviews) {
    // point
    $review_sort = $cfg['review'];

    $start_icon = array();
    $p_avggrade = $overall = 0;
    
    // 默认分制
    $st = $cfg['scoretype'] ? $cfg['scoretype'] : 0;
    $dp = empty($cfg['decimalpoint']) || $cfg['decimalpoint'] < 0 ? 0 : $cfg['decimalpoint']; 
    if(!is_array($review_sort) || empty($review_sort)) return $sumScore;
    
    foreach($review_sort as $key => $val) {
        $sortfield = 'sum'.$key;
        // 各个评分项目算平均分。默认不显示。
        $start_icon[$key] = ($sumScore[$sortfield] == 0) ? 0 : round($sumScore[$sortfield]/$reviews);
        // 用于计算综合分数
        $p_avggrade += $start_icon[$key];

        if($st > 0 && !empty($sumScore[$sortfield])) {
            $sumScore[$sortfield] = round(($sumScore[$sortfield]/$reviews)*($st/5),$dp);
        } elseif(empty($sumScore[$sortfield])) {
            $sumScore[$sortfield] = '-';
        }
        $sumScore[$key] =& $sumScore[$sortfield];
        $overall += $sumScore[$sortfield];
        
    }
    $sumScore['overall'] = $overall > 0 ? round($overall/count($review_sort), $dp) : 0;
    $sumScore['avggrade'] = $p_avggrade > 0 ? round($p_avggrade/count($review_sort)) : 0;
    $sumScore['avgprice'] = $sumScore['avgprice'] ? $sumScore['avgprice'] : '-';
    return $sumScore;
}

// 转换对象内容到前台显示
function itemToArray($row, $isEdit = false) {
    global $_config,$_areacodes,$_panels,$_panel_config,$_classcodes,$_membercard;

    // 状态
    $status_arr = array('1' => '正常', '2' => '未审核', '3' => '停止营业', '4' => '暂停营业', '5' => '尚未开业', 
        '6' => '隐藏显示', );
    $row['shopid'] = $row['shopid'] ? $row['shopid'] : $row['sid'];
    $row['panelcode'] = substr($row['classcode'], 0, 2);
    $row['panelname'] = $_panels[$row['panelcode']];
    $row['panelcfg'] = $_panel_config[$row['panelcode']];
    $row['classname'] = $_classcodes[$row['classcode']]['classname'];
    $row['name'] = $row['shopname'];
    $row['name_enc'] = rawurlencode($row['shopname']);
    $row['fullname'] = $row['shopname'].($row['subname'] ? '('.$row['subname'].')' : '');
    $row['areaname'] = $_areacodes[$row['areacode']];
    $row['streetname'] = $_areacodes[$row['streetcode']];
    $row['fulladdress'] = sprintf("%s%s%s", $row['areaname'],$row['streetname'],$row['address']);
    $row['statusname'] = empty($status_arr[$row['status']]) ? 'unkown' : $status_arr[$row['status']];
    if($row['thumb']) {
        $fileinfo = pathinfo($row['thumb']);
        $row['thumb_s'] = get_picture($fileinfo['dirname'], $fileinfo['basename'], 'small');
        $row['thumb_b'] = get_picture($fileinfo['dirname'], $fileinfo['basename'], 'big');
        unset($fileinfo);
    } else {
        $row['thumb_s'] = $_config['siteurl'].'images/s_noimg.gif';
        $row['thumb_b'] = $_config['siteurl'].'images/noimg.gif';
    }
    // point
    $row = calcScore($row['panelcfg'], $row ,$row['reviews']);
    // Map
    if(checkMappoint($row['mappoint'])) {
        $row['usemap'] = true;
        $row['mappoint'] = explode(',',$row['mappoint']);
    } else {
        $row['usemap'] = false;
        $row['mappoint'] = array(0,0);
    }
    // Video
    $row['video'] = !$row['video'] && $row['panelcfg']['video_url'] ? $row['panelcfg']['video_url'] : ($row['video'] ? $row['video'] : '');
    // card
    $row['membercard'] = $_membercard['enable'] && $row['membercard_available'];
    if($row['cardsort'] == 'both') {
        $row['membercard_msg'] = sprintf("%0.1F折, %s", $row['discount'], $row['largess']);
    } elseif($row['cardsort'] == 'discount') {
        $row['membercard_msg'] = sprintf("%0.1F折", $row['discount']);
    } else {
        $row['membercard_msg'] = $row['largess'];
    }
    //$row['membercard_exception'] = $row['exception'];
    // content
    !$isEdit and $row['content'] = strip_textarea($row['content']);
    // 兼容老版本
    if($_config['compatible']) {
        $row['sid'] =& $row['shopid'];
        //$row['shopname'] = $row['fullname']; 
        $row['shopnameenc']=& $row['name_enc'];
        $row['upclassname']=& $row['panelname'];
        $row['upclasscode']=& $row['panelcode'];
        $row['picture'] =& $row['thumb'];
        $row['map'] =& $row['usemap'];
   }
   return $row;
}

// 商铺维护记录
function getItemlogs($shopid, $offset = 10) {
    global $db, $dbpre;
    if(empty($shopid) || $shopid < 0) return;
    $query = $db->query("SELECT uid,username,posttime FROM {$dbpre}upshops WHERE shopid='$shopid' AND 
        disposal=1 LIMIT $offset");
    $result = array();
    while($row = $db->fetch_array($query)) {
        $result[] = $row;
    }
    return $result;
}

// 取得商铺图片
function getPictures($shopid, $offset = 10) {
    global $db, $dbpre;

    if(empty($shopid) || $shopid < 0) return;
    $query = $db->query("SELECT * FROM {$dbpre}pictures WHERE shopid='$shopid' AND status=1 
        ORDER BY addtime DESC LIMIT $offset");
    $result = array();
    while($row = $db->fetch_array($query)) {
        $result[] = $row;
    }
    return $result;
}

// 地图标注
function markMappoint($user, $shopid, $point, $force=false) {
    global $db, $dbpre;

    if(!checkMappoint($point)) {
        redirect("无效的标注点。");
    } elseif(!is_numeric($shopid) || $shopid <= 0) {
        redirect("未知的商铺ID。");
    }

    $item = $db->get_one("SELECT * FROM {$dbpre}shops WHERE sid='$shopid'");
    empty($item) and redirect('您标注的商铺不存在或已删除，请返回刷新。');
    if(checkMappoint($item['point']) && !$force) {
        redirect('地图已经标注，无需再次标注。');
    }

    $db->update("UPDATE {$dbpre}shops SET mappoint='$point' WHERE sid='$shopid'");
    return true;
}

// 提交点评对象补充信息
function suppItem($post) {
    global $db,$dbpre,$timestamp;

    $post['username'] = isset($post['username']) ? html_special_chars_ex($post['username']) : '';
    $post['email'] = isset($post['email']) ? html_special_chars_ex($post['email']) : '';
    $post['upcontent'] = isset($post['upcontent']) ? strip_textarea(unite_textarea($post['upcontent'])) : '';
    $post['point'] = isset($post['point']) ? html_special_chars_ex($post['point']) : '';

    $updateMap = !empty($post['point']);
    $mappoint = $post['point'];
    unset($post['point']);

    if(!is_numeric($post['shopid']) || $post['shopid'] <= 0) {
        $error = '未知的补充对象。';
    } elseif(!$item = $db->get_one("SELECT * FROM {$dbpre}shops WHERE sid='{$post['shopid']}'")) {
        $error = '补充对象不存在或已删除，请返回刷新。';
    } elseif($updateMap && !checkMappoint($mappoint)) {
        $error = '地图标注坐标未确定。';
    }if(empty($post['username'])) {
        $error = '未填写您的昵称';
    } elseif(strlen($post['username']) < 2 || strlen($post['username']) > 16) {
        $error = '昵称不能小于2个字符或者大于16个字符';
    } elseif(empty($post['email'])) {
        $error = '未填写您的邮件地址';
    } elseif(!isemail($post['email'])) {
        $error = '邮件地址格式不规范';
    } elseif(!$post['upcontent']) {
        $error = '未填写补充信息说明';
    } elseif(strlen($post['upcontent']) < 10 || strlen($post['upcontent']) > 300) {
        $error = '补充信息不能小于10个字符或者大于300个字符';
    } else {
        //mapmark format [preg_match("/^MarkPoint:([A-Za-z0-9\.]+),([A-Za-z0-9\.]+)\\r\\n/")]
        if($updateMap) {
            $post['upcontent'] = "MarkPoint:".$mappoint."\r\n".$post['upcontent'];
        }
        $db->insert_new($dbpre.'upshops', $post);
        //$db->query("INSERT INTO {$dbpre}upshops (shopid,uid,username,email,upcontent,disposal,posttime,upremark,disposaltime) VALUES('$shopid','$uid','$username','$email','$content','2','$timestamp','',0)");
        //$post['point']
    }
    
    if($error) {
        return '<script type="text/javascript">alert("'.$error.'");</script>';
    } else {
        return '<script type="text/javascript">alert("提交完毕，谢谢您的支持。");window.parent.document.forms["frmupshop"].hide.click();</script>';
    }
}

// 处理补充信息
function checkSuppItem($upid, $post) {
    global $db, $dbpre;

    if(!validKey($upid)) {
        cpmsg('无效的补充信息ID。', 'stop');
    } elseif($post['addpoint']=='updateshop' && empty($post['uid'])) {
        cpmsg('无效的用户ID，无法增加积分。', 'stop');
    }
    if($post['addpoint'] = 'updateshop') {
        // 给补充信息的会员增加积分
        if(!function_exists('updateCredit')) {
            require_once(MUDDER_ROOT.'./member/include/fun_member.php');
        }
        updateCredit($post['uid'], 'updateshop');
    }
    $db->update("UPDATE {$dbpre}upshops SET disposal='1',upremark='{$post['upremark']}',disposaltime='{$post['disposaltime']}' WHERE upid='$upid'");
}

// 取得商铺的维护信息
function itemSupplogs($shopid, $offset = 10) {
    global $db, $dbpre;
    $query = $db->query("SELECT uid,username,posttime FROM {$dbpre}upshops WHERE shopid='$shopid' AND disposal=1 LIMIT $offset");
    $result = array();
    while($row = $db->fetch_array($query)) {
        $result[] = $row;
    }
    return $result;
}

// 全方位商铺搜索
function searchItem($params) {
    global $db, $dbpre;
    extract($params);
    $form = "{$dbpre}shops s";
    if($showcard) {
        $form .= " LEFT JOIN {$dbpre}carddiscounts c ON(s.sid=c.shopid)";
    }
    $where = array();
    if($classcode) {
        if(strlen($classcode)==2) {
            $where[] = "classcode BETWEEN '{$classcode}00' AND '{$classcode}99'";
        } else {
            $where[] = "classcode='$classcode'";
        }
    }
    if($streetcode) {
        $where[] = "streetcode='$streetcode'";
    } elseif($areacode) {
        $where[] = "areacode='$areacode'";
    }
    if($mappoint) {
        $where [] = "mappoint NOT NULL";
    }
    if($reviews = intval($reviews)) {
        $where [] = "reviews>='$reviews'";
    }
    if($adduid = intval($adduid)) {
        $where [] = "adduid='$adduid'";
    }
    if($firstuid = intval($firstuid)) {
        $where [] = "firstuid='$firstuid'";
    }
    if($adduid = intval($adduid)) {
        $where [] = "adduid='$adduid'";
    }
    if($ownerid = intval($ownerid)) {
        $where [] = "ownerid='$ownerid'";
    }
    $where[] = "status IN (1,3,4,5)";
    $where = implode(" AND ", $where);
    $total = $db->get_value("SELECT COUNT(*) FROM {$dbpre}shops WHERE $where");
    $result = array();
    if($total > 0) {
        if($showdetial) {
            $select = "*";
        } else {
            $select = "s.sid,s.shopname,s.subname,s.classcode,s.areacode,s.streetcode,s.status,s.finer";
            if($showbase) $select .= ",s.addtime,s.mappoint,s.thumb,s.address,s.tel1,s.tel2";
            if($showtotal) $select .= ",s.reviews,s.pictures,s.pageviews,s.effect1,s.effect2,s.coupons";
            if($showpoint) $select .= ",sumreview,sumsort1,sumsort2,sumsort3,sumsort4,sumsort5,sumsort6,sumsort7,sumsort8,avgprice,sumenjoy";
            if($showmember) $select .= ",adduid,addname,firstuid,firstname,ownerid,owner";
            if($showinfo) $select .= ",mobile,video,website";
            if($showcontent) $select .= ",content";
            if($showcard) $select .= ",c.cardsort,c.discount,c.largess,c.exception,c.available as membercard_available";
        }
        $orderby = $orderby ? "ORDER BY $orderby" : '';
        $limit = $limit ? "LIMIT $limit" : ''; 
        $query = $db->query("SELECT $select FROM $form WHERE $where $orderby $limit");
        while($row = $db->fetch_array($query)) {
            $result[] = itemToArray($row);
        }
    }
    return array($total, $result);
}

// 重建商铺数据
function rebuildItem($shopids) {
    global $db, $dbpre;

    if(!is_array($shopids)) return;
    foreach($shopids as $shopid) {
        $uplist = array();
        $uplist['reviews'] = intval($db->select_count($dbpre.'reviews', "shopid='$shopid' AND status<>2"));
        $uplist['pictures'] = intval($db->select_count($dbpre.'pictures', "shopid='$shopid' AND status<>2"));
        $uplist['avgprice'] = intval($db->select_value("ROUND(AVG(avgprice))", $dbpre.'reviews', "shopid='$shopid' AND 
        	avgprice>0 AND status<>2"));
        $sorts = $db->get_one("SELECT SUM(sort1) as sumsort1,SUM(sort2) as sumsort2,
        	SUM(sort3) as sumsort3,SUM(sort4) as sumsort4,SUM(sort5) as sumsort5,
        	SUM(sort6) as sumsort6,SUM(sort7) as sumsort7,SUM(sort8) as sumsort8,
        	SUM(sumsort) as sumreview,SUM(enjoy) as sumenjoy FROM {$dbpre}reviews WHERE shopid='$shopid' AND status<>2");
        $unlist['sumreview'] = intval($sorts['sumreview']);
        $unlist['sumenjoy'] = intval($sorts['sumenjoy']);
        for($i=1; $i<=8; $i++) {
            $uplist['sumsort'.$i] = intval($sorts['sumsort'.$i]);
        }
        $where = implode(",", $uplist);
        $db->update_new($dbpre.'shops', "sid='$shopid'", $uplist);
    }
}

// 提交申请
function postItemApply($post) {
    global $db, $dbpre;

    $post['applyname'] = html_special_chars_ex($post['applyname']);
    $post['contact'] = isset($post['contact']) ? html_special_chars_ex($post['contact']) : '';
    $post['content'] = isset($post['content']) ? strip_textarea(unite_textarea($post['content'])) : '';

    if(!validKey($post['shopid'])) {
        redirect('无效的商铺ID。');
    } elseif(!$post['applyname']) {
        redirect('未填写认领人姓名，请返回填写。');
    } elseif(!$post['contact']) {
        redirect('未填写联系方式，请返回填写。');
    }

    // 图片提交
    if(!class_exists('Upload_class')) {
        require_once(MUDDER_ROOT.'./include/upload.class.php');
    }
    $upimg =& new Upload_Image_calss($_FILES['pic']);
    if($upimg->error) redirect($upimg->error);
    $upimg->folder = 'itemapply';
    $upimg->max_size = 1*1024*1024; // 1MB
    $upimg->upload();
    if($upimg->error) redirect($upimg->error);
    $post['pic'] = $upimg->upsubdir.'/'.$upimg->filename;
    $db->insert_new($dbpre.'itemapply', $post);
    return $db->insert_id();
}

// 更新所属分类
function updateItemClass($oldclasscode,$newclasscode) {
    global $db, $dbpre;
    if(empty($oldclasscode) || empty($newclasscode)) {
        return;
    }
    $db->update("UPDATE {$dbpre}shops SET classcode='$newclasscode' WHERE classcode='$oldclasscode'");
}
?>