<?php
/**
* Ajax数据处理
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
* @version $Id: ajax.php 3 2008-1-4 21:34 $
*/
header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );

define('AJAX', TRUE);

require_once './include/common.inc.php';

$in_login_action = array('addflower', 'addfavorite', 'addfriend', 'changepassword', 'changeface', 'pmsg', 'readmsg');

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

    $forward = rawurlencode($php_referer);
    dialog('您目前进行的操作', '', 'login');

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

    $caption = '查看图片';

    if(is_numeric($pictureid) && $pictureid > 0) {
        $current_pic = $db->get_one("SELECT * FROM {$dbpre}pictures WHERE pid='$pictureid'");
        if($current_pic) {

            $picture['src'] = '{$_config[siteurl]}uploads/pictures/'.$picture['folder'].'/'.$picture['filename'];
            $current_pic['width'] = intval($current_pic['width']) > 0 ? intval($current_pic['width']) : 650;
            $current_pic['height'] = intval($current_pic['height']) > 0 ? intval($current_pic['height']) : 420;
            $current_pic['imagetype'] = 'width="'.$current_pic['width'].'"';
            $current_pic['addtime'] = date('Y-m-d', $current_pic['addtime']);

            require_once template('dlg_shop_pic');

            $db->update("UPDATE {$dbpre}pictures SET browse=browse+1 WHERE pid='{$current_pic['pid']}'");
        } else {
            dialog($caption, '图片不存在。');
        }
    } else {
        dialog($caption, '无效的图片。');
    }

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

    $caption = '举报不规范点评';

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

       $review = $db->get_one("SELECT status FROM {$dbpre}reviews WHERE rid='$reviewid'"); 
       !$review && dialog($caption, '点评信息不存在或已删除。');

    } else {

        dialog($caption, '点评信息不存在。');

    }
    require_once template('dlg_report');

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

    $caption = '补充商铺信息';

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

       $shop = $db->get_one("SELECT status FROM {$dbpre}shops WHERE sid='$shopid'"); 
       !$shop && dialog($caption, '商铺不存在或已删除。');

    } else {

        dialog($caption, '商铺不存在。');

    }

    require_once template('dlg_upshopinfo');

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

    $caption = '地图标注更新';

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

        $shop = $db->get_one("SELECT mappoint FROM {$dbpre}shops WHERE sid='$shopid'"); 
        !$shop && dialog($caption, '商铺不存在或已删除。');
        (!$shop['mappoint'] || !preg_match("/^[A-Za-z0-9\.\-]+,[A-Za-z0-9\.\-]+$/", $shop['mappoint'])) && dialog($caption, '商铺地图位置尚未标注，您可以进行标注。');

        $shop['mappoint'] = explode(',', $shop['mappoint']);

    } else {

        dialog($caption, '商铺不存在。');

    }

    require_once template('dlg_upshopmap');

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

    $caption = '赠送鲜花';

    if(!$user->isLogin) {
        $forward = rawurlencode($host_url.$php_referer);
        dialog($caption, '', 'login');
    }

    if(is_numeric($reviewid) && $reviewid > 0) {
        $review = $db->get_one("SELECT a.uid,b.username FROM {$dbpre}reviews a LEFT JOIN {$dbpre}members b ON(a.uid=b.uid) WHERE rid='$reviewid'");
        if(!$review) {
            $error = '点评不存在。';
        } elseif($review['uid'] == $user->uid) {
            $error = '您无法给自己赠送鲜花。';
        } else {
            $result = $db->get_one("SELECT fid FROM {$dbpre}flowers WHERE reviewid='$reviewid' AND uid='{$user->uid}'");
            if($result) {
                $error = '您已经为此点评赠送了鲜花。';
            } else {
                $db->update("UPDATE {$dbpre}members SET flowers=flowers+1 WHERE uid='{$review['uid']}'");
                $db->query("INSERT INTO {$dbpre}flowers(reviewid,uid,username) VALUES('$reviewid','{$user->uid}','{$user->username}')");
                $db->update("UPDATE {$dbpre}reviews SET flower=flower+1 WHERE rid='$reviewid'");
                
                //require_once(MUDDER_ROOT.'./include/addnew.func.php');
                //member_activity($review['uid'], $timestamp, 0, 0, 1, 0);
                if(!function_exists('updateActivity')) {
                    require_once(MUDDER_ROOT.'./'.$_modules['member']['directory'].'/include/fun_member.php');
                    updateActivity($user->uid,$user->username,'flowers');
                }
            }
            unset($review);
        }
    } else {
        $error = '无效的点评信息。'; 
    }
    if($error) dialog($caption, $error);

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

    $caption = '收藏商铺';

    if(is_numeric($shopid) && $shopid > 0) {
        $result = $db->get_one("SELECT COUNT(*) as count FROM {$dbpre}favorites WHERE uid='{$user->uid}' AND shopid='$shopid'");
        if($result['count'] == 0) {

            unset($result);

            $result = $db->query("INSERT INTO {$dbpre}favorites(uid,shopid,addtime) VALUES('{$user->uid}','$shopid','$timestamp')");
            $result && $db->update("UPDATE {$dbpre}members SET favorites=favorites+1 WHERE uid='{$user->uid}'");
            dialog($caption, '收藏成功！');

      } else {
        $error = '您已经收藏了这家商铺。';
      }

    } else {
      $error = '您收藏的商铺不存在或者已经删除。';
    }

    if($error) dialog($caption, $error);

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

    $caption = '查找商铺';

    if($charset != 'utf-8') {
        if(!class_exists('Chinese')) {
            require_once(MUDDER_ROOT."./include/chinese.class.php");
        }
        $chs = new Chinese('utf-8', $charset);
        $shopname = isset($shopname) ? $chs->Convert($shopname) : '';
    }

    if(!$shopname) {
        dialog($caption, '未填写商铺名关键字。');
    }

    $sql= "SELECT sid,shopname,subname FROM {$dbpre}shops WHERE CONCAT(shopname,subname) like '%{$shopname}%'";

    $result = $db->query("SELECT sid,shopname,subname FROM {$dbpre}shops WHERE CONCAT(shopname,subname) like '%{$shopname}%'");
    if(!$result || $db->num_rows($result) <= 0) {
        dialog($caption, '该商铺不存在，请进行添加。');
    }

    if(!$option) $select = '<select size="10" style="width:90%;height:85%;line-height:18px">'."\r\n";
    while($shop = $db->fetch_array($result)) {
        $shop['shopname'] .= $shop['subname'] ? "({$shop['subname']})" : '';
        $select .= "<option value=\"{$shop['sid']}\">{$shop['shopname']}</option>\r\n";
    }

    if(!$option) {
        $select .= '</select>';
        dialog($caption, $select, 'myDialog');
    } else {
        echo $select;
    }

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

    if(in_array($effectaction, array('add','dec')) && !$user->isLogin) {
        $forward = rawurlencode($php_referer);
        dialog('您目前进行的操作', '', 'login');
    }

    $idtypes = array(
        'coupon' => 'coupons',
        'shop' => 'shops',
    );
    $effects = array(
        'effect1',
        'effect2',
    );
    $pks = array(
        'coupon' => 'couponid', 
        'shop' => 'sid',
    );

    if(!array_key_exists($idtype, $idtypes)) dialog('操作提示', '未知的行为。');
    if(!in_array($effect, $effects)) dialog('操作提示', '不存在的行为。');
    if(empty($keyid) || $keyid < 0) dialog('操作提示', '对象ID不存在。');

    $tablename = $dbpre.$idtypes[$idtype];
    $keyname = $pks[$idtype];

    $detail = $db->get_one("SELECT $keyid,$effect FROM $tablename WHERE $keyname='$keyid'");
    if(empty($detail)) dialog('操作提示', '对象不存在或已删除。');

    $query = $db->query("SELECT uid,username FROM {$dbpre}membereffect WHERE id='$keyid' AND idtype='$idtype' AND $effect=1 AND uid='{$user->uid}'");
    $row = $db->fetch_array($query);

    if($effectaction == 'add') {
        $row && dialog('系统提示', '您已经做出过选择。');
        $db->query("INSERT {$dbpre}membereffect SET id='$keyid', idtype='$idtype',uid='{$user->uid}',username='{$user->username}',dateline='$timestamp',$effect=1");
        $db->update("UPDATE $tablename SET $effect=$effect+1 WHERE $keyname='$keyid'");
        echo $detail[$effect]+1;
    } elseif($effectaction == 'dec') {
        if($row) {
            $db->update("UPDATE $tablename SET $effect=$effect-1 WHERE $keyname='$keyid'");
            $db->update("DELETE FROM {$dbpre}membereffect WHERE id='$keyid' AND idtype='$idtype' AND $effect=1 AND uid='{$user->uid}'");
            echo $detail[$effect]-1;
        } else {
            echo 'keep';
        }
    } elseif($effectaction == 'getusers') {
        $query = $db->query("SELECT uid,username FROM {$dbpre}membereffect WHERE id='$keyid' AND idtype='$idtype' AND $effect=1 ORDER BY dateline");
        if($db->num_rows($query) > 0) {
            $split = '';
            while($row = $db->fetch_array($query)) {
                echo $split.'<a href="'.$_modules['space']['url'].'index.php?suid='.$row['uid'].'">'.$row['username'].'</a>';
                $split = ',';
            }
        } else {
            echo 'clear';
        }
    } else {
        echo 'keep';
    }
    output();

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

    $idtypes = array(
        'article' => 'articles',
        'shop' => 'shops',
    );
    $pks = array(
        'article' => 'articleid', 
        'shop' => 'sid',
    );

    if(!array_key_exists($idtype, $idtypes)) dialog('操作提示', '未知的行为。');
    if(empty($keyid) || $keyid < 0) dialog('操作提示', '对象ID不存在。');

    $tablename = $dbpre.$idtypes[$idtype];
    $keyname = $pks[$idtype];

    $detail = $db->get_one("SELECT $keyid,digg FROM $tablename WHERE $keyname='$keyid'");
    if(empty($detail)) dialog('操作提示', '顶一下对象不存在或已删除。');

    $digged = $_DCOOKIE['digg_'.$keyid] == 1;
    if($digged) {
        echo 'digg顶过了('.$detail['digg'].')';
    } else {
        $db->update("UPDATE $tablename SET digg=digg+1 WHERE $keyname='$keyid'");
        set_cookie('digg_'.$keyid, '1', 24*3600);
        echo 'digg谢谢支持('.++$detail['digg'].')';
    }
    output();

} else {

    dialog('操作提示', '未定义操作。');

}
?>
