<?php
/**
* POST处理
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
* @version $Id: post.php 4 2008-5-31 15:02 $
*/

define('SCRIPTNAV', 'post');
require_once './include/inc_common.php';
if($ucenter_enable) {
    require_once MUDDER_ROOT.'include/feed_uc.class.php';
}

$in_login_action =  array('newshop','newreview','newrespond','uploadpicture','exchange');

if(empty($action)) {

    redirect('未知的操作。', NULL);

} elseif(!$user->isLogin && in_array($action, $in_login_action)) {

    $forward = $php_reuri ? $host_url.$php_reuri : $_config['siteurl'];
    location($_config['siteurl'].'member/'.'login.php?forward='.rawurlencode($forward));

} elseif($action == 'newshop') {

    if(!check_submit('newshopsubmit')) {

        if($user->groupid == 1 || $user->groupid == 3) {
            redirect('您没有权限，无法添加商铺和点评商铺。');
        }
        if(is_numeric($shopid) && $shopid > 0) {
            $shop = $db->get_one("SELECT shopname,classcode FROM {$dbpre}shops WHERE sid='$shopid'");
            if($shop) {
                $shopname = $shop['shopname'];
                $pcd = substr($shop['classcode'], 0, 2);
                $addsub = true;
                unset($shop);
            }
        }
        $subtitle = $pcd ? '登记'.$_panels[$post['pcd']].'商铺' : '选择商铺类型';
        require_once MUDDER_ROOT.'header.php';
        include template('shop_post_item');
        footer();

    } else {

        require_once(MUDDER_ROOT."include/mycode.func.php");

        $post = array();
        $post['shopname'] = filterWords($shopname);
        $post['subname'] = filterWords($subname);
        $post['classcode'] = $classcode;
        $post['areacode'] = $areacode;
        $post['address'] = filterWords($address);
        $post['website'] = $website;
        $post['video'] = $video;
        $post['tel1'] = $tel1;
        $post['tel2'] = $tel2;
        $post['mobile'] = $mobile;
        // $post['tags'] = $tags;
        $post['adduid'] = $user->uid;
        $post['addname'] = $user->username;
        $post['content'] = filterWords($content);
        // 自动添加
        $post['status'] = $_auditing['addshop']||filterCheck($post['content']) ? '2' : '1'; // 审核\非审核
        $post['addtime'] = $timestamp;
        $post['templateid'] = intval($_config['item_styleid']); // 默认模板
        // 验证
        $post['seccode'] = $seccode;

        // 提交检查，并录入
        $shopid = postItem($post);
    	$url = $MOD['url'].'shop.php?shopid='.$shopid;
        if($post['status']==2) {
            redirect('新商铺提交完毕，请等待管理员审核。', $url);
        } else {
	    	if($_panel_config[substr($classcode,0,2)]['mapmark']) {
	    		$url = array(
	    			array('name' => '查看添加的商铺', 'url' => $url),
	    			array('name' => '给商铺添加地图标注', 'url' => $MOD['url'].'shop_map.php?action=mark&shopid='.$shopid),
	    		);
	    	}
            redirect('新商铺添加完毕！', $url);
        }
    }

} elseif($action == 'newreview') {

    if($user->groupid == 1 || $user->groupid == 3) {
        redirect('您没有足够的权限来完成本次操作。');
    }
    if(!check_submit('newreviewsubmit')) {

        if(is_numeric($shopid) && $shopid > 0) {

            $selectshop = $db->get_one("SELECT sid,shopname,subname,classcode,status FROM {$dbpre}shops WHERE sid='$shopid'");
            if(!$selectshop) {
                unset($shopid);
                redirect("商铺不存在或已删除。");
            } elseif($selectshop['status'] == 2) {
                redirect('点评的商铺尚在审核状态，暂时无法添加点评。');
            } elseif($selectshop['status'] == 3) {
                redirect('点评的商铺已停业，无法添加点评。');
            } else {
                $pcd = substr($selectshop['classcode'], 0,2);
                $panelcfg = $_panel_config[$pcd];
                $review_item = get_item_review($pcd);
                $subtitle = '点评_'.$selectshop['shopname'].$selectshop['subname'];
                $selectshop['shopname'] .= $selectshop['subname'] ? "({$selectshop['subname']})" : '' ;

                $hot_shoptags = $db->get_all("SELECT tagname,tagsort FROM {$dbpre}shoptags WHERE shopid='$shopid' AND tagsort='shop' GROUP BY tagname LIMIT 10");
                $hot_producttags = $db->get_all("SELECT tagname,tagsort FROM {$dbpre}shoptags WHERE shopid='$shopid' AND tagsort='product' GROUP BY tagname LIMIT 10");

                $review = $db->get_one("SELECT * FROM {$dbpre}reviews WHERE shopid='$shopid' AND uid='{$user->uid}'");
                if($review) {
                    $isEdit = true; //编辑标记
                    $reviewid = $review['rid'];
                    $shopid = $review['shopid'];
                    for($i=0;$i<=8;$i++) {
                        $keyname = sprintf("sort%d", $i);
                        $$keyname = $review[$keyname];
                    }
                    $avgprice = $review['avgprice'] ? $review['avgprice'] : '';
                    $content = html_special_chars($review['content']);
                    $enjoy = $review['enjoy'];
                    $shoptags = $review['shoptags'];
                    $producttags = $review['producttags'];
                }
            }
        } else {
            $subtitle = '点评商铺';
        }
        require_once MUDDER_ROOT.'header.php';
        require_once template('shop_post_review');
        footer();

    } else {

        require_once(MUDDER_ROOT."include/mycode.func.php");

        if($isEdit && (empty($reviewid) || $reviewid < 0)) {
            redirect('无效的编辑对象。');
        }
        $post = array();
        $post['seccode'] = $seccode;
        $post['shopid'] = $shopid;
        $post['uid'] = $user->uid;
        $post['username'] = $user->username;
        $panelcfg = $_panel_config[$pcd];
        for($i=1; $i<=8; $i++) {
            $val = sprintf("sort%d", $i);
            $post['sort'.$i] = $$val;
        }
        $post['avgprice'] = $avgprice;
        $post['enjoy'] = $enjoy;
        $post['content'] = filterWords($content);
        $post['shoptags'] = filterWords($shoptags);
        $post['producttags'] = filterWords($producttags);
        $post['suitplacetags'] = $suitplace;

        if(!$isEdit) {
            $post['status'] = $_auditing['addreview']||filterCheck($post['content']) ? '2' : '1';
        }
        $post['posttime'] = $timestamp;
        $post['ip'] = $onlineip;

        // 提交数据库
        if($isEdit) {
            updateReview($post, $reviewid, $user->uid);
        } else {
            $reviewid = postReview($post);
        }
        if($post['status']==2 && !$isEdit) {
            redirect('点评完毕，请等待管理员审核。', $_modules['shop']['url'].'shop.php?shopid='.$shopid);
        } else {
            redirect('点评完毕！', $_modules['shop']['url'].'shop.php?shopid='.$shopid);
        }
    }

} elseif($action == 'newrespond') {

    if($user->groupid == 1) {
        redirect('您没有权限，无法回应点评。');
    }
    if(check_submit('newrespondsubmit')) {
        if(!is_numeric($reviewid) || !$reviewid || $reviewid < 0) {
            redirect('无效的点评对象。');
        }

        require_once(MUDDER_ROOT."include/mycode.func.php");

        $post = array();
        $post['reviewid'] = $reviewid;
        $post['content'] = filterWords($content);
        // 自动
        $post['uid'] = $user->uid;
        $post['username'] = $user->username;
        $post['posttime'] = $timestamp;
        $post['status'] = $_auditing['addrespond']||filterCheck($post['content']) ? '2' : '1';
        $post['ip'] = $onlineip;
        // 提交数据库
        $respondid = postRespond($post);
        if($post['status']==2) {
            redirect('回应提交完毕，请等待管理员审核。', 'viewreview.php?reviewid='.$reviewid);
        } else {
            location('viewreview.php?reviewid='.$reviewid);
        }
    }

} elseif($action == 'uploadpicture') {

    if(!is_numeric($shopid) || !$shopid || $shopid < 0){
        redirect('无效的商铺对象。', NULL);
    }

    $limit_ext = array('jpeg', 'jpg', 'gif', 'png'); 
    $limit_str = implode('，', $limit_ext);
    $php_max_size = return_bytes(ini_get('upload_max_filesize')); 
    $systen_max_size = return_bytes($_config['picture_upload_size'].'k');
    $max_size = min($php_max_size,$systen_max_size);
    $upload_max_size = round($max_size / 1024).' KB';

    if(!check_submit('uploadpicturesubmit')) {
        $shop = $db->get_one("SELECT sid,classcode,shopname,subname,status FROM {$dbpre}shops WHERE sid='$shopid'");
        if(!$shop) {
            redirect('您选择的商铺不存在或已删除。', NULL);
        } elseif($shop['status'] == 2) {
            redirect('您选择的商铺尚未通过审核，暂时无法上传图片。');
        } else {
            $shop['shopname'] .= $shop['subname'] ? "({$shop['subname']})" : "";
            $pcd = substr($shop['classcode'], 0, 2);
        }

        $subtitle = '上传图片_'.$shop['shopname'];
        require_once MUDDER_ROOT.'header.php';
        require_once template('shop_post_itempic');
        footer();
    } else {

        require_once MUDDER_ROOT.'./include/upload.class.php';

        $uploadimg = new Upload_Image_calss($_FILES['picture']);

        $uploadimg->error && redirect($uploadimg->error.'请返回修改。');
        $_FILES['picture'] && $uploadimg->error && redirect($uploadimg->error.'请返回修改。');

        $uploadimg->userSubdir = true;

        $title = isset($title) ? html_special_chars_ex($title) : '';
        $sort = isset($sort) && is_numeric($sort) && ($sort >= 1 && $sort <= 3) ? $sort : -1;
        $comments = isset($comments) ? html_special_chars_ex($comments) : '';
        $tags = isset($tags) ? html_special_chars_ex($tags) : '';

        if(!$title) {
            $error = '图片标题未填写。';
        } elseif(strlen($title) < 2 || strlen($title) > 20) {
            $error = '图片标题不能小于2个字符或者大于20个字符。';
        } elseif($sort == -1) {
            $error = '未选择图片的类型。';
        } elseif(strlen($comments) > 50) {
            $error = '图片说明不能大于50个字符。';
        } elseif(strlen($tags) > 60) {
            $error = '图片标签不能大于60个字符。';
        }

        if($error) redirect($error.'请返回修改。');

        if($_FILES['picture'] && !$uploadimg->error) {
            $uploadimg->folder = 'pictures';
            $uploadimg->userWatermark = $_config['watermark'];
            $uploadimg->setmaxsize($_config['picture_upload_size']);
            $uploadimg->thumb = array ( 
                'small' => array ( 
                    'prefix' => 's_',  
                    'width' => $_picture_thumb['small']['width'],
                    'height' => $_picture_thumb['small']['height'],
                ),
                'big' => array ( 
                    'prefix' => 'g_',  
                    'width' => $_picture_thumb['big']['width'],
                    'height' => $_picture_thumb['big']['height'],
                ),
            );

            $uploadimg->upload();
            $uploadimg->error && redirect($uploadimg->error.'请返回修改。');

            if(!$uploadimg->error) {
                $status = $_auditing['uploadpicture'] ? '2' : '1';
                $result = $db->query("INSERT INTO {$dbpre}pictures (uid,username,shopid,title,folder,filename,width,height,size,comments,sort,browse,tags,addtime,status) VALUES ('{$user->uid}','{$user->username}','$shopid','$title','{$uploadimg->subdir}','{$uploadimg->filename}','{$uploadimg->width}','{$uploadimg->height}','{$uploadimg->size}','$comments','$sort','0','$tags','$timestamp','$status')");

                if($result) {
                    if(!$_auditing['uploadpicture']) {
                        $set = array();
                        // set thumb
                        if($_config['shopthumb'] == 3) { // auto
                            $picture_total = intval($db->get_value("SELECT pictures FROM {$dbpre}shops WHERE sid='$shopid'"));
                            $picture_total > 0 && $set[] = "thumb='{$uploadimg->subdir}/{$uploadimg->filename}'";
                        } elseif($_config['shopthumb'] != 2) { // always new picture
                            $set[] = "thumb='{$uploadimg->subdir}/{$uploadimg->filename}'";
                        }
                        $set[] ="pictures=pictures+1";
                        $db->update("UPDATE {$dbpre}shops SET ".implode(",",$set)." WHERE sid='$shopid'");
                        //updateTags($shopid, $tags, 3);
                        $sqlset = upexpleve('addpicture','sqlset');
                        $sqlset .= $sqlset ? ', pictures=pictures+1' : 'pictures=pictures+1';
                        $db->update("UPDATE {$dbpre}members SET $sqlset WHERE uid='{$user->uid}'");
                        $msg = "图片上传成功。";
                    } else {
                        $msg = "图片上传成功，等待管理员审核。";
                    }
                    $urls = array(
                        1 => array(
                            'name'=>'查看图片列表',
                            'url'=>'shop_pic.php?shopid='.$shopid
                        ),
                        2 => array(
                            'name'=>'继续添加图片',
                            'url'=>'post.php?action=uploadpicture&amp;shopid='.$shopid
                        ),
                        3 => array(
                            'name'=>'返回商铺页面',
                            'url'=>'shop.php?shopid='.$shopid
                        ),
                    );
                    redirect($msg, $urls);
                } else {
                    // ADD LOG
                    redirect('数据写入失败，请将错误信息报告联系管理员。', NULL);
                }
            } else {
                // ADD LOG
                redirect('上传失败，可能网络忙碌，请稍后进行尝试。', NULL);
            }

        }
    }

} elseif($action == 'report') {

    if(check_submit('reportsubmit')) {

        $uid = $user->isLogin ? $user->uid : 0;
        $username = $user->isLogin ? $user->username : $username;
        $email = $user->isLogin ? $user->email : $email;
        $post = array();
        $post['reviewid'] = $reviewid;
        $post['uid'] = $uid;
        $post['username'] = $username;
        $post['email'] = $email;
        $post['sort'] = $sort;
        $post['reportcontent'] = $content;
        $post['posttime'] = $timestamp;
        $post['reportremark'] = '';
        echo reportReview($post, $reviewid);
    }

} elseif($action == 'upshopinfo' || $action == 'upshopmap') {

    if(check_submit('upshopinfosubmit') || check_submit('upshopmapsubmit')) {

        $post = array();
        $uid = $user->isLogin ? $user->uid : 0;
        $username = $user->isLogin ? $user->username : $username;
        $email = $user->isLogin ? $user->email : $email;

        $post['shopid'] = $shopid;
        $post['uid'] = $uid;
        $post['username'] = $username;
        $post['email'] = $email;
        $post['upcontent'] = $content;
        $post['posttime'] = $timestamp;
        $post['upremark'] = '';
        if($action == 'upshopmap') {
            $post['point'] = $lng.",".$lat;
        }
        echo suppItem($post);
    }

} elseif($action == 'mapmark') {

    markMappoint($user, $shopid, "$lng,$lat");
    redirect('标注成功！谢谢您的支持！', 'shop.php?shopid='.$shopid);

} elseif($action == 'exchange') {

    !$_modules['exchange'] && redirect('未开启积分兑换功能。');
    (!is_numeric($giftid) || $giftid < 0) && redirect('无效的礼品编号。');

    if(!check_submit('exchangesubmit')) {

        location($_modules['exchange']['url'].'?action=gift&giftid='.$giftid, false);

    } else {

        $linkman = html_special_chars_ex($linkman);
        $number = trim($number);
        $tel = trim($tel);
        $mobile = trim($mobile);
        $postcode = trim($postcode);
        $address = html_special_chars_ex($address);
        $seccode = trim($seccode);
        $comment = html_special_chars_ex($comment);
        if(!$linkman) {
            redirect('未填写联系人，请返回填写。');
        } elseif(!is_numeric($number) || $number < 1) {
            redirect('兑换数量必须大于等于1，请返回修改。');
        } elseif(!preg_match('/^[0-9\-]+$/', $tel)) {
            redirect('联系电话格式不正确，请返回修改。');
        } elseif($mobile && !preg_match('/^[0-9\-]+$/', $mobile)) {
            redirect('手机号码格式不正确，请返回修改。');
        } elseif(!preg_match('/^[0-9]+$/', $postcode)) {
            redirect('邮政编码格式不正确，请返回修改。');
        } elseif(!$address) {
            redirect('未填写联系地址，请返回填写。');
        } elseif($_exchange['seccode'] && ($_DCOOKIE['seccode'] != formhash(strtolower($seccode),'',''))) {
            redirect('验证码错误，请返回填写。');
        }
        $gift = $db->get_one("SELECT * FROM {$dbpre}gifts WHERE giftid='$giftid'");
        if(!$gift) {
            redirect('礼品不存在，或已删除。', NULL);
        } elseif(!$gift['available']) {
            redirect('此礼品当前已停止兑换，您可以选择其他礼品进行兑换。');
        } elseif($gift['num'] <= 0) {
            redirect('此礼品当前已缺货，您可以选择其他礼品进行兑换。');
        } 
        $total_price = $gift['price'] * $number;
        ($user->coin < $total_price) && redirect('您的积分不足，无法兑换此礼品，请继续加油。');
        $contact = '联系人：'.$linkman.'<br />'.
            '联系电话：'.$tel.'<br />'.
            '手机号码：'.$mobile.'<br />'.
            '邮政编码：'.$postcode.'<br />'.
            '联系地址：'.$address.'<br />'.
            '备注说明：'.$comment;
        $db->query("INSERT INTO {$dbpre}exchange (uid,giftid,giftname, number,price,status,status_extra,exchangetime,contact,checker) VALUES ('{$user->uid}','$giftid','{$gift['name']}','$number','{$gift['price']}','1','','$timestamp','$contact','')");
        $urls = array(
            array('name' => '去兑奖中心', 'url' => $_modules['exchange']['url']),
            array('name' => '查看我的兑奖列表', 'url' => $_config['siteurl'].'member/index.php?ac=exchange'),
        );
        $db->update("UPDATE {$dbpre}gifts SET num=num-'$number',salevolume=salevolume+'$number' WHERE giftid='$giftid'");
        $db->update("UPDATE {$dbpre}members SET coin=coin-'$total_price' WHERE uid='{$user->uid}'");
        redirect('您目前已经成功提交了兑换请求，本站工作人员将在7个工作日内处理你的兑换请求，请关注你的兑换列表。',$urls);
    }

} else {

    redirect('未定义操作。', NULL);

}
?>